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

224. 实现 mish 及其梯度

MediumActivations

重要性 手写激活函数的梯度是 fused-kernel 作者在开发每个新激活函数时都会做的事情。

Mish 是 x * tanh(softplus(x))。手写其梯度是练习链式法则的好方法。

编写 mish(x)。返回 (y, dy),其中 y = x * tanh(sp), sp = log(1 + exp(x)), 且 dy = tanh(sp) + x * (1 - tanh(sp)^2) * sigmoid(x)。使用 np.logaddexp(0, x) 稳定地计算 softplus。

函数def mish(x)
Play with it

Mish against SiLU

Mish = x · tanh(softplus(x)). The dashed curve is the gradient of Mish.

024-4-2024x
input
0.00
mish
0
SiLU
0
slope of mish
0.6
mishSiLUslope

示例 1

输入: mish([0])

输出: y [0] and dy [tanh(log 2)] = [0.6]

示例 2

输入: x = [-2, -0.5, 1, 3]

输出: ([-0.252501, -0.220744, 0.865098, 2.986535], [-0.108355, 0.289511, 1.049036, 1.021107])

约束条件

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

softplus 的导数是 sigmoid。

提示 2

对 x * tanh(softplus(x)) 使用乘法法则。

提示 3

d tanh(u) = 1 - tanh(u)^2。

提示 4

d softplus(x) = sigmoid(x)。

常见错误
  • 漏掉了 sigmoid 因子。
  • 直接计算 log(1 + exp(x)),这会导致溢出。
理解思路

Mish 是一种平滑的激活函数:y = x * tanh(softplus(x)),其中 softplus(x) = log(1 + e^x)。为了得到其导数,你需要对 x 乘以 t 使用乘法法则,并在 t 内部使用链式法则。Worked example at x = 1: softplus = log(1 + 2.718) = 1.3133, t = tanh(1.3133) = 0.8651, so y = 0.8651. sigmoid(1) = 0.7311 and 1 - t^2 = 0.2516, so dy = 0.8651 + 1 * 0.2516 * 0.7311 = 0.8651 + 0.1839 = about 1.049.

sp = softplus(x), t = tanh(sp), y = x * t, dy = t + x * (1 - t^2) * sigmoid(x). sigmoid 来自于 softplus 的导数;忘记它是一个经典的错误。使用 logaddexp(0, x) 稳定地计算 softplus,以防止较大的 x 导致溢出。应用场景:YOLOv4 风格的检测器和其他 CNN,以及作为通过有限差分检查手写梯度的良好实践案例。
Shape 与数据流
x -> softplus -> tanh -> times x
dy = t + x * (1 - t^2) * sigmoid(x)
主题
Activations
相似题目
  • 编写永不溢出的 sigmoid 和 log-sigmoidMedium
  • 返回 SiLU 及其用于 backward pass 的精确导数Medium
  • 实现 GPT 和 BERT 中的激活函数 GELUEasy
  • 在输入值较大时计算不溢出的 softplusEasy
所有 Activations 道题目
反馈
224 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def mish(x):
# your code here
pass
​

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

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