Forward and backward pass for GLU, ReGLU, SwiGLU and GEGLU gates

Gated linear units run two projections of the same input and use one, passed through an activation, to gate the other. Variants differ only in the activation: sigmoid (GLU), ReLU (ReGLU), SiLU (SwiGLU) and GELU (GEGLU). Writing one backward pass that handles all of them is a good test of the chain rule.

Write glu_forward_backward(x, W, V, g, kind):
- x is (n, d), W and V are (d, h), g is the upstream gradient dL/dout of shape (n, h).
- a = x @ W, b = x @ V, out = act(a) * b.
- kind is one of "glu" (sigmoid), "reglu" (relu, with derivative 0 at a = 0), "swiglu" (silu(a) = a * sigmoid(a)), "geglu" (tanh approximation: 0.5 * a * (1 + tanh(sqrt(2 / pi) * (a + 0.044715 * a ** 3)))).

Return a dict with keys "out" (n, h), "dx" (n, d), "dW" (d, h), "dV" (d, h).

Signaturedef glu_forward_backward(x, W, V, g, kind)

Example

with kind "reglu", any column where a < 0 gives out 0 there, and no gradient flows into W or V through that entry.

Understand the idea

A gated linear unit makes two projections of the same input, a = xW and b = xV, and outputs act(a) * b,. In the backward pass the product splits the upstream gradient g into two branches, and since x feeds both, its gradient is the sum of both paths. Worked example with scalars, ReGLU: x = 1, W = 2, V = 3, g = 1. a = 2, b = 3, out = relu(2) * 3 = 6. da = g * b * relu'(a) = 3, db = g * act(a) = 2. dW = x * da = 3, dV = x * db = 2, dx = da * W + db * V = 6 + 6 = 12. Rule in matrix form: da = g * b * act'(a), db = g * act(a), dW = x^T da, dV = x^T db, dx = da W^T + db V^T. Only act' changes per variant: sigmoid s(1 - s), relu step (0 at a = 0), silu s + a s (1 - s), and the derivative of the tanh GELU formula. SwiGLU and GEGLU power LLaMA-style feed-forward layers.

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

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: gluglu_forward_backward(_x, _W, _V, _g, 'glu')
  • Sample 2: regluglu_forward_backward(_x, _W, _V, _g, 'reglu')