0296 STATIC SOURCE EXCERPTS
Repository: https://github.com/lciernik/similarity_consistency
Commit: 99d8051f9985f86d1bc64fd43243d30b408c2606
All notebook cell indices are zero-based; line numbers are one-based inside decoded cell source.
No author code was executed. These excerpts do not establish historical figure provenance.

MEMBER notebooks/aggregate_consistencies_for_model_set_pairs.ipynb
SHA256 32f8ea47ab24a411314931f56ea49a93d291fae1647d605250f1eae14ac1d6ae
Git blob e6597a109d6c609dcc0c86c3fea4b965f47e9fd1
CELL 8
1: def get_sim_data(category, sim_metric):
2:     cat_groups = model_configs.reset_index(names=['mid']).groupby(category)['mid'].unique()
3:     cat_groups.index = [cat_name_mapping[x] for x in cat_groups.index]
4:     sim_metric_mats = sim_mats[sim_metric]
5:     return cat_groups, sim_metric_mats
6: 
7: 
8: def process_sim_mat(ds, sim_mat, cat):
9:     indx_i, indx_j = np.triu_indices(n=len(sim_mat), k=1)
10:     flat_sim_mat = pd.DataFrame(
11:         {'Similarity value': sim_mat.values[indx_i, indx_j],
12:          'Model 1': sim_mat.index.values[indx_i],
13:          'Model 2': sim_mat.columns.values[indx_j]
14:          })
15:     flat_sim_mat['M1 obj.'] = flat_sim_mat['Model 1'].apply(lambda x: cat_name_mapping[model_configs.loc[x, cat]])
16:     flat_sim_mat['M2 obj.'] = flat_sim_mat['Model 2'].apply(lambda x: cat_name_mapping[model_configs.loc[x, cat]])
17:     flat_sim_mat['DS'] = ds
18:     return flat_sim_mat
19: 
20: 
21: def r_coeff(df, ds1, ds2, corr_type):
22:     x = df[df['DS'] == ds1]['Similarity value']
23:     y = df[df['DS'] == ds2]['Similarity value']
24:     if 'pearsonr' == corr_type:
25:         corr, _ = pearsonr(x, y)
26:     elif 'spearmanr' == corr_type:
27:         corr, _ = spearmanr(x, y)
28:     else:
29:         raise ValueError(f'Unknown {corr_type=}! Need to select pearsonr or spearmanr r_corr in corr_type.')
30:     return corr
31: 
32: 
33: def get_r_coeff_df(sim_metric_mats, cat_groups, corr_type):
34:     # flatten each similarity matrix 
35:     pp_mats = []
36:     for ds, sim_mat in sim_metric_mats.items():
37:         pp_mats.append(process_sim_mat(ds, sim_mat, desired_cat))
38:     pp_mats = pd.concat(pp_mats)
39:     # get each dataset pair 
40:     combs = combinations(list(pp_mats['DS'].unique()), 2)
41:     r_coeffs = []
42:     for ds1, ds2 in combs:
43:         subset_ds = pp_mats[pp_mats['DS'].isin([ds1, ds2])]
44:         for cat in cat_groups.index.tolist():
45:             subset_data = subset_ds[(subset_ds['M1 obj.'] == cat) | (subset_ds['M2 obj.'] == cat)].copy()
46:             subset_data['other cat'] = subset_data[['M1 obj.', 'M2 obj.']].apply(
47:                 lambda x: x['M2 obj.'] if x['M1 obj.'] == cat else x['M1 obj.'], axis=1)
48:             for other_cat, other_cat_data in subset_data.groupby('other cat'):
49: 
50:                 if len(other_cat_data) <= 2:
51:                     print(f'Cannot compute correlation for {(ds1, ds2)} and {(cat, other_cat)}, too few model pairs')
52:                     continue
53:                 r_coeffs.append(
54:                     {
55:                         'ds1': ds1,
56:                         'ds2': ds2,
57:                         'anchor_cat': cat,
58:                         'other_cat': other_cat,
59:                         'r coeff': r_coeff(other_cat_data, ds1, ds2, corr_type),
60:                         'cat_pair': tuple(sorted([cat, other_cat]))
61:                     }
62:                 )
63:     df_r_coeffs = pd.DataFrame(r_coeffs)
64:     return df_r_coeffs

