code stringlengths 17 6.64M |
|---|
def build_compute_metrics_fn(task_name: str) -> Callable[([EvalPrediction], Dict)]:
try:
output_mode = glue_output_modes[task_name]
except KeyError:
raise ValueError(('Task not found: %s' % task_name))
def compute_metrics_fn(p: EvalPrediction):
if (output_mode == 'classification')... |
def glue_data_dir(DATA_DIR):
return os.path.join(DATA_DIR, 'glue_data')
|
def make_just_y(ds, **kw):
y = [feature.label for feature in ds]
y = torch.tensor(y)
return TensorDataset(y)
|
def get_extended_attention_mask(attention_mask, input_ids, dtype=torch.float32):
' Extented attention mask, removing the preprocessing from inside to outside, bert'
if (attention_mask is None):
attention_mask = torch.ones_like(input_ids)
extended_attention_mask = attention_mask.unsqueeze(1).unsque... |
def make_just_x(ds, **kw):
d = defaultdict(list)
for feature in ds:
for (key, val) in vars(feature).items():
if (key == 'label'):
continue
if (val is None):
continue
d[key].append(val)
print(d.keys())
if ('attention_mask' in d... |
def make_just_by_ds(ds, just, **kw):
assert isinstance(just, list)
A = set((MAP_NAMES_TO_FEATURES[i] for i in just))
if kw['is_last_partition']:
A |= LAST_PARTITION_EXTRA_LABELS
d = defaultdict(list)
for feature in ds:
for (key, val) in vars(feature).items():
if (val is... |
def getitem(t):
if isinstance(t, dict):
res = {i: getitem(v) for (i, v) in t.items()}
else:
try:
res = t.item()
except:
res = t
return res
|
def get_just_x_or_y_train_dev_dataset(just, DATA_DIR, **kw):
' get x or y datset. '
tokenizer = kw['tokenizer']
task_name = kw['task_name']
max_seq_length = kw['max_seq_length']
overwrite_cache = kw['overwrite_cache']
is_last_partition = kw.get('is_last_partition')
precompute_attention_mas... |
class SEP_GLUE_DatasetHandler(CommonDatasetHandler):
def __init__(self, **kw):
super().__init__()
d = extract_needed_keywords(**kw)
(train_ds, dev_ds, extra) = get_just_x_or_y_train_dev_dataset(**d)
self.train_ds = train_ds
self.dev_ds = dev_ds
self.extra = extra
... |
def extract_needed_keywords(**kw):
args = kw['args']
dataset_keywords = dict(tokenizer=kw['tokenizer'], overwrite_cache=getattr(args, 'overwrite_cache', False), task_name=getattr(args, 'glue_task_name'), max_seq_length=getattr(args, 'max_seq_length', 128), precompute_masks=getattr(args, 'precompute_masks', Fa... |
class TextDataset(Dataset):
def __init__(self, tokenizer, model_name_or_path, overwrite_cache=False, file_path='train', block_size=512):
assert os.path.isfile(file_path), file_path
(directory, filename) = os.path.split(file_path)
cached_features_file = os.path.join(directory, ((((model_na... |
def mask_tokens(inputs: torch.Tensor, tokenizer: PreTrainedTokenizer, mlm_probability=0.15, generator=None) -> Tuple[(torch.Tensor, torch.Tensor)]:
' Prepare masked tokens inputs/labels for masked language modeling:\n 80% MASK, 10% random, 10% original.\n\n Usage:\n inputs, labels = mask_tokens(bat... |
def mask_tokens_just_inputs(inputs: torch.Tensor, tokenizer: PreTrainedTokenizer, mlm_probability=0.15, generator=None) -> Tuple[(torch.Tensor, torch.Tensor)]:
' Prepare masked tokens inputs/labels for masked language modeling:\n 80% MASK, 10% random, 10% original.\n\n Usage:\n inputs, labels = mas... |
def mask_tokens_just_labels(inputs: torch.Tensor, tokenizer: PreTrainedTokenizer, mlm_probability=0.15, generator=None) -> Tuple[(torch.Tensor, torch.Tensor)]:
' Prepare masked tokens inputs/labels for masked language modeling:\n 80% MASK, 10% random, 10% original.\n\n Usage:\n inputs, labels = mas... |
def get_wikitext2_raw_train_valid_test_ds(model_name_or_path, tokenizer, block_size=512, overwrite_cache=False, DATA_DIR=DEFAULT_DATA_DIR, split='all'):
wt2_data_path = os.path.join(DATA_DIR, 'wikitext-2-raw')
train_file = os.path.join(wt2_data_path, 'wiki.train.raw')
valid_file = os.path.join(wt2_data_pa... |
def get_wikitext2_raw_train_test_ds(model_name_or_path, tokenizer, train_seq_len=512, test_seq_len=512, overwrite_cache=False, DATA_DIR=DEFAULT_DATA_DIR):
' Returns train and test datasets '
train_ds = get_wikitext2_raw_train_valid_test_ds(model_name_or_path=model_name_or_path, tokenizer=tokenizer, split='tra... |
def get_wikitext2_raw_train_valid_ds(model_name_or_path, tokenizer, train_seq_len=512, valid_seq_len=512, overwrite_cache=False, DATA_DIR=DEFAULT_DATA_DIR):
train_ds = get_wikitext2_raw_train_valid_test_ds(model_name_or_path=model_name_or_path, tokenizer=tokenizer, split='train', block_size=train_seq_len, overwri... |
def get_wikitext2_raw_test_ds(model_name_or_path, tokenizer, test_seq_len=512, overwrite_cache=False, DATA_DIR=DEFAULT_DATA_DIR):
test_ds = get_wikitext2_raw_train_valid_test_ds(model_name_or_path=model_name_or_path, tokenizer=tokenizer, split='test', block_size=test_seq_len, overwrite_cache=overwrite_cache)
... |
def lm_collate(tokenizer, examples: List[torch.Tensor]):
if (tokenizer._pad_token is None):
return pad_sequence(examples, batch_first=True)
return pad_sequence(examples, batch_first=True, padding_value=tokenizer.pad_token_id)
|
def lm_collate_factory(tokenizer):
assert (tokenizer is not None)
return functools.partial(lm_collate, tokenizer)
|
def get_lm_train_dl(ds_train, bs_train, tokenizer=None, collate_fn=None, shuffle=True, **kw):
collate = (collate_fn if collate_fn else lm_collate_factory(tokenizer))
train_sampler = RandomSampler(ds_train)
train_dl = DataLoader(ds_train, shuffle=False, sampler=train_sampler, batch_size=bs_train, collate_f... |
def get_lm_eval_dl(ds_eval, bs_eval, tokenizer=None, shuffle=False, collate_fn=None, **kw):
collate = (collate_fn if collate_fn else lm_collate_factory(tokenizer))
eval_sampler = SequentialSampler(ds_eval)
eval_dl = DataLoader(bs_eval, sampler=eval_sampler, batch_size=bs_eval, shuffle=False, collate_fn=co... |
def get_lm_train_valid_dl(ds_train, ds_test, bs_train, bs_test, tokenizer=None, **kw):
if ('collate_fn' not in kw):
collate = lm_collate_factory(tokenizer)
kw['collate_fn'] = collate
train_dl = get_lm_train_dl(ds_train, bs_train, **kw)
valid_dl = get_lm_eval_dl(ds_test, bs_test, **kw)
... |
class SEP_WIKITEXT2_DatasetHandler(CommonDatasetHandler):
def __init__(self, **kw):
super().__init__()
d = extract_needed_keywords(**kw)
(train_ds, test_ds) = get_wikitext2_raw_train_test_ds(**d)
self.train_ds = train_ds
self.test_ds = test_ds
tokenizer = kw['token... |
def extract_needed_keywords(**kw):
args = kw['args']
tokenizer = kw['tokenizer']
overwrite_cache = getattr(args, 'overwrite_cache', False)
d = dict(model_name_or_path=args.model_name_or_path, tokenizer=tokenizer, train_seq_len=args.train_seq_len, test_seq_len=args.test_seq_len, overwrite_cache=overwri... |
def load_and_cache_examples_just_x_or_y(just, model_name_or_path, max_seq_length, doc_stride, max_query_length, threads, tokenizer, DATA_DIR, evaluate=False, output_examples=False, overwrite_cache=True, save=False, version_2_with_negative=False, **kw):
squad_dir = get_squad_dir(DATA_DIR, version_2_with_negative)
... |
def squad_convert_examples_to_features_just_x_or_y(just, examples, tokenizer, max_seq_length, doc_stride, max_query_length, is_training, return_dataset='pt', threads=1, do_all_cls_index=False, do_all_p_mask=False, do_all_is_impossible=False, **kw):
"\n Converts a list of examples into a list of features that c... |
def get_dataset_by_just(d, just):
l = []
for name in just:
l.append(d[name])
if ('all_start_positions' in d):
l.append(d['all_start_positions'])
if ('all_end_positions' in d):
l.append(d['all_end_positions'])
if ('all_example_index' in d):
l.append(d['all_example_in... |
def train_just(just, DATA_DIR, **kw):
train_ds = load_and_cache_examples_just_x_or_y(just=just, DATA_DIR=DATA_DIR, evaluate=False, output_examples=False, **kw)
return train_ds
|
def dev_just(just, DATA_DIR, **kw):
(dev_ds, examples, features) = load_and_cache_examples_just_x_or_y(just=just, DATA_DIR=DATA_DIR, evaluate=True, output_examples=True, **kw)
return (dev_ds, examples, features)
|
def getitem(t):
if isinstance(t, dict):
res = {i: getitem(v) for (i, v) in t.items()}
else:
try:
res = t.item()
except:
res = t
return res
|
def get_just_x_or_y_train_dev_dataset(just, DATA_DIR, **kw):
' get x or y datset. '
train_ds = load_and_cache_examples_just_x_or_y(just=just, DATA_DIR=DATA_DIR, evaluate=False, output_examples=False, **kw)
print('squad', 'version_2_with_negative', kw['version_2_with_negative'])
(dev_ds, examples, feat... |
def get_squad_dir(DATA_DIR, version_2_with_negative: bool):
if version_2_with_negative:
res = os.path.join(DATA_DIR, 'squad2')
else:
res = os.path.join(DATA_DIR, 'squad1')
return res
|
def get_train_file(squad_dir, version_2_with_negative):
if version_2_with_negative:
res = os.path.join(squad_dir, 'train-v2.0.json')
else:
res = os.path.join(squad_dir, 'train-v1.1.json')
return res
|
def get_predict_file(squad_dir, version_2_with_negative):
if version_2_with_negative:
res = os.path.join(squad_dir, 'dev-v2.0.json')
else:
res = os.path.join(squad_dir, 'dev-v1.1.json')
return res
|
def make_examples(DATA_DIR, train_file, predict_file, evaluate, version_2_with_negative):
' In case we not loading them '
processor = (SquadV2Processor() if version_2_with_negative else SquadV1Processor())
if evaluate:
examples = processor.get_dev_examples(DATA_DIR, filename=predict_file)
else... |
def update_on_precomputed_attention_mask(all_attention_masks, all_input_ids, d, kw):
if (('input1' in d) or ('attention_mask' in d)):
if kw.get('precompute_attention_mask', False):
name = 'attention_mask'
if ('input1' in d):
warnings.warn('name input1 is deprecated.... |
def evaluate(examples, features, tokenizer, args, all_results, config=None, prefix=''):
' Called after we have all results\n TODO: replace args?\n '
print('Evaluating Squad on CPU')
if (not os.path.exists(args.output_dir)):
os.makedirs(args.output_dir)
output_prediction_file = os.pat... |
def get_extended_attention_mask(attention_mask, input_ids, dtype=torch.float32):
' Extented attention mask, removing the preprocessing from inside to outside, bert'
if (attention_mask is None):
attention_mask = torch.ones_like(input_ids)
extended_attention_mask = attention_mask.unsqueeze(1).unsque... |
class SEP_SQUAD_DatasetHandler(CommonDatasetHandler):
def __init__(self, **kw):
super().__init__()
d = extract_needed_keywords(**kw)
(train_ds, test_ds, extra) = get_just_x_or_y_train_dev_dataset(kw['just'], kw['DATA_DIR'], **d)
self.train_ds = train_ds
self.dev_ds = test_... |
def extract_needed_keywords(**kw):
args = kw['args']
tokenizer = kw['tokenizer']
overwrite_cache = getattr(args, 'overwrite_cache', False)
version_2_with_negative = (args.dataset == 'squad2')
if hasattr(args, 'version_2_with_negative'):
assert (version_2_with_negative == args.version_2_wit... |
def density(x):
return (np.count_nonzero(x) / np.prod(x.shape))
|
def analyze_packing(mixture_or_task_name, sequence_length, dataset_split='train', packed_ds=None):
if (packed_ds is None):
packed_ds = like_mtf(mixture_or_task_name=mixture_or_task_name, sequence_length=sequence_length, dataset_split=dataset_split, pack=True)
ds = packed_ds
def create_record(pack... |
def analyze_padding(mixture_or_task_name, sequence_length, dataset_split='train', padded_ds=None):
if (padded_ds is None):
padded_ds = like_mtf(mixture_or_task_name=mixture_or_task_name, sequence_length=sequence_length, dataset_split=dataset_split, pack=False)
ds = padded_ds
def create_record(pad... |
def infer_no_truncation_padding_seq_length(df):
sequence_length = {'inputs': df['input_seq_length'].max(), 'targets': df['target_seq_length'].max()}
return sequence_length
|
def infer_no_truncation_padding_seq_length_all_splits(mixture_or_task_name, sequence_length, splits=['train', 'validation']):
df = pd.concat([analyze_padding(mixture_or_task_name=mixture_or_task_name, sequence_length=sequence_length, dataset_split=dataset_split) for dataset_split in splits])
return infer_no_t... |
def infer_no_truncation_padding_seq_length_for_all_t5_available_tasks():
names = t5_tasks_we_want()
sequence_length = {'inputs': 512, 'targets': 512}
splits = ['train', 'validation']
res = {}
for mixture_or_task_name in names:
req = infer_no_truncation_padding_seq_length_all_splits(mixture... |
def t5_tasks_we_want():
return ['glue_cola_v002', 'glue_sst2_v002', 'glue_qqp_v002', 'glue_mrpc_v002', 'glue_stsb_v002', 'glue_qnli_v002', 'glue_rte_v002', 'glue_wnli_v002', 'super_glue_boolq_v102', 'super_glue_cb_v102', 'super_glue_copa_v102', 'super_glue_multirc_v102', 'super_glue_record_v102', 'super_glue_rte_... |
def glue_rte_v002():
mixture_or_task_name = 'glue_rte_v002'
sequence_length = {'inputs': 512, 'targets': 87}
dataset_split = 'train'
df_packing = analyze_packing(mixture_or_task_name=mixture_or_task_name, sequence_length=sequence_length, dataset_split=dataset_split)
df_padding = analyze_padding(mi... |
def sum_task(mixture_or_task_name, dataset_split='train', add_percentiles=True):
sequence_length = {'inputs': 512, 'targets': 512}
df_packing = analyze_packing(mixture_or_task_name=mixture_or_task_name, sequence_length=sequence_length, dataset_split=dataset_split)
df_padding = analyze_padding(mixture_or_t... |
def load_huggingface_checkpoint(args, cp_number, spread_across_devices=True, **kwargs):
hf_transformers_model_class = T5ForConditionalGeneration
loader = NewT5HFLoader(hf_transformers_model_class=hf_transformers_model_class)
if (cp_number == 'c4'):
model_name_or_path = args.model_name_or_path
... |
class T5Evaluator():
'Slightly patched with features'
def __init__(self, args, model_dir, device, model: T5ForConditionalGeneration=None, spread_across_devices=True, use_existing_model_next_loads=True):
super().__init__()
self._model: T5ForConditionalGeneration = None
self._writer = S... |
def write_lines_to_file(lines, filename):
import tensorflow.compat.v1 as tf
'Write each line to filename, replacing the file if it exists.'
if tf.io.gfile.exists(filename):
tf.io.gfile.remove(filename)
with tf.io.gfile.GFile(filename, 'w') as output_file:
output_file.write('\n'.join([s... |
def get_t5_sequence_length_from_args(args):
return {'inputs': args.max_seq_length, 'targets': args.answer_max_seq_length}
|
def evaluate_t5_tfds(args, cp_number, device='cpu'):
DIR_NAME = 'results/t5_eval_dir/'
model_dir = os.path.join(DIR_NAME, auto_file_name(args))
batch_size = getattr(args, 'single_worker_eval_batch_size', 32)
generate_kwargs = getattr(args, 'generate_kwargs', {})
evaluator = T5Evaluator(args, model... |
def load_huggingface_checkpoint(args, cp_number, spread_across_devices=True, **kwargs):
if spread_across_devices:
hf_transformers_model_class = ModelParallelT5ForConditionalGeneration
else:
hf_transformers_model_class = T5ForConditionalGeneration
loader = T5HFLoader(hf_transformers_model_c... |
class T5Evaluator():
'Slightly patched with features'
def __init__(self, args, model_dir, device, model: T5ForConditionalGeneration=None, spread_across_devices=True, use_existing_model_next_loads=True):
super().__init__()
self._model: T5ForConditionalGeneration = None
self._writer = t... |
def write_lines_to_file(lines, filename):
import tensorflow.compat.v1 as tf
'Write each line to filename, replacing the file if it exists.'
if tf.io.gfile.exists(filename):
tf.io.gfile.remove(filename)
with tf.io.gfile.GFile(filename, 'w') as output_file:
output_file.write('\n'.join([s... |
def get_t5_sequence_length_from_args(args):
return {'inputs': args.max_seq_length, 'targets': args.answer_max_seq_length}
|
def evaluate_t5_tfds(args, cp_number, device='cpu'):
DIR_NAME = 'results/t5_eval_dir/'
model_dir = os.path.join(DIR_NAME, auto_file_name(args))
batch_size = getattr(args, 'single_worker_eval_batch_size', 32)
generate_kwargs = getattr(args, 'generate_kwargs', {})
evaluator = T5Evaluator(args, model... |
def get_transformations(mean, std, resize_size, crop_size, mode='train', jit_script=False):
if (mode == 'train'):
transform = [torchvision.transforms.Resize((resize_size, resize_size)), torchvision.transforms.RandomCrop((crop_size, crop_size)), torchvision.transforms.RandomHorizontalFlip(), torchvision.tr... |
def cifar10_transformations(jit_script=False, resize_size=384, crop_size=384):
mean = np.array(CIFAR10_DEFAULT_MEAN)
std = np.array(CIFAR10_DEFAULT_STD)
train_transform = get_transformations(mean=mean, std=std, crop_size=crop_size, resize_size=resize_size, mode='train', jit_script=jit_script)
test_tra... |
def cifar100_transformations(jit_script=False, resize_size=384, crop_size=384):
mean = np.array(CIFAR100_DEFAULT_MEAN)
std = np.array(CIFAR100_DEFAULT_STD)
train_transform = get_transformations(mean=mean, std=std, crop_size=crop_size, resize_size=resize_size, mode='train', jit_script=jit_script)
test_... |
def imagenet_transformations(jit_script=False, resize_size=384, crop_size=384):
mean = IMAGENET_DEFAULT_MEAN
std = IMAGENET_DEFAULT_STD
train_transform = get_transformations(mean=mean, std=std, crop_size=crop_size, resize_size=resize_size, mode='train', jit_script=jit_script)
test_transform = get_tran... |
def sep_imagenet_handler_factory(resize_size=384, crop_size=384):
class SepImagenetAutoGenDatasetHandler(CommonDatasetHandler):
def __init__(self, **kw):
super().__init__()
def get_train_ds(self, **kw):
(train_transform, _) = imagenet_transformations(resize_size=resize_s... |
class SepCifar10_384_DatasetHandler(CommonDatasetHandler):
def __init__(self, **kw):
super().__init__()
def get_train_ds(self, **kw):
(train_transform, _) = cifar10_transformations(resize_size=384, crop_size=384)
return get_cifar_10_just_x_or_y_ds(transform=train_transform, train=Tru... |
class SepCifar100_384_DatasetHandler(CommonDatasetHandler):
def __init__(self, **kw):
super().__init__()
def get_train_ds(self, **kw):
(train_transform, _) = cifar100_transformations(resize_size=384, crop_size=384)
return get_cifar_100_just_x_or_y_ds(transform=train_transform, train=... |
def infer_all_cps(args) -> int:
if (args.epochs > 0):
n_cps = args.epochs
if (getattr(args, 'save_checkpoint_every_x_steps', None) is not None):
warnings.warn(f'Miss-Estimated number of checkpoints due args.save_checkpoint_every_x_steps={args.save_checkpoint_every_x_steps}')
elif (... |
def get_all_eval_results(args):
explicit_eval_cp = getattr(args, 'explicit_eval_cp', None)
if (explicit_eval_cp is not None):
all_cps = [explicit_eval_cp]
print(f'Got explicit_eval_cp={explicit_eval_cp}. changing out_file_name')
args.out_filename = ((explicit_eval_cp + '_') + args.out_... |
def is_json(fn):
return ('.json' in fn)
|
def all_files(path):
file_names = []
for (root, dirs, files) in os.walk(path, topdown=True):
for name in files:
if is_json(name):
fn = os.path.join(root, name)
file_names.append(fn)
return file_names
|
class InferStuff():
def __init__(self, config, fit_res):
self.config = config
self.fit_res = fit_res
stat_to_default = {'step_every': 1}
def get_from_cfg(stat):
return (config[stat] if (stat in config) else stat_to_default[stat])
self.interesting_from_config =... |
def process_file(f):
' Returns a dataframe '
(config, fit_res) = load_experiment(f)
inferer = InferStuff(config, fit_res)
inferer.infer_epoch_attrs()
inferer.replicate()
return inferer.to_df()
|
def all_results_to_csv(root_paths, csv_name):
if isinstance(root_paths, str):
root_paths = [root_paths]
files = []
for root_path in root_paths:
files += all_files(root_path)
print(f'-I- There are {len(files)} json files in {root_paths}')
print('-I- Creating....')
df = pd.concat... |
def print_uniques(csv, cols=['alg', 'bs_train', 'model', 'dataset', 'seed', 'step_every']):
df = pd.read_csv(csv)
var_to_uniques = {var: pd.unique(df[var]) for var in cols}
var_to_len_uniques = {i: len(v) for (i, v) in var_to_uniques.items()}
print(f'-I- Describing csv: {csv}')
print(f'-I- Analyze... |
def try_to_move_from_cfg_to_fit_res(config, fit_res, stats_names=STATS_SAVED_IN_ARGS):
for name in stats_names:
if (name in config):
fit_res[name] = config[name]
del config[name]
|
def add_plot(fn, legened, fig=None, plot_fn=plot.plot_fit, try_to_move=True):
(config, fit_res) = load_experiment(fn)
if try_to_move:
try_to_move_from_cfg_to_fit_res(config, fit_res)
loss_per_batch = ('loss_per_batch' in config['statistics'])
(fig, ax) = plot_fn(fit_res, fig=fig, log_loss=Fals... |
def gen_plot(out_dir='results', out_base_name='current_status.png'):
plt.plot()
if (not os.path.exists(out_dir)):
os.makedirs(out_dir)
out_file_name = os.path.join(out_dir, out_base_name)
plt.savefig(out_file_name)
print(f'-I- Generated: "{out_file_name}"')
|
def gen_plot_from_dict(fn_to_contour, plot_fn, out_base_name, out_dir='results'):
d = dict(fig=None, plot_fn=plot_fn)
for (n, c) in fn_to_contour.items():
(d['fig'], ax) = add_plot(n, c, **d)
gen_plot(out_dir=out_dir, out_base_name=f'{out_base_name}.png')
|
def vit_b_16_c100():
out_base_name = 'ViT_B_16_norm'
out_dir = 'results/figs'
plot_fn = plot.plot_grad_norm
fn_to_contour = {'results/vit/cifar100/fast_dcgn_global_no_nesterov_meanstd05_vit_base_patch16_384_in21k_imagenet_384c384_8p_bw12_gpipe_acyclic_cifar100_384_gpipe_bs_512_se_16_seed_42.json': 'gl... |
def alg(fn):
all_algs = ['msnag', 'aggmsnag', 'stale', 'pipedream']
for a in all_algs:
ga_alg = f'{a}_ws_ga'
if (ga_alg in fn):
return ga_alg
ws_alg = '{a}_ws'
if ((ws_alg + '_') in fn):
return ws_alg
return ('gpipe' if ('gpipe' in fn) else ('aggmsna... |
def read_desc_df(path='desc.csv'):
df = pd.read_csv(path, index_col=[0, 1, 2], header=[0, 1], skipinitialspace=True)
return df
|
def filter_desc_df_squad(desc):
df = desc
return df[[(i, j) for i in ['f1', 'em', 'total_time'] for j in ['mean', 'max', 'min', 'std']]]
|
def filter_desc_df_lm(desc):
df = desc
return df[[(i, j) for i in ['ppl', 'total_time'] for j in ['mean', 'max', 'min', 'std']]]
|
def filter_desc_df_cv(desc):
df = desc
return df[[(i, j) for i in ['acc', 'total_time'] for j in ['mean', 'max', 'min', 'std']]]
|
def write_squad_desc_df():
ls = glob.glob
records = []
for f in ls('*.json'):
d = {}
with open(f, 'rb') as fd:
r = json.load(fd)
d['name'] = f
d['alg'] = alg(f)
d['seed'] = r['config']['seed']
d['agg'] = r['config']['step_every']
... |
def write_lm_desc_df():
ls = glob.glob
records = []
for f in ls('*.json'):
d = {}
with open(f, 'rb') as fd:
r = json.load(fd)
d['name'] = f
d['alg'] = alg(f)
d['seed'] = r['config']['seed']
d['agg'] = r['config']['step_every']
... |
def write_cv_desc_df():
ls = glob.glob
records = []
for f in ls('*.json'):
d = {}
with open(f, 'rb') as fd:
r = json.load(fd)
d['name'] = f
d['alg'] = alg(f)
d['seed'] = r['config']['seed']
d['agg'] = r['config']['step_every']
... |
def plot_loss(fit_res: Union[(NamedTuple, dict)], fig=None, log_loss=False, legend=None, loss_per_batch=False, step_every=1, original_step_every=1):
if (fig is None):
(fig, axes) = plt.subplots(nrows=2, ncols=1, figsize=(8, 10))
axes = axes.reshape((- 1))
else:
axes = fig.axes
for ... |
def plot_fit(fit_res: Union[(NamedTuple, dict)], fig=None, log_loss=False, legend=None, loss_per_batch=False):
'\n Plots a FitResult object.\n Creates four plots: train loss, test loss, train acc, test acc.\n :param fit_res: The fit result to plot.\n :param fig: A figure previously returned from this ... |
def plot_grad_norm(fit_res: Union[(NamedTuple, dict)], fig=None, legend=None, **kw):
local_norm_key = 'local_grad_norm'
total_norms = sum(((local_norm_key in key) for key in fit_res.keys()))
assert ((total_norms % 2) == 0)
if (fig is None):
(fig, axes) = plt.subplots(nrows=(1 + (total_norms //... |
def plot_gap(fit_res: Union[(NamedTuple, dict)], fig=None, legend=None, **kw):
total = sum((('gap' in key) for key in fit_res.keys()))
assert ((total % 2) == 0)
if (fig is None):
(fig, axes) = plt.subplots(nrows=(1 + (total // 2)), ncols=2, figsize=(16, 10), sharex='col', sharey=False)
axe... |
def plot_tta(fit_res: Union[(NamedTuple, dict)], fig=None, log_loss=False, legend=None, loss_per_batch=False):
time_units = 'hours'
time_div_factor = {'seconds': 1, 'minutes': 60, 'hours': 3600}
time_div_factor = time_div_factor.get(time_units)
if loss_per_batch:
raise NotImplementedError()
... |
def p1(graph='test_acc'):
csv = '4partitions.csv'
out_file_name = f'{graph}.png'
out_file_name = os.path.join('.', out_file_name)
df = pd.read_csv(csv).query("dataset == 'cifar100'")
ax = sns.lineplot(x='epoch', y=graph, hue='alg', data=df)
ax.set_title(graph)
model = pd.unique(df.model)
... |
def p1_fit_plots():
for graph in ['test_acc', 'train_acc', 'train_loss', 'test_loss']:
plt.figure()
p1(graph)
|
def p2():
csv = '4partitions.csv'
out_file_name = 'output.png'
out_file_name = os.path.join('.', out_file_name)
df = pd.read_csv(csv).query("dataset == 'cifar100'").query('epoch == 200')
ax = sns.barplot(x='epoch', y='test_acc', hue='alg', data=df)
model = pd.unique(df.model)
assert (len(m... |
def p2_2partitions(model='wrn_28x10_c100_dr03_p2'):
csv = '2partitions.csv'
out_file_name = f'{model}_output.png'
out_file_name = os.path.join('.', out_file_name)
df = pd.read_csv(csv).query("dataset == 'cifar100' and model == @model").query('epoch == 200')
ax = sns.barplot(x='epoch', y='test_acc'... |
def p2_2partitions_16x4(model='wrn_16x4_c100_p2'):
csv = '2partitions.csv'
out_file_name = f'{model}_output.png'
out_file_name = os.path.join('.', out_file_name)
df = pd.read_csv(csv).query("dataset == 'cifar100' and model == @model").query('epoch == 200')
ax = sns.barplot(x='epoch', y='test_acc',... |
def p2_2partitions_all_models():
for model in ['wrn_16x4_c100_p2', 'wrn_28x10_c100_dr03_p2']:
plt.figure()
p2_2partitions(model)
|
def p3():
csv = '4partitions.csv'
out_file_name = 'output2.png'
out_file_name = os.path.join('.', out_file_name)
df = pd.read_csv(csv).query("dataset == 'cifar10'").query('epoch == 200')
ax = sns.barplot(x='epoch', y='test_acc', hue='alg', data=df)
model = pd.unique(df.model)
assert (len(m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.