code
stringlengths
17
6.64M
class Adam(Optimizer): 'Implements Adam algorithm.\n\n It has been proposed in `Adam: A Method for Stochastic Optimization`_.\n\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): learning rate (default: 1...
class Adam(Optimizer): 'Implements Adam algorithm.\n\n It has been proposed in `Adam: A Method for Stochastic Optimization`_.\n\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): learning rate (default: 1...
class AdamW(Optimizer): 'Implements AdamW algorithm.\n\n The original Adam algorithm was proposed in `Adam: A Method for Stochastic Optimization`_.\n The AdamW variant was proposed in `Decoupled Weight Decay Regularization`_.\n\n Arguments:\n params (iterable): iterable of parameters to optimize o...
class AdamW(Optimizer): 'Implements AdamW algorithm.\n The original Adam algorithm was proposed in `Adam: A Method for Stochastic Optimization`_.\n The AdamW variant was proposed in `Decoupled Weight Decay Regularization`_.\n Arguments:\n params (iterable): iterable of parameters to optimize or di...
class AdamW(Optimizer): 'Implements AdamW algorithm.\n The original Adam algorithm was proposed in `Adam: A Method for Stochastic Optimization`_.\n The AdamW variant was proposed in `Decoupled Weight Decay Regularization`_.\n Arguments:\n params (iterable): iterable of parameters to optimize or di...
def get_multi_step_lr_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps, milestones, gamma, last_epoch=(- 1)): ' Create a schedule with a learning rate that decreases with gamma factor every milestone, after\n linearly increasing during a warmup period.\n user responsibility to assure that each mi...
class WarmupMultiStepLR(LambdaLR): ' Create a schedule with a learning rate that decreases with gamma factor every milestone, after\n linearly increasing during a warmup period.\n user responsibility to assure that each milestone is bigger than num_warmup steps.\n ' def __init__(self, optimizer, num...
class _RequiredParameter(object): 'Singleton class representing a required parameter for an Optimizer.' def __repr__(self): return '<required parameter>'
class SGD(Optimizer): 'Implements stochastic gradient descent (optionally with momentum).\n\n Nesterov momentum is based on the formula from\n `On the importance of initialization and momentum in deep learning`__.\n\n Args:\n params (iterable): iterable of parameters to optimize or dicts defining\...
class SGD(Optimizer): 'Implements stochastic gradient descent (optionally with momentum).\n\n With Momentum Correction\n See https://arxiv.org/pdf/1706.02677.pdf\n\n Nesterov momentum is based on the formula from\n `On the importance of initialization and momentum in deep learning`__.\n\n Args:...
def linear_lr_scaling(bs_train, BASE_LR, BASE_BS_TRAIN, downscale=False): if (bs_train < BASE_BS_TRAIN): if (not downscale): return BASE_LR else: lr = (BASE_LR / (BASE_BS_TRAIN / bs_train)) else: lr = (BASE_LR * (bs_train / BASE_BS_TRAIN)) assert (lr > 0) ...
class CommPolicy(Enum): P2P = auto() BCAST = auto()
def to_policy(backend, cpu): assert (backend in {'nccl', 'gloo', 'mpi'}) if ((backend == 'mpi') or cpu): return CommPolicy.P2P raise NotImplementedError()
def get_auto_comm_handler_cls(backend, cpu): return POLICY_TO_COMM[to_policy(backend, cpu)]
def zero_grad_fn(g): return for b in g: b.detach_().zero_()
class PreProcIter(): def __init__(self, itr, preproc_fn): self.itr = itr self.preproc_fn = preproc_fn def __next__(self): x = next(self.itr) self.preproc_fn(x) return x def __iter__(self): raise NotImplementedError()
class Buffers(): def __init__(self, max_buffers, create_fn, irecv_fn, is_grad=False, prev_stream_to_use: Optional[torch.cuda.Stream]=None): self.buffers = [] self.create_fn = create_fn self.max_buffers = max_buffers self._is_initialized = False self.irecv_fn = irecv_fn ...
class BufferSimpleCommBase(SimpleCommBase): def __init__(self, *args, **kw): super().__init__(*args, **kw) def _create_recv_buffers(self, tensor_ranks, for_grads=False): with torch.no_grad(): buffers = [] for (tensor_name, ranks) in tensor_ranks: dtype...
class FuturesHandler(FuturesHandlerBase): ' This is mostly for MPI, where sent objects are problematic - currently not deleted automatically ' def __init__(self, pipe_config: PipelineConfig, my_stage_id): super().__init__() patience = pipe_config.max_send_depth_for_stage(my_stage_id) ...
def make_buff(comm_handler: BufferSimpleCommBase, is_bwd, shapes, dtypes=None, max_buffers=1, create=False, prev_stream_to_use=None): 'Create recv buffer.\n TODO: This should be moved to comm handler\n ' comm_handler.set_tensor_shapes(shapes) comm_handler.set_tensor_dtypes(dtypes) if is_bwd:...
class SimpleCommBase(CommunicationHandlerBase, ABC): ' common for all MPI based.\n TODO: some functions in the end should be moved to lower class\n ' def __init__(self, rank, local_rank, backend, world_size, num_stages, stage, receive_ranks, send_ranks, target_tensor_names, ranks_in_previous_stage, ran...
def zip_discard_compr(*iterables, sentinel=object()): return [[entry for entry in iterable if (entry is not sentinel)] for iterable in zip_longest(*iterables, fillvalue=sentinel)]
def grouper(iterable, n): 'Collect data into *non fixed-length* chunks or blocks\n (changed the one in itertools recepies)\n ' args = ([iter(iterable)] * n) return zip_discard_compr(*args)
class FuturesHandlerBase(abc.ABC): def __init__(self): pass @abc.abstractmethod def after_forward(self, sent_request_objects, done_fwds, training): pass @abc.abstractmethod def after_backward(self, sent_request_objects, done_bwds): pass @abc.abstractmethod def c...
class CommunicationHandlerBase(abc.ABC): ' Base class for all communication handlers.\n Handles communication between stages.\n ' def __init__(self): pass def init_buffers_ctx(self, buffers_ctx): pass def init_buffers(self): pass @abc.abstractmethod de...
class MultiprocessingCommunicationHandler(SimpleCommBase): def __init__(self, share, stage_to_device_map, local_rank_to_device_map, *args, **kw): kw['GRAD_UGLY_SHAMEFUL_NAME'] = '_grad' super().__init__(*args, **kw) (rcv_queues, buffer_reuse_queues) = share self.rcv_queues = rcv_q...
class FuturesHandler(FuturesHandlerBase): ' Handle sent object futures ' def __init__(self, pipe_config: PipelineConfig, my_stage_id: int): super().__init__() self.sent_object_patience = pipe_config.max_send_depth_for_stage(my_stage_id) self.last_fwd_result = [] self.last_bwd_...
class P2PCommunicationHandler(BufferSimpleCommBase): def __init__(self, *args, **kw): kw['GRAD_UGLY_SHAMEFUL_NAME'] = '_grad' super().__init__(*args, **kw) def set_tensor_dtypes(self, tensor_dtypes): if (tensor_dtypes is not self.tensor_dtypes): super().set_tensor_dtypes(...
def tensor_tags_from_config(pipe_config: PipelineConfig, num_chunks=1, target_tensor_names=None, GRAD_UGLY_SHAMEFUL_NAME='_grad'): tensor_tags = {} tensor_tag = 1 for (i, stage) in pipe_config.d['stages'].items(): input_tensors = stage['inputs'] output_tensors = stage['outputs'] re...
def None_tensor(): return torch.tensor(np.nan)
def is_None_tensor(recved_tensor): return ((recved_tensor.size() == torch.Size()) and np.isnan(recved_tensor.item()))
class TensorWrapper(): ' Hack for sending everything as tensors\n e.g:\n int -> tensor -> send -> recv -> int\n\n TODO: mapping conventions\n ' def __init__(self, comm_handler: SimpleCommBase, dtypes: Dict[(str, type)]): self.send_dtype_map = TensorWrapper.make_send_dtype_...
def get_propagator_cls(args) -> Type[PipelineDataPropagator]: propagator_cls = AVAILABLE_PROPAGATORS.get(args.data_propagator) if (propagator_cls is None): raise NotImplementedError(f'args.data_propagator={args.data_propagator}, AVAILABLE_PROPAGATORS={AVAILABLE_PROPAGATORS.keys()}') return propaga...
class AutomaticPipelinePropagator(PipelineDataPropagator): SENDING_LABELS_IN_PIPELINE = False def __init__(self, device, is_last_partition, is_first_partition, stage_id, pipe_config: PipelineConfig): super().__init__() self.device = device pcs = pipe_config.d['stages'][stage_id] ...
class AutomaticPipelinePropagatorNonContig(PipelineDataPropagator): def __init__(self, *args, **kw): super().__init__() def pack_send_context(self, model_out, *ctx): return (*model_out, *ctx)
class CVTargetInPipePropagator(PipelineDataPropagator): def __init__(self, device, is_last_partition, is_first_partition): super().__init__() self.device = device if is_last_partition: self.unpack_cls = self.unpack_data_for_last_partition elif is_first_partition: ...
class PipelineDataPropagator(abc.ABC): '\n Class describing how to handle data loaded or passed through the pipeline.\n \n Usage:\n\n # Get data:\n (1)\n from_prev_stage = (...) # get it from somewhere\n to_stage, to_somewhere_else = propagator.preload_from_dataloader(dli...
def _call_method(method, rref, *args, **kwargs): '\n a helper function to call a method on the given RRef\n ' return method(rref.local_value(), *args, **kwargs)
def _remote_method(method, rref, *args, **kwargs): '\n a helper function to run method on the owner of rref and fetch back the\n result using RPC\n ' args = ([method, rref] + list(args)) return rpc.rpc_async(rref.owner(), _call_method, args=args, kwargs=kwargs)
class Observer(): def __init__(self): self.last_calc = 0 self.is_set = False def set_params(self, parameters, max_norm, norm_type=2): self.parameters = parameters self.max_norm = max_norm self.norm_type = norm_type self.is_set = True def calc_local_partia...
class Agent(): ' Agent to perform approximation of distributed grad norm in async pipeline.\n\n Instead of synchronously waiting for grad norm result from earlier stages,\n Will use previouslly calculated grad norm results (i.e from last batch).\n\n if no there is no previous grad norm result...
def convert_to_num_gpus(module, num_gpus_to_sim): 'Converts torch.nn.BatchNorm instances to simulate DDP with the desired number of GPUs' module_output = module if isinstance(module, torch.nn.modules.batchnorm._BatchNorm): new_cls = MODULE_INSTANCES_TO_REPLACE[module.__class__.__name__] mo...
class _NormBase(Module): 'Common base of _InstanceNorm and _BatchNorm' _version = 2 __constants__ = ['track_running_stats', 'momentum', 'eps', 'weight', 'bias', 'running_mean', 'running_var', 'num_batches_tracked', 'num_features', 'affine'] def __init__(self, num_features, eps=1e-05, momentum=0.1, af...
class _BatchNorm(_NormBase): def __init__(self, num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True, num_gpus_to_sim=1): super(_BatchNorm, self).__init__(num_features, eps, momentum, affine, track_running_stats, num_gpus_to_sim) def forward(self, input): self._check_...
class BatchNorm1d(_BatchNorm): "Applies Batch Normalization over a 2D or 3D input (a mini-batch of 1D\n inputs with optional additional channel dimension) as described in the paper\n `Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`_ .\n .. math::\n y =...
class BatchNorm2d(_BatchNorm): "Applies Batch Normalization over a 4D input (a mini-batch of 2D inputs\n with additional channel dimension) as described in the paper\n `Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`_ .\n .. math::\n y = \\frac{x - \\m...
class BatchNorm3d(_BatchNorm): "Applies Batch Normalization over a 5D input (a mini-batch of 3D inputs\n with additional channel dimension) as described in the paper\n `Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`_ .\n .. math::\n y = \\frac{x - \\m...
def gap_aware_adam_init(optimizer): for pg in optimizer.param_groups: for p in pg['params']: state = optimizer.state[p] if (len(state) == 0): state['exp_avg'] = torch.zeros_like(p.data, memory_format=torch.preserve_format) state['exp_avg_sq'] = torch...
def opt_params_iter(optimizer): return chain(*[pg['params'] for pg in optimizer.param_groups])
def adam_gap1(beta1, beta2, eps, eta, gt, m, v): tmp0 = (1 - beta1) sq_tmp0 = math.sqrt(tmp0) tmp1 = (tmp0 * eps) tmp2 = (m * (eta * beta1)) nom1 = tmp2 dnom1 = (tmp1 + (torch.sqrt(v) * sq_tmp0)) e1 = (nom1 / dnom1) nom2_1 = tmp2 nom2_2 = (gt * (tmp0 * eta)) nom2 = (nom2_1 + no...
class AdamGapAware(GapAwareBase): ' Gap aware for ADAM optimizer ' def __init__(self, optimizer, from_grad=False): ' Apply Gap Aware on computed gradients ' super().__init__(optimizer) gap_aware_adam_init(optimizer) def apply_from_grad(self): ' Calculate gap aware from gr...
def get_adam_gap_aware_cls() -> Type[AdamGapAware]: gap_aware_cls = AdamGapAware return gap_aware_cls
def gap_aware_adam_init(optimizer): for pg in optimizer.param_groups: for p in pg['params']: state = optimizer.state[p] if (len(state) == 0): state['exp_avg'] = torch.zeros_like(p.data, memory_format=torch.preserve_format) state['exp_avg_sq'] = torch...
def opt_params_iter(optimizer): return chain(*[pg['params'] for pg in optimizer.param_groups])
def adam_gap1(beta1, beta2, eps, eta, gt, m, v): tmp0 = (1 - beta1) sq_tmp0 = math.sqrt(tmp0) tmp1 = (tmp0 * eps) tmp2 = (m * (eta * beta1)) nom1 = tmp2 dnom1 = (tmp1 + (torch.sqrt(v) * sq_tmp0)) e1 = (nom1 / dnom1) nom2_1 = tmp2 nom2_2 = (gt * (tmp0 * eta)) nom2 = (nom2_1 + no...
class AdamGapAware(GapAwareBase): ' Gap aware for ADAM optimizer ' def __init__(self, optimizer, from_grad=False): ' Apply Gap Aware on computed gradients ' super().__init__(optimizer) gap_aware_adam_init(optimizer) def apply_from_grad(self): ' Calculate gap aware from gr...
def get_adam_gap_aware_cls() -> Type[AdamGapAware]: gap_aware_cls = AdamGapAware return gap_aware_cls
def opt_params_iter(optimizer): return chain(*[pg['params'] for pg in optimizer.param_groups])
class AdamWGapAware(GapAwareBase): ' Gap aware for ADAMW optimizer\n ADAMW\n https://arxiv.org/pdf/1711.05101.pdf\n\n # Just adding the square of the weights to the loss function is *not*\n # the correct way of using L2 regularization/weight decay with Adam,\n # since that will interact with the m ...
def get_adamw_gap_aware_cls() -> Type[AdamWGapAware]: gap_aware_cls = AdamWGapAware return gap_aware_cls
class HookFactory(ABC): def __init__(self): self.batch_to_hooks = dict() self.current_handles = None def register_hooks(self, batch_idx): self.current_handles = [p.register_hook(hook) for (p, hook) in self.batch_to_hooks.pop(batch_idx)] def remove_current_handles(self): ...
class AdamGAHookFactory(HookFactory): def __init__(self): super().__init__() def create_apply_hooks_on_stashed(self, batch_idx, get_stashed_theta_fn): opt_state = self.optimizer.state all_hooks = [] for (pg_idx, pg) in enumerate(self.optimizer.param_groups): max_l...
class GapAwareBase(abc.ABC): '\n GAP aware implementation for pipeline,\n based on\n https://arxiv.org/abs/1909.10802\n We can apply it if one of the following happends:\n 1. we stash the parameters theta we did forwad on (so we could calculate the gap)\n 2. the gap is easy (e.g the grad...
def init_running_avg_step(optimizer): opt_params_iter = chain(*[pg['params'] for pg in optimizer.param_groups]) running_avg_step = {id(p): torch.zeros_like(p) for p in opt_params_iter} return running_avg_step
class GapAware(GapAwareBase): '\n GAP aware implementation for pipeline,\n based on\n https://arxiv.org/abs/1909.10802\n We can apply it if one of the following happends:\n 1. we stash the parameters theta we did forwad on (so we could calculate the gap)\n 2. the gap is easy (e.g the gra...
def get_sgd_gap_aware_cls(sgd_type: str) -> GapAware: gap_aware_cls = SGD_TYPE_TO_GAP_AWARE_CLASS.get(sgd_type, None) return gap_aware_cls
def convert_child_by_dict(model, dict_id_b4_to_after): if (not dict_id_b4_to_after): return for (child_name, child) in model.named_children(): if (id(child) in dict_id_b4_to_after): setattr(model, child_name, dict_id_b4_to_after[id(child)]) else: convert_child_b...
class DummyForwardMonkeyPatcher(): def __init__(self, model, classes_list_to_patch): ' List of model names to patch ' self.model = model self.classes_to_patch = classes_list_to_patch self.models = [] self.encapsulators = [] self.fmodels = [] self.state_is_d...
def test(): import torch features = 3 batch = 3 model = torch.nn.Sequential(torch.nn.Linear(features, features), torch.nn.BatchNorm1d(features)) patcher = DummyForwardMonkeyPatcher(model, classes_list_to_patch=[torch.nn.BatchNorm1d]) patcher.sync() print(model) patcher.replace_for_dumm...
def test_no_grad_and_bwd(): import torch features = 3 batch = 3 model = torch.nn.Sequential(torch.nn.Linear(features, features), torch.nn.BatchNorm1d(features)) patcher = DummyForwardMonkeyPatcher(model, classes_list_to_patch=[torch.nn.BatchNorm1d]) patcher.sync() patcher.replace_for_dummy...
def find_modules(module, module_name, module_instance, found): "\n Recursively find all instances of a specific module inside a module.\n\n Arguments:\n module {nn.Module} -- Module to search on\n module_name {str} -- Name of the model to search on in the currect context (used to output access...
def _patched_parameters(self, recurse: bool=True, time: _typing.Optional[int]=None) -> _typing.Iterable[_torch.Tensor]: 'Returns an iterator over monkey patched module fast parameters.\n\n Args:\n recurse (bool): if True, then yields fast parameters of this module\n and all submodules. Otherw...
class _MonkeyPatchBase(_abc.ABC, _torch.nn.Module): @_abc.abstractmethod def __init__(self) -> None: self._param_mapping: _typing.List[int] = [] def forward(self): raise NotImplementedError("The monkey-patching logic has failed to override self.forward on the new module, or you tried cal...
def buffer_sync(module: _torch.nn.Module, fmodule: _MonkeyPatchBase, device: _typing.Optional[_torch.device]=None) -> None: 'One off sync (copy) of buffers in ``fmodule`` with those from ``module``.\n ' for (key, value) in module._buffers.items(): if (not _torch.is_tensor(value)): fmodu...
class _ParameterPlaceholder(): def __init__(self, name: str) -> None: self._param_name = name def __repr__(self) -> str: return 'Parameter placeholder ("{}")'.format(self._param_name)
def _make_functional(module: _torch.nn.Module, params_box: _typing.Sequence[_typing.Optional[_typing.List[_torch.Tensor]]], params_offset: int) -> _typing.Tuple[(int, _MonkeyPatchBase, _typing.Type[_MonkeyPatchBase])]: if isinstance(module, _MonkeyPatchBase): raise ValueError("Monkey-patching monkey-patch...
def _update_patched_params(fmodule: _MonkeyPatchBase, params_box: _typing.Sequence[_typing.List[_torch.Tensor]], params_offset: int) -> int: num_params = len([1 for p in fmodule._parameters.values() if (p is not None)]) child_params_offset = (params_offset + num_params) for (name, child) in fmodule._modul...
def make_functional(module: _torch.nn.Module, encapsulator: _EncapsulatorType=None) -> _MonkeyPatchBase: 'Returns a stateless version of an ``nn.Module`` instance.' params_box = [None] (_, fmodule, MonkeyPatched) = _make_functional(module, params_box, 0) top_name = ('Functional' + MonkeyPatched._wrapp...
def dummy_forward_monkeypatch(module: _torch.nn.Module) -> _MonkeyPatchBase: 'Create a monkey-patched stateless version of a module.\n\n This function produces a monkey-patched version of a module, and returns a\n copy of its parameters for use as fast weights. Where the original module\n or any of its s...
def monkeypatch(module: _torch.nn.Module, device: _typing.Optional[_torch.device]=None, copy_initial_weights: bool=True) -> _MonkeyPatchBase: 'Create a monkey-patched stateless version of a module.\n\n This function produces a monkey-patched version of a module, and returns a\n copy of its parameters for us...
def _copy_tensor(t: _torch.Tensor, safe_copy: bool, device: _typing.Optional[_torch.device]=None) -> _torch.Tensor: if safe_copy: t = t.clone().detach().requires_grad_(t.requires_grad) else: t = t.detach().requires_grad_(t.requires_grad) t = (t if (device is None) else t.to(device)) re...
def _recursive_copy_and_cast(target: _typing.Union[(list, tuple, dict, set, _torch.Tensor)], device: _typing.Optional[_torch.device]) -> _torch.Tensor: def map_fn(x): if _torch.is_tensor(x): return _copy_tensor(x, True, device=device) else: return x return _recursive_m...
def _recursive_map(target: _typing.Union[(list, tuple, dict, set, _T)], map_fn: _typing.Callable[([_T], _U)]) -> _typing.Union[(list, tuple, dict, set, _U)]: if isinstance(target, list): return type(target)([_recursive_map(x, map_fn) for x in target]) elif isinstance(target, tuple): return typ...
def _is_container(target: _typing.Any) -> bool: flag = (isinstance(target, list) or isinstance(target, tuple) or isinstance(target, dict) or isinstance(target, set)) return flag
def _find_param_in_list(param: _torch.Tensor, l: _typing.Iterable[_torch.Tensor]) -> _typing.Optional[int]: for (i, p) in enumerate(l): if (p is param): return i else: return None
def _get_param_mapping(module: _torch.nn.Module, seen: _typing.List[_torch.Tensor], mapping: _typing.List[int]) -> _typing.List[int]: for param in module._parameters.values(): if (param is None): continue found = _find_param_in_list(param, seen) if (found is None): ...
def flatten(x: _typing.Any) -> _typing.List[_typing.Any]: 'Returns a flattened list of objects from a nested structure.' l: _typing.List[_typing.Any] = [] if isinstance(x, dict): for y in x.values(): l.extend(flatten(y)) elif (isinstance(x, list) or isinstance(x, set) or isinstance...
def get_func_params(module: _torch.nn.Module, device: _typing.Optional[_torch.device]=None, safe_copy: bool=True) -> _typing.List[_torch.Tensor]: 'Returns a detached copy of module parameters which requires gradient.' params = [_copy_tensor(p, safe_copy, device) for p in module.parameters()] return params...
def get_buffers_for_ddp_sync(model, classes_to_patch=DEFAULT_CLASSES_LIST_TO_PATCH): found = [] for model_to_patch in classes_to_patch: find_modules(model, '', model_to_patch, found) found = sorted(found, key=(lambda t: t[0])) buffers = [] for (access_string, model) in found: buffe...
class Partition(nn.Module): '\n Partition with recomputation.\n Should be used as Intermediate partition.\n\n saves activations.\n pop happens when we read the gradient.\n\n NOTE: there are other class for LastPartition and FirstPartition, to be used as needed.\n ' _REQ_GRAD = True _HAS_...
class FirstPartition(Partition): " The first partition does not need to record gradients of stashed inputs.\n This may save some memory.\n We don't clone inputs.\n We don't record gradients for inputs.\n " _REQ_GRAD = False _HAS_DUMMY_FORWARD = True def __init__(self, *args, *...
class LastPartition(Partition): _REQ_GRAD = True _HAS_DUMMY_FORWARD = False def __init__(self, *args, **kw): super(LastPartition, self).__init__(*args, **kw) def forward(self, x: TensorOrTensors, micro_batch_idx): if self.training: if isinstance(x, Tensor): ...
class PartitionWithoutRecomputation(nn.Module): _HAS_DUMMY_FORWARD = False _CLONE_INPUTS = True def __init__(self, layers, device, to_device=True, _REQ_GRAD=True, req_grad=None): '\n Intermediate partition which does not do recomputation.\n HACK: has misleading names to be u...
class FirstPartitionWithoutRecomputation(PartitionWithoutRecomputation): ' its Just a hack for GPIpe... ' _CLONE_INPUTS = False def __init__(self, *args, **kw): super().__init__(*args, _REQ_GRAD=False, **kw)
class GPipePartition(nn.Module): ' Do not do recomputation on the last micro batch\n we have to know if we are last micro batch at all functions.\n ' RECOMP_PARTITION_CLS = Partition NO_RECOMP_PARTITION_CLS = PartitionWithoutRecomputation _CLONE_INPUTS = True def __init__(self, *args, ...
class GPipeFirstPartition(GPipePartition): ' Do not do recomputation on the last micro batch ' RECOMP_PARTITION_CLS = FirstPartition NO_RECOMP_PARTITION_CLS = FirstPartitionWithoutRecomputation _CLONE_INPUTS = False def __init__(self, *args, **kw): super().__init__(*args, **kw)
class GPipeLastPartition(GPipePartition): ' NOTE: for doing backward_fro_recomputed,just pass (NONE) as grad_tensor ' RECOMP_PARTITION_CLS = Partition NO_RECOMP_PARTITION_CLS = LastPartition _CLONE_INPUTS = True def __init__(self, *args, **kw): super().__init__(*args, **kw) def forwa...
def filter_for_backward(x, g): x = list(filter_req_grad_tensors(x)) assert (len(x) == len(g)) tensors = [] grad_tensors = [] for (t, gt) in zip(x, g): if t.requires_grad: if (gt is not None): tensors.append(t) grad_tensors.append(gt) ...
def req_grad_dict_to_tuple(req_grad: Dict[(Any, bool)]) -> Tuple[bool]: ret = tuple((v for (i, v) in req_grad.items())) return ret
def assert_same_size(x, g): assert (len(list(x)) == len(list(g))), str((len(list(x)), len(list(g))))