MEMBER notebooks/aggregate_consistencies_for_anchor_models.ipynb
SHA256 41c785287c2850bdb2fc9f49974f0d2485078c4bd21ee5d9472a957b0d3da67a
Git blob 4bcf5cd78623657f12c50e684efabe252f0ef46e
CELL 10
23: def get_melted_sim_values_metric_anchor(anch, met, met_ds_mats):
24:     sim_vals_ds = []
25:     # for each dataset, get the similarity values of the anchor model to all other models
26:     for ds, curr_sim_mat in met_ds_mats.items():
27:         cols = curr_sim_mat.columns.tolist()
28:         cols.remove(anch)
29:         cols = sorted(list(set(cols).intersection(allowed_models)))
30:         row_sim_mat = curr_sim_mat.loc[anch, cols]
31:         row_sim_mat.name = ds
32:         sim_vals_ds.append(row_sim_mat)
33: 
34:     # concatenate the similarity values of the anchor model to all other models for all datasets
35:     anchor_sim_vals = pd.concat(sim_vals_ds, axis=1)
36:     anchor_sim_vals = anchor_sim_vals.reset_index(names=[other_col])
37:     # get the model information for all other models and add it to the dataframe
38:     anchor_sim_vals = pd.concat([anchor_sim_vals,
39:                                  pd.DataFrame(anchor_sim_vals[other_col].apply(get_other_model_info).tolist(),
40:                                               columns=info_cols)], axis=1)
41:     anchor_sim_vals[sim_metric_col] = sim_metric_name_mapping[met]
42:     anchor_sim_vals[anchor_col] = anch
43:     # melt the dataframe to have one row per dataset and anchor & other model pair 
44:     anchor_sim_vals = pd.melt(anchor_sim_vals,
45:                               id_vars=id_cols,
46:                               var_name=other_ds_col,
47:                               value_name=sim_ds_col,
48:                               )
49:     return anchor_sim_vals
CELL 15
1: # get all unique datasets and create all possible pairs
2: all_datasets = all_sims[other_ds_col].unique()
3: ds_pairs = list(combinations(all_datasets, 2))
4: print('Nr. dataset pairs: ', len(ds_pairs))
CELL 16
12: def compute_corr(data):
13:     res = []
14:     for ds1, ds2 in ds_pairs:
15:         x = data[data[other_ds_col] == ds1][sim_ds_col]
16:         y = data[data[other_ds_col] == ds2][sim_ds_col]
17:         corr = correlation(x, y)
18:         res.append((ds1, ds2, corr))
19:     return res
20: 
21: 
22: def post_process_group_op(df):
23:     df = df.explode(r_col).reset_index(drop=True)
24:     df_split = df[r_col].apply(pd.Series)
25:     df_split.columns = ['DS 1', 'DS 2', r_col]
26:     df.drop(columns=[r_col], inplace=True)
27:     df = pd.concat([df, df_split], axis=1)
28:     return df
29: 
30: 
31: r_dfs = []
32: for strata in tqdm(info_cols):
33:     grouping_cols = [sim_metric_col, anchor_col, strata]
34: 
35:     strata_rs = all_sims.groupby(grouping_cols, dropna=False).apply(compute_corr, include_groups=False).reset_index()
36:     strata_rs.columns = grouping_cols + [r_col]
37:     strata_rs = post_process_group_op(strata_rs)
38: 
39:     all_rs = all_sims.groupby(grouping_cols[:-1], dropna=False).apply(compute_corr, include_groups=False).reset_index()
40:     all_rs.columns = grouping_cols[:-1] + [r_col]
41:     all_rs = post_process_group_op(all_rs)
42:     all_rs[strata] = 'All'
43: 
44:     rs = pd.concat([all_rs, strata_rs], axis=0).reset_index(drop=True)
45:     rs = rs.sort_values([sim_metric_col, anchor_col]).reset_index(drop=True)
46:     r_dfs.append(rs)

