"""10장 · RF-DETR 의 구조 — 9장까지의 부품을 조립해 "미니 RF-DETR" 을 만들고, 진짜 RF-DETR Nano 와 나란히 본다.

무엇을 하나
  1. MiniRFDETR: 윈도 ViT 백본(9장) → 다중 층 특징 → C2f 프로젝터(9장) → 2단계 질의 선택(묶음별)
     → 디코더(묶음별 자기 어텐션 → 변형 교차 어텐션(8장) → FFN) → 공유 분류 · 박스 머리(박스 재매개변수화).
     기준 박스는 모든 디코더 층이 처음 것을 함께 쓴다 (lite 기준점 정제). 구조와 계산은 공식 구현을 따르고
     크기(차원 · 층 수 · 질의 수)만 줄였다.
  2. 입력부터 출력까지 텐서 모양을 한 단계씩 추적하고, 부품별 매개변수 수를 센다.
  3. 구조에서 따라 나오는 성질을 check 로 확인한다: 추론 출력 = 학습 때 첫 묶음의 출력, 디코더를 k 층만 쓴 출력 =
     k 번째 보조 출력, 0 층 = 인코더 제안, 초기화 직후의 박스 = 제안 박스 그대로.
  4. 손잡이: 해상도 · 패치 크기 · 윈도 수 · 디코더 층 수 · 질의 수를 forward 인자로 바꿔 가며 속도를 잰다 (12장의 예고).
  5. 진짜 RF-DETR Nano (rfdetr 패키지가 깔려 있을 때만): 384×384 입력의 단계별 텐서 모양과 부품별 매개변수 수를
     훅으로 실제로 재서 미니 모델과 나란히 놓는다.

실행
  python ch10_rfdetr_model.py            # 본문 결과 (노트북 GPU 약 35초. RF-DETR Nano 대조는 CPU 에서 돈다)
  python ch10_rfdetr_model.py --quick    # 연기 시험 (CPU 약 15초, Nano 대조는 건너뜀)
  --nano-weights 경로   RF-DETR Nano 가중치 파일 (없으면 rfdetr 가 그 경로에 내려받는다. 기본 rf-detr-nano.pth)
그림은 --fig-dir (기본 figures/) 에 저장된다. 이 파일은 학습을 하지 않는다 (학습은 11장 ch11_train.py).

11장 ch11_train.py · 12장 ch12_nas.py · 13장 ch13_seg.py 가 이 파일의 MiniRFDETR · DEFAULT_CONFIG · postprocess 를 가져다 쓴다.
"""

from __future__ import annotations

import argparse
import math
import os
import time

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

from ch07_detr import MLP, get_device, sine_embed, sine_position_2d
from ch08_deformable import MSDeformAttn, gen_proposals, postprocess_sigmoid
from ch09_lwdetr_parts import (SCALE_FACTORS, MultiScaleProjector, WindowedViT, box_reparam, count_parameters,
                               group_self_attention, to_window_major)
from rf_shapes import NUM_CLASSES, ShapesDataset, draw_boxes


# ── 1. 디코더 층 ─────────────────────────────────────────────────────────────


# --8<-- [start:decoder-layer]
class RFDETRDecoderLayer(nn.Module):
    """RF-DETR 디코더 한 층 (post-norm): ① 묶음별 자기 어텐션 → ② 변형 교차 어텐션 → ③ FFN, 각각 뒤에 더하고 층 정규화.

    8장의 DeformableDecoderLayer 와 다른 점: 자기 어텐션과 교차 어텐션의 머리 수가 다르고 (공식 8 · 16),
    학습 때 자기 어텐션을 질의 묶음 안에서만 한다 (Group DETR, 9장 group_self_attention).
    매개변수 이름은 공식 TransformerDecoderLayer 와 같다.
    """

    def __init__(self, dim: int, sa_heads: int, ca_heads: int, ffn_dim: int, n_levels: int, n_points: int):
        super().__init__()
        self.self_attn = nn.MultiheadAttention(dim, sa_heads, batch_first=True)
        self.norm1 = nn.LayerNorm(dim)
        self.cross_attn = MSDeformAttn(dim, n_levels, ca_heads, n_points)
        self.norm2 = nn.LayerNorm(dim)
        self.linear1 = nn.Linear(dim, ffn_dim)
        self.linear2 = nn.Linear(ffn_dim, dim)
        self.norm3 = nn.LayerNorm(dim)

    def forward(self, tgt, query_pos, reference, memory, spatial_shapes, groups: int = 1, return_details=False):
        """tgt · query_pos (B, G·N, D), reference (B, G·N, L, 4) 기준 박스, memory (B, ΣHW, D).

        돌려주는 값: 새 tgt (B, G·N, D).  return_details=True 면 (tgt, 표본점 (B, G·N, M, L, K, 2), 가중치).
        """
        attended = group_self_attention(self.self_attn, tgt + query_pos, tgt, groups)  # ① 같은 묶음끼리만 본다
        tgt = self.norm1(tgt + attended)
        attended, locations, weights = self.cross_attn(tgt + query_pos, reference, memory, spatial_shapes,
                                                       return_details=True)  # ② 기준 박스 안팎의 M·L·K 곳만 읽는다
        tgt = self.norm2(tgt + attended)
        tgt = self.norm3(tgt + self.linear2(F.relu(self.linear1(tgt))))  # ③ FFN
        return (tgt, locations, weights) if return_details else tgt
# --8<-- [end:decoder-layer]


# ── 2. 미니 RF-DETR ──────────────────────────────────────────────────────────


