"""Independent pure-NumPy & Matplotlib lab for Transformer Architecture (Ch 13)."""
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 layer_norm(x: np.ndarray, eps: float = 1e-5) -> np.ndarray:
mean = np.mean(x, axis=-1, keepdims=True)
var = np.var(x, axis=-1, keepdims=True)
return (x - mean) / np.sqrt(var + eps)
def scaled_dot_product_attention(q: np.ndarray, k: np.ndarray, v: np.ndarray, mask: np.ndarray | None = None):
d_k = q.shape[-1]
scores = np.matmul(q, np.swapaxes(k, -2, -1)) / np.sqrt(float(d_k))
if mask is not None:
scores = np.where(mask == 0, -1e9, scores)
weights = softmax(scores, axis=-1)
return np.matmul(weights, v), weights
def sinusoidal_positional_encoding(max_len: int, d_model: int) -> np.ndarray:
pos = np.arange(max_len, dtype=float)[:, None]
div_term = np.exp(np.arange(0, d_model, 2, dtype=float) * (-np.log(10000.0) / d_model))
pe = np.zeros((max_len, d_model), dtype=float)
pe[:, 0::2] = np.sin(pos * div_term)
pe[:, 1::2] = np.cos(pos * div_term)
return pe
def multi_head_attention(q_in, k_in, v_in, wq, wk, wv, wo, num_heads, mask=None):
b, lq, d_model = q_in.shape
lk = k_in.shape[1]
d_k = d_model // num_heads
q = (q_in @ wq).reshape(b, lq, num_heads, d_k).transpose(0, 2, 1, 3)
k = (k_in @ wk).reshape(b, lk, num_heads, d_k).transpose(0, 2, 1, 3)
v = (v_in @ wv).reshape(b, lk, num_heads, d_k).transpose(0, 2, 1, 3)
out, weights = scaled_dot_product_attention(q, k, v, mask=mask)
concat = out.transpose(0, 2, 1, 3).reshape(b, lq, d_model)
return concat @ wo, weights
def run_cases(fig_dir: Path | None):
cases = []
figures = {}
rng = np.random.default_rng(2017)
# 1. Scaled Dot-Product Attention & Causal Mask Anti-Cheat Verification
l_seq, d_k = 5, 16
q = rng.normal(0.0, 1.0, size=(1, l_seq, d_k))
k = rng.normal(0.0, 1.0, size=(1, l_seq, d_k))
v = rng.normal(0.0, 1.0, size=(1, l_seq, d_k))
causal_mask = np.tril(np.ones((l_seq, l_seq), dtype=int))
out_orig, w_causal = scaled_dot_product_attention(q, k, v, mask=causal_mask)
# Perturb future positions (t=3, 4) drastically and check positions 0..2 stay bit-identical
q_pert, k_pert, v_pert = q.copy(), k.copy(), v.copy()
q_pert[:, 3:, :] += 50.0
k_pert[:, 3:, :] -= 40.0
v_pert[:, 3:, :] += 100.0
out_pert, _ = scaled_dot_product_attention(q_pert, k_pert, v_pert, mask=causal_mask)
prefix_diff = float(np.max(np.abs(out_orig[:, :3, :] - out_pert[:, :3, :])))
future_weight_max = float(np.max(w_causal[0][causal_mask == 0]))
c1_ok = prefix_diff < 1e-12 and future_weight_max < 1e-9
cases.append(dict(
name="scaled_attention_and_causal_mask",
inputs=dict(seq_len=l_seq, d_k=d_k, perturbed_future_start=3),
prerequisites="按练习 1 公式实现带下三角掩码(mask==0 置 -1e9)的缩放点积注意力。",
action="大幅扰动未来位置 t>=3 的输入张量,核对前序位置 0..2 输出变化与上三角权重。",
expected=dict(future_weights_zero=True, zero_future_information_leakage=True),
actual=dict(future_weights_zero=future_weight_max < 1e-9, zero_future_information_leakage=prefix_diff < 1e-12),
measurements=dict(
max_future_weight=float(f"{future_weight_max:.2e}"),
prefix_max_abs_diff=float(f"{prefix_diff:.2e}"),
),
passed=c1_ok,
))
# 2. Sinusoidal Positional Encoding: exact bounds, relative-offset rotation, extrapolation
d_model = 64
pe_256 = sinusoidal_positional_encoding(256, d_model)
pos0_even_err = float(np.max(np.abs(pe_256[0, 0::2] - 0.0)))
pos0_odd_err = float(np.max(np.abs(pe_256[0, 1::2] - 1.0)))
# Verify exact relative-position linear rotation PE(pos + k) = R(k) * PE(pos) for offset k=7
offset_k = 7
div_term = np.exp(np.arange(0, d_model, 2, dtype=float) * (-np.log(10000.0) / d_model))
max_rot_err = 0.0
for pos in (0, 5, 19, 120, 200):
pred = np.zeros(d_model, dtype=float)
c_k = np.cos(offset_k * div_term)
s_k = np.sin(offset_k * div_term)
pred[0::2] = c_k * pe_256[pos, 0::2] + s_k * pe_256[pos, 1::2]
pred[1::2] = -s_k * pe_256[pos, 0::2] + c_k * pe_256[pos, 1::2]
max_rot_err = max(max_rot_err, float(np.max(np.abs(pred - pe_256[pos + offset_k]))))
# Cosine similarity decays smoothly with local distance (pos=10 vs pos=11 > pos=15 > pos=25)
pe_norm = pe_256[:50] / np.linalg.norm(pe_256[:50], axis=-1, keepdims=True)
sim_mat = pe_norm @ pe_norm.T
sim_d1 = float(sim_mat[10, 11])
sim_d5 = float(sim_mat[10, 15])
sim_d15 = float(sim_mat[10, 25])
c2_ok = (
pos0_even_err < 1e-12
and pos0_odd_err < 1e-12
and max_rot_err < 1e-11
and sim_d1 > sim_d5 > sim_d15
)
cases.append(dict(
name="sinusoidal_positional_encoding_properties",
inputs=dict(d_model=d_model, max_len=256, relative_offset_k=offset_k),
prerequisites="依据正弦/余弦偶奇维公式生成长度 256、维度 64 的位置编码矩阵。",
action="验证 pos=0 初值、任意绝对位置按固定偏移 k=7 的线性旋转恒等式,以及近邻余弦相似度单调衰减。",
expected=dict(pos0_exact=True, relative_linear_transform_exact=True, local_similarity_decays=True),
actual=dict(
pos0_exact=(pos0_even_err < 1e-12 and pos0_odd_err < 1e-12),
relative_linear_transform_exact=max_rot_err < 1e-11,
local_similarity_decays=(sim_d1 > sim_d5 > sim_d15),
),
measurements=dict(
pe_min=round(float(np.min(pe_256)), 4),
pe_max=round(float(np.max(pe_256)), 4),
relative_rotation_max_err=float(f"{max_rot_err:.2e}"),
cos_sim_dist1=round(sim_d1, 4),
cos_sim_dist5=round(sim_d5, 4),
cos_sim_dist15=round(sim_d15, 4),
),
passed=c2_ok,
))
# 3. Full Encoder-Decoder Block Forward: MHA + Cross-Attention + ReLU FFN + Residual + LayerNorm + Vocab Linear
b, src_len, tgt_len, dm, nh, d_ff, vocab = 1, 6, 4, 32, 4, 64, 20
src_x = rng.normal(0.0, 1.0, size=(b, src_len, dm)) + sinusoidal_positional_encoding(src_len, dm)[None, :, :]
tgt_x = rng.normal(0.0, 1.0, size=(b, tgt_len, dm)) + sinusoidal_positional_encoding(tgt_len, dm)[None, :, :]
def rand_w(r, c):
return rng.normal(0.0, np.sqrt(2.0 / (r + c)), size=(r, c))
# Encoder block
e_wq, e_wk, e_wv, e_wo = [rand_w(dm, dm) for _ in range(4)]
e_w1, e_b1, e_w2, e_b2 = rand_w(dm, d_ff), np.zeros(d_ff), rand_w(d_ff, dm), np.zeros(dm)
enc_attn, _ = multi_head_attention(src_x, src_x, src_x, e_wq, e_wk, e_wv, e_wo, nh)
enc_h1 = layer_norm(src_x + enc_attn)
enc_ffn = np.maximum(0.0, enc_h1 @ e_w1 + e_b1) @ e_w2 + e_b2
enc_out = layer_norm(enc_h1 + enc_ffn)
# Decoder block (Masked Self-Attn -> Cross-Attn -> FFN -> Vocab Linear + Softmax)
d_sq, d_sk, d_sv, d_so = [rand_w(dm, dm) for _ in range(4)]
d_cq, d_ck, d_cv, d_co = [rand_w(dm, dm) for _ in range(4)]
d_w1, d_b1, d_w2, d_b2 = rand_w(dm, d_ff), np.zeros(d_ff), rand_w(d_ff, dm), np.zeros(dm)
w_vocab = rand_w(dm, vocab)
dec_mask = np.tril(np.ones((tgt_len, tgt_len), dtype=int))
def run_decoder(t_in, memory):
self_a, _ = multi_head_attention(t_in, t_in, t_in, d_sq, d_sk, d_sv, d_so, nh, mask=dec_mask)
h1 = layer_norm(t_in + self_a)
cross_a, cw = multi_head_attention(h1, memory, memory, d_cq, d_ck, d_cv, d_co, nh)
h2 = layer_norm(h1 + cross_a)
ffn = np.maximum(0.0, h2 @ d_w1 + d_b1) @ d_w2 + d_b2
h3 = layer_norm(h2 + ffn)
probs = softmax(h3 @ w_vocab, axis=-1)
return h3, probs, cw
dec_out, vocab_probs, cross_w = run_decoder(tgt_x, enc_out)
# Check LayerNorm zero-mean / unit-std
ln_mean_err = float(np.max(np.abs(np.mean(dec_out, axis=-1))))
ln_std_err = float(np.max(np.abs(np.std(dec_out, axis=-1) - 1.0)))
# Check Cross-Attention sensitivity to encoder memory
dec_out_mem2, _, _ = run_decoder(tgt_x, enc_out + 1.5)
mem_effect = float(np.mean(np.abs(dec_out - dec_out_mem2)))
prob_sum_err = float(np.max(np.abs(np.sum(vocab_probs, axis=-1) - 1.0)))
c3_ok = (
enc_out.shape == (b, src_len, dm)
and dec_out.shape == (b, tgt_len, dm)
and vocab_probs.shape == (b, tgt_len, vocab)
and cross_w.shape == (b, nh, tgt_len, src_len)
and ln_mean_err < 1e-6
and ln_std_err < 1e-3
and mem_effect > 0.05
and prob_sum_err < 1e-12
)
cases.append(dict(
name="encoder_decoder_block_forward_and_layernorm",
inputs=dict(src_len=src_len, tgt_len=tgt_len, d_model=dm, num_heads=nh, d_ff=d_ff, vocab_size=vocab),
prerequisites="纯 NumPy 搭建完整 Transformer 编码器块、解码器块(含掩码自注意力与交叉注意力)及词表线性投影层。",
action="验证编码/解码输出形状、LayerNorm 均值归零与标准差近 1、交叉注意力响应编码器记忆变化以及词表概率归一。",
expected=dict(shapes_valid=True, layernorm_normalized=True, cross_attn_responds_to_encoder=True, vocab_probs_sum_one=True),
actual=dict(
shapes_valid=(enc_out.shape == (b, src_len, dm) and vocab_probs.shape == (b, tgt_len, vocab)),
layernorm_normalized=(ln_mean_err < 1e-6 and ln_std_err < 1e-3),
cross_attn_responds_to_encoder=mem_effect > 0.05,
vocab_probs_sum_one=prob_sum_err < 1e-12,
),
measurements=dict(
encoder_shape=list(enc_out.shape),
cross_attn_shape=list(cross_w.shape),
vocab_probs_shape=list(vocab_probs.shape),
layernorm_max_mean_abs=float(f"{ln_mean_err:.2e}"),
layernorm_max_std_err=float(f"{ln_std_err:.2e}"),
encoder_memory_perturbation_delta=round(mem_effect, 4),
),
passed=c3_ok,
))
# 4. O(n^2) Attention Memory Scaling vs O(n) Sequential Steps
lengths = [32, 64, 128, 256]
attn_elements = []
for n in lengths:
qn = rng.normal(0.0, 1.0, size=(n, 16))
kn = rng.normal(0.0, 1.0, size=(n, 16))
mat = qn @ kn.T
attn_elements.append(int(mat.size))
ratios = [round(attn_elements[i + 1] / attn_elements[i], 4) for i in range(len(lengths) - 1)]
c4_ok = ratios == [4.0, 4.0, 4.0] and attn_elements[-1] == 65536
cases.append(dict(
name="quadratic_memory_scaling_check",
inputs=dict(sequence_lengths=lengths),
prerequisites="在序列长度翻倍序列 32/64/128/256 上实际构造单头自注意力得分矩阵。",
action="验证序列长度每次翻倍时注意力矩阵元素数精确扩大为 4 倍,量化 O(n^2) 显存瓶颈。",
expected=dict(exact_quadratic_ratios=True, len256_elements=65536),
actual=dict(exact_quadratic_ratios=(ratios == [4.0, 4.0, 4.0]), len256_elements=attn_elements[-1]),
measurements=dict(matrix_elements_by_len=dict(zip([str(n) for n in lengths], attn_elements)), doubling_ratios=ratios),
passed=c4_ok,
))
# 5. Matplotlib PNG: Sinusoidal Positional Encoding & Position Cosine Similarity Matrix
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.0), dpi=140)
im0 = axes[0].imshow(pe_256[:50, :], cmap="RdBu", vmin=-1.0, vmax=1.0, aspect="auto")
axes[0].set_title("Sinusoidal Positional Encoding (pos=0..49, d=64)", fontsize=10)
axes[0].set_xlabel("Embedding Dimension")
axes[0].set_ylabel("Sequence Position")
fig.colorbar(im0, ax=axes[0], fraction=0.046, pad=0.04)
im1 = axes[1].imshow(sim_mat, cmap="viridis", vmin=-0.5, vmax=1.0, aspect="auto")
axes[1].set_title("Pairwise Cosine Similarity (Relative-Distance Bands)", fontsize=10)
axes[1].set_xlabel("Position j")
axes[1].set_ylabel("Position i")
fig.colorbar(im1, ax=axes[1], fraction=0.046, pad=0.04)
fig.tight_layout()
out_png = fig_dir / "transformer-positional-encoding.png"
fig.savefig(out_png)
plt.close(fig)
figures["transformer-positional-encoding.png"] = sha(out_png)
mpl_ver = matplotlib.__version__
c5_ok = sim_mat.shape == (50, 50) and float(np.max(np.abs(np.diag(sim_mat) - 1.0))) < 1e-12
cases.append(dict(
name="observed_positional_encoding_plot",
inputs=dict(plotted_positions=50, d_model=d_model),
prerequisites="使用实测位置编码矩阵与 50x50 位置余弦相似度矩阵绘制双联图(覆盖练习 2)。",
action="验证对角线自相似度精确为 1.0 并产出位置编码热力图与相对距离带状相似度图。",
expected=dict(diag_sim_one=True, matrix_shape_50x50=True),
actual=dict(
diag_sim_one=float(np.max(np.abs(np.diag(sim_mat) - 1.0))) < 1e-12,
matrix_shape_50x50=(sim_mat.shape == (50, 50)),
),
measurements=dict(figure_generated="transformer-positional-encoding.png" in figures),
passed=c5_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-transformer-architecture-lab/explore-transformer-architecture.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-transformer-architecture.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。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a564.zip
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a545.zip