Concepts / The L2 Norm and Vector Length

The L2 Norm and Vector Length

The source specifies the L2 norm, which is also called the Euclidean norm.

  • Programming

Why One Batch Can Push Parameters Too Far

Training a large language model is a long sequence of small corrections. On each step, a batch of training text produces a loss, backpropagation works out a gradient for every parameter, and the parameters move a little in the direction the gradient indicates. Most of the time these movements are reasonable in size. But now and then a batch can produce a gradient that is far larger than usual, and if that gradient is applied at full size, one step can push the parameters somewhere they should never have gone.

What do you think happens?

You want the model to keep learning from every batch, but no single update should be allowed to dominate. How would you limit the size of an update without throwing the batch away?

Reveal answer
Answer:

Keep the gradient's direction but shrink its size so that its length is capped at a fixed threshold.

Rejecting an unusually large gradient would waste the batch entirely. Clipping instead keeps the direction the gradient points and reduces how big it is, so the batch still contributes to learning with a bounded influence. Doing this requires a single number that measures how big the gradient is, which is the norm.

Where Clipping Sits in a Training Step

Follow one gradient through a standard training loop. The loss for a batch is calculated, and backpropagation then computes the gradients. Those gradients are what would normally be used to update the parameters. Clipping is applied to the gradients after backpropagation has produced them and before they are used for the update. That placement is why clipping acts directly on the updates that backpropagation generates: it is a check on the gradients, not on the data or the loss.

python
Notes on the code
  • loss.backward() computes the gradients for the parameters
  • clip_grad_norm_ limits the gradient norm to at most 1.0 before the update
  • optimizer.step() applies the (possibly clipped) gradients to the parameters

Measuring Size With the L2 Norm

To decide whether a gradient is too large, we need a single number that describes its size. In gradient clipping, that number is the norm of the gradient. The norm measures the length, or magnitude, of the gradient vector within the model's parameter space. The source specifies the L2 norm, which is also called the Euclidean norm. It is computed in three steps: square each entry, sum the squares, and take the square root of the total.

Formula

Geometrically, the sum of squares is the same calculation that gives the length of an arrow drawn from the origin to a point. In two dimensions, for a point with coordinates 3 and 4, the squares add to 9 + 16 = 25 and the square root gives a length of 5. The L2 norm extends that same idea to a gradient with any number of entries.

Gradient entries3, 0, 0, 4Square each entry9, 0, 0, 16Sum the squares25Take the square root5L2 norm5squareaddrootresult
What sequence of operations turns each gradient element into a single length value, and what does each step produce? This example uses the entries 3, 0, 0, and 4.

Deciding Whether to Clip

Clipping is a short sequence of decisions. First, compute the L2 norm of the gradient. Second, compare that norm to max_norm. If the norm does not exceed max_norm, nothing changes and the gradient is used as it is. If the norm does exceed max_norm, a scaling factor is computed as max_norm divided by the norm, and every entry of the gradient is multiplied by that factor. Because the factor is applied to the whole gradient, the new norm comes out exactly equal to max_norm.

Rule

Compute L2 normnorm of gradient GNorm greater thanmax_norm?compareLeave gradientunchangedno changeCompute factormax_norm divided by normMultiply every entryby factordirection keptNew norm equalsmax_normexactly max_normNoYes
What happens next when the computed norm is compared to max_norm: is the gradient left alone, or is it rescaled, and by what factor?

Tracing a Clipping Decision by Hand

The source works through a gradient matrix G whose L2 norm is 5. With a max_norm of 1, that norm exceeds the threshold, so clipping is required. The source does not list the entries, so the worked example below uses a small matrix with the same norm of 5 so that every step can be checked.

Worked example

Clipping a 2 by 2 gradient with max_norm 1

Let G be the matrix with rows [3, 0] and [0, 4]. Find its L2 norm, decide whether it must be clipped at max_norm = 1, and find the clipped matrix G' and its norm.

  1. 1
    Square each entry

    The squares are 9, 0, 0, and 16.

  2. 2
    Sum the squares

    9 + 0 + 0 + 16 = 25.

  3. 3
    Take the square root

    The L2 norm is the square root of 25, which is 5.

  4. 4
    Compare to max_norm

    5 is greater than 1, so the gradient must be clipped.

  5. 5
    Compute the scaling factor

    The factor is max_norm divided by the norm: 1 divided by 5, which equals 0.2.

  6. 6
    Multiply every entry

    Each entry is multiplied by 0.2. The 3 becomes 0.6, the 4 becomes 0.8, and the zeros stay zero. The result is G' with rows [0.6, 0] and [0, 0.8].

  7. 7
    Check the new norm

    The squares are 0.36 and 0.64, which sum to 1. The square root of 1 is 1, exactly max_norm.

