Skip to content

← Activations step 9 of 9

Hard Framework

Custom Activation with Gradient

Compute the SiLU activation and its derivative at each position in a vector. SiLU, also called Swish with coefficient 1, multiplies a value by its sigmoid:

sigmoid(t) = 1 / (1 + exp(-t))
silu(t) = t * sigmoid(t)

Your task

Implement silu_with_grad(x) for a floating-point vector of shape (n,). Return a dictionary with exactly these two keys:

  • "output": the SiLU values, shape (n,).
  • "gradient": the derivative of each output with respect to its own input, also shape (n,).

Preserve x's dtype and device in both tensors and leave x unchanged. Return the dictionary itself. No custom backward class or full Jacobian is required.

At x=0, sigmoid is 0.5, so the output is 0 and the derivative is 0.5. For checking other values, write s=sigmoid(x); the elementwise derivative is s + x*s*(1-s).

Differentiate a scalar total

Build the activation from multiplication and sigmoid. To use automatic differentiation, sum the activation values and differentiate that scalar total with respect to x. Each output depends only on the input at the same position, so this gradient contains the individual derivatives. That shortcut does not give the Jacobian of a function whose outputs mix input positions.

In PyTorch, enable gradient tracking on a copy of x and use torch.autograd.grad(output.sum(), x_copy). In JAX, use jax.grad on a function that returns jnp.sum(x * jax.nn.sigmoid(x)). Return the unsummed activation values under "output"; the sum is only used for differentiation. An empty input returns two empty vectors.