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

223. 返回 SiLU 及其用于 backward pass 的精确导数

MediumActivations

SiLU (也称为 swish) 是 silu(x) = x * sigmoid(x)。它是 SwiGLU feed-forward 模块中的门控。当你编写自定义 backward pass 时需要它的导数,而乘法法则很容易只写对一半。

为数组 x 编写 silu_and_grad(x)。返回一个包含两个数组的元组 (y, dy),其 shape 与 x 相同:
- y = x * sigmoid(x)
- dy = 每个元素的 d silu / dx

以一种在输入为 -800 或 800 时不会产生 overflow 警告或 nan 的方式计算 sigmoid。

函数def silu_and_grad(x)
Play with it

SiLU and its derivative

SiLU = x · σ(x). Its slope, dashed, goes slightly above 1 and below 0, unlike ReLU's step.

0246-6-4-20246x
input
0.00
SiLU
0
slope of SiLU
0.5
SiLUslope

示例 1

at x = 0, y = 0 and dy = 0.5.

示例 2

输入: x = [-2.0, -0.5, 0.5, 2.0]

输出: ([-0.238406, -0.18877, 0.31123, 1.761594], [-0.090784, 0.260039, 0.739961, 1.090784])

示例 3

输入: x = [-800.0, 800.0]

输出: ([-0.0, 800.0], [-0.0, 1.0])

约束条件

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

令 s = sigmoid(x)。

提示 2

根据乘法法则 dy = s + x * s * (1 - s),这可以简化为 s * (1 + x * (1 - s))。

常见错误
  • 有 bug 的版本仅返回 sigmoid(x),这把 x 当作了常数。
理解思路

SiLU 将输入与其自身的 sigmoid 相乘:silu(x) = x * s(x),其中 s 是 sigmoid。因为它是一个依赖于 x 的两个项的乘积,所以乘法法则会产生两项,漏掉其中一项是常见的 bug。

Worked example

x = 2. s(2) = 0.8808, so silu = 1.7616. 导数是 s + x * s * (1 - s) = 0.8808 + 2 * 0.8808 * 0.1192 = 0.8808 + 0.2100 = 1.0908. 当 x = 0 时, s = 0.5, 得到 y = 0 且 dy = 0.5.

dy/dx = s(x) * (1 + x * (1 - s(x))). 为了获得稳定的 sigmoid,当 x >= 0 时计算 1 / (1 + exp(-x)),当 x < 0 时计算 exp(x) / (1 + exp(x)),这样在输入为 800 或 -800 时,exp 永远不会遇到很大的正参数。SiLU 是大多数现代 LLM 的 SwiGLU feed-forward 层中的门控激活函数。
主题
Activations
相似题目
  • 编写永不溢出的 sigmoid 和 log-sigmoidMedium
  • 实现 mish 及其梯度Medium
  • 实现 GPT 和 BERT 中的激活函数 GELUEasy
  • 在输入值较大时计算不溢出的 softplusEasy
所有 Activations 道题目
反馈
223 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def silu_and_grad(x):
# your code here
pass
​

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

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