Merged
新增situglu和situglugrad算子 #8651
guijianweiAdd on Aug 13
新增situglu和situglugrad算子 #8651
Merged
guijianweiAdd on Aug 13
guijianwei
guijianweiCollaborators
Aug 13

描述

situ系列算子为SiTU(Scalable Interpolated Tanh Units)相关的融合算子族。新增两个situ激活正反向算子及其torch_extension接口,各算子功能如下:

1. situ_glu

SiTU门控线性单元(SiTU Gated Linear Unit)激活函数。对输入张量 x 沿指定维度 dim 切分为门控(gate)与上路径(up)两半,按SiTU公式计算输出。

将 x 基于 dim 进行合轴,合轴后维度为 [pre, cut],cut 必须为偶数,令 h = cut // 2。根据 activate_left 切分:

  • activate_left=True:gate = x[..., :h],up = x[..., h:]
  • activate_left=False:gate = x[..., h:],up = x[..., :h]

SiTU计算:

situ_a=β⋅tanh⁡(gateβ)⋅σ(gate)situ\_a = \beta \cdot \tanh\left(\frac{gate}{\beta}\right) \cdot \sigma(gate)

当 linear_beta > 0 时:

up=linear_beta⋅tanh⁡(uplinear_beta)up = linear\_beta \cdot \tanh\left(\frac{up}{linear\_beta}\right)

输出:

y=situ_a⋅upy = situ\_a \cdot up

输出 y 的 dim 轴大小为 x 的一半,其他维度与 x 相同。

2. situ_glu_grad

situ_glu 的反向梯度算子。给定前向输出梯度 grad_y 与前向输入 x,按SiTU门控线性单元公式对 x 求导,返回输入梯度 grad_x。

记前向中间量:

tg=tanh⁡(gateβ),sg=σ(gate),situ_a=β⋅tg⋅sgt_g = \tanh\left(\frac{gate}{\beta}\right), \quad s_g = \sigma(gate), \quad situ\_a = \beta \cdot t_g \cdot s_g

当 linear_beta > 0 时:up′=linear_beta⋅tanh⁡(up/linear_beta)up' = linear\_beta \cdot \tanh(up / linear\_beta),否则 up′=upup' = up。

乘积法则:

grad_situ_a=grad_y⋅up′,grad_up′=grad_y⋅situ_agrad\_situ\_a = grad\_y \cdot up', \quad grad\_up' = grad\_y \cdot situ\_a

gate梯度:

grad_gate=grad_situ_a⋅sg⋅[(1−tg2)+β⋅tg⋅(1−sg)]grad\_gate = grad\_situ\_a \cdot s_g \cdot \left[(1 - t_g^2) + \beta \cdot t_g \cdot (1 - s_g)\right]

up梯度:

  • linear_beta > 0 时:grad_up=grad_up′⋅(1−tanh⁡2(up/linear_beta))grad\_up = grad\_up' \cdot (1 - \tanh^2(up / linear\_beta))
  • linear_beta ≤ 0 时:grad_up=grad_up′grad\_up = grad\_up'

按 activate_left 拼接 grad_gate、grad_up 为 grad_x(shape与 x 一致)。

关联的Issue

Issue #4749

测试

1、泛化测试
正向泛化功能测试OK
反向泛化功能测试OK
2、torch接口测试
正向torch接口功能测试OK
反向orch接口功能测试OK
3、示例代码测试
示例代码验证通过

文档更新

类型标签

AI/Agent生成声明

likedislike
Pull Request has been successfully merged by CANN-robot.
(Thank you for guijianwei's contribution.)
guijianweiguijianweiCollaborators
Aug 13 Created pull request, commit ea843feb
atomgit-bot
atomgit-bot
Aug 13 Comments:

🤖 正在生成合并请求摘要,请稍候…

likedislike
Incorrect?
atomgit-bot
atomgit-bot
Aug 13 Comments:

🤖 AI 代码检视正在进行中,请稍候…

likedislike
Incorrect?
CANN-robotCANN-robotCollaborators
Aug 13 Added label: stat/needs-squash
CANN-robotCANN-robotCollaborators
Aug 13 Added label: cann-cla/yes
305 messages are collapsed here。 See more
zhajianqing123
zhajianqing123Collaborators
Aug 17 Comments:

/lgtm
/approve

likedislike
CANN-robotCANN-robotCollaborators
Aug 17 Added label: approved
CANN-robotCANN-robotCollaborators
Aug 17 Closed associated issue
CANN-robotCANN-robotCollaborators
Aug 17 Merged pull request
CANN-robot
CANN-robotCollaborators
Aug 17 Comments:

Pull Request 已合并或已关闭。

If you want to solve this problem, you can click here to do it in the FAQs.

likedislike