"""silab · 基础篇 05：换上 PyTorch
需要同一个文件夹里的 engine.py（第 3、4 课写的自动求导引擎）。
运行：python l05_torch.py，逐行对照注释里的应得输出（第 8 步的耗时每台电脑不同）。
"""
import sys
import time
import random
import torch
import torch.nn as nn
from engine import Value

# ═══ 第 1 步：张量 = 一整张数表，形状写在 shape 里 ═══════════
xs = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
ys = [2.0, 4.0, 6.0, 7.0, 8.0, 9.0]
X = torch.tensor(xs).reshape(6, 1)       # 6 个例子 × 1 个输入
Y = torch.tensor(ys).reshape(6, 1)       # 6 个例子 × 1 个输出
print(X.shape, Y.shape)
# 应得：torch.Size([6, 1]) torch.Size([6, 1])

# ═══ 第 2 步：第 4 课的手搭网络，改写成矩阵 ═══════════════
W1 = torch.tensor([[1.0], [1.0]])        # 2 个神经元 × 1 个输入（PyTorch 的习惯：输出 × 输入）
b1 = torch.tensor([0.0, -3.0])           # 每个神经元一个偏置
W2 = torch.tensor([[2.0, -1.0]])         # 1 个输出 × 2 个神经元
b2 = torch.tensor([0.0])
Z = X @ W1.T + b1                        # (6,1) @ (1,2) = (6,2)，再加 (2,)
H = torch.relu(Z)                        # 逐格折一下，形状不变
Yhat = H @ W2.T + b2                     # (6,2) @ (2,1) = (6,1)
print(Z.T)
print(H.T)
print(Yhat.T)
# 应得：tensor([[ 1.,  2.,  3.,  4.,  5.,  6.],
#               [-2., -1.,  0.,  1.,  2.,  3.]])
# 应得：tensor([[1., 2., 3., 4., 5., 6.],
#               [0., 0., 0., 1., 2., 3.]])
# 应得：tensor([[2., 4., 6., 7., 8., 9.]])

# ═══ 第 3 步：广播，以及它最常见的坑 ══════════════════════
print((X @ W1.T).shape, b1.shape, Z.shape)
# 应得：torch.Size([6, 2]) torch.Size([2]) torch.Size([6, 2])
y_flat = torch.tensor(ys)                # 形状 (6,)，少了一维
print((Yhat - Y).shape, (Yhat - y_flat).shape)
print(((Yhat - Y) ** 2).mean().item(), ((Yhat - y_flat) ** 2).mean().item())
# 应得：torch.Size([6, 1]) torch.Size([6, 6])
# 应得：0.0 11.333333015441895      ← 模型明明全对，损失却不是 0：(6,1) 和 (6,) 被广播成了 6×6

# ═══ 第 4 步：nn.Linear 里面就是 x @ W.T + b ══════════════
lin = nn.Linear(1, 2)
print(lin.weight.shape, lin.bias.shape)
with torch.no_grad():
    lin.weight.copy_(W1)
    lin.bias.copy_(b1)
print(torch.equal(lin(X), X @ W1.T + b1))
# 应得：torch.Size([2, 1]) torch.Size([2])
# 应得：True

# ═══ 第 5 步：自己写 Linear 和网络（继承 nn.Module）═══════════
class MyLinear(nn.Module):
    def __init__(self, n_in, n_out):
        super().__init__()
        k = 1 / n_in ** 0.5               # 和 nn.Linear 一样的初始化范围
        self.weight = nn.Parameter(torch.empty(n_out, n_in).uniform_(-k, k))
        self.bias = nn.Parameter(torch.empty(n_out).uniform_(-k, k))
    def forward(self, x):
        return x @ self.weight.T + self.bias

class MyMLP(nn.Module):
    def __init__(self, n_in, n_hidden, n_out):
        super().__init__()
        self.l1 = MyLinear(n_in, n_hidden)
        self.l2 = MyLinear(n_hidden, n_out)
    def forward(self, x):
        return self.l2(torch.relu(self.l1(x)))

net = MyMLP(1, 8, 1)
for name, p in net.named_parameters():
    print(name, tuple(p.shape))
print("旋钮个数：", sum(p.numel() for p in net.parameters()))
# 应得：l1.weight (8, 1) / l1.bias (8,) / l2.weight (1, 8) / l2.bias (1,)
# 应得：旋钮个数： 25

