"""Independent pure-NumPy & Matplotlib lab for Attention Mechanism (Ch 12)."""
import argparse
import hashlib
import json
import platform
from pathlib import Path
import numpy as np
def sha(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def softmax(x: np.ndarray, axis: int = -1) -> np.ndarray:
shifted = x - np.max(x, axis=axis, keepdims=True)
ex = np.exp(shifted)
return ex / np.sum(ex, axis=axis, keepdims=True)
def scaled_dot_product_attention(q: np.ndarray, k: np.ndarray, v: np.ndarray, mask: np.ndarray | None = None, scale: bool = True):
d_k = q.shape[-1]
scores = np.matmul(q, np.swapaxes(k, -2, -1))
if scale:
scores = scores / np.sqrt(float(d_k))
if mask is not None:
scores = np.where(mask, scores, -1e9)
weights = softmax(scores, axis=-1)
output = np.matmul(weights, v)
return output, weights, scores
def shannon_entropy(probs: np.ndarray) -> float:
p = np.clip(probs, 1e-12, 1.0)
return float(np.mean(-np.sum(p * np.log(p), axis=-1)))
def run_cases(fig_dir: Path | None):
cases = []
figures = {}
rng = np.random.default_rng(42)
# 1. Scaled Dot-Product Attention & Softmax Saturation Control
seq_len = 8
q_small = rng.normal(0.0, 1.0, size=(1, seq_len, 4))
k_small = rng.normal(0.0, 1.0, size=(1, seq_len, 4))
v_small = rng.normal(0.0, 1.0, size=(1, seq_len, 4))
out_s, w_s, _ = scaled_dot_product_attention(q_small, k_small, v_small, scale=True)
row_sum_err = float(np.max(np.abs(np.sum(w_s, axis=-1) - 1.0)))
# Compare variance & entropy at large d_k=256 (scaled vs unscaled)
d_large = 256
q_big = rng.normal(0.0, 1.0, size=(64, seq_len, d_large))
k_big = rng.normal(0.0, 1.0, size=(64, seq_len, d_large))
v_big = rng.normal(0.0, 1.0, size=(64, seq_len, d_large))
_, w_unscaled, sc_unscaled = scaled_dot_product_attention(q_big, k_big, v_big, scale=False)
_, w_scaled, sc_scaled = scaled_dot_product_attention(q_big, k_big, v_big, scale=True)
var_unscaled = float(np.var(sc_unscaled))
var_scaled = float(np.var(sc_scaled))
ent_unscaled = shannon_entropy(w_unscaled)
ent_scaled = shannon_entropy(w_scaled)
max_w_unscaled = float(np.mean(np.max(w_unscaled, axis=-1)))
max_w_scaled = float(np.mean(np.max(w_scaled, axis=-1)))
c1_ok = (
out_s.shape == (1, seq_len, 4)
and row_sum_err < 1e-12
and var_scaled < var_unscaled / 100.0
and ent_scaled > ent_unscaled * 2.0
)
cases.append(dict(
name="scaled_dot_product_and_saturation",
inputs=dict(seq_len=seq_len, d_k_small=4, d_k_large=d_large, batch_for_stats=64),
prerequisites="固定随机种子构造标准正态 Q/K/V,分别计算 d_k=4 与 d_k=256 下未缩放与 1/sqrt(d_k) 缩放点积注意力。",
action="验证权重行和精确为 1,以及在高维 d_k=256 下缩放因子防止得分方差膨胀与 Softmax 饱和。",
expected=dict(row_sums_one=True, variance_controlled=True, entropy_preserved=True),
actual=dict(
row_sums_one=row_sum_err < 1e-12,
variance_controlled=var_scaled < var_unscaled / 100.0,
entropy_preserved=ent_scaled > ent_unscaled * 2.0,
),
measurements=dict(
row_sum_max_err=float(f"{row_sum_err:.2e}"),
score_var_unscaled_d256=round(var_unscaled, 2),
score_var_scaled_d256=round(var_scaled, 4),
entropy_unscaled_d256=round(ent_unscaled, 4),
entropy_scaled_d256=round(ent_scaled, 4),
mean_peak_weight_unscaled=round(max_w_unscaled, 4),
mean_peak_weight_scaled=round(max_w_scaled, 4),
),
passed=c1_ok,
))
# 2. Multi-Head Attention (correct transpose vs missing-transpose bug check)
batch, L, d_model, num_heads = 2, 6, 16, 4
d_k = d_model // num_heads
x = rng.normal(0.0, 1.0, size=(batch, L, d_model))
wq = rng.normal(0.0, 0.35, size=(d_model, d_model))
wk = rng.normal(0.0, 0.35, size=(d_model, d_model))
wv = rng.normal(0.0, 0.35, size=(d_model, d_model))
wo = rng.normal(0.0, 0.35, size=(d_model, d_model))
# Correct MHA: reshape (B, L, H, d_k) -> transpose (B, H, L, d_k)
q_proj = (x @ wq).reshape(batch, L, num_heads, d_k).transpose(0, 2, 1, 3)
k_proj = (x @ wk).reshape(batch, L, num_heads, d_k).transpose(0, 2, 1, 3)
v_proj = (x @ wv).reshape(batch, L, num_heads, d_k).transpose(0, 2, 1, 3)
mha_head_out, mha_weights, _ = scaled_dot_product_attention(q_proj, k_proj, v_proj, scale=True)
concat = mha_head_out.transpose(0, 2, 1, 3).reshape(batch, L, d_model)
mha_out = concat @ wo
# Demonstrate bug when transpose(1,2) before matmul is omitted (source Code 2 pitfall)
q_bug = (x @ wq).reshape(batch, L, num_heads, d_k)
k_bug = (x @ wk).reshape(batch, L, num_heads, d_k)
bug_scores = np.matmul(q_bug, np.swapaxes(k_bug, -2, -1)) / np.sqrt(float(d_k))
# Pairwise diversity across the 4 heads on sample 0
head_diffs = [
float(np.mean(np.abs(mha_weights[0, i] - mha_weights[0, j])))
for i in range(num_heads)
for j in range(i + 1, num_heads)
]
mean_head_diff = float(np.mean(head_diffs))
c2_ok = (
mha_out.shape == (batch, L, d_model)
and mha_weights.shape == (batch, num_heads, L, L)
and bug_scores.shape == (batch, L, num_heads, num_heads)
and mean_head_diff > 0.02
)
cases.append(dict(
name="multi_head_attention_shape_and_subspaces",
inputs=dict(batch=batch, seq_len=L, d_model=d_model, num_heads=num_heads, d_k=d_k),
prerequisites="构造 4 头并行线性投影矩阵,在注意力前将 (B, L, H, d_k) 转置为 (B, H, L, d_k) 再拼接输出。",
action="验证正确多头注意力的权重形状 (B, H, L, L)、头间模式分化,以及遗漏转置时产生的错误得分形状。",
expected=dict(output_shape_matches=True, weights_per_head_seq_x_seq=True, bug_omitting_transpose_detected=True, heads_diverse=True),
actual=dict(
output_shape_matches=mha_out.shape == (batch, L, d_model),
weights_per_head_seq_x_seq=mha_weights.shape == (batch, num_heads, L, L),
bug_omitting_transpose_detected=bug_scores.shape == (batch, L, num_heads, num_heads),
heads_diverse=mean_head_diff > 0.02,
),
measurements=dict(
output_shape=list(mha_out.shape),
correct_weight_shape=list(mha_weights.shape),
missing_transpose_score_shape=list(bug_scores.shape),
mean_inter_head_l1_diff=round(mean_head_diff, 4),
),
passed=c2_ok,
))
# 3. Variants: Bahdanau Additive (mismatched dims), Causal Mask, Local/Sparse Window, SimpleAttention Pooling
# (a) Bahdanau additive attention: query dim=6, key dim=10, hidden=8
q_add = rng.normal(0.0, 1.0, size=(1, 6))
k_add = rng.normal(0.0, 1.0, size=(7, 10))
v_add = rng.normal(0.0, 1.0, size=(7, 12))
w1 = rng.normal(0.0, 0.5, size=(6, 8))
w2 = rng.normal(0.0, 0.5, size=(10, 8))
v_vec = rng.normal(0.0, 0.5, size=(8, 1))
add_scores = (np.tanh(q_add @ w1 + k_add @ w2) @ v_vec).T # (1, 7)
add_weights = softmax(add_scores, axis=-1)
add_ctx = add_weights @ v_add # (1, 12)
add_sum_err = float(abs(np.sum(add_weights) - 1.0))
# (b) Causal masked self-attention on L=6
causal_mask = np.tril(np.ones((L, L), dtype=bool))
_, w_causal, _ = scaled_dot_product_attention(q_proj[0, 0], k_proj[0, 0], v_proj[0, 0], mask=causal_mask)
future_leak = float(np.max(w_causal[np.triu(np.ones((L, L), dtype=bool), k=1)]))
# (c) Local / Sliding-Window Sparse Attention (L=8, window radius=1 -> attends to at most 3 neighbors)
l_sp = 8
idx = np.arange(l_sp)
window_mask = np.abs(idx[:, None] - idx[None, :]) <= 1
q_sp = rng.normal(0.0, 1.0, size=(l_sp, 8))
k_sp = rng.normal(0.0, 1.0, size=(l_sp, 8))
v_sp = rng.normal(0.0, 1.0, size=(l_sp, 8))
_, w_sparse, _ = scaled_dot_product_attention(q_sp, k_sp, v_sp, mask=window_mask)
active_entries = int(np.sum(window_mask))
outside_window_max = float(np.max(w_sparse[~window_mask]))
sparsity_reduction = 1.0 - active_entries / float(l_sp * l_sp)
# (d) SimpleAttention sequence pooling (Exercise 1): (B=2, L=6, H=16) -> ctx (2, 16), weights (2, 6)
w_pool = rng.normal(0.0, 0.4, size=(d_model, 1))
b_pool = np.zeros((1,))
pool_scores = (x @ w_pool + b_pool).squeeze(-1) # (2, 6)
pool_weights = softmax(pool_scores, axis=-1)
pool_ctx = np.matmul(pool_weights[:, None, :], x).squeeze(1) # (2, 16)
pool_sum_err = float(np.max(np.abs(np.sum(pool_weights, axis=-1) - 1.0)))
c3_ok = (
add_ctx.shape == (1, 12)
and add_sum_err < 1e-12
and future_leak < 1e-9
and outside_window_max < 1e-9
and active_entries == 22
and pool_ctx.shape == (batch, d_model)
and pool_sum_err < 1e-12
)
cases.append(dict(
name="attention_variants_additive_causal_local_sparse",
inputs=dict(add_dq=6, add_dk=10, sparse_seq_len=l_sp, window_radius=1, pool_shape=[batch, L, d_model]),
prerequisites="分别构造异维加法注意力、GPT 风格因果掩码自注意力、半径 1 滑动窗口稀疏注意力及 SimpleAttention 序列池化。",
action="验证异维 Q/K 兼容、未来位置权重归零、窗口外稀疏置零(计算量下降 65.6%)及上下文池化形状与概率归一。",
expected=dict(additive_mismatched_dims_ok=True, causal_no_future_leak=True, sparse_window_exact=True, simple_pooling_ok=True),
actual=dict(
additive_mismatched_dims_ok=(add_ctx.shape == (1, 12) and add_sum_err < 1e-12),
causal_no_future_leak=future_leak < 1e-9,
sparse_window_exact=(outside_window_max < 1e-9 and active_entries == 22),
simple_pooling_ok=(pool_ctx.shape == (batch, d_model) and pool_sum_err < 1e-12),
),
measurements=dict(
additive_context_shape=list(add_ctx.shape),
causal_max_future_weight=float(f"{future_leak:.2e}"),
sparse_active_pairs=active_entries,
full_pairs=l_sp * l_sp,
sparse_compute_reduction_pct=round(sparsity_reduction * 100.0, 2),
simple_attention_context_shape=list(pool_ctx.shape),
),
passed=c3_ok,
))
# 4. Cross-Attention Alignment Heatmap (Exercise 2: EN -> FR tokens, row-normalized!) + Matplotlib PNG
source_tokens = ["The", "cat", "sat", "on", "the", "mat"]
target_tokens = ["Le", "chat", "s'est", "assis", "sur", "le", "tapis"]
# Build deterministic semantic concept space (6 latent concepts: det1, feline, sit, prep, det2, rug)
src_emb = np.array([
[2.2, 0.2, 0.0, 0.1, 0.6, 0.0], # The
[0.1, 2.5, 0.2, 0.0, 0.0, 0.2], # cat
[0.0, 0.2, 2.4, 0.3, 0.0, 0.1], # sat
[0.0, 0.0, 0.3, 2.3, 0.2, 0.3], # on
[0.5, 0.0, 0.0, 0.2, 2.2, 0.3], # the
[0.0, 0.2, 0.1, 0.2, 0.2, 2.6], # mat
], dtype=float)
tgt_emb = np.array([
[2.3, 0.3, 0.0, 0.0, 0.4, 0.0], # Le
[0.2, 2.6, 0.1, 0.0, 0.0, 0.1], # chat
[0.0, 0.3, 2.1, 0.2, 0.0, 0.0], # s'est
[0.0, 0.2, 2.5, 0.3, 0.0, 0.1], # assis
[0.0, 0.0, 0.2, 2.5, 0.2, 0.2], # sur
[0.4, 0.0, 0.0, 0.2, 2.3, 0.3], # le
[0.0, 0.1, 0.1, 0.2, 0.3, 2.6], # tapis
], dtype=float)
_, cross_weights, _ = scaled_dot_product_attention(tgt_emb, src_emb, src_emb, scale=True)
cross_row_err = float(np.max(np.abs(np.sum(cross_weights, axis=-1) - 1.0)))
aligned_pairs = {
target_tokens[i]: source_tokens[int(np.argmax(cross_weights[i]))]
for i in range(len(target_tokens))
}
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)
fig, axes = plt.subplots(1, 2, figsize=(10.2, 4.2), dpi=140)
im0 = axes[0].imshow(cross_weights, cmap="YlGnBu", vmin=0.0, vmax=1.0, aspect="auto")
axes[0].set_xticks(range(len(source_tokens)))
axes[0].set_xticklabels(source_tokens, fontsize=9)
axes[0].set_yticks(range(len(target_tokens)))
axes[0].set_yticklabels(target_tokens, fontsize=9)
axes[0].set_xlabel("Source Tokens (EN)")
axes[0].set_ylabel("Target Tokens (FR)")
axes[0].set_title("Cross-Attention Weights (Row Softmax)", fontsize=10)
for i in range(len(target_tokens)):
for j in range(len(source_tokens)):
val = cross_weights[i, j]
axes[0].text(j, i, f"{val:.2f}", ha="center", va="center",
color="white" if val > 0.5 else "#1a1a1a", fontsize=7.5)
fig.colorbar(im0, ax=axes[0], fraction=0.046, pad=0.04)
im1 = axes[1].imshow(w_causal, cmap="Blues", vmin=0.0, vmax=1.0, aspect="auto")
axes[1].set_xticks(range(L))
axes[1].set_xticklabels([f"t{k}" for k in range(L)], fontsize=9)
axes[1].set_yticks(range(L))
axes[1].set_yticklabels([f"t{k}" for k in range(L)], fontsize=9)
axes[1].set_xlabel("Key Position")
axes[1].set_ylabel("Query Position")
axes[1].set_title("Causal Masked Self-Attention (Lower Tri)", fontsize=10)
for i in range(L):
for j in range(L):
val = w_causal[i, j]
axes[1].text(j, i, f"{val:.2f}", ha="center", va="center",
color="white" if val > 0.5 else "#1a1a1a", fontsize=7.5)
fig.colorbar(im1, ax=axes[1], fraction=0.046, pad=0.04)
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__
c4_ok = (
cross_row_err < 1e-12
and aligned_pairs["chat"] == "cat"
and aligned_pairs["assis"] == "sat"
and aligned_pairs["sur"] == "on"
and aligned_pairs["tapis"] == "mat"
)
cases.append(dict(
name="observed_attention_heatmap_plot",
inputs=dict(source_len=len(source_tokens), target_len=len(target_tokens)),
prerequisites="以缩放点积 Softmax 计算英法句对交叉注意力矩阵(保证每行权重和为 1),并同步绘制因果掩码自注意力热力图。",
action="核对目标词准确对齐对应源词(chat->cat、assis->sat、sur->on、tapis->mat)且双联图正常导出。",
expected=dict(row_normalized=True, semantic_alignment_correct=True),
actual=dict(
row_normalized=cross_row_err < 1e-12,
semantic_alignment_correct=(
aligned_pairs["chat"] == "cat"
and aligned_pairs["assis"] == "sat"
and aligned_pairs["sur"] == "on"
and aligned_pairs["tapis"] == "mat"
),
),
measurements=dict(
chat_to_cat_weight=round(float(cross_weights[1, 1]), 4),
tapis_to_mat_weight=round(float(cross_weights[6, 5]), 4),
aligned_pairs=aligned_pairs,
figure_generated="attention-weights-heatmap.png" in figures,
),
passed=c4_ok,
))
payload = dict(
version=platform.python_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 x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。
入口文件:projects/nlp-attention-mechanism-lab/explore-attention-mechanism.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-attention-mechanism.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a545.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a544.zip