实验实践 / 算法与编程

注意力机制华为笔试

第一题:5G基站设备故障风险预警

题目描述

通信工程师需要对部署在户外的5G基站进行实时健康监控。现收集到一批基站的历史运行数据,包含两个关键指标:设备工作温度(特征 x1x_1)和天线负载系数(特征 $ x_2 $),以及该基站是否发生故障的标签 $ y $(1表示故障,0表示正常)。使用逻辑回归结合批量梯度下降法(Batch Gradient Descent),从零开始训练一个故障预警模型,并预测新基站的故障概率。

模型公式与更新规则:

  1. 预测函数:
    y^=σ(w⋅x+b),\hat{y} = \sigma(w \cdot x + b), 其中 σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z})

  2. 参数初始化: w=[0,0],b=0w = [0, 0],\quad b = 0

  3. 梯度计算: 基于全体 $ N $ 个样本计算平均梯度
    dw=1NXT(y^−y),db=1N∑(y^−y)dw = \frac{1}{N} X^T (\hat{y} - y), \quad db = \frac{1}{N} \sum (\hat{y} - y)

  4. 参数更新: w←w−α⋅dw,b←b−α⋅dbw \leftarrow w - \alpha \cdot dw,\quad b \leftarrow b - \alpha \cdot db

迭代指定次数后输出新样本的预测故障概率,保留 4 位小数。


输入:第一行 $ N $、迭代次数 epochs 和学习率 $ \alpha $。第 2 到第 $ N+1 $ 行每行三个数值 $ x_1, x_2, y $。最后一行将预测样本的两个特征。

2 1 0.1
1.0 2.0 1
-1.0 -2.0 0
0.5 1.0
输出
0.5312

思路分析

第一步:理解逻辑回归模型

逻辑回归先算线性打分 $ z = w \cdot x + b $,再用 sigmoid 压成概率 $ p = \sigma(z) $。这里的任务就是按照题目给定的公式迭代更新参数。

第二步:梯度推导

对二元交叉熵 L=−log⁡p+(1−y)log⁡(1−p)L = -\log p + (1 - y) \log(1 - p) 链式求导,利用 σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1 - \sigma(z)) 化简后得到题目的“误差率”形式: ∇wL=(y^−y)⋅x.\nabla_w L = (\hat{y} - y) \cdot x.

第三步:批量更新的关键陷阱

每一轮必须先用同一组 $ w, b $ 把全部样本的预测和梯度算完,再统一更新一次。如果边遍历边更新会退化为 SGD,结果与标答不符。

第四步:数值稳定的 Safe Sigmoid

当 $ z $ 为负数时 $ e^{-z} $ 会上溢或 $ \inf 。分两种情况实现:。分两种情况实现: z \geq 0 $ 时用 $ 1/(1 + e^{-z}) ,, z < 0 $ 时用 $ e^{z}/(1 + e^{z}) $,让指数项的指数值为非正。

题解代码

import sys
import numpy as np

input = sys.stdin.readline

def sigmoid(z):
z = np.asarray(z, dtype=np.float64)
return np.where(
z >= 0.0,
1.0 / (1.0 + np.exp(-z)),
np.exp(z) / (1.0 + np.exp(z))
)

def solve():
first_line = input().split()
n, epochs = int(first_line[0]), int(first_line[1])
alpha = float(first_line[2])

samples = []
for _ in range(n):
parts = input().split()
samples.append((float(parts[0]), float(parts[1]), int(parts[2])))

query = list(map(float, input().split()))

data = np.array(samples, dtype=np.float64)
x = data[:, :2]
y = data[:, 2]

w = np.zeros(2, dtype=np.float64)
b = 0.0
for _ in range(epochs):
pred = sigmoid(x @ w + b)
diff = pred - y
dw = (x.T @ diff) / n
db = float(np.mean(diff))
w -= alpha * dw
b -= alpha * db
query = np.array(query, dtype=np.float64)
prob = float(sigmoid(query @ w + b))
print(f"{prob:.4f}")

solve()

复杂度分析

时间复杂度:O(epochs×N×d),每轮对 N个样本做 d维向量运算。 空间复杂度:O(N×d),存储数据矩阵。


第二题:多头注意力掩码计算

题目描述

将多个不同长度的句子打包成 Batch 计算注意力时,需要同时处理:

  • Batch + Padding:短句子后面补 0,需要忽略 padding 位置
  • 因果掩码:第 ii 个 token 只能看自己和过去(j≤ij≤i)
  • 位置惩罚:第 hh 个头(从 0 起)的斜率 slope=h+1slope=h+1,对未被掩码的位置减去 slope×(i−j)slope×(i−j),让不同头看不同距离
  • Safe Softmax:行内归一化时需先减最大值防溢出

给定 BB 个 S×SS×S 的得分矩阵(按 batch ×× head 顺序输入)和每个 batch 的有效长度 LbLb,输出处理后的注意力权重张量。

输入:第一行 BB, HH, SS。第二行 BB 个有效长度。接下来 B×HB×H 个 S×SS×S 矩阵(每行 SS 个浮点数)。

样例

输入

2 2 2
2 1
10.0 10.0
10.0 10.0
10.0 10.0
10.0 10.0
5.0 5.0
5.0 5.0
5.0 5.0
5.0 5.0

输出

1.0000 0.0000
0.2689 0.7311
1.0000 0.0000
0.1192 0.8808
1.0000 0.0000
0.0000 0.0000
1.0000 0.0000
0.0000 0.0000

思路分析

第一步:构造双重掩码合并因果约束(j≤i)和 Padding 约束(i<L 且 j<L)。位置 (i,j)(i,j) 有效当且仅当三个条件同时满足。当 i≥Li≥L 时整行无效,对应输出全 0。

**第二步:位置惩罚(ALiBi 风格)**第 hh 个头的斜率为 h+1h+1,对得分减去随距离线性增长的偏置:score[i][j]−=slope×(i−j)score[i][j]−=slope×(i−j)。低编号头看远处惩罚小,高编号头聚焦邻近 token。

第三步:Safe Softmax每行减最大值再 exp,保证指数项 ≤1≤1 不溢出。把无效位置得分置为 −∞−∞,让其在 softmax 中自然消失为 0,无需逐位置 if-else。

第四步:处理全无效行整行无效(i≥Li≥L)的行保留全 0 输出,跳过归一化以防除以 0。

题解代码

import sys
import numpy as np

def process_matrix(matrix, length, head_index, size):
result = np.zeros((size, size), dtype=np.float64)
if length <= 0:
return result

slope = head_index + 1
row = np.arange(size).reshape(size, 1)
col = np.arange(size).reshape(1, size)

mask = (row < length) & (col < length) & (col <= row)
adjusted = matrix - (row - col) * slope
masked = np.where(mask, adjusted, -np.inf)

valid_rows = np.arange(size) < length
part = masked[valid_rows]

max_value = np.max(part, axis=1, keepdims=True)
exp_values = np.exp(part - max_value)
exp_values = np.where(mask[valid_rows], exp_values, 0.0)
result[valid_rows] = exp_values / np.sum(exp_values, axis=1, keepdims=True)
return result
def solve():
data = sys.stdin.buffer.read().split()
idx = 0
batch_count = int(data[idx]); head_count = int(data[idx + 1]); size = int(data[idx + 2])
idx += 3
lengths = [int(data[idx + i]) for i in range(batch_count)]
idx += batch_count
matrices = []
for _ in range(batch_count * head_count):
values = [float(data[idx + i]) for i in range(size * size)]
idx += size * size
matrices.append(np.array(values, dtype=np.float64).reshape(size, size))
answer = []
index = 0
for b in range(batch_count):
for h in range(head_count):
answer.extend(process_matrix(matrices[index], lengths[b], h, size))
index += 1
print("\n".join(" ".join(f"{x:.4f}" for x in row) for row in answer))
solve()

机器翻译中的多头自注意力

为了说明多头自注意力机制的作用,我们以英语到法语的机器翻译任务为例。

问题描述: 假设我们需要将英文句子 “I love artificial intelligence” 翻译成法语。传统模型可能只关注单一的上下文关系,而多头自注意力机制可以同时捕捉到 “I” 和 “love” 的主谓关系,以及 “artificial” 和 “intelligence” 的修饰关系。

步骤解析:

  1. 输入嵌入:将英文句子中的每个单词映射为向量。

  2. 多头自注意力

    :通过多个头分别捕捉不同的语义关系,例如:

    • 头 1 关注 “I” 和 “love” 的关系。
    • 头 2 关注 “artificial” 和 “intelligence” 的关系。
  3. 输出生成:通过注意力机制加权后,生成法语句子的翻译结果。

代码示例:

import torch
import torch.nn.functional as F
from torch import nn

class MultiHeadSelfAttention(nn.Module):
def __init__(self, embed_size, num_heads):
super(MultiHeadSelfAttention, self).__init__()
assert embed_size % num_heads == 0

self.num_heads = num_heads
self.head_dim = embed_size // num_heads

self.query = nn.Linear(embed_size, embed_size)
self.key = nn.Linear(embed_size, embed_size)
self.value = nn.Linear(embed_size, embed_size)
self.fc_out = nn.Linear(embed_size, embed_size)

def forward(self, x):
N, seq_length, embed_size = x.shape

Q = self.query(x)
K = self.key(x)
V = self.value(x)
Q = Q.view(N, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
K = K.view(N, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
V = V.view(N, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
attention = F.softmax((Q @ K.transpose(-2, -1)) / (self.head_dim ** 0.5), dim=-1)
out = attention @ V
out = out.transpose(1, 2).contiguous().view(N, seq_length, embed_size)
return self.fc_out(out)
# 测试代码
embed_size = 128
num_heads = 8
seq_length = 10
x = torch.rand((32, seq_length, embed_size))

attention = MultiHeadSelfAttention(embed_size, num_heads)
output = attention(x)
print(output.shape) # 应输出 (32, seq_length, embed_size)

简单的Self-Attention

import torch
import torch.nn as nn
import torch.nn.functional as F
import math

class SelfAttention(nn.Module):
def __init__(self, embed_dim,d_k):
super().__init__()
self.embed_dim = embed_dim
self.W_Q = nn.Linear(embed_dim, d_k)
self.W_K = nn.Linear(embed_dim, d_k)
self.W_V = nn.Linear(embed_dim, d_k)

def forward(self, x):
# x: [batch_size, seq_len, embed_dim]
Q = self.W_Q(x) # [B, L, D]
K = self.W_K(x) # [B, L, D]
V = self.W_V(x) # [B, L, D]

# Attention scores: [B, L, L]
score = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)

attn_weights = F.softmax(score, dim=-1) # [B, L, L]

att_output = torch.matmul(attn_weights, V) # [B, L, D]
return att_output

多头注意力:

import torch
import torch.nn as nn
import math
import torch.nn.functional as F
class MultiHeadAttention(nn.Module):
#定义参数
def __init__(self,embed_dim,head_num):
super().__init__()
self.embed_dim=embed_dim
self.head_num=head_num
self.head_dim=embed_dim//head_num #每个头的维度
#定义好Q,K,V矩阵和最后的输出变换矩阵
self.W_Q=nn.Linear(embed_dim, embed_dim)
self.W_K=nn.Linear(embed_dim, embed_dim)
self.W_V=nn.Linear(embed_dim, embed_dim)
self.W_O=nn.Linear(embed_dim, embed_dim)# 注意力输出后再投回原维度

#前向传播
def forward(self,x):
# x维度是BLD,batch_size seq_len embed_dim
batch_size,seq_len,embed_dim=x.size()
# 先全量投影得到了QKV矩阵再拆头
Q = self.W_Q(x) # [B, L, embed_dim]
K = self.W_K(x) # [B, L, embed_dim]
V = self.W_V(x) # [B, L, embed_dim]
#拆分多头
# 方法:先view,再transpose
# 拆分成[B, L, num_heads, head_dim],再变成[B, num_heads, L, head_dim]
Q=Q.view(batch_size, seq_len, self.head_num, self.head_dim).transpose(1, 2)
K=K.view(batch_size, seq_len, self.head_num, self.head_dim).transpose(1, 2)
V=V.view(batch_size, seq_len, self.head_num, self.head_dim).transpose(1, 2)
# 此时shape均为[B, num_heads, L, head_dim]

# Q @ K^T:最后两维做乘法
# K.transpose(-2, -1): [B, num_heads, head_dim, L]
score = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.head_dim) # [B, num_heads, L, L]
attn_weights = F.softmax(score, dim=-1) # [B, num_heads, L, L]
# 得到每个头的注意力输出
att_output = torch.matmul(attn_weights, V) # [B, num_heads, L, head_dim]
# 变回 [B, L, embed_dim]
# 先transpose(1,2): [B, L, num_heads, head_dim]
# 然后view为 [B, L, num_heads*head_dim] = [B, L, embed_dim]
att_output = att_output.transpose(1, 2).contiguous().view(batch_size, seq_len, self.embed_dim)
output = self.W_O(att_output) # [B, L, embed_dim]
return output

为什么要拆分成 (num_heads, head_dim)?

背景:你的输入每个 token 有 embed_dim 维(比如 768)。多头注意力机制本质上是把输入特征维度切成 num_heads 块,每块 head_dim 维,分别做自注意力,然后拼回去。每个头都是一个“小的单头 self-attention”,但只用一部分特征(head_dim = embed_dim // num_heads)。
举例:如果 embed_dim=768, num_heads=12, 每头 head_dim=64。768=12*64。

原始Q的shape

Q = [B, L, embed_dim] (batch, sequence, feature维)

目标:希望得到一个 shape = [B, num_heads, L, head_dim]

这样后续每个head可以独立做 Attention(矩阵乘法/softmax/加权 …)。 为什么用 view(B, L, num_heads, head_dim).transpose(1, 2)? Step 1: view(B, L, num_heads, head_dim)

把最后一维 embed_dim 拆成 num_heads * head_dim
假设 embed_dim=768, num_heads=12, head_dim=64,则拆分成 [B, L, 12, 64]

Step 2: transpose(1, 2)

把 head 数移到序列长度前面
[B, L, num_heads, head_dim] --> [B, num_heads, L, head_dim]
这样每个 batch 下,对每个头进行独立计算(更方便并行处理多头)

过程可视化

比如有 Q: [2, 10, 768](batch=2, seq=10, 768维)

view(2, 10, 12, 64) -- 12个头,每头64维
transpose(1, 2) 得到 (2, 12, 10, 64)

为什么顺序不能交换?

如果你写成 view(B, num_heads, L, head_dim),就完全不对了!因为:

原始数据是按 [B, L, embed_dim] 顺序排列的。
view 顺序必须是先序列后特征,特征维度用于拆分。
而且在 PyTorch、Tensorflow 中,view 后的数据不会自动乱序分配,只是“重新组织 shape”,不会帮助你把循环顺序换掉。
transpose(1, 2) 是在 [B, L, num_heads, head_dim] 基础上,把 head 放到序列之前。

如果互换 num_heads、L 顺序,会把 batch 里的时间步和头搞混,后续 Attention 计算也会错。 为什么最终要 [B, num_heads, L, head_dim]?

这样每个头彼此独立,并且都遍历了全部 batch 的序列。
方便后续在每个头上分别做 Attention 计算。

总结口诀

view 拆头之前,总是最后一维(embed_dim)先拆成 (num_heads, head_dim),再用 transpose 把 head 移到 L 之前,得到 [B, num_heads, L, head_dim]。不能交换顺序,因为原始数据排列是 batch, seq, feat,再拆 feat。

22. 多头注意力掩码计算

问题背景

在人类语言模型训练过程中,为了提高 GPU 的效率,我们通常将多个不同长度的序列打包成一个 Batch。

Batch(批处理):不同句子的长度不一致,较短子句会补零(Padding)。

Multi-Head(多头):每层注意力会被拆分成多个头,每个头独立计算注意力,以捕捉不同层面的语义。

双重掩码:在计算时,必须同时屏蔽因果掩码(不能看未来)和 Padding 掩码(不参加有效计算)。

位置惩罚:对未被掩码的位置进行偏置惩罚。如果所有的头都使用相同的惩罚力度,那么它们关注的注意模式会高度重合,造成计算资源的浪费,因此需要引入随着“头”变化的惩罚项。本题中惩罚因子:slope = s + 1 其中 ss 为头索引(从 0 开始)。


下面将给定一个 Batch 的注意力得分张量,默认该张量已经过缩放:

Score=QKTdkScore = \frac{QK^T}{\sqrt{d_k}}

请针对每批次和头,实现其掩码注入和归一化过程。


主要步骤

  1. 因果掩码

我们需要对计算出的得分矩阵进行掩码处理。对于一个给定的:n×nn \times n得分矩阵 Score:其上三角位置(不包括对角)的值全部替换为-1e9。其它位置保持不变。

目的是防止模型看到“未来”的信息。

  1. Padding 掩码注入:给定每个序列的有效长度 LL。若列索引j≥Lj \ge L(列索引从 0 开始)

则:Scorei,j=−1e9Score_{i,j} = -1e9即该 Token 是填充的,不应该被关注。

  1. 位置惩罚注入距离偏置。对于未被掩码的位置(即下三角位置),在其原始得分基础上减去距离偏置:

(1)偏置计算:Biasi,j=(i−j)×slopeBias_{i,j} = (i - j) \times slope

(2)更新公式Scorei,j′=Scorei,j−Biasi,jScore'_{i,j} = Score_{i,j} - Bias_{i,j}

  1. 归一化

    对处理后的矩阵每一行进行 Safe Softmax 归一化,步骤:

    1. 对于每一行 ii,先找到该行中非掩码位置集合:validivalid_i

    2. 找到第 ii 行的最大值:MiM_i

    3. 对于第 ii 行第 jj 列元素:

      • 若 j∉validij \notin valid_i,则:
        Softmax(Scorei,j′)=0\text{Softmax}(Score'_{i,j}) = 0

      • 若 j∈validij \in valid_i,则进行标准 Softmax 计算:
        Softmax(Scorei,j)=eScorei,j−Mi∑k∈validieScorei,k−Mi\text{Softmax}(Score_{i,j}) = \frac{e^{Score_{i,j} - M_i}}{\sum_{k \in valid_i} e^{Score_{i,k} - M_i}}

        (注意:原提示中公式写作 Softmax(Scorei,j)=eScorei,j−Mi∑j=1SeScorei,j−MiSoftmax(Score_{i,j}) = \frac{e^{Score_{i,j}} - M_i}{\sum_{j=1}^{S} e^{Score_{i,j}} - M_i} 可能有笔误,正确形式应为上述指数内减最大值,分母为指数和。此处按标准 Safe Softmax 语义提取。)注意:当 Scorei,j=−1e9Score_{i,j} = -1e9 时,视为 ex=0e^{x} = 0

输入

第一行:三个整数 B(批数量),H(头数量),S(得分矩阵维度,即每个头的序列长度)。

第二行:B 个整数,代表每个 Batch 的有效序列长度 Lb(最小值为 0)。

接下来 B×H×S行,每行 SS 个浮点数。数据按B→H→S顺序排列,即:先遍历 Batch 维度(B批)再遍历 Head 维度(H个头)最后遍历 Sequence 维度(S个位置)是经过缩放之后的得分矩阵 Score。

2 2 3
3 2
1.0 1.0 1.0
1.0 1.0 1.0
1.0 1.0 1.0
1.0 1.0 1.0
1.0 1.0 1.0
1.0 1.0 1.0
2.0 2.0 2.0
2.0 2.0 2.0
2.0 2.0 2.0
2.0 2.0 2.0
2.0 2.0 2.0
2.0 2.0 2.0

输出

输出处理后的张量,每行 S个浮点数,保留 4 位小数。

1.0000 0.0000 0.0000
0.2689 0.7311 0.0000
0.0900 0.2447 0.6652
1.0000 0.0000 0.0000
0.1192 0.8808 0.0000
0.0159 0.1173 0.8668
1.0000 0.0000 0.0000
0.2689 0.7311 0.0000
0.0000 0.0000 0.0000
1.0000 0.0000 0.0000
0.1192 0.8808 0.0000
0.0000 0.0000 0.0000
import sys
import math
def main():
data = sys.stdin.read().strip().split()
if not data:
return
idx = 0
B = int(data[idx])
idx += 1
H = int(data[idx])
idx += 1
S = int(data[idx])
idx += 1
lengths = []
for _ in range(B):
lengths.append(int(data[idx]))
idx += 1
ans = []
for b in range(B):
L = lengths[b]
for h in range(H):
slope = h + 1
score = []
for i in range(S):
row = []
for j in range(S):
row.append(float(data[idx]))
idx += 1
score.append(row)
for i in range(S):
# 如果 query 本身是 padding,整行输出 0
if i >= L:
ans.append(["0.0000"] * S)
continue
vals = []
valid_js = []
for j in range(S):
# 必须满足:不是 padding,并且是下三角 j <= i
if j < L and j <= i:
bias = (i - j) * slope
val = score[i][j] - bias
vals.append(val)
valid_js.append(j)
# 理论上 i < L 时一定有有效位置,但这里保险处理
if not vals:
ans.append(["0.0000"] * S)
continue
max_val = max(vals)
exp_vals = []
total = 0.0
for v in vals:
e = math.exp(v - max_val)
exp_vals.append(e)
total += e
out = [0.0] * S
for k in range(len(valid_js)):
j = valid_js[k]
out[j] = exp_vals[k] / total
ans.append([f"{x:.4f}" for x in out])
for row in ans:
print(" ".join(row))

if __name__ == "__main__":
main()
— 本篇完 —

个人学习与研究记录。引用论文请以原文为准,欢迎交流与指正。

搜索研究笔记

输入关键词,探索笔记中的内容。