# --8<-- [start:config]
DEFAULT_CONFIG = {
    "num_classes": NUM_CLASSES,  # 3 (원 · 사각형 · 삼각형)
    "num_queries": 12,           # 묶음 하나의 질의 수 (공식 300)
    "group_detr": 4,             # 학습 때의 질의 묶음 수 (공식 13). 추론 때는 첫 묶음만 쓴다
    "hidden_dim": 128,           # 프로젝터 출력 · 디코더의 차원 (공식 256)
    "dec_layers": 3,             # 디코더 층 수 (Nano 2, Small 3, Medium 4)
    "sa_heads": 8,               # 디코더 자기 어텐션의 머리 수 (공식 8)
    "ca_heads": 16,              # 디코더 변형 교차 어텐션의 머리 수 (공식 16)
    "dec_n_points": 2,           # 머리 · 레벨마다의 표본점 수 (공식 2)
    "ffn_dim": 256,              # 디코더 FFN 의 은닉 차원 (공식 2048)
    "img_size": 96,              # 기본 입력 해상도 (Nano 384)
    "patch_size": 8,             # 기본 패치 크기 (Nano 16) → 토큰 격자 12×12 (Nano 24×24)
    "vit_dim": 96,               # 백본의 차원 (DINOv2-S 384)
    "vit_depth": 6,              # 백본의 블록 수 (DINOv2-S 12)
    "vit_heads": 4,              # 백본의 머리 수 (DINOv2-S 6)
    "out_feature_indexes": (2, 4, 6),  # 특징을 꺼내는 층 (Nano [3, 6, 9, 12]) → 윈도 블록 0, 1, 3, 5 / 전역 블록 2, 4
    "num_windows": 2,            # 한 변의 윈도 수 (Nano 2)
    "projector_scale": ("P4",),  # 프로젝터가 만드는 스케일 (공식 ["P4"])
}
# --8<-- [end:config]


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

    backbone   WindowedViT            그림 → 특징 맵 여러 장 (B, vit_dim, h, w)
    projector  MultiScaleProjector    → 스케일마다 (B, D, h_l, w_l).  기본은 P4 한 장 (12×12)
    2단계 질의 선택 (묶음마다 따로 있는 enc_output · enc_out_class_embed · enc_out_bbox_embed)
               모든 칸의 특징 → 클래스 로짓 → 최댓값 상위 N 칸 → 그 칸의 제안 박스를 델타로 고친 박스
    decoder    RFDETRDecoderLayer × L. 기준 박스는 모든 층이 같은 것을 쓴다 (lite 기준점 정제)
    class_embed · bbox_embed   모든 디코더 층이 함께 쓰는 머리. 박스 = box_reparam(Δ, 기준 박스) (시그모이드 없음)

    학습(model.train())  질의 G·N 개 (G = group_detr 묶음). 출력의 질의 축 길이가 G·N.
    추론(model.eval())   첫 묶음의 N 개만.
    forward 의 인자로 해상도(그림 크기) · patch_size · num_windows · dec_layers · num_queries 를 바꿀 수 있다.
    매개변수 이름은 공식 LWDETR · Transformer 와 맞췄다 (transformer. 접두어는 뗐다).
    """

    def __init__(self, **config):
        super().__init__()
        self.config = {**DEFAULT_CONFIG, **config}
        c = self.config
        dim = c["hidden_dim"]
        self.num_queries, self.group_detr, self.hidden_dim = c["num_queries"], c["group_detr"], dim
        self.num_levels = len(c["projector_scale"])
        self.backbone = WindowedViT(c["img_size"], c["patch_size"], c["vit_dim"], c["vit_depth"], c["vit_heads"],
                                    out_feature_indexes=c["out_feature_indexes"], num_windows=c["num_windows"])
        self.projector = MultiScaleProjector([c["vit_dim"]] * len(c["out_feature_indexes"]), dim,
                                             [SCALE_FACTORS[name] for name in c["projector_scale"]])
        # 2단계 질의 선택: 묶음마다 따로
        groups = self.group_detr
        self.enc_output = nn.ModuleList(nn.Linear(dim, dim) for _ in range(groups))
        self.enc_output_norm = nn.ModuleList(nn.LayerNorm(dim) for _ in range(groups))
        # 디코더
        self.decoder = nn.ModuleList(
            RFDETRDecoderLayer(dim, c["sa_heads"], c["ca_heads"], c["ffn_dim"], self.num_levels, c["dec_n_points"])
            for _ in range(c["dec_layers"]))
        self.decoder_norm = nn.LayerNorm(dim)  # 층마다의 출력에 함께 쓰는 층 정규화
        self.ref_point_head = MLP(2 * dim, dim, dim, num_layers=2)  # 기준 박스의 사인 임베딩 → 질의 위치 임베딩
        for module in (self.enc_output, self.decoder, self.ref_point_head):  # 공식: Transformer 의 행렬은 Xavier 초기화
            for p in module.parameters():
                if p.dim() > 1:
                    nn.init.xavier_uniform_(p)
        for layer in self.decoder:
            layer.cross_attn._reset_parameters()  # 변형 어텐션은 자기 초기화로 되돌린다 (8장)
        # 머리 (모든 디코더 층이 공유)
        self.class_embed = nn.Linear(dim, c["num_classes"])
        self.bbox_embed = MLP(dim, dim, 4, num_layers=3)
        nn.init.constant_(self.class_embed.bias, -math.log((1 - 0.01) / 0.01))  # σ(편향) = 0.01 에서 출발
        nn.init.constant_(self.bbox_embed.layers[-1].weight, 0.0)  # 처음의 Δ = 0 → 박스 = 기준 박스 그대로
        nn.init.constant_(self.bbox_embed.layers[-1].bias, 0.0)
        # 인코더 제안용 머리: 묶음마다 하나씩, 위의 머리를 (초기화까지) 복사해서 시작한다
        self.enc_out_class_embed = nn.ModuleList(nn.Linear(dim, c["num_classes"]) for _ in range(groups))
        self.enc_out_bbox_embed = nn.ModuleList(MLP(dim, dim, 4, num_layers=3) for _ in range(groups))
        for head in self.enc_out_class_embed:
            head.load_state_dict(self.class_embed.state_dict())
        for head in self.enc_out_bbox_embed:
            head.load_state_dict(self.bbox_embed.state_dict())
        # 질의: 내용(query_feat)과 기준 박스 보정(refpoint_embed) 을 묶음 G 개 × N 개만큼 학습한다
        self.query_feat = nn.Embedding(self.num_queries * groups, dim)
        self.refpoint_embed = nn.Embedding(self.num_queries * groups, 4)
        nn.init.constant_(self.refpoint_embed.weight, 0.0)  # 0 → 처음에는 선택된 제안 박스를 그대로 기준 박스로 쓴다

    def extract_features(self, images, num_windows=None, patch_size=None):
        """그림 → 백본 특징 목록, 프로젝터 특징 목록, memory (B, ΣHW, D), spatial_shapes [(h_0, w_0), …]."""
        backbone_features = self.backbone(images, num_windows=num_windows, patch_size=patch_size)
        projected = self.projector(backbone_features)  # [(B, D, h_l, w_l), …]
        spatial_shapes = [tuple(p.shape[-2:]) for p in projected]
        memory = torch.cat([p.flatten(2).transpose(1, 2) for p in projected], dim=1)  # 레벨 순서 · 행 우선
        return backbone_features, projected, memory, spatial_shapes

    def select_queries(self, memory, spatial_shapes, num_queries: int, groups: int):
        """2단계 질의 선택. 돌려주는 값 (모두 질의 축 길이 G·N):

        boxes   (B, G·N, 4)  선택된 칸의 제안 박스를 델타로 고친 박스 (기울기가 흐른다 → 손실에 들어간다)
        logits  (B, G·N, K)  선택된 칸의 클래스 로짓
        feats   (B, G·N, D)  선택된 칸의 특징 (enc_output → 층 정규화를 거친 것)
        top     (B, G·N)     선택된 칸의 번호 (memory 의 토큰 번호)
        """
        proposals = gen_proposals(spatial_shapes, device=memory.device)  # (ΣHW, 4): 칸 중심, 너비 · 높이 0.05·2^레벨
        boxes, logits, feats, tops = [], [], [], []
        for g in range(groups):  # 묶음마다 자기 Linear · 머리로 따로 고른다
            feature = self.enc_output_norm[g](self.enc_output[g](memory))  # (B, ΣHW, D)
            all_logits = self.enc_out_class_embed[g](feature)  # (B, ΣHW, K)
            top = all_logits.max(-1).values.topk(num_queries, dim=1).indices  # (B, N): 클래스 로짓 최댓값의 상위 N 칸
            chosen = torch.gather(feature, 1, top[..., None].expand(-1, -1, feature.shape[-1]))  # (B, N, D)
            delta = self.enc_out_bbox_embed[g](chosen)  # (B, N, 4)
            boxes.append(box_reparam(delta, proposals[top]))  # 제안 박스 + 델타 (재매개변수화)
            logits.append(torch.gather(all_logits, 1, top[..., None].expand(-1, -1, all_logits.shape[-1])))
            feats.append(chosen)
            tops.append(top)
        return torch.cat(boxes, 1), torch.cat(logits, 1), torch.cat(feats, 1), torch.cat(tops, 1)

    def forward(self, images, num_windows: int | None = None, patch_size: int | None = None,
                dec_layers: int | None = None, num_queries: int | None = None, return_features: bool = False):
        """images: (B, 3, H, W), 값 0 – 1.

        손잡이 (None 이면 만들 때의 설정)
          num_windows  백본 윈도 블록의 한 변 윈도 수        patch_size  패치 크기 (패치 임베딩을 보간)
          dec_layers   앞의 몇 층만 쓸지. 0 이면 디코더 없이 인코더 제안이 곧 예측
          num_queries  추론 때 질의를 앞의 몇 개만 쓸지 (인코더 클래스 점수 순으로 상위 몇 개). 학습 때는 무시
        돌려주는 값: {"pred_logits": (B, Q, K), "pred_boxes": (B, Q, 4) 정규화 cxcywh,
                     "aux_outputs": [앞 층들의 {"pred_logits", "pred_boxes"}], "enc_outputs": {인코더 제안의 로짓 · 박스}}
                     Q = 학습 때 G·N, 추론 때 N (또는 num_queries).
        return_features=True 면 "features" 사전도 넣는다 (13장의 분할 머리 등이 쓴다):
          "backbone" [(B, vit_dim, h, w), …], "projector" [(B, D, h_l, w_l), …], "memory" (B, ΣHW, D),
          "spatial_shapes", "hs" (디코더 층 수, B, Q, D) 층별 질의 임베딩 (decoder_norm 을 거친 것),
          "enc_hs" (B, Q, D) 선택된 칸의 특징, "references" (B, Q, 4) 디코더의 기준 박스, "topk" (B, Q) 선택된 칸 번호.
        """
        groups = self.group_detr if self.training else 1
        if self.training or num_queries is None:
            num_queries = self.num_queries
        num_layers = len(self.decoder) if dec_layers is None else dec_layers
        backbone_features, projected, memory, spatial_shapes = self.extract_features(images, num_windows, patch_size)
        batch = memory.shape[0]

        # ── 2단계 질의 선택 ──
        enc_boxes, enc_logits, enc_feats, top = self.select_queries(memory, spatial_shapes, num_queries, groups)
        enc_outputs = {"pred_logits": enc_logits, "pred_boxes": enc_boxes}
        features = {"backbone": backbone_features, "projector": projected, "memory": memory,
                    "spatial_shapes": spatial_shapes, "enc_hs": enc_feats, "topk": top}
        if num_layers == 0:  # 디코더를 모두 떼면 인코더 제안이 곧 예측이다
            outputs = dict(enc_outputs, aux_outputs=[])
            if return_features:
                outputs["features"] = features
            return outputs

        # ── 디코더 ──
        total = groups * num_queries
        # 기준 박스 = 선택된 박스(기울기 차단) 를 학습되는 refpoint_embed 로 한 번 더 고친 것. 모든 층이 이것을 쓴다
        reference = box_reparam(self.refpoint_embed.weight[:total][None], enc_boxes.detach())  # (B, G·N, 4)
        query_pos = self.ref_point_head(sine_embed(reference, self.hidden_dim // 2))  # (B, G·N, 2D) → (B, G·N, D)
        reference_input = reference[:, :, None].expand(-1, -1, self.num_levels, -1)  # 모든 레벨에 같은 기준 박스
        tgt = self.query_feat.weight[:total][None].expand(batch, -1, -1)  # 내용 질의: 그림과 무관하게 학습된 임베딩
        hs = []
        for layer in self.decoder[:num_layers]:
            tgt = layer(tgt, query_pos, reference_input, memory, spatial_shapes, groups)
            hs.append(self.decoder_norm(tgt))
        hs = torch.stack(hs)  # (층 수, B, G·N, D)

        # ── 머리: 모든 층이 같은 머리를 쓰고, 박스는 언제나 "처음 기준 박스" 에서 출발한다 ──
        logits = self.class_embed(hs)  # (층 수, B, G·N, K)
        boxes = box_reparam(self.bbox_embed(hs), reference)  # (층 수, B, G·N, 4)
        outputs = {"pred_logits": logits[-1], "pred_boxes": boxes[-1],
                   "aux_outputs": [{"pred_logits": a, "pred_boxes": b} for a, b in zip(logits[:-1], boxes[:-1])],
                   "enc_outputs": enc_outputs}
        if return_features:
            outputs["features"] = dict(features, hs=hs, references=reference)
        return outputs
# --8<-- [end:model]


# --8<-- [start:postprocess]
@torch.no_grad()
def postprocess(outputs, num_select: int | None = None):
    """RF-DETR 의 후처리 = 8장의 postprocess_sigmoid: (질의, 클래스) 쌍의 시그모이드 점수 상위 num_select 개. NMS 없음."""
    return postprocess_sigmoid(outputs, num_select)


def parameter_groups(model: MiniRFDETR):
    """부품별 매개변수 수. 돌려주는 값: [(이름, 전체 수, 추론 때 쓰이는 수)].

    묶음마다 따로 있는 것(enc_output …, 질의 임베딩)은 추론 때 첫 묶음 것만 쓰인다.
    """
    groups = model.group_detr
    rows = [("backbone (WindowedViT)", count_parameters(model.backbone), count_parameters(model.backbone)),
            ("projector (C2f)", count_parameters(model.projector), count_parameters(model.projector))]
    two_stage = sum(count_parameters(m) for m in (model.enc_output, model.enc_output_norm, model.enc_out_class_embed,
                                                   model.enc_out_bbox_embed))
    rows.append(("two-stage heads (x groups)", two_stage, two_stage // groups))
    decoder = sum(count_parameters(m) for m in (model.decoder, model.decoder_norm, model.ref_point_head))
    rows.append(("decoder layers", decoder, decoder))
    heads = count_parameters(model.class_embed) + count_parameters(model.bbox_embed)
    rows.append(("class + box heads", heads, heads))
    queries = count_parameters(model.query_feat) + count_parameters(model.refpoint_embed)
    rows.append(("query embeddings (x groups)", queries, queries // groups))
    return rows
# --8<-- [end:postprocess]


# ── 3. 모양 추적과 check ─────────────────────────────────────────────────────


def shape_trace(model: MiniRFDETR, images: torch.Tensor):
    """입력부터 출력까지 단계별 텐서 모양 (추론 모드와 학습 모드)."""
    c = model.config
    print("[모양 추적] 입력", tuple(images.shape), "— 추론 모드 (묶음 1개)")
    model.eval()
    with torch.no_grad():
        tokens, grid = model.backbone.embed(images)
        windows = to_window_major(tokens[:, 1:], *grid, c["num_windows"])
        out = model(images, return_features=True)
    f = out["features"]
    rows = [
        ("그림", tuple(images.shape)),
        ("패치 임베딩 + CLS + 위치 임베딩", tuple(tokens.shape)),
        ("윈도 우선 재배열 + 윈도마다 CLS", (windows.shape[0], windows.shape[1] + 1, windows.shape[2])),
        (f"백본 특징 맵 × {len(f['backbone'])} (층 {list(c['out_feature_indexes'])})", tuple(f["backbone"][0].shape)),
        ("프로젝터 출력 (P4)", tuple(f["projector"][0].shape)),
        ("memory (칸을 한 줄로)", tuple(f["memory"].shape)),
        ("제안 박스 (칸마다 하나)", (f["memory"].shape[1], 4)),
        ("칸마다의 클래스 로짓", (*f["memory"].shape[:2], c["num_classes"])),
        ("선택된 칸 번호 topk", tuple(f["topk"].shape)),
        ("인코더 제안: 로짓 / 박스", (tuple(out["enc_outputs"]["pred_logits"].shape), tuple(out["enc_outputs"]["pred_boxes"].shape))),
        ("기준 박스 (모든 층 공유)", tuple(f["references"].shape)),
        ("기준 박스의 사인 임베딩 → ref_point_head", ((*f["references"].shape[:2], 2 * c["hidden_dim"]), tuple(f["hs"].shape[1:]))),
        ("디코더 층별 질의 임베딩 hs", tuple(f["hs"].shape)),
        ("pred_logits / pred_boxes", (tuple(out["pred_logits"].shape), tuple(out["pred_boxes"].shape))),
        ("aux_outputs", f"{len(out['aux_outputs'])}개 (앞 층들), 각각 같은 모양"),
    ]
    for name, shape in rows:
        print(f"    {name:38s} {shape}")
    pos = sine_position_2d(*f["spatial_shapes"][0], c["hidden_dim"])
    print(f"    (참고) 2차원 사인 위치 인코딩          {tuple(pos.shape)} — 공식 구현은 이것을 계산해 디코더에 넘기지만 "
          "디코더가 쓰지 않는다 (아래 Nano 대조에서 확인)")
    model.train()
    with torch.no_grad():
        out_train = model(images, return_features=True)
    print(f"  학습 모드 (묶음 {model.group_detr}개): pred_logits {tuple(out_train['pred_logits'].shape)}, "
          f"enc_outputs {tuple(out_train['enc_outputs']['pred_logits'].shape)}, hs {tuple(out_train['features']['hs'].shape)}")
    model.eval()
    return out, out_train


def structure_checks(model: MiniRFDETR, images: torch.Tensor, out_eval, out_train):
    """구조에서 따라 나오는 성질들."""
    n = model.num_queries
    print("[check] 구조에서 따라 나오는 성질")
    diff = max(float((out_train[k][:, :n] - out_eval[k]).abs().max()) for k in ("pred_logits", "pred_boxes"))
    print(f"  추론 출력 = 학습 모드 출력의 첫 묶음 (질의 0 – {n - 1}): 최대 차이 {diff:.2e}")
    with torch.no_grad():
        for k in range(len(model.decoder)):
            partial = model(images, dec_layers=k)
            if k == 0:
                reference = out_eval["enc_outputs"]
                name = "enc_outputs"
            else:
                reference = out_eval["aux_outputs"][k - 1]
                name = f"aux_outputs[{k - 1}]"
            diff = max(float((partial[key] - reference[key]).abs().max()) for key in ("pred_logits", "pred_boxes"))
            print(f"  dec_layers={k} 의 출력 = 전체 모델의 {name}: 최대 차이 {diff:.2e}")
        half = model(images, dec_layers=0, num_queries=n // 2)
        diff = float((half["pred_boxes"] - out_eval["enc_outputs"]["pred_boxes"][:, :n // 2]).abs().max())
        print(f"  num_queries={n // 2}, dec_layers=0 의 출력 = 인코더 제안 {n}개의 앞 {n // 2}개 (점수 순): 최대 차이 {diff:.2e}")
        half = model(images, num_queries=n // 2)
        diff = float((half["pred_logits"] - out_eval["pred_logits"][:, :n // 2]).abs().max())
        print(f"  num_queries={n // 2}, 디코더 3층의 로짓 vs 질의 {n}개일 때의 앞 {n // 2}개: 최대 차이 {diff:.2e} "
              "(같지 않다 — 자기 어텐션의 상대가 줄었다)")
        scores = out_eval["enc_outputs"]["pred_logits"].max(-1).values
        print(f"  선택된 칸은 점수 내림차순으로 놓인다: {bool((scores[:, :-1] >= scores[:, 1:]).all())}")
    # 초기화 직후: Δ = 0 이므로 모든 층의 박스가 선택된 제안 박스 그대로
    fresh = MiniRFDETR(**model.config).eval()
    with torch.no_grad():
        out = fresh(images, return_features=True)
    proposals = gen_proposals(out["features"]["spatial_shapes"])
    chosen = proposals[out["features"]["topk"]]
    diffs = [float((layer["pred_boxes"] - chosen).abs().max()) for layer in out["aux_outputs"] + [out, out["enc_outputs"]]]
    print(f"  초기화 직후의 박스(디코더 3개 층 + 인코더 제안) = 선택된 칸의 제안 박스: 최대 차이 {max(diffs):.2e}, "
          f"박스 크기 {float(out['pred_boxes'][..., 2:].min()):.2f} – {float(out['pred_boxes'][..., 2:].max()):.2f}")
    prob = out["pred_logits"].sigmoid()
    print(f"  초기화 직후의 클래스 확률: 평균 {float(prob.mean()):.4f}, 범위 {float(prob.min()):.4f} – {float(prob.max()):.4f} "
          "(편향 −log 99 = −4.595 → σ = 0.01 근처)")


def knob_checks(model: MiniRFDETR, device: str, quick: bool):
    """손잡이를 바꿔 가며 출력 모양과 순전파 시간을 잰다 (학습되지 않은 가중치 — 속도는 가중치와 무관하다)."""
    print("[손잡이] 같은 가중치, forward 인자만 바꿈 — 추론 모드, 배치 1 과 배치 64 의 순전파 시간")
    model = model.to(device).eval()
    settings = [("기본 (96, 패치 8, 윈도 2, 디코더 3, 질의 12)", {}),
                ("디코더 2층", {"dec_layers": 2}), ("디코더 1층", {"dec_layers": 1}), ("디코더 0층", {"dec_layers": 0}),
                ("질의 6개", {"num_queries": 6}), ("윈도 1×1 (전부 전역)", {"num_windows": 1}),
                ("윈도 3×3", {"num_windows": 3}), ("패치 12 (격자 8×8)", {"patch_size": 12}),
                ("패치 6 (격자 16×16)", {"patch_size": 6}), ("해상도 64 (격자 8×8)", {"size": 64}),
                ("해상도 128 (격자 16×16)", {"size": 128})]
    rounds = 5 if quick else 40
    # 설정을 하나씩 차례로 재면 그 사이 GPU 의 상태(클록 · 다른 작업)가 달라져 비교가 흔들린다.
    # 그래서 "모든 설정을 한 번씩" 을 rounds 번 되풀이하고, 설정마다 가장 빨랐던 값을 쓴다 (앞 1/5 은 버린다).
    inputs = {(size, batch): torch.rand(batch, 3, size, size, device=device) for size in (64, 96, 128) for batch in (1, 64)}
    samples = {(i, batch): [] for i in range(len(settings)) for batch in (1, 64)}
    shapes = {}
    with torch.no_grad():
        for _ in range(rounds):
            for i, (name, kwargs) in enumerate(settings):
                kwargs = dict(kwargs)
                size = kwargs.pop("size", 96)
                for batch in (1, 64):
                    if device == "cuda":
                        torch.cuda.synchronize()
                    start = time.perf_counter()
                    out = model(inputs[(size, batch)], **kwargs)
                    if device == "cuda":
                        torch.cuda.synchronize()
                    samples[(i, batch)].append(time.perf_counter() - start)
                shapes[i] = tuple(out["pred_boxes"].shape)
    rows = []
    print(f"  ({rounds}바퀴 가운데 앞 {rounds // 5}바퀴를 버린 최솟값)")
    print("  설정                                     | 출력 pred_boxes | 배치 1 (ms) | 배치 64 (ms/장)")
    for i, (name, _) in enumerate(settings):
        times = [1000 * min(samples[(i, batch)][rounds // 5:]) / batch for batch in (1, 64)]
        rows.append((name, times[0], times[1]))
        print(f"  {name:38s} | {str(shapes[i]):15s} | {times[0]:11.2f} | {times[1]:10.3f}")
    model.cpu()
    return rows


# ── 4. 진짜 RF-DETR Nano 와 대조 ─────────────────────────────────────────────


def nano_trace(weights_path: str):
    """설치된 rfdetr 의 RF-DETR Nano 를 만들어, 384×384 입력의 단계별 모양과 부품별 매개변수 수를 훅으로 잰다.

    돌려주는 값: 부품별 매개변수 표 [(이름, 전체, 추론 때 쓰이는 수)], rfdetr 가 없으면 None.
    """
    try:
        import logging
        import warnings

        warnings.filterwarnings("ignore")
        logging.disable(logging.WARNING)
        import rfdetr
        from rfdetr import RFDETRNano
    except ImportError:
        print("[RF-DETR Nano 대조] rfdetr 패키지가 없어 건너뜀 (pip install rfdetr)")
        return None
    version = getattr(rfdetr, "__version__", None)
    if version is None:
        from importlib.metadata import version as package_version
        version = package_version("rfdetr")
    print(f"[RF-DETR Nano 대조] rfdetr {version}, 가중치 {os.path.basename(weights_path)}, 장치 cpu")
    wrapper = RFDETRNano(pretrain_weights=weights_path, device="cpu")
    logging.disable(logging.NOTSET)
    core = wrapper.model.model.eval()  # rfdetr.models.lwdetr.LWDETR
    args = wrapper.model.args
    print(f"  설정: resolution {args.resolution}, patch_size {args.patch_size}, num_windows {args.num_windows}, "
          f"out_feature_indexes {args.out_feature_indexes}, hidden_dim {args.hidden_dim}, dec_layers {args.dec_layers}, "
          f"num_queries {args.num_queries}, group_detr {args.group_detr}, sa_nheads {args.sa_nheads}, "
          f"ca_nheads {args.ca_nheads}, dec_n_points {args.dec_n_points}, projector_scale {args.projector_scale}")
    vit_config = core.backbone[0].encoder.encoder.config
    print(f"  백본: 차원 {vit_config.hidden_size}, 블록 {vit_config.num_hidden_layers}, 머리 {vit_config.num_attention_heads}, "
          f"윈도 블록 {vit_config.window_block_indexes}, 레지스터 토큰 {vit_config.num_register_tokens}")

    records = {}
    hooks = []

    def shape_of(value):
        if torch.is_tensor(value):
            return tuple(value.shape)
        if isinstance(value, (list, tuple)):
            return [shape_of(v) for v in value if torch.is_tensor(v) or isinstance(v, (list, tuple))]
        return type(value).__name__

    def watch(name, module):
        def hook(_module, inputs, output):
            call = {"in": [shape_of(v) for v in inputs if torch.is_tensor(v)], "out": shape_of(output),
                    "args": [v for v in inputs if isinstance(v, bool)]}
            records.setdefault(name, call)  # 첫 호출
            records[name + ":last"] = call  # 마지막 호출 (한 순전파에서 두 번 불리는 모듈이 있다)
        hooks.append(module.register_forward_hook(hook))

    modules = dict(core.named_modules())
    watch("embeddings", modules["backbone.0.encoder.encoder.embeddings"])
    for i in range(vit_config.num_hidden_layers):
        watch(f"block{i}", modules[f"backbone.0.encoder.encoder.encoder.layer.{i}"])
        watch(f"attn{i}", modules[f"backbone.0.encoder.encoder.encoder.layer.{i}.attention"])
    watch("vit", modules["backbone.0.encoder"])
    watch("projector", modules["backbone.0.projector"])
    watch("position", modules["backbone.1"])
    watch("enc_output", modules["transformer.enc_output.0"])
    watch("enc_class", modules["transformer.enc_out_class_embed.0"])
    watch("enc_bbox", modules["transformer.enc_out_bbox_embed.0"])
    watch("ref_point_head", modules["transformer.decoder.ref_point_head"])
    for i in range(args.dec_layers):
        watch(f"dec{i}", modules[f"transformer.decoder.layers.{i}"])
        watch(f"dec{i}_cross", modules[f"transformer.decoder.layers.{i}.cross_attn"])
    watch("class_embed", modules["class_embed"])
    watch("bbox_embed", modules["bbox_embed"])

    torch.manual_seed(0)
    x = torch.rand(1, 3, args.resolution, args.resolution)
    with torch.no_grad():
        out = core(x)
    for hook in hooks:
        hook.remove()

    full = [i for i in range(vit_config.num_hidden_layers) if records[f"block{i}"]["args"][-1]]
    print("  단계별 텐서 모양 (추론 모드, 배치 1, 훅으로 실제로 잰 값)")
    rows = [
        ("그림", tuple(x.shape)),
        ("임베딩 출력 (윈도 우선 + 윈도마다 CLS)", records["embeddings"]["out"]),
        ("윈도 블록의 어텐션 입력 (예: 블록 0)", records["attn0"]["in"][0]),
        (f"전역 블록의 어텐션 입력 (블록 {full})", records[f"attn{full[0]}"]["in"][0]),
        (f"백본 특징 맵 × {len(records['vit']['out'])}", records["vit"]["out"][0]),
        ("프로젝터 출력", records["projector"]["out"][0]),
        ("2차원 사인 위치 인코딩", records["position"]["out"]),
        ("enc_output (모든 칸)", records["enc_output"]["out"]),
        ("칸마다의 클래스 로짓 (순위를 매길 때)", records["enc_class"]["out"]),
        ("선택된 칸의 클래스 로짓 (enc_outputs)", records["enc_class:last"]["out"]),
        ("선택된 칸의 박스 델타", records["enc_bbox"]["out"]),
        ("ref_point_head 입력 → 출력", (records["ref_point_head"]["in"][0], records["ref_point_head"]["out"])),
        ("변형 교차 어텐션 입력: 질의 / 기준 박스 / memory", tuple(records["dec0_cross"]["in"][:3])),
        (f"디코더 층 출력 × {args.dec_layers}", records["dec0"]["out"]),
        ("class_embed 출력 (층 축 포함)", records["class_embed"]["out"]),
        ("pred_logits / pred_boxes", (tuple(out["pred_logits"].shape), tuple(out["pred_boxes"].shape))),
    ]
    for name, shape in rows:
        print(f"    {name:44s} {shape}")
    grid = args.resolution // args.patch_size
    print(f"    → 패치 토큰 {grid}×{grid} = {grid * grid}개, 윈도 {args.num_windows}×{args.num_windows} 로 나누면 윈도마다 "
          f"{(grid // args.num_windows) ** 2}개 + CLS 1개. 전역 블록은 {full} (0 부터 센 번호)")
    print(f"    → 특징을 꺼내는 자리: 블록 {[i - 1 for i in args.out_feature_indexes]} 의 출력 (out_feature_indexes "
          f"{args.out_feature_indexes} 는 '블록 몇 개를 지난 뒤' 라는 뜻)")
    print(f"    → 출력 키: {sorted(out.keys())}  (추론 모드에서도 aux_outputs · enc_outputs 가 나온다)")

    # 사인 위치 인코딩이 결과에 쓰이는가: 0 으로 바꿔 넣고 출력을 비교한다
    handle = modules["backbone.1"].register_forward_hook(lambda _m, _i, output: torch.zeros_like(output))
    with torch.no_grad():
        out_zero = core(x)
    handle.remove()
    diff = max(float((out_zero[k] - out[k]).abs().max()) for k in ("pred_logits", "pred_boxes"))
    print(f"  check 사인 위치 인코딩을 모두 0 으로 바꿔도 출력이 같은가: 최대 차이 {diff:.2e} "
          "→ 이 구성(인코더 없음 + 변형 교차 어텐션)에서는 쓰이지 않는다")

    # 부품별 매개변수 수
    def count(prefixes, keep=lambda name: True):
        return sum(p.numel() for name, p in core.named_parameters()
                   if any(name.startswith(prefix) for prefix in prefixes) and keep(name))

    first_group = lambda name: name.split(".")[2] == "0"  # noqa: E731 — transformer.enc_xxx.<묶음>.…
    two_stage = ["transformer.enc_output.", "transformer.enc_output_norm.", "transformer.enc_out_class_embed.",
                 "transformer.enc_out_bbox_embed."]
    queries = count(["query_feat.", "refpoint_embed."])
    table = [
        ("backbone (windowed DINOv2-S)", count(["backbone.0.encoder."]), count(["backbone.0.encoder."])),
        ("projector (C2f)", count(["backbone.0.projector."]), count(["backbone.0.projector."])),
        ("two-stage heads (x groups)", count(two_stage), count(two_stage, first_group)),
        ("decoder layers", count(["transformer.decoder."]), count(["transformer.decoder."])),
        ("class + box heads", count(["class_embed.", "bbox_embed."]), count(["class_embed.", "bbox_embed."])),
        ("query embeddings (x groups)", queries, queries // args.group_detr),
    ]
    total = sum(p.numel() for p in core.parameters())
    print("  부품별 매개변수 수")
    print("    부품                          |      전체     | 추론 때 쓰이는 것 (묶음 1개)")
    for name, full_count, used in table:
        print(f"    {name:29s} | {full_count:13,d} | {used:13,d}")
    used_total = sum(row[2] for row in table)
    print(f"    {'합계':27s} | {sum(row[1] for row in table):13,d} | {used_total:13,d}")
    print(f"    check 표의 합계 = 모델 전체 매개변수 {total:,}: {sum(row[1] for row in table) == total}")
    print(f"    → 전체 {total / 1e6:.2f}M 은 논문 표 2 의 30.5M 과 맞아떨어진다 (학습용 질의 묶음 {args.group_detr}개를 모두 센 수). "
          f"추론에 실제로 쓰이는 것은 {used_total / 1e6:.2f}M.")
    return table


# ── 5. 그림 ──────────────────────────────────────────────────────────────────

COLORS = ["#0072B2", "#D55E00", "#009E73", "#CC79A7", "#E69F00", "#56B4E9"]


def plot_params(mini_rows, nano_rows, path):
    """부품별 매개변수 수: 미니 모델과 Nano (전체 / 추론 때 쓰이는 것)."""
    import matplotlib.pyplot as plt

    models = [("mini RF-DETR", mini_rows)] + ([("RF-DETR Nano", nano_rows)] if nano_rows else [])
    fig, axes = plt.subplots(1, len(models), figsize=(6.2 * len(models), 3.9), squeeze=False)
    for ax, (title, rows) in zip(axes[0], models):
        names = [r[0] for r in rows]
        y = np.arange(len(rows))[::-1]
        unit, scale = ("M", 1e6) if max(r[1] for r in rows) > 5e6 else ("K", 1e3)
        ax.barh(y + 0.2, [r[1] / scale for r in rows], 0.4, color=COLORS[0], label="all parameters (training)")
        ax.barh(y - 0.2, [r[2] / scale for r in rows], 0.4, color=COLORS[1], hatch="//", edgecolor="white",
                label="used at inference (1 group)")
        for yi, r in zip(y, rows):
            ax.text(r[1] / scale, yi + 0.2, f" {r[1] / scale:.1f}{unit}" if scale == 1e3 else f" {r[1] / scale:.2f}{unit}",
                    va="center", fontsize=7.5)
            ax.text(r[2] / scale, yi - 0.2, f" {r[2] / scale:.1f}{unit}" if scale == 1e3 else f" {r[2] / scale:.2f}{unit}",
                    va="center", fontsize=7.5)
        ax.set_yticks(y)
        ax.set_yticklabels(names, fontsize=8)
        ax.set_xlabel(f"parameters ({unit})")
        ax.set_xlim(0, max(r[1] for r in rows) / scale * 1.22)
        total, used = sum(r[1] for r in rows), sum(r[2] for r in rows)
        ax.set_title(f"{title}: {total / 1e6:.2f}M total, {used / 1e6:.2f}M used at inference", fontsize=9.5)
        ax.grid(alpha=0.3, axis="x")
        ax.legend(fontsize=8, loc="lower right")
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


def plot_proposals(path):
    """제안 박스 격자: 12×12 칸마다 0.05×0.05 박스 하나. 도형의 크기와 견주어 본다."""
    import matplotlib.pyplot as plt

    dataset = ShapesDataset(4, seed=1)
    proposals = gen_proposals([(12, 12)])
    fig, axes = plt.subplots(1, 3, figsize=(11, 4.3))
    for ax, index in zip(axes[:2], (1, 2)):
        image, target = dataset[index]
        draw_boxes(ax, image, proposals, color="#ffd400", linewidth=0.7)
        draw_boxes(ax, image, target["boxes"], color="white", linestyle="--", linewidth=1.4)
        for k in range(1, 12):
            ax.axhline(k * 8 - 0.5, color="white", lw=0.3, alpha=0.5)
            ax.axvline(k * 8 - 0.5, color="white", lw=0.3, alpha=0.5)
        ax.set_title(f"val #{index}: 144 proposals (yellow, 0.05 x 0.05)\nand ground truth (white dashed)", fontsize=9)
    ax = axes[2]
    image, target = dataset[1]
    draw_boxes(ax, image, target["boxes"], color="white", linestyle="--", linewidth=1.4)
    for box, color in zip(target["boxes"], ("#39ff14", "#ff5ad1", "#00e5ff", "#ffd400")):
        cell = ((box[:2] * 12).floor() + 0.5) / 12
        proposal = torch.cat([cell, torch.tensor([0.05, 0.05])])
        draw_boxes(ax, image, proposal[None], color=color, linewidth=2.0)
        delta = torch.cat([(box[:2] - cell) / 0.05, (box[2:] / 0.05).log()])
        ax.annotate("", xy=(float(box[0]) * 96 - 0.5, float(box[1]) * 96 - 0.5),
                    xytext=(float(cell[0]) * 96 - 0.5, float(cell[1]) * 96 - 0.5),
                    arrowprops={"arrowstyle": "->", "color": color, "lw": 1.2})
        ax.text(float(box[0] - box[2] / 2) * 96, float(box[1] - box[3] / 2) * 96 - 2.5,
                "d = (" + ", ".join(f"{float(v):.1f}" for v in delta) + ")", color=color, fontsize=7.5,
                fontweight="bold")
    ax.set_title("the proposal of the cell holding each object centre\nand the delta that turns it into the object box",
                 fontsize=9)
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


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

    labels = ["default", "decoder 2", "decoder 1", "decoder 0", "6 queries", "1x1 window", "3x3 windows", "patch 12",
              "patch 6", "res 64", "res 128"]
    fig, axes = plt.subplots(1, 2, figsize=(11.5, 3.9))
    for ax, column, title in ((axes[0], 1, "batch 1: time per image (ms)"),
                              (axes[1], 2, "batch 64: time per image (ms)")):
        values = [row[column] for row in rows]
        colors = [COLORS[0]] + [COLORS[1]] * 3 + [COLORS[2]] + [COLORS[3]] * 2 + [COLORS[4]] * 2 + [COLORS[5]] * 2
        ax.bar(range(len(values)), values, color=colors)
        for i, v in enumerate(values):
            ax.text(i, v, f"{v:.2f}" if column == 1 else f"{v:.3f}", ha="center", va="bottom", fontsize=7)
        ax.axhline(values[0], color="gray", lw=0.8, ls="--")
        ax.set_xticks(range(len(values)))
        ax.set_xticklabels(labels[:len(values)], rotation=40, ha="right", fontsize=8)
        ax.set_ylabel("ms / image")
        ax.set_title(f"{title} on {device}", fontsize=10)
        ax.grid(alpha=0.3, axis="y")
    fig.suptitle("forward time of the mini RF-DETR when one knob is changed (same weights; min over runs)", fontsize=10)
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


# ── 6. 본 실행 ───────────────────────────────────────────────────────────────


# --8<-- [start:main]
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--quick", action="store_true")
    parser.add_argument("--fig-dir", default="figures")
    parser.add_argument("--seed", type=int, default=0)
    parser.add_argument("--nano-weights", default="rf-detr-nano.pth")
    args = parser.parse_args()
    import matplotlib
    matplotlib.use("Agg")
    os.makedirs(args.fig_dir, exist_ok=True)
    torch.manual_seed(args.seed)
    device = get_device()
    if device == "cpu":
        torch.set_num_threads(4)
    start = time.time()
    print(f"장치: {device}")

    model = MiniRFDETR()
    c = model.config
    print("[미니 RF-DETR] 설정")
    for key, value in c.items():
        print(f"    {key:20s} {value}")
    print(f"  윈도 블록 {model.backbone.window_block_indexes}, 전역 블록 "
          f"{[i for i in range(c['vit_depth']) if i not in model.backbone.window_block_indexes]}")
    images = ShapesDataset(2, seed=1).images.float() / 255.0  # (2, 3, 96, 96)
    out_eval, out_train = shape_trace(model, images)

    mini_rows = parameter_groups(model)
    print("[매개변수] 부품별")
    print("    부품                          |    전체   | 추론 때 쓰이는 것 (묶음 1개)")
    for name, full, used in mini_rows:
        print(f"    {name:29s} | {full:9,d} | {used:9,d}")
    total = count_parameters(model)
    print(f"    {'합계':27s} | {sum(r[1] for r in mini_rows):9,d} | {sum(r[2] for r in mini_rows):9,d}")
    print(f"    check 표의 합계 = 모델 전체 매개변수 {total:,}: {sum(r[1] for r in mini_rows) == total}")

    structure_checks(model, images, out_eval, out_train)
    multi = MiniRFDETR(projector_scale=("P3", "P4", "P5")).eval()
    with torch.no_grad():
        out_multi = multi(images, return_features=True)
    print(f"[다중 스케일] projector_scale = (P3, P4, P5): spatial_shapes {out_multi['features']['spatial_shapes']}, "
          f"memory {tuple(out_multi['features']['memory'].shape)}, pred_boxes {tuple(out_multi['pred_boxes'].shape)}, "
          f"매개변수 {count_parameters(multi):,}개")

    knob_rows = knob_checks(model, device, args.quick)
    nano_rows = None if args.quick else nano_trace(args.nano_weights)

    plot_params(mini_rows, nano_rows, os.path.join(args.fig_dir, "ch10-params.png"))
    plot_proposals(os.path.join(args.fig_dir, "ch10-proposals.png"))
    plot_knobs(knob_rows, device, os.path.join(args.fig_dir, "ch10-knobs.png"))
    print(f"그림 3장 저장: {args.fig_dir}/ch10-*.png  |  전체 {time.time() - start:.1f}초")
# --8<-- [end:main]


if __name__ == "__main__":
    main()
