Add L1 and L2 penalties and their gradients to weight matrices only

Why it matters Weight decay configs in real training scripts always exclude biases and normalisation parameters.

Regularisation is usually applied to weights but not to biases. A clean helper makes that rule explicit.

Write regularize(params, l1, l2). params is a dict from a name to an array. Only names ending with ".weight" are penalised. Return (penalty, grads) where penalty = sum over weights of l1 * sum(|w|) + 0.5 * l2 * sum(w^2) as a float, and grads is a dict with the same keys: l1 * sign(w) + l2 * w for weights (sign(0) = 0) and zeros of the same shape for every other key.

Signaturedef regularize(params, l1, l2)

Example

params = {"fc.weight": [1, -2], "fc.bias": [3]}, l1 = 0.1, l2 = 0.5 gives penalty 1.55 and grads {"fc.weight": [0.6, -1.1], "fc.bias": [0]}.

Understand the idea

Penalties pull weights toward zero so the model does not lean too hard on any single feature. L1 pulls with a constant force, so small weights get pushed all the way to 0. L2 pulls in proportion to the weight, so big weights shrink fast and small ones barely move. Biases only shift outputs, so penalising them does not reduce overfitting.

Tiny example: w = [1, -2], l1 = 0.1, l2 = 0.5. L1 part 0.1 * 3 = 0.3. L2 part 0.5 * 0.5 * 5 = 1.25. Total 1.55. Gradient: 0.1 * [1, -1] + 0.5 * [1, -2] = [0.6, -1.1].

Rules: penalty = l1 * sum|w| + 0.5 * l2 * sum w^2, grad = l1 * sign(w) + l2 * w.

Training recipes for ResNets and transformers apply weight decay to weight matrices only, using exactly this kind of name filter.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleregularize({'fc.weight': [1.0, -2.0], 'fc.bias': [3.0]}, 0.1, 0.5)
  • Sample 2: zero weightregularize({'a.weight': [[0.0, 2.0], [-1.0, 0.0]], 'a.bias': [1.0, 1.0], 'norm.scale': [5.0]}, 0.2, 0.0)
  • Test 3: l2 onlyregularize({'x.weight': [0.5, -0.5, 3.0]}, 0.0, 0.1)