"""6장 선택 실습: 진짜 DINOv2 ViT-S/14 의 패치 특징을 도형 세상 그림에서 들여다본다.

하는 일
  1. Hugging Face Hub 에서 공개 가중치 facebook/dinov2-small (ViT-S/14, 약 88MB)을 내려받는다.
  2. 도형 세상 장면을 224×224 로 그려(격자 16×16 = 패치 256개) 넣고, 패치 특징 (256, 384) 을 꺼낸다.
  3. 패치 특징을 주성분 분석(PCA)해 앞의 세 성분을 빨강 · 초록 · 파랑으로 칠한다.
     첫 주성분의 부호만으로 배경과 도형이 갈리는지도 본다 (DINOv2 논문 그림 1 의 절차).
  4. 패치 특징 위에 선형 분류기 하나만 학습해 "이 패치는 배경 · 원 · 사각형 · 삼각형 중 무엇인가" 를 맞혀 본다.
     같은 구조를 무작위로 초기화한 것과 비교한다 — 차이가 곧 "사전 학습이 준 것" 이다.

실행
  pip install transformers          # requirements.txt 에 없는 패키지 (이 파일에서만 쓴다)
  python ch06_dinov2_features.py    # 8GB 노트북 GPU 로 약 1분 30초 (대부분 224×224 그림 900장 그리기와 선형 분류기 학습)
  python ch06_dinov2_features.py --quick

인터넷 연결이 필요하다. 본문 실습(ch06_vit.py)과는 독립이고, 다른 파일이 이 파일을 가져다 쓰지 않는다.
DINOv2 가중치는 Meta AI 가 Apache 2.0 으로 공개한 것이다.
"""

from __future__ import annotations

import argparse
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 NUM_CLASSES, ShapesDataset

MODEL_NAME = "facebook/dinov2-small"
IMAGENET_MEAN = torch.tensor([0.485, 0.456, 0.406]).reshape(1, 3, 1, 1)  # DINOv2 가 학습 때 쓴 입력 정규화
IMAGENET_STD = torch.tensor([0.229, 0.224, 0.225]).reshape(1, 3, 1, 1)


# --8<-- [start:features]
@torch.no_grad()
def patch_features(model, images_uint8: torch.Tensor, device: str, batch_size: int = 100):
    """DINOv2 의 마지막 층 출력을 꺼낸다.

    images_uint8: (n, 3, 224, 224) → CLS (n, 384), 패치 특징 (n, 256, 384).
    출력 토큰 열은 [CLS, 패치 256개] 순서다 (이 가중치는 레지스터 토큰이 없는 판이다).
    """
    cls_list, patch_list = [], []
    for i in range(0, len(images_uint8), batch_size):
        x = images_uint8[i : i + batch_size].to(device).float() / 255.0
        x = (x - IMAGENET_MEAN.to(device)) / IMAGENET_STD.to(device)
        tokens = model(pixel_values=x).last_hidden_state  # (B, 1 + 256, 384)
        cls_list.append(tokens[:, 0].cpu())
        patch_list.append(tokens[:, 1:].cpu())
    return torch.cat(cls_list), torch.cat(patch_list)
# --8<-- [end:features]


# --8<-- [start:patch-labels]
def patch_labels(dataset: ShapesDataset, patch_size: int = 14) -> torch.Tensor:
    """패치마다의 정답: 0 배경, 1 원, 2 사각형, 3 삼각형. (n, 격자²)

    패치 안의 픽셀을 "배경 · 원 · 사각형 · 삼각형" 넷으로 나눠 세어, 가장 많은 것을 그 패치의 라벨로 한다.
    """
    grid = dataset.size // patch_size
    labels = torch.zeros(len(dataset), grid * grid, dtype=torch.int64)
    for i, target in enumerate(dataset.targets):
        pixel_class = torch.zeros(dataset.size, dataset.size, dtype=torch.int64)
        for mask, cls in zip(target["masks"], target["labels"]):
            pixel_class[mask] = int(cls) + 1  # 보이는 부분만 True 인 마스크라 겹쳐도 덮어쓰지 않는다
        one_hot = F.one_hot(pixel_class, NUM_CLASSES + 1).permute(2, 0, 1).float()[None]  # (1, 4, S, S)
        counts = F.avg_pool2d(one_hot, patch_size)[0]  # (4, 격자, 격자): 패치 안에서 각 종류가 차지하는 비율
        labels[i] = counts.argmax(dim=0).flatten()
    return labels