# ═══ 第 6 步：自己写优化器，和 torch.optim.SGD 逐步对数 ══════
class MySGD:
    def __init__(self, params, lr):
        self.params = list(params)
        self.lr = lr
    def zero_grad(self):
        for p in self.params:
            p.grad = None                 # 清空上一步攒下的梯度
    def step(self):
        with torch.no_grad():
            for p in self.params:
                p -= self.lr * p.grad     # 第 1 课的那一行，对每个参数做一遍

torch.manual_seed(0)
ref = nn.Sequential(nn.Linear(1, 8), nn.ReLU(), nn.Linear(8, 1))
mine = MyMLP(1, 8, 1)
with torch.no_grad():                     # 初始旋钮复制成一模一样
    mine.l1.weight.copy_(ref[0].weight); mine.l1.bias.copy_(ref[0].bias)
    mine.l2.weight.copy_(ref[2].weight); mine.l2.bias.copy_(ref[2].bias)
Xc = X - 3.5                              # 和第 4 课一样，先中心化
opt_ref = torch.optim.SGD(ref.parameters(), lr=0.03)
opt_mine = MySGD(mine.parameters(), lr=0.03)
for step in range(3001):
    l_ref = ((ref(Xc) - Y) ** 2).mean()
    l_mine = ((mine(Xc) - Y) ** 2).mean()
    if step in (0, 10, 100, 1000, 3000):
        print(f"第 {step:4d} 步  官方零件 = {l_ref.item():.6f}  自己写的 = {l_mine.item():.6f}")
    opt_ref.zero_grad(); l_ref.backward(); opt_ref.step()
    opt_mine.zero_grad(); l_mine.backward(); opt_mine.step()
# 应得：第 0 步两边都是 39.033100，第 3000 步都是 0.000061，和第 4 课一样（中间偶尔最后一位差 1）

# ═══ 第 7 步：忘了 zero_grad 会怎样 ═════════════════════════
w = torch.tensor(0.0, requires_grad=True)
for i in range(3):
    loss = ((w * X - Y) ** 2).mean()      # w 不变，每次算出的梯度都一样
    loss.backward()                       # 没有清零：梯度一次次累加
    print(f"第 {i + 1} 次 backward 后 w.grad = {w.grad.item():.4f}")
# 应得：-50.0000 / -100.0000 / -150.0000

# ═══ 第 8 步：快多少？同一个网络，100 张手写数字，前向 + 反向一次 ══
random.seed(0)
torch.manual_seed(0)
N, D, Hn, K = 100, 64, 32, 10
Xb = torch.rand(N, D)
Yb = torch.rand(N, K)
big = MyMLP(D, Hn, K)

t0 = time.perf_counter()
loss = ((big(Xb) - Yb) ** 2).mean()
loss.backward()
t_torch = time.perf_counter() - t0

Wa, ba = big.l1.weight.tolist(), big.l1.bias.tolist()
Wb, bb = big.l2.weight.tolist(), big.l2.bias.tolist()
P1 = [[Value(v) for v in row] for row in Wa]; q1 = [Value(v) for v in ba]
P2 = [[Value(v) for v in row] for row in Wb]; q2 = [Value(v) for v in bb]
sys.setrecursionlimit(100000)              # 图太深，引擎递归排序会超过 Python 默认的 1000 层
t0 = time.perf_counter()
total = Value(0.0)
for x, y in zip(Xb.tolist(), Yb.tolist()):
    h = [sum((w * xi for w, xi in zip(row, x)), b).relu() for row, b in zip(P1, q1)]
    for row, b, yk in zip(P2, q2, y):
        out = sum((w * hi for w, hi in zip(row, h)), b)
        total = total + (out - yk) ** 2
total = total / (N * K)
total.backward()
t_engine = time.perf_counter() - t0
print(f"损失：PyTorch {loss.item():.6f}  自己的引擎 {total.data:.6f}")
print(f"梯度对得上：{abs(big.l1.weight.grad[0, 0].item() - P1[0][0].grad) < 1e-6}")
print(f"耗时：自己的引擎 {t_engine:.2f} 秒，PyTorch {t_torch * 1000:.1f} 毫秒")
# 应得：两边损失相同（小数点后 6 位），梯度对得上：True
# 耗时每台电脑不同；作者的电脑上引擎约 4 秒，PyTorch 不到 1 毫秒，差几千倍
