"""6장 실습: Vision Transformer(ViT)를 직접 만들고, 라벨 없이 학습하는 미니 DINO 를 돌려 본다.

하는 일
  1. 패치 임베딩: "패치를 펴서 선형 투영" 과 "커널 · 스트라이드가 패치 크기인 합성곱" 이 같은 계산임을 확인한다.
  2. ViT-S/16 · ViT-B/16 의 매개변수 수를 부품별 공식으로 세고, 실제로 만든 모델과 대조한다.
  3. MiniViT(96×96, 패치 8, d = 96, 4층)를 "어떤 도형이 있는가(다중 라벨 분류) + 가장 큰 도형은 어디에 있는가
     (중심 좌표)" 로 지도 학습한다.
  4. 96 으로 학습한 모델을 64 · 128 해상도 그림에 적용한다 (위치 임베딩 보간이 있을 때 · 없을 때),
     위치 임베딩을 지우면 어떻게 되는지도 본다.
  5. CLS 토큰의 어텐션 지도를 그린다.
  6. 미니 DINO: 라벨 없는 그림으로 자기 증류(학생 · EMA 교사 · centering · 온도)를 돌린다.
     그림을 두 종류(도형이 여럿인 장면 / 도형 하나)로 바꿔 가며 두 번 하고,
     centering 을 끈 것 · sharpening 을 끈 것과 붕괴 여부를 비교한다.
  7. 얼린 특징 위의 선형 분류기(linear probe)로 "무작위 초기화 · 미니 DINO · 지도 학습" 백본을 비교한다
     (장면에 어떤 도형이 있는가 / 객체가 몇 개인가 / 도형 하나짜리 그림의 도형은 무엇인가).

실행
  python ch06_vit.py            # 본문 결과. 8GB 노트북 GPU 를 다른 작업과 함께 쓰는 상태에서 10분 30초
                                # (지도 학습 2분 + 미니 DINO 두 번 7분 + 나머지), GPU 메모리 최대 1.5GB
  python ch06_vit.py --quick    # 연기 시험. GPU 약 12초 / CPU 4스레드 약 30초 (수치는 의미 없음)
  python ch06_vit.py --tau-t 0.04 --dino-steps 6000    # 미니 DINO 의 교사 온도 · 스텝 수 바꿔 보기

다른 실습 파일은 이 파일을 가져다 쓰지 않는다 (9 · 10장의 윈도 ViT 는 그 장에서 따로 만든다).
필요한 패키지는 torch · numpy · matplotlib 뿐이다. 그림은 --fig-dir (기본 figures) 에 ch06-*.png 로 저장된다.
"""

from __future__ import annotations

import argparse
import math
import os
import time

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

from rf_shapes import CLASS_NAMES, NUM_CLASSES, ShapesDataset


def get_device() -> str:
    if torch.cuda.is_available():
        return "cuda"
    if torch.backends.mps.is_available():
        return "mps"
    return "cpu"


# --8<-- [start:patchify]
def patchify(images: torch.Tensor, patch_size: int) -> torch.Tensor:
    """그림을 패치로 잘라, 패치 하나하나를 한 줄 벡터로 편다.

    images: (B, C, H, W)  →  돌려주는 값: (B, N, C·p·p),  N = (H/p)·(W/p)
    패치 순서는 글 읽는 순서(왼쪽 위에서 오른쪽으로, 다음 줄로)이고,
    한 패치 안의 값은 (채널, 행, 열) 순서로 편다 — 합성곱 가중치 (D, C, p, p) 를 펼 때와 같은 순서여야 한다.
    """
    B, C, H, W = images.shape
    p = patch_size
    gh, gw = H // p, W // p  # 세로 · 가로 패치 수
    x = images.reshape(B, C, gh, p, gw, p)  # 높이를 (패치 줄, 패치 안 행), 너비를 (패치 칸, 패치 안 열)로 쪼갠다
    x = x.permute(0, 2, 4, 1, 3, 5)  # (B, gh, gw, C, p, p): 패치 위치를 앞으로
    return x.reshape(B, gh * gw, C * p * p)
# --8<-- [end:patchify]


# --8<-- [start:patch-embed]
class PatchEmbed(nn.Module):
    """패치 임베딩: 그림 (B, 3, H, W) → 토큰 열 (B, N, D).

    커널 크기 = 스트라이드 = p 인 합성곱 하나다. 창이 겹치지 않고 p 칸씩 건너뛰므로
    "패치마다 같은 선형 층을 한 번씩 적용" 하는 것과 같은 계산이 된다.
    """

    def __init__(self, patch_size: int, dim: int, in_channels: int = 3):
        super().__init__()
        self.patch_size = patch_size
        self.proj = nn.Conv2d(in_channels, dim, kernel_size=patch_size, stride=patch_size)

    def forward(self, images: torch.Tensor) -> torch.Tensor:
        x = self.proj(images)  # (B, D, H/p, W/p): 격자 한 칸이 패치 하나
        return x.flatten(2).transpose(1, 2)  # (B, D, N) → (B, N, D)


def check_patch_embed(log=print):
    """합성곱 방식과 '펴서 선형 투영' 방식이 같은 값을 내는지 확인한다."""
    torch.manual_seed(0)
    embed = PatchEmbed(patch_size=8, dim=96)
    images = torch.rand(2, 3, 96, 96)
    by_conv = embed(images)  # (2, 144, 96)
    weight = embed.proj.weight.reshape(96, -1)  # (D, C, p, p) → (D, C·p·p) = (96, 192)
    by_linear = patchify(images, 8) @ weight.T + embed.proj.bias  # (2, 144, 192) @ (192, 96) → (2, 144, 96)
    diff = (by_conv - by_linear).abs().max().item()
    log(f"[check] 패치 임베딩: 합성곱 {tuple(by_conv.shape)} vs 펴서 선형 투영 {tuple(by_linear.shape)}, 최대 차이 {diff:.2e}")
    assert diff < 1e-5
# --8<-- [end:patch-embed]


