code
stringlengths
17
6.64M
def wrn16x4_c100(): "\n all_results_to_df.py\n -I- There are 236 json files in ['results/4partitions', 'results/sequential']\n -I- Creating....\n -I- Created df.shape: (68370, 23)\n -I- Writing csv: ./4p_seq_ddpsim.csv\n -I- Done\n -I- Describing csv: ./4p_seq_ddpsim.csv\n -I- Analyzed col...
def wrn16x4_c100_gap(): "\n all_results_to_df.py\n -I- There are 236 json files in ['results/4partitions', 'results/sequential']\n -I- Creating....\n -I- Created df.shape: (68370, 23)\n -I- Writing csv: ./4p_seq_ddpsim.csv\n -I- Done\n -I- Describing csv: ./4p_seq_ddpsim.csv\n -I- Analyzed...
def for_meeting(): csv = 'for_meeting.csv' out_file_name = 'for_meeting.png' out_file_name = os.path.join('.', out_file_name) df = pd.read_csv(csv).query("dataset == 'cifar100'").query('epoch == 200').query("bs_train == 32 and alg == 'ddp' or bs_train == 128 and alg != 'ddp'") ax = sns.barplot(x='...
def for_meeting2(): csv = 'for_meeting.csv' out_file_name = 'for_meeting_bigger_ddp.png' out_file_name = os.path.join('.', out_file_name) df = pd.read_csv(csv).query("dataset == 'cifar100'").query('epoch == 200').query("bs_train == 128 and alg == 'ddp' or bs_train == 128 and alg != 'ddp'") ax = sn...
def arrowed_spines(fig, ax): (xmin, xmax) = ax.get_xlim() (ymin, ymax) = ax.get_ylim() for side in ['bottom', 'right', 'top', 'left']: ax.spines[side].set_visible(False) plt.xticks([]) plt.yticks([]) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') dps = ...
def sanitize_memory(memory_mb): return ((memory_mb / 11019) * GPU_MAX_WIDTH)
def sanitize_utilizaton(util): return ((util / 100) * GPU_HEIGHT)
def add_gpu(ax, gpu_id, memory, utilization): memory = sanitize_memory(memory) utilization = sanitize_utilizaton(utilization) frac = utilization fat = memory height = GPU_HEIGHT x = (gpu_id * (GPU_MAX_WIDTH + SPACE)) y = GPU_DOWN_BORDER bb = Rectangle((x, y), GPU_MAX_WIDTH, GPU_HEIGHT,...
def load_experiment(filename) -> Tuple[(Dict[(Any, Any)], Dict[(Any, Any)])]: ' Returns:\n config, fit_res\n ' with open(filename, 'r') as f: output = json.load(f) config = output['config'] fit_res = output['results'] return (config, fit_res)
def load_experiment_for_update(run_name, out_dir): output_filename = f'{os.path.join(out_dir, run_name)}.json' with open(output_filename, 'r') as f: output = json.load(f) config = output['config'] fit_res = output['results'] return (config, fit_res)
def save_experiment(run_name, out_dir, config, fit_res: Dict): if isinstance(fit_res, NamedTuple): fit_res = fit_res._asdict() elif isinstance(fit_res, SimpleNamespace): fit_res = fit_res.__dict__ output = dict(config=config, results=fit_res) output_filename = f'{os.path.join(out_dir, ...
class ArgsStasher(): '\n used for naming and reproducibility conventions,\n (as sometimes we change the args inplace)\n ' STASH_NAME = '_tmp_stashed' @staticmethod def stash_to_args(args, replaced_key, old_value): if (not hasattr(args, 'auto_file_name')): return S...
def auto_file_name(args, verbose=True): ArgsStasher.reload_stashed_args(args) 'This is used to distinguish different configurations by file name ' assert hasattr(args, 'auto_file_name') wp = (args.weight_prediction['type'] if hasattr(args, 'weight_prediction') else 'stale') ws = ('ws_' if getattr(...
def set_style(): sns.set_context('paper') sns.set(font='serif') sns.set_style('white', {'font.family': 'serif', 'font.serif': ['Times', 'Palatino', 'serif']}) import matplotlib matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42
def parse_all_eval_results_dict(fn): with open(fn, 'r') as f: d = ast.literal_eval(f.read()) return d
def extract_values(d, subkey=None, verbose=False): if (subkey is None): s = set() for v in d.values(): for x in v.keys(): s.add(x) if (len(s) == 1): subkey = next(iter(s)) else: raise ValueError('please choose subkey from', s) ...
def plot_epochs_vs_accuracy(*, gpipe_dict=None, stale_dict=None, acc_without_ft=None, title='super_glue_boolq_accuracy', ylabel=f'Accuracy'): (fix, ax) = plt.subplots() if (acc_without_ft is None): ax.plot(list(gpipe_dict.keys()), list(gpipe_dict.values()), marker=GPIPE_MARKER, label='gpipe') ...
def extract_cumsum_train_times(loaded, time_units='seconds'): times = extract_train_epoch_times(loaded) times = times_to_cumsum_and_units(time_units, times) return times
def extract_train_epoch_times(loaded): return loaded[0]['train_epochs_times']
def times_to_cumsum_and_units(time_units, times): time_div_factor = {'seconds': 1, 'minutes': 60, 'hours': 3600} time_div_factor = time_div_factor.get(time_units.lower()) times = (np.array(times) / time_div_factor) times = np.cumsum(times) return times
def plot_time_vs_accuracy(*, gpipe_dict=None, stale_dict=None, times_gpipe=None, times_stale=None, time_units='hours', acc_without_ft=None, title='super_glue_boolq_accuracy', ylabel=f'Accuracy'): (fix, ax) = plt.subplots() if (acc_without_ft is None): ax.plot(times_gpipe, list(gpipe_dict.values()), ma...
def get_fixed_dict_and_times_single(exp_fn, checkpoints_eval_fn, checkpoint_every_x_epochs=1, epochs_in_last_checkpoint=None, time_units='hours', subkey=None): times_list = extract_cumsum_train_times(load_experiment(exp_fn), time_units=time_units) checkpoints_dict = extract_values(parse_all_eval_results_dict(...
def analyze_datars(times1, times2, values1, values2, colors=('red', 'navy')): from adjustText import adjust_text all_ts = [] all_times = [*times1, *times2] all_vals = [*values1, *values2] for (times, values, color) in zip([times1, times2], [values1, values2], colors): max = np.max(values) ...
def epoch_speedup_dict(exp_gpipe_fn, exp_stale_fn): times_gpipe = extract_cumsum_train_times(load_experiment(exp_gpipe_fn)) times_stale = extract_cumsum_train_times(load_experiment(exp_stale_fn)) d = epoch_speedup_dict_from_cumsum_times(times_gpipe, times_stale) return d
def epoch_speedup_dict_from_cumsum_times(times_gpipe, times_stale): try: assert (len(times_gpipe) == len(times_stale)), str((len(times_gpipe), len(times_stale))) except AssertionError as e: if ((len(times_gpipe) - len(times_stale)) == 1): warnings.warn('allowing 1 difference') ...
def epoch_speedup_from_cumsum_times(*args, idx=(- 1), **kwargs): return list(epoch_speedup_dict_from_cumsum_times(*args, **kwargs).values())[idx]
def epoch_speedup(*args, idx=(- 1), **kwargs): return list(epoch_speedup_dict(*args, **kwargs).values())[idx]
def dump_all_raw_data(exp_stale_fn, exp_gpipe_fn, gpipe_fn, stale_fn, acc_without_ft=None): ' Prints all raw data used for analysis\n The rest are calculations on this data\n ' print('-I- dump_all_raw_data') print(parse_all_eval_results_dict(gpipe_fn)) print(parse_all_eval_results_dict(stal...
def time_to_best_result(gpipe_dict, stale_dict, times_gpipe, times_stale, slow_alg_name='gpipe', fast_alg_name='stale'): values_gpipe = list(gpipe_dict.values()) values_stale = list(stale_dict.values()) max_gpipe = np.max(values_gpipe) max_stale = np.max(values_stale) argmax_gpipe = np.argmax(valu...
def compute_all_speedups(seq_gpipe_dict, seq_gpipe_times, seq_stale_dict, seq_stale_times, virtual_gpipe_dict, virtual_stale_dict, virtual_times_gpipe, virtual_times_stale, skip_gpipe_seq=False): if (not skip_gpipe_seq): time_to_best_result(seq_gpipe_dict, virtual_stale_dict, seq_gpipe_times, virtual_time...
class MultiRC(): @staticmethod def all_speedups_multirc(): subkey = 'eval/super_glue_multirc_v102/f1' (seq_gpipe_dict, seq_gpipe_times) = Hack.get_multirc_seq_hack_gpipe_times_and_dict(subkey=subkey) exp_results_dir = 'results/t5/super_glue/multirc/' seq_exp_stale_fn = os.path...
class WIC(): @staticmethod def all_speedups_wic(): checkpoint_every_x_epochs = (100 // (5427 // 128)) seq_stale_fn = 'results/all_results_no_virtual_stages_benchmark_layer_graph_t5_3b_tied_lmheads_64_4_8p_bw12_squad1_pipedream_t5_tfds_stale_bs_128_se_4_seed_42_layer_graph_t5_3b_tied_lmheads_6...
class BoolQ(): @staticmethod def all_speedups_boolq(): (seq_gpipe_dict, seq_gpipe_times) = Hack.get_boolq_seq_hack_gpipe_times_and_dict() seq_stale_fn = 'results/FOR_PAPER/all_results_new_t5_layer_graph_t5_3b_tied_lmheads_512_4_8p_bw12_squad1_pipedream_t5_tfds_stale_bs_20_se_10_seed_42_layer_...
class RTE(): @staticmethod def all_speedups_rte(): (seq_gpipe_dict, seq_gpipe_times) = Hack.get_rte_seq_hack_gpipe_times_and_dict() seq_stale_fn = 'results/FOR_PAPER/all_results_glue_rte_12_epochs_layer_graph_t5_3b_tied_lmheads_320_8_8p_bw12_squad1_pipedream_t5_tfds_stale_bs_40_se_10_seed_42_...
class Hack(): @staticmethod def get_rte_seq_hack_gpipe_times_and_dict(): exp_gpipe_fn = 'results_new_t5/t5/glue/rte/glue_rte_12_epochs_layer_graph_t5_3b_tied_lmheads_320_8_8p_bw12_squad1_pipedream_t5_tfds_gpipe_bs_40_se_10_seed_42.json' gpipe_fn = 'results_new_t5/all_results_rte_virtual_layer...
class AnnotationPlotsRTE(): @staticmethod def winning_RTE_seq_gpipe_vs_MIXED_stale(): set_style() (gpipe_dict, times_gpipe) = Hack.get_rte_seq_hack_gpipe_times_and_dict() exp_results_dir = 'results_b4_20_5_changes/t5/glue/rte' exp_stale_fn = os.path.join(exp_results_dir, 'new_...
def set_style(): sns.set_context('paper') sns.set(font='serif') sns.set_style('white', {'font.family': 'serif', 'font.serif': ['Times', 'Palatino', 'serif']})
def parse_all_eval_results_dict(fn): with open(fn, 'r') as f: d = ast.literal_eval(f.read()) return d
def extract_values(d, subkey=None, verbose=False): if (subkey is None): s = set() for v in d.values(): for x in v.keys(): s.add(x) if (len(s) == 1): subkey = next(iter(s)) else: raise ValueError('please choose subkey from', s) ...
def plot_epochs_vs_accuracy(*, gpipe_dict=None, stale_dict=None, acc_without_ft=None, title='super_glue_boolq_accuracy', ylabel=f'Accuracy'): (fix, ax) = plt.subplots() if (acc_without_ft is None): ax.plot(list(gpipe_dict.keys()), list(gpipe_dict.values()), marker=GPIPE_MARKER, label='gpipe') ...
def extract_cumsum_train_times(loaded, time_units='seconds'): times = extract_train_epoch_times(loaded) times = times_to_cumsum_and_units(time_units, times) return times
def extract_train_epoch_times(loaded): return loaded[0]['train_epochs_times']
def times_to_cumsum_and_units(time_units, times): time_div_factor = {'seconds': 1, 'minutes': 60, 'hours': 3600} time_div_factor = time_div_factor.get(time_units.lower()) times = (np.array(times) / time_div_factor) times = np.cumsum(times) return times
def plot_time_vs_accuracy(*, gpipe_dict=None, stale_dict=None, times_gpipe=None, times_stale=None, time_units='hours', acc_without_ft=None, title='super_glue_boolq_accuracy', ylabel=f'Accuracy'): (fix, ax) = plt.subplots() if (acc_without_ft is None): ax.plot(times_gpipe, list(gpipe_dict.values()), ma...
def get_fixed_dict_and_times_single(exp_fn, checkpoints_eval_fn, checkpoint_every_x_epochs=1, epochs_in_last_checkpoint=None, time_units='hours', subkey=None): times_list = extract_cumsum_train_times(load_experiment(exp_fn), time_units=time_units) checkpoints_dict = extract_values(parse_all_eval_results_dict(...
def analyze_datars(times1, times2, values1, values2, colors=['red', 'navy']): from adjustText import adjust_text all_ts = [] all_times = [*times1, *times2] all_vals = [*values1, *values2] for (times, values, color) in zip([times1, times2], [values1, values2], colors): max = np.max(values) ...
def epoch_speedup_dict(exp_gpipe_fn, exp_stale_fn): times_gpipe = extract_cumsum_train_times(load_experiment(exp_gpipe_fn)) times_stale = extract_cumsum_train_times(load_experiment(exp_stale_fn)) d = epoch_speedup_dict_from_cumsum_times(times_gpipe, times_stale) return d
def epoch_speedup_dict_from_cumsum_times(times_gpipe, times_stale): assert (len(times_gpipe) == len(times_stale)) d = dict() for i in range(len(times_stale)): d[i] = (times_gpipe[i] / times_stale[i]) return d
def epoch_speedup_from_cumsum_times(*args, idx=(- 1), **kwargs): return list(epoch_speedup_dict_from_cumsum_times(*args, **kwargs).values())[idx]
def epoch_speedup(*args, idx=(- 1), **kwargs): return list(epoch_speedup_dict(*args, **kwargs).values())[idx]
def dump_all_raw_data(exp_stale_fn, exp_gpipe_fn, gpipe_fn, stale_fn, acc_without_ft=None): ' Prints all raw data used for analysis\n The rest are calculations on this data\n ' print('-I- dump_all_raw_data') print(parse_all_eval_results_dict(gpipe_fn)) print(parse_all_eval_results_dict(stal...
def time_to_best_result(gpipe_dict, stale_dict, times_gpipe, times_stale, slow_alg_name='gpipe', fast_alg_name='stale'): values_gpipe = list(gpipe_dict.values()) values_stale = list(stale_dict.values()) max_gpipe = np.max(values_gpipe) max_stale = np.max(values_stale) argmax_gpipe = np.argmax(valu...
def set_style(): sns.set_context('paper') sns.set(font='serif') sns.set_style('white', {'font.family': 'serif', 'font.serif': ['Times', 'Palatino', 'serif']}) import matplotlib matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42
def set_style(): sns.set_context('paper') sns.set(font='serif') sns.set_style('white', {'font.family': 'serif', 'font.serif': ['Times', 'Palatino', 'serif']}) import matplotlib matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42
def set_style(): sns.set_context('paper') sns.set(font='serif') sns.set_style('white', {'font.family': 'serif', 'font.serif': ['Times', 'Palatino', 'serif']}) import matplotlib matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42
def parse_distributed_cli(parser): parser.add_argument('--rank', default=None, type=int, help='Rank of worker, given by torch.distributed.launch, overridden otherwise') parser.add_argument('--local_rank', default=0, type=int, help='Local rank of worker, given by torch.distributed.launch, overridden otherwise'...
def parse_multiprocessing_cli(parser): parser.add_argument('--nprocs', type=int, default=4, help='Tells us how much processes do we want') parser.add_argument('--master_port', type=int, default=29500) parser.add_argument('--verbose_comm', action='store_true') parser.add_argument('--verbose_comm_from_c...
def parse_cli(): parser = argparse.ArgumentParser(description='PyTorch partition as part of Async Pipeline') parser.add_argument('--mode', choices=['dist', 'mp', 'preproc', 'eval'], default='dist', help='Running mode') parse_distributed_cli(parser) parse_multiprocessing_cli(parser) parser.add_argu...
def maybe_parse_mpi_env_vars(args): '\n Parses env vars (e.g from mpirun) and push them into args (overriding).\n This allows completing some "incomplete" cli-argument parsing.\n\n Requires:\n args = parse_cli()\n\n References:\n https://www.open-mpi.org/faq/?category=running#mpi-environ...
def save_distributed_experiment(statistics, args, world_size, rank, local_rank, stage): def careful_del(x, n): if (n in x): del x[n] un_needed_args = ['stage', 'rank', 'local_rank'] if (rank == (world_size - 1)): if statistics: fit_res = statistics.get_stats(stage)...
def mp_queue_matrix(args, start_method='spawn'): 'create queues matrix to be shared among precesses' mmp = mp.get_context(start_method) world_size = args.world_size cfg = args.model prefer_seq_sends = True handler = AVAILABLE_MODELS.get(cfg) if (handler is None): raise ValueError(f...
def multiprocessing_worker(rank, args, share): mp.set_start_method('fork', force=True) local_rank = rank args.rank = rank args.local_rank = local_rank args.is_multiprocessing_worker = True backend = 'gloo' current_env = os.environ current_env['MASTER_ADDR'] = '127.0.0.1' current_en...
def start_distributed(python_args_dict=None): args = get_basic_args(python_args_dict) maybe_parse_mpi_env_vars(args) args.world_size = get_world_size(args.distributed_backend) args.is_multiprocessing_worker = False main(args)
def main(args, shared_ctx=None): if (args.debug and ((args.rank in args.debug) or ((- 1) in args.debug))): import ptvsd port = (3000 + args.local_rank) args.num_data_workers = 0 address = ('127.0.0.1', port) print(f'-I- rank {args.rank} waiting for attachment on {address}')...
def start_mutiprocessing(python_args_dict=None): args = get_basic_args(python_args_dict) args.world_size = args.nprocs start_method = 'spawn' rcv_queues = mp_queue_matrix(args, start_method=start_method) buffer_reuse_queues = mp_queue_matrix(args, start_method=start_method) share = (rcv_queues...
def start_preproc(python_args_dict=None): args = get_basic_args(python_args_dict) args.world_size = args.nprocs cache = None for rank in range(args.world_size): print(f'-I- preprocessing data for rank {rank}/{(args.world_size - 1)} (word size is {args.world_size})...') local_rank = ran...
def start_eval_checkpoint(python_args_dict=None): args = get_basic_args(python_args_dict) all_results = get_all_eval_results(args) pprint(all_results) with io.StringIO() as buf, redirect_stdout(buf): pprint(all_results) s = buf.getvalue() auto_file_name(args) fn = f'results/all...
def get_basic_args(python_args_dict=None): args = parse_cli() if python_args_dict: add_parsed_config_to_args(args, python_args_dict) else: parse_json_config(args, args.config, first=True) return args
def start(python_args_dict=None): print(f'Using {torch.get_num_threads()} Threads') args = parse_cli() if (args.mode == 'mp'): print('Running in multiprocessing mode') start_mutiprocessing(python_args_dict=python_args_dict) elif (args.mode == 'preproc'): print('Running in prepr...
def get_config(): config = ConfigDict() config.logdir = 'logs/t5/mpipe/' config.data_dir = '/home_local/saareliad/data' config.out_dir = 'results/t5/super_glue/boolq' config.auto_file_name = True config.out_filename = 'test_vs' config.distributed_backend = 'mpi' config.model = 't5_3b_t...
class FileLogger(): def __init__(self, output_dir: str, global_rank: int, local_rank: int, name: str, world_size: int, name_prefix=''): self.output_dir = output_dir if (not os.path.exists(self.output_dir)): os.makedirs(self.output_dir, exist_ok=True) self.logger = FileLogger.g...
def MPI_Init(): print('-I- calling MPI_Init') argc = c_int() argv = POINTER(c_char_p)() mpi.MPI_Init(byref(argc), byref(argv))
def mpi_finalize(): print('-I- Calling MPI_Finalize') mpi.MPI_Finalize()
def process_begin_mpi(): MPI_Init() atexit.register(mpi_finalize)
def worker_function(local_rank, world_size): print('-I- my local_rank is', local_rank) import os os.environ['OMPI_COMM_WORLD_SIZE'] = str(world_size) os.environ['OMPI_COMM_WORLD_RANK'] = str(local_rank) os.environ['OMPI_COMM_WORLD_LOCAL_RANK'] = str(local_rank) os.environ['OMPI_UNIVERSE_SIZE']...
def wait(handlers): for i in handlers: i.wait()
def parse_cli(): parser = argparse.ArgumentParser(description='tst') parser.add_argument('--master_port', type=int, default=29500) parser.add_argument('--rank', default=None, type=int, help='Rank of worker') parser.add_argument('--local_rank', default=0, type=int, help='Local rank of worker') pars...
def gloo_cuda_test(): BACKAND = 'gloo' NUM_ISEND = 3 shape = (512, 32, 32, 64) args = parse_cli() local_rank = args.local_rank rank = args.local_rank print(local_rank) backend = 'gloo' current_env = os.environ current_env['MASTER_ADDR'] = '127.0.1.1' current_env['MASTER_POR...
def test_general(): dist.init_process_group(BACKAND, init_method='env://', world_size=2) handlers = [] if (dist.get_rank() == 0): device = torch.device(('cuda:0' if (BACKAND == 'mpi') else 'cpu')) if (BACKAND == 'mpi'): torch.cuda.set_device(device) tensors = [torch.one...
def gpt2_tied(): COMMAND = 'mpirun -np 5 python main.py' cfgs_dir = 'configs/lm/wt2/gpt2/tied/' all_algs = ['stale'] param_grid = {'config': [f'{cfgs_dir}{cfg}.json' for cfg in all_algs], 'seed': [1322019]} run_grid_on_multi_gpu_per_run(COMMAND, param_grid, gpu_list=list(range(8)), gpus_per_config...
def gpt2xl(): COMMAND = 'python main.py --mode mp --nprocs 8 --step_every 8 --step_every_from_cmd' cfgs_dir = 'configs/lm/wt2/gpt2xl/untied/' all_algs = ['aggmsnag', 'stale', 'seq', 'gpipe'] param_grid = {'config': [f'{cfgs_dir}{cfg}.json' for cfg in all_algs], 'seed': [42, 20202020, 77777777, 314159,...
def grad_accumulation_WRN(): def mp_cv_grad_accumulation(helper, alg='stale_nr', model='wrn_28x10_c100_dr03_p4_group_norm', port=29500, seed=42): COMMAND = 'python main.py --mode mp' cv_cfgs_dir = 'configs/cv/cifar100/wrn28x10/no_recomputation/' gpus_per_config = 4 cfgs_dir = cv_c...
def t5_glue(): ALL_TASKS = {} def mp_helper(helper, alg='stale_nr', model='wrn_28x10_c100_dr03_p4_group_norm', port=29500, seed=42): COMMAND = 'python main.py --mode mp' cv_cfgs_dir = 'configs/cv/cifar100/wrn28x10/no_recomputation/' gpus_per_config = 4 cfgs_dir = cv_cfgs_dir ...
def parse_cli(): parser = argparse.ArgumentParser('replicate experiments grid') parser.add_argument('-e', '--exp', choices=AVAIALBE_EXPS.keys(), default='grad_accumulation_WRN') args = parser.parse_args() return args
def get_input_args_kwargs(sample) -> Tuple[(Tuple, Dict)]: if isinstance(sample, dict): kwargs = sample args = tuple() elif isinstance(sample, tuple): kwargs = dict() args = sample else: kwargs = dict() args = (sample,) return (args, kwargs)
def run_sanity_check(cmd_args: Namespace, partitioner: PartitioningTask, analysis_config: AnalysisPipelineConfig, device='cpu', training=False, check_grads=True, ref_model=None, check_init=False): try: torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False try: ...
def make_dot(var): node_attr = dict(style='filled', shape='box', align='left', fontsize='12', ranksep='0.1', height='0.2') dot = Digraph(node_attr=node_attr, graph_attr=dict(size='12,12')) seen = set() def add_nodes(var): if (var not in seen): if isinstance(var, torch.Tensor): ...
def run(rank, size, hostname): print(f'I am {rank} of {size} in {hostname}') tensor = torch.zeros(1) if (rank == 0): tensor += 1 dist.send(tensor=tensor, dst=1) else: dist.recv(tensor=tensor, src=0) print('Rank ', rank, ' has data ', tensor[0])
def init_processes(rank, size, hostname, fn, backend='tcp'): ' Initialize the distributed environment. ' dist.init_process_group(backend, rank=rank, world_size=size) fn(rank, size, hostname)
def run(rank, size, hostname): print(f'I am {rank} of {size} in {hostname}') tensor = torch.zeros(1).cuda() if (rank == 0): tensor += 1 dist.send(tensor=tensor, dst=1) else: dist.recv(tensor=tensor, src=0) print('Rank ', rank, ' has data ', tensor[0])
def init_processes(rank, size, hostname, fn, backend='tcp'): ' Initialize the distributed environment. ' dist.init_process_group(backend, rank=rank, world_size=size) fn(rank, size, hostname)
def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if (args.n_gpu > 0): torch.cuda.manual_seed_all(args.seed)
def to_list(tensor): return tensor.detach().cpu().tolist()
def train(args, train_dataset, model, tokenizer): ' Train the model ' if (args.local_rank in [(- 1), 0]): tb_writer = SummaryWriter() args.train_batch_size = (args.per_gpu_train_batch_size * max(1, args.n_gpu)) train_sampler = (RandomSampler(train_dataset) if (args.local_rank == (- 1)) else Di...
def evaluate(args, model, tokenizer, prefix=''): (dataset, examples, features) = load_and_cache_examples(args, tokenizer, evaluate=True, output_examples=True) if ((not os.path.exists(args.output_dir)) and (args.local_rank in [(- 1), 0])): os.makedirs(args.output_dir) args.eval_batch_size = (args.p...
def load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False): if ((args.local_rank not in [(- 1), 0]) and (not evaluate)): torch.distributed.barrier() input_dir = (args.data_dir if args.data_dir else '.') cached_features_file = os.path.join(input_dir, 'cached_{}_{}_{}'.forma...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--model_type', default=None, type=str, required=True, help=('Model type selected in the list: ' + ', '.join(MODEL_TYPES))) parser.add_argument('--model_name_or_path', default=None, type=str, required=True, help='Path to pretrained model o...
class TextDataset(Dataset): def __init__(self, tokenizer: PreTrainedTokenizer, args, file_path: str, block_size=512): assert os.path.isfile(file_path) block_size = (block_size - (tokenizer.max_len - tokenizer.max_len_single_sentence)) (directory, filename) = os.path.split(file_path) ...
class LineByLineTextDataset(Dataset): def __init__(self, tokenizer: PreTrainedTokenizer, args, file_path: str, block_size=512): assert os.path.isfile(file_path) logger.info('Creating features from dataset file at %s', file_path) with open(file_path, encoding='utf-8') as f: lin...
def load_and_cache_examples(args, tokenizer, evaluate=False): file_path = (args.eval_data_file if evaluate else args.train_data_file) if args.line_by_line: return LineByLineTextDataset(tokenizer, args, file_path=file_path, block_size=args.block_size) else: return TextDataset(tokenizer, arg...