"""Compute the source arithmetic and observe independent attention and training cases."""
from fractions import Fraction
from math import exp, sqrt
import torch
from torch.nn.functional import scaled_dot_product_attention
from lab_tools import run_exercise
def affine(inputs, weights, bias):
return sum(a * b for a, b in zip(inputs, weights, strict=True)) + bias
def exercise(checks, workspace):
expect = checks.expect
x = list(map(Fraction, ("0.8", "0.9", "0.7")))
w = list(map(Fraction, ("0.5", "0.4", "0.3")))
source = affine(x, w, Fraction("-0.6"))
expect("ai_works_source_relu", [["0.8", "0.9", "0.7"], ["0.5", "0.4", "0.3"], "-0.6"],
"Use exact rational arithmetic and compare the stated weighted sum with ReLU output",
["37/100", "0.370"], [str(source), f"{float(max(0, source)):.3f}"])
expect("ai_works_relu_branches", [-3, 0, 3], "Apply ReLU to negative, zero, and positive affine values",
[0, 0, 3], [max(0, affine([value], [1], 0)) for value in (-3, 0, 3)])
try:
affine([1, 2], [3], 0)
except ValueError as exc:
invalid = type(exc).__name__
else:
invalid = None
expect("ai_works_shape_mismatch", [[1, 2], [3]],
"Reject length mismatch instead of truncating the inputs", "ValueError", invalid)
q = torch.tensor([[[1., 0.]]], dtype=torch.float64)
k = torch.tensor([[[1., 0.], [0., 1.]]], dtype=torch.float64)
v = torch.tensor([[[2.], [8.]]], dtype=torch.float64)
e = exp(1 / sqrt(2))
expected = (e * 2 + 8) / (e + 1)
unmasked = scaled_dot_product_attention(q, k, v, dropout_p=0).item()
masked = scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=0).item()
expect("ai_works_attention", {"Q": [1, 0], "K": [[1, 0], [0, 1]], "V": [2, 8]},
"Run scaled dot product with and without the causal mask",
[round(expected, 8), 2], [round(unmasked, 8), masked])
model = torch.nn.Linear(1, 1, bias=False, dtype=torch.float64)
with torch.no_grad():
model.weight.zero_()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
inputs = torch.tensor([[1.], [2.]], dtype=torch.float64)
targets = 2 * inputs
loss = torch.nn.MSELoss()
initial = loss(model(inputs), targets)
optimizer.zero_grad()
initial.backward()
gradient = model.weight.grad.item()
optimizer.step()
weight = model.weight.item()
later = loss(model(inputs), targets).item()
expect("ai_works_training", [[1, 2], [2, 4], 0.1], "Backpropagate and run one actual SGD update",
[10, -10, 1, 2.5], [initial.item(), gradient, weight, later])
model.eval()
with torch.inference_mode():
prediction = model(torch.tensor([[3.]], dtype=torch.float64)).item()
expect("ai_works_inference", 3, "Run inference and compare parameter before and after",
[3, 1, 1], [prediction, weight, model.weight.item()])
if __name__ == "__main__":
run_exercise(exercise)
本例需在 Python 3.12.14,PyTorch 2.10.0 CPU,分数精确计算与固定的五条短语。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Python 3.12.14,PyTorch 2.10.0 CPU,分数精确计算与固定的五条短语。
入口文件:projects/ai-how-works/how_works.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
how_works.py,或下载右侧课程工程包。 - 确认本地已准备 Python 3.12.14,PyTorch 2.10.0 CPU,分数精确计算与固定的五条短语。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联30章) · 含当前章节或实例 · mbskycom202612a5.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a13.zip