MEMBER notebooks/app_F_validating_infl_train_obj_with_anchor_modles.ipynb
SHA256 1d76c9c4e74032b1562f4b7a75b44678bcce13f5fd81a9aa3bc699dbb0fbd448
Git blob 5d8c94f63c1c3a1d086e726365c3e1156224a879
CELL 3
19: ## Define aggregated data path
20: curr_data = available_data[0]
21: agg_data_path = BASE_PATH_RESULTS / f'aggregated/r_coeff_dist/with_anchor_models/{curr_data}'
22: assert agg_data_path.exists(), f'Path does not exist: {agg_data_path}. Aggregated correlation coefficients across all dataset pairs not found, please run aggregate_consistencies_for_model_set_pairs.ipynb first.'
CELL 11
12: def get_pvals_pairs(pairs, df, strata_col, alpha=0.05):
13:     p_values = []
14:     for (config1, config2) in pairs:
15:         dat1 = get_config_data(df, config1, strata_col)[r_col].reset_index(drop=True)
16:         dat2 = get_config_data(df, config2, strata_col)[r_col].reset_index(drop=True)
17:         idx2drop = list(np.where(dat1.isna())[0]) + list(np.where(dat2.isna())[0])
18:         dat1.drop(labels=idx2drop, inplace=True)
19:         dat2.drop(labels=idx2drop, inplace=True)
20:         assert len(dat1) == len(dat2)
21:         stat, p_value = ranksums(dat1, dat2)
22:         p_values.append(p_value)
23:     return p_values
24: 
25: 
26: def add_sign_bars(anchor_pairs, anchor_corr_pvals, axes, strata_col, alpha=0.01):
27:     total_annots = 0
28:     for i, anchor in enumerate(anchors):
29:         curr_pairs = anchor_pairs[anchor]
30:         curr_corr_pvals = anchor_corr_pvals[anchor]
31:         annotations = [(config1, config2, pval) for (config1, config2), pval in zip(curr_pairs, curr_corr_pvals) if
32:                        pval < alpha]
33:         total_annots += len(annotations)
34:         starbars.draw_annotation(annotations, ax=axes[i])
35:         axes[i].get_legend().remove()
36: 
37: 
38: def correct_anchor_pvalues(anchor_pairs, anchor_pvals):
39:     anchor_corr_pvals = {}
40:     all_pvals = list(np.concatenate(list(anchor_pvals.values())))
41:     # corrected_all_pvals = multipletests(all_pvals, method='hs')[1]
42:     corrected_all_pvals = multipletests(all_pvals, method='bonferroni')[1]
43:     # corrected_all_pvals = multipletests(all_pvals, method='fdr_bh')[1]
44:     idx = 0
45:     for anchor in anchors:
46:         nr_pvals = len(anchor_pairs[anchor])
47:         anchor_corr_pvals[anchor] = corrected_all_pvals[idx:(idx + nr_pvals)]
48:         idx += nr_pvals
49:     return anchor_corr_pvals
CELL 13
1: r_df.loc[r_df[comp_cat_col] == 'Dataset size', comp_cat_col] = 'Training data'
2: add_significances = False
3: # for include_all in [True, False]:
4: for include_all in [False]:
5:     if not include_all:
6:         subset = r_df[r_df[comp_val_col] != 'All']
7:     else:
8:         subset = r_df
9:     for strata_cat, df in subset.groupby(comp_cat_col):
10:         strata_cat_orig = df[comp_cat_orig_col].unique()[0]
11:         fig = plot_box_per_sim_metric(df, strata_cat, comp_val_col, strata_cat_orig, add_significances)
12:         save_or_show(fig,
13:                      storing_path / f'dist_r_coeffs_{strata_cat.replace(" ", "_")}_only_box_per_sim_metric{"_include_all" if include_all else ""}.pdf',
14:                      SAVE)

