Return SiLU and its exact derivative for the backward pass

SiLU (also called swish) is silu(x) = x * sigmoid(x). It is the gate inside SwiGLU feed-forward blocks. When you write a custom backward pass you need its derivative, and the product rule is easy to get half right.

Write silu_and_grad(x) for an array x. Return a tuple (y, dy) of two arrays with the same shape as x:
- y = x * sigmoid(x)
- dy = d silu / dx at each element

Compute sigmoid in a way that gives no overflow warnings or nan for inputs like -800 or 800.

Signaturedef silu_and_grad(x)

Example

at x = 0, y = 0 and dy = 0.5.

Understand the idea

SiLU multiplies the input by its own sigmoid: silu(x) = x * s(x), where s is the sigmoid. Because it is a product of two things that both depend on x, the product rule gives two terms, and forgetting one is the usual bug. Worked example: x = 2. s(2) = 0.8808, so silu = 1.7616. The derivative is s + x * s * (1 - s) = 0.8808 + 2 * 0.8808 * 0.1192 = 0.8808 + 0.2100 = 1.0908. At x = 0, s = 0.5, giving y = 0 and dy = 0.5. Rule: dy/dx = s(x) * (1 + x * (1 - s(x))). For a stable sigmoid, compute 1 / (1 + exp(-x)) when x >= 0 and exp(x) / (1 + exp(x)) when x < 0, so exp never sees a large positive argument at inputs like 800 or -800. SiLU is the gate activation inside the SwiGLU feed-forward layers of most modern LLMs.

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

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

  • Sample 1: zerosilu_and_grad([0.0])
  • Sample 2: small valuessilu_and_grad([-2.0, -0.5, 0.5, 2.0])
  • Test 3: random 3x4silu_and_grad(_x)
  • Test 4: extremes stay finitesilu_and_grad([-800.0, 800.0])