"""7장 · DETR: 탐지를 집합 예측으로 — 도형 세상에서 미니 DETR 을 처음부터 만든다.

무엇을 하나
  1. 헝가리안 매칭: 작은 비용 행렬에서 모든 배정을 훑는 무차별 탐색과 scipy 의 풀이가 같은 답을 내는지 본다.
  2. 집합 손실(SetCriterion): 매칭된 질의는 정답 클래스, 나머지는 "객체 없음(∅)" 으로 하는 교차 엔트로피
     + 매칭된 쌍의 L1 · GIoU 손실, 그리고 디코더 층마다의 보조 손실.
  3. MiniDETR: 작은 CNN 백본 → 사인 위치 인코딩 → Transformer 인코더 3층 → 디코더 3층(객체 질의 12개)
     → 분류 머리 · 박스 머리.
  4. 학습하며 에폭마다 손실을, 정해 둔 에폭마다 검증 AP 를 기록한다 (수렴 속도를 8장과 견주기 위해 기록을 ch07_history.json 에 남긴다).
  5. 분석: 예측 그림, 질의의 전문화, 디코더 교차 어텐션 지도, 디코더 층별 AP, NMS 를 해도 AP 가 변하지 않음.
  6. 체크포인트 ch07_detr.pt 와 학습 기록 ch07_history.json 을 실행 폴더에 저장한다 (8장이 곡선을 겹쳐 그린다).

실행
  python ch07_detr.py            # 본문 결과 (노트북 GPU 약 15분 — 다른 작업과 GPU 를 나눠 쓰며 잰 값)
  python ch07_detr.py --quick    # 연기 시험 (CPU 약 15초)
그림은 --fig-dir (기본 figures/) 에 저장된다.

8장부터의 실습 파일이 이 파일의 HungarianMatcher · SetCriterion · MLP · sine_embed · sine_position_2d ·
SmallBackbone · TransformerEncoderLayer · postprocess · train_one_epoch · collect_outputs · evaluate · fit 을 가져다 쓴다.
"""

from __future__ import annotations

import argparse
import itertools
import json
import os
import time

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.optimize import linear_sum_assignment

from ch02_boxes import box_cxcywh_to_xyxy, box_iou, generalized_box_iou, paired_generalized_box_iou
from ch03_metrics import evaluate_ap, nms
from rf_shapes import CLASS_NAMES, NUM_CLASSES, ShapesDataset, draw_boxes, make_loader


def get_device() -> str:
    if torch.cuda.is_available():
        return "cuda"
    if getattr(torch.backends, "mps", None) is not None and torch.backends.mps.is_available():
        return "mps"
    return "cpu"


# ── 1. 헝가리안 매칭 ─────────────────────────────────────────────────────────


# --8<-- [start:brute-force]
def brute_force_assignment(cost: np.ndarray):
    """비용 행렬에서 총비용이 가장 작은 일대일 배정을 "전부 해 보고" 찾는다.

    cost: (N, T) — cost[i, j] 는 예측 i 를 정답 j 에 배정하는 비용. N ≥ T (예측이 정답보다 많다).
    정답 0, 1, …, T−1 에 서로 다른 예측을 하나씩 고르는 방법은 N·(N−1)·…·(N−T+1) 가지다.
    돌려주는 값: (정답 j 가 짝지어진 예측 번호의 튜플, 그 총비용, 훑어본 배정의 수).
    N = 100, T = 20 이면 약 10^39 가지라 이 방법은 쓸 수 없다 → 헝가리안 알고리즘이 필요한 이유.
    """
    num_preds, num_targets = cost.shape
    best_rows, best_cost, tried = None, float("inf"), 0
    for rows in itertools.permutations(range(num_preds), num_targets):  # rows[j] = 정답 j 의 짝
        total = sum(cost[rows[j], j] for j in range(num_targets))
        tried += 1
        if total < best_cost:
            best_rows, best_cost = rows, total
    return best_rows, float(best_cost), tried


def greedy_assignment(cost: np.ndarray):
    """비교용 탐욕 배정: 정답 0 부터 차례로, 아직 안 쓰인 예측 가운데 비용이 가장 작은 것을 고른다.

    빠르지만 총비용이 최소라는 보장이 없다 (앞의 정답이 뒤의 정답에게 더 필요한 예측을 가져갈 수 있다).
    """
    used, rows = set(), []
    for j in range(cost.shape[1]):
        order = [i for i in np.argsort(cost[:, j]) if i not in used]
        rows.append(int(order[0]))
        used.add(int(order[0]))
    return tuple(rows), float(sum(cost[rows[j], j] for j in range(cost.shape[1])))
# --8<-- [end:brute-force]


# --8<-- [start:matcher]
class HungarianMatcher(nn.Module):
    """예측 N 개와 정답 T 개 사이의 비용 행렬을 만들고, 총비용이 최소인 일대일 배정을 구한다.

    비용 = cost_class · C_cls + cost_bbox · C_L1 + cost_giou · C_GIoU
      C_L1[i, j]   = ‖b̂_i − b_j‖₁                     (cxcywh 네 숫자의 차의 절댓값 합)
      C_GIoU[i, j] = −GIoU(b̂_i, b_j)
      C_cls[i, j]  = class_cost 에 따라
        "prob"  (DETR)            : −p̂_i(c_j)   — 소프트맥스 확률. 로짓의 마지막 칸은 ∅ 클래스.
        "focal" (Deformable DETR~): α(1−p)^γ(−log p) − (1−α)p^γ(−log(1−p)),  p = σ(로짓_i[c_j])
                                    — 클래스별 시그모이드. ∅ 칸이 없다 (8장부터 쓴다).
    DETR 의 계수는 (1, 5, 2), Deformable DETR · RF-DETR 은 (2, 5, 2) 이다.
    매칭은 "누가 누구의 짝인가" 만 정하는 이산 연산이라 기울기가 필요 없다 → no_grad.
    """

    def __init__(self, cost_class: float = 1.0, cost_bbox: float = 5.0, cost_giou: float = 2.0,
                 class_cost: str = "prob", focal_alpha: float = 0.25, focal_gamma: float = 2.0):
        super().__init__()
        assert class_cost in ("prob", "focal")
        self.cost_class, self.cost_bbox, self.cost_giou = cost_class, cost_bbox, cost_giou
        self.class_cost, self.focal_alpha, self.focal_gamma = class_cost, focal_alpha, focal_gamma

    @torch.no_grad()
    def cost_parts(self, logits, boxes, tgt_labels, tgt_boxes):
        """세 비용 행렬을 따로 돌려준다. logits (Q, K 또는 K+1), boxes (Q, 4), tgt_labels (T,), tgt_boxes (T, 4).

        돌려주는 값: C_cls, C_L1, C_GIoU — 모두 (Q, T). 박스는 정규화 (cx, cy, w, h).
        """
        if self.class_cost == "prob":
            prob = logits.softmax(-1)  # (Q, K+1)
            c_cls = -prob[:, tgt_labels]  # (Q, T): 열 j 는 정답 j 의 클래스에 준 확률 (부호 −)
        else:
            prob = logits.sigmoid()[:, tgt_labels]  # (Q, T)
            alpha, gamma = self.focal_alpha, self.focal_gamma
            positive = alpha * (1 - prob) ** gamma * (-(prob + 1e-8).log())  # 이 칸을 양성으로 볼 때의 포컬 손실
            negative = (1 - alpha) * prob**gamma * (-(1 - prob + 1e-8).log())  # 음성으로 볼 때의 포컬 손실
            c_cls = positive - negative
        c_l1 = torch.cdist(boxes, tgt_boxes, p=1)  # (Q, T)
        c_giou = -generalized_box_iou(box_cxcywh_to_xyxy(boxes), box_cxcywh_to_xyxy(tgt_boxes))
        return c_cls, c_l1, c_giou

    @torch.no_grad()
    def cost_matrix(self, logits, boxes, tgt_labels, tgt_boxes):
        c_cls, c_l1, c_giou = self.cost_parts(logits, boxes, tgt_labels, tgt_boxes)
        return self.cost_class * c_cls + self.cost_bbox * c_l1 + self.cost_giou * c_giou

    @torch.no_grad()
    def forward(self, outputs, targets):
        """outputs: {"pred_logits": (B, N, K 또는 K+1), "pred_boxes": (B, N, 4)}, targets: 길이 B 의 목록.

        돌려주는 값: 길이 B 의 목록. b 번째는 (pred_idx, tgt_idx) — 둘 다 길이 T_b 의 LongTensor 이고,
        "그림 b 의 예측 pred_idx[k] 의 짝은 정답 tgt_idx[k]" 라는 뜻이다. 짝이 없는 예측은 목록에 없다.
        """
        batch, num_queries = outputs["pred_logits"].shape[:2]
        sizes = [len(t["labels"]) for t in targets]
        # 배치의 모든 예측 (B·N) × 배치의 모든 정답 (ΣT) 을 한 번에 계산한 뒤, 그림별로 자기 정답 열만 잘라 쓴다
        cost = self.cost_matrix(
            outputs["pred_logits"].flatten(0, 1), outputs["pred_boxes"].flatten(0, 1),
            torch.cat([t["labels"] for t in targets]), torch.cat([t["boxes"] for t in targets]),
        ).view(batch, num_queries, -1).cpu()
        indices = []
        for b, block in enumerate(cost.split(sizes, dim=-1)):  # block: (B, N, T_b)
            rows, cols = linear_sum_assignment(block[b].numpy())  # 헝가리안 풀이 (scipy)
            indices.append((torch.as_tensor(rows, dtype=torch.long), torch.as_tensor(cols, dtype=torch.long)))
        return indices
