C3MediumPart C · 位置编码演进
ALiBi 线性偏置注意力(斜率衰减与外推)
无需位置向量嵌入,直接在 Query-Key 点积上添加静态线性距离惩罚偏置,外推能力极强。
⏱️ 时间复杂度:
O(S^2) 一次性构建偏置网格💾 空间复杂度:
O(H * S^2) 注意力矩阵偏置🎯 免登录实战自测闭环(先做再看答案)
按「机制回忆 → 关键行填空 → 边界反例 → 追问与错题记录」顺序自测,进度自动保存在本地。
Step 1 · 机制口述与数值稳定性自检
Step 2 · 核心代码关键行补全
import numpy as np
def get_alibi_slopes(num_heads: int) -> np.ndarray:
"""生成每个头的几何衰减斜率 m"""
def get_slopes_power_of_2(n):
start =
ratio = start
return [start * (ratio ** i) for i in range(n)]
if np.log2(num_heads).is_integer():
return np.array(get_slopes_power_of_2(num_heads))
else:
# 非 2 的幂次向下寻找最近的幂
closest_power = 2 ** int(np.log2(num_heads))
slopes = get_slopes_power_of_2(closest_power)
# 补齐多出的头
extra_slopes = get_slopes_power_of_2(2 * closest_power)[0::2][:num_heads - closest_power]
return np.array(slopes + extra_slopes)
def build_alibi_bias(seq_len: int, num_heads: int) -> np.ndarray:
"""
构建 ALiBi 偏置矩阵。
返回形状: (1, num_heads, seq_len, seq_len)
"""
slopes = get_alibi_slopes(num_heads) # (H,)
# 构造因果距离矩阵: i - j
pos_i = np.arange(seq_len)[:, np.newaxis]
pos_j = np.arange(seq_len)[np.newaxis, :]
distance = np.maximum(0, pos_i - pos_j) # 下三角距离矩阵 (S, S)
# 广播相乘: (H, 1, 1) * (1, S, S) -> (H, S, S)
bias = -slopes[:, np.newaxis, np.newaxis] * distance[np.newaxis, :, :]
return
Step 3 · 反例与边界断言核对
💡
实战一句话记忆口诀
点积直加负偏置,等比斜率分多头,对角为零向后扣
📐 核心数学公式与机理推导
### 线性斜率几何惩罚
Ofir Press 等人在 2021 年提出 ALiBi。其核心思想是:与其在表示向量中编码位置,不如直接在注意力矩阵得分上惩罚远距离的 Token。
在计算注意力分数时直接添加相对距离惩罚项 (针对因果单向掩码 )。
为了给不同的注意力头赋予多样化的长短程敏感度,每个注意力头分配一个几何等比衰减的固定斜率 。
对于 个头,斜率集合定义为:
在 BLOOM 和 MPT 模型中得到大规模工业级验证,训练 2k 长度可在推理期外推至 8k 甚至更长。
Ofir Press 等人在 2021 年提出 ALiBi。其核心思想是:与其在表示向量中编码位置,不如直接在注意力矩阵得分上惩罚远距离的 Token。
在计算注意力分数时直接添加相对距离惩罚项 (针对因果单向掩码 )。
为了给不同的注意力头赋予多样化的长短程敏感度,每个注意力头分配一个几何等比衰减的固定斜率 。
对于 个头,斜率集合定义为:
在 BLOOM 和 MPT 模型中得到大规模工业级验证,训练 2k 长度可在推理期外推至 8k 甚至更长。
🔄 张量维度与形状流转说明
slopes: (H,) -> distance: (S, S) -> bias: (1, H, S, S) -> 直接加到 (B, H, S, S) 注意力分数矩阵
🛡️ 数值稳定性自检与边界要点
- ALiBi 的惩罚偏置为负值,斜率 m 为正,越远惩罚越大
- 在 FlashAttention-2 中由于融合算子直接在 SRAM 内部计算,支持通过注入 alibi_slopes 变量实现原生硬件加速
💻 完整参考代码实现
import numpy as np
def get_alibi_slopes(num_heads: int) -> np.ndarray:
"""生成每个头的几何衰减斜率 m"""
def get_slopes_power_of_2(n):
start = (2 ** (-2 ** -(np.log2(n) - 3)))
ratio = start
return [start * (ratio ** i) for i in range(n)]
if np.log2(num_heads).is_integer():
return np.array(get_slopes_power_of_2(num_heads))
else:
# 非 2 的幂次向下寻找最近的幂
closest_power = 2 ** int(np.log2(num_heads))
slopes = get_slopes_power_of_2(closest_power)
# 补齐多出的头
extra_slopes = get_slopes_power_of_2(2 * closest_power)[0::2][:num_heads - closest_power]
return np.array(slopes + extra_slopes)
def build_alibi_bias(seq_len: int, num_heads: int) -> np.ndarray:
"""
构建 ALiBi 偏置矩阵。
返回形状: (1, num_heads, seq_len, seq_len)
"""
slopes = get_alibi_slopes(num_heads) # (H,)
# 构造因果距离矩阵: i - j
pos_i = np.arange(seq_len)[:, np.newaxis]
pos_j = np.arange(seq_len)[np.newaxis, :]
distance = np.maximum(0, pos_i - pos_j) # 下三角距离矩阵 (S, S)
# 广播相乘: (H, 1, 1) * (1, S, S) -> (H, S, S)
bias = -slopes[:, np.newaxis, np.newaxis] * distance[np.newaxis, :, :]
return bias[np.newaxis, ...] # (1, H, S, S)
🧪 本地测试与正确性断言
可直接复制到本地 Python / Jupyter 验证:
import numpy as np
bias = build_alibi_bias(seq_len=4, num_heads=4)
assert bias.shape == (1, 4, 4, 4)
# 对角线上 i=j,偏置应为 0
assert np.allclose(np.diagonal(bias[0, 0]), 0.0)
# 距离越远,负值越大 (惩罚越重)
assert bias[0, 0, 3, 0] < bias[0, 0, 3, 2]
print("✓ ALiBi 偏置自测通过")🎯 核心工程追问与标准应答
Q1:ALiBi 与 RoPE 相比,主要优缺点是什么?
ALiBi 的优势在于其零参数且推理外推能力极强,完全不需要做位置插值;但其劣势在于这种严格衰减假设限制了模型对远距离反常强烈依赖的捕获能力,在中短文本丰富语义表达上综合评测略逊于 RoPE。
⚡
想检验本题的肌肉记忆?进入 3 阶闪卡主动回忆盲测
隐藏答案遮罩,自测:审题锚点 ➔ 数理公式机理 ➔ 工业标杆代码与连环追问。3 分钟攻破认知盲区!