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 None
Inspect 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}]

About this algorithm

How Partition AdamW parameters without duplicate ownership works

The idea

AdamW shrinks weights toward zero a little on every step, separately from the gradient. That is weight decay, and it does not suit every parameter. The usual policy, and the one this Lab declares, is to decay tensors with two or more dimensions (weight matrices, embeddings) and to exempt scalars and vectors (biases, normalization scales).

An optimizer accepts a list of groups, each with its own weight_decay, so the job is a clean partition. Every trainable parameter must appear in exactly one group. Frozen parameters appear in none. A tied weight, one Parameter object reachable under two names, must still be listed once, which is why adamw_groups records id(parameter) in seen.

How it works

  1. Reject a decay that is negative or not finite.
  2. Walk model.named_parameters() in order.
  3. Skip a parameter when requires_grad is False or its id is already in seen.
  4. Append tensors with ndim >= 2 to decayed and scalars and vectors to exempt.
  5. Raise ValueError if no trainable parameter was found.
  6. Return two dicts holding the original Parameter objects: one with weight_decay set to decay, one with 0.0.

What it costs

Passes
one over the tensors
Memory
O(k) references
Scales with
tensor count k

The function looks at each parameter tensor once and stores only references, so its cost depends on how many tensors the model has, not on how large they are.

Where it is used

  • Karpathy's nanoGPT builds its AdamW groups with this exact rule: parameters with two or more dimensions decay, the rest do not.
  • Hugging Face Transformers' Trainer leaves bias and LayerNorm weights out of weight decay when it creates its optimizer.
  • The timm image model library skips weight decay for one-dimensional parameters and biases when it builds optimizer groups.

Watch out for

  • Listing a tied weight in both groups: PyTorch raises an error because one parameter appears in more than one group.
  • Passing detached copies or clones: the optimizer then updates the copies and the model never changes.
  • Leaving a trainable parameter out of every group: nothing fails, it just silently never trains.