# --8<-- [end:matcher]


# ── 2. 집합 손실 ─────────────────────────────────────────────────────────────


# --8<-- [start:criterion]
class SetCriterion(nn.Module):
    """DETR 의 집합 손실(헝가리안 손실).

    1) 매칭으로 (예측, 정답) 짝을 정한다.
    2) 분류: 모든 질의에 대해 교차 엔트로피. 짝이 있는 질의의 목표는 정답 클래스, 없는 질의의 목표는 ∅(번호 K).
       ∅ 가 목표인 항에는 가중치 eos_coef = 0.1 을 곱한다 (질의 대부분이 ∅ 라서 그대로 두면 ∅ 만 배운다).
    3) 박스: 짝이 있는 질의만. L1 과 (1 − GIoU) 를 더해 배치의 객체 수로 나눈다.
    4) 디코더의 중간 층 출력(outputs["aux_outputs"])과, 있으면 인코더 제안(outputs["enc_outputs"], 8장)에도
       매칭부터 다시 해서 같은 손실을 건다 → 보조 손실.

    전체 = Σ_층 (w_cls · loss_ce + w_bbox · loss_bbox + w_giou · loss_giou).  DETR 의 계수는 (1, 5, 2).
    뒤 장은 loss_labels 만 갈아 끼워 포컬 손실(8장) · IA-BCE(9장)로 바꾼다.
    """

    def __init__(self, num_classes: int, matcher: HungarianMatcher, eos_coef: float = 0.1,
                 loss_ce: float = 1.0, loss_bbox: float = 5.0, loss_giou: float = 2.0):
        super().__init__()
        self.num_classes, self.matcher = num_classes, matcher
        self.weights = {"loss_ce": loss_ce, "loss_bbox": loss_bbox, "loss_giou": loss_giou}
        class_weight = torch.ones(num_classes + 1)
        class_weight[-1] = eos_coef  # 마지막 칸(∅)의 가중치
        self.register_buffer("class_weight", class_weight)

    def match(self, outputs, targets):
        """매칭을 하고, 손실 계산에 쓰기 좋은 번호 세 줄로 편다 (모두 길이 ΣT 의 LongTensor).

        batch_idx[k], query_idx[k] : k 번째 짝의 예측은 pred[batch_idx[k], query_idx[k]]
        tgt_idx[k]                 : 그 짝의 정답은 "배치의 정답을 한 줄로 이어 붙인 것" 의 tgt_idx[k] 번째
        """
        indices = self.matcher(outputs, targets)
        offsets = np.cumsum([0] + [len(t["labels"]) for t in targets])
        batch_idx = torch.cat([torch.full_like(rows, b) for b, (rows, _) in enumerate(indices)])
        query_idx = torch.cat([rows for rows, _ in indices])
        tgt_idx = torch.cat([cols + int(offsets[b]) for b, (_, cols) in enumerate(indices)])
        device = outputs["pred_boxes"].device
        return batch_idx.to(device), query_idx.to(device), tgt_idx.to(device)

    def loss_labels(self, outputs, tgt_labels, matched, num_boxes):
        """분류 손실. pred_logits (B, N, K+1). 목표 (B, N): 기본값 ∅(= K), 짝이 있는 자리만 정답 클래스.

        tgt_labels: (ΣT,) 배치의 정답 클래스를 이어 붙인 것. matched: match() 가 돌려준 번호 세 줄.
        """
        logits = outputs["pred_logits"]
        batch_idx, query_idx, tgt_idx = matched
        target_classes = torch.full(logits.shape[:2], self.num_classes, dtype=torch.long, device=logits.device)
        target_classes[batch_idx, query_idx] = tgt_labels[tgt_idx]
        # 가중 교차 엔트로피: Σ w(c_i)·(−log p̂_i(c_i)) / Σ w(c_i)   (PyTorch 의 weight 인자가 하는 일)
        return F.cross_entropy(logits.flatten(0, 1), target_classes.flatten(), weight=self.class_weight)

    def loss_boxes(self, outputs, tgt_boxes, matched, num_boxes):
        """박스 손실 두 가지 (짝이 있는 예측만). 둘 다 배치의 객체 수 num_boxes 로 나눈다. tgt_boxes: (ΣT, 4)."""
        batch_idx, query_idx, tgt_idx = matched
        pred = outputs["pred_boxes"][batch_idx, query_idx]  # (ΣT, 4)
        target = tgt_boxes[tgt_idx]  # (ΣT, 4)
        loss_bbox = F.l1_loss(pred, target, reduction="sum") / num_boxes
        giou = paired_generalized_box_iou(box_cxcywh_to_xyxy(pred), box_cxcywh_to_xyxy(target))
        loss_giou = (1 - giou).sum() / num_boxes
        return loss_bbox, loss_giou

    def layer_loss(self, outputs, targets, tgt_labels, tgt_boxes, num_boxes):
        """출력 한 벌(디코더 층 하나)에 대한 매칭 + 세 손실."""
        matched = self.match(outputs, targets)
        loss_bbox, loss_giou = self.loss_boxes(outputs, tgt_boxes, matched, num_boxes)
        return {"loss_ce": self.loss_labels(outputs, tgt_labels, matched, num_boxes),
                "loss_bbox": loss_bbox, "loss_giou": loss_giou}

    def forward(self, outputs, targets):
        """outputs: 모델 출력 사전, targets: 길이 B 의 목록 ({"labels": (T_b,), "boxes": (T_b, 4)}).

        돌려주는 값: 사전. "loss" 가 역전파할 전체 손실(가중합)이고, 나머지는 기록용 낱개 손실이다.
        "loss_ce" · "loss_bbox" · "loss_giou" 는 마지막 디코더 층, "loss_ce_0" … 은 보조(중간) 층,
        "loss_ce_enc" … 은 인코더 제안의 값이다 (모두 가중치를 곱하기 전).
        """
        num_boxes = max(sum(len(t["labels"]) for t in targets), 1)
        tgt_labels = torch.cat([t["labels"] for t in targets])  # (ΣT,)
        tgt_boxes = torch.cat([t["boxes"] for t in targets])  # (ΣT, 4)
        losses = self.layer_loss(outputs, targets, tgt_labels, tgt_boxes, num_boxes)
        for i, aux in enumerate(outputs.get("aux_outputs", [])):  # 보조 손실: 층마다 매칭부터 다시
            aux_losses = self.layer_loss(aux, targets, tgt_labels, tgt_boxes, num_boxes)
            losses.update({f"{k}_{i}": v for k, v in aux_losses.items()})
        if "enc_outputs" in outputs:
            enc_losses = self.layer_loss(outputs["enc_outputs"], targets, tgt_labels, tgt_boxes, num_boxes)
            losses.update({f"{k}_enc": v for k, v in enc_losses.items()})
        losses["loss"] = sum(self.weights["_".join(k.split("_")[:2])] * v for k, v in losses.items())
        return losses
