"""11장 · RF-DETR 의 학습 — 미니 RF-DETR 을 공식 구현과 같은 방식으로 학습한다.

무엇을 하나
  1. 손실 RFDETRCriterion: 질의 묶음마다 따로 헝가리안 매칭(포컬 꼴 비용 2 · 5 · 2) → IoU 인지 BCE(IA-BCE) 분류 손실
     + L1(계수 5) + GIoU(계수 2). 모든 디코더 층과 인코더 제안에 같은 손실을 걸고, 정답 수 × 묶음 수로 나눈다.
  2. 학습 설정: AdamW, 워밍업 · 스케줄 없이 일정한 학습률, 기울기 자르기 0.1, 지수 이동 평균(EMA, 감쇠 0.993 · τ 100),
     층별 학습률 감쇠(백본 블록마다 0.8배) · 구성 요소별 감쇠(0.7) · 백본 학습률을 따로.
  3. 본 실험: 도형 세상(학습 4,000장, 검증 500장)에서 60 에폭. 7장 · 8장의 곡선과 겹쳐 그리고, EMA 모델과 일반 모델,
     디코더 층별 AP(0층 = 인코더 제안만), 예측 그림, 2단계 질의 선택의 모습, 점수와 IoU 의 상관을 본다.
  4. 절제 실험 (--ablations, 각 15 에폭): (a) IA-BCE vs 포컬 손실 (b) 질의 묶음 1개 vs 4개 (c) EMA 유무
     (d) 윈도 1×1 vs 2×2. --seed 를 바꿔 여러 번 돌리면 시드별 요약 표가 함께 나온다.
  5. 절제 실험 (--pretrain): (e) 백본 사전 학습 — 라벨 없는 그림 8,000장으로 마스크 그림 모델링(MIM) 사전 학습을 한
     백본과 무작위 초기화 백본을, 학습 그림 200장(시드 3개) / 4,000장에서, 층별 학습률 감쇠가 있을 때 / 없을 때 비교한다.
  6. 체크포인트 ch11_rfdetr.pt (일반 가중치 + EMA 가중치 + 모델 설정) 와 학습 기록 ch11_history.json 을 실행 폴더에 저장한다.

실행 (한 번에 한 가지 모드. 시간은 노트북 GPU 한 장에서 아래 실행 여럿을 동시에 돌리며 잰 값 — 따로 돌리면 더 빠르다)
  python ch11_train.py                # 본 실험 (약 17분: 60 에폭 학습 16분 + 분석 1분)
  python ch11_train.py --ablations    # 절제 (a) – (d) (약 16분). ch11_ablations_seed0.json 저장. --seed 1 처럼 시드를 바꿀 수 있다
  python ch11_train.py --pretrain     # 절제 (e) (약 25분). ch11_backbone_mim.pt · ch11_pretrain.json 저장
  python ch11_train.py --quick        # 연기 시험 (CPU 약 20초). --quick --ablations (약 15초), --quick --pretrain (약 10초)
그림은 --fig-dir (기본 figures/) 에 저장된다. ch07_history.json · ch08_history.json · ch08_deformable.pt 가 실행 폴더에 있으면
7장 · 8장의 곡선과 점수 분포를 함께 그린다 (없으면 건너뛴다).

12장 ch12_nas.py 가 이 파일의 RFDETRCriterion · ModelEMA · build_optimizer · train_one_epoch · predict ·
evaluate_model 을, 13장 ch13_seg.py 가 RFDETRCriterion 의 매칭 결과와 체크포인트를 가져다 쓴다.
"""

from __future__ import annotations

import argparse
import copy
import glob
import json
import math
import os
import time

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.stats import pearsonr, spearmanr

from ch02_boxes import box_cxcywh_to_xyxy, box_iou, paired_box_iou, paired_generalized_box_iou
from ch03_metrics import evaluate_ap
from ch07_detr import apply_nms, count_duplicates, get_device, is_eval_epoch, plot_predictions, targets_to
from ch08_deformable import gen_proposals, sigmoid_focal_loss
from ch09_lwdetr_parts import GroupHungarianMatcher, WindowedViT, ia_bce_loss
from ch10_rfdetr_model import DEFAULT_CONFIG, MiniRFDETR, postprocess
from rf_shapes import CLASS_NAMES, NUM_CLASSES, ShapesDataset, draw_boxes, make_loader


# ── 1. 손실 ──────────────────────────────────────────────────────────────────


# --8<-- [start:criterion]
class RFDETRCriterion(nn.Module):
    """RF-DETR 의 집합 손실 (공식 criterion.py 의 SetCriterion 과 같은 식).

    층 하나(마지막 디코더 층, 앞 디코더 층들, 인코더 제안)마다
      1) 질의 묶음마다 따로 헝가리안 매칭.  비용 = 2·C_cls(포컬 꼴) + 5·C_L1 + 2·C_GIoU
      2) 분류: IA-BCE (cls_loss="ia_bce", 9장) 또는 포컬 손실 (cls_loss="focal", 8장 — 절제 실험용)
      3) 박스: 매칭된 쌍의 L1 합, (1 − GIoU) 합
      세 손실 모두 num_boxes = (배치의 정답 수) × (묶음 수) 로 나눈다.
    전체 = Σ_층 (1·loss_ce + 5·loss_bbox + 2·loss_giou).
    학습 모드(self.training)에서는 묶음 group_detr 개, 평가 모드에서는 1개로 본다 (모델의 출력과 맞춘다).
    """

    def __init__(self, num_classes: int = NUM_CLASSES, group_detr: int = 4, cls_loss: str = "ia_bce",
                 loss_ce: float = 1.0, loss_bbox: float = 5.0, loss_giou: float = 2.0,
                 alpha: float = 0.25, gamma: float = 2.0):
        super().__init__()
        assert cls_loss in ("ia_bce", "focal")
        self.num_classes, self.group_detr, self.cls_loss = num_classes, group_detr, cls_loss
        self.alpha, self.gamma = alpha, gamma
        self.matcher = GroupHungarianMatcher(cost_class=2.0, cost_bbox=5.0, cost_giou=2.0)
        self.weights = {"loss_ce": loss_ce, "loss_bbox": loss_bbox, "loss_giou": loss_giou}

    @torch.no_grad()
    def match_layers(self, layers, targets, groups: int):
        """여러 층의 매칭을 한꺼번에 한다 (비용 행렬을 GPU 에서 한 번에 만들고 CPU 로 한 번만 옮긴다).

        layers: [{"pred_logits": (B, Q, K), "pred_boxes": (B, Q, 4)}, …]  (Q = 묶음 수 × N)
        돌려주는 값: 층마다 (batch_idx, query_idx, tgt_idx) — 각각 (M,) LongTensor (M = 정답 수 × 묶음 수).
          k 번째 짝: 예측 pred[batch_idx[k], query_idx[k]] ↔ 배치의 정답을 한 줄로 이어 붙인 것의 tgt_idx[k] 번째.
        """
        logits = torch.stack([layer["pred_logits"] for layer in layers])  # (S, B, Q, K)
        boxes = torch.stack([layer["pred_boxes"] for layer in layers])  # (S, B, Q, 4)
        num_layers, batch, total = logits.shape[:3]
        sizes = [len(t["labels"]) for t in targets]
        offsets = np.cumsum([0] + sizes)
        cost = self.matcher.cost_matrix(logits.flatten(0, 2), boxes.flatten(0, 2),
                                        torch.cat([t["labels"] for t in targets]),
                                        torch.cat([t["boxes"] for t in targets]))
        cost = cost.view(num_layers, batch, total, -1).cpu().numpy()  # (S, B, Q, ΣT)
        layer_ids, batch_ids, query_ids, target_ids = [], [], [], []
        for s in range(num_layers):
            for b in range(batch):
                if sizes[b] == 0:
                    continue
                rows, cols = self.matcher.assign_groups(cost[s, b, :, offsets[b]:offsets[b + 1]], groups)
                layer_ids.append(np.full(len(rows), s))
                batch_ids.append(np.full(len(rows), b))
                query_ids.append(rows)
                target_ids.append(cols + offsets[b])
        index = np.stack([np.concatenate(ids) for ids in (layer_ids, batch_ids, query_ids, target_ids)])
        index = torch.as_tensor(index, dtype=torch.long, device=logits.device)  # (4, 전체 짝 수): 한 번에 장치로
        return [tuple(index[1:, index[0] == s]) for s in range(num_layers)]

    def layer_loss(self, layer, matched, tgt_labels, tgt_boxes, num_boxes):
        """층 하나의 세 손실. tgt_labels (ΣT,), tgt_boxes (ΣT, 4): 배치의 정답을 이어 붙인 것."""
        batch_idx, query_idx, tgt_idx = matched
        pred = layer["pred_boxes"][batch_idx, query_idx]  # (M, 4)
        target = tgt_boxes[tgt_idx]  # (M, 4)
        pred_xyxy, target_xyxy = box_cxcywh_to_xyxy(pred), box_cxcywh_to_xyxy(target)
        loss_bbox = F.l1_loss(pred, target, reduction="sum") / num_boxes
        loss_giou = (1 - paired_generalized_box_iou(pred_xyxy, target_xyxy)).sum() / num_boxes
        logits = layer["pred_logits"]
        if self.cls_loss == "ia_bce":
            ious = paired_box_iou(pred_xyxy.detach(), target_xyxy)  # 지금 이 예측 박스가 정답과 얼마나 겹치는가
            loss_ce = ia_bce_loss(logits, (batch_idx, query_idx), tgt_labels[tgt_idx], ious, num_boxes,
                                  self.alpha, self.gamma)
        else:
            onehot = torch.zeros_like(logits)
            onehot[batch_idx, query_idx, tgt_labels[tgt_idx]] = 1.0
            loss_ce = sigmoid_focal_loss(logits, onehot, self.alpha, self.gamma).sum() / num_boxes
        return {"loss_ce": loss_ce, "loss_bbox": loss_bbox, "loss_giou": loss_giou}

    def forward(self, outputs, targets, return_matches: bool = False):
        """outputs: MiniRFDETR 의 출력 사전, targets: 길이 B 의 목록 ({"labels": (T_b,), "boxes": (T_b, 4)}).

        돌려주는 값: 손실 사전. "loss" 가 역전파할 전체 손실. "loss_ce" · "loss_bbox" · "loss_giou" 는 마지막 디코더 층,
        "loss_ce_0" … 은 앞 층들, "loss_ce_enc" … 은 인코더 제안의 값 (계수를 곱하기 전).
        return_matches=True 면 (손실 사전, 매칭 목록) — 매칭 목록의 순서는 [마지막 층, 앞 층 0, 앞 층 1, …, 인코더 제안].
        """
        groups = self.group_detr if self.training else 1
        layers = [outputs] + list(outputs.get("aux_outputs", []))
        suffixes = [""] + [f"_{i}" for i in range(len(layers) - 1)]
        if "enc_outputs" in outputs:
            layers.append(outputs["enc_outputs"])
            suffixes.append("_enc")
        tgt_labels = torch.cat([t["labels"] for t in targets])
        tgt_boxes = torch.cat([t["boxes"] for t in targets])
        num_boxes = max(len(tgt_labels) * groups, 1)
        matches = self.match_layers(layers, targets, groups)
        losses = {}
        for layer, suffix, matched in zip(layers, suffixes, matches):
            for name, value in self.layer_loss(layer, matched, tgt_labels, tgt_boxes, num_boxes).items():
                losses[name + suffix] = value
        losses["loss"] = sum(self.weights["_".join(k.split("_")[:2])] * v for k, v in losses.items())
        return (losses, matches) if return_matches else losses
