"""Independent PyTorch 2.10 CPU attention mechanisms lab (SDPA, MHA, cross-attention, CBAM, Pre-Norm vs Post-Norm, AttentionPooling)."""
import argparse
import hashlib
import json
import math
import platform
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
def manual_sdpa(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: torch.Tensor | None = None):
d_k = q.size(-1)
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, float("-inf"))
weights = F.softmax(scores, dim=-1)
return torch.matmul(weights, v), weights
class SEBlock(nn.Module):
def __init__(self, channels: int, reduction: int = 4):
super().__init__()
self.fc = nn.Sequential(
nn.Linear(channels, channels // reduction, bias=False),
nn.ReLU(inplace=True),
nn.Linear(channels // reduction, channels, bias=False),
nn.Sigmoid(),
)
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
b, c, _, _ = x.shape
w = self.fc(x.mean(dim=(2, 3))).view(b, c, 1, 1)
return x * w, w
class SpatialAttention(nn.Module):
def __init__(self, kernel_size: int = 5):
super().__init__()
self.conv = nn.Conv2d(2, 1, kernel_size=kernel_size, padding=kernel_size // 2, bias=False)
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
avg_out = x.mean(dim=1, keepdim=True)
max_out, _ = x.max(dim=1, keepdim=True)
w = torch.sigmoid(self.conv(torch.cat([avg_out, max_out], dim=1)))
return x * w, w
class CBAM(nn.Module):
def __init__(self, channels: int):
super().__init__()
self.ca = SEBlock(channels)
self.sa = SpatialAttention(kernel_size=3)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x, _ = self.ca(x)
x, _ = self.sa(x)
return x
class PreNormEncoderLayer(nn.Module):
"""True Pre-Norm Transformer block (LN before residual sublayer)."""
def __init__(self, d_model: int, nhead: int, d_ff: int):
super().__init__()
self.ln1 = nn.LayerNorm(d_model)
self.attn = nn.MultiheadAttention(d_model, nhead, batch_first=True)
self.ln2 = nn.LayerNorm(d_model)
self.ffn = nn.Sequential(nn.Linear(d_model, d_ff), nn.GELU(), nn.Linear(d_ff, d_model))
def forward(self, x: torch.Tensor, key_padding_mask: torch.Tensor | None = None):
h = self.ln1(x)
attn_out, weights = self.attn(h, h, h, key_padding_mask=key_padding_mask, need_weights=True)
x = x + attn_out
x = x + self.ffn(self.ln2(x))
return x, weights
class AttentionPoolClassifier(nn.Module):
def __init__(self, vocab_size: int, d_model: int = 24, nhead: int = 4, num_classes: int = 2):
super().__init__()
self.emb = nn.Embedding(vocab_size, d_model, padding_idx=0)
self.pos = nn.Parameter(torch.randn(1, 16, d_model) * 0.05)
self.enc = PreNormEncoderLayer(d_model, nhead, d_model * 2)
self.pool_score = nn.Linear(d_model, 1)
self.head = nn.Linear(d_model, num_classes)
def forward(self, x: torch.Tensor):
pad_mask = x == 0 # True = ignore
h = self.emb(x) + self.pos[:, : x.size(1), :]
h, attn_w = self.enc(h, key_padding_mask=pad_mask)
scores = self.pool_score(h).squeeze(-1).masked_fill(pad_mask, float("-inf"))
pool_w = F.softmax(scores, dim=-1)
ctx = torch.bmm(pool_w.unsqueeze(1), h).squeeze(1)
return self.head(ctx), attn_w, pool_w
def sha(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def run_cases(fig_dir: Path | None):
torch.manual_seed(2026)
cases = []
figures = {}
# 1. Scaled dot-product attention variance stabilization & SDPA parity
q = torch.randn(2, 4, 6, 64)
k = torch.randn(2, 4, 6, 64)
v = torch.randn(2, 4, 6, 64)
raw_std = float(torch.matmul(q, k.transpose(-2, -1)).std().item())
scaled_std = float((torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(64)).std().item())
out_m, w_m = manual_sdpa(q, k, v)
out_f = F.scaled_dot_product_attention(q, k, v)
row_sum_err = float((w_m.sum(dim=-1) - 1.0).abs().max().item())
sdpa_diff = float((out_m - out_f).abs().max().item())
c1_ok = raw_std > 5.0 and 0.6 < scaled_std < 1.5 and row_sum_err < 1e-6 and sdpa_diff < 1e-5
cases.append(dict(
name="scaled_dot_product_variance_and_weights",
inputs=dict(shape=[2, 4, 6, 64], d_k=64),
prerequisites="对比缩放前后点积标准差,并核对自写注意力与 F.scaled_dot_product_attention 一致性",
action="验证除以 sqrt(64) 将点积标准差从约 8 压回约 1、权重行和为 1 且与内置 SDPA 误差 <1e-5。",
expected=dict(raw_std_gt_5=True, scaled_std_near_1=True, row_sum_is_1=True, matches_builtin_sdpa=True),
actual=dict(raw_std_gt_5=raw_std > 5.0, scaled_std_near_1=0.6 < scaled_std < 1.5, row_sum_is_1=row_sum_err < 1e-6, matches_builtin_sdpa=sdpa_diff < 1e-5),
measurements=dict(raw_std=round(raw_std, 4), scaled_std=round(scaled_std, 4), sdpa_max_diff=round(sdpa_diff, 7)),
passed=c1_ok,
))
# 2. nn.MultiheadAttention key_padding_mask (True=ignore), causal SDPA, and invalid attn_implementation kwarg check
mha = nn.MultiheadAttention(embed_dim=32, num_heads=4, batch_first=True)
xm = torch.randn(2, 6, 32)
kpm = torch.tensor([[False, False, False, False, True, True], [False, False, False, True, True, True]])
mha_out, mha_w = mha(xm, xm, xm, key_padding_mask=kpm, need_weights=True)
pad_col_max_w = float(max(mha_w[0, :, 4:].abs().max().item(), mha_w[1, :, 3:].abs().max().item()))
causal_mask = torch.tril(torch.ones(6, 6))
out_c_man, w_c_man = manual_sdpa(q, k, v, mask=causal_mask)
out_c_sdpa = F.scaled_dot_product_attention(q, k, v, is_causal=True)
causal_diff = float((out_c_man - out_c_sdpa).abs().max().item())
upper_max = float(w_c_man.triu(diagonal=1).abs().max().item())
invalid_kwarg_raises = False
try:
nn.MultiheadAttention(32, 4, attn_implementation="flash_attention_2") # type: ignore[call-arg]
except TypeError:
invalid_kwarg_raises = True
c2_ok = list(mha_out.shape) == [2, 6, 32] and pad_col_max_w == 0.0 and causal_diff < 1e-5 and upper_max == 0.0 and invalid_kwarg_raises
cases.append(dict(
name="multihead_mha_key_padding_mask_and_sdpa",
inputs=dict(embed_dim=32, num_heads=4, seq_len=6),
prerequisites="核对 key_padding_mask(True=忽略)、is_causal=True 与 nn.MultiheadAttention 参数签名",
action="验证被遮蔽键列权重恒为 0.0、因果 SDPA 上三角权重为 0.0 且传非法 attn_implementation 报 TypeError。",
expected=dict(out_shape=[2, 6, 32], pad_weight_zero=True, causal_matches=True, future_weight_zero=True, invalid_kwarg_errors=True),
actual=dict(out_shape=list(mha_out.shape), pad_weight_zero=pad_col_max_w == 0.0, causal_matches=causal_diff < 1e-5, future_weight_zero=upper_max == 0.0, invalid_kwarg_errors=invalid_kwarg_raises),
passed=c2_ok,
))
# 3. Cross-attention (Q len 5, K/V len 9) & positional encoding breaking permutation invariance
cross_mha = nn.MultiheadAttention(32, 4, batch_first=True)
q_dec = torch.randn(2, 5, 32)
kv_enc = torch.randn(2, 9, 32)
c_out, c_w = cross_mha(q_dec, kv_enc, kv_enc, need_weights=True)
# Permutation equivariance without PE vs broken with sinusoidal PE
seq_a = torch.randn(1, 5, 16)
seq_b = seq_a[:, [2, 0, 4, 1, 3], :]
o_a, _ = manual_sdpa(seq_a, seq_a, seq_a)
o_b, _ = manual_sdpa(seq_b, seq_b, seq_b)
no_pe_mean_diff = float((o_a.mean(dim=1) - o_b.mean(dim=1)).abs().max().item())
pe = torch.zeros(1, 5, 16)
pos = torch.arange(5).unsqueeze(1).float()
div = torch.exp(torch.arange(0, 16, 2).float() * (-math.log(10000.0) / 16))
pe[0, :, 0::2] = torch.sin(pos * div)
pe[0, :, 1::2] = torch.cos(pos * div)
op_a, _ = manual_sdpa(seq_a + pe, seq_a + pe, seq_a + pe)
op_b, _ = manual_sdpa(seq_b + pe, seq_b + pe, seq_b + pe)
with_pe_mean_diff = float((op_a.mean(dim=1) - op_b.mean(dim=1)).abs().max().item())
c3_ok = list(c_out.shape) == [2, 5, 32] and list(c_w.shape) == [2, 5, 9] and no_pe_mean_diff < 1e-5 and with_pe_mean_diff > 0.05
cases.append(dict(
name="self_cross_attention_and_positional_encoding",
inputs=dict(q_len=5, kv_len=9, d_model=32),
prerequisites="核对交叉注意力非方阵权重 [B, 5, 9] 与正余弦位置编码打破置换不变性",
action="验证交叉注意力输出/权重维度,且无位置编码时打乱序列均值差 <1e-5、叠加位置编码后差值 >0.05。",
expected=dict(cross_out=[2, 5, 32], cross_weights=[2, 5, 9], no_pe_invariant=True, pe_breaks_symmetry=True),
actual=dict(cross_out=list(c_out.shape), cross_weights=list(c_w.shape), no_pe_invariant=no_pe_mean_diff < 1e-5, pe_breaks_symmetry=with_pe_mean_diff > 0.05),
measurements=dict(no_pe_diff=round(no_pe_mean_diff, 7), with_pe_diff=round(with_pe_mean_diff, 4)),
passed=c3_ok,
))
# 4. Vision attention: SEBlock, SpatialAttention, CBAM shapes, (0,1) bounds & gradients
feat = torch.randn(2, 16, 8, 8, requires_grad=True)
se_out, se_w = SEBlock(16)(feat)
sp_out, sp_w = SpatialAttention(3)(feat)
cbam = CBAM(16)
cb_out = cbam(feat)
cb_out.sum().backward()
c4_ok = (
list(se_out.shape) == [2, 16, 8, 8]
and list(se_w.shape) == [2, 16, 1, 1]
and list(sp_w.shape) == [2, 1, 8, 8]
and list(cb_out.shape) == [2, 16, 8, 8]
and float(se_w.min().item()) > 0.0 and float(se_w.max().item()) < 1.0
and float(sp_w.min().item()) > 0.0 and float(sp_w.max().item()) < 1.0
and feat.grad is not None and float(feat.grad.abs().sum().item()) > 0.0
)
cases.append(dict(
name="vision_se_spatial_and_cbam_attention",
inputs=dict(feature_shape=[2, 16, 8, 8]),
prerequisites="核对通道注意力 SEBlock、空间注意力 SpatialAttention 与串联模块 CBAM 的张量形状与梯度回传",
action="验证通道权重 [2,16,1,1]、空间权重 [2,1,8,8] 落在 (0,1) 区间且 CBAM 反向梯度正常回传。",
expected=dict(se_w_shape=[2, 16, 1, 1], sp_w_shape=[2, 1, 8, 8], cbam_shape=[2, 16, 8, 8], weights_in_0_1=True, grad_flows=True),
actual=dict(
se_w_shape=list(se_w.shape),
sp_w_shape=list(sp_w.shape),
cbam_shape=list(cb_out.shape),
weights_in_0_1=0.0 < float(se_w.min().item()) and float(se_w.max().item()) < 1.0 and 0.0 < float(sp_w.min().item()) and float(sp_w.max().item()) < 1.0,
grad_flows=feat.grad is not None and float(feat.grad.abs().sum().item()) > 0.0,
),
passed=c4_ok,
))
# 5. Pre-Norm vs Post-Norm distinction + real AttentionPoolClassifier training on keyword detection
# Vocab: 0=PAD, 1..20=background, 21..23=positive keywords, 24..26=negative keywords
g = torch.Generator().manual_seed(77)
def make_kw_dataset(n: int):
xs = torch.zeros((n, 10), dtype=torch.long)
ys = torch.zeros(n, dtype=torch.long)
kw_pos = []
for i in range(n):
length = int(torch.randint(6, 11, (1,), generator=g).item())
bg = torch.randint(1, 21, (length,), generator=g)
cls = i % 2
pos_i = int(torch.randint(0, length, (1,), generator=g).item())
bg[pos_i] = int(torch.randint(21, 24, (1,), generator=g).item()) if cls == 1 else int(torch.randint(24, 27, (1,), generator=g).item())
xs[i, :length] = bg
ys[i] = cls
kw_pos.append(pos_i)
return xs, ys, kw_pos
x_tr, y_tr, _ = make_kw_dataset(240)
x_va, y_va, va_kw_pos = make_kw_dataset(60)
clf = AttentionPoolClassifier(vocab_size=28, d_model=24, nhead=4, num_classes=2)
opt = optim.AdamW(clf.parameters(), lr=1e-2, weight_decay=1e-3)
ep1_loss, last_loss = None, None
for ep in range(25):
clf.train()
opt.zero_grad(set_to_none=True)
logits, _, _ = clf(x_tr)
loss = F.cross_entropy(logits, y_tr)
loss.backward()
opt.step()
if ep == 0:
ep1_loss = round(float(loss.item()), 5)
last_loss = round(float(loss.item()), 5)
clf.eval()
with torch.inference_mode():
val_logits, val_attn_w, val_pool_w = clf(x_va)
val_acc = round(float((val_logits.argmax(dim=1) == y_va).float().mean().item()), 4)
kw_weights = [float(val_pool_w[i, va_kw_pos[i]].item()) for i in range(len(y_va))]
mean_kw_weight = round(float(np.mean(kw_weights)), 4)
# Verify Pre-Norm preserves unnormalized skip path (variance != 1) unlike Post-Norm
ln_probe = nn.LayerNorm(24)
probe_x = torch.randn(2, 4, 24) * 5.0
pre_out, _ = clf.enc(probe_x)
post_out = ln_probe(probe_x)
pre_std = float(pre_out.std().item())
post_std = float(post_out.std().item())
c5_ok = last_loss < 0.08 and val_acc >= 0.95 and mean_kw_weight > 0.5 and pre_std > 2.5 and abs(post_std - 1.0) < 0.15
cases.append(dict(
name="prenorm_vs_postnorm_and_attention_classifier",
inputs=dict(train=240, val=60, seq_len=10, epochs=25),
prerequisites="使用真正 Pre-Norm 编码层 + 注意力池化训练变长关键词分类器(修正来源把 Post-Norm 误注为 Pre-Norm)",
action="验证损失降至 <0.08、留出准确率 >=95%、注意力池化在关键词位平均权重 >0.5,并区分 Pre-Norm 残差直通尺度。",
expected=dict(loss_lt_008=True, val_acc_ge_95=True, focuses_on_keyword=True, prenorm_preserves_skip_scale=True),
actual=dict(loss_lt_008=last_loss < 0.08, val_acc_ge_95=val_acc >= 0.95, focuses_on_keyword=mean_kw_weight > 0.5, prenorm_preserves_skip_scale=pre_std > 2.5 and abs(post_std - 1.0) < 0.15),
measurements=dict(ep1_loss=ep1_loss, ep25_loss=last_loss, val_acc=val_acc, mean_keyword_pool_weight=mean_kw_weight),
passed=c5_ok,
))
# 6. Plot real self-attention heatmap & attention-pooling keyword focus
mpl_ver = None
if fig_dir is not None:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig_dir.mkdir(parents=True, exist_ok=True)
sample_idx = 0
attn_mat = val_attn_w[sample_idx].numpy()
pool_vec = val_pool_w[sample_idx].numpy()
tok_ids = x_va[sample_idx].tolist()
labels = [f"KW({t})" if t >= 21 else ("PAD" if t == 0 else f"t{t}") for t in tok_ids]
fig, axes = plt.subplots(1, 2, figsize=(9.6, 3.8), dpi=140)
im = axes[0].imshow(attn_mat, cmap="viridis", vmin=0.0, vmax=max(0.35, float(attn_mat.max())))
axes[0].set_title("Self-Attention Weights (Sample 0)", fontsize=10)
axes[0].set_xticks(range(len(labels)))
axes[0].set_xticklabels(labels, rotation=45, ha="right", fontsize=7)
axes[0].set_yticks(range(len(labels)))
axes[0].set_yticklabels(labels, fontsize=7)
fig.colorbar(im, ax=axes[0], fraction=0.046, pad=0.04)
colors = ["#ae511d" if t >= 21 else ("#cbd5e1" if t == 0 else "#174d79") for t in tok_ids]
axes[1].bar(range(len(labels)), pool_vec, color=colors)
axes[1].set_title(f"Attention Pooling Focus (Mean KW Weight {mean_kw_weight:.2f})", fontsize=10)
axes[1].set_xticks(range(len(labels)))
axes[1].set_xticklabels(labels, rotation=45, ha="right", fontsize=7)
axes[1].set_ylabel("Pool Weight")
axes[1].set_ylim(0, 1.05)
axes[1].grid(True, axis="y", alpha=0.3)
fig.tight_layout()
out_png = fig_dir / "attention-weights-heatmap.png"
fig.savefig(out_png)
plt.close(fig)
figures["attention-weights-heatmap.png"] = sha(out_png)
mpl_ver = matplotlib.__version__
cases.append(dict(
name="observed_attention_heatmap_plot",
inputs=dict(sample_seq_len=10),
prerequisites="留出验证样本的自注意力权重矩阵与注意力池化分布",
action="输出自注意力热力图与关键词聚焦柱状图。",
expected=dict(seq_len_plotted=10),
actual=dict(seq_len_plotted=int(val_attn_w.shape[-1])),
measurements=dict(figure_generated="attention-weights-heatmap.png" in figures),
passed=int(val_attn_w.shape[-1]) == 10,
))
payload = dict(version=platform.python_version(), torch=torch.__version__, system=platform.system(), cases=cases)
if mpl_ver:
payload["matplotlib"] = mpl_ver
payload["figures"] = figures
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--figures", type=Path, default=None)
args = parser.parse_args()
run_cases(args.figures)
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
入口文件:projects/pytorch-attention-lab/explore-attention-mechanisms.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-attention-mechanisms.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a408.zip