# --8<-- [end:criterion]


# ── 3. 모델 부품 ─────────────────────────────────────────────────────────────


# --8<-- [start:mlp]
class MLP(nn.Module):
    """Linear → ReLU 를 되풀이하고 마지막은 Linear 로 끝나는 작은 다층 퍼셉트론 (박스 머리 등에 쓴다)."""

    def __init__(self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int):
        super().__init__()
        dims = [input_dim] + [hidden_dim] * (num_layers - 1) + [output_dim]
        self.layers = nn.ModuleList(nn.Linear(a, b) for a, b in zip(dims[:-1], dims[1:]))

    def forward(self, x):
        for i, layer in enumerate(self.layers):
            x = layer(x)
            if i < len(self.layers) - 1:
                x = F.relu(x)
        return x
# --8<-- [end:mlp]


# --8<-- [start:position]
def sine_embed(coords: torch.Tensor, dim: int, temperature: float = 10000.0) -> torch.Tensor:
    """0 – 1 로 정규화한 좌표를 사인 · 코사인 벡터로 바꾼다. coords (..., k) → (..., k · dim).

    좌표 하나 u 마다 dim 칸: 주파수 번호 i = 0 … dim/2 − 1 에 대해
      [sin(2π·u / T^(2i/dim)), cos(2π·u / T^(2i/dim))]   (T = temperature)
    5장의 1차원 위치 인코딩과 같은 식이고, 위치 대신 2π·u 를 넣은 것이다.
    """
    index = torch.arange(dim, dtype=torch.float32, device=coords.device)
    freq = temperature ** (2 * torch.div(index, 2, rounding_mode="floor") / dim)  # (dim,): 같은 값이 두 번씩
    angle = coords[..., None] * (2 * torch.pi) / freq  # (..., k, dim)
    embed = torch.stack((angle[..., 0::2].sin(), angle[..., 1::2].cos()), dim=-1).flatten(-2)  # sin, cos 교대로
    return embed.flatten(-2)  # (..., k · dim)