# --8<-- [end:criterion]


# ── 2. 지수 이동 평균 ────────────────────────────────────────────────────────


# --8<-- [start:ema]
class ModelEMA:
    """가중치의 지수 이동 평균. 공식 구현(RFDETREMACallback)과 같은 식이다.

    옵티마이저가 한 스텝 갈 때마다:   θ_ema ← d·θ_ema + (1 − d)·θ
    감쇠 d 는 처음에 0 에서 출발해 decay 로 올라간다:   d = decay · (1 − exp(−스텝 수 / τ))   (decay 0.993, τ 100)
    처음 몇 스텝은 d ≈ 0 이라 EMA 가 모델을 그대로 따라가므로, 무작위 초기값이 평균에 오래 남지 않는다.
    평가 · 배포에는 self.module (EMA 가중치를 가진 모델 사본) 을 쓴다.
    """

    def __init__(self, model: nn.Module, decay: float = 0.993, tau: float = 100.0):
        self.module = copy.deepcopy(model).eval()
        for p in self.module.parameters():
            p.requires_grad_(False)
        self.decay, self.tau, self.updates = decay, tau, 0

    def effective_decay(self, updates: int) -> float:
        return self.decay * (1 - math.exp(-updates / self.tau)) if self.tau > 0 else self.decay

    @torch.no_grad()
    def update(self, model: nn.Module):
        self.updates += 1
        d = self.effective_decay(self.updates)
        for ema_p, p in zip(self.module.parameters(), model.parameters()):
            ema_p.lerp_(p, 1 - d)  # ema + (1 − d)·(θ − ema) = d·ema + (1 − d)·θ
# --8<-- [end:ema]


# ── 3. 매개변수 그룹: 층별 학습률 감쇠 ───────────────────────────────────────


# --8<-- [start:param-groups]
def vit_layer_id(name: str, num_layers: int) -> int:
    """백본 매개변수의 "층 번호": 임베딩(패치 · CLS · 위치) 0, 블록 i 는 i + 1, 그 밖(마지막 층 정규화)은 num_layers + 1.

    공식 get_dinov2_lr_decay_rate 와 같은 규칙. 학습률 배율은 decay ** (num_layers + 1 − 층 번호) 이다.
    """
    if name.startswith("backbone.blocks."):
        return int(name.split(".")[2]) + 1
    if name.startswith(("backbone.patch_embed", "backbone.cls_token", "backbone.mask_token", "backbone.pos_embed")):
        return 0
    return num_layers + 1


def build_param_groups(model: MiniRFDETR, lr: float = 2e-4, lr_encoder: float | None = None,
                       vit_layer_decay: float = 0.8, component_decay: float = 0.7, weight_decay: float = 1e-4):
    """공식 param_groups.py 의 규칙으로 매개변수마다 학습률 · 가중치 감쇠를 정한다.

      백본(ViT)        lr_encoder · vit_layer_decay^(num_layers + 1 − 층 번호) · component_decay²
                       num_layers = out_feature_indexes[-1] + 1 (공식 구현이 이렇게 센다 — 블록 수보다 1 크다).
                       편향 · 층 정규화 · 임베딩(패치 임베딩의 가중치 포함)은 가중치 감쇠 0
      디코더           lr · component_decay        (디코더 층, decoder_norm, ref_point_head)
      그 밖            lr                          (프로젝터, 2단계 머리, 분류 · 박스 머리, 질의 임베딩)
    lr_encoder 를 주지 않으면 공식 기본값의 비율(1.5e-4 / 1e-4)대로 1.5 · lr.
    돌려주는 값: (옵티마이저에 넘길 그룹 목록, 사람이 읽을 표 [(이름, 학습률, 가중치 감쇠, 매개변수 수)]).
    """
    lr_encoder = 1.5 * lr if lr_encoder is None else lr_encoder
    num_layers = model.config["out_feature_indexes"][-1] + 1
    buckets, table = {}, {}
    for name, p in model.named_parameters():
        if name.startswith("backbone."):
            layer_id = vit_layer_id(name, num_layers)
            p_lr = lr_encoder * vit_layer_decay ** (num_layers + 1 - layer_id) * component_decay**2
            no_decay = layer_id == 0 or name.endswith(".bias") or "norm" in name
            p_wd = 0.0 if no_decay else weight_decay
            label = ("backbone: embeddings" if layer_id == 0 else
                     f"backbone: block {layer_id - 1}" if layer_id <= num_layers else "backbone: final norm")
        elif name.startswith(("decoder.", "decoder_norm.", "ref_point_head.")):
            p_lr, p_wd, label = lr * component_decay, weight_decay, "decoder"
        else:
            p_lr, p_wd = lr, weight_decay
            label = ("projector" if name.startswith("projector.") else
                     "two-stage heads" if name.startswith("enc_") else
                     "query embeddings" if name.startswith(("query_feat", "refpoint_embed")) else "class + box heads")
        buckets.setdefault((p_lr, p_wd), []).append(p)  # 설정이 같은 매개변수는 한 그룹으로
        row = table.setdefault(label, [p_lr, 0])
        row[1] += p.numel()
    groups = [{"params": params, "lr": g_lr, "weight_decay": g_wd} for (g_lr, g_wd), params in buckets.items()]
    return groups, [(label, row[0], row[1]) for label, row in table.items()]


def build_optimizer(model: MiniRFDETR, lr: float = 2e-4, **kwargs):
    """AdamW. 스케줄러는 없다 — RF-DETR 은 학습 내내 같은 학습률을 쓴다 (워밍업도 없다)."""
    groups, table = build_param_groups(model, lr, **kwargs)
    return torch.optim.AdamW(groups, lr=lr, weight_decay=kwargs.get("weight_decay", 1e-4)), table
# --8<-- [end:param-groups]


# ── 4. 학습 · 평가 고리 ──────────────────────────────────────────────────────


# --8<-- [start:train-loop]
def train_one_epoch(model, criterion, loader, optimizer, device, ema: ModelEMA | None = None, max_norm: float = 0.1,
                    resolutions=None, rng: np.random.Generator | None = None, forward_kwargs_fn=None):
    """한 에폭 학습. 돌려주는 값: 손실 이름 → 에폭 평균.

    resolutions: 주면 배치마다 그 가운데 하나를 골라 배치 전체를 그 해상도로 바꾼다 (다중 해상도 학습, 12장).
                 박스는 정규화 좌표라 그대로다. 해상도는 patch_size × num_windows 의 배수여야 한다.
    forward_kwargs_fn: 주면 스텝마다 불러 model 의 forward 인자(num_windows, patch_size …)를 정한다 (12장의 NAS).
    """
    model.train()
    criterion.train()
    sums, steps = {}, 0
    for images, targets in loader:
        images = images.to(device)
        if resolutions:
            size = int(resolutions[rng.integers(len(resolutions))])
            if size != images.shape[-1]:
                images = F.interpolate(images, size=(size, size), mode="bilinear", align_corners=False, antialias=True)
        kwargs = forward_kwargs_fn() if forward_kwargs_fn else {}
        losses = criterion(model(images, **kwargs), targets_to(targets, device))
        optimizer.zero_grad(set_to_none=True)
        losses["loss"].backward()
        nn.utils.clip_grad_norm_(model.parameters(), max_norm)  # 기울기 자르기: 전체 노름을 0.1 이하로
        optimizer.step()
        if ema is not None:
            ema.update(model)  # 스텝마다 EMA 갱신
        for k, v in losses.items():
            sums[k] = sums.get(k, 0.0) + v.detach()
        steps += 1
    return {k: float(v) / steps for k, v in sums.items()}


