A4Medium★ 核心必练 · 工业基石Part A · 基础算子与激活函数

SwiGLU 门控前馈算子(LLaMA / DeepSeek 核心)

⚡闪卡盲测➔

现代大模型最核心的 FFN 算子,由 Gate/Up 投影与 SiLU 逐元素相乘并 Down 投影降维。

⏱️ 时间复杂度: O(3 * B * S * D * D_ffn)
💾 空间复杂度: O(B * S * D_ffn)
🎯 免登录实战自测闭环(先做再看答案)
按「机制回忆 → 关键行填空 → 边界反例 → 追问与错题记录」顺序自测,进度自动保存在本地。
Step 1 · 机制口述与数值稳定性自检
Step 2 · 核心代码关键行补全
import numpy as np
def swiglu(x: np.ndarray, W_gate: np.ndarray, W_up: np.ndarray, W_down: np.ndarray) -> np.ndarray:
"""
SwiGLU Feed-Forward Network operator.
Dimensions:
x: (B, S, D)
W_gate, W_up: (D, D_ffn)
W_down: (D_ffn, D)
"""
gate =
pos = gate >= 0
sig = np.empty_like(gate)
sig[pos] = 1.0 / (1.0 + np.exp(-gate[pos]))
ez = np.exp(gate[~pos])
sig[~pos] = ez / (1.0 + ez)
silu_gate = gate * sig # SiLU(gate)
up = x @ W_up # (B, S, D_ffn)
hidden = silu_gate * up # Hadamard product
return
Step 3 · 反例与边界断言核对
Step 4 · 面试追问盲答与错题记录
Q1: 在分布式模型并行(Tensor Parallelism)中,SwiGLU 矩阵该如何切分?
下一题: Softplus 与 LeakyReLU(数值防溢出分段) →
💡

实战一句话记忆口诀

门控升维两路走,SiLU 激活哈达玛,最后降维回原形

📐 核心数学公式与机理推导

SwiGLU(x)=(SiLU(xWgate)⊙xWup)Wdown\mathrm{SwiGLU}(x) = \left(\mathrm{SiLU}(x W_{\mathrm{gate}}) \odot x W_{\mathrm{up}}\right) W_{\mathrm{down}}
### 架构演进与数学表示
Noam Shazeer 在 2020 年将 GLU 门控激活替换为 Swish/SiLU(SiLU(z)=z⋅σ(z)\mathrm{SiLU}(z) = z \cdot \sigma(z)),提出 SwiGLU。
在标准 Transformer 中,FFN 仅含两个矩阵(隐层维度 4d4d)。为了在引入第三个矩阵 WgateW_{\mathrm{gate}} 的同时保持参数总量和计算量不变,通常将中间隐藏层维度收敛至约 83d\frac{8}{3}d(如 LLaMA 中的 11008 / 14336)。

🔄 张量维度与形状流转说明

(B, S, D) -> W_gate & W_up 并行投影 -> 2x (B, S, D_ffn) -> SiLU(gate) * up -> (B, S, D_ffn) -> W_down 投影 -> (B, S, D)

🛡️ 数值稳定性自检与边界要点

  • SiLU 包含 sigmoid,在底层需要防御大负数的 exp 溢出
  • 工业实现中通常将 W_gate 和 W_up 拼接为一个矩阵 [W_gate, W_up] 执行单次 GEMM
  • D_ffn 必须是 256 或 128 的整数倍以满足硬件 Tensor Core 内存对齐

💻 完整参考代码实现

import numpy as np

def swiglu(x: np.ndarray, W_gate: np.ndarray, W_up: np.ndarray, W_down: np.ndarray) -> np.ndarray:
    """
    SwiGLU Feed-Forward Network operator.
    Dimensions:
        x: (B, S, D)
        W_gate, W_up: (D, D_ffn)
        W_down: (D_ffn, D)
    """
    gate = x @ W_gate                      # (B, S, D_ffn)
    pos = gate >= 0
    sig = np.empty_like(gate)
    sig[pos] = 1.0 / (1.0 + np.exp(-gate[pos]))
    ez = np.exp(gate[~pos])
    sig[~pos] = ez / (1.0 + ez)
    silu_gate = gate * sig                 # SiLU(gate)
    
    up = x @ W_up                          # (B, S, D_ffn)
    hidden = silu_gate * up                # Hadamard product
    return hidden @ W_down                 # (B, S, D)

🧪 本地测试与正确性断言

可直接复制到本地 Python / Jupyter 验证:

import numpy as np
B, S, D, D_ffn = 2, 4, 8, 16
x = np.random.randn(B, S, D)
Wg = np.random.randn(D, D_ffn)
Wu = np.random.randn(D, D_ffn)
Wd = np.random.randn(D_ffn, D)
res = swiglu(x, Wg, Wu, Wd)
assert res.shape == (B, S, D)
assert not np.isnan(res).any()
print("✓ SwiGLU assertion passed")

🎯 核心工程追问与标准应答

Q1:在分布式模型并行(Tensor Parallelism)中,SwiGLU 矩阵该如何切分?
W_gate 和 W_up 采用列并行(Column Parallel),计算部分通道后就地做门控相乘;W_down 采用行并行(Row Parallel),最后在 GPU 间做一次 All-Reduce 汇总。
⚡
想检验本题的肌肉记忆?进入 3 阶闪卡主动回忆盲测
隐藏答案遮罩,自测:审题锚点 ➔ 数理公式机理 ➔ 工业标杆代码与连环追问。3 分钟攻破认知盲区!
🎯 立即在闪卡中盲测此题➔
← 上一题: GELU 激活函数(Tanh 近似与精确式)返回 Part A 与全部 105 题下一题: Softplus 与 LeakyReLU(数值防溢出分段) →