def sine_position_2d(height: int, width: int, dim: int, device=None) -> torch.Tensor:
    """H × W 특징 맵의 2차원 사인 위치 인코딩 (H·W, dim). 앞 절반은 x 좌표, 뒤 절반은 y 좌표의 인코딩.

    칸 (행 r, 열 c) 의 좌표는 칸의 중심 ((c + 0.5) / W, (r + 0.5) / H) 이다. 토큰 순서는 행 우선(r·W + c).
    """
    ys = (torch.arange(height, dtype=torch.float32, device=device) + 0.5) / height
    xs = (torch.arange(width, dtype=torch.float32, device=device) + 0.5) / width
    grid_y, grid_x = torch.meshgrid(ys, xs, indexing="ij")  # (H, W)
    coords = torch.stack([grid_x, grid_y], dim=-1).reshape(-1, 2)  # (H·W, 2): (x, y)
    return sine_embed(coords, dim // 2)  # (H·W, dim)
# --8<-- [end:position]


# --8<-- [start:backbone]
class SmallBackbone(nn.Module):
    """작은 CNN 백본. 그림 (B, 3, 96, 96) → 특징 맵 (B, 4·width, 12, 12)  (스트라이드 8).

    3×3 합성곱 6층. 스트라이드 2 인 층 셋이 해상도를 96 → 48 → 24 → 12 로 줄인다.
    마지막 칸 하나가 보는 입력 범위(수용 영역)는 43 픽셀로, 가장 큰 도형(약 40 픽셀)을 덮는다.
    DETR 의 ResNet-50(스트라이드 32)을 이 작은 그림에 맞게 줄인 것이다.
    """

    def __init__(self, width: int = 32):
        super().__init__()

        def block(cin, cout, stride):
            return nn.Sequential(nn.Conv2d(cin, cout, 3, stride, 1, bias=False), nn.BatchNorm2d(cout), nn.ReLU())

        self.net = nn.Sequential(
            block(3, width, 2), block(width, width, 1),  # 96 → 48
            block(width, 2 * width, 2), block(2 * width, 2 * width, 1),  # 48 → 24
            block(2 * width, 4 * width, 2), block(4 * width, 4 * width, 1),  # 24 → 12
        )
        self.out_channels = 4 * width
        self.stride = 8

    def forward(self, images: torch.Tensor) -> torch.Tensor:
        return self.net((images - 0.5) / 0.25)  # 0 – 1 의 그림을 대략 −2 – 2 로 맞춰 넣는다
# --8<-- [end:backbone]


# --8<-- [start:encoder-layer]
class TransformerEncoderLayer(nn.Module):
    """인코더 한 층: 자기 어텐션 → 더하고 층 정규화 → FFN → 더하고 층 정규화 (post-norm, DETR 과 같다).

    위치 인코딩 pos 는 층마다 질의 · 열쇠에만 더한다 (값에는 더하지 않는다) — DETR 의 방식.
    """

    def __init__(self, dim: int, heads: int, ffn_dim: int, dropout: float = 0.0):
        super().__init__()
        self.self_attn = nn.MultiheadAttention(dim, heads, dropout=dropout, batch_first=True)
        self.norm1 = nn.LayerNorm(dim)
        self.ffn = nn.Sequential(nn.Linear(dim, ffn_dim), nn.ReLU(), nn.Dropout(dropout), nn.Linear(ffn_dim, dim))
        self.norm2 = nn.LayerNorm(dim)
        self.dropout = nn.Dropout(dropout)

    def forward(self, src: torch.Tensor, pos: torch.Tensor) -> torch.Tensor:
        """src (B, HW, D), pos (HW, D) 또는 (B, HW, D) → (B, HW, D)."""
        q = src + pos
        attended, _ = self.self_attn(q, q, src, need_weights=False)  # 질의 = 열쇠 = src + pos, 값 = src
        src = self.norm1(src + self.dropout(attended))
        return self.norm2(src + self.dropout(self.ffn(src)))
# --8<-- [end:encoder-layer]


# --8<-- [start:decoder-layer]
class TransformerDecoderLayer(nn.Module):
    """DETR 디코더 한 층: 질의끼리 자기 어텐션 → 그림 특징에 교차 어텐션 → FFN (각각 뒤에 더하고 층 정규화).

    tgt        (B, N, D)  : 질의의 "내용" — 첫 층에는 0 이 들어온다
    query_pos  (N, D)     : 질의 위치 임베딩(학습됨) = 객체 질의. 층마다 질의 · 열쇠에 더한다
    memory     (B, HW, D) : 인코더 출력
    pos        (HW, D)    : 특징 맵의 사인 위치 인코딩 (교차 어텐션의 열쇠에 더한다)
    """

    def __init__(self, dim: int, heads: int, ffn_dim: int, dropout: float = 0.0):
        super().__init__()
        self.self_attn = nn.MultiheadAttention(dim, heads, dropout=dropout, batch_first=True)
        self.norm1 = nn.LayerNorm(dim)
        self.cross_attn = nn.MultiheadAttention(dim, heads, dropout=dropout, batch_first=True)
        self.norm2 = nn.LayerNorm(dim)
        self.ffn = nn.Sequential(nn.Linear(dim, ffn_dim), nn.ReLU(), nn.Dropout(dropout), nn.Linear(ffn_dim, dim))
        self.norm3 = nn.LayerNorm(dim)
        self.dropout = nn.Dropout(dropout)

    def forward(self, tgt, query_pos, memory, pos):
        """돌려주는 값: 새 tgt (B, N, D), 교차 어텐션 가중치 (B, N, HW) — 머리 평균, 행마다 합이 1."""
        # ① 자기 어텐션: 질의끼리 서로를 본다 → "그 객체는 내가 맡았으니 너는 다른 것을" 을 주고받는 통로
        q = tgt + query_pos
        attended, _ = self.self_attn(q, q, tgt, need_weights=False)
        tgt = self.norm1(tgt + self.dropout(attended))
        # ② 교차 어텐션: 질의가 그림의 HW 개 토큰 전부를 본다
        attended, weights = self.cross_attn(tgt + query_pos, memory + pos, memory, need_weights=True)
        tgt = self.norm2(tgt + self.dropout(attended))
        # ③ FFN
        tgt = self.norm3(tgt + self.dropout(self.ffn(tgt)))
        return tgt, weights
# --8<-- [end:decoder-layer]


# --8<-- [start:model]
class MiniDETR(nn.Module):
    """미니 DETR. 그림 (B, 3, 96, 96) → 질의 N 개마다 (클래스 로짓 K+1 개, 박스 4개).

    백본(12×12 특징 맵) → 1×1 합성곱으로 D 채널 → 토큰 144개 + 사인 위치 인코딩
    → 인코더 → 디코더(객체 질의 N 개) → 분류 머리(Linear) · 박스 머리(3층 MLP → 시그모이드).
    두 머리와 마지막 층 정규화는 모든 디코더 층이 함께 쓴다 (보조 손실용 중간 출력도 같은 머리로 읽는다).
    """

    def __init__(self, num_classes: int = NUM_CLASSES, num_queries: int = 12, dim: int = 128, heads: int = 8,
                 enc_layers: int = 3, dec_layers: int = 3, ffn_dim: int = 256, dropout: float = 0.0,
                 backbone_width: int = 32):
        super().__init__()
        self.num_classes, self.num_queries, self.dim = num_classes, num_queries, dim
        self.backbone = SmallBackbone(backbone_width)
        self.input_proj = nn.Conv2d(self.backbone.out_channels, dim, kernel_size=1)
        self.encoder = nn.ModuleList(TransformerEncoderLayer(dim, heads, ffn_dim, dropout) for _ in range(enc_layers))
        self.decoder = nn.ModuleList(TransformerDecoderLayer(dim, heads, ffn_dim, dropout) for _ in range(dec_layers))
        self.decoder_norm = nn.LayerNorm(dim)
        self.query_embed = nn.Embedding(num_queries, dim)  # 객체 질의 = 학습되는 질의 위치 임베딩 (N, D)
        self.class_embed = nn.Linear(dim, num_classes + 1)  # 분류 머리: 클래스 K 개 + ∅
        self.bbox_embed = MLP(dim, dim, 4, num_layers=3)  # 박스 머리: (cx, cy, w, h) 의 로짓
        for module in (self.encoder, self.decoder):  # DETR 처럼 Transformer 의 행렬은 Xavier 균등 초기화
            for p in module.parameters():
                if p.dim() > 1:
                    nn.init.xavier_uniform_(p)

    def forward(self, images: torch.Tensor, return_attn: bool = False):
        """돌려주는 값: {"pred_logits": (B, N, K+1), "pred_boxes": (B, N, 4) — 정규화 cxcywh,
                       "aux_outputs": [중간 디코더 층마다 같은 두 키의 사전, …]}
        return_attn=True 면 "cross_attn": [층마다 (B, N, HW)] 도 넣는다.
        """
        feature = self.input_proj(self.backbone(images))  # (B, D, H, W)
        batch, _, height, width = feature.shape
        memory = feature.flatten(2).transpose(1, 2)  # (B, HW, D): 행 우선으로 편 토큰
        pos = sine_position_2d(height, width, self.dim, device=images.device)  # (HW, D)
        for layer in self.encoder:
            memory = layer(memory, pos)

        query_pos = self.query_embed.weight  # (N, D)
        tgt = torch.zeros(batch, self.num_queries, self.dim, device=images.device)  # 디코더 입력은 0 에서 출발
        layer_outputs, attn_maps = [], []
        for layer in self.decoder:
            tgt, weights = layer(tgt, query_pos, memory, pos)
            hidden = self.decoder_norm(tgt)  # (B, N, D)
            layer_outputs.append({"pred_logits": self.class_embed(hidden),
                                  "pred_boxes": self.bbox_embed(hidden).sigmoid()})
            attn_maps.append(weights)
        outputs = dict(layer_outputs[-1])
        outputs["aux_outputs"] = layer_outputs[:-1]
        if return_attn:
            outputs["cross_attn"] = attn_maps
        return outputs
# --8<-- [end:model]


# --8<-- [start:postprocess]
@torch.no_grad()
def postprocess(outputs):
    """DETR 방식 후처리: 모델 출력 → evaluate_ap 가 받는 예측 목록. NMS 가 없다.

    질의마다 소프트맥스 확률에서 ∅ 칸을 뺀 K 칸 가운데 최댓값이 점수, 그 자리가 클래스다.
    질의 N 개가 모두 예측으로 나간다 (∅ 라고 본 질의는 점수가 낮아 순위에서 저절로 밀린다).
    outputs: {"pred_logits": (B, N, K+1), "pred_boxes": (B, N, 4)}
    돌려주는 값: 길이 B 의 목록, 각각 {"boxes": (N, 4), "scores": (N,), "labels": (N,)}.
    """
    prob = outputs["pred_logits"].softmax(-1)
    scores, labels = prob[..., :-1].max(-1)
    return [{"boxes": b, "scores": s, "labels": c} for b, s, c in zip(outputs["pred_boxes"], scores, labels)]
# --8<-- [end:postprocess]


# ── 4. 학습 · 평가 고리 (8장부터도 그대로 쓴다) ──────────────────────────────


# --8<-- [start:train-loop]
def targets_to(targets, device):
    """정답 목록을 장치로 옮긴다. 작은 텐서를 하나씩 옮기면 느리므로, 이어 붙여 한 번에 옮긴 뒤 다시 나눈다."""
    sizes = [len(t["labels"]) for t in targets]
    boxes = torch.cat([t["boxes"] for t in targets]).to(device).split(sizes)
    labels = torch.cat([t["labels"] for t in targets]).to(device).split(sizes)
    return [{"boxes": b, "labels": c} for b, c in zip(boxes, labels)]


def train_one_epoch(model, criterion, loader, optimizer, device, max_norm: float = 0.1):
    """한 에폭 학습. 돌려주는 값: 손실 이름 → 에폭 평균 (criterion 이 돌려준 모든 키)."""
    model.train()
    sums, steps = {}, 0
    for images, targets in loader:
        losses = criterion(model(images.to(device)), targets_to(targets, device))
        optimizer.zero_grad(set_to_none=True)
        losses["loss"].backward()
        nn.utils.clip_grad_norm_(model.parameters(), max_norm)  # 기울기 자르기 (DETR: 최대 노름 0.1)
        optimizer.step()
        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 is_eval_epoch(epoch: int, total: int) -> bool:
    """검증 AP 를 재는 에폭: 처음 10 에폭은 매번, 그 뒤로는 5 에폭마다, 그리고 마지막 에폭 (채점이 느려서)."""
    return epoch <= 10 or epoch % 5 == 0 or epoch == total


def split_layers(outputs):
    """모델 출력을 디코더 층 순서의 목록으로 편다: [첫 층, …, 마지막 층], 각각 pred_logits · pred_boxes."""
    last = {"pred_logits": outputs["pred_logits"], "pred_boxes": outputs["pred_boxes"]}
    return list(outputs.get("aux_outputs", [])) + [last]


@torch.no_grad()
def collect_outputs(model, dataset, device, batch_size: int = 250):
    """데이터셋 전체를 순전파해 디코더 층별 출력을 CPU 에 모은다.

    돌려주는 값: 길이 L(디코더 층 수)의 목록, 각각 {"pred_logits": (n, N, ·), "pred_boxes": (n, N, 4)}.
    """
    model.eval()
    chunks = []
    for start in range(0, len(dataset), batch_size):
        images = dataset.images[start:start + batch_size].to(device).float() / 255.0
        chunks.append([{k: v.cpu() for k, v in layer.items()} for layer in split_layers(model(images))])
    return [{k: torch.cat([chunk[i][k] for chunk in chunks]) for k in ("pred_logits", "pred_boxes")}
            for i in range(len(chunks[0]))]


def evaluate(model, dataset, device, postprocess_fn=postprocess):
    """마지막 디코더 층의 예측으로 AP 를 잰다. 돌려주는 값: (evaluate_ap 의 결과 사전, 예측 목록)."""
    predictions = postprocess_fn(collect_outputs(model, dataset, device)[-1])
    return evaluate_ap(predictions, dataset.targets, NUM_CLASSES), predictions


def fit(model, criterion, optimizer, scheduler, loader, val_set, epochs, device, postprocess_fn=postprocess,
        max_norm: float = 0.1):
    """epochs 에폭 학습하며 기록을 남긴다. 돌려주는 값: 기록 사전.

    "epoch" · "loss" · "loss_ce" · "loss_bbox" · "loss_giou" · "time"(누적 초) 은 에폭마다,
    "ap_epoch" · "AP" · "AP50" · "AP75" 는 채점한 에폭(is_eval_epoch)마다 한 칸씩 늘어난다.
    """
    history = {k: [] for k in ("epoch", "loss", "loss_ce", "loss_bbox", "loss_giou", "time",
                               "ap_epoch", "AP", "AP50", "AP75")}
    start = time.time()
    for epoch in range(1, epochs + 1):
        losses = train_one_epoch(model, criterion, loader, optimizer, device, max_norm)
        scheduler.step()
        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_eval_epoch(epoch, epochs):
            result, _ = evaluate(model, val_set, device, postprocess_fn)
            history["ap_epoch"].append(epoch)
            for k in ("AP", "AP50", "AP75"):
                history[k].append(result[k])
            print(f"에폭 {epoch:3d} | 손실 {losses['loss']:7.4f} (ce {losses['loss_ce']:.4f} "
                  f"bbox {losses['loss_bbox']:.4f} giou {losses['loss_giou']:.4f}) | "
                  f"검증 AP {result['AP']:.4f} AP50 {result['AP50']:.4f} AP75 {result['AP75']:.4f} | "
                  f"{time.time() - start:5.0f}초", flush=True)
    print(f"학습 끝: {time.time() - start:.0f}초")
    return history
# --8<-- [end:train-loop]


# --8<-- [start:duplicates]
def apply_nms(predictions, iou_threshold: float = 0.5):
    """예측 목록에 클래스별 NMS 를 건다 (3장의 nms). DETR 에는 필요 없음을 확인하는 용도."""
    kept = []
    for pred in predictions:
        keep = []
        for cls in pred["labels"].unique():
            index = torch.nonzero(pred["labels"] == cls).flatten()
            chosen = nms(box_cxcywh_to_xyxy(pred["boxes"][index]), pred["scores"][index], iou_threshold)
            keep.append(index[chosen])
        keep = torch.cat(keep) if keep else torch.zeros(0, dtype=torch.long)
        kept.append({k: v[keep] for k, v in pred.items()})
    return kept


def count_duplicates(predictions, score_threshold: float = 0.5, iou_threshold: float = 0.5):
    """점수가 문턱값 이상인 예측끼리 IoU 가 iou_threshold 를 넘게 겹치는 쌍의 수 (클래스 무관).

    도형 세상의 정답끼리는 IoU 가 0.2 를 넘지 않으므로, 이런 쌍은 "한 객체를 두 번 예측한 것" 이다.
    돌려주는 값: (겹치는 쌍의 수, 점수가 문턱값 이상인 예측의 수).
    """
    pairs, confident = 0, 0
    for pred in predictions:
        boxes = box_cxcywh_to_xyxy(pred["boxes"][pred["scores"] >= score_threshold])
        confident += len(boxes)
        if len(boxes) > 1:
            iou, _ = box_iou(boxes, boxes)
            pairs += int((torch.triu(iou, diagonal=1) > iou_threshold).sum())
    return pairs, confident
# --8<-- [end:duplicates]


# ── 5. 손계산 예와 check ─────────────────────────────────────────────────────


# --8<-- [start:toy]
def toy_example():
    """본문에서 손으로 따라가는 작은 예: 예측 4개 × 정답 3개."""
    names = CLASS_NAMES + ["no-object"]
    # 예측 4개의 클래스 확률 [원, 사각형, 삼각형, ∅] 과 박스 (cx, cy, w, h)
    probs = torch.tensor([[0.70, 0.10, 0.10, 0.10],
                          [0.60, 0.20, 0.10, 0.10],
                          [0.10, 0.20, 0.60, 0.10],
                          [0.05, 0.05, 0.10, 0.80]])
    boxes = torch.tensor([[0.33, 0.31, 0.24, 0.24],
                          [0.24, 0.26, 0.16, 0.16],
                          [0.66, 0.70, 0.30, 0.24],
                          [0.50, 0.50, 0.40, 0.40]])
    # 정답 3개: 원, 원, 삼각형
    tgt_labels = torch.tensor([0, 0, 2])
    tgt_boxes = torch.tensor([[0.30, 0.30, 0.20, 0.20],
                              [0.42, 0.34, 0.30, 0.30],
                              [0.70, 0.70, 0.30, 0.20]])
    logits = probs.log()  # 소프트맥스를 거치면 다시 probs 가 되는 로짓

    matcher = HungarianMatcher(cost_class=1.0, cost_bbox=5.0, cost_giou=2.0, class_cost="prob")
    c_cls, c_l1, c_giou = matcher.cost_parts(logits, boxes, tgt_labels, tgt_boxes)
    cost = matcher.cost_matrix(logits, boxes, tgt_labels, tgt_boxes).numpy()
    np.set_printoptions(precision=4, suppress=True)
    print("[손계산 예] 예측 4개 × 정답 3개 (정답: 원, 원, 삼각형)")
    print("C_cls = −p̂_i(c_j)\n", c_cls.numpy())
    print("C_L1 = ‖b̂_i − b_j‖₁\n", c_l1.numpy())
    print("C_GIoU = −GIoU\n", c_giou.numpy())
    print("C = 1·C_cls + 5·C_L1 + 2·C_GIoU\n", cost)

    rows_bf, cost_bf, tried = brute_force_assignment(cost)
    rows_sp, cols_sp = linear_sum_assignment(cost)
    rows_sp = tuple(int(rows_sp[np.argsort(cols_sp)][j]) for j in range(cost.shape[1]))
    rows_gr, cost_gr = greedy_assignment(cost)
    print(f"무차별 탐색: 배정 {tried}가지 가운데 최소 — 정답 0,1,2 의 짝 = 예측 {rows_bf}, 총비용 {cost_bf:.4f}")
    print(f"scipy linear_sum_assignment: 예측 {rows_sp}, 총비용 {cost[list(rows_sp), range(3)].sum():.4f}")
    print(f"탐욕 배정(정답 0 부터 가장 싼 예측): 예측 {rows_gr}, 총비용 {cost_gr:.4f}")
    print("check 무차별 탐색 = scipy:", rows_bf == rows_sp)

    # 무작위 비용 행렬 200개에서도 두 방법의 최소 비용이 같은지
    rng = np.random.default_rng(0)
    worst = 0.0
    for _ in range(200):
        num_targets = int(rng.integers(1, 5))
        random_cost = rng.normal(size=(6, num_targets))
        rows, cols = linear_sum_assignment(random_cost)
        worst = max(worst, abs(random_cost[rows, cols].sum() - brute_force_assignment(random_cost)[1]))
    print(f"check 무작위 6×T 비용 행렬 200개: 최소 비용의 최대 차이 = {worst:.2e}")

    # 이 매칭으로 손실을 계산한다 (배치 = 그림 1장)
    criterion = SetCriterion(NUM_CLASSES, matcher)
    outputs = {"pred_logits": logits[None], "pred_boxes": boxes[None]}
    targets = [{"labels": tgt_labels, "boxes": tgt_boxes}]
    losses = criterion(outputs, targets)
    print(f"손실: loss_ce {losses['loss_ce']:.4f}, loss_bbox {losses['loss_bbox']:.4f}, "
          f"loss_giou {losses['loss_giou']:.4f} → 전체 1·ce + 5·bbox + 2·giou = {losses['loss']:.4f}")
    # check: 분류 손실을 식 그대로 손으로 — 짝 있는 질의는 가중치 1, ∅ 질의는 0.1
    target_classes = torch.full((4,), NUM_CLASSES)
    target_classes[list(rows_bf)] = tgt_labels
    weight = torch.where(target_classes == NUM_CLASSES, 0.1, 1.0)
    nll = -probs[torch.arange(4), target_classes].log()
    manual = float((weight * nll).sum() / weight.sum())
    print("질의별 목표 클래스:", [names[c] for c in target_classes.tolist()],
          "−log p̂:", np.round(nll.numpy(), 4), "가중치:", weight.numpy())
    print(f"check 가중 교차 엔트로피 손계산 {manual:.6f} vs SetCriterion {float(losses['loss_ce']):.6f}")
# --8<-- [end:toy]


# ── 6. 그림 ──────────────────────────────────────────────────────────────────


def plot_curves(history, path, title="MiniDETR"):
    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="#0072B2", label="class (CE)")
    ax.plot(epochs, [5 * v for v in history["loss_bbox"]], "--", color="#D55E00", label="5 x L1")
    ax.plot(epochs, [2 * v for v in history["loss_giou"]], "-.", color="#009E73", label="2 x (1 - GIoU)")
    ax.set_xlabel("epoch")
    ax.set_ylabel("training loss (last decoder layer)")
    ax.set_yscale("log")
    ax.set_title(f"{title}: training loss", fontsize=10)
    ax.grid(alpha=0.3, which="both")
    ax.legend(fontsize=8)
    ax = axes[1]
    ax.plot(ap_epochs, history["AP50"], "--", color="#009E73", label="AP50")
    ax.plot(ap_epochs, history["AP"], "-", color="#0072B2", lw=2, label="AP (IoU .50:.95)")
    ax.plot(ap_epochs, history["AP75"], "-.", color="#D55E00", label="AP75")
    ax.set_xlabel("epoch")
    ax.set_ylabel("validation AP")
    ax.set_ylim(0, 1)
    ax.set_title(f"{title}: validation AP", fontsize=10)
    ax.grid(alpha=0.3)
    ax.legend(fontsize=8, loc="lower right")
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


