Apply tanh soft-capping to logits and get its gradient

Why it matters Soft-capping attention and output logits is a training-stability trick used in some open model families such as Gemma 2.

Instead of clipping logits hard, some models squash them smoothly with tanh so they never exceed a cap but gradients still flow.

Write soft_cap(x, cap). Return (y, dy_dx) where y = cap * tanh(x / cap) and dy_dx = 1 - tanh(x / cap) ** 2, both as float arrays with the shape of x. If cap is None or 0, return (x as a float array, ones like x).

Signaturedef soft_cap(x, cap)

Example

soft_cap([0, 30, -60], 30) is y = [0, 22.8478, -28.9208] and dy_dx = [1, 0.42, 0.0707].

Understand the idea

A hard clip at 30 cuts every logit above 30 to exactly 30 and gives zero gradient there. Soft-capping bends instead of cutting: small logits pass almost unchanged, big ones approach the cap slowly, like a car's suspension absorbing a bump.

Example with cap 30: x = 0 gives 0. x = 30 gives 30 * tanh(1) = 22.85. x = -60 gives 30 * tanh(-2) = -28.92. The slopes are 1, 0.42 and 0.07: still positive, so learning continues.

Rule: y = cap * tanh(x / cap); dy/dx = 1 - tanh(x / cap)^2.

For |x| much smaller than cap, tanh(x / cap) is about x / cap, so y is about x. Gemma 2 uses soft-capping on attention logits and on the final output logits to keep them from growing without limit during training.

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

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

  • Sample 1: examplesoft_cap([0.0, 30.0, -60.0], 30.0)
  • Sample 2: small values nearly unchangedsoft_cap([0.5, -1.0, 2.0], 50.0)
  • Test 3: matrixsoft_cap([[100.0, -5.0], [0.0, 25.0]], 20.0)
  • Test 4: no capsoft_cap([3.0, -4.0], None)