MEMBER notebooks/app_E_does_local_n_global_sim_differ.ipynb
SHA256 21a4fe4a80cf9fbf5c8c69879a71a85767c79ea09ddcc2df52e6879b47a94da0
Git blob 175498fc0624e758100ea146bf243f17b39a0d4b
CELL 3
1: # Datasets
2: ds_list, ds_info = load_all_datasetnames_n_info(ds_list_sim_file, verbose=False)
3: 
4: # Experiment configuration
5: corr_type = 'pearsonr'  # 'pearsonr', 'spearmanr'
6: suffix = ''  # '', '_wo_mae'
7: exp_conf = f'{corr_type}{suffix}'
8: 
9: # Path to correlation data
10: data_path = BASE_PATH_RESULTS / f'aggregated/r_coeff_dist/with_cats_as_anchors/agg_{corr_type}_all_ds_with_rsa{suffix}.csv'
11: assert data_path.exists(), f'Path does not exist: {data_path}. Aggregated correlation coefficients across all dataset pairs not found, please run aggregate_consistencies_for_model_set_pairs.ipynb first.'
CELL 7
1: from scipy import stats
2: 
3: combs = [('CKA linear', 'CKA RBF 0.4'), ('CKA linear', 'RSA spearman')]
4: fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(12, 5))  # Increased width for better visibility
5: 
6: for i, (x, y) in enumerate(combs):
7:     dat1 = r_coeff_data[r_coeff_data['Similarity metric'] == x]
8:     dat2 = r_coeff_data[r_coeff_data['Similarity metric'] == y]
9:     dat1 = dat1.set_index(['ds1', 'ds2', 'anchor_cat', 'other_cat'])
10:     dat2 = dat2.set_index(['ds1', 'ds2', 'anchor_cat', 'other_cat'])
11: 
12:     dat1.columns = [col + ' sm1' for col in dat1.columns]
13:     dat2.columns = [col + ' sm2' for col in dat2.columns]
14:     dat_concat = pd.concat([dat1, dat2], axis=1)
15: 
16:     ax = axs[i]
17:     sns.scatterplot(data=dat_concat, x="r coeff sm1", y="r coeff sm2", alpha=0.5, s=10, ax=ax)
18: 
19:     ax.set_xlabel(f'r coeff. ({x})', fontsize=curr_fontsizes['label'])
20:     ax.set_ylabel(f'r coeff. ({y})', fontsize=curr_fontsizes['label'])
21:     ax.tick_params(labelsize=curr_fontsizes['ticks'])
22: 
23:     r, p = stats.pearsonr(dat_concat['r coeff sm1'], dat_concat['r coeff sm2'])
24:     ax.text(0.05, 0.95, f'Overall r = {r:.2f}\np-value < 0.001', transform=ax.transAxes,
25:             verticalalignment='top', fontsize=curr_fontsizes['legend'])
26: 
27: plt.subplots_adjust(wspace=0.2 if version == 'arxiv' else 0.3)
28: save_or_show(fig, storing_path / f'consistency_local_global_scatter_plot{suffix}.pdf', SAVE)

MEMBER notebooks/4_7_can_similarity_predict_perf_gap.ipynb
SHA256 b56791d4534fef289dd63c61a40eb9e0134420bb29cb58dab27619c93c586d31
Git blob 025ad2765a08f5522f84dd447f72de1dad78bd28
CELL 16
1: def get_model_perf(row):
2:     m1_perf = perf_res.loc[(perf_res['Model'] == row['Model 1']) & (perf_res['DS'] == row['DS']), 'TestAcc'].item()
3:     m2_perf = perf_res.loc[(perf_res['Model'] == row['Model 2']) & (perf_res['DS'] == row['DS']), 'TestAcc'].item()
4:     return m1_perf, m2_perf, np.abs(m1_perf - m2_perf)
CELL 20
1: def get_correlation(subset_data):
2:     corr_sp, _ = spearmanr(subset_data['Similarity value'], subset_data['abs. diff. perf.'])
3:     corr_pr, _ = pearsonr(subset_data['Similarity value'], subset_data['abs. diff. perf.'])
4:     return {'spearmanr': corr_sp, 'pearsonr': corr_pr}
5: 
6: 
7: r_coeffs = sim_data_new.groupby(['Similarity metric', 'DS'])[['Similarity value', 'abs. diff. perf.']].apply(
8:     get_correlation)
9: r_coeffs = pd.DataFrame(r_coeffs.tolist(), index=r_coeffs.index)

MEMBER notebooks/aggregate_downstream_task_perfs.ipynb
SHA256 18d7c0d6954fa7cf2a5ffd7b672b48b68df8d2ac354a5f08f8ada8c789d5f3b5
Git blob 4f6598a545a63f1169a1ef43ffb1af4be484a106
CELL 7
1: res = []
2: for ds, mid in product(ds_list_perf, allowed_models):
3:     performance = retrieve_performance(
4:         model_id=mid,
5:         dataset_id=ds,
6:         metric_column='test_lp_acc1',
7:         results_root=results_root,
8:         regularization="weight_decay",
9:         allow_db_results=False
10:     )
11:     res.append({
12:         'DS': ds,
13:         'Model': mid,
14:         'TestAcc': performance
15:     })
16: perf_res = pd.DataFrame(res)