def plot_predictions(dataset, predictions, path, indices, score_threshold=0.5, title=None):
    """정답(흰 점선)과 점수가 문턱값 이상인 예측(초록 실선)을 함께 그린다."""
    import matplotlib.pyplot as plt

    fig, axes = plt.subplots(2, len(indices) // 2, figsize=(len(indices) // 2 * 2.6, 5.6))
    for ax, i in zip(axes.flat, indices):
        image, target = dataset[i]
        pred = predictions[i]
        keep = pred["scores"] >= score_threshold
        draw_boxes(ax, image, target["boxes"], color="white", linestyle="--", linewidth=1.2)
        draw_boxes(ax, image, pred["boxes"][keep], pred["labels"][keep], pred["scores"][keep])
        ax.set_title(f"val #{i}: {int(keep.sum())} pred / {len(target['labels'])} gt", fontsize=8)
    fig.suptitle(title or f"predictions with score >= {score_threshold} (green) and ground truth (white dashed)",
                 fontsize=10)
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


def plot_query_specialization(boxes, scores, path, score_threshold=0.5):
    """질의마다, 검증 그림 전체에서 그 질의가 낸 박스의 중심을 점으로 찍는다 (DETR 논문 그림 7 과 같은 종류).

    boxes (n, N, 4), scores (n, N). 점수가 문턱값 이상인 예측("객체가 있다")은 박스 크기 · 모양에 따라 색을 달리하고,
    문턱값 미만("객체 없음")인 예측은 옅은 회색으로 찍는다.
    """
    import matplotlib.pyplot as plt

    boxes, scores = boxes.numpy(), scores.numpy()
    num_queries = boxes.shape[1]
    cols = (num_queries + 1) // 2
    fig, axes = plt.subplots(2, cols, figsize=(cols * 1.9, 4.7))
    for q, ax in enumerate(axes.flat):
        if q >= num_queries:
            ax.axis("off")
            continue
        cx, cy, w, h = boxes[:, q].T
        used = scores[:, q] >= score_threshold
        small = used & (np.maximum(w, h) < 0.28)  # 긴 변이 그림의 0.28 배보다 작다
        wide = used & ~small & (w >= h)
        tall = used & ~small & (w < h)
        ax.scatter(cx[~used], cy[~used], s=2, c="#bbbbbb", marker=".", linewidths=0)
        for mask, color, marker in ((small, "#009E73", "o"), (wide, "#D55E00", "s"), (tall, "#0072B2", "^")):
            ax.scatter(cx[mask], cy[mask], s=5, c=color, marker=marker, alpha=0.7, linewidths=0)
        ax.set_xlim(0, 1)
        ax.set_ylim(1, 0)  # 그림 좌표처럼 y 가 아래로 커지게
        ax.set_aspect("equal")
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_title(f"query {q} (object in {100 * used.mean():.0f}%)", fontsize=8)
    handles = [plt.Line2D([], [], ls="", marker=m, color=c, label=label) for c, m, label in (
        ("#009E73", "o", "small box (long side < 0.28)"), ("#D55E00", "s", "large, wide (w >= h)"),
        ("#0072B2", "^", "large, tall (w < h)"), ("#bbbbbb", ".", f"score < {score_threshold} (no object)"))]
    fig.legend(handles=handles, loc="lower center", ncol=4, fontsize=8, frameon=False)
    fig.suptitle("box centers predicted by each object query over the validation set", fontsize=10)
    fig.tight_layout(rect=(0, 0.06, 1, 1), h_pad=1.5)
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


@torch.no_grad()
def plot_attention(model, dataset, index, path, device, score_threshold=0.5):
    """그림 한 장에서, 객체를 맡은 질의마다 마지막 디코더 층의 교차 어텐션 지도(12×12)를 그린다."""
    import matplotlib.pyplot as plt

    model.eval()
    image, target = dataset[index]
    outputs = model(image[None].to(device), return_attn=True)
    pred = postprocess(outputs)[0]
    attn = outputs["cross_attn"][-1][0].cpu()  # (N, HW)
    side = int(round(attn.shape[1] ** 0.5))
    chosen = torch.nonzero(pred["scores"].cpu() >= score_threshold).flatten().tolist()
    fig, axes = plt.subplots(1, len(chosen) + 1, figsize=((len(chosen) + 1) * 2.5, 2.9), squeeze=False)
    axes = axes[0]
    draw_boxes(axes[0], image, target["boxes"], target["labels"], color="white", linestyle="--", linewidth=1.2)
    axes[0].set_title(f"val #{index}: image and ground truth", fontsize=8)
    for ax, q in zip(axes[1:], chosen):
        heat = attn[q].reshape(side, side).numpy()
        im = ax.imshow(heat, cmap="magma", extent=(-0.5, image.shape[2] - 0.5, image.shape[1] - 0.5, -0.5),
                       interpolation="nearest", vmin=0)
        cx, cy, w, h = pred["boxes"][q].cpu().tolist()
        size = image.shape[1]
        ax.add_patch(plt.Rectangle(((cx - w / 2) * size - 0.5, (cy - h / 2) * size - 0.5), w * size, h * size,
                                   fill=False, edgecolor="#39ff14", linewidth=1.5))
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_title(f"query {q}: {CLASS_NAMES[int(pred['labels'][q])]} {float(pred['scores'][q]):.2f}\n"
                     f"max weight {heat.max():.2f}", fontsize=8)
        fig.colorbar(im, ax=ax, fraction=0.046, pad=0.03)
    fig.suptitle("cross-attention of the last decoder layer (mean over heads), with the query's predicted box",
                 fontsize=9)
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)
    return chosen, attn