@torch.no_grad()
def predict(model, dataset, device, batch_size: int = 250, size: int | None = None, **forward_kwargs):
    """데이터셋 전체를 추론 모드로 순전파해 출력을 CPU 에 모은다.

    size: 주면 그림을 그 해상도로 바꿔 넣는다.  forward_kwargs: num_windows · patch_size · dec_layers · num_queries.
    돌려주는 값: {"pred_logits": (n, N, K), "pred_boxes": (n, N, 4), "aux_outputs": [...], "enc_outputs": {...}}.
    """
    model.eval()
    chunks = []
    for start in range(0, len(dataset), batch_size):
        images = dataset.images[start:start + batch_size].to(device).float() / 255.0
        if size is not None and size != images.shape[-1]:
            images = F.interpolate(images, size=(size, size), mode="bilinear", align_corners=False, antialias=True)
        out = model(images, **forward_kwargs)
        layers = [out] + list(out["aux_outputs"]) + ([out["enc_outputs"]] if "enc_outputs" in out else [])
        chunks.append([{k: layer[k].cpu() for k in ("pred_logits", "pred_boxes")} for layer in layers])
    merged = [{k: torch.cat([chunk[i][k] for chunk in chunks]) for k in ("pred_logits", "pred_boxes")}
              for i in range(len(chunks[0]))]
    num_aux = len(out["aux_outputs"])
    result = dict(merged[0], aux_outputs=merged[1:1 + num_aux])
    if "enc_outputs" in out:
        result["enc_outputs"] = merged[-1]
    return result


def evaluate_model(model, dataset, device, **predict_kwargs):
    """검증 AP. 돌려주는 값: (evaluate_ap 의 결과 사전, 예측 목록). predict 의 인자를 그대로 받는다."""
    predictions = postprocess(predict(model, dataset, device, **predict_kwargs))
    return evaluate_ap(predictions, dataset.targets, NUM_CLASSES), predictions


def fit(model, criterion, optimizer, loader, val_set, epochs, device, ema: ModelEMA | None = None,
        max_norm: float = 0.1, eval_fn=is_eval_epoch, eval_raw: bool = True, verbose: bool = True, **train_kwargs):
    """epochs 에폭 학습하며 기록을 남긴다. 돌려주는 값: 기록 사전.

    "epoch" · "loss" · "loss_ce" · "loss_bbox" · "loss_giou" · "time"(누적 초) 은 에폭마다.
    채점한 에폭(eval_fn(epoch, epochs) 가 참)마다 "ap_epoch", 일반 모델의 "AP_raw" · "AP50_raw" · "AP75_raw",
    EMA 모델의 "AP" · "AP50" · "AP75" 가 한 칸씩 늘어난다 (EMA 를 쓰지 않으면 "AP" 등은 일반 모델의 값).
    eval_raw=False 면 EMA 모델만 채점한다 (채점이 느려서; "AP_raw" 등은 비어 있다).
    """
    keys = ("epoch", "loss", "loss_ce", "loss_bbox", "loss_giou", "time", "ap_epoch", "AP", "AP50", "AP75",
            "AP_raw", "AP50_raw", "AP75_raw")
    history = {k: [] for k in keys}
    start = time.time()
    for epoch in range(1, epochs + 1):
        losses = train_one_epoch(model, criterion, loader, optimizer, device, ema, max_norm, **train_kwargs)
        for k in ("loss", "loss_ce", "loss_bbox", "loss_giou"):
            history[k].append(losses[k])
        history["epoch"].append(epoch)
        history["time"].append(time.time() - start)
        if eval_fn(epoch, epochs):
            raw = evaluate_model(model, val_set, device)[0] if eval_raw or ema is None else None
            best = evaluate_model(ema.module, val_set, device)[0] if ema is not None else raw
            history["ap_epoch"].append(epoch)
            for k in ("AP", "AP50", "AP75"):
                history[k].append(best[k])
                if raw is not None:
                    history[k + "_raw"].append(raw[k])
            if verbose:
                text = f"EMA AP {best['AP']:.4f} AP50 {best['AP50']:.4f} AP75 {best['AP75']:.4f} | " if ema else ""
                if raw is not None:
                    text += f"일반 AP {raw['AP']:.4f} AP50 {raw['AP50']:.4f} AP75 {raw['AP75']:.4f} | "
                print(f"에폭 {epoch:3d} | 손실 {losses['loss']:7.4f} (ce {losses['loss_ce']:.4f} "
                      f"bbox {losses['loss_bbox']:.4f} giou {losses['loss_giou']:.4f}) | {text}"
                      f"{time.time() - start:5.0f}초", flush=True)
    if verbose:
        print(f"학습 끝: {time.time() - start:.0f}초")
    return history
# --8<-- [end:train-loop]


# --8<-- [start:run]
def run_experiment(name, train_set, val_set, epochs, device, seed: int = 0, lr: float = 2e-4, batch_size: int = 32,
                   cls_loss: str = "ia_bce", use_ema: bool = True, vit_layer_decay: float = 0.8,
                   component_decay: float = 0.7, lr_encoder: float | None = None, backbone_state=None,
                   eval_fn=is_eval_epoch, eval_raw: bool = True, verbose: bool = True, **model_config):
    """모델 · 손실 · 옵티마이저 · EMA 를 만들어 학습한다. 돌려주는 값: (model, ema 또는 None, history, 그룹 표).

    backbone_state: 사전 학습한 백본의 state_dict (없으면 무작위 초기화).  model_config: MiniRFDETR 의 설정을 덮어쓴다.
    """
    torch.manual_seed(seed)
    model = MiniRFDETR(**model_config).to(device)
    if backbone_state is not None:
        model.backbone.load_state_dict(backbone_state)
    criterion = RFDETRCriterion(NUM_CLASSES, group_detr=model.group_detr, cls_loss=cls_loss).to(device)
    optimizer, table = build_optimizer(model, lr, lr_encoder=lr_encoder, vit_layer_decay=vit_layer_decay,
                                       component_decay=component_decay)
    ema = ModelEMA(model) if use_ema else None
    loader = make_loader(train_set, batch_size, shuffle=True, seed=seed)
    if verbose:
        print(f"\n[{name}] 매개변수 {sum(p.numel() for p in model.parameters()):,}개, 에폭 {epochs}, "
              f"에폭당 {len(loader)} 스텝, 학습 그림 {len(train_set)}장")
    history = fit(model, criterion, optimizer, loader, val_set, epochs, device, ema, eval_fn=eval_fn,
                  eval_raw=eval_raw, verbose=verbose)
    return model, ema, history, table
# --8<-- [end:run]


# ── 5. 백본 사전 학습: 마스크 그림 모델링 ────────────────────────────────────


# --8<-- [start:pretrain]
def patchify(images: torch.Tensor, patch: int) -> torch.Tensor:
    """(B, 3, H, W) → (B, h·w, 3·p·p): 패치마다 픽셀을 한 줄로 편다 (행 우선 패치 순서)."""
    batch, channels, height, width = images.shape
    x = images.unfold(2, patch, patch).unfold(3, patch, patch)  # (B, 3, h, w, p, p)
    return x.permute(0, 2, 3, 1, 4, 5).reshape(batch, -1, channels * patch * patch)


def mim_pretrain(backbone: WindowedViT, images: torch.Tensor, epochs: int, device, batch_size: int = 128,
                 lr: float = 5e-4, mask_ratio: float = 0.5, seed: int = 0, verbose: bool = True):
    """라벨 없이 하는 백본 사전 학습: 마스크 그림 모델링 (SimMIM 방식의 축소판).

    패치의 절반을 가리고(그 자리의 패치 임베딩을 학습되는 mask_token 으로 바꾼다) 백본을 통과시킨 뒤,
    마지막 특징 맵의 각 칸에서 선형 층 하나로 그 패치의 픽셀 3·p·p 개를 맞힌다. 손실은 가린 패치의 L1.
    보이는 패치만으로 가려진 곳을 채우려면 도형의 모양 · 경계를 알아야 한다 → 라벨 없이도 쓸모 있는 특징이 생긴다.
    (RF-DETR 의 DINOv2 는 다른 자기 지도 방식이고, LW-DETR 의 CAEv2 가 이 계열(MIM)이다.)
    images: (n, 3, H, W) uint8.  돌려주는 값: 에폭별 평균 손실 목록, 복원 머리 (그림용).
    """
    generator = torch.Generator().manual_seed(seed)
    torch.manual_seed(seed)
    patch = backbone.patch_size
    head = nn.Linear(backbone.dim, 3 * patch * patch).to(device)
    backbone.to(device).train()
    optimizer = torch.optim.AdamW(list(backbone.parameters()) + list(head.parameters()), lr=lr, weight_decay=0.05)
    history = []
    for epoch in range(1, epochs + 1):
        order = torch.randperm(len(images), generator=generator)
        total, steps = 0.0, 0
        for start in range(0, len(order) - batch_size + 1, batch_size):
            x = images[order[start:start + batch_size]].to(device).float() / 255.0
            target = patchify((x - 0.5) / 0.25, patch)  # (B, h·w, 3·p·p)
            mask = torch.rand(target.shape[:2], device=device) < mask_ratio  # (B, h·w): True = 가린다
            feature = backbone(x, mask=mask)[-1]  # (B, C, h, w)
            pred = head(feature.flatten(2).transpose(1, 2))  # (B, h·w, 3·p·p)
            loss = ((pred - target).abs().mean(-1) * mask).sum() / mask.sum()
            optimizer.zero_grad(set_to_none=True)
            loss.backward()
            optimizer.step()
            total += float(loss.detach())
            steps += 1
        history.append(total / steps)
        if verbose and (epoch <= 3 or epoch % 5 == 0 or epoch == epochs):
            print(f"  사전 학습 에폭 {epoch:3d} | 가린 패치의 L1 손실 {history[-1]:.4f}", flush=True)
    return history, head
# --8<-- [end:pretrain]


# ── 6. 분석 ──────────────────────────────────────────────────────────────────


def layer_table(outputs, dataset):
    """디코더 층 수별 AP: 0층(인코더 제안만) … L층. NMS 를 건 뒤의 AP 와 중복 쌍의 수도 함께."""
    layers = [outputs["enc_outputs"]] + list(outputs["aux_outputs"]) + [outputs]
    rows = []
    print("디코더 층 수 | AP     AP50   AP75  | NMS 뒤 AP  AP50  | 점수≥0.5 예측 수 | 그중 IoU>0.5 로 겹치는 쌍")
    for depth, layer in enumerate(layers):
        predictions = postprocess(layer)
        plain = evaluate_ap(predictions, dataset.targets, NUM_CLASSES)
        with_nms = evaluate_ap(apply_nms(predictions), dataset.targets, NUM_CLASSES)
        pairs, confident = count_duplicates(predictions)
        rows.append({"AP": plain["AP"], "AP50": plain["AP50"], "AP75": plain["AP75"], "AP_nms": with_nms["AP"],
                     "AP50_nms": with_nms["AP50"], "pairs": pairs, "confident": confident})
        name = f"{depth} (제안)" if depth == 0 else f"{depth}       "
        print(f"   {name:9s} | {plain['AP']:.4f} {plain['AP50']:.4f} {plain['AP75']:.4f} | "
              f"{with_nms['AP']:.4f}  {with_nms['AP50']:.4f} | {confident:8d}         | {pairs:6d}")
    return rows


def score_iou_pairs(predictions, targets, iou_threshold: float = 0.5):
    """정답 객체마다 "그 객체를 찾은 예측" 의 (점수, IoU) 를 모은다. 돌려주는 값: (점수 배열, IoU 배열, 정답 객체 수).

    찾은 예측 = 클래스가 같고 IoU 가 iou_threshold 이상인 예측 가운데 점수가 가장 높은 것
    (3장의 채점에서 그 객체의 참 양성이 되는 예측). 그런 예측이 없는 객체(놓친 객체)는 뺀다.
    """
    scores, ious, total = [], [], 0
    for pred, target in zip(predictions, targets):
        total += len(target["labels"])
        if len(target["labels"]) == 0:
            continue
        iou, _ = box_iou(box_cxcywh_to_xyxy(pred["boxes"]), box_cxcywh_to_xyxy(target["boxes"]))  # (예측, 정답)
        valid = (iou >= iou_threshold) & (pred["labels"][:, None] == target["labels"][None, :])
        candidate = torch.where(valid, pred["scores"][:, None], torch.full_like(iou, -1.0))  # 후보가 아니면 −1
        best_score, best_pred = candidate.max(dim=0)  # 정답마다: 후보 가운데 점수가 가장 높은 예측
        found = best_score >= 0
        scores.append(best_score[found])
        ious.append(iou[best_pred, torch.arange(iou.shape[1])][found])
    return torch.cat(scores).numpy(), torch.cat(ious).numpy(), total


def score_iou_report(name, predictions, targets):
    """점수가 박스 품질(IoU)을 얼마나 따라가는가. 돌려주는 값: (통계 사전, (점수, IoU))."""
    s, u, total = score_iou_pairs(predictions, targets)
    nan = float("nan")
    row = {"n": len(s), "total": total, "pearson": nan, "spearman": nan, "mean_score": nan, "mean_iou": nan, "gap": nan}
    if len(s) < 3:  # 거의 학습되지 않은 모델 (--quick): 상관을 계산할 수 없다
        print(f"  {name:28s} | 찾은 객체가 {len(s)}개뿐이라 상관을 계산하지 않음")
        return row, (s, u)
    row.update(pearson=float(pearsonr(s, u)[0]), spearman=float(spearmanr(s, u)[0]), mean_score=float(s.mean()),
               mean_iou=float(u.mean()), gap=float(np.abs(s - u).mean()))
    print(f"  {name:28s} | 찾은 객체 {row['n']:4d} / {total} | 피어슨 {row['pearson']:+.3f} | 스피어만 {row['spearman']:+.3f} | "
          f"평균 점수 {row['mean_score']:.3f} | 평균 IoU {row['mean_iou']:.3f} | 평균 |점수 − IoU| {row['gap']:.3f}")
    return row, (s, u)


def first_epoch_reaching(history, level, key="AP"):
    reached = [e for e, ap in zip(history["ap_epoch"], history[key]) if ap >= level]
    return reached[0] if reached else None


# ── 7. 그림 ──────────────────────────────────────────────────────────────────

COLORS = ["#0072B2", "#D55E00", "#009E73", "#CC79A7", "#E69F00", "#56B4E9", "#000000"]
STYLES = ["-", "--", "-.", ":", (0, (5, 1)), (0, (3, 1, 1, 1)), (0, (1, 1))]
MARKERS = ["o", "s", "^", "d", "v", "x", "+"]


def plot_curves(history, path):
    import matplotlib.pyplot as plt

    epochs, ap_epochs = history["epoch"], history["ap_epoch"]
    fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))
    ax = axes[0]
    ax.plot(epochs, history["loss_ce"], "-", color=COLORS[0], label="class (IA-BCE)")
    ax.plot(epochs, [5 * v for v in history["loss_bbox"]], "--", color=COLORS[1], label="5 x L1")
    ax.plot(epochs, [2 * v for v in history["loss_giou"]], "-.", color=COLORS[2], label="2 x (1 - GIoU)")
    ax.set_xlabel("epoch")
    ax.set_ylabel("training loss (last decoder layer)")
    ax.set_yscale("log")
    ax.set_title("mini RF-DETR: training loss (constant learning rate)", fontsize=10)
    ax.grid(alpha=0.3, which="both")
    ax.legend(fontsize=8)
    ax = axes[1]
    for k, (key, label) in enumerate((("AP50", "AP50"), ("AP", "AP (IoU .50:.95)"), ("AP75", "AP75"))):
        ax.plot(ap_epochs, history[key], "-", color=COLORS[k], lw=2 if key == "AP" else 1.3, label=f"{label}, EMA model")
        ax.plot(ap_epochs, history[key + "_raw"], ":", color=COLORS[k], lw=1.3, label=f"{label}, raw model")
    ax.set_xlabel("epoch")
    ax.set_ylabel("validation AP")
    ax.set_ylim(0, 1)
    ax.set_title("mini RF-DETR: validation AP", fontsize=10)
    ax.grid(alpha=0.3)
    ax.legend(fontsize=7.5, loc="lower right", ncol=2)
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


def plot_convergence(curves, path, title):
    """curves: [(이름, 에폭 목록, {"AP": […], "AP75": […]})]. 검증 AP · AP75 곡선을 겹쳐 그린다."""
    import matplotlib.pyplot as plt

    fig, axes = plt.subplots(1, 2, figsize=(11, 3.9))
    for ax, key in zip(axes, ("AP", "AP75")):
        for k, (name, epochs, values) in enumerate(curves):
            ax.plot(epochs, values[key], linestyle=STYLES[k], marker=MARKERS[k], markersize=3.5, color=COLORS[k],
                    label=name)
        ax.set_xlabel("epoch")
        ax.set_ylabel(f"validation {key}")
        ax.set_ylim(0, 1)
        ax.grid(alpha=0.3)
        ax.set_title(f"{title}: {key}", fontsize=10)
        ax.legend(fontsize=8, loc="lower right")
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


def plot_ema(history, steps_per_epoch, path, decay=0.993, tau=100.0):
    import matplotlib.pyplot as plt

    fig, axes = plt.subplots(1, 3, figsize=(13, 3.8))
    ax = axes[0]
    steps = np.arange(1, 1001)
    d = decay * (1 - np.exp(-steps / tau))
    ax.plot(steps, d, color=COLORS[0], lw=2, label="effective decay d")
    ax.axhline(decay, color="gray", ls="--", lw=0.8)
    ax.text(990, decay - 0.045, f"decay = {decay}", ha="right", fontsize=8, color="gray")
    ax.set_xlabel("optimizer step")
    ax.set_ylabel("d = decay * (1 - exp(-step / tau))")
    ax.set_title(f"EMA warm-up (tau = {tau:.0f})", fontsize=10)
    ax.grid(alpha=0.3)
    twin = ax.twinx()
    twin.plot(steps, 1 / (1 - d), color=COLORS[1], ls="--", label="averaging window 1 / (1 - d)")
    twin.set_ylabel("steps averaged over, 1 / (1 - d)")
    lines = ax.get_lines()[:1] + twin.get_lines()
    ax.legend(lines, [line.get_label() for line in lines], fontsize=8, loc="center right")
    ax = axes[1]
    ap_epochs = history["ap_epoch"]
    ax.plot(ap_epochs, history["AP_raw"], ":", marker="s", markersize=3.5, color=COLORS[1], label="raw model")
    ax.plot(ap_epochs, history["AP"], "-", marker="o", markersize=3.5, color=COLORS[0], label="EMA model")
    ax.set_xlabel("epoch")
    ax.set_ylabel("validation AP")
    ax.set_title(f"validation AP ({steps_per_epoch} steps per epoch)", fontsize=10)
    ax.grid(alpha=0.3)
    ax.legend(fontsize=8, loc="lower right")
    ax = axes[2]
    diff = np.array(history["AP"]) - np.array(history["AP_raw"])
    ax.bar(range(len(diff)), diff, color=[COLORS[0] if v >= 0 else COLORS[1] for v in diff])
    ax.axhline(0, color="black", lw=0.8)
    ax.set_xticks(range(len(diff)))
    ax.set_xticklabels(ap_epochs, fontsize=7)
    ax.set_xlabel("epoch")
    ax.set_ylabel("AP(EMA) - AP(raw)")
    ax.set_title("EMA minus raw (blue: EMA better)", fontsize=10)
    ax.grid(alpha=0.3, axis="y")
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