# --8<-- [end:patch-labels]


def linear_probe_patches(train_x, train_y, test_x, test_y, device, epochs=30, seed=0):
    """패치 특징 (패치 수, D) 위에 선형 층 하나로 4종 분류. 돌려주는 값: (정확도, 배경이 아닌 패치만의 정확도)"""
    torch.manual_seed(seed)
    mean, std = train_x.mean(0, keepdim=True), train_x.std(0, keepdim=True) + 1e-6
    train_x, test_x = ((train_x - mean) / std).to(device), ((test_x - mean) / std).to(device)
    train_y, test_y = train_y.to(device), test_y.to(device)
    probe = nn.Linear(train_x.shape[1], NUM_CLASSES + 1).to(device)
    optimizer = torch.optim.AdamW(probe.parameters(), lr=1e-3, weight_decay=1e-2)
    for _ in range(epochs):
        order = torch.randperm(len(train_x), device=device)
        for i in range(0, len(order), 4096):
            index = order[i : i + 4096]
            loss = F.cross_entropy(probe(train_x[index]), train_y[index])
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
    with torch.no_grad():
        correct = probe(test_x).argmax(dim=1) == test_y
        foreground = test_y > 0
        return correct.float().mean().item(), correct[foreground].float().mean().item()


# --8<-- [start:pca]
def pca_colors(features: torch.Tensor) -> np.ndarray:
    """(패치 수, D) 특징 → (패치 수, 3) 색. 앞의 세 주성분을 성분별로 0 – 1 로 늘려 RGB 로 쓴다.

    주성분 분석은 특징이 가장 크게 퍼진 방향부터 차례로 찾는다. 비슷한 특징을 가진 패치는 비슷한 색이 된다.
    """
    centered = features - features.mean(dim=0, keepdim=True)
    _, _, vh = torch.linalg.svd(centered, full_matrices=False)  # vh 의 줄이 주성분 방향
    projected = centered @ vh[:3].T  # (패치 수, 3)
    low, high = projected.min(dim=0).values, projected.max(dim=0).values
    return ((projected - low) / (high - low)).numpy()


def first_component_foreground(features: torch.Tensor):
    """첫 주성분 값과, 그 부호로 가른 "도형 패치" 표시. 수가 적은 쪽을 도형으로 본다 (그림의 대부분은 배경이다)."""
    centered = features - features.mean(dim=0, keepdim=True)
    _, _, vh = torch.linalg.svd(centered, full_matrices=False)
    first = centered @ vh[0]
    positive = first > 0
    if positive.float().mean() > 0.5:  # 주성분의 부호는 임의다: 적은 쪽이 True 가 되게 뒤집는다
        positive = ~positive
    return first, positive
# --8<-- [end:pca]


