code
stringlengths
17
6.64M
def Convolution(data, num_filter, kernel, stride=None, dilate=None, pad=None, num_group=1, no_bias=False, weight=None, bias=None, name=None, lr_mult=1, reuse=None, **kwargs): if (reuse is not None): assert (name is not None) name = (GetLayerName.get('conv') if (name is None) else name) stride = ((...
def Deconvolution(data, num_filter, kernel, stride=None, dilate=None, pad=None, adj=None, target_shape=None, num_group=1, no_bias=False, weight=None, bias=None, name=None, lr_mult=1, reuse=None): if (reuse is not None): assert (name is not None) name = (GetLayerName.get('deconv') if (name is None) els...
def FullyConnected(data, num_hidden, flatten=True, no_bias=False, weight=None, bias=None, name=None, lr_mult=1, reuse=None): if (reuse is not None): assert (name is not None) name = (GetLayerName.get('fc') if (name is None) else name) W = (get_variable((name + '_weight'), lr_mult, reuse) if (weigh...
def Relu(data, name=None): name = (GetLayerName.get('relu') if (name is None) else name) x = mx.sym.Activation(data, act_type='relu', name=name) return x
def LeakyRelu(data, slope=0.25, name=None): name = (GetLayerName.get('leakyRelu') if (name is None) else name) x = mx.sym.LeakyReLU(data, slope=slope, act_type='leaky', name=name) return x
def Tanh(data, name=None): name = (GetLayerName.get('tanh') if (name is None) else name) x = mx.sym.tanh(data, name=name) return x
def Swish(data, name=None): name = (GetLayerName.get('swish') if (name is None) else name) x = (data * mx.sym.sigmoid(data)) return x
def Pooling(data, kernel, stride=None, pad=None, pool_type='max', global_pool=False, name=None): name = (GetLayerName.get('pool') if (name is None) else name) stride = (kernel if (stride is None) else stride) pad = (((0,) * len(kernel)) if (pad is None) else pad) x = mx.sym.Pooling(data, kernel=kernel...
def Dropout(data, p, name=None): name = (GetLayerName.get('drop') if (name is None) else name) x = mx.sym.Dropout(data, p=p, name=name) return x
def BatchNorm(data, fix_gamma=False, momentum=0.9, eps=1e-05, use_global_stats=False, gamma=None, beta=None, moving_mean=None, moving_var=None, name=None, lr_mult=1, reuse=None): if (reuse is not None): assert (name is not None) name = (GetLayerName.get('bn') if (name is None) else name) gamma = (...
def InstanceNorm(data, eps=1e-05, gamma=None, beta=None, name=None, lr_mult=1, reuse=None): if (reuse is not None): assert (name is not None) name = (GetLayerName.get('in') if (name is None) else name) gamma = (get_variable((name + '_gamma'), lr_mult, reuse) if (gamma is None) else gamma) beta...
def Flatten(data, name=None): name = (GetLayerName.get('flatten') if (name is None) else name) x = mx.sym.flatten(data, name=name) return x
def ConvRelu(*args, **kwargs): x = Conv(*args, **kwargs) x = Relu(x, (x.name + '_relu')) return x
def BNRelu(*args, **kwargs): x = BN(*args, **kwargs) x = Relu(x, (x.name + '_relu')) return x
def FCRelu(*args, **kwargs): x = FC(*args, **kwargs) x = Relu(x, (x.name + '_relu')) return x
def ConvBNRelu(*args, **kwargs): x = Conv(*args, **kwargs) x = BN(x, name=(x.name + '_bn'), lr_mult=kwargs.get('lr_mult', 1), reuse=kwargs.get('reuse', None)) x = Relu(x, (x.name + '_relu')) return x
def get_variable(name, lr_mult=1, reuse=None): if (reuse is None): return mx.sym.Variable(name, lr_mult=lr_mult) return reuse.get_internals()[name]
class GetLayerName(object): _name_count = {} @classmethod def get(cls, name_prefix): cnt = cls._name_count.get(name_prefix, 0) cls._name_count[name_prefix] = (cnt + 1) return (name_prefix + str(cnt))
def padding_helper(in_size, kernel_size, stride, pad_type='same'): pad_type = pad_type.lower() if (pad_type == 'same'): out_size = ((in_size // stride) + int(((in_size % stride) > 0))) pad_size = max(((((out_size - 1) * stride) + kernel_size) - in_size), 0) return ((pad_size // 2), (pa...
class OpConstant(mx.operator.CustomOp): def __init__(self, val): self.val = val def forward(self, is_train, req, in_data, out_data, aux): self.assign(out_data[0], req[0], self.val) def backward(self, req, out_grad, in_data, out_data, in_grad, aux): pass
@mx.operator.register('Constant') class OpConstantProp(mx.operator.CustomOpProp): def __init__(self, val_str, shape_str, type_str='float32'): super(OpConstantProp, self).__init__(need_top_grad=False) val = [float(x) for x in val_str.split(',')] shape = [int(x) for x in shape_str.split(','...
def CustomConstantEncoder(value, dtype='float32'): if (not isinstance(value, np.ndarray)): if (not isinstance(value, (list, tuple))): value = [value] value = np.array(value, dtype=dtype) return (','.join([str(x) for x in value.ravel()]), ','.join([str(x) for x in value.shape]))
def Constant(value, dtype='float32'): assert isinstance(dtype, str), dtype (val, shape) = CustomConstantEncoder(value, dtype) return mx.sym.Custom(val_str=val, shape_str=shape, type_str=dtype, op_type='Constant')
class BilinearScale(mx.operator.CustomOp): def __init__(self, scale): self.scale = scale def forward(self, is_train, req, in_data, out_data, aux): x = in_data[0] (h, w) = x.shape[2:] new_h = (int(((h - 1) * self.scale)) + 1) new_w = (int(((w - 1) * self.scale)) + 1) ...
@mx.operator.register('BilinearScale') class BilinearScaleProp(mx.operator.CustomOpProp): def __init__(self, scale): super(BilinearScaleProp, self).__init__(need_top_grad=True) self.scale = float(scale) def infer_shape(self, in_shape): (n, c, h, w) = in_shape[0] new_h = (int(...
class BilinearScaleLike(mx.operator.CustomOp): def forward(self, is_train, req, in_data, out_data, aux): (x, x_ref) = in_data (new_h, new_w) = x_ref.shape[2:] x.attach_grad() with mx.autograd.record(): new_x = mx.nd.contrib.BilinearResize2D(x, height=new_h, width=new_w...
@mx.operator.register('BilinearScaleLike') class BilinearScaleLikeProp(mx.operator.CustomOpProp): def __init__(self): super(BilinearScaleLikeProp, self).__init__(need_top_grad=True) def list_arguments(self): return ['d1', 'd2'] def infer_shape(self, in_shape): out_shape = list(i...
class SegmentLoss(mx.operator.CustomOp): def __init__(self, has_grad_scale, onehot_label, grad_scale): self.has_grad_scale = has_grad_scale self.onehot_label = onehot_label self.grad_scale = grad_scale def forward(self, is_train, req, in_data, out_data, aux): prediction = mx....
@mx.operator.register('SegmentLoss') class SegmentLossProp(mx.operator.CustomOpProp): def __init__(self, has_grad_scale=0, onehot_label=0, grad_scale=1): super(SegmentLossProp, self).__init__(need_top_grad=False) self.has_grad_scale = (int(has_grad_scale) > 0) self.onehot_label = (int(one...
class MultiSigmoidLoss(mx.operator.CustomOp): def __init__(self, grad_scale): self.grad_scale = grad_scale def forward(self, is_train, req, in_data, out_data, aux): (logit, label) = in_data prediction = mx.nd.sigmoid(logit, axis=1) self.assign(out_data[0], req[0], prediction)...
@mx.operator.register('MultiSigmoidLoss') class MultiSigmoidLossProp(mx.operator.CustomOpProp): def __init__(self, grad_scale=1): super(MultiSigmoidLossProp, self).__init__(need_top_grad=False) self.grad_scale = float(grad_scale) def list_arguments(self): return ['data', 'label'] ...
class MultiSoftmaxLoss(mx.operator.CustomOp): def forward(self, is_train, req, in_data, out_data, aux): (logit, label) = in_data prediction = mx.nd.softmax(logit, axis=1) self.assign(out_data[0], req[0], prediction) def backward(self, req, out_grad, in_data, out_data, in_grad, aux): ...
@mx.operator.register('MultiSoftmaxLoss') class MultiSoftmaxLossProp(mx.operator.CustomOpProp): def __init__(self): super(MultiSoftmaxLossProp, self).__init__(need_top_grad=False) def list_arguments(self): return ['data', 'label'] def list_outputs(self): return ['output'] d...
def vgg16_deeplab(x, name=None, lr_mult=1, reuse=None): name = ('' if (name is None) else name) x = ConvRelu(x, 64, (3, 3), pad=(1, 1), name=(name + 'conv1_1'), lr_mult=lr_mult, reuse=reuse) x = ConvRelu(x, 64, (3, 3), pad=(1, 1), name=(name + 'conv1_2'), lr_mult=lr_mult, reuse=reuse) x = Pool(x, kern...
def vgg16_largefov(x, num_cls, name=None, lr_mult=10, reuse=None): name = ('' if (name is None) else name) x = vgg16_deeplab(x, name, lr_mult=1, reuse=reuse) x = ConvRelu(x, 1024, (3, 3), dilate=(12, 12), pad=(12, 12), name=(name + 'fc6'), reuse=reuse) x = Drop(x, 0.5, name=(name + 'drop6')) x = C...
def vgg16_aspp(x, num_cls, name=None, lr_mult=10, reuse=None): name = ('' if (name is None) else name) x_backbone = vgg16_deeplab(x, name, lr_mult=1, reuse=reuse) x_aspp = [] for d in (6, 12, 18, 24): x = ConvRelu(x_backbone, 1024, (3, 3), dilate=(d, d), pad=(d, d), name=(name + ('fc6_aspp%d' ...
def vgg16_cam(x, num_cls, name=None, lr_mult=10, reuse=None): name = ('' if (name is None) else name) x = vgg16_deeplab(x, name, lr_mult=1, reuse=reuse) x = ConvRelu(x, 1024, (3, 3), pad=(1, 1), name=(name + 'fc6'), reuse=reuse) x = Drop(x, 0.5, name=(name + 'drop6')) x = ConvRelu(x, 1024, (1, 1),...
class _VOC_proto(object): @staticmethod def _get_palette(): def bitget(bit, idx): return ((bit & (1 << idx)) > 0) cmap = [] for i in range(256): (r, g, b) = (0, 0, 0) idx = i for j in range(8): r = (r | (bitget(idx, 0) <...
def imwrite(filename, image): dirname = os.path.dirname(filename) if (not os.path.exists(dirname)): try: os.makedirs(dirname) except: pass cv2.imwrite(filename, image)
def npsave(filename, data): dirname = os.path.dirname(filename) if (not os.path.exists(dirname)): try: os.makedirs(dirname) except: pass np.save(filename, data)
def pkldump(filename, data): dirname = os.path.dirname(filename) if (not os.path.exists(dirname)): try: os.makedirs(dirname) except: pass with open(filename, 'wb') as f: pickle.dump(data, f)
def imhstack(images, height=None): images = as_list(images) images = list(map(image2C3, images)) if (height is None): height = np.array([img.shape[0] for img in images]).max() images = [resize_height(img, height) for img in images] if (len(images) == 1): return images[0] images...
def imvstack(images, width=None): images = as_list(images) images = list(map(image2C3, images)) if (width is None): width = np.array([img.shape[1] for img in images]).max() images = [resize_width(img, width) for img in images] if (len(images) == 1): return images[0] images = [[...
def as_list(data): if (not isinstance(data, (list, tuple))): return [data] return list(data)
def image2C3(image): if (image.ndim == 3): return image if (image.ndim == 2): return np.repeat(image[(..., np.newaxis)], 3, axis=2) raise ValueError('image.ndim = {}, invalid image.'.format(image.ndim))
def resize_height(image, height): if (image.shape[0] == height): return image (h, w) = image.shape[:2] width = ((height * w) // h) image = cv2.resize(image, (width, height)) return image
def resize_width(image, width): if (image.shape[1] == width): return image (h, w) = image.shape[:2] height = ((width * h) // w) image = cv2.resize(image, (width, height)) return image
def imtext(image, text, space=(3, 3), color=(0, 0, 0), thickness=1, fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=1.0): assert isinstance(text, str), type(text) size = cv2.getTextSize(text, fontFace, fontScale, thickness) image = cv2.putText(image, text, (space[0], (size[1] + space[1])), fontFace, fontScal...
def setGPU(gpus): len_gpus = len(gpus.split(',')) os.environ['CUDA_VISIBLE_DEVICES'] = gpus gpus = ','.join(map(str, range(len_gpus))) return gpus
def getTime(): return datetime.now().strftime('%m-%d %H:%M:%S')
class Timer(object): curr_record = None prev_record = None @classmethod def record(cls): cls.prev_record = cls.curr_record cls.curr_record = time.time() @classmethod def interval(cls): if (cls.prev_record is None): return 0 return (cls.curr_record ...
def wrapColor(string, color): try: header = {'red': '\x1b[91m', 'green': '\x1b[92m', 'yellow': '\x1b[93m', 'blue': '\x1b[94m', 'purple': '\x1b[95m', 'cyan': '\x1b[96m', 'darkcyan': '\x1b[36m', 'bold': '\x1b[1m', 'underline': '\x1b[4m'}[color.lower()] except KeyError: raise ValueError('Unknown ...
def info(logger, msg, color=None): msg = ('[{}]'.format(getTime()) + msg) if (logger is not None): logger.info(msg) if (color is not None): msg = wrapColor(msg, color) print(msg)
def summaryArgs(logger, args, color=None): if isinstance(args, ModuleType): args = vars(args) keys = [key for key in args.keys() if (key[:2] != '__')] keys.sort() length = max([len(x) for x in keys]) msg = [(('{:<' + str(length)) + '}: {}').format(k, args[k]) for k in keys] msg = ('\n'...
def loadParams(filename): data = mx.nd.load(filename) (arg_params, aux_params) = ({}, {}) for (name, value) in data.items(): if (name[:3] == 'arg'): arg_params[name[4:]] = value elif (name[:3] == 'aux'): aux_params[name[4:]] = value if (len(arg_params) == 0): ...
class SaveParams(object): def __init__(self, model, snapshot, model_name, num_save=5): self.model = model self.snapshot = snapshot self.model_name = model_name self.num_save = num_save self.save_params = [] def save(self, n_epoch): self.save_params += [os.path...
def getLogger(snapshot, model_name): if (not os.path.exists(snapshot)): os.makedirs(snapshot) logging.basicConfig(filename=os.path.join(snapshot, (model_name + '.log')), level=logging.INFO) logger = logging.getLogger() return logger
class LrScheduler(object): def __init__(self, method, init_lr, kwargs): self.method = method self.init_lr = init_lr if (method == 'step'): self.step_list = kwargs['step_list'] self.factor = kwargs['factor'] self.get = self._step elif (method == ...
class GradBuffer(object): def __init__(self, model): self.model = model self.cache = None def write(self): if (self.cache is None): self.cache = [[(None if (g is None) else g.copyto(g.context)) for g in g_list] for g_list in self.model._exec_group.grad_arrays] els...
def initNormal(mean, std, name, shape): if name.endswith('_weight'): return mx.nd.normal(mean, std, shape) if name.endswith('_bias'): return mx.nd.zeros(shape) if name.endswith('_gamma'): return mx.nd.ones(shape) if name.endswith('_beta'): return mx.nd.zeros(shape) ...
def checkParams(mod, arg_params, aux_params, auto_fix=True, initializer=mx.init.Normal(0.01), logger=None): arg_params = ({} if (arg_params is None) else arg_params) aux_params = ({} if (aux_params is None) else aux_params) arg_shapes = {name: array[0].shape for (name, array) in zip(mod._exec_group.param_...
def compute_embeddings(dataset: str, architecture: str, seed: int, step: int, layer: int) -> np.ndarray: '\n Compute the representations of a layer specified by the arguments and save to a npy file\n\n :param dataset: Dataset to compute embeddings for\n :param architecture: Model weights to load\n :pa...
def get_filepath(dataset, architecture, seed, step, layer, folder=False): '\n Get filepath for embedding of interest (in order to check whether it has already\n been computed\n ' if folder: return os.path.join(EMBEDDING_PATH, dataset, architecture, str(seed), str(step), str(layer)) else: ...
def get_string_filepath(dataset, architecture, seed, step, layer): return '{head}/{dataset}/{architecture}/{seed}/{step}/{layer}'.format(head=EMBEDDING_PATH, dataset=dataset, architecture=architecture, seed=seed, step=step, layer=layer)
def get_embedding_folderpath(dataset: str, architecture: str, seed: int, step: int) -> pathlib.Path: '\n Return path of folder containing embedding arrays corresponding to:\n - layers of model specified by architecture, seed and step\n - inputs from dataset\n\n Args:\n dataset (str): name of th...
def get_checkpoint_filepath(architecture: str, seed: int, step: int) -> pathlib.Path: '\n Return path to model checkpoint specified by architecture, seed and step\n\n Args:\n architecture (str): name of model architecture, eg "resnet18"\n seed (int): seed used to train model\n step (int...
def initialise_model(architecture: str) -> nn.Module: '\n Return initialised network of a given architecture\n Currently: only works for resnet18, resnet34, resnet50, resnet101, resnet152\n\n Args:\n architecture (str): name of model architecture, eg "resnet18"\n\n Returns:\n nn.Module: ...
def initialise_dataset(dataset: str, sample_size: int, sample_seed: int, normalize=True): '\n Return Dataset object corresponding to a dataset name\n\n Args:\n dataset (str): name of dataset\n sample_size (int): number of inputs to subsample\n sample_seed (int): seed to use when subsamp...
def get_embedding_folder(dataset, architecture, seed, step, layer): suffix = pathlib.Path(f'embeddings/{dataset}/{architecture}/{seed}/{step}/{layer}') return (resources_path / suffix)
def load_embedding(dataset: str, architecture: str, seed: int, step: int, layer: int) -> np.ndarray: folder_path = get_embedding_folder(dataset, architecture, seed, step, layer) if (not os.path.exists(folder_path)): print('Computing representations for model') os.makedirs(folder_path) ...
def score_pair_to_csv(rep1_dict: dict, rep2_dict: dict, filename: str, metrics: list) -> None: '\n Compute metric distance between two representations and save it to a csv file\n\n Args:\n rep1_dict (dict): dictionary specifying configuration of representation 1, to load its representation from disk\...
def score_local_pair(rep1: np.ndarray, rep2: np.ndarray, filename: str, metrics: list, metadata: dict={}) -> None: '\n Compute metric distances between two representations (in numpy array format) and\n save results to a csv file\n\n Args:\n rep1 (np.ndarray): representation 1 to compare\n r...
def cca_decomp(A, B): 'Computes CCA vectors, correlations, and transformed matrices\n requires a < n and b < n\n Args:\n A: np.array of size a x n where a is the number of neurons and n is the dataset size\n B: np.array of size b x n where b is the number of neurons and n is the dataset size\n...
def mean_sq_cca_corr(rho): 'Compute mean squared CCA correlation\n :param rho: canonical correlation coefficients returned by cca_decomp(A,B)\n ' return (np.sum((rho * rho)) / len(rho))
def mean_cca_corr(rho): 'Compute mean CCA correlation\n :param rho: canonical correlation coefficients returned by cca_decomp(A,B)\n ' return (np.sum(rho) / len(rho))
def pwcca_dist(A, rho, transformed_a): 'Computes projection weighted CCA distance between A and B given the correlation\n coefficients rho and the transformed matrices after running CCA\n :param A: np.array of size a x n where a is the number of neurons and n is the dataset size\n :param B: np.array of s...
def lin_cka_dist(A, B): '\n Computes Linear CKA distance bewteen representations A and B\n ' similarity = (np.linalg.norm((B @ A.T), ord='fro') ** 2) normalization = (np.linalg.norm((A @ A.T), ord='fro') * np.linalg.norm((B @ B.T), ord='fro')) return (1 - (similarity / normalization))
def lin_cka_prime_dist(A, B): '\n Computes Linear CKA prime distance bewteen representations A and B\n The version here is suited to a, b >> n\n ' if (A.shape[0] > A.shape[1]): At_A = (A.T @ A) Bt_B = (B.T @ B) numerator = np.sum(((At_A - Bt_B) ** 2)) denominator = ((n...
def procrustes(A, B): '\n Computes Procrustes distance bewteen representations A and B\n ' A_sq_frob = np.sum((A ** 2)) B_sq_frob = np.sum((B ** 2)) nuc = np.linalg.norm((A @ B.T), ord='nuc') return ((A_sq_frob + B_sq_frob) - (2 * nuc))
def get_acc_diff(row, scores_df, task_list): score_row1 = scores_df.iloc[row['seed1']] score_row2 = scores_df.iloc[row['seed2']] for task in task_list: acc1 = score_row1[task] acc2 = score_row2[task] row[f'{task}_diff'] = abs((acc1 - acc2)) return row
def rename_scores(scores_df): scores_df = scores_df.rename(columns={'MNLI dev acc.': 'mnli_dev_acc', 'Lexical (entailed)': 'lex_ent', 'Subseq (entailed)': 'sub_ent', 'Constituent (entailed)': 'const_ent', 'Lexical (nonent)': 'lex_nonent', 'Subseq (nonent)': 'sub_nonent', 'Constituent (nonent)': 'const_nonent', 'O...
def get_full_df(scores_path, dists_path, full_df_path): scores_df = pd.read_csv(scores_path)[0:100] scores_df = rename_scores(scores_df) task_list = list(scores_df.columns[1:9]) print('got scores_df') dists_df = pd.read_csv(dists_path) print('got dists_df') print('getting full_df, will tak...
def feather_sub_df(df, task, ref_depth): seeds = list(df.seed1.unique()) accs = [scores_df.iloc[seed][task] for seed in seeds] acc_dict = dict(zip(seeds, accs)) best_seed = max(acc_dict, key=acc_dict.get) sub_df = df[(((df.layer1 == ref_depth) & (df.layer2 == ref_depth)) & ((df.seed1 == best_seed)...
def feather_sub_df(df, task, ref_depth): seeds = list(df.seed1.unique()) accs = [scores_df.iloc[seed][task] for seed in seeds] acc_dict = dict(zip(seeds, accs)) best_seed = max(acc_dict, key=acc_dict.get) sub_df = df[(((df.layer1 == ref_depth) & (df.layer2 == ref_depth)) & ((df.seed1 == best_seed)...
def get_probing_accuracy(data_dict, task, seed, depth): '\n average accuracy of model finetuned with finetuning seed seed on mnli\n when probing layer layer on task\n ' return np.mean(data_dict[task][seed][(depth + 1)][0][0])
def get_full_df(scores_path, dists_path, full_df_path): dists_df = pd.read_csv(dists_path) print('got dists_df') print('adding probing scores to get full_df') full_df = dists_df data_dict = pkl.load(open(scores_path, 'rb')) for task in task_list: task_diff_list = [] for (_, row...
def best_probing_seed(task, ref_depth, list_ref_seeds): data_dict = pkl.load(open(scores_path, 'rb')) list_to_max = [np.mean(data_dict[task][seed][(ref_depth + 1)][0][0]) for seed in list_ref_seeds] (idx, _) = max(enumerate(list_to_max), key=(lambda x: x[1])) return list_ref_seeds[idx]
def layer_sub_df(df, ref_depth, ref_seed): sub_df = df.loc[(((df['seed1'] == ref_seed) & (df['layer1'] == ref_depth)) | ((df['seed2'] == ref_seed) & (df['layer2'] == ref_depth)))].reset_index() num_layers = 12 assert (len(sub_df) == (num_layers * 10)) return sub_df
def aggregate_rank_corrs(df, task, layer_depths, list_ref_seeds, METRICS, sub_df_fn): rho = {metric: [] for metric in METRICS} rho_p = {metric: [] for metric in METRICS} tau = {metric: [] for metric in METRICS} tau_p = {metric: [] for metric in METRICS} bad_fracs = {metric: [] for metric in METRIC...
def best_probing_seed(task, ref_depth, list_ref_seeds): data_dict = pkl.load(open(scores_path, 'rb')) list_to_max = [np.mean(data_dict[task][seed][(ref_depth + 1)][0][0]) for seed in list_ref_seeds] (idx, _) = max(enumerate(list_to_max), key=(lambda x: x[1])) return list_ref_seeds[idx]
def layer_sub_df(df, ref_depth, ref_seed): sub_df = df.loc[(((df['seed1'] == ref_seed) & (df['layer1'] == ref_depth)) | ((df['seed2'] == ref_seed) & (df['layer2'] == ref_depth)))].reset_index() num_layers = 12 assert (len(sub_df) == (num_layers * 10)) return sub_df
def aggregate_rank_corrs(df, task, layer_depths, list_ref_seeds, METRICS, sub_df_fn): rho = {metric: [] for metric in METRICS} rho_p = {metric: [] for metric in METRICS} tau = {metric: [] for metric in METRICS} tau_p = {metric: [] for metric in METRICS} bad_fracs = {metric: [] for metric in METRIC...
def get_acc(data_dict, task, seed, layer, dims, run='average'): if (run == 'average'): return np.mean(data_dict[task][seed][(layer + 1)][dims]) elif (run == 'std'): return np.std(data_dict[task][seed][(layer + 1)][dims]) else: return data_dict[task][seed][(layer + 1)][dims][run]
def get_acc_diff(data_dict, row): acc1 = get_acc(data_dict, task=probe_task, seed=row['seed1'], layer=row['layer1'], dims=0, run='average') acc2 = get_acc(data_dict, task=probe_task, seed=row['seed2'], layer=row['layer2'], dims=row['dims_deleted'], run='average') return np.abs((acc1 - acc2))
def get_full_df(scores_path, dists_path, full_df_path): dists_df = pd.read_csv(dists_path) print('got dists_df') full_df = pd.DataFrame(dists_df[(((dists_df['seed1'].isin(REF_SEEDS) & dists_df['seed2'].isin(REF_SEEDS)) & dists_df['layer1'].isin(LAYERS)) & dists_df['layer2'].isin(LAYERS))]) print('filt...
def pca_sub_df(df, task, ref_depth): data_dict = pkl.load(open(scores_path, 'rb')) accs = [get_acc(data_dict, probe_task, seed, layer=ref_depth, dims=0, run='average') for seed in REF_SEEDS] acc_dict = dict(zip(REF_SEEDS, accs)) best_seed = max(acc_dict, key=acc_dict.get) sub_df = df[(((df.layer1 ...
def pca_sub_df(df, task, ref_depth): data_dict = pkl.load(open(scores_path, 'rb')) accs = [get_acc(data_dict, probe_task, seed, layer=ref_depth, dims=0, run='average') for seed in REF_SEEDS] acc_dict = dict(zip(REF_SEEDS, accs)) best_seed = max(acc_dict, key=acc_dict.get) sub_df = df[(((df.layer1 ...
def collect_scores(scores_path): (model2correctness_tensor, data_dict) = pkl.load(open(scores_path, 'rb')) guid_set = set() for datapoint in data_dict: guid_set.add(datapoint['guid'].split('-')[0]) acc_dict = {} for test_set in guid_set: test_set_idxes = [idx for (idx, d) in enumer...
def get_accuracy(acc_dict, stress_test, pretraining_seed, finetuning_seed): return acc_dict[stress_test][pretraining_seed][finetuning_seed]
def get_acc_diff(acc_dict, stress_test, pre_seed1, pre_seed2, fine_seed1, fine_seed2): avg_acc1 = get_accuracy(acc_dict, stress_test, pre_seed1, fine_seed1) avg_acc2 = get_accuracy(acc_dict, stress_test, pre_seed2, fine_seed2) return np.abs((avg_acc2 - avg_acc1))