"""silab · 模型篇 01：卷积，以及反过来的“转置卷积”
需要同一个文件夹里的 train.py。数据还是基础篇的手写数字（8×8）。
运行：python m01_conv.py，逐行对照注释里的应得输出（第 8 步约 10 秒）。
仅核对网页平移实验：python m01_conv.py --inspect（只用标准库，无需训练）。
"""
import sys

if "--inspect" in sys.argv:
    import json

    def inspect_shift(a, n, dx, boundary):
        out = []
        for i in range(n * n):
            row, col = divmod(i, n)
            col -= dx
            if boundary == "circular":
                col %= n
            out.append(a[row * n + col] if 0 <= col < n else 0)
        return out

    def inspect_conv(a, boundary):
        kernel = [-1, 0, 1, -1, 0, 1, -1, 0, 1]
        out = []
        for row in range(8):
            for col in range(8):
                value = 0
                for u in range(-1, 2):
                    for v in range(-1, 2):
                        r, c = row + u, col + v
                        if boundary == "circular":
                            r, c = r % 8, c % 8
                        if 0 <= r < 8 and 0 <= c < 8:
                            value += a[r * 8 + c] * kernel[(u + 1) * 3 + v + 1]
                out.append(value)
        return out

    def inspect_pool(a):
        return [max(0, a[2*r*8+2*c], a[2*r*8+2*c+1],
                    a[(2*r+1)*8+2*c], a[(2*r+1)*8+2*c+1])
                for r in range(4) for c in range(4)]

    cases = []
    for pattern in ["center", "edge"]:
        pixels = [0] * 64
        start = 2 if pattern == "center" else 6
        for r in range(2, 5):
            for c in range(start, start + 2):
                pixels[r * 8 + c] = 1
        for boundary in ["zero", "circular"]:
            for pooled in [False, True]:
                for dx in [1, 2]:
                    def transform(x):
                        y = inspect_conv(x, boundary)
                        return inspect_pool(y) if pooled else y
                    original = transform(pixels)
                    actual = transform(inspect_shift(pixels, 8, dx, boundary))
                    aligned = not pooled or dx % 2 == 0
                    n = 4 if pooled else 8
                    expected = inspect_shift(original, n, dx // 2 if pooled else dx, boundary) if aligned else original
                    differences = [abs(a-b) for a, b in zip(actual, expected)]
                    cases.append(dict(pattern=pattern, boundary=boundary, pool=pooled, dx=dx,
                                      aligned=aligned, maxDifference=max(differences),
                                      changed=sum(d > 1e-10 for d in differences),
                                      actual=actual, expected=expected))
    print(json.dumps(cases))
    sys.exit(0)

import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.datasets import load_digits
from train import fit, evaluate

d = load_digits()
X = torch.tensor(d.data / 16, dtype=torch.float32)
y = torch.tensor(d.target)
perm = torch.randperm(len(y), generator=torch.Generator().manual_seed(0))
X, y = X[perm], y[perm]
Xtr, ytr, Xte, yte = X[:1500], y[:1500], X[1500:], y[1500:]
img = lambda A: A.reshape(-1, 1, 8, 8)       # (例子数, 通道数, 高, 宽)：卷积要的形状


# ═══ 第 1 步：手算一次卷积 ═══════════════════════════════════
x = torch.tensor([[0., 0., 1., 1., 1.],
                  [0., 0., 1., 1., 1.],
                  [0., 0., 1., 1., 1.],
                  [0., 0., 1., 1., 1.],
                  [0., 0., 1., 1., 1.]])      # 左暗右亮，中间有一条竖直的边
k = torch.tensor([[-1., 0., 1.],
                  [-1., 0., 1.],
                  [-1., 0., 1.]])             # 右边减左边：找“从暗到亮”的竖边
out = F.conv2d(x.reshape(1, 1, 5, 5), k.reshape(1, 1, 3, 3))
print(out[0, 0])
# 应得：tensor([[3., 3., 0.], [3., 3., 0.], [3., 3., 0.]])   ← 竖边所在的位置是 3，平坦的地方是 0


# ═══ 第 2 步：输出有多大 ═══════════════════════════════════
for pad, stride in [(0, 1), (1, 1), (1, 2)]:
    o = F.conv2d(torch.zeros(1, 1, 8, 8), torch.zeros(1, 1, 3, 3), padding=pad, stride=stride)
    print(f"8×8 输入，3×3 卷积核，填充 {pad}，步长 {stride}：输出 {tuple(o.shape[2:])}")
# 应得：(6, 6) / (8, 8) / (4, 4)        ← 输出边长 = (n + 2p − k) / s + 1，向下取整


# ═══ 第 3 步：卷积就是一个“大部分是 0、又处处重复”的矩阵乘法 ═══
C = torch.zeros(9, 25)                        # 输出 9 格 × 输入 25 格
for r in range(3):
    for c in range(3):
        for i in range(3):
            for j in range(3):
                C[r * 3 + c, (r + i) * 5 + (c + j)] = k[i, j]
print(torch.allclose(C @ x.flatten(), out.flatten()), "矩阵里不是 0 的格子：", int((C != 0).sum()), "/ 225，但只有 9 个不同的数")
# 应得：True 矩阵里不是 0 的格子： 54 / 225，但只有 9 个不同的数
#       （卷积核里有 3 个 0，所以每行 6 个非零；全连接要 225 个旋钮，卷积只要 9 个）


# ═══ 第 4 步：卷积的反向传播，就是“转置卷积” ═══════════════════
xg = x.reshape(1, 1, 5, 5).clone().requires_grad_(True)
g = torch.tensor([[1., 0., 0.], [0., 0., 0.], [0., 0., 2.]]).reshape(1, 1, 3, 3)   # 假设损失对输出的梯度
(F.conv2d(xg, k.reshape(1, 1, 3, 3)) * g).sum().backward()
print(torch.allclose(xg.grad.flatten(), C.T @ g.flatten()),
      torch.allclose(xg.grad, F.conv_transpose2d(g, k.reshape(1, 1, 3, 3))))
print(xg.grad[0, 0])
# 应得：True True      ← 往回传梯度：乘 Cᵀ，也就是“转置卷积”
#       每个输出格子的梯度，被卷积核“盖章”盖回它当初看过的 3×3 区域：
#       左上角盖一个 1×k，右下角盖一个 2×k，重叠处相加：
#       tensor([[-1.,  0.,  1.,  0.,  0.],
#               [-1.,  0.,  1.,  0.,  0.],
#               [-1.,  0., -1.,  0.,  2.],      ← 正中间：1×(右下角的 1) + 2×(左上角的 −1) = −1
#               [ 0.,  0., -2.,  0.,  2.],
#               [ 0.,  0., -2.,  0.,  2.]])


# ═══ 第 5 步：转置卷积：从小图生成大图 ═════════════════════════
s = torch.tensor([[1., 2.], [3., 4.]]).reshape(1, 1, 2, 2)
kk = torch.ones(1, 1, 3, 3)                   # 先用全是 1 的卷积核，看清“盖章”是怎么叠起来的
big = F.conv_transpose2d(s, kk, stride=2)
print(big[0, 0])
# 应得：5×5 的图：每个输入数在大图上盖一个 3×3 的章，步长 2，相邻的章重叠一行或一列，重叠处相加
#       tensor([[ 1.,  1.,  3.,  2.,  2.],
#               [ 1.,  1.,  3.,  2.,  2.],
#               [ 4.,  4., 10.,  6.,  6.],
#               [ 3.,  3.,  7.,  4.,  4.],
#               [ 3.,  3.,  7.,  4.,  4.]])
print(F.conv_transpose2d(torch.ones(1, 1, 2, 2), kk, stride=2)[0, 0])
# 应得：中间那一行和那一列被盖了两次，正中间被盖了四次：这就是转置卷积常见的“棋盘格”痕迹的来源


# ═══ 第 6 步：卷积网络认手写数字 ══════════════════════════════
class CNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.c1 = nn.Conv2d(1, 8, 3, padding=1)     # 8 个 3×3 卷积核：8×8 → 8 张 8×8 特征图
        self.c2 = nn.Conv2d(8, 16, 3, padding=1)    # 16 个 8 通道的 3×3 卷积核
        self.fc = nn.Linear(16 * 2 * 2, 10)
    def forward(self, x):
        x = F.max_pool2d(torch.relu(self.c1(img(x))), 2)   # → (N, 8, 4, 4)
        x = F.max_pool2d(torch.relu(self.c2(x)), 2)        # → (N, 16, 2, 2)
        return self.fc(x.flatten(1))                       # → (N, 64) → (N, 10)

def shifted(A, dx):                           # 整张图往右（dx > 0）或往左挪 dx 个像素
    a, b = img(A), torch.zeros_like(img(A))
    if dx > 0: b[..., dx:] = a[..., :-dx]
    elif dx < 0: b[..., :dx] = a[..., -dx:]
    else: b = a.clone()
    return b.reshape(-1, 64)

torch.manual_seed(0)
mlp = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10))
fit(mlp, Xtr, ytr, Xte, yte, show=())
torch.manual_seed(0)
cnn = CNN()
fit(cnn, Xtr, ytr, Xte, yte, show=(), epochs=30, opt=torch.optim.Adam(cnn.parameters(), lr=3e-3))
for name, m in [("全连接", mlp), ("卷积", cnn)]:
    acc = [evaluate(m, shifted(Xte, dx), yte)[1] for dx in [0, 1, -1]]
    print(f"{name}：旋钮 {sum(p.numel() for p in m.parameters())} 个；测试准确率 {acc[0]:.3f}；整体右移 1 像素 {acc[1]:.3f}；左移 1 像素 {acc[2]:.3f}")