def plot_layers(layer_rows, path, title="MiniDETR"):
    """디코더 층별 AP 를 NMS 를 걸기 전 · 후로 나란히 그린다."""
    import matplotlib.pyplot as plt

    layers = np.arange(1, len(layer_rows) + 1)
    fig, axes = plt.subplots(1, 2, figsize=(9, 3.4))
    for ax, key in zip(axes, ("AP", "AP50")):
        ax.plot(layers, [r[key] for r in layer_rows], "o-", color="#0072B2", label="no NMS")
        ax.plot(layers, [r[key + "_nms"] for r in layer_rows], "s--", color="#D55E00", label="with NMS (IoU 0.5)")
        ax.set_xticks(layers)
        ax.set_xlabel("decoder layer used for prediction")
        ax.set_ylabel(f"validation {key}")
        ax.grid(alpha=0.3)
        ax.legend(fontsize=8)
    fig.suptitle(f"{title}: AP after each decoder layer", fontsize=10)
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


def layer_report(layers, dataset, postprocess_fn=postprocess):
    """디코더 층마다: AP, NMS 를 건 뒤의 AP, 중복 쌍의 수를 계산해 표로 출력한다."""
    rows = []
    print("디코더 층 | AP     AP50   AP75  | NMS 뒤 AP  AP50  | 점수≥0.5 예측 수 | 그중 IoU>0.5 로 겹치는 쌍")
    for i, layer in enumerate(layers):
        predictions = postprocess_fn(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})
        print(f"    {i + 1}     | {plain['AP']:.4f} {plain['AP50']:.4f} {plain['AP75']:.4f} | "
              f"{with_nms['AP']:.4f}  {with_nms['AP50']:.4f} | {confident:8d}         | {pairs:6d}")
    return rows


