Clip a list of gradients by their combined global norm

Large-model training clips gradients so one bad batch cannot blow up the weights. The standard version measures the norm of all gradients together, as if they were one long vector, and rescales every tensor by the same factor so the update direction is unchanged.

Write clip_by_global_norm(grads, max_norm) where grads is a list of arrays of any shapes.
- total = sqrt(sum of squares of every entry of every array).
- If total > max_norm, multiply every array by max_norm / total. Otherwise leave them unchanged.
Return (clipped_list, total) where total is the norm before clipping, as a float.

Signaturedef clip_by_global_norm(grads, max_norm)

Example

grads [[3.0], [4.0]] with max_norm 1.0 gives total 5.0 and clipped [[0.6], [0.8]].

Understand the idea

Gradient clipping is a speed limit for weight updates. Global norm clipping treats every gradient tensor as part of one long vector, measures its total length, and if it is too long, shrinks all tensors by the same factor. Because every piece is scaled equally, the update keeps its direction and only its size changes. Worked example: grads [[1, 2], [2]] and max_norm 1.5. Total = sqrt(1 + 4 + 4) = 3. Since 3 > 1.5, scale = 1.5 / 3 = 0.5, giving [[0.5, 1.0], [1.0]]. The new total is exactly 1.5. If max_norm were 5, nothing would change. Rule: total = square root of the sum of squares of every entry in every tensor; if total > max_norm multiply every tensor by max_norm / total; return the clipped tensors and the original total. Clipping each tensor by its own norm is a different and wrong method here. Used in almost every LLM training run, typically with max_norm = 1.0.

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

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

  • Sample 1: exampleclip_by_global_norm([[3.0], [4.0]], 1.0)
  • Sample 2: no clipping neededclip_by_global_norm([[0.1, 0.2], [0.2]], 1.0)
  • Test 3: mixed shapesclip_by_global_norm(_gs, 1.5)
  • Test 4: clipped norm equals max_normfloat(np.sqrt(sum((g ** 2).sum() for g in clip_by_global_norm(_gs, 0.7)[0])))