Skip to content
This repository was archived by the owner on Jul 1, 2023. It is now read-only.

Add support for gelu #268

Merged
merged 2 commits into from
Jun 21, 2019
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
18 changes: 18 additions & 0 deletions Sources/TensorFlow/Operators/Math.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1051,6 +1051,24 @@ func _vjpRelu<T: TensorFlowFloatingPoint>(
(relu(x), { v in Tensor(x .> 0) * v })
}

/// Returns the Gaussian Error Linear Unit (GELU) activations of the specified tensor element-wise.
///
/// Specifically, `gelu` approximates `xP(X <= x)`, where `P(X <= x)` is the Standard Gaussian
/// cumulative distribution, by computing: x * [0.5 * (1 + tanh[√(2/π) * (x + 0.044715 * x^3)])].
///
/// See [Gaussian Error Linear Units](https://arxiv.org/abs/1606.08415).
@inlinable
@differentiable
public func gelu<T: TensorFlowFloatingPoint>(_ x: Tensor<T>) -> Tensor<T> {
let ratio = Tensor<T>(0.7978845608) // An approximation of √(2/π).
// An approximation of the Gauss error function.
// NOTE: This is needed because the compiler otherwise gives an "unable to type-check this
// in reasonable time" error when the below expressions are written on a single line.
let approximateErf = tanh(ratio * (x + 0.044715 * pow(x, 3)))
let cdf = 0.5 * (1.0 + approximateErf)
return x * cdf
}

//===------------------------------------------------------------------------------------------===//
// Element-wise Binary Math Functions
//===------------------------------------------------------------------------------------------===//
Expand Down
8 changes: 8 additions & 0 deletions Tests/TensorFlowTests/OperatorTests/MathTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,13 @@ final class MathOperatorTests: XCTestCase {
XCTAssertEqual(y, expected)
}

func testGelu() {
let x = Tensor<Float>([2.0, 1.0, 7.0])
let y = gelu(x)
let expected = Tensor<Float>([1.95459769, 0.84119199, 7.0])
XCTAssertEqual(y, expected)
}

func testLeakyRelu() {
let x = Tensor<Float>([[-1.0, 2.0, 3.0]])
let y = leakyRelu(x, alpha: 0.4)
Expand Down Expand Up @@ -318,6 +325,7 @@ final class MathOperatorTests: XCTestCase {
("testReduction", testReduction),
("testCosineSimilarity", testCosineSimilarity),
("testElu",testElu),
("testGelu", testGelu),
("testArgmax", testArgmax),
("testSoftplus", testSoftplus),
("testSoftsign", testSoftsign),
Expand Down