def train(seed, schedule, num_steps, max_norm=1.0, alpha=0.995):
"""AdamW with betas (0.9, 0.95) and weight decay 0.1 on the matrices at
the rate schedule(t), clipped at max_norm, with an EMA of the weights;
return the losses, the model, the EMA and the fraction of clipped steps."""
model = tiny_lm(seed)
matrices = [p for name, p in model.named_parameters()
if p.ndim == 2 and 'emb' not in name]
others = [p for name, p in model.named_parameters()
if p.ndim != 2 or 'emb' in name]
adamw = torch.optim.AdamW([{'params': matrices, 'weight_decay': 0.1},
{'params': others, 'weight_decay': 0.0}],
lr=1.0, betas=(0.9, 0.95)) # Times schedule
scheduler = torch.optim.lr_scheduler.LambdaLR(adamw, schedule)
ema = torch.optim.swa_utils.AveragedModel(
model, multi_avg_fn=torch.optim.swa_utils.get_ema_multi_avg_fn(alpha))
adamw.register_step_post_hook(lambda *_: scheduler.step())
adamw.register_step_post_hook(lambda *_: ema.update_parameters(model))
optimizer = Clipped(adamw, model.parameters(), max_norm)
losses = d2l.train_steps(model, data, optimizer, num_steps)
clip_rate = (torch.stack(optimizer.norms) > max_norm).float().mean()
return losses, model, ema, float(clip_rate)