# 应得：全连接：旋钮 2410 个；0.970；0.478；0.438
#       卷积：  旋钮 1898 个；0.983；0.714；0.731      ← 旋钮更少、更准，挪一下也没那么怕


# ═══ 第 7 步：都在训练时见过挪动的图，再考一个没见过的“挪 2 像素” ═══
Xaug = torch.cat([shifted(Xtr, dx) for dx in [-1, 0, 1]])
yaug = ytr.repeat(3)
for name, make in [("全连接", lambda: nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10))), ("卷积", CNN)]:
    torch.manual_seed(0)
    m = make()
    fit(m, Xaug, yaug, Xte, yte, show=(), opt=torch.optim.Adam(m.parameters(), lr=3e-3))
    print(f"{name}（训练时见过挪 1 像素）：右移 2 像素 {evaluate(m, shifted(Xte, 2), yte)[1]:.3f}")
# 应得：全连接 0.566；卷积 0.747      ← 卷积核在每个位置都一样，换个位置照样认得出笔画


# ═══ 第 8 步：反过来：用转置卷积，从 2 个数生成一张 8×8 的数字 ═════
class AutoEncoder(nn.Module):
    def __init__(self, z=2):
        super().__init__()
        self.e1 = nn.Conv2d(1, 8, 3, padding=1)
        self.e2 = nn.Conv2d(8, 16, 3, padding=1)
        self.ez = nn.Linear(64, z)                                     # 压缩：64 个像素 → z 个数
        self.dz = nn.Linear(z, 64)                                     # 展开：z 个数 → 16 张 2×2
        self.d1 = nn.ConvTranspose2d(16, 8, 4, stride=2, padding=1)    # 2×2 → 4×4
        self.d2 = nn.ConvTranspose2d(8, 1, 4, stride=2, padding=1)     # 4×4 → 8×8
    def encode(self, x):
        x = F.max_pool2d(torch.relu(self.e1(img(x))), 2)
        x = F.max_pool2d(torch.relu(self.e2(x)), 2)
        return self.ez(x.flatten(1))
    def decode(self, z):
        h = torch.relu(self.dz(z)).reshape(-1, 16, 2, 2)
        h = torch.relu(self.d1(h))
        return torch.sigmoid(self.d2(h)).reshape(-1, 64)               # 每个像素压到 0–1
    def forward(self, x):
        return self.decode(self.encode(x))

torch.manual_seed(0)
ae = AutoEncoder()
opt = torch.optim.Adam(ae.parameters(), lr=3e-3)
for ep in range(60):
    order = torch.randperm(1500, generator=torch.Generator().manual_seed(ep))
    for i in range(0, 1500, 50):
        idx = order[i:i + 50]
        loss = F.mse_loss(ae(Xtr[idx]), Xtr[idx])     # 损失：还原出的图和原图差多少
        opt.zero_grad(); loss.backward(); opt.step()
with torch.no_grad():
    print(f"测试图还原误差（每个像素平方差的平均）：{F.mse_loss(ae(Xte), Xte).item():.4f}")
    print("解码器的旋钮：", sum(p.numel() for n, p in ae.named_parameters() if n.startswith("d")))
    print("从 2 个数 (0, 0) 生成的图：")
    for row in ae.decode(torch.zeros(1, 2)).reshape(8, 8):
        print("".join(" .:-=+*#%@"[min(9, int(v * 10))] for v in row))
# 应得：还原误差 0.0426；解码器 2377 个旋钮；最后打印出一个模糊的数字形状