# --8<-- [start:attention]
class SelfAttention(nn.Module):
    """다중 머리 자기 어텐션 (5장). 어텐션 가중치를 꺼내 볼 수 있게 직접 구현한다.

    x: (B, T, D) → (B, T, D).  T 는 토큰 수(CLS 1개 + 패치 N개), 머리 수 h, 머리 하나의 차원 D/h.
    """

    def __init__(self, dim: int, heads: int):
        super().__init__()
        assert dim % heads == 0
        self.heads = heads
        self.qkv = nn.Linear(dim, dim * 3)  # 질의 · 열쇠 · 값을 한 번에 만든다
        self.proj = nn.Linear(dim, dim)  # 머리들을 다시 합친 뒤의 출력 투영

    def forward(self, x: torch.Tensor, return_attention: bool = False):
        B, T, D = x.shape
        qkv = self.qkv(x).reshape(B, T, 3, self.heads, D // self.heads).permute(2, 0, 3, 1, 4)
        q, k, v = qkv[0], qkv[1], qkv[2]  # 각각 (B, h, T, D/h)
        scores = q @ k.transpose(-2, -1) / math.sqrt(D // self.heads)  # (B, h, T, T)
        attention = scores.softmax(dim=-1)  # 행마다 합이 1: 토큰 i 가 토큰 j 를 보는 비율
        out = (attention @ v).transpose(1, 2).reshape(B, T, D)  # (B, h, T, D/h) → (B, T, D)
        out = self.proj(out)
        return (out, attention) if return_attention else out


class Block(nn.Module):
    """pre-norm Transformer 인코더 블록: x + Attn(LN(x)), 그다음 x + MLP(LN(x))."""

    def __init__(self, dim: int, heads: int, mlp_ratio: int = 4):
        super().__init__()
        self.norm1 = nn.LayerNorm(dim)
        self.attn = SelfAttention(dim, heads)
        self.norm2 = nn.LayerNorm(dim)
        self.mlp = nn.Sequential(nn.Linear(dim, dim * mlp_ratio), nn.GELU(), nn.Linear(dim * mlp_ratio, dim))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = x + self.attn(self.norm1(x))  # 층 정규화를 먼저(pre-norm), 잔차 연결은 정규화 밖에서
        return x + self.mlp(self.norm2(x))
# --8<-- [end:attention]


def check_attention(log=print):
    """직접 만든 SelfAttention 을 PyTorch 내장 nn.MultiheadAttention 과 대조한다 (같은 가중치를 넣어서)."""
    torch.manual_seed(0)
    mine = SelfAttention(dim=32, heads=4)
    ref = nn.MultiheadAttention(32, 4, batch_first=True)
    with torch.no_grad():
        ref.in_proj_weight.copy_(mine.qkv.weight)
        ref.in_proj_bias.copy_(mine.qkv.bias)
        ref.out_proj.weight.copy_(mine.proj.weight)
        ref.out_proj.bias.copy_(mine.proj.bias)
        x = torch.randn(2, 10, 32)
        out, attention = mine(x, return_attention=True)
        out_ref, attention_ref = ref(x, x, x, need_weights=True, average_attn_weights=False)
    diff = max((out - out_ref).abs().max().item(), (attention - attention_ref).abs().max().item())
    log(f"[check] 자기 어텐션: 직접 구현 vs nn.MultiheadAttention 최대 차이 {diff:.2e}")
    assert diff < 1e-5


# --8<-- [start:pos-interp]
def interpolate_pos_embed(patch_pos: torch.Tensor, old_grid: int, new_grid: int, mode: str = "bicubic") -> torch.Tensor:
    """패치 위치 임베딩을 다른 격자 크기로 보간한다.

    patch_pos: (1, old_grid², D)  →  (1, new_grid², D)
    ① 한 줄로 늘어선 위치 임베딩을 원래의 2차원 격자로 되돌린다.
    ② 격자를 "D 채널짜리 작은 그림" 으로 보고 크기를 바꾼다 (쌍삼차 보간).
    ③ 다시 한 줄로 편다.
    """
    if old_grid == new_grid:
        return patch_pos
    D = patch_pos.shape[-1]
    grid = patch_pos.reshape(1, old_grid, old_grid, D).permute(0, 3, 1, 2)  # ① (1, D, old, old)
    grid = F.interpolate(grid, size=(new_grid, new_grid), mode=mode, align_corners=False)  # ② (1, D, new, new)
    return grid.permute(0, 2, 3, 1).reshape(1, new_grid * new_grid, D)  # ③
# --8<-- [end:pos-interp]


# --8<-- [start:vit]
class MiniViT(nn.Module):
    """작은 Vision Transformer.

    그림 (B, 3, H, W)
      → 패치 임베딩 (B, N, D)
      → 맨 앞에 CLS 토큰을 붙여 (B, 1 + N, D)
      → 위치 임베딩을 더함
      → pre-norm 블록 L 개
      → 마지막 층 정규화 → (B, 1 + N, D).   [:, 0] 이 CLS(그림 전체의 요약), [:, 1:] 이 패치 특징.
    num_outputs > 0 이면 CLS 위에 선형 분류 머리를 하나 단다.
    """

    def __init__(self, image_size: int = 96, patch_size: int = 8, dim: int = 96, depth: int = 4, heads: int = 4,
                 mlp_ratio: int = 4, num_outputs: int = 0):
        super().__init__()
        self.patch_size = patch_size
        self.grid = image_size // patch_size  # 학습 해상도에서 한 변의 패치 수 (96 / 8 = 12)
        self.dim = dim
        self.patch_embed = PatchEmbed(patch_size, dim)
        self.cls_token = nn.Parameter(torch.zeros(1, 1, dim))
        self.pos_embed = nn.Parameter(torch.zeros(1, 1 + self.grid**2, dim))  # CLS 자리 1개 + 패치 자리 N개
        self.blocks = nn.ModuleList([Block(dim, heads, mlp_ratio) for _ in range(depth)])
        self.norm = nn.LayerNorm(dim)
        self.head = nn.Linear(dim, num_outputs) if num_outputs > 0 else None
        nn.init.trunc_normal_(self.cls_token, std=0.02)
        nn.init.trunc_normal_(self.pos_embed, std=0.02)

    def embed(self, images: torch.Tensor, interpolate: bool = True) -> torch.Tensor:
        """그림 → 위치 임베딩까지 더한 토큰 열 (B, 1 + N, D)."""
        B, _, H, W = images.shape
        assert H == W and H % self.patch_size == 0, "정사각형이고 패치 크기로 나누어떨어지는 그림만 받는다"
        x = self.patch_embed(images)  # (B, N, D)
        x = torch.cat([self.cls_token.expand(B, -1, -1), x], dim=1)  # (B, 1 + N, D)
        pos = self.pos_embed
        new_grid = H // self.patch_size
        if interpolate and new_grid != self.grid:
            # CLS 자리의 위치 임베딩은 그대로 두고, 패치 자리의 것만 2차원 격자로 보간한다
            patch_pos = interpolate_pos_embed(pos[:, 1:], self.grid, new_grid)
            pos = torch.cat([pos[:, :1], patch_pos], dim=1)
        return x + pos  # 보간을 끄고 격자 크기가 다르면 여기서 모양이 맞지 않아 오류가 난다

    def forward_tokens(self, images: torch.Tensor, interpolate: bool = True) -> torch.Tensor:
        x = self.embed(images, interpolate)
        for block in self.blocks:
            x = block(x)
        return self.norm(x)  # (B, 1 + N, D)

    def forward(self, images: torch.Tensor, interpolate: bool = True) -> torch.Tensor:
        cls = self.forward_tokens(images, interpolate)[:, 0]  # (B, D)
        return self.head(cls) if self.head is not None else cls

    @torch.no_grad()
    def last_attention(self, images: torch.Tensor) -> torch.Tensor:
        """마지막 블록에서 CLS 토큰이 각 패치를 보는 비율. (B, h, grid, grid)"""
        x = self.embed(images)
        for block in self.blocks[:-1]:
            x = block(x)
        last = self.blocks[-1]
        _, attention = last.attn(last.norm1(x), return_attention=True)  # (B, h, 1 + N, 1 + N)
        g = images.shape[-1] // self.patch_size
        return attention[:, :, 0, 1:].reshape(len(images), -1, g, g)  # 0번 행(CLS)의 1번 열부터(패치들)
# --8<-- [end:vit]


# --8<-- [start:count]
def vit_param_count(image_size: int, patch_size: int, dim: int, depth: int, mlp_ratio: int = 4, num_classes: int = 0,
                    in_channels: int = 3) -> dict:
    """ViT 의 매개변수 수를 부품별 공식으로 센다 (가중치 + 편향).

    선형 층 Linear(a, b) 는 a·b + b 개, 층 정규화 LayerNorm(d) 는 2d 개(배율 γ 와 이동 β)이다.
    머리 수는 매개변수 수에 영향을 주지 않는다 (같은 qkv 행렬을 머리 수만큼 나눠 쓸 뿐이다).
    """
    n_patches = (image_size // patch_size) ** 2
    hidden = dim * mlp_ratio
    counts = {
        "patch_embed": in_channels * patch_size * patch_size * dim + dim,
        "cls_token": dim,
        "pos_embed": (1 + n_patches) * dim,
        "block.norm x2": 2 * (2 * dim),
        "block.attn.qkv": dim * 3 * dim + 3 * dim,
        "block.attn.proj": dim * dim + dim,
        "block.mlp.fc1": dim * hidden + hidden,
        "block.mlp.fc2": hidden * dim + dim,
        "final_norm": 2 * dim,
        "head": (dim * num_classes + num_classes) if num_classes else 0,
    }
    counts["block"] = sum(v for k, v in counts.items() if k.startswith("block."))
    counts["total"] = (counts["patch_embed"] + counts["cls_token"] + counts["pos_embed"] + depth * counts["block"]
                       + counts["final_norm"] + counts["head"])
    return counts
# --8<-- [end:count]


def report_param_counts(log=print):
    """공식으로 센 값과, 같은 설정으로 실제로 만든 MiniViT 의 매개변수 수를 대조한다."""
    for name, dim, heads in [("ViT-S/16", 384, 6), ("ViT-B/16", 768, 12)]:
        c = vit_param_count(224, 16, dim, 12, 4, num_classes=1000)
        model = MiniViT(224, 16, dim, 12, heads, 4, num_outputs=1000)
        actual = sum(p.numel() for p in model.parameters())
        log(f"[count] {name}: 패치 임베딩 {c['patch_embed']:,} + CLS {c['cls_token']:,} + 위치 임베딩 {c['pos_embed']:,}"
            f" + 블록 12 × {c['block']:,} + 마지막 LN {c['final_norm']:,} + 분류 머리 {c['head']:,} = {c['total']:,}")
        log(f"        블록 하나: LN 2개 {c['block.norm x2']:,} + qkv {c['block.attn.qkv']:,} + proj {c['block.attn.proj']:,}"
            f" + MLP {c['block.mlp.fc1']:,} + {c['block.mlp.fc2']:,}")
        log(f"        실제로 만든 모델 {actual:,}개 → {'일치' if actual == c['total'] else '불일치'}"
            f" (분류 머리 빼면 {c['total'] - c['head']:,})")
        assert actual == c["total"]
        del model


# --8<-- [start:handcalc]
def hand_checks(log=print):
    """본문의 손계산 예를 코드로 다시 계산한다."""
    # (1) 토큰 수 N = (H/p)·(W/p) 와, 자기 어텐션이 다루는 쌍의 수 N²
    for name, size, p in [("도형 세상", 96, 8), ("DINOv2 사전 학습", 224, 14), ("DINOv2 고해상도", 518, 14),
                          ("RF-DETR nano", 384, 16), ("RF-DETR small", 512, 16), ("RF-DETR medium", 576, 16),
                          ("RF-DETR base(패치 14)", 560, 14)]:
        g = size // p
        log(f"[hand] {name}: {size}/{p} = {g} → N = {g * g}, N² = {(g * g) ** 2:,}")
    # (2) 위치 임베딩 보간의 작은 예: 2×2 격자(값 하나짜리)를 3×3 으로, 쌍선형
    small = torch.tensor([[0.0, 3.0], [6.0, 9.0]]).reshape(1, 4, 1)
    bilinear = interpolate_pos_embed(small, 2, 3, mode="bilinear").reshape(3, 3)
    bicubic = interpolate_pos_embed(small, 2, 3, mode="bicubic").reshape(3, 3)
    log(f"[hand] 2×2 → 3×3 쌍선형: {[[round(v, 3) for v in row] for row in bilinear.tolist()]}")
    log(f"[hand] 2×2 → 3×3 쌍삼차: {[[round(v, 3) for v in row] for row in bicubic.tolist()]}")
    # (3) EMA: θ_t ← m θ_t + (1 − m) θ_s
    for m in (0.9, 0.996):
        theta_t, theta_s = 1.0, 2.0
        log(f"[hand] EMA m = {m}: θ_t = {m * theta_t + (1 - m) * theta_s:.4f}, 차이가 반으로 줄기까지 {math.log(0.5) / math.log(m):.1f} 스텝")
    # (4) 온도: 같은 점수 (0.2, 0.1, 0.0) 을 학생 온도 0.1, 교사 온도 0.04 로 소프트맥스
    z = torch.tensor([0.2, 0.1, 0.0])
    p_s, p_t = (z / 0.1).softmax(0), (z / 0.04).softmax(0)
    log(f"[hand] 온도 0.1: {[round(v, 4) for v in p_s.tolist()]}, 온도 0.04: {[round(v, 4) for v in p_t.tolist()]}")
    log(f"[hand] 교차 엔트로피 H(P_t, P_s) = {-(p_t * p_s.log()).sum().item():.4f}, 교사 엔트로피 h(P_t) = {-(p_t * p_t.log()).sum().item():.4f}")
    # (5) centering: 두 그림의 교사 점수가 모두 0번 차원으로 쏠려 있을 때
    g = torch.tensor([[0.30, 0.10, 0.00], [0.28, 0.12, 0.02]])
    c = g.mean(0)
    log(f"[hand] 중심 c = {[round(v, 3) for v in c.tolist()]}")
    log(f"[hand] centering 없이: {[[round(v, 4) for v in row] for row in (g / 0.04).softmax(1).tolist()]}")
    log(f"[hand] centering 하고: {[[round(v, 4) for v in row] for row in ((g - c) / 0.04).softmax(1).tolist()]}")
# --8<-- [end:handcalc]


# --8<-- [start:labels]
def presence_labels(targets) -> torch.Tensor:
    """정답 목록 → (그림 수, 3) 의 0/1 표: 그 그림에 원 · 사각형 · 삼각형이 있는가."""
    labels = torch.zeros(len(targets), NUM_CLASSES)
    for i, target in enumerate(targets):
        labels[i, target["labels"]] = 1.0
    return labels


def largest_centers(targets) -> torch.Tensor:
    """정답 목록 → (그림 수, 2): 박스 넓이가 가장 큰 객체의 중심 (cx, cy), 0 – 1 로 정규화된 좌표."""
    centers = torch.zeros(len(targets), 2)
    for i, target in enumerate(targets):
        boxes = target["boxes"]  # (객체 수, 4) = (cx, cy, w, h)
        centers[i] = boxes[(boxes[:, 2] * boxes[:, 3]).argmax(), :2]
    return centers
# --8<-- [end:labels]


def to_float(images_uint8: torch.Tensor) -> torch.Tensor:
    return images_uint8.float() / 255.0


@torch.no_grad()
def predict(model, images_uint8, interpolate=True, batch_size=100):
    """모델 출력 (그림 수, 5): 앞의 3개는 클래스 로짓, 뒤의 2개는 중심 좌표의 로짓."""
    model.eval()
    return torch.cat([model(to_float(images_uint8[i : i + batch_size]), interpolate) for i in range(0, len(images_uint8), batch_size)])


def accuracy(logits: torch.Tensor, labels: torch.Tensor):
    """(라벨 하나하나의 정확도, 세 라벨을 모두 맞힌 그림의 비율). 로짓 > 0 ⇔ 시그모이드 > 0.5."""
    correct = (logits > 0).float() == labels
    return correct.float().mean().item(), correct.all(dim=1).float().mean().item()


def evaluate(outputs: torch.Tensor, labels: torch.Tensor, centers: torch.Tensor):
    """(라벨 정확도, 세 라벨 모두, 중심 오차). 중심 오차 = 예측 중심과 정답 중심 사이 거리의 평균 (그림 한 변 = 1)."""
    acc, exact = accuracy(outputs[:, :NUM_CLASSES], labels)
    distance = (outputs[:, NUM_CLASSES:].sigmoid() - centers).norm(dim=1).mean().item()
    return acc, exact, distance


# --8<-- [start:train-supervised]
def train_supervised(model, train_images, train_labels, train_centers, val_images, val_labels, val_centers, epochs,
                     batch_size=128, lr=1e-3, weight_decay=0.05, center_weight=5.0, seed=0, log=print):
    """MiniViT 를 지도 학습한다. CLS 출력 위의 선형 머리가 숫자 5개를 낸다.

    - 앞의 3개: "원 · 사각형 · 삼각형이 있는가" 의 로짓. 손실은 4장의 BCE (라벨마다 따로, 평균).
    - 뒤의 2개: 가장 큰 객체의 중심 (cx, cy). 시그모이드로 0 – 1 에 넣고 정답과의 L1 거리(2장)를 손실로 쓴다.
    "무엇이 있는가" 와 "어디에 있는가" 를 함께 묻는, 탐지의 아주 작은 축소판이다.
    학습률은 워밍업(처음 5%) 뒤 코사인으로 줄인다. 증강은 좌우 뒤집기뿐이다 (뒤집으면 cx 는 1 − cx 가 된다).
    """
    generator = torch.Generator(device=train_images.device).manual_seed(seed)
    optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=weight_decay)
    steps_per_epoch = len(train_images) // batch_size
    total = epochs * steps_per_epoch
    warmup = max(1, total // 20)
    schedule = lambda step: min((step + 1) / warmup, 0.5 * (1 + math.cos(math.pi * step / total)))
    scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, schedule)
    history = []
    for epoch in range(epochs):
        model.train()
        order = torch.randperm(len(train_images), device=train_images.device, generator=generator)
        running = 0.0
        for i in range(steps_per_epoch):
            index = order[i * batch_size : (i + 1) * batch_size]
            images = to_float(train_images[index])  # (B, 3, 96, 96)
            centers = train_centers[index].clone()  # (B, 2)
            flip = torch.rand(len(index), device=images.device, generator=generator) < 0.5
            images = torch.where(flip[:, None, None, None], images.flip(-1), images)
            centers[:, 0] = torch.where(flip, 1 - centers[:, 0], centers[:, 0])
            outputs = model(images)  # (B, 5)
            loss_class = F.binary_cross_entropy_with_logits(outputs[:, :NUM_CLASSES], train_labels[index])
            loss_center = (outputs[:, NUM_CLASSES:].sigmoid() - centers).abs().mean()
            loss = loss_class + center_weight * loss_center
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            scheduler.step()
            running += loss.item()
        val_acc, val_exact, val_distance = evaluate(predict(model, val_images), val_labels, val_centers)
        history.append((running / steps_per_epoch, val_acc, val_exact, val_distance))
        if (epoch + 1) % max(1, epochs // 10) == 0 or epoch == 0:
            log(f"  에폭 {epoch + 1:3d} | 학습 손실 {history[-1][0]:.4f} | 검증 라벨 정확도 {val_acc:.3f} | 세 라벨 모두 {val_exact:.3f}"
                f" | 중심 오차 {val_distance:.4f}")
    return history
# --8<-- [end:train-supervised]


# --8<-- [start:augment]
def random_view(images: torch.Tensor, out_size: int, scale: tuple, generator: torch.Generator) -> torch.Tensor:
    """그림마다 무작위 "뷰" 하나를 만든다: 무작위 자르기 + 좌우 뒤집기 + 색 바꾸기 + 잡음.

    images: (B, 3, H, W) 0 – 1  →  (B, 3, out_size, out_size)
    - 자르기: 넓이가 원래의 scale[0] – scale[1] 배, 가로세로 비가 3/4 – 4/3 인 창을 무작위 위치에서 잘라
      out_size 로 크기를 바꾼다 (F.affine_grid + F.grid_sample 로 배치 전체를 한 번에).
    - 색: 채널 순서를 무작위로 섞고(빨강 도형이 파랑 도형이 된다) 밝기를 0.6 – 1.4 배로 바꾼다.
      도형 세상에서 색은 도형의 종류와 무관하므로, "색이 달라도 같은 그림" 이라고 알려 주는 셈이다.
    """
    B, device = len(images), images.device
    rand = lambda *shape: torch.rand(*shape, device=device, generator=generator)
    area = scale[0] + (scale[1] - scale[0]) * rand(B)
    log_ratio = math.log(4 / 3) * (2 * rand(B) - 1)
    width = (area * log_ratio.exp()).sqrt().clamp(max=1.0)  # 창의 너비 · 높이 (그림 한 변 = 1)
    height = (area / log_ratio.exp()).sqrt().clamp(max=1.0)
    center_x = (2 * rand(B) - 1) * (1 - width)  # affine_grid 의 좌표는 −1 – 1: 창이 그림 밖으로 나가지 않게
    center_y = (2 * rand(B) - 1) * (1 - height)
    flip = 1 - 2 * (rand(B) < 0.5).float()  # −1 이면 좌우 뒤집기
    theta = torch.zeros(B, 2, 3, device=device)
    theta[:, 0, 0], theta[:, 0, 2] = width * flip, center_x
    theta[:, 1, 1], theta[:, 1, 2] = height, center_y
    grid = F.affine_grid(theta, (B, 3, out_size, out_size), align_corners=False)
    views = F.grid_sample(images, grid, mode="bilinear", padding_mode="border", align_corners=False)
    permutation = torch.argsort(rand(B, 3), dim=1)  # 그림마다 채널 순서 섞기
    views = torch.gather(views, 1, permutation[:, :, None, None].expand(-1, -1, out_size, out_size))
    views = views * (0.6 + 0.8 * rand(B, 1, 1, 1))
    views = views + 0.02 * torch.randn(views.shape, device=device, generator=generator)
    return views.clamp(0, 1)
# --8<-- [end:augment]


# --8<-- [start:dino-head]
class DINOHead(nn.Module):
    """투영 머리: 백본의 CLS 특징 (B, D) → K 차원 점수 (B, K).

    MLP → 병목 차원으로 줄임 → 길이 1 로 정규화 → 가중치 행의 길이도 1 인 선형 층.
    마지막 두 단계 때문에 점수 하나하나는 "두 단위 벡터의 내적" 이라 −1 – 1 사이에 있다.
    그래서 온도 0.1 로 나누면 −10 – 10, 0.02 로 나누면 −50 – 50 의 로짓이 된다.
    이 머리는 사전 학습 때만 쓰고, 학습이 끝나면 버린다 (쓸모 있는 것은 백본이다).
    """

    def __init__(self, dim: int, out_dim: int = 256, hidden: int = 256, bottleneck: int = 64):
        super().__init__()
        self.mlp = nn.Sequential(nn.Linear(dim, hidden), nn.GELU(), nn.Linear(hidden, hidden), nn.GELU(),
                                 nn.Linear(hidden, bottleneck))
        self.last = nn.Linear(bottleneck, out_dim, bias=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = F.normalize(self.mlp(x), dim=-1)
        return F.linear(x, F.normalize(self.last.weight, dim=-1))
# --8<-- [end:dino-head]


# --8<-- [start:dino-loss]
def dino_loss(student_out, teacher_out, center, tau_s: float, tau_t: float):
    """DINO 손실: 교사 분포와 학생 분포의 교차 엔트로피를 "서로 다른 뷰" 끼리 계산해 평균한다.

    student_out: 뷰마다의 학생 점수 목록, 각각 (B, K).  teacher_out: 교사 점수 목록(전역 뷰 2개), 각각 (B, K).
    center: (K,) — 교사 점수의 이동 평균. 돌려주는 값: (손실, 교사 분포의 엔트로피 평균, 교사 분포 목록)
    """
    # 교사: 중심을 빼고(centering) 낮은 온도로 나눠(sharpening) 소프트맥스. 기울기는 흘리지 않는다.
    teacher_probs = [((t - center) / tau_t).softmax(dim=-1).detach() for t in teacher_out]
    student_logp = [(s / tau_s).log_softmax(dim=-1) for s in student_out]
    loss, pairs = 0.0, 0
    for i, p_t in enumerate(teacher_probs):
        for j, logp_s in enumerate(student_logp):
            if i == j:  # 같은 뷰끼리는 비교하지 않는다 (그건 그냥 교사를 베끼는 문제가 된다)
                continue
            loss = loss + (-(p_t * logp_s).sum(dim=-1)).mean()  # H(P_t, P_s) = −Σ_k P_t(k) log P_s(k)
            pairs += 1
    entropy = torch.stack([-(p * (p + 1e-12).log()).sum(dim=-1).mean() for p in teacher_probs]).mean()
    return loss / pairs, entropy, teacher_probs
# --8<-- [end:dino-loss]


# --8<-- [start:dino-train]
def train_dino(train_images, steps, batch_size=64, dim=96, depth=4, heads=4, out_dim=256, lr=5e-4, weight_decay=0.04,
               tau_s=0.1, tau_t=0.04, momentum=0.99, center_momentum=0.9, use_centering=True, local_views=2,
               seed=0, log=print, name="DINO"):
    """미니 DINO. 라벨은 전혀 쓰지 않는다 (train_images 만 받는다).

    돌려주는 값: (교사 백본, 기록) — 기록은 스텝마다 (손실, 교사 엔트로피, KL, 배치 평균 분포의 엔트로피).
    """
    device = train_images.device
    torch.manual_seed(seed)
    generator = torch.Generator(device=device).manual_seed(seed)
    student = nn.ModuleDict({"backbone": MiniViT(96, 8, dim, depth, heads), "head": DINOHead(dim, out_dim)}).to(device)
    teacher = nn.ModuleDict({"backbone": MiniViT(96, 8, dim, depth, heads), "head": DINOHead(dim, out_dim)}).to(device)
    teacher.load_state_dict(student.state_dict())  # 교사는 학생과 같은 값에서 출발한다
    for p in teacher.parameters():
        p.requires_grad_(False)  # 교사는 기울기로 배우지 않는다. EMA 로만 바뀐다.
    optimizer = torch.optim.AdamW(student.parameters(), lr=lr, weight_decay=weight_decay)
    warmup = max(1, steps // 10)
    center = torch.zeros(out_dim, device=device)
    history = []
    for step in range(steps):
        for group in optimizer.param_groups:  # 학습률: 워밍업 뒤 코사인
            group["lr"] = lr * min((step + 1) / warmup, 0.5 * (1 + math.cos(math.pi * step / steps)))
        index = torch.randint(len(train_images), (batch_size,), device=device, generator=generator)
        images = to_float(train_images[index])
        # 같은 그림에서 뷰를 여러 개: 크게 자른 전역 뷰 2개(96×96) + 작게 자른 지역 뷰 local_views 개(48×48)
        global_views = [random_view(images, 96, (0.5, 1.0), generator) for _ in range(2)]
        local_view_list = [random_view(images, 48, (0.15, 0.5), generator) for _ in range(local_views)]
        with torch.no_grad():  # 교사는 전역 뷰만 본다
            teacher_out = [teacher["head"](teacher["backbone"](v)) for v in global_views]
        # 학생은 모든 뷰를 본다. 48×48 뷰는 격자가 6×6 이라 위치 임베딩이 보간되어 들어간다.
        student_out = [student["head"](student["backbone"](v)) for v in global_views + local_view_list]
        loss, entropy, teacher_probs = dino_loss(student_out, teacher_out, center if use_centering else 0.0, tau_s, tau_t)
        optimizer.zero_grad()
        loss.backward()
        torch.nn.utils.clip_grad_norm_(student.parameters(), 3.0)
        optimizer.step()
        with torch.no_grad():
            # 교사 = 학생의 지수 이동 평균. m 은 코사인을 따라 momentum → 1 로 올라간다.
            m = 1 - (1 - momentum) * 0.5 * (1 + math.cos(math.pi * step / steps))
            for p_t, p_s in zip(teacher.parameters(), student.parameters()):
                p_t.mul_(m).add_(p_s.detach(), alpha=1 - m)
            # 중심 = 교사 점수의 배치 평균을 이동 평균한 것
            center = center_momentum * center + (1 - center_momentum) * torch.cat(teacher_out).mean(dim=0)
            mean_probs = torch.cat(teacher_probs).mean(dim=0)  # 배치 전체가 K 개 차원을 얼마나 고르게 쓰는가
            marginal_entropy = -(mean_probs * (mean_probs + 1e-12).log()).sum().item()
        history.append((loss.item(), entropy.item(), loss.item() - entropy.item(), marginal_entropy))
        if (step + 1) % max(1, steps // 5) == 0 or step == 0:
            log(f"  [{name}] 스텝 {step + 1:5d} | 손실 {loss.item():.3f} | 교사 엔트로피 {entropy.item():.3f}"
                f" | KL {loss.item() - entropy.item():.3f} | 배치 평균 분포의 엔트로피 {marginal_entropy:.3f}")
    return teacher["backbone"].eval(), np.array(history)
# --8<-- [end:dino-train]


# --8<-- [start:linear-probe]
@torch.no_grad()
def extract_features(backbone, images_uint8, batch_size=250) -> torch.Tensor:
    """얼린 백본의 특징: CLS 토큰과 패치 토큰 평균을 이어 붙인다. (그림 수, 2D)"""
    backbone.eval()
    features = []
    for i in range(0, len(images_uint8), batch_size):
        tokens = backbone.forward_tokens(to_float(images_uint8[i : i + batch_size]))  # (B, 1 + N, D)
        features.append(torch.cat([tokens[:, 0], tokens[:, 1:].mean(dim=1)], dim=1))
    return torch.cat(features)


def linear_probe(train_features, train_targets, test_features, epochs=300, lr=1e-2, seed=0) -> torch.Tensor:
    """얼린 특징 위에 선형 층 하나만 학습하고 (라벨은 여기서만 쓴다), 시험 특징에 대한 로짓을 돌려준다.

    train_targets 가 실수 (n, 3) 이면 다중 라벨 문제로 보고 BCE 를,
    정수 (n,) 이면 여러 클래스 중 하나를 고르는 문제로 보고 소프트맥스 교차 엔트로피를 쓴다.
    특징은 학습 세트의 평균 · 표준편차로 정규화한다. 선형 층 하나로 풀리는 만큼만 점수가 나오므로,
    "특징 안에 답이 얼마나 꺼내기 쉬운 꼴로 들어 있는가" 를 재는 시험이 된다.
    """
    torch.manual_seed(seed)
    mean, std = train_features.mean(0, keepdim=True), train_features.std(0, keepdim=True) + 1e-6
    x_train, x_test = (train_features - mean) / std, (test_features - mean) / std
    multi_label = train_targets.is_floating_point()
    n_outputs = train_targets.shape[1] if multi_label else int(train_targets.max()) + 1
    probe = nn.Linear(x_train.shape[1], n_outputs).to(x_train.device)
    optimizer = torch.optim.AdamW(probe.parameters(), lr=lr, weight_decay=1e-2)
    for _ in range(epochs):  # 특징이 작아서 전체를 한 배치로 쓴다
        logits = probe(x_train)
        loss = F.binary_cross_entropy_with_logits(logits, train_targets) if multi_label else F.cross_entropy(logits, train_targets)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    with torch.no_grad():
        return probe(x_test)
# --8<-- [end:linear-probe]


def plot_patches(image, patch_size, path):
    """그림 한 장과 그것을 패치로 자른 모습."""
    grid = image.shape[-1] // patch_size
    fig, axes = plt.subplots(1, 2, figsize=(7.2, 3.7))
    axes[0].imshow(image.permute(1, 2, 0).numpy(), interpolation="nearest")
    axes[0].set_title(f"image {image.shape[-1]}x{image.shape[-1]}")
    for k in range(1, grid):
        axes[0].axhline(k * patch_size - 0.5, color="white", linewidth=0.5, alpha=0.6)
        axes[0].axvline(k * patch_size - 0.5, color="white", linewidth=0.5, alpha=0.6)
    axes[0].set_xticks([])
    axes[0].set_yticks([])
    patches = patchify(image[None], patch_size)[0].reshape(grid * grid, 3, patch_size, patch_size)
    canvas = np.ones((grid * (patch_size + 2), grid * (patch_size + 2), 3), dtype=np.float32)
    for n in range(grid * grid):
        r, c = divmod(n, grid)
        canvas[r * (patch_size + 2) + 1 : r * (patch_size + 2) + 1 + patch_size,
               c * (patch_size + 2) + 1 : c * (patch_size + 2) + 1 + patch_size] = patches[n].permute(1, 2, 0).numpy()
    axes[1].imshow(canvas, interpolation="nearest")
    axes[1].set_title(f"{grid}x{grid} = {grid * grid} patches ({patch_size}x{patch_size} px each)")
    axes[1].set_xticks([])
    axes[1].set_yticks([])
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


def main():
    parser = argparse.ArgumentParser(description="6장: Vision Transformer 와 미니 DINO")
    parser.add_argument("--quick", action="store_true", help="아주 작게 돌려 오류만 확인")
    parser.add_argument("--n-train", type=int, default=8000)
    parser.add_argument("--n-test", type=int, default=1000)
    parser.add_argument("--epochs", type=int, default=40, help="지도 학습 에폭 수")
    parser.add_argument("--dino-steps", type=int, default=3000, help="미니 DINO 스텝 수")
    parser.add_argument("--ablation-steps", type=int, default=300, help="centering · sharpening 을 끈 실험의 스텝 수")
    parser.add_argument("--tau-t", type=float, default=0.02, help="미니 DINO 의 교사 온도 (DINO 논문은 0.04 – 0.07)")
    parser.add_argument("--seed", type=int, default=0)
    parser.add_argument("--fig-dir", default="figures")
    args = parser.parse_args()
    if args.quick:
        args.n_train, args.n_test, args.epochs, args.dino_steps, args.ablation_steps = 256, 128, 2, 6, 4
    probe_epochs = 20 if args.quick else 300
    batch_size = 64 if args.quick else 128  # 지도 학습의 배치 크기
    dino_batch = 32 if args.quick else 64  # 미니 DINO 는 그림마다 뷰를 4장 만들므로 배치를 작게 잡는다

    os.makedirs(args.fig_dir, exist_ok=True)
    torch.manual_seed(args.seed)
    np.random.seed(args.seed)
    device = get_device()
    if device == "cpu":  # 작은 모델은 스레드가 많으면 오히려 느려진다 (다른 일을 하고 있는 컴퓨터에서는 더)
        torch.set_num_threads(min(torch.get_num_threads(), 4))
    print(f"장치: {device}")
    t_start = time.time()

    # 0. 검산
    check_patch_embed()
    check_attention()
    report_param_counts()
    hand_checks()

    # 1. 데이터: 학습(seed 0) · 검증(seed 1) · 시험(seed 2). 시험 장면은 64 · 128 해상도로도 그려 둔다.
    t0 = time.time()
    train_set = ShapesDataset(args.n_train, seed=0)
    val_set = ShapesDataset(args.n_test, seed=1)
    test_sets = {size: ShapesDataset(args.n_test, size=size, seed=2) for size in (64, 96, 128)}
    train_images, train_labels = train_set.images.to(device), presence_labels(train_set.targets).to(device)
    val_images, val_labels = val_set.images.to(device), presence_labels(val_set.targets).to(device)
    train_centers, val_centers = largest_centers(train_set.targets).to(device), largest_centers(val_set.targets).to(device)
    test_images = {size: ds.images.to(device) for size, ds in test_sets.items()}
    test_labels = presence_labels(test_sets[96].targets).to(device)
    test_centers = largest_centers(test_sets[96].targets).to(device)  # 정규화 좌표라 해상도와 무관하다
    base_rate = train_labels.mean(0)
    majority = torch.maximum(base_rate, 1 - base_rate).mean().item()
    print(f"데이터: 학습 {len(train_set)}장, 검증 {len(val_set)}장, 시험 {args.n_test}장 × 해상도 64 · 96 · 128 ({time.time() - t0:.1f}초)")
    print(f"라벨이 1 인 비율 (원, 사각형, 삼각형): {[round(v, 3) for v in base_rate.tolist()]} → 늘 많은 쪽으로 찍으면 라벨 정확도 {majority:.3f}")
    constant_distance = (train_centers.mean(0, keepdim=True) - test_centers).norm(dim=1).mean().item()
    print(f"가장 큰 객체의 중심: 늘 평균 위치 {[round(v, 3) for v in train_centers.mean(0).tolist()]} 라고 답하면 중심 오차 {constant_distance:.4f}")
    plot_patches(train_set[0][0], 8, os.path.join(args.fig_dir, "ch06-patches.png"))

    # 2. 지도 학습: 출력 5개 = 클래스 로짓 3 + 중심 좌표 2
    torch.manual_seed(args.seed)
    supervised = MiniViT(96, 8, dim=96, depth=4, heads=4, num_outputs=NUM_CLASSES + 2).to(device)
    n_params = sum(p.numel() for p in supervised.parameters())
    formula = vit_param_count(96, 8, 96, 4, 4, NUM_CLASSES + 2)["total"]
    print(f"MiniViT 매개변수 {n_params:,}개 (공식 {formula:,}), 토큰 수 1 + {supervised.grid ** 2}")
    t0 = time.time()
    history = train_supervised(supervised, train_images, train_labels, train_centers, val_images, val_labels, val_centers,
                               args.epochs, batch_size=batch_size, seed=args.seed)
    print(f"지도 학습 {time.time() - t0:.1f}초")
    supervised.eval()

    # 3. 해상도를 바꿔 보기
    print("해상도 실험 (시험 세트, 같은 장면을 각 해상도로 그린 것)")
    resolution_rows = []
    for size in (64, 96, 128):
        grid = size // 8
        try:
            predict(supervised, test_images[size], interpolate=False)
            without = "동작"
        except RuntimeError as error:
            without = "오류: " + str(error).split("\n")[0][:70]
        acc, exact, distance = evaluate(predict(supervised, test_images[size], interpolate=True), test_labels, test_centers)
        # 비교: 그림을 96×96 으로 크기를 바꿔서(쌍선형) 넣기 — 위치 임베딩은 그대로
        resized = F.interpolate(to_float(test_images[size]), size=96, mode="bilinear", align_corners=False, antialias=True)
        acc_r, exact_r, distance_r = evaluate(predict(supervised, (resized * 255).round().to(torch.uint8)), test_labels, test_centers)
        resolution_rows.append((size, grid, acc, exact, distance, acc_r, exact_r, distance_r))
        print(f"  {size:3d}×{size:<3d} 격자 {grid:2d}×{grid:<2d} 토큰 {grid * grid:3d} | 보간 없이: {without}")
        print(f"            위치 임베딩 보간:        라벨 정확도 {acc:.3f} | 세 라벨 모두 {exact:.3f} | 중심 오차 {distance:.4f}")
        print(f"            그림을 96 으로 바꿔 넣기: 라벨 정확도 {acc_r:.3f} | 세 라벨 모두 {exact_r:.3f} | 중심 오차 {distance_r:.4f}")
    # 위치 임베딩이 하는 일: 패치 자리의 위치 임베딩을 지우고(0 으로) 96×96 시험 세트를 다시 채점한다
    saved = supervised.pos_embed.data.clone()
    supervised.pos_embed.data[:, 1:] = 0.0
    acc_z, exact_z, distance_z = evaluate(predict(supervised, test_images[96]), test_labels, test_centers)
    supervised.pos_embed.data.copy_(saved)
    print(f"  위치 임베딩을 0 으로 지우면 (96×96): 라벨 정확도 {acc_z:.3f} | 세 라벨 모두 {exact_z:.3f} | 중심 오차 {distance_z:.4f}")

    # 4. 그림: 학습 곡선 + 해상도
    hist = np.array(history)
    fig, axes = plt.subplots(1, 3, figsize=(13, 3.5))
    epochs_axis = np.arange(1, len(hist) + 1)
    axes[0].plot(epochs_axis, hist[:, 1], "--", color="#2f6fdb", label="val per-label accuracy")
    axes[0].plot(epochs_axis, hist[:, 2], ":", color="#1b8a5a", linewidth=2, label="val all-3-correct")
    axes[0].axhline(majority, color="gray", linewidth=0.8, linestyle="-.")
    axes[0].text(len(hist), majority + 0.012, "majority guess (per-label accuracy)", color="gray", fontsize=7.5, ha="right", va="bottom")
    axes[0].set_xlabel("epoch")
    axes[0].set_ylabel("accuracy")
    axes[0].set_ylim(0, 1.02)
    twin = axes[0].twinx()
    twin.plot(epochs_axis, hist[:, 3], "-", color="#b7620c", label="val center error")
    twin.axhline(constant_distance, color="#b7620c", linewidth=0.8, linestyle="-.")
    twin.text(len(hist), constant_distance + 0.006, "center error of a constant guess", color="#b7620c", fontsize=7.5, ha="right", va="bottom")
    twin.set_ylabel("center error (image side = 1)")
    twin.set_ylim(0, constant_distance * 2.0)
    lines = axes[0].get_lines() + twin.get_lines()
    lines = [line for line in lines if not line.get_label().startswith("_")]
    twin.legend(lines, [line.get_label() for line in lines], loc="lower right", bbox_to_anchor=(1.0, 0.24), fontsize=7.5)
    axes[0].set_title("MiniViT, supervised: what + where", fontsize=10)
    x = np.arange(3)
    tick_labels = [f"{row[0]}x{row[0]}\n({row[1]}x{row[1]} tokens)" for row in resolution_rows]
    for ax, (ci, cr), ylabel, top in [(axes[1], (3, 6), "test all-3-correct accuracy", 1.3),
                                      (axes[2], (4, 7), "test center error (image side = 1)", None)]:
        a_vals, b_vals = [row[ci] for row in resolution_rows], [row[cr] for row in resolution_rows]
        ax.bar(x - 0.2, a_vals, 0.4, color="#2f6fdb", label="interpolate position embedding")
        ax.bar(x + 0.2, b_vals, 0.4, color="#b7620c", hatch="//", label="resize image to 96")
        top = top or max(a_vals + b_vals) * 1.45
        for k in range(3):
            ax.text(k - 0.2, a_vals[k] + top * 0.01, f"{a_vals[k]:.3f}", ha="center", fontsize=8)
            ax.text(k + 0.2, b_vals[k] + top * 0.01, f"{b_vals[k]:.3f}", ha="center", fontsize=8)
        ax.set_xticks(x)
        ax.set_xticklabels(tick_labels, fontsize=8)
        ax.set_ylabel(ylabel)
        ax.set_ylim(0, top)
        ax.legend(loc="upper left", fontsize=8)
    axes[1].set_title("trained at 96x96, tested at other resolutions", fontsize=10)
    axes[2].set_title("same, localization (lower is better)", fontsize=10)
    fig.tight_layout()
    fig.savefig(os.path.join(args.fig_dir, "ch06-supervised.png"), dpi=120, facecolor="white")
    plt.close(fig)

    # 5. 그림: 학습된 위치 임베딩끼리의 닮음(코사인 유사도)
    with torch.no_grad():
        pos = F.normalize(supervised.pos_embed[0, 1:], dim=-1)  # (144, D)
        similarity = (pos @ pos.T).reshape(12, 12, 12, 12).cpu().numpy()
    fig, axes = plt.subplots(1, 4, figsize=(11, 3.1))
    for ax, (r, c) in zip(axes, [(1, 1), (3, 8), (6, 6), (10, 3)]):
        im = ax.imshow(similarity[r, c], cmap="viridis", vmin=-1, vmax=1)
        ax.plot(c, r, "r*", markersize=10)
        ax.set_title(f"patch (row {r}, col {c})", fontsize=9)
        ax.set_xticks([])
        ax.set_yticks([])
    fig.colorbar(im, ax=axes, shrink=0.85, label="cosine similarity of position embeddings")
    fig.savefig(os.path.join(args.fig_dir, "ch06-pos-embed.png"), dpi=120, facecolor="white", bbox_inches="tight")
    plt.close(fig)

    # 6. 미니 DINO: 라벨 없는 그림 두 종류로 따로 사전 학습한다
    #    (가) 장면: 도형이 1 – 4개 있는 보통의 도형 세상 그림   (나) 도형 하나: 도형이 하나만 있는 그림
    single_set = ShapesDataset(args.n_train, seed=0, min_objects=1, max_objects=1)
    single_test = ShapesDataset(args.n_test, seed=2, min_objects=1, max_objects=1)
    single_images, single_test_images = single_set.images.to(device), single_test.images.to(device)
    single_classes = torch.tensor([int(t["labels"][0]) for t in single_set.targets], device=device)  # 채점(선형 분류기)에만 쓴다
    single_test_classes = torch.tensor([int(t["labels"][0]) for t in single_test.targets], device=device)
    print(f"미니 DINO (라벨 없이): 스텝 {args.dino_steps}, 배치 {dino_batch}, 교사 온도 {args.tau_t}")
    t0 = time.time()
    dino_scene, history_scene = train_dino(train_images, args.dino_steps, batch_size=dino_batch, tau_t=args.tau_t,
                                           seed=args.seed, name="DINO · 장면")
    dino_single, history_single = train_dino(single_images, args.dino_steps, batch_size=dino_batch, tau_t=args.tau_t,
                                             seed=args.seed, name="DINO · 도형 하나")
    print(f"미니 DINO 학습 둘 {time.time() - t0:.1f}초")
    # centering · sharpening 을 하나씩 끈 실험 (도형 하나 그림으로, 짧게)
    t0 = time.time()
    no_center, history_no_center = train_dino(single_images, args.ablation_steps, batch_size=dino_batch, tau_t=args.tau_t,
                                              seed=args.seed, use_centering=False, name="centering 끔")
    no_sharpen, history_no_sharpen = train_dino(single_images, args.ablation_steps, batch_size=dino_batch, tau_t=1.0,
                                                seed=args.seed, name="sharpening 끔")
    print(f"끈 실험 둘 {time.time() - t0:.1f}초, log K = log 256 = {math.log(256):.3f}")

    # 7. 선형 분류기로 얼린 특징 비교 (시험 세트). 세 가지를 묻는다.
    #    ① 장면에 어떤 도형이 있는가 (다중 라벨)  ② 장면에 객체가 몇 개인가  ③ 도형 하나짜리 그림의 도형은 무엇인가
    n_probe = min(4000, len(train_images))
    train_counts = torch.tensor([len(t["labels"]) - 1 for t in train_set.targets], device=device)  # 0 – 3 (= 1 – 4개)
    test_counts = torch.tensor([len(t["labels"]) - 1 for t in test_sets[96].targets], device=device)
    count_majority = torch.bincount(test_counts).max().item() / len(test_counts)
    class_majority = torch.bincount(single_test_classes).max().item() / len(single_test_classes)
    random_backbones = []
    for k in (1, 2):  # 무작위 초기화는 시드를 달리해 두 번: 시드에 따른 흔들림의 크기를 보려고
        torch.manual_seed(args.seed + k)
        random_backbones.append(MiniViT(96, 8, dim=96, depth=4, heads=4).to(device).eval())

    def probe_all(features_of):
        """features_of(그림) → 특징. 세 과제의 시험 정확도를 돌려준다."""
        f_train, f_test = features_of(train_images[:n_probe]), features_of(test_images[96])
        acc, exact = accuracy(linear_probe(f_train, train_labels[:n_probe], f_test, epochs=probe_epochs), test_labels)
        count_acc = (linear_probe(f_train, train_counts[:n_probe], f_test, epochs=probe_epochs).argmax(1) == test_counts)
        s_train, s_test = features_of(single_images[:n_probe]), features_of(single_test_images)
        class_acc = (linear_probe(s_train, single_classes[:n_probe], s_test, epochs=probe_epochs).argmax(1) == single_test_classes)
        return acc, exact, count_acc.float().mean().item(), class_acc.float().mean().item()

    probe_rows = []
    print(f"선형 분류기 (얼린 특징 192차원, 라벨 달린 학습 그림 {n_probe}장, 시험 {args.n_test}장)")
    print(f"  {'백본':26s} | ① 장면의 도형 종류: 라벨 정확도 · 세 라벨 모두 | ② 장면의 객체 수 | ③ 도형 하나의 종류")
    for name, backbone in [("무작위 초기화 (시드 1)", random_backbones[0]), ("무작위 초기화 (시드 2)", random_backbones[1]),
                           ("미니 DINO · 장면", dino_scene), ("미니 DINO · 도형 하나", dino_single),
                           ("centering 끈 DINO", no_center), ("sharpening 끈 DINO", no_sharpen),
                           ("지도 학습 백본 (참고)", supervised)]:
        row = probe_all(lambda images: extract_features(backbone, images))
        probe_rows.append((name, *row))
        print(f"  {name:26s} | {row[0]:.3f} · {row[1]:.3f} | {row[2]:.3f} | {row[3]:.3f}")
    row = probe_all(lambda images: F.avg_pool2d(to_float(images), 8).flatten(1))  # 8×8 평균 낸 픽셀 432개: 신경망 없는 기준
    print(f"  {'픽셀 (8×8 평균, 432차원)':26s} | {row[0]:.3f} · {row[1]:.3f} | {row[2]:.3f} | {row[3]:.3f}")
    print(f"  {'늘 많은 쪽으로 찍기':26s} | {majority:.3f} ·   —   | {count_majority:.3f} | {class_majority:.3f}")

    # 8. 그림: DINO 학습 곡선 (교사 엔트로피 · KL · 배치 평균 분포의 엔트로피)
    def smooth(values, k=25):
        k = min(k, len(values))
        return np.convolve(values, np.ones(k) / k, mode="valid")

    fig, axes = plt.subplots(1, 3, figsize=(12.5, 3.4))
    runs = [("DINO, scenes", history_scene, "#2f6fdb", "-"),
            ("DINO, single-object images", history_single, "#7b3fb5", "-."),
            ("no centering", history_no_center, "#b7620c", "--"),
            ("no sharpening (teacher temp. 1.0)", history_no_sharpen, "#1b8a5a", ":")]
    for ax, column, title in zip(axes, (1, 2, 3), ("teacher entropy h(P_t)", "KL(P_t || P_s) = loss - entropy",
                                                    "entropy of batch-mean P_t")):
        for label, run, color, style in runs:
            ax.plot(smooth(run[:, column]), style, color=color, label=label, linewidth=1.8)
        if column != 2:
            ax.axhline(math.log(256), color="gray", linewidth=0.8, linestyle="-.")
            ax.text(0.99, math.log(256) - 0.05, "log K = 5.55", color="gray", fontsize=8, ha="right", va="top",
                    transform=ax.get_yaxis_transform())
        ax.set_xlabel("step")
        ax.set_title(title, fontsize=10)
    axes[1].legend(fontsize=8)
    fig.tight_layout()
    fig.savefig(os.path.join(args.fig_dir, "ch06-dino-curves.png"), dpi=120, facecolor="white")
    plt.close(fig)

    # 9. 그림: 선형 분류기 결과 막대
    fig, axes = plt.subplots(1, 3, figsize=(13.5, 3.5), sharey=True)
    labels_en = ["random init (seed 1)", "random init (seed 2)", "mini DINO, scenes", "mini DINO, single-object",
                 "DINO, no centering", "DINO, no sharpening", "supervised (reference)"]
    colors = ["#888888", "#aaaaaa", "#2f6fdb", "#7b3fb5", "#b7620c", "#1b8a5a", "#444444"]
    positions = np.arange(len(probe_rows))[::-1]
    for ax, column, base, title in [(axes[0], 1, majority, "(1) scenes: which shapes? (per-label acc.)"),
                                    (axes[1], 3, count_majority, "(2) scenes: how many objects? (acc.)"),
                                    (axes[2], 4, class_majority, "(3) single object: which shape? (acc.)")]:
        values = [row[column] for row in probe_rows]
        bars = ax.barh(positions, values, color=colors)
        for bar, value in zip(bars, values):
            ax.text(value + 0.01, bar.get_y() + bar.get_height() / 2, f"{value:.3f}", va="center", fontsize=9)
        ax.axvline(base, color="black", linestyle="-.", linewidth=0.9)
        ax.set_xlim(0, 1.15)
        ax.set_title(title, fontsize=10)
        ax.set_xlabel("linear-probe accuracy (test); dash-dot line = majority guess", fontsize=9)
    axes[0].set_yticks(positions)
    axes[0].set_yticklabels(labels_en)
    fig.tight_layout()
    fig.savefig(os.path.join(args.fig_dir, "ch06-linear-probe.png"), dpi=120, facecolor="white")
    plt.close(fig)

    # 10. 그림: CLS 토큰의 어텐션 지도 (지도 학습 모델과 미니 DINO 교사 둘)
    n_show = 6
    show = test_images[96][:n_show]
    maps = [m.last_attention(to_float(show)).mean(dim=1).cpu().numpy() for m in (supervised, dino_scene, dino_single)]  # 머리 평균
    fig, axes = plt.subplots(4, n_show, figsize=(1.75 * n_show, 7.4))
    for k in range(n_show):
        axes[0, k].imshow(show[k].permute(1, 2, 0).cpu().numpy(), interpolation="nearest")
        for row, attention in enumerate(maps, start=1):
            axes[row, k].imshow(attention[k], cmap="magma", interpolation="nearest")
        present = [CLASS_NAMES[c][:4] for c in range(NUM_CLASSES) if test_labels[k, c] > 0]
        axes[0, k].set_title("+".join(present), fontsize=8)
    for ax, name in zip(axes[:, 0], ["test image", "supervised ViT\nCLS attention", "mini DINO (scenes)\nCLS attention",
                                     "mini DINO (single-object)\nCLS attention"]):
        ax.set_ylabel(name, fontsize=9)
    for ax in axes.ravel():
        ax.set_xticks([])
        ax.set_yticks([])
    fig.tight_layout(pad=0.4)
    fig.savefig(os.path.join(args.fig_dir, "ch06-attention.png"), dpi=120, facecolor="white")
    plt.close(fig)

    if device == "cuda":
        print(f"GPU 메모리 최대 사용량 {torch.cuda.max_memory_allocated() / 2**20:.0f} MiB")
    print(f"그림 저장: {args.fig_dir}/ch06-*.png, 전체 {time.time() - t_start:.1f}초")


if __name__ == "__main__":
    main()
