BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Activations1 of 13 in topic

215. 实现 GPT 和 BERT 中的激活函数 GELU

EasyActivations

ReLU 通过硬转折点将负数截断为零。而用于 GPT-2、BERT 和大多数 transformer 中的 GELU 则采用平滑弯曲的方式。GPT-2 使用一种快速的 tanh 近似:

gelu(x) = 0.5 x (1 + tanh(sqrt(2 / pi) (x + 0.044715 x ** 3)))

请为任意形状的 NumPy 数组编写 gelu(x),并返回相同形状的数组。

函数def gelu(x)
Play with it

GELU against ReLU

GELU (tanh form) bends smoothly through 0 and dips slightly below 0 for small negative inputs. ReLU cuts off hard.

024-4-2024x
input
0.00
GELU (tanh)
0
ReLU
0
slope of GELU (tanh)
0.5
GELU (tanh)ReLU

示例 1

输入: x = [-3.0, -1.0, 0.0, 0.5, 2.0]

输出: [-0.003637, -0.158808, 0.0, 0.345714, 1.954598]

示例 2

输入: x = [[1.0, -2.0], [3.0, 0.1]]

输出: [[0.841192, -0.045402], [2.996363, 0.053983]]

示例 3

输入: x = [10.0]

输出: [10.0]

约束条件

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 3 tests to be accepted.
提示 1

直接使用 np.tanh 和 np.sqrt(2 / np.pi) 翻译公式即可。

提示 2

所有操作都是 elementwise 的。

常见错误
  • 三次项很重要;错误的实现版本使用了平方而不是立方。
理解思路

GELU 是一种平滑的激活函数。ReLU 通过尖锐的转折点将每个负输入截断为零;而 GELU 则让输入根据标准正态分布值低于该输入的概率成比例地通过,因此小的负值会轻微泄漏。GPT-2 使用了它的快速 tanh 近似。

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. 对于 x = -1,结果约为 -0.159,很小但不是零。较大的正 x 结果几乎等于 x,较大的负 x 结果几乎等于 0。

gelu(x) = 0.5 x (1 + tanh(sqrt(2 / pi) (x + 0.044715 x^3))), 按元素应用以保持形状。注意该项是 x 的三次方,而不是平方。GPT-2、BERT 和许多 transformer MLP 层都使用 GELU。
主题
Activations
相似题目
  • 在输入值较大时计算不溢出的 softplusEasy
  • 实现 ELU 及其导数Easy
  • 实现 hard swishEasy
  • 计算 dead ReLU 单元的比例Easy
所有 Activations 道题目
反馈
215 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def gelu(x):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 3 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS