Skip to content

← Activations step 5 of 9

Easy Research

GELU Activation

GELU stands for Gaussian Error Linear Unit. Its exact definition is x times the standard normal cumulative distribution function at x. That multiplier lies between zero and one: positive inputs are mostly preserved when large, while large negative inputs approach zero from below.

This exercise uses the tanh approximation, not the exact normal-CDF formula. Compute the following elementwise expression, where ** means exponentiation:

0.5 * x * (1 + tanh(sqrt(2 / pi) * (x + 0.044715 * x**3)))

For x=[-1.0, 0.0, 1.0], this gives approximately [-0.158808, 0.0, 0.841192]. Unlike ReLU, GELU does not replace every negative input with zero.

Your task

Implement gelu(x) using the tanh formula above for a floating-point tensor of any shape. Return a tensor with the same shape. Use basic arithmetic and tanh rather than torch.nn.functional.gelu or jax.nn.gelu.

Compute the scalar constant sqrt(2 / pi) once in your expression. In Python, write x**3 for the cube; x^3 is a different operator.

The visualization compares GELU with ReLU. The expected values for this exercise specifically follow the tanh approximation, which differs slightly from exact GELU.

Loading visualization…