Skip to content

Use erfc for numerically stable GELU - #681

Merged
polvalente merged 2 commits into
elixir-nx:mainfrom
hfiguera:gelu-tail-stability
Sep 28, 2026
Merged

polvalente merged 2 commits into
elixir-nx:mainfrom
hfiguera:gelu-tail-stability

Conversation

@hfiguera

Copy link
Copy Markdown
Contributor

The erf-based GELU formula loses precision in the negative tail through cancellation in 1 + erf(x / sqrt(2)). Multiplying by x before dividing by two can also overflow for large finite positive inputs.

Compute GELU as (x / 2) * erfc(-x / sqrt(2)). This retains small negative tails and avoids that intermediate overflow. Update the documented outputs and add regressions for f32/f64 tails, large finite inputs, vectorized inputs, and a nonlinear gradient composition.

Validation: the combined activation/EXLA expression suite passed 421 tests on each of macOS ARM64 and Linux x86_64, with 48 evaluator-only doctests excluded from the EXLA run. The EXLA vectorization regression uses the block-output fix in elixir-nx/nx#1842; the scalar GELU reformulation is independent of that fix.

@polvalente

Copy link
Copy Markdown
Member

@hfiguera could you point to Nx/EXLA/Torchx main here so we can green out the suite?

@hfiguera

Copy link
Copy Markdown
Contributor Author

@hfiguera could you point to Nx/EXLA/Torchx main here so we can green out the suite?

Sure. I will do it.

@polvalente
polvalente merged commit c0df0f2 into elixir-nx:main Sep 28, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants