第一题:5G基站设备故障风险预警
题目描述
通信工程师需要对部署在户外的5G基站进行实时健康监控。现收集到一批基站的历史运行数据,包含两个关键指标:设备工作温度(特征 x 1 x_1 x 1 )和天线负载系数(特征 $ x_2 $),以及该基站是否发生故障的标签 $ y $(1表示故障,0表示正常)。使用逻辑回归结合批量梯度下降法(Batch Gradient Descent),从零开始训练一个故障预警模型,并预测新基站的故障概率。
模型公式与更新规则:
预测函数:
y ^ = σ ( w ⋅ x + b ) , \hat{y} = \sigma(w \cdot x + b), y ^ = σ ( w ⋅ x + b ) , 其中 σ ( z ) = 1 / ( 1 + e − z ) \sigma(z) = 1/(1 + e^{-z}) σ ( z ) = 1 / ( 1 + e − z )
参数初始化: w = [ 0 , 0 ] , b = 0 w = [0, 0],\quad b = 0 w = [ 0 , 0 ] , b = 0
梯度计算: 基于全体 $ N $ 个样本计算平均梯度
d w = 1 N X T ( y ^ − y ) , d b = 1 N ∑ ( y ^ − y ) dw = \frac{1}{N} X^T (\hat{y} - y), \quad db = \frac{1}{N} \sum (\hat{y} - y) d w = N 1 X T ( y ^ − y ) , d b = N 1 ∑ ( y ^ − y )
参数更新: w ← w − α ⋅ d w , b ← b − α ⋅ d b w \leftarrow w - \alpha \cdot dw,\quad b \leftarrow b - \alpha \cdot db w ← w − α ⋅ d w , b ← b − α ⋅ d b
迭代指定次数后输出新样本的预测故障概率,保留 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) L = − log p + ( 1 − y ) log ( 1 − p )
链式求导,利用 σ ′ ( z ) = σ ( z ) ( 1 − σ ( z ) ) \sigma'(z) = \sigma(z)(1 - \sigma(z)) σ ′ ( z ) = σ ( z ) ( 1 − σ ( z ) ) 化简后得到题目的“误差率”形式: ∇ w L = ( y ^ − y ) ⋅ x . \nabla_w L = (\hat{y} - y) \cdot x. ∇ w L = ( y ^ − y ) ⋅ 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 sysimport numpy as npinput = sys.stdin.readlinedef 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:.4 f} " ) 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 关注 “I” 和 “love” 的关系。
头 2 关注 “artificial” 和 “intelligence” 的关系。
输出生成 :通过注意力机制加权后,生成法语句子的翻译结果。
代码示例 :
import torchimport torch.nn.functional as Ffrom torch import nnclass 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)
简单的Self-Attention
import torchimport torch.nn as nnimport torch.nn.functional as Fimport 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 ): Q = self .W_Q(x) K = self .W_K(x) V = self .W_V(x) score = torch.matmul(Q, K.transpose(-2 , -1 )) / math.sqrt(self .d_k) attn_weights = F.softmax(score, dim=-1 ) att_output = torch.matmul(attn_weights, V) return att_output
多头注意力:
import torchimport torch.nn as nnimport mathimport torch.nn.functional as Fclass 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 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 ): batch_size,seq_len,embed_dim=x.size() Q = self .W_Q(x) K = self .W_K(x) V = self .W_V(x) 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 ) score = torch.matmul(Q, K.transpose(-2 , -1 )) / math.sqrt(self .head_dim) attn_weights = F.softmax(score, dim=-1 ) att_output = torch.matmul(attn_weights, V) att_output = att_output.transpose(1 , 2 ).contiguous().view(batch_size, seq_len, self .embed_dim) output = self .W_O(att_output) 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 其中 s s s 为头索引(从 0 开始)。
下面将给定一个 Batch 的注意力得分张量,默认该张量已经过缩放:
S c o r e = Q K T d k Score = \frac{QK^T}{\sqrt{d_k}}
S c o r e = d k Q K T
请针对每批次和头,实现其掩码注入和归一化过程。
主要步骤
因果掩码
我们需要对计算出的得分矩阵进行掩码处理。对于一个给定的:n × n n \times n n × n 得分矩阵 Score:其上三角位置(不包括对角)的值全部替换为-1e9。其它位置保持不变。
目的是防止模型看到“未来”的信息。
Padding 掩码注入:给定每个序列的有效长度 L L L 。若列索引j ≥ L j \ge L j ≥ L (列索引从 0 开始)
则:S c o r e i , j = − 1 e 9 Score_{i,j} = -1e9 S c o r e i , j = − 1 e 9 即该 Token 是填充的,不应该被关注。
位置惩罚注入距离偏置。对于未被掩码的位置(即下三角位置),在其原始得分基础上减去距离偏置:
(1)偏置计算:B i a s i , j = ( i − j ) × s l o p e Bias_{i,j} = (i - j) \times slope B i a s i , j = ( i − j ) × s l o p e
(2)更新公式S c o r e i , j ′ = S c o r e i , j − B i a s i , j Score'_{i,j} = Score_{i,j} - Bias_{i,j} S c o r e i , j ′ = S c o r e i , j − B i a s i , j
归一化
对处理后的矩阵每一行进行 Safe Softmax 归一化,步骤:
对于每一行 i i i ,先找到该行中非掩码位置集合:v a l i d i valid_i v a l i d i
找到第 i i i 行的最大值:M i M_i M i
对于第 i i i 行第 j j j 列元素:
若 j ∉ v a l i d i j \notin valid_i j ∈ / v a l i d i ,则:
Softmax ( S c o r e i , j ′ ) = 0 \text{Softmax}(Score'_{i,j}) = 0 Softmax ( S c o r e i , j ′ ) = 0
若 j ∈ v a l i d i j \in valid_i j ∈ v a l i d i ,则进行标准 Softmax 计算:
Softmax ( S c o r e i , j ) = e S c o r e i , j − M i ∑ k ∈ v a l i d i e S c o r e i , k − M i \text{Softmax}(Score_{i,j}) = \frac{e^{Score_{i,j} - M_i}}{\sum_{k \in valid_i} e^{Score_{i,k} - M_i}} Softmax ( S c o r e i , j ) = ∑ k ∈ v a l i d i e S c o r e i , k − M i e S c o r e i , j − M i
(注意:原提示中公式写作 S o f t m a x ( S c o r e i , j ) = e S c o r e i , j − M i ∑ j = 1 S e S c o r e i , j − M i Softmax(Score_{i,j}) = \frac{e^{Score_{i,j}} - M_i}{\sum_{j=1}^{S} e^{Score_{i,j}} - M_i} S o f t m a x ( S c o r e i , j ) = ∑ j = 1 S e S c o r e i , j − M i e S c o r e i , j − M i 可能有笔误,正确形式应为上述指数内减最大值,分母为指数和。此处按标准 Safe Softmax 语义提取。)注意:当 S c o r e i , j = − 1 e 9 Score_{i,j} = -1e9 S c o r e i , j = − 1 e 9 时,视为 e x = 0 e^{x} = 0 e 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 sysimport mathdef 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): if i >= L: ans.append(["0.0000" ] * S) continue vals = [] valid_js = [] for j in range (S): if j < L and j <= i: bias = (i - j) * slope val = score[i][j] - bias vals.append(val) valid_js.append(j) 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:.4 f} " for x in out]) for row in ans: print (" " .join(row)) if __name__ == "__main__" : main()
— 本篇完 — 个人学习与研究记录。引用论文请以原文为准,欢迎交流与指正。
← 较新的笔记 codexcli无root安装和问题快查 较早的笔记 → rangeimageloss