Result

The norm of G was 5 and must be clipped. The scaling factor is 0.2, and the clipped matrix G' has norm exactly 1.

Entries3, 0, 0, 4Entries0.6, 0, 0, 0.8Norm5Norm1multiply by 0.2set to max_norm
How do the components and the overall length of the gradient change after clipping, and what stays the same? The entries shrink by the factor 0.2 and the norm drops from 5 to 1; the zero entries and the pattern of the matrix stay the same.

Notice what clipping does not do. It does not throw the gradient away, and it does not change which way the gradient points. Every entry is scaled by the same factor, so the ratio between entries is preserved. The batch still contributes to learning, but its influence on the parameters is bounded by max_norm.

Setting max_norm in PyTorch

In PyTorch, gradient clipping is available through the clip_grad_norm_ function. Setting max_norm=1.0 in that function ensures that the norm of the gradients does not surpass 1.0. The source describes this as the practical way to enforce the threshold you just worked through by hand, so the arithmetic in the previous section is exactly what the function performs on the model's gradients. The example call above shows where it belongs: after backpropagation has filled in the gradients, and before the optimizer uses them.

Best practice

Place the clipping call between the backward pass and the optimizer step. Clipping a gradient that has not been computed yet has no effect, and clipping after the update has already been applied would not limit that update.

Mistakes Beginners Make with the Norm

  • Common mistake

    Stopping after the sum of squares

    What it looks like

    For the entries 3, 0, 0, 4, the sum of squares is 25, and it is tempting to compare 25 directly to max_norm = 1.

    Why it fails

    The norm is the square root of the sum of squares. Skipping the final step compares the wrong quantity to the threshold.

    Do this instead

    Take the square root: the norm is 5, which is the value compared to max_norm.

  • Common mistake

    Inverting the scaling factor

    What it looks like

    Using norm divided by max_norm, which gives 5 / 1 = 5 for the matrix above.

    Why it fails

    A factor of 5 would enlarge the gradient instead of shrinking it, and the new norm would be 25, not max_norm.

    Do this instead

    The factor is max_norm divided by the norm, which is 1 / 5 = 0.2.

  • Common mistake

    Scaling only the entries that are large

    What it looks like

    Multiplying only the 4 in the matrix by 0.2 and leaving the 3 unchanged.

    Why it fails

    The factor applies to the whole gradient. Changing only some entries alters the direction and does not give a norm of exactly max_norm.

    Do this instead

    Multiply every entry by the same factor, so the zeros stay zero and the rest shrink together.

  • Common mistake

    Thinking clipping discards the batch

    What it looks like

    Believing that an oversized gradient should be set to zero so the batch has no effect.

    Why it fails

    The source says clipping keeps the gradient's direction and reduces its size, so the batch still contributes to learning.

    Do this instead

    Rescale the gradient so its norm equals max_norm, keeping its direction.

Clipping a Gradient on Your Own

EASY

A gradient vector is [6, 8] and max_norm is 5. Compute the L2 norm, decide whether clipping is needed, and find the clipped gradient and its norm.

Hints
  • Square each entry, add the squares, then take the square root.
  • Clipping is needed only when the norm is greater than max_norm.
  • The scaling factor is max_norm divided by the norm, and every entry is multiplied by that factor.

Reviewing the Clipping Procedure

  1. 1
    Gradient clipping limits the size of gradients that exceed a set threshold, keeping parameter updates in a manageable range during LLM training.
  2. 2
    The L2 norm, also called the Euclidean norm, is computed by squaring each entry, summing the squares, and taking the square root; the same procedure works for matrices.
  3. 3
    If the norm exceeds max_norm, the gradient is multiplied by max_norm divided by the norm, so its norm becomes exactly max_norm while its direction is kept.
  4. 4
    PyTorch's clip_grad_norm_ function with max_norm=1.0 ensures the gradient norm does not surpass 1.0.

Key Takeaways

  • Gradient clipping bounds the size of an unusually large gradient so that one batch cannot push the parameters too far.
  • The L2 norm is found by squaring each entry, summing the squares, and taking the square root.
  • When the norm exceeds max_norm, every entry is multiplied by max_norm divided by the norm, which makes the new norm exactly max_norm.
  • PyTorch's clip_grad_norm_ with max_norm=1.0 enforces this threshold on the gradients after backpropagation and before the update.

Related concepts

More concepts starting with T