Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

馃悰 fix: numerical stability of tanh for GELU #83

Merged
merged 9 commits into from
Apr 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ All notable changes to this project will be documented in this file.

## [unreleased]

馃悰 **fix**: numerical stability of tanh for GELU ([#83](https://github.com/owkin/GrAIdient/pull/83))\
馃敤 **layer_seq**: SelectSeq ([#82](https://github.com/owkin/GrAIdient/pull/82))\
馃殌 **examples**: AutoEncoder models ([#79](https://github.com/owkin/GrAIdient/pull/79))\
馃獪 **layer_2d**: VQ2D ([#81](https://github.com/owkin/GrAIdient/pull/81))\
Expand Down
28 changes: 23 additions & 5 deletions Sources/GrAIdient/Core/Function/Activation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -832,8 +832,17 @@ public class GELU: ActivationFunction
public override func apply(_ x: Double) -> Double
{
let cst = sqrt(2.0 / Double.pi)
let tmp = tanh(cst * (x + 0.044715 * pow(x, 3)))
return 0.5 * x * (1 + tmp)
let tmp1 = cst * (x + 0.044715 * pow(x, 3))
let tmp2: Double
if tmp1 >= 0
{
tmp2 = (1.0 - exp(-2.0 * tmp1)) / (1.0 + exp(-2.0 * tmp1))
}
else
{
tmp2 = (exp(2.0 * tmp1) - 1.0) / (exp(2.0 * tmp1) + 1.0)
}
return 0.5 * x * (1 + tmp2)
}

///
Expand All @@ -845,9 +854,18 @@ public class GELU: ActivationFunction
public override func derivate(_ x: Double) -> Double
{
let cst = sqrt(2.0 / Double.pi)
let tmp1 = tanh(cst * (x + 0.044715 * pow(x, 3)))
let tmp2 = cst * (1 + 3 * 0.044715 * x * x) * (1 - tmp1 * tmp1)
let derivative = 0.5 * (1 + tmp1 + x * tmp2)
let tmp1 = cst * (x + 0.044715 * pow(x, 3))
let tmp2: Double
if tmp1 >= 0
{
tmp2 = (1.0 - exp(-2.0 * tmp1)) / (1.0 + exp(-2.0 * tmp1))
}
else
{
tmp2 = (exp(2.0 * tmp1) - 1.0) / (exp(2.0 * tmp1) + 1.0)
}
let tmp3 = cst * (1 + 3 * 0.044715 * x * x) * (1 - tmp2 * tmp2)
let derivative = 0.5 * (1 + tmp2 + x * tmp3)
return derivative
}
}
Expand Down
3 changes: 1 addition & 2 deletions Sources/GrAIdient/Metal/Kernel/Activation.metal
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,8 @@ kernel void forwardGELU(
{
tmp2 = (exp(2.0 * tmp1) - 1.0) / (exp(2.0 * tmp1) + 1.0);
}
float tmp = tanh(cst * (x + 0.044715 * pow(x, 3)));
tmps[id] = x;
outs[id] = 0.5 * x * (1 + tmp);
outs[id] = 0.5 * x * (1 + tmp2);
}

kernel void backwardGELU(
Expand Down