Implement GELU, the activation inside GPT and BERT
ReLU cuts negatives to zero with a hard corner. GELU, used in GPT-2, BERT and most transformers, bends smoothly instead. GPT-2 uses a fast tanh approximation:
gelu(x) = 0.5 x (1 + tanh(sqrt(2 / pi) (x + 0.044715 x ** 3)))
Write gelu(x) for a NumPy array of any shape and return an array of the same shape.
def gelu(x)Understand the idea
GELU is a smooth activation. ReLU cuts every negative input to zero with a sharp corner; GELU instead lets inputs pass in proportion to how likely a standard normal value is to be below them, so small negatives leak through slightly. GPT-2 uses a fast tanh approximation of it. Worked example: x = 1. Inner = sqrt(2/pi) x (1 + 0.044715 x 1^3) = 0.7979 x 1.044715 = 0.8336. tanh(0.8336) = 0.6823. gelu(1) = 0.5 x 1 x (1 + 0.6823) = 0.841. For x = -1 the result is about -0.159, small but not zero. Large positive x gives almost x, large negative x gives almost 0. Rule: gelu(x) = 0.5 x (1 + tanh(sqrt(2 / pi) (x + 0.044715 x^3))), applied element by element so the shape is kept. Note the term is x cubed, not squared. GPT-2, BERT and many transformer MLP layers use GELU.