224. 实现 mish 及其梯度
重要性 手写激活函数的梯度是 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)Mish against SiLU
Mish = x · tanh(softplus(x)). The dashed curve is the gradient of Mish.
- input
- 0.00
- mish
- 0
- SiLU
- 0
- slope of mish
- 0.6
示例 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)