GELU: A Soft Gate Instead of a Hard Cut

Activation FunctionsMedium+20 XP+15

GELU: A Soft Gate Instead of a Hard Cut

ReLU makes a hard decision at zero: keep the input, or discard it entirely. GELU makes a soft one, weighting each input by roughly how likely it is to be positive — which turns out to work better in transformers, where it's now the default.

The standard tanh approximation:

1GELU(x) = 0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x³)))

Task: write gelu(values) applying this element-wise, rounded to 4 decimal places.

  • Use this exact approximation, not the exact erf-based definition — they differ in the fourth decimal.

Look at what happens around −1: the output is slightly negative, then rises back toward zero. GELU isn't monotonic, and that small dip is the part ReLU can't reproduce — a mildly negative input isn't simply deleted, it's given a small negative weight.

Examples

values = [-2.0, -1.0, 0.0, 1.0, 2.0]
returns [-0.0454, -0.1588, 0.0, 0.8412, 1.9546]
values = [0.5]
returns [0.3457]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run