MEMBER sim_consistency/tasks/model_similarity.py
SHA256 96e477fdbbefdfdde42d2c09ec3ee27210becc96b16b22f43e034e2844952176
Git blob 9cd3d14d80308bd431087b31574da446743b26cb
83: 
84: class CKAModelSimilarity(BaseModelSimilarity):
85:     def __init__(self, feature_root: str, subset_root: Optional[str], split: str = 'train', device: str = 'cuda',
86:                  kernel: str = 'linear', backend: str = 'torch', unbiased: bool = True, sigma: Optional[float] = None,
87:                  max_workers: int = 4) -> None:
88:         super().__init__(feature_root=feature_root, subset_root=subset_root, split=split, device=device,
89:                          max_workers=max_workers)
90:         self.kernel = kernel
91:         self.backend = backend
92:         self.unbiased = unbiased
93:         self.sigma = sigma
94: 
95:     # def _load_feature(self, model_id:str) -> np.ndarray:
96:     #     features = load_features(self.feature_root, model_id, self.split, self.subset_indices)
97:     #     return features
98: 
99:     # def _compute_similarity(self, feat1: np.ndarray, feat2: np.ndarray) -> float:
100:     #     m = feat1.shape[0]
101:     #     cka = get_cka(backend=self.backend, m=m, kernel=self.kernel, unbiased=self.unbiased, device=self.device,
102:     #                     sigma=self.sigma)
103:     #     rho = cka.compare(X=feat1, Y=feat2)
104:     #     return rho
105: 
106:     def compute_similarity_matrix(self) -> np.ndarray:
107:         sim_matrix = self._prepare_sim_matrix()
108:         for idx1, model1 in tqdm(self.model_ids_with_idx, desc=f"Computing CKA matrix"):
109:             features_i = load_features(self.feature_root, model1, self.split, self.subset_indices)
110:             for idx2, model2 in self.model_ids_with_idx:
111:                 if idx1 >= idx2:
112:                     continue
113:                 features_j = load_features(self.feature_root, model2, self.split, self.subset_indices)
114:                 assert features_i.shape[0] == features_j.shape[0], \
115:                     f"Number of features should be equal for CKA computation. (model1: {model1}, model2: {model2})"
116: 
117:                 m = features_i.shape[0]
118:                 cka = get_cka(backend=self.backend, m=m, kernel=self.kernel, unbiased=self.unbiased, device=self.device,
119:                               sigma=self.sigma)
120:                 rho = cka.compare(X=features_i, Y=features_j)
121:                 sim_matrix[idx1, idx2] = rho
122:                 sim_matrix[idx2, idx1] = rho

MEMBER notebooks/helper.py
SHA256 ef5a88c48712b6c7fd7ad8db8431ae4c66d85fc57ef4ab176046983015fc5845
Git blob 6f21872791e3ba902697cde49ec0aa54c28b1816
132: 
133:     Returns:
134: 
135:     """
136:     model_ids_fn = path / 'model_ids.txt'
137:     sim_mat_fn = path / 'similarity_matrix.pt'
138:     if model_ids_fn.exists():
139:         model_ids = get_model_ids(model_ids_fn)
140:     else:
141:         raise FileNotFoundError(f'{str(model_ids_fn)} does not exist.')
142:     sim_mat = torch.load(sim_mat_fn)
143:     df = pd.DataFrame(sim_mat, index=model_ids, columns=model_ids)
144:     df = df.loc[allowed_models, allowed_models]
145:     return df
146: 
147: 
148: def load_similarity_matrices(
149:         path: Union[str, Path],

MEMBER requirements.txt
SHA256 3b46fdeebfd37a547dcde829718b4e3fe68aec24cb4ad9578284772a7e987822
Git blob 5da77de6c2673da281740287ddf50860b2ee54d8
1: numpy<2.0
2: torch>=1.8.1
3: torchvision>=0.8.9
4: tqdm>=2
5: scikit-learn>=1.0,<2
6: open_clip_torch>=2.24.0
7: pycocoevalcap
8: webdataset>=0.2.31
9: transformers
10: thingsvision==2.6.10
11: dreamsim==0.1.2
12: slurmpy
13: timm>=0.9.16
14: notebook
15: seaborn
16: 