def main():
    parser = argparse.ArgumentParser(description="6장 선택 실습: 진짜 DINOv2 의 패치 특징")
    parser.add_argument("--quick", action="store_true")
    parser.add_argument("--n-train", type=int, default=600)
    parser.add_argument("--n-test", type=int, default=300)
    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 = 40, 20
    try:
        from transformers import AutoConfig, AutoModel
    except ImportError:
        raise SystemExit("이 선택 실습에는 transformers 가 필요합니다: pip install transformers")

    os.makedirs(args.fig_dir, exist_ok=True)
    torch.manual_seed(args.seed)
    device = "cuda" if torch.cuda.is_available() else "cpu"
    if device == "cpu":
        torch.set_num_threads(min(torch.get_num_threads(), 4))
    print(f"장치: {device}")
    t_start = time.time()

    pretrained = AutoModel.from_pretrained(MODEL_NAME).to(device).eval()
    config = AutoConfig.from_pretrained(MODEL_NAME)
    random_init = AutoModel.from_config(config).to(device).eval()  # 같은 구조, 무작위 가중치
    n_params = sum(p.numel() for p in pretrained.parameters())
    print(f"{MODEL_NAME}: 매개변수 {n_params:,}개, 층 {config.num_hidden_layers}, 차원 {config.hidden_size},"
          f" 머리 {config.num_attention_heads}, 패치 {config.patch_size}, 위치 임베딩 {tuple(pretrained.embeddings.position_embeddings.shape)}")

    # 같은 장면을 224×224 로 그린다: 224 / 14 = 16 → 패치 256개
    train_set = ShapesDataset(args.n_train, size=224, seed=0, with_masks=True)
    test_set = ShapesDataset(args.n_test, size=224, seed=2, with_masks=True)
    train_y, test_y = patch_labels(train_set).flatten(), patch_labels(test_set).flatten()
    background = (test_y == 0).float().mean().item()
    print(f"패치 라벨: 학습 {len(train_y):,}개, 시험 {len(test_y):,}개, 시험 패치 중 배경 {background:.3f}")

    results = {}
    for name, model in [("사전 학습된 DINOv2", pretrained), ("무작위 초기화 (같은 구조)", random_init)]:
        _, train_patches = patch_features(model, train_set.images, device)
        _, test_patches = patch_features(model, test_set.images, device)
        acc, acc_fg = linear_probe_patches(train_patches.flatten(0, 1), train_y, test_patches.flatten(0, 1), test_y,
                                           device, epochs=3 if args.quick else 30)
        results[name] = test_patches
        print(f"  {name:20s} 패치 분류 정확도 {acc:.3f} | 배경이 아닌 패치만 {acc_fg:.3f}")
    print(f"  {'늘 배경이라고 찍기':20s} 패치 분류 정확도 {background:.3f} | 배경이 아닌 패치만 0.000")

    # 첫 주성분 하나로 배경과 도형을 가를 수 있는가 (DINOv2 논문의 그림 1 · 9 가 쓴 절차)
    n_show = 8
    foreground_true = (test_y > 0).reshape(args.n_test, 256)
    rows = [("input 224x224", None)]
    for name, title in [("사전 학습된 DINOv2", "DINOv2 ViT-S/14"), ("무작위 초기화 (같은 구조)", "same ViT, random init")]:
        patches = results[name]  # (시험 그림 수, 256, 384)
        first, foreground = first_component_foreground(patches.flatten(0, 1))
        foreground = foreground.reshape(args.n_test, 256)
        agreement = (foreground == foreground_true).float().mean().item()
        print(f"  {name:20s} 첫 주성분의 부호만으로 배경/도형 가르기: 정답과 일치 {agreement:.3f}")
        colors_all = torch.from_numpy(pca_colors(patches[:n_show].flatten(0, 1))).reshape(n_show, 16, 16, 3)
        colors_fg = torch.zeros(n_show, 256, 3)  # 배경으로 판정한 패치는 검정
        shown = foreground[:n_show]
        colors_fg[shown] = torch.from_numpy(pca_colors(patches[:n_show][shown])).float()
        rows.append((f"{title}\nPCA of all patches", colors_all.numpy()))
        rows.append((f"{title}\n1st PC > 0, then PCA", colors_fg.reshape(n_show, 16, 16, 3).numpy()))

    fig, axes = plt.subplots(len(rows), n_show, figsize=(1.6 * n_show, 1.72 * len(rows)))
    for row, (title, colors) in enumerate(rows):
        for k in range(n_show):
            ax = axes[row, k]
            if colors is None:
                ax.imshow(test_set.images[k].permute(1, 2, 0).numpy(), interpolation="nearest")
            else:
                ax.imshow(colors[k], interpolation="nearest")
            ax.set_xticks([])
            ax.set_yticks([])
        axes[row, 0].set_ylabel(title, fontsize=7)
    fig.tight_layout(pad=0.4)
    fig.savefig(os.path.join(args.fig_dir, "ch06-dinov2-pca.png"), dpi=120, facecolor="white")
    plt.close(fig)
    print(f"그림 저장: {args.fig_dir}/ch06-dinov2-pca.png, 전체 {time.time() - t_start:.1f}초")


if __name__ == "__main__":
    main()