def plot_lr_groups(table, flat_table, path):
    import matplotlib.pyplot as plt

    fig, ax = plt.subplots(figsize=(10.5, 4.0))
    labels = [row[0] for row in table]
    x = np.arange(len(table))
    ax.bar(x - 0.2, [row[1] * 1e4 for row in table], 0.4, color=COLORS[0],
           label="official rule: layer decay 0.8, component decay 0.7, lr_encoder = 1.5 lr")
    ax.bar(x + 0.2, [row[1] * 1e4 for row in flat_table], 0.4, color=COLORS[1], hatch="//", edgecolor="white",
           label="flat: one learning rate for everything")
    for xi, row in zip(x, table):
        ax.text(xi - 0.2, row[1] * 1e4, f"{row[1] * 1e4:.2f}", ha="center", va="bottom", fontsize=7)
    ax.set_xticks(x)
    counts = [f"{row[2] / 1e3:.0f}K" if row[2] >= 1000 else str(row[2]) for row in table]
    ax.set_xticklabels([f"{label}\n({count})" for label, count in zip(labels, counts)], rotation=40, ha="right",
                       fontsize=7.5)
    ax.set_ylim(0, 2.75)
    ax.set_ylabel("learning rate (x 1e-4)")
    ax.set_title("learning rate of each parameter group (base lr = 2e-4; number of parameters in brackets)", fontsize=10)
    ax.grid(alpha=0.3, axis="y")
    ax.legend(fontsize=8, loc="upper left")
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


def plot_layers(rows, path):
    import matplotlib.pyplot as plt

    depth = list(range(len(rows)))
    fig, axes = plt.subplots(1, 2, figsize=(9.6, 3.9))
    for ax, key, title in ((axes[0], "AP", "AP (IoU .50:.95)"), (axes[1], "AP50", "AP50")):
        ax.plot(depth, [r[key] for r in rows], "o-", color=COLORS[0], label="as predicted (no NMS)")
        ax.plot(depth, [r[key + "_nms"] for r in rows], "s--", color=COLORS[1], label="after NMS")
        for d, r in zip(depth, rows):
            ax.annotate(f"{r[key]:.4f}", (d, r[key]), xytext=(0, -13), textcoords="offset points", ha="center",
                        fontsize=7.5, color=COLORS[0])
        low = min(min(r[key], r[key + "_nms"]) for r in rows)
        high = max(max(r[key], r[key + "_nms"]) for r in rows)
        if high > low:  # (연기 시험처럼 값이 모두 같으면 축 범위를 건드리지 않는다)
            ax.set_ylim(low - 0.35 * (high - low), high + 0.15 * (high - low))
        ax.set_xticks(depth)
        ax.set_xticklabels(["0\n(encoder\nproposals)"] + [str(d) for d in depth[1:]])
        ax.set_xlabel("number of decoder layers used")
        ax.set_ylabel(f"validation {title}")
        ax.set_title(f"mini RF-DETR (EMA): {title} by decoder depth", fontsize=9.5)
        ax.grid(alpha=0.3)
        ax.legend(fontsize=8, loc="upper left")
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


def plot_selection(model, dataset, indices, path, device, score_threshold=0.5):
    """2단계 질의 선택: 고른 칸 → 인코더 제안 박스 → 기준 박스 → 디코더 층마다의 박스."""
    import matplotlib.pyplot as plt

    model.eval()
    images = dataset.images[indices].to(device).float() / 255.0
    with torch.no_grad():
        out = model(images, return_features=True)
    f = out["features"]
    grid_h, grid_w = f["spatial_shapes"][0]
    proposals = gen_proposals(f["spatial_shapes"])[f["topk"].cpu()]  # (n, N, 4) 선택된 칸의 제안 박스
    layers = [out["enc_outputs"]] + list(out["aux_outputs"]) + [out]
    final_scores = out["pred_logits"].sigmoid().max(-1).values.cpu()  # (n, N)
    titles = ["selected cells", "encoder proposals (depth 0)"]
    titles += [f"decoder layer {k}" for k in range(1, len(layers))]
    fig, axes = plt.subplots(len(indices), len(layers) + 1, figsize=(2.75 * (len(layers) + 1), 2.95 * len(indices)))
    for row, index in enumerate(indices):
        image, target = dataset[index]
        keep = final_scores[row] >= score_threshold  # 마지막 층에서 점수가 문턱값 이상이 되는 질의
        ax = axes[row, 0]
        draw_boxes(ax, image, target["boxes"], color="white", linestyle="--", linewidth=1.0)
        draw_boxes(ax, image, proposals[row][~keep], color="#bbbbbb", linewidth=1.0)
        draw_boxes(ax, image, proposals[row][keep], color="#ffd400", linewidth=1.6)
        for k in range(1, grid_h):
            ax.axhline(k * image.shape[1] / grid_h - 0.5, color="white", lw=0.25, alpha=0.5)
            ax.axvline(k * image.shape[2] / grid_w - 0.5, color="white", lw=0.25, alpha=0.5)
        ax.set_ylabel(f"val #{index}", fontsize=8)
        if row == 0:
            ax.set_title(titles[0], fontsize=8)
        for col, layer in enumerate(layers):
            ax = axes[row, col + 1]
            scores, labels = layer["pred_logits"][row].sigmoid().max(-1)
            draw_boxes(ax, image, target["boxes"], color="white", linestyle="--", linewidth=1.0)
            draw_boxes(ax, image, layer["pred_boxes"][row][keep].cpu(), labels[keep].cpu(), scores[keep].cpu(),
                       fontsize=6.5)
            ax.set_title(titles[col + 1] if row == 0 else "", fontsize=8)
    fig.suptitle("left: 0.05 x 0.05 proposals of the 12 selected cells (yellow: queries that end with score >= 0.5, grey: the "
                 "others); right: boxes of the yellow queries after each stage (white dashed: ground truth)", fontsize=9)
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


def plot_score_iou(panels, path):
    """panels: [(제목, (점수, IoU), 통계 사전)]. 정답 객체마다 그 객체를 찾은 예측의 점수와 IoU 의 산점도."""
    import matplotlib.pyplot as plt

    fig, axes = plt.subplots(1, len(panels), figsize=(4.6 * len(panels), 4.3), squeeze=False)
    for ax, (title, (scores, ious), row) in zip(axes[0], panels):
        ax.scatter(ious, scores, s=5, alpha=0.35, color=COLORS[0], linewidths=0)
        bins = np.linspace(0.5, 1.0, 11)
        centers, means = [], []
        for lo, hi in zip(bins[:-1], bins[1:]):
            inside = (ious >= lo) & (ious < hi)
            if inside.sum() >= 5:
                centers.append((lo + hi) / 2)
                means.append(scores[inside].mean())
        ax.plot(centers, means, "o-", color=COLORS[1], lw=2, label="mean score per IoU bin")
        ax.plot([0.5, 1], [0.5, 1], color="gray", lw=0.8, ls="--", label="score = IoU")
        ax.set_xlim(0.5, 1.0)
        ax.set_ylim(0, 1.02)
        ax.set_xlabel("IoU between an object and the prediction that detects it")
        ax.set_ylabel("score of that prediction")
        ax.set_title(f"{title}\nPearson r = {row['pearson']:+.2f}, Spearman = {row['spearman']:+.2f}, "
                     f"mean |score - IoU| = {row['gap']:.2f}", fontsize=8.5)
        ax.grid(alpha=0.3)
        ax.legend(fontsize=8, loc="lower left")
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


def plot_mim(backbone, head, images, path, device, mask_ratio=0.5, seed=0):
    """사전 학습한 백본의 복원 예: 원본 / 가린 그림 / 복원(가린 패치만 채움)."""
    import matplotlib.pyplot as plt

    patch = backbone.patch_size
    x = images.to(device).float() / 255.0
    grid = x.shape[-1] // patch
    generator = torch.Generator().manual_seed(seed)
    mask = (torch.rand(len(x), grid * grid, generator=generator) < mask_ratio).to(device)
    backbone.eval()
    with torch.no_grad():
        pred = head(backbone(x, mask=mask)[-1].flatten(2).transpose(1, 2)) * 0.25 + 0.5  # (n, h·w, 3·p·p), 0 – 1 눈금
    target = patchify(x, patch)
    filled = torch.where(mask[..., None], pred, target).clamp(0, 1)
    hidden = torch.where(mask[..., None], torch.full_like(target, 0.5), target)

    def unpatchify(t):
        t = t.reshape(len(x), grid, grid, 3, patch, patch).permute(0, 3, 1, 4, 2, 5)
        return t.reshape(len(x), 3, grid * patch, grid * patch).cpu().numpy()

    rows = (("original", x.cpu().numpy()), (f"{int(mask_ratio * 100)}% of patches hidden (grey)", unpatchify(hidden)),
            ("reconstruction (hidden patches filled in)", unpatchify(filled)))
    fig, axes = plt.subplots(3, len(x), figsize=(2.2 * len(x), 6.9))
    for r, (title, batch) in enumerate(rows):
        for c in range(len(x)):
            axes[r, c].imshow(np.transpose(batch[c], (1, 2, 0)), interpolation="nearest")
            axes[r, c].set_xticks([])
            axes[r, c].set_yticks([])
        axes[r, 0].set_ylabel(title, fontsize=8)
    fig.suptitle("masked image modelling on unlabeled Shape World images (validation images, not seen in pre-training)",
                 fontsize=10)
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