# ── 7. 본 실행 ───────────────────────────────────────────────────────────────


# --8<-- [start:main]
def main():
    parser = argparse.ArgumentParser(description="7장: 미니 DETR")
    parser.add_argument("--quick", action="store_true", help="아주 작게 돌려 오류만 확인")
    parser.add_argument("--epochs", type=int, default=60)
    parser.add_argument("--train-size", type=int, default=4000)
    parser.add_argument("--val-size", type=int, default=500)
    parser.add_argument("--batch-size", type=int, default=32)
    parser.add_argument("--lr", type=float, default=2e-4)
    parser.add_argument("--num-queries", type=int, default=12)
    parser.add_argument("--seed", type=int, default=0)
    parser.add_argument("--fig-dir", default="figures")
    args = parser.parse_args()
    if args.quick:
        args.epochs, args.train_size, args.val_size = 2, 256, 64

    import matplotlib

    matplotlib.use("Agg")
    os.makedirs(args.fig_dir, exist_ok=True)
    torch.manual_seed(args.seed)
    np.random.seed(args.seed)
    device = get_device()
    if device == "cpu":
        torch.set_num_threads(min(4, os.cpu_count() or 1))  # 작은 텐서뿐이라 스레드가 많으면 오히려 느리다
    print(f"장치: {device}")

    # 1. 헝가리안 매칭과 손실의 손계산 예
    toy_example()

    # 2. 데이터 · 모델
    train_set = ShapesDataset(args.train_size, seed=0)
    val_set = ShapesDataset(args.val_size, seed=1)
    loader = make_loader(train_set, args.batch_size, shuffle=True, seed=args.seed)
    model = MiniDETR(num_queries=args.num_queries).to(device)
    matcher = HungarianMatcher(cost_class=1.0, cost_bbox=5.0, cost_giou=2.0, class_cost="prob")
    criterion = SetCriterion(NUM_CLASSES, matcher, eos_coef=0.1).to(device)
    optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=1e-4)
    # DETR 처럼 학습의 마지막 구간에서 학습률을 1/10 로 한 번 낮춘다
    drop_epoch = max(int(args.epochs * 0.8), 1)
    scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=drop_epoch, gamma=0.1)
    num_params = sum(p.numel() for p in model.parameters())
    print(f"\n학습 {len(train_set)}장 · 검증 {len(val_set)}장, 배치 {args.batch_size}, 에폭 {args.epochs} "
          f"(에폭당 {len(loader)} 스텝), 학습률 {args.lr} → 에폭 {drop_epoch} 뒤 {args.lr / 10:g}")
    print(f"MiniDETR 매개변수 {num_params:,}개, 객체 질의 {args.num_queries}개")
    start = time.time()

    # 3. 학습: 에폭마다 손실을, 정해 둔 에폭마다 검증 AP 를 기록한다
    history = fit(model, criterion, optimizer, scheduler, loader, val_set, args.epochs, device)
    for level in (0.5, 0.8, 0.9):
        reached = [e for e, ap in zip(history["ap_epoch"], history["AP"]) if ap >= level]
        print(f"검증 AP 가 처음 {level} 이상이 된 에폭(채점한 에폭 가운데): {reached[0] if reached else '도달하지 못함'}")

    torch.save({"model": model.state_dict(), "config": {"num_queries": args.num_queries}}, "ch07_detr.pt")
    with open("ch07_history.json", "w") as f:
        json.dump(history, f)
    print("ch07_detr.pt · ch07_history.json 저장")

    # 4. 분석
    plot_curves(history, os.path.join(args.fig_dir, "ch07-curves.png"))
    layers = collect_outputs(model, val_set, device)  # 디코더 층별 출력
    predictions = postprocess(layers[-1])
    final = evaluate_ap(predictions, val_set.targets, NUM_CLASSES)
    print(f"\n[최종] 검증 AP {final['AP']:.4f}, AP50 {final['AP50']:.4f}, AP75 {final['AP75']:.4f}, 클래스별 AP "
          + ", ".join(f"{n} {v:.4f}" for n, v in zip(CLASS_NAMES, final["per_class"])))

    # 4-1 디코더 층별 AP 와 중복 예측 (NMS 가 필요한가?)
    print("\n[디코더 층별 예측과 중복]")
    rows = layer_report(layers, val_set)
    plot_layers(rows, os.path.join(args.fig_dir, "ch07-layers.png"))
    num_gt = sum(len(t["labels"]) for t in val_set.targets)
    print(f"검증 정답 객체 수 {num_gt}개. 마지막 층: 점수≥0.5 예측 {rows[-1]['confident']}개, "
          f"겹치는 쌍 {rows[-1]['pairs']}개, NMS 전후 AP 차이 {rows[-1]['AP_nms'] - rows[-1]['AP']:+.4f}")

    # 4-2 예측 그림
    shown = list(range(8))
    plot_predictions(val_set, predictions, os.path.join(args.fig_dir, "ch07-predictions.png"), shown)

    # 4-3 질의의 전문화
    boxes = layers[-1]["pred_boxes"]  # (n, N, 4)
    scores = torch.stack([p["scores"] for p in predictions])  # (n, N)
    plot_query_specialization(boxes, scores, os.path.join(args.fig_dir, "ch07-queries.png"))
    print("\n[질의의 전문화] 질의별로: 점수≥0.5 로 '객체가 있다' 고 답한 그림의 비율, 그때 낸 박스의 평균(± 표준편차)")
    print("질의 | 쓰인 비율 | 중심 x        중심 y        | 너비          높이")
    for q in range(boxes.shape[1]):
        used = scores[:, q] >= 0.5
        if used.sum() < 2:
            print(f" {q:2d}  |   {float(used.float().mean()):.2f}    | (거의 쓰이지 않음)")
            continue
        mean, std = boxes[used, q].mean(0), boxes[used, q].std(0)
        print(f" {q:2d}  |   {float(used.float().mean()):.2f}    | {mean[0]:.2f} ± {std[0]:.2f}   {mean[1]:.2f} ± {std[1]:.2f}  | "
              f"{mean[2]:.2f} ± {std[2]:.2f}   {mean[3]:.2f} ± {std[3]:.2f}")
    per_image = (scores >= 0.5).sum(1).float()
    counts = torch.tensor([len(t["labels"]) for t in val_set.targets]).float()
    print(f"그림마다 점수≥0.5 인 예측 수가 정답 객체 수와 같은 그림: {int((per_image == counts).sum())} / {len(counts)}장")

    # 4-4 교차 어텐션 지도: 객체가 3개 이상인 첫 검증 그림
    index = next((i for i, t in enumerate(val_set.targets) if len(t["labels"]) >= 3), 0)
    chosen, attn = plot_attention(model, val_set, index, os.path.join(args.fig_dir, "ch07-attention.png"), device)
    print(f"\n[교차 어텐션] 검증 그림 #{index}: 점수≥0.5 인 질의 {chosen}. 지도는 144칸에 걸친 확률 분포(합 1)이고, "
          "칸마다 고르게 보면 1/144 = 0.0069")
    for q in chosen:
        top = torch.topk(attn[q], 5)
        print(f"  질의 {q}: 가장 큰 가중치 {float(top.values[0]):.3f}, 상위 5칸의 합 {float(top.values.sum()):.3f}")
    print(f"\n전체 걸린 시간 {time.time() - start:.0f}초")
# --8<-- [end:main]


if __name__ == "__main__":
    main()
