REAL PYTORCH · CPU TRAINING AND AUTOGRAD
Partition AdamW parameters without duplicate ownership
A training policy must say which parameters receive decoupled weight decay.
Run this Lab in Pythilo
Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.
No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.
PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.
Pythilo on the App Store →Read lesson: Partition AdamW parameters without duplicate ownership →
Your task
Return two optimizer group dicts with params lists. Include each distinct trainable parameter once. In this declared policy, tensors with ndim>=2 receive decay; scalars and vectors receive zero decay. Exclude frozen parameters. Reject negative/nonfinite decay and a model with no trainable parameters. Return original Parameter objects, not detached copies. Tied weights must not enter an optimizer twice.
Starter
import torch
def adamw_groups(model, decay):
return NoneInspect the worked answer
import math
import torch
def adamw_groups(model, decay):
if not math.isfinite(decay) or decay < 0:
raise ValueError('nonnegative finite decay required')
decayed, exempt, seen = [], [], set()
for name, parameter in model.named_parameters():
if not parameter.requires_grad or id(parameter) in seen:
continue
seen.add(id(parameter))
if parameter.ndim >= 2:
decayed.append(parameter)
else:
exempt.append(parameter)
if not seen:
raise ValueError('at least one trainable parameter required')
return [{'params': decayed, 'weight_decay': decay},
{'params': exempt, 'weight_decay': 0.0}]