code stringlengths 17 6.64M |
|---|
def get_dcr(x, req_grad):
assert_same_size(x, req_grad)
res = []
for (t, r) in zip(x, req_grad):
if isinstance(t, Tensor):
assert isinstance(r, bool)
res.append(t.detach().clone().requires_grad_(r))
else:
assert (r is False)
res.append(t)
... |
def get_dr(x, req_grad):
try:
assert_same_size(x, req_grad)
except Exception as e:
print(x)
print(req_grad)
raise e
res = []
for (t, r) in zip(x, req_grad):
if isinstance(t, Tensor):
assert isinstance(r, bool)
res.append(t.detach().requir... |
def get_r(x, req_grad):
assert_same_size(x, req_grad)
res = []
for (t, r) in zip(x, req_grad):
if isinstance(t, Tensor):
assert isinstance(r, bool)
res.append(t.requires_grad_(r))
else:
assert (r is False)
res.append(t)
return res
|
class SinglePartitionManager():
def __init__(self, stage: int, stage_depth: int, pipeline_depth: int, num_stages, partition: torch.nn.Module, comm_handler: CommunicationHandlerBase, work_scheduler: WorkScheduler, device, is_last_partition, is_first_partition, log_frequency=100, step_every=1, use_recomputation=Tr... |
class GPipePartitionManager(SinglePartitionManager):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.saved_for_backward = dict()
def _init_partition(self, partition, use_recomputation, disable_input_clone, req_grad):
TO_DEVICE = False
is_last_partition = s... |
def set_inplace_false_(m):
' return True if replaced '
if (hasattr(m, 'inplace') and m.inplace):
m.inplace = False
return True
return False
|
def replace_inplace_for_a_given_layer_(model, layer_name='l_0'):
' return True if replaced. '
if hasattr(model, layer_name):
return set_inplace_false_(getattr(model, layer_name))
return False
|
def replace_inplace_for_first_innermost_layer_(model):
'\n model: torch.nn.Module.\n\n return True if replaced\n '
(first_innermost_layer, name) = get_innnermost_first_layer_and_name(model, '')
if (not name):
assert (first_innermost_layer is model)
return set_inplace_false_(first_inne... |
def get_innnermost_first_layer_and_name(partition, name=''):
" \n Args:\n partition: a torch.nn.Module\n name: is the name for the partition in the calling context\n\n Returns:\n the innermost layer and its name\n\n Example:\n >>> import torch\n >>> m = torch.nn.Transfo... |
def get_outermost_last_layer_and_name(partition, name=''):
" \n Args:\n partition: a torch.nn.Module\n name: is the name for the partition in the calling context\n\n Returns:\n the outermost layer and its name \n outermost: defined last.\n\n Example:\n >>> import torch\... |
class PartitionRngStasher():
"\n Utility class to stash and restore RNG state.\n Used during recomputation.\n\n Pop happens when we restore the state (therefore can only restore state once).\n\n # NOTE: \n # (1) it will be problematic when 2 recomputing stages are use the same device. (e.g tied G... |
def register_trainer(name, trainer_cls: Type[PipelineSupportedTrainerType]):
'Registers trainer with mixins.'
AVAILABLE_TRAINERS[name] = trainer_cls
AVAILABLE_TRAINERS[(name + '_local_grad_norm')] = local_grad_norm_mixin_trainer_factory(trainer_cls=trainer_cls)
AVAILABLE_TRAINERS[(name + '_global_grad... |
def get_trainer_cls(args) -> Type[PipelineSupportedTrainerType]:
trainer_cls = AVAILABLE_TRAINERS.get(args.trainer['type'])
assert (trainer_cls is not None)
return trainer_cls
|
def SQUAD_loss(logits, start_positions, end_positions):
(start_logits, end_logits) = logits.split(1, dim=(- 1))
start_logits = start_logits.squeeze((- 1))
end_logits = end_logits.squeeze((- 1))
ignored_index = start_logits.size(1)
start_positions.clamp_(0, ignored_index)
end_positions.clamp_(0... |
def to_list(tensor):
return tensor.detach().cpu().tolist()
|
class SquadTrainer(ScheduledOptimizationStepMultiPartitionTrainer):
PER_STEP_SCHEDULER = True
def __init__(self, model: Module, optimizer: Optimizer, scheduler, statistics: SquadStats, step_every=1):
super().__init__(model, optimizer, scheduler, statistics)
self.step_every = step_every
... |
class CEPTrainer(ScheduledOptimizationStepMultiPartitionTrainer):
PER_STEP_SCHEDULER = False
def __init__(self, model: Module, optimizer: Optimizer, scheduler, statistics: Stats, step_every=1):
super().__init__(model, optimizer, scheduler, statistics)
self.loss_fn = torch.nn.BCEWithLogitsLoss... |
class CVTrainer(ScheduledOptimizationStepMultiPartitionTrainer):
PER_STEP_SCHEDULER = False
def __init__(self, model: Module, optimizer: Optimizer, scheduler, statistics: Stats, step_every=1):
super(CVTrainer, self).__init__(model, optimizer, scheduler, statistics)
self.step_every = step_ever... |
class CVTrainerPerStep(CVTrainer):
PER_STEP_SCHEDULER = True
|
class GapAwareTrainerMixin():
HAS_GAP_AWARE = True
def __init__(self, gap_aware: GapAwareBase, scheduler=None):
self.gap_aware = gap_aware
if (scheduler is not None):
gap_aware.patch_scheduler(scheduler)
def apply_gap_aware(self, real_theta=None, delay=None, stashed_theta=Non... |
def gap_aware_trainer_factory(trainer_cls: Type[PipelineSupportedTrainerWithoutGapAware]):
class GapAwareCreatedTrainer(trainer_cls, GapAwareTrainerMixin):
def __init__(self, gap_aware, scheduler=None, **kw):
trainer_cls.__init__(self, scheduler=scheduler, **kw)
GapAwareTrainerMi... |
class GlueTrainer(ScheduledOptimizationStepMultiPartitionTrainer):
PER_STEP_SCHEDULER = True
def __init__(self, model: Module, optimizer: Optimizer, scheduler, statistics: Stats, step_every=1):
super().__init__(model, optimizer, scheduler, statistics)
self.features = None
self.num_lab... |
def global_grad_norm_mixin_trainer_factory(trainer_cls: Type[ScheduledOptimizationStepMultiPartitionTrainer]):
class GradNormMixedTrainer(trainer_cls):
def __init__(self, *args, max_grad_norm=None, always_calc_grad_norm=False, **kw):
super().__init__(*args, **kw)
self.always_calc... |
def local_grad_norm_mixin_trainer_factory(trainer_cls: Type[ScheduledOptimizationStepMultiPartitionTrainer]):
class GradNormMixedTrainer(trainer_cls):
def __init__(self, *args, max_grad_norm=None, always_calc_grad_norm=False, **kw):
super().__init__(*args, **kw)
self.always_calc_... |
def local_grad_norm_prop_mixin_trainer_factory(trainer_cls: Type[ScheduledOptimizationStepMultiPartitionTrainer]):
class GradNormMixedTrainer(trainer_cls):
def __init__(self, *args, max_grad_norm=None, always_calc_grad_norm=False, **kw):
super().__init__(*args, **kw)
self.always_... |
class LastPartitionTrainer(abc.ABC):
@abc.abstractmethod
def backprop_last_partition(self, *args, **kw):
pass
@abc.abstractmethod
def last_partition_step_and_statistics(self, *args, **kw):
pass
@abc.abstractmethod
def step_on_computed_grads(self, **kw):
pass
@ab... |
class DataAndLabelsLastPartitionTrainer(LastPartitionTrainer):
'Adding x,y to represents (data,labels).'
@abc.abstractmethod
def backprop_last_partition(self, x, y, *args, **kw):
pass
@abc.abstractmethod
def last_partition_step_and_statistics(self, x, y, *args, **kw):
'\n ... |
class MultiPartitionTrainer(LastPartitionTrainer):
def __init__(self, optimizer: Optimizer, statistics: Stats):
self.optimizer = optimizer
self.statistics = statistics
@abc.abstractmethod
def non_last_partition_step(self, *args, **kw):
pass
|
class ScheduledOptimizationStepMultiPartitionTrainer(MultiPartitionTrainer):
PER_STEP_SCHEDULER = False
def __init__(self, model, optimizer, scheduler, statistics: Stats):
super().__init__(optimizer, statistics)
self.model = model
self.scheduler = scheduler
def non_last_partition... |
class LMTrainer(ScheduledOptimizationStepMultiPartitionTrainer):
PER_STEP_SCHEDULER = True
def __init__(self, model: Module, optimizer: Optimizer, scheduler, statistics: Stats, step_every=1):
super().__init__(model, optimizer, scheduler, statistics)
self.step_every = step_every
def calc_... |
def register_statistics(name: str, stats_cls: Type[Stats]):
AVAILBALE_STATS[name] = stats_cls
AVAILBALE_STATS[(name + '_loss_per_batch')] = stats_cls
|
def get_statistics(name: str, *args, **kw) -> Stats:
record_loss_per_batch = ('loss_per_batch' in name)
st_cls = AVAILBALE_STATS.get(name)
return st_cls(*args, record_loss_per_batch=record_loss_per_batch, **kw)
|
class CVStats(Stats):
' Class to handle statistics collection for CV '
def __init__(self, record_loss_per_batch=False, is_last_partition=True):
super().__init__(is_last_partition=is_last_partition)
self.add_statistic(name='loss', meter=AverageMeter(), per_batch=record_loss_per_batch, per_epoc... |
class NormCVstats(CVStats):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.add_statistic(name='grad_norm', meter=AverageMeter(), per_batch=True, per_epoch=False, train=True, test=False)
self.add_statistic(name='local_grad_norm', meter=AverageMeter(), per_batch=True, p... |
class CVDistanceNorm(NormCVstats):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.add_statistic(name='gap', meter=AverageMeter(), per_batch=False, per_epoch=True, train=True, test=False)
self.register_pipeline_per_stage_statistic('gap')
|
class CVDistance(CVStats):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.add_statistic(name='gap', meter=AverageMeter(), per_batch=self.record_loss_per_batch, per_epoch=(not self.record_loss_per_batch), train=True, test=False)
self.register_pipeline_per_stage_statist... |
def try_record_real_gap_from_current(statistics: Stats, optimizer: Optimizer, real_theta, pre_computed_gap=None, gap_name='gap'):
' calculates gap between model parameters and a given set of parameters, real_theta\n real_theta: Given set of parameters. TODO: rename\n '
if statistics.has_statistic(ga... |
def glue_compute_metrics_name(task_name):
if (task_name == 'cola'):
return 'mcc'
elif (task_name == 'sst-2'):
return 'acc'
elif (task_name == 'mrpc'):
return 'acc_and_f1'
elif (task_name == 'sts-b'):
return 'corr'
elif (task_name == 'qqp'):
return 'acc_and_f... |
class GlueStats(Stats):
' Class to handle statistics collection for Glue Tasks '
def __init__(self, record_loss_per_batch=False, is_last_partition=True):
super().__init__(is_last_partition=is_last_partition)
self.add_statistic(name='loss', meter=AverageMeter(), per_batch=record_loss_per_batch... |
class NormGluestats(GlueStats):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.add_statistic(name='grad_norm', meter=AverageMeter(), per_batch=self.record_loss_per_batch, per_epoch=(not self.record_loss_per_batch), train=True, test=False)
self.register_pipeline_per_st... |
class GlueDistanceNorm(NormGluestats):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.add_statistic(name='gap', meter=AverageMeter(), per_batch=self.record_loss_per_batch, per_epoch=(not self.record_loss_per_batch), train=True, test=False)
self.register_pipeline_per_s... |
class GlueDistance(GlueStats):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.add_statistic(name='gap', meter=AverageMeter(), per_batch=self.record_loss_per_batch, per_epoch=(not self.record_loss_per_batch), train=True, test=False)
self.register_pipeline_per_stage_sta... |
class Stats(abc.ABC):
' Class to handle statistics collection '
FIT_RESULTS_CLASS = SimpleNamespace
def __init__(self, is_last_partition=True):
self.training = True
self.fit_res = self.FIT_RESULTS_CLASS(num_epochs=0)
assert (not (self.fit_res is None))
self.stats_config = ... |
def _fit_res_to_dict(fit_res) -> Dict:
if isinstance(fit_res, NamedTuple):
fit_res = fit_res._asdict()
elif isinstance(fit_res, SimpleNamespace):
fit_res = fit_res.__dict__
return fit_res
|
class PPLMeter(AverageMeter):
' Update like loss, get_avg() gets the PPL '
def get_avg(self):
avg_loss = (self.sum / self.count)
return math.exp(avg_loss)
|
class LMStats(Stats):
' Class to handle statistics collection for LM '
def __init__(self, record_loss_per_batch=False, is_last_partition=True):
super().__init__(is_last_partition=is_last_partition)
self.add_statistic(name='loss', meter=AverageMeter(), per_batch=record_loss_per_batch, per_epoc... |
class NormLMstats(LMStats):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.add_statistic(name='grad_norm', meter=AverageMeter(), per_batch=self.record_loss_per_batch, per_epoch=(not self.record_loss_per_batch), train=True, test=False)
self.register_pipeline_per_stage_... |
class LMDistanceNorm(NormLMstats):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.add_statistic(name='gap', meter=AverageMeter(), per_batch=self.record_loss_per_batch, per_epoch=(not self.record_loss_per_batch), train=True, test=False)
self.register_pipeline_per_stage... |
class LMDistance(LMStats):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.add_statistic(name='gap', meter=AverageMeter(), per_batch=self.record_loss_per_batch, per_epoch=(not self.record_loss_per_batch), train=True, test=False)
self.register_pipeline_per_stage_statist... |
class SquadStats(Stats):
' Class to handle statistics collection for Squad '
def __init__(self, record_loss_per_batch=False, is_last_partition=True):
super().__init__(is_last_partition=is_last_partition)
self.add_statistic(name='loss', meter=AverageMeter(), per_batch=record_loss_per_batch, pe... |
class NormSquadstats(SquadStats):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.add_statistic(name='grad_norm', meter=AverageMeter(), per_batch=self.record_loss_per_batch, per_epoch=(not self.record_loss_per_batch), train=True, test=False)
self.register_pipeline_per_... |
class SquadDistanceNorm(NormSquadstats):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.add_statistic(name='gap', meter=AverageMeter(), per_batch=self.record_loss_per_batch, per_epoch=(not self.record_loss_per_batch), train=True, test=False)
self.register_pipeline_per... |
class SquadDistance(SquadStats):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.add_statistic(name='gap', meter=AverageMeter(), per_batch=self.record_loss_per_batch, per_epoch=(not self.record_loss_per_batch), train=True, test=False)
self.register_pipeline_per_stage_s... |
class AverageMeter(object):
'Computes and stores the average and current value'
def __init__(self):
self.reset()
def reset(self):
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.sum += (val * n)
self.count += n
def get_a... |
class AccuracyMeter(AverageMeter):
def __init__(self):
super().__init__()
def update(self, val, n=1):
' just to supoort adding num correct instead of accuracy '
self.sum += val
self.count += n
def get_avg(self):
return ((self.sum / self.count) * 100)
|
class T5Trainer(ScheduledOptimizationStepMultiPartitionTrainer):
PER_STEP_SCHEDULER = True
def __init__(self, model: Module, optimizer: Optimizer, scheduler, statistics: Stats, step_every=1, loss_multiplier=1):
super().__init__(model, optimizer, scheduler, statistics)
self.step_every = step_e... |
def calc_local_total_norm(parameters, norm_type=2):
' Exactly like clip_grad_norm_, but without the clip.\n # See https://github.com/pytorch/pytorch/blob/master/torch/nn/utils/clip_grad.py\n '
if isinstance(parameters, torch.Tensor):
parameters = [parameters]
parameters = list(filter((l... |
def calc_local_total_norm_wo_sqrt(parameters, norm_type=2):
' Exactly like clip_grad_norm_, but without the clip.\n # See https://github.com/pytorch/pytorch/blob/master/torch/nn/utils/clip_grad.py\n '
if isinstance(parameters, torch.Tensor):
parameters = [parameters]
parameters = list(f... |
class TrueWeightsStorage():
'\n NOTE: in case of multiple restores, we take a "copy on write" approach.\n Frist restore: no clone -> copy pointers.\n Second restore: clone the true weights ("pop" the previous ones-to the model)\n This is handled by `self.restored_true_weights_to_the_model`... |
def get_world_size(backend) -> int:
'Returns world size (from env), or 1 if not set'
if (backend != 'mpi'):
return int(os.environ.get('WORLD_SIZE', 1))
else:
return int(os.environ.get('OMPI_COMM_WORLD_SIZE', 1))
|
def get_global_rank(backend) -> int:
'Returns global rank (from env), or 0 if not set'
if (backend != 'mpi'):
return int(os.environ.get('RANK', 0))
else:
return int(os.environ.get('OMPI_COMM_WORLD_RANK', 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
return CommPolicy.BCAST
|
def nested_map(func, ts, full=False):
if isinstance(ts, torch.Size):
return func(ts)
elif isinstance(ts, (list, tuple, set)):
return type(ts)((nested_map(func, t, full=full) for t in ts))
elif isinstance(ts, dict):
return {k: nested_map(func, v, full=full) for (k, v) in ts.items()}... |
def flatten(x: Any) -> List[Any]:
'Returns a flattened list of objects from a nested structure.'
l: List[Any] = []
if isinstance(x, torch.Size):
l.append(x)
elif isinstance(x, dict):
for y in x.values():
l.extend(flatten(y))
elif (isinstance(x, list) or isinstance(x, se... |
def unflatten(xs, structure):
res = _unflatten(xs, structure)[0]
f_xs = list(flatten(xs))
f_res = list(flatten(res))
assert (len(f_xs) == len(f_res))
return res
|
def _unflatten(xs, structure):
if isinstance(structure, torch.Size):
return (xs[0], 1)
elif isinstance(structure, (list, tuple, set)):
offset = 0
elements = []
for s in structure:
(e, n) = _unflatten(xs[offset:], s)
elements.append(e)
offset ... |
def detach_tensors(ts):
def detach_if_tensor(t):
if isinstance(t, Tensor):
return t.detach().requires_grad_(t.requires_grad)
return t
return nested_map(detach_if_tensor, ts)
|
def move_tensors(ts, device):
def move(t):
if isinstance(t, (nn.Module, Tensor)):
return t.to(device)
return t
return nested_map(move, ts)
|
def print_tensors(stage, x, in_or_out='out'):
if isinstance(x, torch.Tensor):
pass
else:
t = []
for (i, v) in enumerate(x):
if (not isinstance(v, torch.Tensor)):
t.append(('non-tensor' + str(v)))
else:
t.append(v.shape)
pr... |
def get_weight_predictor(optimizer_type, pred_mem, pred_type, optimizer, scheduler, nag_with_predictor, true_weights_storage, sched_predictor):
if ('sgd' in optimizer_type):
weight_predictor = get_sgd_weight_predictor(optimizer_type, pred_mem, pred_type, optimizer, scheduler=sched_predictor, nag_with_pred... |
def get_adafactor_weight_predictor(pred_mem: str, pred_type: str, optimizer, scheduler=None, nag_with_predictor=False, true_weights_storage=None) -> WeightPredictor:
has_weight_decay = any([(pg['weight_decay'] != 0) for pg in optimizer.param_groups])
if has_weight_decay:
pass
if (pred_type == 'msn... |
def adafactor_init(optimizer):
for pg in optimizer.param_groups:
for p in pg['params']:
state = optimizer.state[p]
grad = p
grad_shape = grad.shape
(factored, use_first_moment) = optimizer._get_options(pg, grad_shape)
if (len(state) == 0):
... |
class AdaFactorWClonedWeightPredictionForAggregation(WeightPredictor):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
from optimizers.adafactor import Adafactor
self.optimizer: Adafactor
adafactor_init(self.optimizer)
def forward(self):
if (not self.n_... |
def get_adam_weight_predictor(pred_mem: str, pred_type: str, optimizer, scheduler=None, nag_with_predictor=False, true_weights_storage=None) -> WeightPredictor:
has_weight_decay = any([(pg['weight_decay'] != 0) for pg in optimizer.param_groups])
if has_weight_decay:
if (pred_type == 'msnag'):
... |
def 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.zeros_lik... |
class AdamClonedWeightPrediction(WeightPredictor):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
adam_init(self.optimizer)
def forward(self):
if (not self.n_steps):
return
self.true_weights_storage.create_cloned_if_needed()
self.true_weigh... |
class AdamClonedWeightPredictionWithWD(WeightPredictor):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
adam_init(self.optimizer)
def forward(self):
if (not self.n_steps):
return
self.true_weights_storage.create_cloned_if_needed()
self.true... |
class AdamClonedWeightPredictionForAggregationWithWD(WeightPredictor):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
adam_init(self.optimizer)
def forward(self):
if (not self.n_steps):
return
self.true_weights_storage.create_cloned_if_needed()
... |
def get_adamw_weight_predictor(pred_mem: str, pred_type: str, optimizer, scheduler=None, nag_with_predictor=False, true_weights_storage=None) -> WeightPredictor:
has_weight_decay = any([(pg['weight_decay'] != 0) for pg in optimizer.param_groups])
if has_weight_decay:
if (pred_type == 'msnag'):
... |
class AdamWClonedWeightPrediction(WeightPredictor):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
adam_init(self.optimizer)
def forward(self):
if (not self.n_steps):
return
self.true_weights_storage.create_cloned_if_needed()
self.true_weig... |
class AdamWClonedWeightPredictionForAggregation(WeightPredictor):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
adam_init(self.optimizer)
def forward(self):
if (not self.n_steps):
return
self.true_weights_storage.create_cloned_if_needed()
... |
class CowDict(MutableMapping):
def __init__(self, base: dict):
self.base = base
self.dict = {}
self.deleted_keys = set()
def __getitem__(self, key):
if (key in self.deleted_keys):
raise KeyError(key)
try:
return self.dict[key]
except Ke... |
class WeightPredictor(abc.ABC):
def __init__(self, optimizer, fix_fn=None, scheduler=None, nag_with_predictor=False, true_weights_storage=None):
self.optimizer = optimizer
self.fix_fn = fix_fn
self.scheduler = scheduler
self.nag_with_predictor = nag_with_predictor
if nag_w... |
class FixFunction(abc.ABC):
@abc.abstractmethod
def __call__(self, p: WeightPredictor, pg):
raise NotImplementedError()
|
def get_sched_predictor(optimizer, sched_creator_cls, **kw):
' Get sched predictor from optimizer and scheduler class and kwargs '
n_param_groups = len(optimizer.param_groups)
lrs = [pg['lr'] for pg in optimizer.param_groups]
d = {'lrs': lrs, 'sched_creator_cls': sched_creator_cls, 'n_param_groups': n... |
def dummy_optimizer(lrs, n_param_groups=1):
' Dummy optimizer with dummy model '
assert (len(lrs) == n_param_groups)
model = nn.Linear(1, 1, bias=False)
optimizer = optim.SGD(model.parameters(), lrs[0])
for i in range(1, n_param_groups):
model = nn.Linear(1, 1, bias=False)
optimize... |
class SchedulerPredictor():
def __init__(self, lrs, sched_creator_cls, *args, n_param_groups=0, **kw):
optimizer = dummy_optimizer(lrs=lrs, n_param_groups=n_param_groups)
scheduler = sched_creator_cls(optimizer, *args, **kw)
optimizer.step()
self.scheduler = scheduler
self... |
class SGDRevertableLinearWeightPrediction(WeightPredictor):
def __init__(self, *args, **kw):
raise NotImplementedError('SGDRevertableLinearWeightPrediction not yet supported for pipeline')
super().__init__(*args, **kw)
def forward(self):
if (not self.n_steps):
return
... |
class SGDClonedWeightPrediction(WeightPredictor):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
for pg in self.optimizer.param_groups:
for p in pg['params']:
self.optimizer.state[p]['momentum_buffer'] = torch.zeros_like(p)
def forward(self):
... |
class SGD2MSNAG(FixFunction):
' \n SGD version mention in Sutskever et al, also used in tensorflow.\n Mentioned as eq 10 Goyal et al.\n Fixed with MSNAG\n '
def __call__(self, p: WeightPredictor, pg):
gamma = pg['momentum']
if (p.n_steps == 1):
return gamma
re... |
class SGD1MSNAG(SGD2MSNAG):
' Pytorch SGD. Mentioned as eq 9 Goyal et al. '
def __call__(self, p: WeightPredictor, pg):
return (pg['lr'] * super().__call__(p, pg))
|
def get_sgd_weight_predictor(sgd_type: str, pred_mem: str, pred_type: str, optimizer, scheduler=None, nag_with_predictor=False, true_weights_storage=None) -> WeightPredictor:
has_weight_decay = any([(pg['weight_decay'] != 0) for pg in optimizer.param_groups])
if has_weight_decay:
if (pred_type == 'msn... |
class SGDWDClonedWeightPrediction(WeightPredictor):
' Pytorch SGD. Mentioned as eq 9 Goyal et al.\n Used msnag to predict, including weight decay.\n '
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
for pg in self.optimizer.param_groups:
for p in pg['para... |
def lambdify_dict(coeff):
' Lambidfy the given expression, returns a dict describing result '
free_symbols_list = sorted(coeff.free_symbols, key=str)
f = lambdify(free_symbols_list, coeff, modules=['math'])
free_symbols_names = sorted(map(str, free_symbols_list))
generated_dict = dict(f=f, free_sy... |
def auto_lambdify_delay_1(optimizer_class, simplify=False, allow_no_coeff=False):
(_, preds, gaps) = run_sim(1, optimizer_class, simplify=simplify)
gap = gaps[0]
pred = preds[0]
fs_gap = list(gap.free_symbols)
fs_pred = list(pred.free_symbols)
f = lambdify(fs_gap, gap, modules=['math'])
di... |
def auto_lambdify(max_staleness, optimizer_class, simplify=False, allow_no_coeff=False):
' Auto generating functions for coefficients\n\n Example:\n Calculate the coefficnt of v.\n (Assuming "v" is in optimizer_class.collect_order)\n\n res, gap_res = auto_lambdify(...)\n\n # given s... |
def calc_gap(theta_true, theta_pred, simplify=True):
gap = (theta_true - theta_pred)
if simplify:
gap = gap.simplify()
return gap
|
def tplus_time(s, time):
if (time == 0):
return Symbol((str(s) + '_{t}'))
return Symbol((((str(s) + '_{t+') + f'{time}') + '}'))
|
class SympyPredictingOptimizer(ABC):
@abstractmethod
def step(self):
pass
@abstractmethod
def prediction(self, nsteps):
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.