def plot_pretrain(mim_loss, small_runs, large_rows, path):
    """small_runs: {설정 이름: [시드마다의 history]}, large_rows: [(이름, AP)]."""
    import matplotlib.pyplot as plt

    fig, axes = plt.subplots(1, 3, figsize=(14, 4.0))
    ax = axes[0]
    ax.plot(range(1, len(mim_loss) + 1), mim_loss, "-", color=COLORS[0])
    ax.set_xlabel("pre-training epoch")
    ax.set_ylabel("L1 loss on hidden patches")
    ax.set_title("backbone pre-training (masked image modelling)", fontsize=10)
    ax.grid(alpha=0.3)
    ax = axes[1]
    for k, (name, histories) in enumerate(small_runs.items()):
        epochs = histories[0]["ap_epoch"]
        values = np.array([h["AP"] for h in histories])
        ax.plot(epochs, values.mean(0), linestyle=STYLES[k], marker=MARKERS[k], markersize=4, color=COLORS[k], label=name)
        if len(histories) > 1:
            ax.fill_between(epochs, values.min(0), values.max(0), color=COLORS[k], alpha=0.15)
    ax.set_xlabel("epoch")
    ax.set_ylabel("validation AP (EMA model)")
    ax.set_ylim(0, 1)
    ax.set_title(f"fine-tuning on 200 images (mean of {len(next(iter(small_runs.values())))} seeds, band = min-max)",
                 fontsize=10)
    ax.grid(alpha=0.3)
    ax.legend(fontsize=8, loc="lower right")
    ax = axes[2]
    names = [name for name, _ in large_rows]
    values = [value for _, value in large_rows]
    ax.bar(range(len(values)), values, color=[COLORS[0], COLORS[2]] * (len(values) // 2 + 1))
    for i, v in enumerate(values):
        ax.text(i, v + 0.01, f"{v:.3f}", ha="center", fontsize=8)
    ax.set_xticks(range(len(values)))
    ax.set_xticklabels(names, fontsize=8)
    ax.set_ylabel("final validation AP (EMA model)")
    ax.set_ylim(0, 1.05)
    ax.set_title("random vs pre-trained backbone (official learning-rate rule)", fontsize=10)
    ax.grid(alpha=0.3, axis="y")
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


# ── 8. 본 실험과 절제 실험 ───────────────────────────────────────────────────


def small_checks(device):
    """학습 전에: 손실의 손계산 대조, EMA 감쇠, 매개변수 그룹."""
    torch.manual_seed(0)
    model = MiniRFDETR().to(device)
    criterion = RFDETRCriterion().to(device)
    dataset = ShapesDataset(4, seed=0)
    images = (dataset.images.float() / 255.0).to(device)
    targets = targets_to(dataset.targets, device)
    model.train()
    criterion.train()
    outputs = model(images)
    losses, matches = criterion(outputs, targets, return_matches=True)
    num_targets = sum(len(t["labels"]) for t in targets)
    print(f"[손실] 그림 4장 (정답 {num_targets}개), 학습 모드: 질의 {outputs['pred_logits'].shape[1]}개 = "
          f"{model.num_queries} × 묶음 {model.group_detr}")
    print(f"  층 {len(matches)}개 (마지막 층, 앞 층 {len(outputs['aux_outputs'])}개, 인코더 제안) 마다 짝 "
          f"{[len(m[0]) for m in matches]}개 = 정답 {num_targets} × 묶음 {model.group_detr},  num_boxes = "
          f"{num_targets * model.group_detr}")
    losses = {k: v.detach() for k, v in losses.items()}
    print("  " + ", ".join(f"{k} {float(v):.4f}" for k, v in losses.items() if k != "loss"))
    manual = sum(float(losses[f"loss_ce{s}"]) + 5 * float(losses[f"loss_bbox{s}"]) + 2 * float(losses[f"loss_giou{s}"])
                 for s in ("", "_0", "_1", "_enc"))
    print(f"  check 전체 손실 {float(losses['loss']):.4f} = Σ_층 (1·ce + 5·bbox + 2·giou) = {manual:.4f}")
    # 묶음을 하나씩 떼어 따로 계산한 손실의 평균과 같은가 (num_boxes 에 묶음 수를 곱했으므로)
    criterion.eval()
    per_group = []
    n = model.num_queries
    for g in range(model.group_detr):
        part = {k: v[:, g * n:(g + 1) * n].detach() for k, v in outputs.items() if k in ("pred_logits", "pred_boxes")}
        per_group.append(float(criterion(part, targets)["loss_ce"]))
    criterion.train()
    print(f"  check 마지막 층 loss_ce {float(losses['loss_ce']):.6f} = 묶음별 loss_ce {np.round(per_group, 4).tolist()} 의 평균 "
          f"{np.mean(per_group):.6f}")

    ema = ModelEMA(model)
    print("[EMA] 실효 감쇠 d = 0.993·(1 − exp(−스텝/100)):  " +
          ", ".join(f"스텝 {s}: {ema.effective_decay(s):.4f}" for s in (1, 10, 50, 100, 300, 1000)))
    before = [p.clone() for p in ema.module.parameters()]
    with torch.no_grad():
        for p in model.parameters():
            p.add_(0.1)
    ema.update(model)
    d = ema.effective_decay(1)
    shift = float(torch.cat([(a - b).flatten() for a, b in zip(ema.module.parameters(), before)]).mean())
    print(f"  check 모델의 모든 가중치를 +0.1 한 뒤 EMA 를 한 번 갱신: EMA 의 변화 {shift:.5f} = (1 − d)·0.1 = {(1 - d) * 0.1:.5f}")

    _, table = build_optimizer(model, 2e-4)
    _, flat = build_optimizer(model, 2e-4, lr_encoder=2e-4, vit_layer_decay=1.0, component_decay=1.0)
    print("[매개변수 그룹] 기본 학습률 2e-4, lr_encoder 3e-4, 층별 감쇠 0.8, 구성 요소별 감쇠 0.7")
    print("    그룹                    | 학습률     | 기본 학습률의 몇 배 | 매개변수 수")
    for label, group_lr, count in table:
        print(f"    {label:23s} | {group_lr:.3e} | {group_lr / 2e-4:8.3f}          | {count:9,d}")
    return table, flat


def main_experiment(args, device, train_set, val_set, table, flat_table):
    epochs = 2 if args.quick else 60
    start = time.time()
    model, ema, history, _ = run_experiment("미니 RF-DETR (본 실험)", train_set, val_set, epochs, device, args.seed)
    steps_per_epoch = len(train_set) // 32
    print(f"[본 실험] 학습 {history['time'][-1]:.0f}초 ({steps_per_epoch * epochs} 스텝), "
          f"EMA 모델 AP {history['AP'][-1]:.4f} AP50 {history['AP50'][-1]:.4f} AP75 {history['AP75'][-1]:.4f} | "
          f"일반 모델 AP {history['AP_raw'][-1]:.4f} AP50 {history['AP50_raw'][-1]:.4f} AP75 {history['AP75_raw'][-1]:.4f}")
    torch.save({"model": model.state_dict(), "ema": ema.module.state_dict(), "config": model.config,
                "history": history, "epochs": epochs}, "ch11_rfdetr.pt")
    with open("ch11_history.json", "w") as f:
        json.dump(history, f)
    print("저장: ch11_rfdetr.pt (model · ema · config · history), ch11_history.json")

    # 7장 · 8장과 수렴 비교
    curves = []
    for name, path in (("ch07 MiniDETR", "ch07_history.json"), ("ch08 Deformable DETR", "ch08_history.json")):
        if os.path.exists(path):
            with open(path) as f:
                other = json.load(f)
            curves.append((name, other["ap_epoch"], other))
        else:
            print(f"({path} 가 없어 {name} 곡선은 건너뜀)")
    curves.append(("ch11 mini RF-DETR (EMA)", history["ap_epoch"], history))
    curves.append(("ch11 mini RF-DETR (raw)", history["ap_epoch"],
                   {"AP": history["AP_raw"], "AP75": history["AP75_raw"]}))
    print("[수렴 비교] 검증 AP (채점한 에폭)")
    print("  에폭 | " + " | ".join(f"{name:24s}" for name, _, _ in curves))
    for i, epoch in enumerate(history["ap_epoch"]):
        cells = []
        for _, other_epochs, values in curves:
            cells.append(f"{values['AP'][other_epochs.index(epoch)]:.4f}".ljust(24) if epoch in other_epochs else " " * 24)
        print(f"  {epoch:4d} | " + " | ".join(cells))
    for name, other_epochs, values in curves:
        reach = {level: next((e for e, ap in zip(other_epochs, values["AP"]) if ap >= level), None)
                 for level in (0.5, 0.8, 0.9)}
        print(f"  {name}: AP 0.5 / 0.8 / 0.9 에 처음 닿은 에폭 = {reach[0.5]} / {reach[0.8]} / {reach[0.9]}, "
              f"마지막 AP {values['AP'][-1]:.4f}")
    plot_curves(history, os.path.join(args.fig_dir, "ch11-curves.png"))
    plot_convergence(curves, os.path.join(args.fig_dir, "ch11-convergence.png"), "same data, same number of epochs")
    plot_ema(history, steps_per_epoch, os.path.join(args.fig_dir, "ch11-ema.png"))
    plot_lr_groups(table, flat_table, os.path.join(args.fig_dir, "ch11-lr-groups.png"))
    gaps = np.array(history["AP"]) - np.array(history["AP_raw"])
    print(f"[EMA vs 일반] 채점한 {len(gaps)}개 에폭 가운데 EMA 가 높은 에폭 {int((gaps > 0).sum())}개, "
          f"차이의 평균 {gaps.mean():+.4f}, 범위 {gaps.min():+.4f} – {gaps.max():+.4f}, 마지막 에폭 {gaps[-1]:+.4f}")
    late = [i for i, e in enumerate(history["ap_epoch"]) if e > epochs // 2]
    raw_late, ema_late = np.array(history["AP_raw"])[late], np.array(history["AP"])[late]
    print(f"  후반(에폭 {epochs // 2} 뒤)의 AP 표준편차: 일반 {raw_late.std():.4f}, EMA {ema_late.std():.4f}")

    # 디코더 층별 AP, 예측, 선택, 점수–IoU
    outputs = predict(ema.module, val_set, device)
    print("[디코더 층 수별 AP] EMA 모델, 검증", len(val_set), "장")
    rows = layer_table(outputs, val_set)
    plot_layers(rows, os.path.join(args.fig_dir, "ch11-layers.png"))
    predictions = postprocess(outputs)
    result = evaluate_ap(predictions, val_set.targets, NUM_CLASSES)
    print("  클래스별 AP: " + ", ".join(f"{CLASS_NAMES[c]} {ap:.4f}" for c, ap in enumerate(result["per_class"])))
    exact = sum(int((p["scores"] >= 0.5).sum()) == len(t["labels"]) for p, t in zip(predictions, val_set.targets))
    print(f"  점수 ≥ 0.5 예측 수가 정답 객체 수와 같은 그림: {exact} / {len(val_set)}장")
    plot_predictions(val_set, predictions, os.path.join(args.fig_dir, "ch11-predictions.png"), list(range(8)))
    plot_selection(ema.module, val_set, [1, 2], os.path.join(args.fig_dir, "ch11-selection.png"), device)
    print("[점수와 IoU] 정답 객체마다 그 객체를 찾은 예측 (같은 클래스 · IoU ≥ 0.5 가운데 점수가 가장 높은 것) 의 점수와 IoU")
    row, pairs = score_iou_report("ch11 mini RF-DETR (IA-BCE)", predictions, val_set.targets)
    panels = [("ch11 mini RF-DETR (IA-BCE loss)", pairs, row)]
    if os.path.exists("ch08_deformable.pt") and not args.quick:
        from ch07_detr import collect_outputs
        from ch08_deformable import MiniDeformableDETR
        checkpoint = torch.load("ch08_deformable.pt", map_location=device)
        other = MiniDeformableDETR(**checkpoint["config"]).to(device)
        other.load_state_dict(checkpoint["model"])
        other_predictions = postprocess(collect_outputs(other, val_set, device)[-1])
        other_row, other_pairs = score_iou_report("ch08 Deformable DETR (focal)", other_predictions, val_set.targets)
        panels.append(("ch08 Deformable DETR (focal loss)", other_pairs, other_row))
    plot_score_iou(panels, os.path.join(args.fig_dir, "ch11-score-iou.png"))
    print(f"본 실험 전체 {time.time() - start:.0f}초")


ABLATION_EPOCHS = 15
BASE_NAME = "base: IA-BCE, 4 groups, 2x2 windows"


def is_ablation_eval_epoch(epoch: int, total: int) -> bool:
    return epoch in (1, 2, 3, 5, 7, 10) or epoch == total


def summarize(history, seconds):
    row = {"AP": history["AP"][-1], "AP50": history["AP50"][-1], "AP75": history["AP75"][-1], "time": seconds,
           "first_08": first_epoch_reaching(history, 0.8)}
    if history["AP_raw"]:
        row.update(AP_raw=history["AP_raw"][-1], AP50_raw=history["AP50_raw"][-1], AP75_raw=history["AP75_raw"][-1])
    return row


def ablation_experiments(args, device, train_set, val_set):
    """절제 (a) – (d): 4,000장, 15 에폭, 시드 1개. 한 번에 한 가지만 base 와 다르게 한다."""
    start = time.time()
    epochs = 1 if args.quick else ABLATION_EPOCHS
    settings = [(BASE_NAME, {}),
                ("focal loss", {"cls_loss": "focal"}),
                ("1 query group", {"group_detr": 1}),
                ("1x1 window (all global)", {"num_windows": 1})]
    results, models = {}, {}
    for name, kwargs in settings:
        t0 = time.time()
        _, ema, history, _ = run_experiment(name, train_set, val_set, epochs, device, args.seed,
                                            eval_fn=is_ablation_eval_epoch, **kwargs)
        results[name] = {"summary": summarize(history, time.time() - t0), "history": history}
        models[name] = ema.module
    print(f"\n[절제 (a) – (d)] 학습 {len(train_set)}장, {epochs} 에폭, 시드 1개 — 마지막 에폭의 검증 AP")
    print("  설정                                  | EMA 모델: AP    AP50   AP75  | 일반 모델: AP   AP50   AP75  | "
          "AP≥0.8 첫 에폭 (EMA) | 학습 시간")
    for name, _ in settings:
        r = results[name]["summary"]
        print(f"  {name:37s} |          {r['AP']:.4f} {r['AP50']:.4f} {r['AP75']:.4f} |          {r['AP_raw']:.4f} "
              f"{r['AP50_raw']:.4f} {r['AP75_raw']:.4f} | {str(r['first_08']):>10s}           | {r['time']:5.0f}초")
    base_history = results[BASE_NAME]["history"]
    print("  (c) EMA 유무는 base 한 번의 학습에서 EMA 모델과 일반 모델을 견준 것이다. 에폭별:")
    print("      에폭      " + " ".join(f"{e:6d}" for e in base_history["ap_epoch"]))
    print("      EMA  AP   " + " ".join(f"{v:.4f}" for v in base_history["AP"]))
    print("      일반 AP   " + " ".join(f"{v:.4f}" for v in base_history["AP_raw"]))
    print("[절제 (a)] 점수와 IoU — 같은 모델 구조, 분류 손실만 다름 (정답 객체마다 그 객체를 찾은 예측의 점수와 IoU)")
    panels = []
    for name, title in ((BASE_NAME, "IA-BCE loss (base)"), ("focal loss", "focal loss")):
        _, predictions = evaluate_model(models[name], val_set, device)
        row, pairs = score_iou_report(title, predictions, val_set.targets)
        results[name]["score_iou"] = row
        panels.append((f"mini RF-DETR, {title}, {epochs} epochs", pairs, row))
    if args.seed == 0:  # 그림은 시드 0 의 실행으로만 그린다 (다른 시드는 표에만 들어간다)
        curves = [(name, results[name]["history"]["ap_epoch"], results[name]["history"]) for name, _ in settings]
        curves.append(("base, raw model (no EMA)", base_history["ap_epoch"],
                       {"AP": base_history["AP_raw"], "AP75": base_history["AP75_raw"]}))
        plot_convergence(curves, os.path.join(args.fig_dir, "ch11-ablation.png"),
                         f"ablations ({epochs} epochs, EMA model, seed 0)")
        plot_score_iou(panels, os.path.join(args.fig_dir, "ch11-ablation-score-iou.png"))
    print("[절제 (d) 보충] 윈도 수를 추론 때만 바꿔 채점 (EMA 모델)")
    for name in (BASE_NAME, "1x1 window (all global)"):
        cells = []
        for windows in (1, 2, 3):
            result, _ = evaluate_model(models[name], val_set, device, num_windows=windows)
            cells.append(f"num_windows={windows}: AP {result['AP']:.4f}")
        print(f"    {name:37s} → " + " | ".join(cells))
    with open(f"ch11_ablations_seed{args.seed}.json", "w") as f:
        json.dump(results, f)
    print(f"저장: ch11_ablations_seed{args.seed}.json  |  절제 실험 전체 {time.time() - start:.0f}초")
    summarize_ablation_seeds([name for name, _ in settings])


def summarize_ablation_seeds(names):
    """실행 폴더에 있는 ch11_ablations_seed*.json (시드를 바꿔 돌린 결과) 을 모아 시드별 표를 출력한다."""
    runs = {}
    for path in sorted(glob.glob("ch11_ablations_seed*.json")):
        with open(path) as f:
            runs[int(path[len("ch11_ablations_seed"):-len(".json")])] = json.load(f)
    seeds = sorted(runs)
    if len(seeds) < 2:
        print("(다른 시드의 결과가 없어 시드별 요약은 건너뜀: --ablations --seed 1 처럼 시드를 바꿔 더 돌리면 여기에 모인다)")
        return
    print(f"\n[절제 (a) – (d) 시드별 요약] 시드 {seeds} — 마지막 에폭의 EMA 모델 검증 AP 와, 같은 시드의 base 와의 차이")
    print("  설정                                  | 시드별 AP                | 평균   | base 와의 차이 (시드별)        | 차이의 평균")
    base = [runs[seed][BASE_NAME]["summary"]["AP"] for seed in seeds]
    for name in names:
        values = [runs[seed][name]["summary"]["AP"] for seed in seeds]
        diffs = [v - b for v, b in zip(values, base)]
        print(f"  {name:37s} | {' '.join(f'{v:.4f}' for v in values):24s} | {np.mean(values):.4f} | "
              f"{' '.join(f'{d:+.4f}' for d in diffs):30s} | {np.mean(diffs):+.4f}")
    raw = [runs[seed][BASE_NAME]["summary"]["AP_raw"] for seed in seeds]
    diffs = [r - b for r, b in zip(raw, base)]
    print(f"  {'base, raw model (no EMA)':37s} | {' '.join(f'{v:.4f}' for v in raw):24s} | {np.mean(raw):.4f} | "
          f"{' '.join(f'{d:+.4f}' for d in diffs):30s} | {np.mean(diffs):+.4f}")
    for key, label in (("AP50", "AP50"), ("AP75", "AP75")):
        cells = [f"{name.split(':')[0]} {np.mean([runs[seed][name]['summary'][key] for seed in seeds]):.4f}" for name in names]
        print(f"  {label} 의 시드 평균: " + " | ".join(cells))
    print("  점수와 IoU 의 상관 (스피어만), 시드별: " + " | ".join(
        f"{title} " + " ".join(f"{runs[seed][name]['score_iou']['spearman']:+.3f}" for seed in seeds)
        for name, title in ((BASE_NAME, "IA-BCE"), ("focal loss", "focal"))))


def pretrain_experiments(args, device, train_set, val_set):
    """절제 (e): 백본 사전 학습의 효과. 작은 데이터(200장) 2×2 (초기화 × 학습률 규칙), 큰 데이터(4,000장) 비교."""
    start = time.time()
    quick = args.quick
    epochs = 1 if quick else ABLATION_EPOCHS
    results = {}
    unlabeled = ShapesDataset(128 if quick else 8000, seed=100)  # 라벨은 쓰지 않는다 (그림만)
    mim_epochs = 2 if quick else 30
    print(f"\n[절제 (e)] 백본 사전 학습: 라벨 없는 그림 {len(unlabeled)}장 (seed 100), 마스크 그림 모델링 {mim_epochs} 에폭, "
          "배치 128, AdamW lr 5e-4, 가린 비율 0.5")
    torch.manual_seed(args.seed)
    c = DEFAULT_CONFIG
    backbone = WindowedViT(c["img_size"], c["patch_size"], c["vit_dim"], c["vit_depth"], c["vit_heads"],
                           out_feature_indexes=c["out_feature_indexes"], num_windows=c["num_windows"])
    t0 = time.time()
    mim_loss, head = mim_pretrain(backbone, unlabeled.images, mim_epochs, device, seed=args.seed)
    print(f"  사전 학습 {time.time() - t0:.0f}초 ({mim_epochs * (len(unlabeled) // 128)} 스텝), 손실 {mim_loss[0]:.4f} → {mim_loss[-1]:.4f}")
    plot_mim(backbone, head, val_set.images[:6], os.path.join(args.fig_dir, "ch11-mim.png"), device)
    backbone_state = {k: v.detach().cpu().clone() for k, v in backbone.state_dict().items()}
    torch.save({"backbone": backbone_state, "mim_loss": mim_loss}, "ch11_backbone_mim.pt")
    results["mim_loss"] = mim_loss

    small_set = ShapesDataset(32 if quick else 200, seed=0)  # 학습 세트의 앞 200장과 같은 그림
    small_epochs = 2 if quick else 100
    seeds = [0] if quick else [0, 1, 2]
    official = {}
    flat = {"lr_encoder": 2e-4, "vit_layer_decay": 1.0, "component_decay": 1.0}
    small_settings = [("random init, official lr rule", None, official), ("random init, flat lr", None, flat),
                      ("pre-trained, official lr rule", backbone_state, official),
                      ("pre-trained, flat lr", backbone_state, flat)]
    eval_small = lambda epoch, total: epoch % 25 == 0 or epoch == total  # noqa: E731
    small_runs = {}
    print(f"  작은 데이터: 학습 {len(small_set)}장, {small_epochs} 에폭 (에폭당 {len(small_set) // 32} 스텝 = "
          f"{small_epochs * (len(small_set) // 32)} 스텝), 시드 {seeds}, EMA 모델의 검증 AP (에폭:AP)")
    for name, state, lr_kwargs in small_settings:
        histories = []
        for seed in seeds:
            t0 = time.time()
            _, _, history, _ = run_experiment(f"{name}, seed {seed}", small_set, val_set, small_epochs, device, seed,
                                              backbone_state=state, eval_fn=eval_small, eval_raw=False, verbose=False,
                                              **lr_kwargs)
            histories.append(history)
            print(f"    {name:31s} 시드 {seed}: " +
                  " ".join(f"{e}:{ap:.4f}" for e, ap in zip(history["ap_epoch"], history["AP"])) +
                  f" | {time.time() - t0:.0f}초", flush=True)
        small_runs[name] = histories
    print(f"  [작은 데이터 {len(small_set)}장] 마지막 에폭의 EMA 모델 검증 AP (시드 {len(seeds)}개)")
    print("    설정                            | 시드별 AP                | 평균   | 최소 – 최대     | AP50 평균 | AP75 평균")
    for name, histories in small_runs.items():
        finals = [h["AP"][-1] for h in histories]
        results[f"small: {name}"] = {"AP": finals, "AP50": [h["AP50"][-1] for h in histories],
                                     "AP75": [h["AP75"][-1] for h in histories], "histories": histories}
        print(f"    {name:31s} | {' '.join(f'{v:.4f}' for v in finals):24s} | {np.mean(finals):.4f} | "
              f"{min(finals):.4f} – {max(finals):.4f} | {np.mean([h['AP50'][-1] for h in histories]):.4f}    | "
              f"{np.mean([h['AP75'][-1] for h in histories]):.4f}")
    mean = {name: float(np.mean(results[f"small: {name}"]["AP"])) for name in small_runs}
    print(f"    사전 학습의 이득 (평균 AP): 공식 학습률 규칙 {mean['pre-trained, official lr rule'] - mean['random init, official lr rule']:+.4f}, "
          f"일정한 학습률 {mean['pre-trained, flat lr'] - mean['random init, flat lr']:+.4f}")
    print(f"    공식 학습률 규칙의 이득 (평균 AP): 사전 학습 백본 {mean['pre-trained, official lr rule'] - mean['pre-trained, flat lr']:+.4f}, "
          f"무작위 초기화 {mean['random init, official lr rule'] - mean['random init, flat lr']:+.4f}")

    # 큰 데이터: 15 에폭, 시드 1개, 공식 학습률 규칙. 무작위 초기화 쪽은 --ablations 의 base 와 같은 설정 · 같은 시드다
    t0 = time.time()
    _, _, base_history, _ = run_experiment(f"random init, {len(train_set)} images", train_set, val_set, epochs, device, args.seed,
                                           eval_fn=is_ablation_eval_epoch)
    results["large: random init"] = {"summary": summarize(base_history, time.time() - t0), "history": base_history}
    t0 = time.time()
    _, _, history, _ = run_experiment(f"pre-trained backbone, {len(train_set)} images", train_set, val_set, epochs, device,
                                      args.seed, backbone_state=backbone_state, eval_fn=is_ablation_eval_epoch)
    results["large: pre-trained"] = {"summary": summarize(history, time.time() - t0), "history": history}
    print(f"  [큰 데이터 {len(train_set)}장, {epochs} 에폭, 시드 1개, 공식 학습률 규칙] EMA 모델의 검증 AP")
    print("      에폭          " + " ".join(f"{e:6d}" for e in history["ap_epoch"]))
    print("      무작위 초기화 " + " ".join(f"{v:.4f}" for v in base_history["AP"]))
    print("      사전 학습     " + " ".join(f"{v:.4f}" for v in history["AP"]))
    small_random, small_pre = mean["random init, official lr rule"], mean["pre-trained, official lr rule"]
    large_random, large_pre = base_history["AP"][-1], history["AP"][-1]
    print(f"  사전 학습의 이득 (공식 학습률 규칙, 마지막 에폭 AP): {len(small_set)}장 {small_pre - small_random:+.4f} "
          f"({small_random:.4f} → {small_pre:.4f}), {len(train_set)}장 {large_pre - large_random:+.4f} "
          f"({large_random:.4f} → {large_pre:.4f})")
    large_rows = [(f"random\n{len(small_set)} images", small_random), (f"pre-trained\n{len(small_set)} images", small_pre),
                  (f"random\n{len(train_set)} images", large_random), (f"pre-trained\n{len(train_set)} images", large_pre)]
    plot_pretrain(mim_loss, small_runs, large_rows, os.path.join(args.fig_dir, "ch11-pretrain.png"))
    with open("ch11_pretrain.json", "w") as f:
        json.dump(results, f)
    print(f"저장: ch11_pretrain.json, ch11_backbone_mim.pt  |  사전 학습 실험 전체 {time.time() - start:.0f}초")


# --8<-- [start:main]
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--quick", action="store_true")
    parser.add_argument("--ablations", action="store_true", help="본 실험 대신 절제 실험 (a) – (d) 를 돌린다")
    parser.add_argument("--pretrain", action="store_true", help="본 실험 대신 절제 실험 (e) 백본 사전 학습을 돌린다")
    parser.add_argument("--fig-dir", default="figures")
    parser.add_argument("--seed", type=int, default=0)
    args = parser.parse_args()
    import matplotlib
    matplotlib.use("Agg")
    os.makedirs(args.fig_dir, exist_ok=True)
    device = get_device()
    if device == "cpu":
        torch.set_num_threads(4)
    print(f"장치: {device}")
    small = args.quick and (args.ablations or args.pretrain)  # 절제의 연기 시험은 학습을 여러 번 하므로 더 작게
    train_set = ShapesDataset((96 if small else 256) if args.quick else 4000, seed=0)
    val_set = ShapesDataset((32 if small else 64) if args.quick else 500, seed=1)
    print(f"학습 {len(train_set)}장, 검증 {len(val_set)}장 (정답 객체 {sum(len(t['labels']) for t in val_set.targets)}개)")
    if args.ablations:
        ablation_experiments(args, device, train_set, val_set)
    elif args.pretrain:
        pretrain_experiments(args, device, train_set, val_set)
    else:
        table, flat_table = small_checks(device)
        main_experiment(args, device, train_set, val_set, table, flat_table)
# --8<-- [end:main]


if __name__ == "__main__":
    main()
