"""12장 · 가중치 공유 NAS — 한 번 학습한 미니 RF-DETR 에서 수백 개의 모델을 꺼내 파레토 곡선을 그린다.

무엇을 하나
  1. 파레토 경계: "지배" 의 정의와, 비용으로 정렬한 뒤 누적 최댓값으로 경계를 찾는 pareto_front.
  2. 패치 임베딩 리사이즈: FlexiViT 의 PI-resize(의사 역행렬 리사이즈) pi_resize_patch_embed 를 만들어
     9장 WindowedViT 의 patch_resize_fn 에 끼우고, 단순 보간과 내적 보존 오차를 견준다.
  3. GPU 시간 재기의 기본(동기화 · 예열 · 중앙값 · 번갈아 재기) measure_interleaved 와 연산량 count_flops.
  4. 가중치 공유 NAS 학습 (기본 모드): 스텝마다 (해상도, 패치 크기, 윈도 수) 를 균등하게 뽑아 기울기 갱신 한 번.
     11장과 같은 데이터 · 같은 60 에폭. 체크포인트 ch12_nas.pt 를 실행 폴더에 저장한다.
  5. 격자 탐색 (--search): 탐색 공간의 모든 구성(408개)에 대해 검증 AP · 연산량(FLOPs) · 지연 시간(배치 1) ·
     처리 시간(배치 64)을 재고 파레토 경계를 찾는다. 11장의 고정 구성 모델(ch11_rfdetr.pt)을 같은 구성들로 꺼냈을 때와
     견주고, 손잡이별 민감도 · 공간 위치 수 · 학습 때 못 본 구성을 본다. 결과는 ch12_search.json.
  6. NAS 뒤 미세 조정 (--finetune): 구성 하나를 고정해 10 에폭 더 학습했을 때 이득이 있는지 (논문 부록 G 의 미니 점검).

실행 (한 번에 한 가지 모드. 시간은 8GB 노트북 GPU 에서 잰 값)
  python ch12_nas.py                          # 점검 + NAS 학습 60 에폭 (약 18분: GPU 를 다른 학습 둘과 나눠 쓰며 잰 값)
  python ch12_nas.py --search                 # 격자 탐색 + 그림 (약 15분: AP 채점 11분 + 시간 측정 3분. GPU 를 혼자 쓰며 잰 값)
                                              #   ch12_nas.pt 가 있어야 한다. ch11_rfdetr.pt 가 있으면 고정 구성 모델과 견준다
  python ch12_nas.py --finetune               # NAS 뒤 미세 조정 점검 (약 9분). ch12_nas.pt 가 있어야 한다
  python ch12_nas.py --seed 1 --tag seed1     # 시드를 바꿔 한 번 더 (ch12_nas_seed1.pt). --search 가 함께 요약한다
  python ch12_nas.py --epochs 120 --tag long  # 두 배 길게 (ch12_nas_long.pt, 약 33분)
  python ch12_nas.py --checks                 # 학습 없이 파레토 · PI-resize 점검과 그 그림만 (약 35초)
  python ch12_nas.py --replot                 # ch12_search.json 으로 표와 그림만 다시 만든다
  python ch12_nas.py --quick                  # 연기 시험 (CPU 약 20초). --quick --search (약 30초), --quick --finetune (약 10초)
그림은 --fig-dir (기본 figures/) 에 저장된다. --quick 의 체크포인트는 ch12_nas_quick.pt 로 따로 저장한다.
AP 채점은 프로세스 여러 개에 나눠 맡긴다 (--workers, 기본은 CPU 코어 수의 절반 · 최대 8).

9장의 WindowedViT.patch_resize_fn, 10장의 MiniRFDETR, 11장의 RFDETRCriterion · ModelEMA · build_optimizer · predict ·
evaluate_model 을 가져다 쓴다 (고치지 않는다). 13장 ch13_seg.py 는 이 파일을 쓰지 않는다.
"""

from __future__ import annotations

import argparse
import glob
import json
import multiprocessing
import os
import subprocess
import sys
import time
from typing import NamedTuple

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

from ch03_metrics import evaluate_ap
from ch07_detr import get_device, targets_to
from ch09_lwdetr_parts import resize_patch_embed_simple
from ch10_rfdetr_model import MiniRFDETR, postprocess
from ch11_train import ModelEMA, RFDETRCriterion, build_optimizer, evaluate_model, predict
from rf_shapes import NUM_CLASSES, ShapesDataset, make_loader

BLUE, ORANGE, GREEN, PINK, RED, SKY, GRAY = "#0072B2", "#E69F00", "#009E73", "#CC79A7", "#D55E00", "#56B4E9", "#777777"


# ── 1. 파레토 경계 ──────────────────────────────────────────────────────────


# --8<-- [start:pareto]
def dominates(a, b) -> bool:
    """점 a = (비용, 정확도) 가 점 b 를 지배하는가: 비용은 같거나 작고, 정확도는 같거나 크고, 둘 중 하나는 진짜로 낫다."""
    return a[0] <= b[0] and a[1] >= b[1] and (a[0] < b[0] or a[1] > b[1])


def pareto_front(cost, accuracy) -> np.ndarray:
    """파레토 경계 위에 있는 점의 번호를 비용이 작은 순서로 돌려준다.

    cost: (n,) 작을수록 좋은 값 (지연 시간, 연산량 …).  accuracy: (n,) 클수록 좋은 값 (AP).
    방법: 비용이 작은 순으로 (비용이 같으면 정확도가 큰 순으로) 늘어놓고 앞에서부터 훑으며,
    "지금까지 본 정확도의 최댓값" 을 넘는 점만 남긴다. 넘지 못한 점은 앞에 있는 (더 싸거나 같은 값인) 어떤 점보다
    정확하지 않으므로 지배당한다. 정렬에 O(n log n), 훑기에 O(n).
    (비용과 정확도가 모두 같은 점이 여럿이면 하나만 남긴다.)
    """
    cost, accuracy = np.asarray(cost, dtype=float), np.asarray(accuracy, dtype=float)
    order = np.lexsort((-accuracy, cost))  # 마지막 열쇠(cost)가 1순위, -accuracy 가 2순위
    keep, best = [], -np.inf
    for i in order:
        if accuracy[i] > best:
            keep.append(i)
            best = accuracy[i]
    return np.array(keep, dtype=int)
# --8<-- [end:pareto]


TOY_POINTS = [("a", 1.0, 30.0), ("b", 2.0, 45.0), ("c", 2.5, 40.0), ("d", 3.0, 52.0), ("e", 4.0, 50.0),
              ("f", 5.0, 58.0), ("g", 6.0, 58.0), ("h", 7.0, 61.0)]  # (이름, 지연 시간 ms, AP) — 본문의 손계산 예


def pareto_checks(fig_dir):
    """본문의 손계산 예(점 8개)와, 정의대로 모든 쌍을 견준 결과가 pareto_front 와 같은지 본다."""
    names = [p[0] for p in TOY_POINTS]
    cost, acc = np.array([p[1] for p in TOY_POINTS]), np.array([p[2] for p in TOY_POINTS])
    front = pareto_front(cost, acc)
    print("[파레토] 손계산 예: (지연 시간 ms, AP)")
    best = -np.inf
    for i in np.lexsort((-acc, cost)):
        dominated_by = [names[j] for j in range(len(names)) if dominates((cost[j], acc[j]), (cost[i], acc[i]))]
        mark = "경계" if acc[i] > best else "지배당함 ← " + ", ".join(dominated_by)
        print(f"  {names[i]} ({cost[i]:.1f}, {acc[i]:.0f}) | 지금까지의 최댓값 {best if best > -np.inf else float('nan'):5.0f} | {mark}")
        best = max(best, acc[i])
    print("  파레토 경계: " + " → ".join(names[i] for i in front))
    rng = np.random.default_rng(0)
    c, a = rng.random(300), rng.random(300)
    brute = sorted(i for i in range(300) if not any(dominates((c[j], a[j]), (c[i], a[i])) for j in range(300)))
    print(f"  check 무작위 점 300개: 정의대로 모든 쌍을 견준 경계 {len(brute)}개 = pareto_front {len(pareto_front(c, a))}개, "
          f"같은 집합인가: {brute == sorted(pareto_front(c, a).tolist())}")
    plot_pareto_toy(names, cost, acc, front, os.path.join(fig_dir, "ch12-pareto-toy.png"))


# ── 2. 패치 임베딩 리사이즈: PI-resize ───────────────────────────────────────


# --8<-- [start:pi-resize]
def resize_matrix(old: int, new: int, ndim: int = 2) -> torch.Tensor:
    """쌍선형 리사이즈를 행렬로 쓴 것. 돌려주는 값 R: (new^ndim, old^ndim), float64.

    리사이즈는 선형 연산이다: 리사이즈(a·x + b·y) = a·리사이즈(x) + b·리사이즈(y). 그러므로 "한 칸만 1 이고 나머지는 0" 인
    패치(기저 벡터)들을 리사이즈한 결과를 열로 세우면 그것이 곧 행렬 R 이고, 어떤 패치 x 든 리사이즈(x) = R·vec(x) 다.
    ndim=1 은 본문의 1차원 손계산 예를 위한 것.
    """
    basis = torch.eye(old**ndim, dtype=torch.float64).reshape(old**ndim, 1, *([old] * ndim))  # 기저 패치 old^ndim 장
    mode = "bilinear" if ndim == 2 else "linear"
    resized = F.interpolate(basis, size=[new] * ndim, mode=mode, align_corners=False)  # (old^ndim, 1, new, …)
    return resized.reshape(old**ndim, new**ndim).T  # j 번째 열 = j 번째 기저 패치를 리사이즈한 것


_PI_CACHE: dict = {}


def pi_resize_matrix(old: int, new: int, ndim: int = 2) -> torch.Tensor:
    """PI-resize 행렬 P = (Rᵀ)⁺: (new^ndim, old^ndim).  새 커널 = P · vec(원래 커널).

    키울 때(new ≥ old)는 P = R (RᵀR)⁻¹ 이고 Rᵀ P = I — 리사이즈한 패치와 새 커널의 내적이 원래 내적과 정확히 같다.
    줄일 때(new < old)는 정확한 답이 없고, P 는 ‖w − Rᵀ ŵ‖² 을 가장 작게 하는 ŵ 를 준다.
    """
    key = (old, new, ndim)
    if key not in _PI_CACHE:
        _PI_CACHE[key] = torch.linalg.pinv(resize_matrix(old, new, ndim).T)
    return _PI_CACHE[key]


def pi_resize_patch_embed(weight: torch.Tensor, new_patch: int) -> torch.Tensor:
    """FlexiViT 의 PI-resize 로 패치 임베딩 합성곱의 가중치를 다른 패치 크기로 바꾼다.

    weight: (C, 3, p, p) → (C, 3, p', p').  출력 채널 · 입력 채널마다 따로 같은 행렬 P 를 곱한다.
    WindowedViT.patch_resize_fn 에 끼워 쓴다 (순전파마다 불린다. P 는 한 번만 계산해 둔다. 기울기는 P 를 거슬러 흐른다).
    """
    old_patch = weight.shape[-1]
    if new_patch == old_patch:
        return weight
    P = pi_resize_matrix(old_patch, new_patch).to(weight)  # (p'², p²)
    flat = weight.reshape(-1, old_patch * old_patch)  # (C·3, p²): 커널의 채널마다 한 줄
    return (flat @ P.T).reshape(*weight.shape[:2], new_patch, new_patch)
# --8<-- [end:pi-resize]


def resize_patch_embed_bilinear(weight: torch.Tensor, new_patch: int) -> torch.Tensor:
    """견주기용: 커널을 그림처럼 쌍선형 보간만 한다 (크기 보정 없음). FlexiViT 논문이 "vanilla" 라고 부르는 것."""
    if new_patch == weight.shape[-1]:
        return weight
    return F.interpolate(weight, size=(new_patch, new_patch), mode="bilinear", align_corners=False)


RESIZERS = {"PI-resize": pi_resize_patch_embed, "bicubic x (p/p')^2 (ch09)": resize_patch_embed_simple,
            "bilinear only": resize_patch_embed_bilinear}


def real_patches(dataset, patch: int, count: int, seed: int = 0) -> torch.Tensor:
    """검증 그림에서 patch×patch 조각을 count 개 잘라 모델이 보는 값((x − 0.5) / 0.25)으로 바꾼다: (count, 3, p, p)."""
    rng = np.random.default_rng(seed)
    size = dataset.images.shape[-1]
    out = []
    for _ in range(count):
        i, r, c = rng.integers(len(dataset)), rng.integers(size - patch + 1), rng.integers(size - patch + 1)
        out.append(dataset.images[i, :, r:r + patch, c:c + patch])
    return (torch.stack(out).double() / 255.0 - 0.5) / 0.25


def inner_product_errors(weight, patches, new_patch):
    """원래 내적 ⟨x, w⟩ 과 리사이즈 뒤의 내적 ⟨Rx, ŵ⟩ 을 방법마다 구한다.

    weight: (C, 3, p, p), patches: (n, 3, p, p).  돌려주는 값: 원래 토큰 (n, C), {방법 이름: 리사이즈 뒤 토큰 (n, C)}.
    """
    old = weight.shape[-1]
    original = F.conv2d(patches, weight).flatten(1)  # (n, C): 패치 하나 = 토큰 하나
    resized_patches = F.interpolate(patches, size=(new_patch, new_patch), mode="bilinear", align_corners=False)
    return original, {name: F.conv2d(resized_patches, fn(weight, new_patch)).flatten(1) for name, fn in RESIZERS.items()}


def pi_resize_checks(val_set, device, fig_dir, quick):
    """PI-resize 의 손계산 예 · 내적 보존 오차 · (11장 모델이 있으면) 그림과 패치를 함께 키웠을 때의 AP."""
    print("[PI-resize] 1차원 손계산 예: 길이 2 인 패치를 길이 4 로")
    R = resize_matrix(2, 4, ndim=1)
    P = pi_resize_matrix(2, 4, ndim=1)
    w, x = torch.tensor([1.0, 3.0], dtype=torch.float64), torch.tensor([2.0, 4.0], dtype=torch.float64)
    print("  R =", [[round(v, 4) for v in row] for row in R.tolist()])
    print("  RᵀR =", [[round(v, 4) for v in row] for row in (R.T @ R).tolist()],
          " (RᵀR)⁻¹ =", [[round(v, 4) for v in row] for row in torch.linalg.inv(R.T @ R).tolist()])
    print("  w = [1, 3], x = [2, 4]:  ⟨x, w⟩ =", float(x @ w))
    print("  Rx =", [round(v, 4) for v in (R @ x).tolist()], " ŵ = P w =", [round(v, 4) for v in (P @ w).tolist()],
          " ⟨Rx, ŵ⟩ =", round(float((R @ x) @ (P @ w)), 6))
    print("  단순 보간 Rw =", [round(v, 4) for v in (R @ w).tolist()], " ⟨Rx, Rw⟩ =", round(float((R @ x) @ (R @ w)), 4),
          " 길이 비로 보정 (2/4)·⟨Rx, Rw⟩ =", round(float((R @ x) @ (R @ w)) / 2, 4))
    print("  check Rᵀ ŵ = w 인가:", [round(v, 6) for v in (R.T @ (P @ w)).tolist()],
          "| P = R(RᵀR)⁻¹ 과의 차이", f"{float((P - R @ torch.linalg.inv(R.T @ R)).abs().max()):.1e}")
    probe = torch.rand(5, 1, 8, 8, dtype=torch.float64, generator=torch.Generator().manual_seed(0))
    direct = F.interpolate(probe, size=(12, 12), mode="bilinear", align_corners=False).reshape(5, -1)
    print(f"  check 2차원 R (8→12, 모양 {tuple(resize_matrix(8, 12).shape)}) 과 F.interpolate 의 차이: "
          f"{float((probe.reshape(5, -1) @ resize_matrix(8, 12).T - direct).abs().max()):.1e}")

    # 내적 보존 오차: 11장 모델의 패치 임베딩(없으면 무작위 커널) × 검증 그림에서 자른 진짜 패치
    if os.path.exists("ch11_rfdetr.pt"):
        ckpt = torch.load("ch11_rfdetr.pt", map_location="cpu")
        weight, source = ckpt["ema"]["backbone.patch_embed.weight"].double(), "11장 모델의 패치 임베딩 (96, 3, 8, 8)"
    else:
        ckpt = None
        weight, source = torch.randn(96, 3, 8, 8, dtype=torch.float64) * 0.02, "무작위 커널 (ch11_rfdetr.pt 가 없다)"
    patches = real_patches(val_set, 8, 200 if quick else 2000)
    print(f"[PI-resize] 내적 보존: {source}, 검증 그림에서 자른 8×8 패치 {len(patches)}개")
    print("  새 패치 | 방법                        | 상대 오차 ‖⟨Rx, ŵ⟩ − ⟨x, w⟩‖ / ‖⟨x, w⟩‖ | 토큰 크기의 비 ‖⟨Rx, ŵ⟩‖ / ‖⟨x, w⟩‖")
    rows = {}
    for new_patch in (4, 6, 10, 12, 16, 24, 32):
        original, resized = inner_product_errors(weight, patches, new_patch)
        for name, tokens in resized.items():
            err = float((tokens - original).norm() / original.norm())
            ratio = float(tokens.norm() / original.norm())
            rows.setdefault(name, []).append((new_patch, err, ratio))
            print(f"  {new_patch:7d} | {name:27s} | {err:12.2e}                             | {ratio:.4f}")
    original, resized = inner_product_errors(weight, patches, 16)
    plot_pi_resize(weight, rows, original, resized, os.path.join(fig_dir, "ch12-pi-resize.png"))

    # FlexiViT 그림 4 의 미니판: 학습이 끝난 고정 구성 모델에서 그림과 패치를 같은 배율로 키운다 (토큰 격자는 12×12 그대로)
    if ckpt is None:
        print("  (ch11_rfdetr.pt 가 없어 '그림과 패치를 함께 키우기' 점검은 건너뜀)")
        return
    model = MiniRFDETR(**ckpt["config"]).to(device)
    model.load_state_dict(ckpt["ema"])
    base = evaluate_model(model, val_set, device, batch_size=125)[0]["AP"]
    print(f"[PI-resize] 11장 모델(해상도 96 · 패치 8 로만 학습)에서 그림과 패치를 같은 배율로 키운다. 원래 AP {base:.4f}")
    print("  해상도 / 패치 (격자) | " + " | ".join(f"{name:27s}" for name in RESIZERS))
    for size, patch in ((120, 10), (144, 12), (192, 16)):
        cells = []
        for fn in RESIZERS.values():
            model.backbone.patch_resize_fn = fn
            cells.append(f"AP {evaluate_model(model, val_set, device, batch_size=125, size=size, patch_size=patch)[0]['AP']:.4f}".ljust(27))
        print(f"  {size:4d} / {patch:2d} ({size // patch}×{size // patch})     | " + " | ".join(cells))


# ── 3. 탐색 공간 ────────────────────────────────────────────────────────────


# --8<-- [start:search-space]
class Config(NamedTuple):
    """구성 하나 = 손잡이 다섯 개의 값."""
    resolution: int   # 입력 그림의 한 변 (픽셀)
    patch_size: int   # 패치의 한 변 (픽셀)
    num_windows: int  # 윈도 블록에서 한 변을 몇 윈도로 나누는가
    dec_layers: int   # 디코더 층 수 (0 이면 인코더 제안이 곧 예측)
    num_queries: int  # 질의 수


BASE = Config(96, 8, 2, 3, 12)  # 11장의 고정 구성
# 학습 때 뽑는 값 (디코더 3층 · 질의 12개는 고정: 이 둘은 추론 때만 줄인다)
TRAIN_SPACE = {"resolution": (64, 80, 96, 112, 128), "patch_size": (8, 16), "num_windows": (1, 2, 4)}
# 탐색(추론) 때 훑는 값. 해상도 72 · 88 · 104 · 120 과 패치 12 는 학습 때 한 번도 보지 않는다
SEARCH_SPACE = {"resolution": (64, 72, 80, 88, 96, 104, 112, 120, 128), "patch_size": (8, 12, 16),
                "num_windows": (1, 2, 4), "dec_layers": (0, 1, 2, 3), "num_queries": (4, 8, 12)}


def is_valid(resolution: int, patch_size: int, num_windows: int) -> bool:
    """손잡이의 조합이 모델에 넣을 수 있는 것인가: 그림이 패치로, 토큰 격자가 윈도로 나누어떨어져야 한다."""
    return resolution % patch_size == 0 and (resolution // patch_size) % num_windows == 0


def backbone_configs(space) -> list:
    """(해상도, 패치, 윈도) 의 쓸 수 있는 조합 전부."""
    return [(r, p, w) for r in space["resolution"] for p in space["patch_size"] for w in space["num_windows"]
            if is_valid(r, p, w)]


def all_configs(space) -> list:
    """탐색 공간의 모든 구성 (Config 의 목록)."""
    return [Config(r, p, w, d, q) for r, p, w in backbone_configs(space)
            for d in space["dec_layers"] for q in space["num_queries"]]
# --8<-- [end:search-space]


def quick_spaces():
    """--quick 용 작은 탐색 공간."""
    train = {"resolution": (64, 96), "patch_size": (8, 16), "num_windows": (1, 2)}
    search = {"resolution": (64, 96), "patch_size": (8, 12, 16), "num_windows": (1, 2), "dec_layers": (0, 3),
              "num_queries": (4, 12)}
    return train, search


def describe_space(train_space, search_space):
    train, search = backbone_configs(train_space), backbone_configs(search_space)
    nominal = int(np.prod([len(v) for v in search_space.values()]))
    configs = all_configs(search_space)
    seen = sum((c.resolution, c.patch_size, c.num_windows) in set(train) for c in configs)
    print(f"[탐색 공간] 학습: 해상도 {train_space['resolution']} × 패치 {train_space['patch_size']} × 윈도 "
          f"{train_space['num_windows']} = {int(np.prod([len(v) for v in train_space.values()]))}가지 가운데 쓸 수 있는 조합 {len(train)}개")
    print(f"  탐색: 해상도 {len(search_space['resolution'])} × 패치 {len(search_space['patch_size'])} × 윈도 "
          f"{len(search_space['num_windows'])} × 디코더 층 {len(search_space['dec_layers'])} × 질의 "
          f"{len(search_space['num_queries'])} = {nominal}가지 가운데 쓸 수 있는 구성 {len(configs)}개 "
          f"(백본 쪽 조합 {len(search)}개 × {len(search_space['dec_layers']) * len(search_space['num_queries'])})")
    print(f"  그 가운데 (해상도, 패치, 윈도) 가 학습 때 뽑힌 적 있는 구성 {seen}개, 한 번도 뽑히지 않은 구성 {len(configs) - seen}개")
    by_patch = {p: sorted({r // p for r, pp, _ in search if pp == p}) for p in search_space["patch_size"]}
    for p, grids in by_patch.items():
        print(f"  패치 {p:2d}: 토큰 격자의 한 변 {grids}")


# ── 4. 가중치 공유 NAS 학습 ──────────────────────────────────────────────────


# --8<-- [start:nas-train]
def train_nas_epoch(model, criterion, loader, optimizer, device, ema, train_configs, rng, max_norm: float = 0.1,
                    counts=None):
    """가중치 공유 NAS 의 한 에폭: 스텝마다 구성 하나를 균등하게 뽑아 그 구성으로 순전파 · 역전파 · 갱신을 한 번 한다.

    train_configs: [(해상도, 패치 크기, 윈도 수), …] — 쓸 수 있는 조합의 목록. 모두 같은 확률로 뽑힌다.
    디코더는 늘 3층 전부, 질의는 늘 12개 × 묶음 4개를 쓴다 (모든 층에 손실이 걸려 있으므로 층 · 질의는 추론 때 줄이면 된다).
    그림은 뽑힌 해상도로 배치째 리사이즈한다. 정답 박스는 정규화 좌표라 손대지 않는다.
    11장 train_one_epoch 와 다른 곳은 "구성을 뽑는 세 줄" 뿐이다. 돌려주는 값: 손실 이름 → 에폭 평균.
    """
    model.train()
    criterion.train()
    sums, steps = {}, 0
    for images, targets in loader:
        resolution, patch_size, num_windows = train_configs[rng.integers(len(train_configs))]  # ← 구성 하나를 뽑는다
        images = images.to(device)
        if resolution != images.shape[-1]:
            images = F.interpolate(images, size=(resolution, resolution), mode="bilinear", align_corners=False,
                                   antialias=True)
        outputs = model(images, patch_size=patch_size, num_windows=num_windows)  # ← 같은 가중치, 뽑힌 구성
        losses = criterion(outputs, targets_to(targets, device))
        optimizer.zero_grad(set_to_none=True)
        losses["loss"].backward()
        nn.utils.clip_grad_norm_(model.parameters(), max_norm)
        optimizer.step()
        ema.update(model)
        if counts is not None:
            counts[(resolution, patch_size, num_windows)] = counts.get((resolution, patch_size, num_windows), 0) + 1
        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()}


def build_nas_model(device, seed: int = 0, max_resolution: int = 128):
    """NAS 용 미니 RF-DETR. 11장 모델과 다른 점은 둘이다.

    ① 위치 임베딩을 "가장 큰 해상도 ÷ 가장 작은 패치" = 128 / 8 = 16×16 격자로 둔다 (11장은 12×12). 더 작은 격자에는 보간한다.
    ② 패치 임베딩 리사이즈를 PI-resize 로 갈아 끼운다.
    """
    torch.manual_seed(seed)
    model = MiniRFDETR(img_size=max_resolution).to(device)  # img_size 는 위치 임베딩 격자의 크기만 정한다
    model.backbone.patch_resize_fn = pi_resize_patch_embed
    return model
# --8<-- [end:nas-train]


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


def load_model(path, device, pi_resize: bool = True):
    """체크포인트의 EMA 가중치를 실은 모델 (추론 모드). 돌려주는 값: (model, ckpt)."""
    ckpt = torch.load(path, map_location=device)
    model = MiniRFDETR(**ckpt["config"]).to(device)
    model.load_state_dict(ckpt["ema"])
    if pi_resize:
        model.backbone.patch_resize_fn = pi_resize_patch_embed
    return model.eval(), ckpt


def eval_config(model, val_set, device, config: Config):
    return evaluate_model(model, val_set, device, batch_size=125, size=config.resolution, patch_size=config.patch_size,
                          num_windows=config.num_windows, dec_layers=config.dec_layers,
                          num_queries=config.num_queries)[0]


@torch.no_grad()
def loss_and_ap(model, dataset, device, config: Config = BASE):
    """추론 모드(질의 묶음 1개)에서 잰 전체 손실의 평균과 AP. 학습 그림과 검증 그림에서 각각 재어 일반화 간격을 본다."""
    criterion = RFDETRCriterion(NUM_CLASSES, group_detr=model.group_detr).to(device).eval()
    model.eval()
    total = 0.0
    for start in range(0, len(dataset), 125):
        images = dataset.images[start:start + 125].to(device).float() / 255.0
        if config.resolution != images.shape[-1]:
            images = F.interpolate(images, size=(config.resolution,) * 2, mode="bilinear", align_corners=False, antialias=True)
        outputs = model(images, patch_size=config.patch_size, num_windows=config.num_windows)
        total += float(criterion(outputs, targets_to(dataset.targets[start:start + 125], device))["loss"]) * len(images)
    return total / len(dataset), eval_config(model, dataset, device, config)["AP"]


def train_mode(args, device, train_set, val_set, train_space):
    epochs = args.epochs or (2 if args.quick else 60)
    train_configs = backbone_configs(train_space)
    model = build_nas_model(device, args.seed, max(train_space["resolution"]))
    criterion = RFDETRCriterion(NUM_CLASSES, group_detr=model.group_detr).to(device)
    optimizer, _ = build_optimizer(model, lr=2e-4)  # 11장과 같은 학습 설정
    ema = ModelEMA(model)
    loader = make_loader(train_set, 32, shuffle=True, seed=args.seed)
    rng = np.random.default_rng(args.seed)
    monitors = [BASE, Config(64, 8, 2, 3, 12), Config(128, 16, 2, 3, 12)]
    if args.quick:
        monitors = monitors[:2]
    print(f"\n[NAS 학습] 매개변수 {sum(p.numel() for p in model.parameters()):,}개 "
          f"(위치 임베딩 격자 {model.backbone.pos_grid}×{model.backbone.pos_grid}), 에폭 {epochs}, 에폭당 {len(loader)} 스텝, "
          f"시드 {args.seed}, 스텝마다 {len(train_configs)}개 조합에서 하나")
    print("  채점하는 구성 (EMA 모델, 디코더 3층 · 질의 12개): " + ", ".join(f"{c.resolution}/{c.patch_size}/w{c.num_windows}" for c in monitors))
    history = {"epoch": [], "loss": [], "loss_ce": [], "loss_bbox": [], "loss_giou": [], "time": [], "ap_epoch": [],
               "AP": [[] for _ in monitors], "monitors": [list(c) for c in monitors]}
    counts, start = {}, time.time()
    for epoch in range(1, epochs + 1):
        losses = train_nas_epoch(model, criterion, loader, optimizer, device, ema, train_configs, rng, counts=counts)
        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 is_nas_eval_epoch(epoch, epochs):
            history["ap_epoch"].append(epoch)
            aps = [eval_config(ema.module, val_set, device, c)["AP"] for c in monitors]
            for column, ap in zip(history["AP"], aps):
                column.append(ap)
            print(f"에폭 {epoch:3d} | 손실 {losses['loss']:7.4f} (ce {losses['loss_ce']:.4f} bbox {losses['loss_bbox']:.4f} "
                  f"giou {losses['loss_giou']:.4f}) | EMA AP " + "  ".join(f"{a:.4f}" for a in aps)
                  + f" | {time.time() - start:5.0f}초", flush=True)
    seconds = time.time() - start
    drawn = np.array([counts.get(c, 0) for c in train_configs])
    print(f"학습 끝: {seconds:.0f}초 ({epochs * len(loader)} 스텝). 조합마다 뽑힌 횟수: 최소 {drawn.min()}, 최대 {drawn.max()}, "
          f"평균 {drawn.mean():.1f} (기본 구성 96/8/w2 는 {counts.get((96, 8, 2), 0)}번 = 전체의 "
          f"{100 * counts.get((96, 8, 2), 0) / drawn.sum():.1f}%)")
    name = "ch12_nas" + ("_quick" if args.quick else "") + (f"_{args.tag}" if args.tag else "") + ".pt"
    torch.save({"model": model.state_dict(), "ema": ema.module.state_dict(), "config": model.config, "history": history,
                "epochs": epochs, "seed": args.seed, "train_space": train_space, "seconds": seconds}, name)
    print(f"저장: {name} (model · ema · config · history)")

    # 학습 직후의 짧은 성적표: 11장의 고정 구성 모델과 몇 개 구성에서 견준다 (전체 격자는 --search)
    probes = [BASE, Config(64, 8, 2, 3, 12), Config(128, 8, 2, 3, 12), Config(128, 16, 2, 3, 12), Config(96, 12, 2, 3, 12),
              Config(96, 8, 1, 3, 12), Config(96, 8, 2, 1, 12), Config(96, 8, 2, 0, 12), Config(96, 8, 2, 3, 4)]
    if args.quick:
        probes = probes[:3]
    fixed = load_model("ch11_rfdetr.pt", device)[0] if os.path.exists("ch11_rfdetr.pt") else None
    print("[짧은 성적표] 검증 AP (EMA 모델). 구성 = 해상도 / 패치 / 윈도 / 디코더 층 / 질의")
    print("  구성                | NAS 학습 모델 | 11장 고정 구성 모델")
    for c in probes:
        nas = eval_config(ema.module, val_set, device, c)["AP"]
        fix = f"{eval_config(fixed, val_set, device, c)['AP']:.4f}" if fixed is not None else "(ch11_rfdetr.pt 없음)"
        print(f"  {c.resolution:3d} / {c.patch_size:2d} / {c.num_windows} / {c.dec_layers} / {c.num_queries:2d}"
              f"{'  (기본)' if c == BASE else '        '} | {nas:.4f}        | {fix}")
    return history


# ── 5. 시간과 연산량 재기 ────────────────────────────────────────────────────


# --8<-- [start:timer]
def time_once(fn, device) -> float:
    """fn() 한 번에 걸린 시간 (ms). GPU 는 일을 맡기고 바로 돌아오므로, 시계를 보기 전후에 끝나기를 기다린다."""
    if device == "cuda":
        torch.cuda.synchronize()  # 앞서 맡긴 일이 끝날 때까지 기다린다 (없으면 그 일의 시간이 섞인다)
    start = time.perf_counter()
    fn()
    if device == "cuda":
        torch.cuda.synchronize()  # fn 이 맡긴 일이 끝날 때까지 기다린다 (없으면 "맡기는 시간" 만 잰다)
    return (time.perf_counter() - start) * 1e3


@torch.no_grad()
def measure_interleaved(fns: dict, device, rounds: int = 10, reps: int = 3, warmup_rounds: int = 1, sleep: float = 0.0,
                        seed: int = 0) -> dict:
    """여러 구성의 시간을 번갈아 잰다. fns: {이름: 인자 없는 함수}.  돌려주는 값: {이름: 잰 시간들 (ms) 의 배열}.

    한 라운드 = 모든 구성을 (무작위 순서로) reps 번씩. 처음 warmup_rounds 라운드는 버린다 (예열).
    구성 A 를 다 잰 뒤 B 를 재면 "그때 GPU 가 바빴는가 · 뜨거웠는가" 가 A 와 B 의 차이에 섞인다.
    번갈아 재면 그런 변화가 모든 구성에 고르게 묻는다. 대푯값은 부르는 쪽이 고른다: 보통은 중앙값 (평균은 가끔 튀는 값에
    끌려간다), 기계의 상태가 빠른 상태와 느린 상태를 오가는 경우에는 최솟값 (가장 방해를 덜 받은 측정).
    sleep: 순전파 사이에 쉬는 시간 (초). RF-DETR 논문의 처방은 0.2 초 (전력 제한을 피하려고).
    """
    rng = np.random.default_rng(seed)
    names = list(fns)
    times = {name: [] for name in names}
    for round_index in range(warmup_rounds + rounds):
        for i in rng.permutation(len(names)):
            for _ in range(reps):
                elapsed = time_once(fns[names[i]], device)
                if round_index >= warmup_rounds:
                    times[names[i]].append(elapsed)
                if sleep:
                    time.sleep(sleep)
    return {name: np.array(values) for name, values in times.items()}


def count_flops(model, images, **forward_kwargs) -> float:
    """순전파 한 번의 연산량 (FLOPs). PyTorch 의 FlopCounterMode 로 센다 (RF-DETR 논문 부록 C 가 쓴 도구).

    합성곱 · 선형 층 · 행렬 곱 · 어텐션의 곱셈 – 덧셈을 센다. 활성 함수 · 정규화의 일부 · 덧셈, 그리고 변형 어텐션의
    grid_sample(쌍선형 보간으로 읽기)은 세지 않는다. 그림 크기와 구성으로 정해지는 값이라 잴 때마다 같다.
    """
    from torch.utils.flop_counter import FlopCounterMode

    model.eval()
    with FlopCounterMode(display=False) as counter:  # (이 도구는 기울기 기록이 켜진 상태에서만 돈다)
        model(images, **forward_kwargs)
    return float(counter.get_total_flops())
# --8<-- [end:timer]


def cpu_core_groups() -> dict:
    """성능 코어 · 효율 코어가 섞인 CPU(인텔 하이브리드)라면 {"P": [코어 번호…], "E": […]} 를, 아니면 빈 사전을 돌려준다."""
    groups = {}
    for name, path in (("P", "/sys/devices/cpu_core/cpus"), ("E", "/sys/devices/cpu_atom/cpus")):
        try:
            cores = []
            for part in open(path).read().strip().split(","):
                low, _, high = part.partition("-")
                cores += list(range(int(low), int(high or low) + 1))
            allowed = sorted(set(cores) & os.sched_getaffinity(0))
            if allowed:
                groups[name] = allowed
        except (OSError, ValueError, AttributeError):
            pass
    return groups


def pin_thread(core=None, restore=None):
    """이 스레드를 CPU 코어 하나에 묶거나(core), 원래대로 되돌린다(restore). 돌려주는 값: 묶기 전의 허용 코어 집합."""
    if not hasattr(os, "sched_setaffinity"):
        return None
    before = os.sched_getaffinity(0)
    os.sched_setaffinity(0, restore if restore is not None else {core})
    return before


def forward_fn(model, images, config: Config):
    return lambda: model(images, patch_size=config.patch_size, num_windows=config.num_windows,
                         dec_layers=config.dec_layers, num_queries=config.num_queries)


def resized_batch(val_set, device, resolution, batch):
    images = val_set.images[:batch].to(device).float() / 255.0
    if resolution != images.shape[-1]:
        images = F.interpolate(images, size=(resolution, resolution), mode="bilinear", align_corners=False, antialias=True)
    return images


def machine_state() -> str:
    """재는 순간 기계가 얼마나 바쁜지 한 줄로 (측정값을 읽을 때 꼭 필요한 정보)."""
    text = f"[기계 상태] load average {os.getloadavg()[0]:.1f} (CPU 코어 {os.cpu_count()}개)"
    try:
        out = subprocess.run(["nvidia-smi", "--query-gpu=utilization.gpu,memory.used", "--format=csv,noheader"],
                             capture_output=True, text=True, timeout=10).stdout.strip()
        apps = subprocess.run(["nvidia-smi", "--query-compute-apps=pid", "--format=csv,noheader"],
                              capture_output=True, text=True, timeout=10).stdout.split()
        text += f", GPU 사용률 · 메모리 {out}, GPU 를 쓰는 프로세스 {len(apps)}개 (이 프로세스 포함)"
    except (OSError, subprocess.SubprocessError):
        text += ", GPU 정보 없음"
    return text


def timing_basics(model, val_set, device, quick, cold):
    """GPU 시간 재기의 기본을 숫자로: 첫 호출들(예열), 동기화를 빼먹었을 때, 사이에 200 ms 를 쉬었을 때.

    cold: 이 프로세스에서 맨 처음 부른 순전파들의 시간 (search_mode 가 시작하자마자 잰 것).
    견주는 방법들은 번갈아 잰다 (한 바퀴에 방법마다 한 번씩) — 방법을 하나씩 차례로 재면 그 사이 기계 상태의 변화가 섞인다.
    """
    model.eval()
    small = forward_fn(model, resized_batch(val_set, device, BASE.resolution, 1), BASE)
    big_batch, big_res = (8, 96) if quick else (64, 128)
    big = forward_fn(model, resized_batch(val_set, device, big_res, big_batch), BASE._replace(resolution=big_res))

    def no_sync(fn):  # 일부러 틀리게: 끝나기를 기다리지 않고 시계를 본다
        start = time.perf_counter()
        fn()
        elapsed = (time.perf_counter() - start) * 1e3
        if device == "cuda":
            torch.cuda.synchronize()  # (다음 측정에 영향이 없도록 여기서 기다린다. 이 시간은 재지 않는다)
        return elapsed

    out = {"cold": cold, "nosync": [], "sync": [], "sleep": [], "after_sleep": [], "big_nosync": [], "big_sync": []}
    with torch.no_grad():
        for _ in range(3):
            time_once(big, device)
        for i in range(20 if quick else 200):  # ① 쉬지 않고: 동기화 없이 / 동기화하고
            out["nosync"].append(no_sync(small))
            out["sync"].append(time_once(small, device))
            if i % 5 == 0:  # 다섯 바퀴에 한 번: GPU 가 실제로 바쁜 일감 (큰 배치)
                out["big_nosync"].append(no_sync(big))
                out["big_sync"].append(time_once(big, device))
        for _ in range(5 if quick else 50):  # ② 200 ms 를 쉰 직후의 순전파와, 바로 이어서 한 번 더
            time.sleep(0.02 if quick else 0.2)
            out["sleep"].append(time_once(small, device))
            out["after_sleep"].append(time_once(small, device))
    cold = np.array(cold)
    print(f"[시간 재기의 기본] 기본 구성, 장치 {device}. 방법들을 번갈아 잰다")
    print(f"  이 프로세스의 첫 순전파들 (ms): 1번째 {cold[0]:.2f}, 2번째 {cold[1]:.2f}, 3번째 {cold[2]:.2f}, 10번째 {cold[9]:.2f}"
          + (f", 40번째 {cold[39]:.2f}" if len(cold) >= 40 else ""))
    rows = (("nosync", "배치 1, 동기화 없이 (틀린 방법)"), ("sync", "배치 1, 동기화하고"), ("sleep", "배치 1, 200 ms 쉰 직후"),
            ("after_sleep", "배치 1, 그 바로 다음 호출"),
            ("big_nosync", f"배치 {big_batch} · 해상도 {big_res}, 동기화 없이"), ("big_sync", f"배치 {big_batch} · 해상도 {big_res}, 동기화하고"))
    for key, label in rows:
        v = np.array(out[key])
        print(f"  {label:32s} {len(v):3d}번: 중앙값 {np.median(v):7.3f} ms, 평균 {v.mean():7.3f}, "
              f"10% – 90% 분위수 {np.percentile(v, 10):.3f} – {np.percentile(v, 90):.3f}, 최대 {v.max():.3f}")
    sync = np.array(out["sync"])
    print(f"  '배치 1, 동기화하고' 를 앞 · 뒤 절반으로 나눈 중앙값: {np.median(sync[:len(sync) // 2]):.3f} / "
          f"{np.median(sync[len(sync) // 2:]):.3f} ms")
    # ③ 순전파를 내보내는 CPU 코어에 따라: 스레드를 코어 하나에 묶고 같은 것을 잰다 (성능 · 효율 코어가 섞인 CPU 에서만)
    groups = cpu_core_groups()
    if len(groups) == 2:
        out["cores"] = {}
        with torch.no_grad():
            for name, label in (("P", "성능 코어"), ("E", "효율 코어")):
                before = pin_thread(core=groups[name][len(groups[name]) // 2])
                for _ in range(5 if quick else 30):
                    small()
                v = np.array([time_once(small, device) for _ in range(10 if quick else 100)])
                pin_thread(restore=before)
                out["cores"][name] = v.tolist()
                print(f"  배치 1, 스레드를 {label} 하나({groups[name][len(groups[name]) // 2]}번)에 묶고 {len(v):3d}번: 중앙값 {np.median(v):7.3f} ms, "
                      f"10% – 90% 분위수 {np.percentile(v, 10):.3f} – {np.percentile(v, 90):.3f}")
    else:
        print("  (성능 · 효율 코어의 구분이 없는 CPU 라 코어별 측정은 건너뜀)")
    return out


# ── 6. 격자 탐색 ────────────────────────────────────────────────────────────

_WORKER = {}


def _worker_init(n_val: int):
    torch.set_num_threads(1)
    _WORKER["targets"] = ShapesDataset(n_val, seed=1).targets


def _worker_eval(job):
    """일꾼 프로세스: 한 구성의 날출력 (logits (n, Q, K), boxes (n, Q, 4)) 을 후처리해 AP 를 계산한다."""
    key, logits, boxes = job
    result = evaluate_ap(postprocess({"pred_logits": torch.from_numpy(logits), "pred_boxes": torch.from_numpy(boxes)}),
                         _WORKER["targets"], NUM_CLASSES)
    return key, (float(result["AP"]), float(result["AP50"]), float(result["AP75"]))


# --8<-- [start:grid-search]
def grid_search(model, val_set, device, space, workers: int = 0) -> dict:
    """탐색 공간의 모든 구성에서 검증 AP 를 잰다 (재학습 없음). 돌려주는 값: {Config: (AP, AP50, AP75)}.

    (해상도, 패치, 윈도, 질의 수) 마다 검증 세트를 한 번만 순전파한다. 그 한 번에서 디코더 0 · 1 · 2 · 3층짜리 모델의
    출력이 모두 나온다: 인코더 제안 = 0층, 보조 출력 = 1 · 2층, 마지막 출력 = 3층 (10장에서 확인한 것처럼 정확히 같다).
    AP 계산(3장의 evaluate_ap)이 순전파보다 느려서, 채점은 여러 프로세스에 나눠 맡긴다 (workers > 0).
    """
    model.eval()
    jobs = []
    for resolution, patch_size, num_windows in backbone_configs(space):
        for num_queries in space["num_queries"]:
            out = predict(model, val_set, device, batch_size=125, size=resolution, patch_size=patch_size,
                          num_windows=num_windows, num_queries=num_queries)
            by_depth = [out["enc_outputs"]] + out["aux_outputs"] + [out]  # 디코더 0, 1, 2, 3층
            for dec_layers in space["dec_layers"]:
                layer = by_depth[dec_layers]
                jobs.append((Config(resolution, patch_size, num_windows, dec_layers, num_queries),
                             layer["pred_logits"].numpy(), layer["pred_boxes"].numpy()))
    if workers > 0:
        with multiprocessing.get_context("spawn").Pool(workers, _worker_init, (len(val_set),)) as pool:
            return dict(pool.imap_unordered(_worker_eval, jobs, chunksize=4))
    _WORKER["targets"] = val_set.targets
    return dict(_worker_eval(job) for job in jobs)
# --8<-- [end:grid-search]


def config_key(c: Config) -> str:
    return "/".join(str(v) for v in c)


def fmt_config(c: Config) -> str:
    return f"{c.resolution:3d} / {c.patch_size:2d} / {c.num_windows} / {c.dec_layers} / {c.num_queries:2d}"


def pick_sizes(configs, cost, ap, budgets):
    """"미니 N / S / M / L": 비용 예산마다, 그 예산 안에서 AP 가 가장 높은 구성의 번호 (없으면 None)."""
    picks = {}
    for name, budget in budgets:
        ok = np.where(cost <= budget)[0]
        picks[name] = int(ok[np.argmax(ap[ok])]) if len(ok) else None
    return picks


def search_mode(args, device, val_set, train_space, search_space):
    suffix = "_quick" if args.quick else ""
    nas_path = f"ch12_nas{suffix}.pt"
    if not os.path.exists(nas_path):
        raise SystemExit(f"{nas_path} 가 없습니다. 먼저 python ch12_nas.py{' --quick' if args.quick else ''} 로 학습하세요.")
    start = time.time()
    nas, nas_ckpt = load_model(nas_path, device)
    print(machine_state())
    # 이 프로세스의 첫 순전파들: 다른 무엇보다 먼저 잰다 (예열 전의 모습을 보려고)
    first = forward_fn(nas, resized_batch(val_set, device, BASE.resolution, 1), BASE)
    with torch.no_grad():
        cold = [time_once(first, device) for _ in range(10 if args.quick else 40)]
    fixed = load_model("ch11_rfdetr.pt", device)[0] if os.path.exists("ch11_rfdetr.pt") else None
    if fixed is None:
        print("(ch11_rfdetr.pt 가 없어 11장 고정 구성 모델과의 비교는 건너뜀)")
    describe_space(train_space, search_space)
    configs = all_configs(search_space)
    train_set_configs = set(backbone_configs(nas_ckpt.get("train_space", train_space)))
    seen = np.array([(c.resolution, c.patch_size, c.num_windows) in train_set_configs for c in configs])

    # (1) 검증 AP — 모든 구성
    t = time.time()
    ap_nas = grid_search(nas, val_set, device, search_space, args.workers)
    print(f"[격자 탐색] NAS 학습 모델 ({nas_path}, {nas_ckpt['epochs']} 에폭): 구성 {len(configs)}개의 검증 AP, {time.time() - t:.0f}초")
    ap_fixed = None
    if fixed is not None:
        t = time.time()
        ap_fixed = grid_search(fixed, val_set, device, search_space, args.workers)
        print(f"[격자 탐색] 11장 고정 구성 모델 (ch11_rfdetr.pt): 구성 {len(configs)}개의 검증 AP, {time.time() - t:.0f}초")
    check = eval_config(nas, val_set, device, Config(*configs[5]))
    print(f"  check 구성 {fmt_config(configs[5])} 을 따로 순전파해 잰 AP {check['AP']:.6f} = 격자 탐색의 값 {ap_nas[configs[5]][0]:.6f}")

    # (2) 연산량 — 모든 구성 (그림 한 장)
    t = time.time()
    flops = np.array([count_flops(nas, resized_batch(val_set, device, c.resolution, 1), patch_size=c.patch_size,
                                  num_windows=c.num_windows, dec_layers=c.dec_layers, num_queries=c.num_queries)
                      for c in configs]) / 1e6
    print(f"[연산량] FlopCounterMode, 그림 한 장: {flops.min():.1f} – {flops.max():.1f} MFLOPs "
          f"(기본 구성 {flops[configs.index(BASE)]:.1f}), {time.time() - t:.0f}초")

    # (3) 시간 — 배치 1 의 지연 시간, 배치 64 의 그림 한 장당 시간. 모든 구성을 번갈아 잰다
    print(machine_state())
    basics = timing_basics(nas, val_set, device, args.quick, cold)
    rounds1, rounds64, big = (2, 1, 8) if args.quick else (20, 8, 64)
    inputs1 = {r: resized_batch(val_set, device, r, 1) for r in search_space["resolution"]}
    inputs64 = {r: resized_batch(val_set, device, r, big) for r in search_space["resolution"]}
    # 구성들을 재는 동안에는 스레드를 성능 코어 하나에 묶어 둔다 (어느 코어에서 도느냐에 따라 값이 두 배씩 달라지므로)
    groups = cpu_core_groups()
    before = pin_thread(core=groups["P"][len(groups["P"]) // 2]) if "P" in groups else None
    print("[시간] 구성을 재는 스레드: " + (f"성능 코어 {groups['P'][len(groups['P']) // 2]}번에 묶음" if before is not None else "코어에 묶지 않음"))
    t = time.time()
    lat = measure_interleaved({c: forward_fn(nas, inputs1[c.resolution], c) for c in configs}, device, rounds1, 3)
    t1 = time.time() - t
    t = time.time()
    thr = measure_interleaved({c: forward_fn(nas, inputs64[c.resolution], c) for c in configs}, device, rounds64, 2)
    t64 = time.time() - t
    if before is not None:
        pin_thread(restore=before)
    lat_med = np.array([np.median(lat[c]) for c in configs])
    lat_min = np.array([lat[c].min() for c in configs])
    lat_hi = np.array([np.percentile(lat[c], 90) for c in configs])
    per_image_med = np.array([np.median(thr[c]) for c in configs]) / big
    per_image = np.array([thr[c].min() for c in configs]) / big
    base_index = configs.index(BASE) if BASE in configs else 0
    ratio = lat_med / lat_min
    print(f"[시간] 배치 1: 구성마다 {len(lat[configs[0]])}번 (라운드 {rounds1} × 3, 번갈아), {t1:.0f}초. "
          f"중앙값 {lat_med.min():.2f} – {lat_med.max():.2f} ms (기본 구성 {lat_med[base_index]:.2f}), "
          f"최솟값 {lat_min.min():.2f} – {lat_min.max():.2f} ms (기본 구성 {lat_min[base_index]:.2f})")
    base_times = lat[configs[base_index]]
    by_round = base_times.reshape(-1, 3).mean(axis=1)
    print(f"  기본 구성의 {len(base_times)}번: 최소 {base_times.min():.2f}, 10% {np.percentile(base_times, 10):.2f}, 25% "
          f"{np.percentile(base_times, 25):.2f}, 중앙값 {np.median(base_times):.2f}, 75% {np.percentile(base_times, 75):.2f}, "
          f"90% {np.percentile(base_times, 90):.2f} ms")
    print("  기본 구성의 라운드별 평균 (ms): " + " ".join(f"{v:.1f}" for v in by_round))
    print(f"  구성마다의 '중앙값 ÷ 최솟값': 중앙값 {np.median(ratio):.2f}, 최소 {ratio.min():.2f}, 최대 {ratio.max():.2f}. "
          f"이 비가 1.3 보다 작은 구성 {int((ratio < 1.3).sum())}개, 큰 구성 {int((ratio >= 1.3).sum())}개")
    if (ratio >= 1.3).any():
        print("  → 같은 구성의 값이 빠른 무리와 느린 무리로 갈린다 (중앙값이 어느 무리에 떨어지는지는 구성마다 다를 수 있다). "
              "지연 시간의 대푯값으로 최솟값을 쓴다")
    else:
        print("  → 값이 한 무리로 모여 있다. 지연 시간의 대푯값으로 최솟값을 쓴다 (중앙값과 거의 같다)")
    ratio64 = per_image_med / per_image
    print(f"[시간] 배치 {big}: 구성마다 {len(thr[configs[0]])}번, {t64:.0f}초 ('중앙값 ÷ 최솟값' 의 중앙값 {np.median(ratio64):.2f}, "
          f"최대 {ratio64.max():.2f}; 여기서도 최솟값을 쓴다). 그림 한 장당 {per_image.min():.3f} – {per_image.max():.3f} ms "
          f"(처리량 초당 {1e3 / per_image.max():,.0f} – {1e3 / per_image.min():,.0f}장), "
          f"기본 구성 {per_image[base_index]:.3f} ms (초당 {1e3 / per_image[base_index]:,.0f}장)")
    from scipy.stats import spearmanr

    depth = np.array([c.dec_layers for c in configs])
    print("  디코더 층 수별 (그 층 수인 구성들의 중앙값과 범위): " + ", ".join(
        f"{d}층 배치 1 {np.median(lat_min[depth == d]):.2f} ms ({lat_min[depth == d].min():.2f} – {lat_min[depth == d].max():.2f}) · "
        f"배치 {big} {np.median(per_image[depth == d]):.3f} ms/장"
        for d in sorted(set(depth.tolist()))))
    print(f"  연산량(MFLOPs)과의 순위 상관(스피어만): 배치 1 지연 시간 {spearmanr(flops, lat_min)[0]:+.3f}, "
          f"배치 {big} 장당 시간 {spearmanr(flops, per_image)[0]:+.3f} | 디코더 층 수와의 순위 상관: 배치 1 "
          f"{spearmanr(depth, lat_min)[0]:+.3f}, 배치 {big} {spearmanr(depth, per_image)[0]:+.3f}")
    if device == "cuda":
        print(f"  GPU 메모리 최대 사용 {torch.cuda.max_memory_allocated() / 2**20:.0f} MiB")
    print(machine_state())

    # (3.5) 일반화 간격: 기본 구성에서 학습 그림과 검증 그림의 손실 · AP
    train_part = ShapesDataset(len(val_set), seed=0)  # 학습 세트의 앞부분과 같은 그림
    gap = []
    for name, model in [("NAS 학습 모델", nas)] + ([("11장 고정 구성 모델", fixed)] if fixed is not None else []):
        gap.append([name, *loss_and_ap(model, train_part, device), *loss_and_ap(model, val_set, device)])

    result = {
        "gap": gap, "n_val": len(val_set),
        "configs": [list(c) for c in configs], "seen": seen.tolist(),
        "ap_nas": [list(ap_nas[c]) for c in configs],
        "ap_fixed": [list(ap_fixed[c]) for c in configs] if ap_fixed else None,
        "flops": flops.tolist(), "latency": lat_min.tolist(), "latency_median": lat_med.tolist(), "latency_hi": lat_hi.tolist(),
        "per_image_median": per_image_med.tolist(),
        "latency_raw": [lat[c].round(4).tolist() for c in configs], "per_image_raw": [(thr[c] / big).round(5).tolist() for c in configs],
        "per_image": per_image.tolist(), "big_batch": big, "basics": basics, "device": device,
        "history": nas_ckpt["history"], "extras": {},
    }
    # (4) 다른 시드 · 더 긴 학습의 체크포인트가 있으면 같은 격자의 AP 를 함께 잰다
    for path in sorted(glob.glob("ch12_nas_*.pt")):
        tag = path[len("ch12_nas_"):-3]
        if args.quick or tag.startswith("quick"):
            continue
        extra, extra_ckpt = load_model(path, device)
        ap_extra = grid_search(extra, val_set, device, search_space, args.workers)
        result["extras"][tag] = {"ap": [list(ap_extra[c]) for c in configs], "epochs": extra_ckpt["epochs"],
                                 "seed": extra_ckpt.get("seed", 0)}
    with open(f"ch12_search{suffix}.json", "w") as f:
        json.dump(result, f)
    print(f"저장: ch12_search{suffix}.json  |  측정 전체 {time.time() - start:.0f}초")
    report(result, args.fig_dir)


def report(result, fig_dir):
    """ch12_search.json 의 내용으로 표를 찍고 그림을 그린다."""
    configs = [Config(*c) for c in result["configs"]]
    index = {c: i for i, c in enumerate(configs)}
    seen = np.array(result["seen"])
    ap = np.array(result["ap_nas"])[:, 0]
    full = np.array(result["ap_nas"])
    fixed = np.array(result["ap_fixed"])[:, 0] if result["ap_fixed"] else None
    flops, lat, per_image = np.array(result["flops"]), np.array(result["latency"]), np.array(result["per_image"])
    spaces = {k: sorted({getattr(c, k) for c in configs}) for k in Config._fields}

    def row(c):
        i = index[c]
        fix = f"{fixed[i]:.4f}" if fixed is not None else "   -  "
        return (f"{fmt_config(c)} | {'봄 ' if seen[i] else '못 봄'} | {ap[i]:.4f} {full[i, 1]:.4f} {full[i, 2]:.4f} | {fix} | "
                f"{flops[i]:7.1f} | {lat[i]:5.2f} | {per_image[i]:.3f}")

    header = ("해상도 / 패치 / 윈도 / 층 / 질의 | 학습 때 | NAS: AP AP50   AP75   | 고정   | MFLOPs  | 배치 1 ms | "
              f"배치 {result['big_batch']} ms/장")

    # ── 기본 구성, 전체 요약 ──
    print("\n[기본 구성] " + header)
    if BASE in index:
        print("  " + row(BASE))
    print(f"[전체 요약] 구성 {len(configs)}개 (학습 때 본 조합 {int(seen.sum())}개, 못 본 조합 {int((~seen).sum())}개)")
    names = [("NAS 학습 모델", ap)] + ([("11장 고정 구성 모델", fixed)] if fixed is not None else [])
    for name, values in names:
        print(f"  {name:18s} | AP 평균 {values.mean():.4f}, 중앙값 {np.median(values):.4f}, 최소 {values.min():.4f}, 최대 "
              f"{values.max():.4f} | AP ≥ 0.90 인 구성 {int((values >= 0.9).sum())}개, ≥ 0.80 {int((values >= 0.8).sum())}개, "
              f"< 0.50 {int((values < 0.5).sum())}개")
    best = int(np.argmax(ap))
    print(f"  NAS 학습 모델의 최고 AP: {fmt_config(configs[best])} → {ap[best]:.4f}")
    if fixed is not None:
        same = np.array([(c.resolution, c.patch_size) == (BASE.resolution, BASE.patch_size) for c in configs])
        print(f"  11장 모델: 학습한 (해상도 96, 패치 8) 인 구성 {int(same.sum())}개의 AP 평균 {fixed[same].mean():.4f} "
              f"(최소 {fixed[same].min():.4f}), 그 밖의 구성 {int((~same).sum())}개의 AP 평균 {fixed[~same].mean():.4f} "
              f"(최대 {fixed[~same].max():.4f})")
        print(f"  NAS 모델이 11장 모델보다 AP 가 높은 구성: {int((ap > fixed).sum())} / {len(configs)}개. "
              f"(해상도 96, 패치 8) 구성들에서의 차이 NAS − 고정: 평균 {np.mean(ap[same] - fixed[same]):+.4f}, "
              f"범위 {np.min(ap[same] - fixed[same]):+.4f} – {np.max(ap[same] - fixed[same]):+.4f}")
    print(f"  학습 때 본 조합의 AP 평균 {ap[seen].mean():.4f}, 못 본 조합 {ap[~seen].mean():.4f} (디코더 3층 · 질의 12개만: "
          f"{np.mean([ap[i] for i, c in enumerate(configs) if seen[i] and c.dec_layers == 3 and c.num_queries == 12]):.4f} / "
          f"{np.mean([ap[i] for i, c in enumerate(configs) if not seen[i] and c.dec_layers == 3 and c.num_queries == 12]):.4f})")

    print(f"[일반화 간격] 기본 구성, 학습 세트의 앞 {result.get('n_val', 500)}장과 검증 {result.get('n_val', 500)}장 (EMA 모델, 추론 모드)")
    print("  모델                | 학습 그림: 손실   AP     | 검증 그림: 손실   AP     | 손실의 차이 (검증 − 학습)")
    for name, train_loss, train_ap, val_loss, val_ap in result["gap"]:
        print(f"  {name:18s} |           {train_loss:.4f} {train_ap:.4f} |           {val_loss:.4f} {val_ap:.4f} | {val_loss - train_loss:+.4f}")

    # ── 손잡이별 민감도: 기본 구성에서 하나만 바꾼다 ──
    print("\n[손잡이별 민감도] 기본 구성에서 손잡이 하나만 바꾼다")
    knob_rows = {}
    for knob in Config._fields:
        rows = [BASE._replace(**{knob: v}) for v in spaces[knob]]
        rows = [c for c in rows if c in index]
        knob_rows[knob] = rows
        print(f"  ({knob}) " + header)
        for c in rows:
            print("    " + row(c) + ("   ← 기본" if c == BASE else ""))

    # ── 디코더 층 × 질의 수 (논문 부록 B · 그림 4 의 미니판) ──
    print("\n[디코더 층 × 질의 수] 백본 쪽은 기본 구성 (96 / 8 / 윈도 2). 칸: AP (배치 1 지연 시간 ms)")
    print("  디코더 층 | " + " | ".join(f"질의 {q:2d}        " for q in spaces["num_queries"]))
    for d in spaces["dec_layers"]:
        cells = [f"{ap[index[c]]:.4f} ({lat[index[c]]:.2f})" for q in spaces["num_queries"]
                 for c in [BASE._replace(dec_layers=d, num_queries=q)] if c in index]
        print(f"  {d:9d} | " + " | ".join(cells))

    # ── 공간 위치 수 (부록 L 의 미니 점검): 윈도 1 · 디코더 3층 · 질의 12개 ──
    print("\n[공간 위치 수] 토큰 격자의 한 변 = 해상도 ÷ 패치. 윈도 1, 디코더 3층, 질의 12개")
    print("  격자 | (해상도 / 패치: AP, *는 학습 때 못 본 조합) …                                   | AP 의 범위")
    dq = (max(spaces["dec_layers"]), max(spaces["num_queries"]))
    grids = {}
    for i, c in enumerate(configs):
        if c.num_windows == 1 and (c.dec_layers, c.num_queries) == dq:
            grids.setdefault(c.resolution // c.patch_size, []).append(i)
    for g in sorted(grids):
        cells = [f"{configs[i].resolution}/{configs[i].patch_size}: {ap[i]:.4f}{'' if seen[i] else '*'}" for i in grids[g]]
        values = ap[grids[g]]
        spread = f"{values.max() - values.min():.4f}" if len(values) > 1 else "  -"
        print(f"  {g:4d} | {', '.join(cells):78s} | {spread}")

    # ── 학습 때 못 본 구성 ──
    print("\n[학습 때 못 본 해상도] 패치 8, 윈도 1, 디코더 3층, 질의 12개: 해상도 → AP (*는 못 본 해상도)")
    line = [f"{c.resolution}{'' if seen[i] else '*'}: {ap[i]:.4f}" for i, c in enumerate(configs)
            if c.patch_size == 8 and c.num_windows == 1 and (c.dec_layers, c.num_queries) == dq]
    print("  " + ",  ".join(line))
    for flag, label in ((True, "본"), (False, "못 본")):
        rows_p8 = [ap[i] for i, c in enumerate(configs) if c.patch_size == 8 and c.num_windows == 1
                   and (c.dec_layers, c.num_queries) == dq and seen[i] == flag and 64 < c.resolution < 128]
        if rows_p8:
            print(f"  해상도 72 – 120 가운데 학습 때 {label} 해상도 {len(rows_p8)}개의 AP 평균 {np.mean(rows_p8):.4f}")

    # ── 파레토 경계 ──
    fronts = {}
    for axis, cost, unit in (("flops", flops, "MFLOPs"), ("latency", lat, "배치 1 ms"), ("per_image", per_image, "ms/장")):
        front = pareto_front(cost, ap)
        fronts[axis] = front.tolist()
        print(f"\n[파레토 경계] 가로축 = {unit}: {len(configs)}개 가운데 {len(front)}개가 경계 위")
        print("  " + header)
        for i in front:
            print("  " + row(configs[i]))
        for knob in Config._fields:
            used = sorted({getattr(configs[i], knob) for i in front})
            print(f"    경계 위 구성이 쓰는 {knob}: {used}")
        if fixed is not None:
            ffront = pareto_front(cost, fixed)
            fronts[axis + "_fixed"] = ffront.tolist()
    base_flops = flops[index[BASE]] if BASE in index else flops.max()
    budgets = [("N", base_flops / 4), ("S", base_flops / 2), ("M", base_flops), ("L", np.inf)]
    picks = pick_sizes(configs, flops, ap, budgets)
    print(f"\n[미니 N / S / M / L] 연산량 예산 = 기본 구성({base_flops:.1f} MFLOPs)의 1/4 · 1/2 · 1배 · 제한 없음 안에서 AP 가 가장 높은 구성")
    print("  이름 | 예산 MFLOPs | " + header)
    for name, budget in budgets:
        if picks[name] is not None:
            print(f"  {name:4s} | {budget:11.1f} | " + row(configs[picks[name]]))
    if fixed is not None:
        fpicks = pick_sizes(configs, flops, fixed, budgets)
        print("  같은 예산에서 11장 고정 구성 모델로 고르면: " + ", ".join(
            f"{name} {fmt_config(configs[fpicks[name]]).replace(' ', '')} AP {fixed[fpicks[name]]:.4f}"
            for name, _ in budgets if fpicks[name] is not None))

    # ── 다른 시드 · 더 긴 학습 ──
    if result["extras"]:
        print("\n[다른 실행과의 비교] 같은 격자의 검증 AP")
        print("  실행                         | 기본 구성 AP | 기본 구성에서 디코더 0층 | 전체 평균 | 최고   | AP ≥ 0.90 인 구성 | N      S      M      L (위에서 고른 구성의 AP)")
        runs = [("NAS 60 에폭, 시드 0 (본 실행)", ap)] + [
            (f"NAS {e['epochs']} 에폭, 시드 {e['seed']} ({tag})", np.array(e["ap"])[:, 0]) for tag, e in result["extras"].items()]
        if fixed is not None:
            runs.append(("11장 고정 구성, 60 에폭", fixed))
        for name, values in runs:
            print(f"  {name:28s} | {values[index[BASE]]:.4f}       | {values[index[BASE._replace(dec_layers=0)]]:.4f}                   | "
                  f"{values.mean():.4f}    | {values.max():.4f} | "
                  f"{int((values >= 0.9).sum()):4d}              | "
                  + " ".join(f"{values[picks[n]]:.4f}" for n, _ in budgets if picks[n] is not None))

    plot_training(result["history"], os.path.join(fig_dir, "ch12-training.png"))
    plot_pareto(configs, ap, flops, lat, fronts, picks, os.path.join(fig_dir, "ch12-pareto.png"))
    if fixed is not None:
        plot_fixed_vs_nas(configs, seen, ap, fixed, flops, fronts, os.path.join(fig_dir, "ch12-fixed-vs-nas.png"))
    plot_knobs(knob_rows, index, ap, fixed, flops, os.path.join(fig_dir, "ch12-knobs.png"))
    plot_spatial(configs, seen, ap, per_image, grids, result["big_batch"], os.path.join(fig_dir, "ch12-spatial.png"))
    plot_latency(result, configs, flops, lat, per_image, os.path.join(fig_dir, "ch12-latency.png"))


# ── 7. NAS 뒤 미세 조정 (부록 G 의 미니 점검) ────────────────────────────────


def finetune_mode(args, device, train_set, val_set, train_space):
    suffix = "_quick" if args.quick else ""
    path = f"ch12_nas{suffix}.pt"
    if not os.path.exists(path):
        raise SystemExit(f"{path} 가 없습니다. 먼저 학습하세요.")
    epochs = 1 if args.quick else 10
    targets = [Config(64, 16, 1, 3, 12), Config(64, 8, 2, 3, 12), BASE]
    if args.quick:
        targets = targets[1:2]
    ckpt = torch.load(path, map_location=device)
    reference = load_model(path, device)[0]
    before = {c: eval_config(reference, val_set, device, c)["AP"] for c in targets}
    print(f"[NAS 뒤 미세 조정] {path} 의 EMA 가중치에서 출발해 {epochs} 에폭 더 학습 (학습률 등은 그대로, 시드 {args.seed})")
    runs = [("NAS 를 계속 (대조군)", backbone_configs(ckpt.get("train_space", train_space)))]
    runs += [(f"{c.resolution}/{c.patch_size}/w{c.num_windows} 로 고정", [(c.resolution, c.patch_size, c.num_windows)])
             for c in targets]
    table = {}
    for name, train_configs in runs:
        start = time.time()
        torch.manual_seed(args.seed)
        model = MiniRFDETR(**ckpt["config"]).to(device)
        model.load_state_dict(ckpt["ema"])
        model.backbone.patch_resize_fn = pi_resize_patch_embed
        criterion = RFDETRCriterion(NUM_CLASSES, group_detr=model.group_detr).to(device)
        optimizer, _ = build_optimizer(model, lr=2e-4)
        ema = ModelEMA(model)
        loader = make_loader(train_set, 32, shuffle=True, seed=args.seed + 100)
        rng = np.random.default_rng(args.seed + 100)
        for _ in range(epochs):
            train_nas_epoch(model, criterion, loader, optimizer, device, ema, train_configs, rng)
        table[name] = {c: eval_config(ema.module, val_set, device, c)["AP"] for c in targets}
        print(f"  {name:22s} 학습 끝 ({time.time() - start:.0f}초)", flush=True)
    print("  채점하는 구성 →            | " + " | ".join(f"{c.resolution}/{c.patch_size}/w{c.num_windows}".ljust(16) for c in targets))
    print("  미세 조정 전 (NAS 모델)     | " + " | ".join(f"{before[c]:.4f}".ljust(16) for c in targets))
    for name, values in table.items():
        print(f"  {name:26s} | " + " | ".join(f"{values[c]:.4f} ({values[c] - before[c]:+.4f})" for c in targets))
    print("  (괄호 = 미세 조정 전과의 차이. 대각선 — 고정한 구성과 채점하는 구성이 같은 칸 — 이 '그 구성만으로 미세 조정' 의 효과다)")


# ── 8. 그림 ─────────────────────────────────────────────────────────────────


def plot_pareto_toy(names, cost, acc, front, path):
    import matplotlib.pyplot as plt

    fig, ax = plt.subplots(figsize=(6.6, 4.2))
    on = set(front.tolist())
    d = names.index("d")
    ax.fill_between([cost[d], 8.0], 20, acc[d], color=ORANGE, alpha=0.15, lw=0)
    ax.text(7.9, 22, "region dominated by d\n(slower and less accurate)", ha="right", va="bottom", fontsize=8, color=RED)
    xs = [cost[i] for i in front] + [8.0]
    ys = [acc[i] for i in front] + [acc[front[-1]]]
    ax.step(xs, ys, where="post", color=BLUE, lw=1.8, label="Pareto frontier")
    for i, name in enumerate(names):
        if i in on:
            ax.plot(cost[i], acc[i], "o", color=BLUE, ms=9)
        else:
            ax.plot(cost[i], acc[i], "X", color=GRAY, ms=9)
        ax.annotate(name, (cost[i], acc[i]), textcoords="offset points", xytext=(-11, 6), fontsize=11, fontweight="bold")
    ax.plot([], [], "o", color=BLUE, label="Pareto-optimal")
    ax.plot([], [], "X", color=GRAY, label="dominated")
    ax.set_xlim(0.5, 8.0)
    ax.set_ylim(20, 66)
    ax.set_xlabel("latency (ms)  — lower is better")
    ax.set_ylabel("accuracy (AP)  — higher is better")
    ax.set_title("Toy example: 8 models, 5 on the Pareto frontier")
    ax.grid(alpha=0.3)
    ax.legend(loc="upper left", fontsize=8)
    fig.tight_layout()
    fig.savefig(path, dpi=120)
    plt.close(fig)


def plot_pi_resize(weight, rows, original, resized, path):
    import matplotlib.pyplot as plt

    fig = plt.figure(figsize=(14.5, 4.6))
    grid = fig.add_gridspec(2, 4, width_ratios=[1, 1, 2.6, 2.6], wspace=0.42, hspace=0.32)
    channel = int(weight.flatten(1).std(dim=1).argmax())
    kernel = weight[channel:channel + 1]  # (1, 3, 8, 8)
    short = {"PI-resize": "PI-resize", "bicubic x (p/p')^2 (ch09)": "bicubic, scaled", "bilinear only": "bilinear only"}
    panels = [("original kernel 8x8", kernel)] + [(short[name] + " 16x16", fn(kernel, 16)) for name, fn in RESIZERS.items()]
    scale = float(kernel.abs().max())
    for k, (title, w) in enumerate(panels):
        ax = fig.add_subplot(grid[k // 2, k % 2])
        ax.imshow(w[0, 0].numpy(), cmap="RdBu_r", vmin=-scale, vmax=scale)
        ax.set_title(title, fontsize=8.5)
        ax.set_xticks([])
        ax.set_yticks([])
    styles = {"PI-resize": (BLUE, "o", "-"), "bicubic x (p/p')^2 (ch09)": (ORANGE, "s", "--"), "bilinear only": (GREEN, "^", ":")}
    ax = fig.add_subplot(grid[:, 2])
    lim = float(original.abs().max()) * 1.05
    for name in ("bilinear only", "bicubic x (p/p')^2 (ch09)", "PI-resize"):
        color, marker, _ = styles[name]
        ax.plot(original.flatten()[::37].numpy(), resized[name].flatten()[::37].numpy(), marker, ms=2.5, color=color,
                alpha=0.5, label=name)
    ax.plot([-lim, lim], [-lim, lim], color="k", lw=0.8, label="y = x (perfect preservation)")
    ax.set_xlim(-lim, lim)
    ax.set_ylim(-4.2 * lim, 4.2 * lim)
    ax.set_xlabel("token before:  <x, w>  (patch 8, kernel 8)")
    ax.set_ylabel("token after resizing both to 16:  <Rx, w_hat>")
    ax.set_title("tokens before vs. after (8 -> 16)", fontsize=9.5)
    ax.legend(fontsize=7, loc="upper left", markerscale=3)
    ax.grid(alpha=0.3)
    ax = fig.add_subplot(grid[:, 3])
    for name, values in rows.items():
        color, marker, line = styles[name]
        ax.plot([str(v[0]) for v in values], [max(v[1], 1e-16) for v in values], marker=marker, ls=line, color=color, label=name)
    ax.axvline(1.5, color=GRAY, lw=0.8, ls="--")
    ax.text(1.42, 1e-8, "shrink", fontsize=8, color=GRAY, ha="right")
    ax.text(1.58, 1e-8, "enlarge", fontsize=8, color=GRAY, ha="left")
    ax.set_yscale("log")
    ax.set_xlabel("new patch size p'  (original: 8)")
    ax.set_ylabel("relative error of the tokens")
    ax.set_title("inner-product preservation error", fontsize=9.5)
    ax.legend(fontsize=7, loc="center right")
    ax.grid(alpha=0.3)
    fig.suptitle("left: one kernel (red channel) of the patch embedding and its three resized versions, same colour scale", fontsize=9, x=0.02, ha="left")
    fig.savefig(path, dpi=120, bbox_inches="tight")
    plt.close(fig)


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

    fig, axes = plt.subplots(1, 2, figsize=(11, 3.9))
    fixed = None
    if os.path.exists("ch11_history.json"):
        with open("ch11_history.json") as f:
            fixed = json.load(f)
    axes[0].plot(history["epoch"], history["loss"], color=BLUE, label="weight-sharing NAS (random config per step)")
    if fixed:
        axes[0].plot(fixed["epoch"], fixed["loss"], color=ORANGE, ls="--", label="ch11 fixed config (96 / patch 8 / 2 windows)")
    axes[0].set_yscale("log")
    axes[0].set_xlabel("epoch")
    axes[0].set_ylabel("training loss (sum over 3 decoder layers + proposals)")
    axes[0].set_title("training loss")
    axes[0].legend(fontsize=8)
    axes[0].grid(alpha=0.3, which="both")
    styles = [(BLUE, "o", "-"), (GREEN, "^", "-."), (PINK, "s", ":")]
    for column, monitor, (color, marker, line) in zip(history["AP"], history["monitors"], styles):
        axes[1].plot(history["ap_epoch"], column, marker=marker, ms=4, ls=line, color=color,
                     label=f"NAS model @ res {monitor[0]} / patch {monitor[1]} / {monitor[2]} windows")
    if fixed:
        axes[1].plot(fixed["ap_epoch"], fixed["AP"], marker="x", ms=4, ls="--", color=ORANGE, label="ch11 fixed model @ res 96 / patch 8 / 2 windows")
    axes[1].set_ylim(0.6, 0.96)
    axes[1].set_xlabel("epoch")
    axes[1].set_ylabel("validation AP (EMA weights)")
    axes[1].set_title("validation AP during training (3 decoder layers, 12 queries)")
    axes[1].legend(fontsize=7.5, loc="lower right")
    axes[1].grid(alpha=0.3)
    fig.tight_layout()
    fig.savefig(path, dpi=120)
    plt.close(fig)


DEPTH_COLORS = {0: RED, 1: ORANGE, 2: GREEN, 3: BLUE}
DEPTH_MARKERS = {0: "v", 1: "s", 2: "^", 3: "o"}


def plot_pareto(configs, ap, flops, lat, fronts, picks, path):
    import matplotlib.pyplot as plt

    fig, axes = plt.subplots(1, 2, figsize=(13, 5))
    low = max(0.0, min(0.6, float(np.percentile(ap, 2)) - 0.02))
    for ax, cost, key, label in ((axes[0], flops, "flops", "compute per image (MFLOPs)"),
                                 (axes[1], lat, "latency", "latency, batch 1 (ms, fastest of 60 runs)")):
        for depth in sorted({c.dec_layers for c in configs}):
            sel = np.array([c.dec_layers == depth for c in configs])
            ax.scatter(cost[sel], ap[sel], s=14, alpha=0.55, color=DEPTH_COLORS[depth], marker=DEPTH_MARKERS[depth],
                       label={0: "0 decoder layers (proposals only)", 1: "1 decoder layer"}.get(depth, f"{depth} decoder layers"))
        front = np.array(fronts[key])
        ax.step(cost[front], ap[front], where="post", color="k", lw=1.5, label="Pareto frontier")
        ax.scatter(cost[front], ap[front], s=46, facecolors="none", edgecolors="k", lw=1.2)
        ax.set_xlabel(label)
        ax.set_ylabel("validation AP")
        ax.set_ylim(low, min(1.0, float(ap.max()) + 0.015))
        ax.grid(alpha=0.3)
    for name, i in picks.items():
        if i is not None:
            axes[0].annotate(f"mini {name}", (flops[i], ap[i]), textcoords="offset points", xytext=(14, -34), fontsize=9,
                             fontweight="bold", arrowprops={"arrowstyle": "-", "lw": 0.8},
                             bbox={"boxstyle": "round,pad=0.15", "fc": "white", "ec": "none", "alpha": 0.8})
    below = int((ap < low).sum())
    axes[0].set_title(f"all {len(configs)} configurations of ONE trained model" + (f" ({below} below the axis)" if below else ""))
    axes[1].set_title("same points, measured latency on this laptop GPU")
    axes[0].legend(fontsize=8, loc="lower right")
    fig.tight_layout()
    fig.savefig(path, dpi=120)
    plt.close(fig)


def plot_fixed_vs_nas(configs, seen, ap, fixed, flops, fronts, path):
    import matplotlib.pyplot as plt

    fig, axes = plt.subplots(1, 3, figsize=(15.5, 4.6))
    same = np.array([(c.resolution, c.patch_size) == (BASE.resolution, BASE.patch_size) for c in configs])
    ax = axes[0]
    ax.scatter(fixed[~same & seen], ap[~same & seen], s=14, color=BLUE, alpha=0.6, label="other configs sampled in NAS training")
    ax.scatter(fixed[~seen], ap[~seen], s=22, color=GREEN, marker="*", alpha=0.7, label="configs never sampled in training")
    ax.scatter(fixed[same], ap[same], s=26, color=ORANGE, marker="s", label="res 96 / patch 8 (what the fixed model was trained on)")
    ax.plot([0, 1], [0, 1], color="k", lw=0.8)
    ax.set_xlim(-0.02, 1.0)
    ax.set_ylim(-0.02, 1.0)
    ax.set_xlabel("AP of the ch11 fixed-config model")
    ax.set_ylabel("AP of the weight-sharing NAS model")
    ax.set_title("same configuration, two models (above the line: NAS wins)", fontsize=10)
    ax.legend(fontsize=7.5, loc="lower right")
    ax.grid(alpha=0.3)
    ax = axes[1]
    top = (max(c.dec_layers for c in configs), max(c.num_queries for c in configs))
    for patch, color, marker in ((8, BLUE, "o"), (16, ORANGE, "s"), (12, GREEN, "*")):
        rows = [(c.resolution, ap[i], fixed[i]) for i, c in enumerate(configs)
                if c.patch_size == patch and c.num_windows == 1 and (c.dec_layers, c.num_queries) == top]
        if not rows:
            continue
        res, a, b = zip(*sorted(rows))
        ax.plot(res, a, marker=marker, color=color, label=f"NAS model, patch {patch}")
        ax.plot(res, b, marker=marker, color=color, ls=":", mfc="none", label=f"fixed model, patch {patch}")
    ax.set_xlabel("inference resolution (1 window, 3 decoder layers, 12 queries)")
    ax.set_ylabel("validation AP")
    ax.set_title("solid: NAS model, dotted: ch11 fixed model", fontsize=10)
    ax.legend(fontsize=7.5, ncol=3, loc="upper center", bbox_to_anchor=(0.5, -0.16))
    ax.grid(alpha=0.3)
    ax = axes[2]
    ax.scatter(flops, fixed, s=8, color=ORANGE, alpha=0.35)
    ax.scatter(flops, ap, s=8, color=BLUE, alpha=0.35)
    for key, values, color, label in (("flops", ap, BLUE, "NAS model: Pareto frontier"), ("flops_fixed", fixed, ORANGE, "fixed model: Pareto frontier")):
        front = np.array(fronts[key])
        ax.step(flops[front], values[front], where="post", color=color, lw=1.8, label=label)
    ax.set_xlabel("compute per image (MFLOPs)")
    ax.set_ylabel("validation AP")
    ax.set_ylim(0.0, 1.0)
    ax.set_title("Pareto frontiers of the two models", fontsize=10)
    ax.legend(fontsize=8, loc="lower right")
    ax.grid(alpha=0.3)
    fig.tight_layout()
    fig.savefig(path, dpi=120)
    plt.close(fig)


def plot_knobs(knob_rows, index, ap, fixed, flops, path):
    import matplotlib.pyplot as plt

    titles = {"resolution": "(d) resolution", "patch_size": "(a) patch size", "num_windows": "(e) windows per side",
              "dec_layers": "(b) decoder layers", "num_queries": "(c) queries"}
    order = ["patch_size", "dec_layers", "num_queries", "resolution", "num_windows"]
    fig, axes = plt.subplots(1, 5, figsize=(16.5, 3.9))
    for ax, knob in zip(axes, order):
        rows = knob_rows[knob]
        xs = [str(getattr(c, knob)) for c in rows]
        twin = ax.twinx()
        twin.bar(xs, [flops[index[c]] for c in rows], color=GRAY, alpha=0.22, width=0.6)
        twin.set_ylim(0, max(flops) * 1.05)
        twin.tick_params(labelsize=7)
        if knob == order[-1]:
            twin.set_ylabel("MFLOPs (gray bars)", fontsize=8)
        ax.plot(xs, [ap[index[c]] for c in rows], marker="o", color=BLUE, label="NAS model", zorder=3)
        if fixed is not None:
            ax.plot(xs, [fixed[index[c]] for c in rows], marker="s", ls="--", color=ORANGE, mfc="none", label="ch11 fixed model", zorder=3)
        base = xs.index(str(getattr(BASE, knob)))
        ax.axvline(base, color="k", lw=0.6, ls=":")
        ax.set_ylim(0.0, 1.0)
        ax.set_zorder(twin.get_zorder() + 1)
        ax.patch.set_visible(False)
        ax.set_title(titles[knob], fontsize=10)
        ax.set_xlabel(knob, fontsize=8)
        ax.grid(alpha=0.3)
    axes[0].set_ylabel("validation AP")
    axes[0].legend(fontsize=7.5, loc="lower left")
    fig.suptitle("one knob at a time from the base config (96 / patch 8 / 2 windows / 3 layers / 12 queries; dotted line)", fontsize=10)
    fig.tight_layout()
    fig.savefig(path, dpi=120)
    plt.close(fig)


def plot_spatial(configs, seen, ap, per_image, grids, big, path):
    import matplotlib.pyplot as plt

    fig, axes = plt.subplots(1, 2, figsize=(12, 4.4))
    styles = {8: (BLUE, "o"), 12: (GREEN, "*"), 16: (ORANGE, "s")}
    for ax, values, label in ((axes[0], ap, "validation AP"), (axes[1], per_image, f"time per image at batch {big} (ms, fastest run)")):
        for patch, (color, marker) in styles.items():
            for flag in (True, False):
                pts = [(g, values[i]) for g, rows in grids.items() for i in rows
                       if configs[i].patch_size == patch and seen[i] == flag]
                if pts:
                    x, y = zip(*pts)
                    ax.scatter(x, y, s=70 if marker == "*" else 44, marker=marker, color=color if flag else "none",
                               edgecolors=color, lw=1.4,
                               label=f"patch {patch}" + ("" if flag else " (config not seen in training)"))
        ax.set_xlabel("spatial positions per side = resolution / patch size")
        ax.set_ylabel(label)
        ax.set_xticks(sorted(grids))
        ax.grid(alpha=0.3)
    for g, rows in grids.items():
        if len(rows) > 1:
            axes[0].annotate(", ".join(f"{configs[i].resolution}/{configs[i].patch_size}" for i in rows),
                             (g, min(ap[rows])), textcoords="offset points", xytext=(14, -30), ha="left", fontsize=7,
                             arrowprops={"arrowstyle": "-", "lw": 0.6, "color": GRAY})
    axes[0].set_title("accuracy vs. number of spatial positions (1 window, 3 layers, 12 queries)", fontsize=10)
    axes[1].set_title("speed vs. number of spatial positions", fontsize=10)
    axes[0].legend(fontsize=8, loc="lower right")
    fig.tight_layout()
    fig.savefig(path, dpi=120)
    plt.close(fig)


def plot_latency(result, configs, flops, lat, per_image, path):
    import matplotlib.pyplot as plt

    basics = result["basics"]
    fig, axes = plt.subplots(2, 3, figsize=(16.5, 8))
    ax = axes[0, 0]
    ax.plot(range(1, len(basics["cold"]) + 1), basics["cold"], marker="o", ms=3, color=BLUE)
    ax.set_yscale("log")
    ax.set_xlabel("call number (the very first forward passes of the process)")
    ax.set_ylabel("time (ms, log scale)")
    ax.set_title("cold start: first calls in a fresh process", fontsize=10)
    ax.grid(alpha=0.3, which="both")
    ax = axes[0, 1]
    data = [basics["nosync"], basics["sync"], basics["sleep"], basics["after_sleep"]]
    box = ax.boxplot(data, showfliers=False, patch_artist=True, medianprops={"color": "k"})
    ax.set_xticks([1, 2, 3, 4], ["no synchronize\n(wrong)", "synchronize", "right after\n200 ms sleep", "the call\nafter that"], fontsize=8)
    for patch, color in zip(box["boxes"], (RED, BLUE, GREEN, SKY)):
        patch.set_facecolor(color)
        patch.set_alpha(0.5)
    for k, values in enumerate(data):
        ax.text(k + 1.3, float(np.median(values)), f"{np.median(values):.2f}", fontsize=8, va="center")
    ax.set_xlim(0.5, 4.9)
    ax.set_ylabel("time (ms)")
    ax.set_ylim(bottom=0)
    ax.set_title("base config, batch 1: how you measure changes the number", fontsize=10)
    ax.grid(alpha=0.3, axis="y")
    ax = axes[0, 2]
    if "latency_raw" in result:
        base = np.array(result["latency_raw"][configs.index(BASE) if BASE in configs else 0])
        ax.hist(base, bins=30, color=BLUE, alpha=0.7)
        ax.axvline(base.min(), color=RED, lw=1.5, label=f"minimum {base.min():.2f} ms")
        ax.axvline(np.median(base), color="k", lw=1.5, ls="--", label=f"median {np.median(base):.2f} ms")
        ax.legend(fontsize=8)
    ax.set_xlabel("time of one forward pass (ms)")
    ax.set_ylabel("count")
    ax.set_title("base config, batch 1: the repeated measurements", fontsize=10)
    ax.grid(alpha=0.3)
    for ax, values, label, title in ((axes[1, 0], lat, "latency, batch 1 (ms, fastest of 60 runs)", "batch 1: latency follows the number of layers"),
                                     (axes[1, 1], per_image, f"time per image, batch {result['big_batch']} (ms, fastest run)",
                                      f"batch {result['big_batch']}: time follows the compute")):
        for depth in sorted({c.dec_layers for c in configs}):
            sel = np.array([c.dec_layers == depth for c in configs])
            ax.scatter(flops[sel], values[sel], s=12, alpha=0.6, color=DEPTH_COLORS[depth], marker=DEPTH_MARKERS[depth],
                       label={1: "1 decoder layer"}.get(depth, f"{depth} decoder layers"))
        ax.set_xlabel("compute per image (MFLOPs)")
        ax.set_ylabel(label)
        ax.set_title(title, fontsize=10)
        ax.set_ylim(bottom=0)
        ax.grid(alpha=0.3)
    axes[1, 0].legend(fontsize=8, loc="lower right")
    ax = axes[1, 2]
    grid = np.array([c.resolution // c.patch_size for c in configs])
    top = max(c.dec_layers for c in configs)
    for values, color, marker, label in ((lat, BLUE, "o", "batch 1 latency"), (per_image, ORANGE, "s", f"batch {result['big_batch']} time per image")):
        sel = np.array([c.dec_layers == top and c.num_queries == max(k.num_queries for k in configs) and c.num_windows == 1 for c in configs])
        order = np.argsort(grid[sel])
        ref = values[sel][order][grid[sel][order] == grid[sel].min()].mean()
        ax.plot(grid[sel][order], values[sel][order] / ref, marker, color=color, ms=5, alpha=0.8, label=label)
    ax.set_xlabel("spatial positions per side (1 window, 3 layers, 12 queries)")
    ax.set_ylabel("time relative to the smallest grid")
    ax.set_title(f"more tokens: batch 1 does not notice, batch {result['big_batch']} does", fontsize=10)
    ax.legend(fontsize=8)
    ax.grid(alpha=0.3)
    fig.tight_layout()
    fig.savefig(path, dpi=120)
    plt.close(fig)


# ── 9. 실행 ─────────────────────────────────────────────────────────────────


# --8<-- [start:main]
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--quick", action="store_true")
    parser.add_argument("--search", action="store_true", help="학습 대신 격자 탐색 (ch12_nas.pt 가 있어야 한다)")
    parser.add_argument("--finetune", action="store_true", help="학습 대신 NAS 뒤 미세 조정 점검")
    parser.add_argument("--replot", action="store_true", help="ch12_search.json 으로 표와 그림만 다시 만든다")
    parser.add_argument("--checks", action="store_true", help="학습 없이 파레토 · PI-resize 점검과 그 그림만")
    parser.add_argument("--epochs", type=int, default=0, help="NAS 학습 에폭 수 (기본 60)")
    parser.add_argument("--tag", default="", help="체크포인트 이름에 붙일 꼬리표 (ch12_nas_<tag>.pt)")
    parser.add_argument("--workers", type=int, default=-1, help="AP 채점에 쓸 프로세스 수 (기본: 코어 수의 절반, 최대 8)")
    parser.add_argument("--fig-dir", default="figures")
    parser.add_argument("--seed", type=int, default=0)
    args = parser.parse_args()
    sys.stdout.reconfigure(line_buffering=True)  # 파일로 돌려도 줄마다 바로 적히게
    import matplotlib
    matplotlib.use("Agg")
    os.makedirs(args.fig_dir, exist_ok=True)
    device = get_device()
    if device == "cpu":
        torch.set_num_threads(4)
    if args.workers < 0:
        args.workers = 0 if args.quick else min(8, (os.cpu_count() or 2) // 2)
    print(f"장치: {device}")
    train_space, search_space = quick_spaces() if args.quick else (TRAIN_SPACE, SEARCH_SPACE)
    start = time.time()
    if args.replot:
        with open("ch12_search_quick.json" if args.quick else "ch12_search.json") as f:
            report(json.load(f), args.fig_dir)
        return
    train_set = ShapesDataset(256 if args.quick else 4000, seed=0)
    val_set = ShapesDataset((32 if args.search else 64) if args.quick else 500, seed=1)
    if args.checks:
        pareto_checks(args.fig_dir)
        pi_resize_checks(val_set, device, args.fig_dir, args.quick)
    elif args.search:
        search_mode(args, device, val_set, train_space, search_space)
    elif args.finetune:
        finetune_mode(args, device, train_set, val_set, train_space)
    else:
        if not args.tag:  # 꼬리표를 단 추가 실행에서는 점검을 되풀이하지 않는다
            pareto_checks(args.fig_dir)
            pi_resize_checks(val_set, device, args.fig_dir, args.quick)
        describe_space(train_space, search_space)
        train_mode(args, device, train_set, val_set, train_space)
    print(f"전체 {time.time() - start:.0f}초")
# --8<-- [end:main]


if __name__ == "__main__":
    main()
