"""9장 · 실시간 DETR: RT-DETR 과 LW-DETR — LW-DETR 이 들여온 부품을 하나씩 만들어 본다.

무엇을 하나
  1. 윈도 어텐션과 윈도 우선 배치: 토큰을 윈도 단위로 늘어놓는 to_window_major 를 만들고, LW-DETR 논문의
     4×4 장난감 예를 그대로 출력한다. "행 우선 배치에서 층마다 순서를 바꾸는 방식" 과 "윈도 우선 배치로 한 번만
     바꾸는 방식" 의 출력이 같음을 확인하고, 어텐션 쌍의 수와 실제 시간을 잰다.
  2. 윈도 ViT 인코더 WindowedViT: 패치 임베딩 + 윈도마다 복제한 CLS 토큰 + 학습 위치 임베딩 + pre-norm 블록.
     어느 블록이 윈도 · 전역인지는 공식 구현의 규칙(꺼내는 층 번호의 여집합)으로 정하고, 여러 블록의 특징 맵을 꺼낸다.
     입력 해상도 · 패치 크기 · 윈도 수를 호출할 때마다 바꿀 수 있다 (12장의 NAS 가 쓴다).
  3. 프로젝터: ConvX · Bottleneck · C2f · 채널 우선 LayerNorm · MultiScaleProjector (공식 projector.py 와 같은 구조).
  4. IoU 인지 BCE 손실 ia_bce_loss: 손계산 예, 목표 t = p^α · IoU^(1−α) 의 곡선, 논문 식 (1) 과의 관계.
  5. Group DETR: 질의 묶음 안에서만 자기 어텐션(질의를 잘라 배치 축으로 붙이는 방식 = 어텐션 마스크 방식),
     묶음마다 따로 하는 헝가리안 매칭.
  6. 박스 재매개변수화 box_reparam: 기준 박스 크기에 비례해 움직이는 박스. 8장의 시그모이드 방식과 비교.

실행
  python ch09_lwdetr_parts.py            # 본문 결과 (노트북 GPU 약 32초 — 대부분 윈도 어텐션의 시간 측정)
  python ch09_lwdetr_parts.py --quick    # 줄인 판 (CPU 약 7초)
그림은 --fig-dir (기본 figures/) 에 저장된다. 이 파일은 학습을 하지 않는다 (체크포인트 없음).

10장 ch10_rfdetr_model.py 가 이 파일의 WindowedViT · MultiScaleProjector · box_reparam · group_self_attention 을,
11장 ch11_train.py 가 ia_bce_loss · GroupHungarianMatcher 를 가져다 쓴다.
"""

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 scipy.optimize import linear_sum_assignment

from ch02_boxes import box_cxcywh_to_xyxy, generalized_box_iou
from ch07_detr import HungarianMatcher, get_device
from ch08_deformable import inverse_sigmoid
from rf_shapes import ShapesDataset


def count_parameters(module: nn.Module) -> int:
    return sum(p.numel() for p in module.parameters())


# ── 1. 윈도 우선 배치 ────────────────────────────────────────────────────────


# --8<-- [start:window-order]
def to_window_major(tokens: torch.Tensor, grid_h: int, grid_w: int, num_windows: int) -> torch.Tensor:
    """행 우선으로 늘어선 토큰을 윈도 우선으로 다시 늘어놓고, 윈도를 배치 축으로 올린다.

    tokens: (B, H·W, C) — 토큰 격자 H×W 를 한 행씩 읽은 순서 (행 우선, row-major).
    num_windows: 한 변의 윈도 수 W_n. 격자를 W_n × W_n 개 윈도로 나눈다 (H, W 는 W_n 의 배수).
    돌려주는 값: (B·W_n², (H/W_n)·(W/W_n), C) — 윈도 하나가 배치의 한 줄. 윈도 순서도, 윈도 안 순서도 행 우선.
    """
    batch, _, channels = tokens.shape
    win_h, win_w = grid_h // num_windows, grid_w // num_windows  # 윈도 하나의 높이 · 너비 (토큰 수)
    x = tokens.view(batch, num_windows, win_h, num_windows, win_w, channels)  # (B, 윈도 행, 안쪽 행, 윈도 열, 안쪽 열, C)
    x = x.permute(0, 1, 3, 2, 4, 5)  # (B, 윈도 행, 윈도 열, 안쪽 행, 안쪽 열, C) — 여기서 순서가 바뀐다 (복사가 일어난다)
    return x.reshape(batch * num_windows**2, win_h * win_w, channels)


def from_window_major(tokens: torch.Tensor, grid_h: int, grid_w: int, num_windows: int) -> torch.Tensor:
    """to_window_major 의 역연산. (B·W_n², (H/W_n)·(W/W_n), C) → (B, H·W, C) 행 우선."""
    channels = tokens.shape[-1]
    win_h, win_w = grid_h // num_windows, grid_w // num_windows
    x = tokens.view(-1, num_windows, num_windows, win_h, win_w, channels)
    x = x.permute(0, 1, 3, 2, 4, 5)  # (B, 윈도 행, 안쪽 행, 윈도 열, 안쪽 열, C)
    return x.reshape(-1, grid_h * grid_w, channels)


def window_major_order(grid_h: int, grid_w: int, num_windows: int) -> torch.Tensor:
    """윈도 우선 배치에서 k 번째 자리에 오는 토큰의 행 우선 번호. (H·W,) LongTensor."""
    index = torch.arange(grid_h * grid_w, dtype=torch.float32).view(1, -1, 1)
    return to_window_major(index, grid_h, grid_w, num_windows).flatten().long()
# --8<-- [end:window-order]


def toy_window_order():
    """LW-DETR 논문 3.4절의 4×4 장난감 예 (식 3 – 5) 를 그대로 재현한다."""
    print("[윈도 우선 배치] LW-DETR 논문의 4×4 예, 윈도 크기 2×2 (한 변의 윈도 수 2)")
    names = [f"f{r}{c}" for r in range(1, 5) for c in range(1, 5)]  # 행 우선: f11, f12, f13, f14, f21, …
    order = window_major_order(4, 4, 2).tolist()
    print("  행 우선  :", "; ".join(", ".join(names[i:i + 4]) for i in range(0, 16, 4)))
    print("  윈도 우선:", "; ".join(", ".join(names[j] for j in order[i:i + 4]) for i in range(0, 16, 4)))
    print("  윈도 우선 자리 → 행 우선 번호:", order)
    tokens = torch.arange(16, dtype=torch.float32).view(1, 16, 1)
    windows = to_window_major(tokens, 4, 4, 2)
    back = from_window_major(windows, 4, 4, 2)
    print(f"  to_window_major: (1, 16, 1) → {tuple(windows.shape)}  (윈도 4개가 배치 축으로)")
    print(f"  check from_window_major(to_window_major(x)) = x: {torch.equal(back, tokens)}")
    return order


# ── 2. ViT 블록과 두 가지 윈도 어텐션 구현 ───────────────────────────────────


# --8<-- [start:vit-block]
class SelfAttention(nn.Module):
    """다중 머리 자기 어텐션 (5장). 입력 (B, T, C) 의 토큰 T 개가 서로를 본다 — 배치의 다른 줄은 보지 않는다.

    "윈도 어텐션" 을 위한 특별한 코드는 없다. 윈도를 배치 축에 올려 (B·윈도 수, 윈도 안 토큰 수, C) 로 넣으면
    이 모듈이 저절로 윈도 안에서만 어텐션을 한다.
    """

    def __init__(self, dim: int, heads: int):
        super().__init__()
        assert dim % heads == 0
        self.heads = heads
        self.qkv = nn.Linear(dim, 3 * dim)  # 질의 · 열쇠 · 값 투영을 한 번에
        self.proj = nn.Linear(dim, dim)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        batch, tokens, dim = x.shape
        qkv = self.qkv(x).view(batch, tokens, 3, self.heads, dim // self.heads).permute(2, 0, 3, 1, 4)
        q, k, v = qkv[0], qkv[1], qkv[2]  # 각각 (B, 머리, T, C/머리)
        out = F.scaled_dot_product_attention(q, k, v)  # softmax(QKᵀ/√d)·V — 계산량이 T² 에 비례한다
        return self.proj(out.transpose(1, 2).reshape(batch, tokens, dim))


class ViTBlock(nn.Module):
    """ViT 블록 한 개 (pre-norm): x + γ₁·어텐션(LN(x)), 이어서 x + γ₂·MLP(LN(x)).

    DINOv2 처럼 잔차 가지마다 학습되는 배율 γ (LayerScale) 가 있다. merge 인자가 윈도 · 전역을 가른다.
    """

    def __init__(self, dim: int, heads: int, mlp_ratio: float = 4.0, layer_scale: float = 1.0):
        super().__init__()
        self.norm1 = nn.LayerNorm(dim, eps=1e-6)
        self.attn = SelfAttention(dim, heads)
        self.gamma1 = nn.Parameter(torch.full((dim,), layer_scale))
        self.norm2 = nn.LayerNorm(dim, eps=1e-6)
        hidden = int(dim * mlp_ratio)
        self.mlp = nn.Sequential(nn.Linear(dim, hidden), nn.GELU(), nn.Linear(hidden, dim))
        self.gamma2 = nn.Parameter(torch.full((dim,), layer_scale))

    def forward(self, x: torch.Tensor, merge: int = 1) -> torch.Tensor:
        """x: (B', T, C).  merge = 1 이면 들어온 모양 그대로 어텐션 (윈도 우선 배치에서는 "윈도 어텐션").

        merge = m > 1 이면 배치의 이웃한 m 줄을 한 줄로 이어 붙여 (B'/m, m·T, C) 로 보고 어텐션을 한 뒤 되돌린다.
        윈도 우선 배치에서 m = 윈도 수면 "전역 어텐션" 이다. 메모리에서 이웃한 줄을 붙이는 것이라 view 만으로 된다
        (값을 옮기지 않는다) — 이것이 윈도 우선 배치의 이득이다.
        """
        shape = x.shape
        y = self.norm1(x)
        if merge > 1:
            y = y.view(shape[0] // merge, merge * shape[1], shape[2])
        y = self.attn(y).view(shape)
        x = x + self.gamma1 * y
        return x + self.gamma2 * self.mlp(self.norm2(x))
# --8<-- [end:vit-block]


# --8<-- [start:window-two-ways]
def run_blocks_row_major(blocks, tokens, grid_h, grid_w, num_windows, window_blocks):
    """(a) 행 우선 배치: 토큰은 늘 (B, H·W, C) 로 두고, 윈도 블록을 만날 때마다 순서를 바꿨다가 되돌린다 (ViTDet 방식)."""
    for i, block in enumerate(blocks):
        if i in window_blocks:
            windows = to_window_major(tokens, grid_h, grid_w, num_windows)  # 순서 바꾸기 (복사)
            tokens = from_window_major(block(windows), grid_h, grid_w, num_windows)  # 되돌리기 (복사)
        else:
            tokens = block(tokens)  # 전역 어텐션은 그대로
    return tokens


def run_blocks_window_major(blocks, tokens, grid_h, grid_w, num_windows, window_blocks):
    """(b) 윈도 우선 배치: 들어갈 때 한 번, 나올 때 한 번만 순서를 바꾼다 (LW-DETR · RF-DETR 방식).

    그 사이의 윈도 블록은 그대로, 전역 블록은 view 로 윈도 W_n² 개를 한 줄로 붙여서 계산한다.
    """
    windows = to_window_major(tokens, grid_h, grid_w, num_windows)  # (B·W_n², T_w, C)
    for i, block in enumerate(blocks):
        windows = block(windows, merge=1 if i in window_blocks else num_windows**2)
    return from_window_major(windows, grid_h, grid_w, num_windows)
# --8<-- [end:window-two-ways]


def window_checks(device, quick: bool):
    """두 방식의 출력이 같은지 확인하고, 어텐션 쌍의 수와 시간을 잰다."""
    torch.manual_seed(0)
    dim, heads, depth = 96, 4, 6
    window_blocks = {0, 1, 3, 5}  # 미니 모델과 같은 무늬: 블록 2, 4 만 전역
    blocks = nn.ModuleList(ViTBlock(dim, heads) for _ in range(depth)).to(device).eval()
    tokens = torch.randn(2, 144, dim, device=device)
    with torch.no_grad():
        out_a = run_blocks_row_major(blocks, tokens, 12, 12, 2, window_blocks)
        out_b = run_blocks_window_major(blocks, tokens, 12, 12, 2, window_blocks)
        out_g = run_blocks_row_major(blocks, tokens, 12, 12, 2, set())
    print("[윈도 어텐션] 블록 6개 (윈도 0, 1, 3, 5 / 전역 2, 4), 12×12 토큰, 윈도 2×2")
    print(f"  check (a) 행 우선 + 매번 순서 바꾸기 vs (b) 윈도 우선: 최대 차이 {float((out_a - out_b).abs().max()):.2e} "
          f"(출력 평균 절댓값 {float(out_a.abs().mean()):.3f})")
    print(f"  참고: 모든 블록을 전역으로 돌린 출력과의 차이 {float((out_a - out_g).abs().max()):.2e} (다른 계산이다)")

    print("  어텐션 한 번이 계산하는 (질의, 열쇠) 쌍의 수 — 전역 N² 과 윈도 W_n²·(N/W_n²)² = N²/W_n²")
    print("  토큰 격자 |    N |    전역 N² | 윈도 2×2 | 윈도 3×3 | 윈도 4×4")
    pair_rows = []
    for grid in (12, 24, 48):
        n = grid * grid
        row = [n * n] + [n * n // w**2 for w in (2, 3, 4)]
        pair_rows.append((grid, row))
        print(f"   {grid:3d}×{grid:<3d} | {n:4d} | {row[0]:10,d} | {row[1]:8,d} | {row[2]:8,d} | {row[3]:8,d}")

    rounds = 6 if quick else 40
    grids = (12, 24) if quick else (12, 24, 48)
    print(f"  시간 (장치 {device}, 배치 8, 블록 6개, 차원 {dim}, ms) — 세 방식을 번갈아 {rounds}바퀴 재고, "
          f"앞 {rounds // 5}바퀴를 버린 최솟값")
    print("  토큰 격자 | 전부 전역 | (a) 행 우선 + 순서 바꾸기 | (b) 윈도 우선 | (a) − (b)")
    time_rows = []
    with torch.no_grad():
        for grid in grids:
            x = torch.randn(8, grid * grid, dim, device=device)
            variants = (lambda: run_blocks_row_major(blocks, x, grid, grid, 2, set()),
                        lambda: run_blocks_row_major(blocks, x, grid, grid, 2, window_blocks),
                        lambda: run_blocks_window_major(blocks, x, grid, grid, 2, window_blocks))
            samples = [[] for _ in variants]
            for _ in range(rounds):  # 번갈아 재야 GPU 상태의 변화가 세 방식에 고르게 실린다
                for k, fn in enumerate(variants):
                    if device == "cuda":
                        torch.cuda.synchronize()
                    start = time.perf_counter()
                    fn()
                    if device == "cuda":
                        torch.cuda.synchronize()
                    samples[k].append(time.perf_counter() - start)
            t_global, t_a, t_b = (1000 * min(sample[rounds // 5:]) for sample in samples)
            time_rows.append((grid, t_global, t_a, t_b))
            print(f"   {grid:3d}×{grid:<3d} | {t_global:9.2f} | {t_a:24.2f} | {t_b:13.2f} | {t_a - t_b:+8.2f}")
    return pair_rows, time_rows


# ── 3. 윈도 ViT 인코더 ───────────────────────────────────────────────────────


# --8<-- [start:window-indexes]
def compute_window_block_indexes(out_feature_indexes, window_block_indexes=None):
    """어느 블록이 윈도 어텐션을 쓰는가 (0 부터 센 블록 번호의 목록). 공식 구현의 규칙 그대로다.

    따로 지정하지 않으면 0 … out_feature_indexes[-1] 가운데 out_feature_indexes 에 **없는** 번호가 윈도 블록이다.
    예: [3, 6, 9, 12] → 윈도 [0, 1, 2, 4, 5, 7, 8, 10, 11], 전역은 블록 3, 6, 9.
    out_feature_indexes 의 숫자 i 는 "블록 i 개를 지난 뒤의 특징" 이라는 뜻이므로 (0 = 임베딩 직후),
    특징을 꺼낸 **바로 다음** 블록이 전역 블록이 된다.
    """
    if window_block_indexes is not None:
        return sorted(window_block_indexes)
    return sorted(set(range(out_feature_indexes[-1] + 1)) - set(out_feature_indexes))
# --8<-- [end:window-indexes]


# --8<-- [start:patch-resize]
def resize_patch_embed_simple(weight: torch.Tensor, new_patch: int) -> torch.Tensor:
    """패치 임베딩 합성곱의 가중치를 다른 패치 크기로 바꾸는 가장 단순한 방법: 가중치를 그림처럼 보간한다.

    weight: (C, 3, p, p) → (C, 3, p', p').  쌍삼차 보간 뒤 (p/p')² 를 곱해, 밋밋한 패치에 대한 응답 크기를 맞춘다
    (가중치의 합이 p'²/p² 배로 늘어나는 것을 되돌린다).
    FlexiViT 는 이보다 나은 변환(보간의 유사 역행렬)을 쓴다 — 12장에서 WindowedViT.patch_resize_fn 에 끼워 넣는다.
    """
    old_patch = weight.shape[-1]
    if new_patch == old_patch:
        return weight
    resized = F.interpolate(weight, size=(new_patch, new_patch), mode="bicubic", align_corners=False, antialias=True)
    return resized * (old_patch / new_patch) ** 2
# --8<-- [end:patch-resize]


# --8<-- [start:windowed-vit]
class WindowedViT(nn.Module):
    """윈도 어텐션을 섞은 작은 ViT 인코더 (RF-DETR 백본 dinov2_with_windowed_attn.py 의 축소판).

    그림 (B, 3, H, W) → 특징 맵 목록 [(B, C, H/p, W/p), …]  (out_feature_indexes 마다 하나씩, 모두 같은 해상도).

    순서
      1) 패치 임베딩: p×p 합성곱(스트라이드 p) → 토큰 (B, h·w, C),  h = H/p, w = W/p
      2) CLS 토큰을 앞에 붙이고 학습되는 위치 임베딩을 더한다 (격자 크기가 다르면 위치 임베딩을 보간한다)
      3) 패치 토큰을 윈도 우선으로 다시 늘어놓고, CLS 토큰을 윈도마다 복제해 붙인다 → (B·W_n², 1 + h·w/W_n², C)
      4) 블록: 윈도 블록은 그대로(윈도 안에서만 어텐션), 전역 블록은 view 로 윈도를 한 줄로 붙여서
         (윈도마다의 CLS 토큰까지 모두 서로 본다)
      5) out_feature_indexes 의 층마다: 공유 LayerNorm → CLS 를 떼고 → 행 우선으로 되돌려 (B, C, h, w)

    forward 의 인자 num_windows · patch_size 와 입력 그림의 크기는 호출할 때마다 바꿀 수 있다 (가중치는 그대로).
    """

    def __init__(self, img_size: int = 96, patch_size: int = 8, dim: int = 96, depth: int = 6, heads: int = 4,
                 mlp_ratio: float = 4.0, out_feature_indexes=(2, 4, 6), num_windows: int = 2,
                 window_block_indexes=None, pos_grid: int | None = None):
        super().__init__()
        assert max(out_feature_indexes) <= depth
        self.patch_size, self.dim, self.num_windows = patch_size, dim, num_windows
        self.out_feature_indexes = list(out_feature_indexes)
        self.window_block_indexes = compute_window_block_indexes(self.out_feature_indexes, window_block_indexes)
        self.patch_embed = nn.Conv2d(3, dim, patch_size, stride=patch_size)
        self.cls_token = nn.Parameter(torch.zeros(1, 1, dim))
        self.mask_token = nn.Parameter(torch.zeros(1, dim))  # 사전 학습(마스크 그림 모델링)에서 가린 패치 자리에 넣는다
        self.pos_grid = pos_grid or img_size // patch_size  # 위치 임베딩 격자의 한 변 (기본 12)
        self.pos_embed = nn.Parameter(torch.zeros(1, 1 + self.pos_grid**2, dim))  # [CLS 자리, 격자 (행 우선)]
        self.blocks = nn.ModuleList(ViTBlock(dim, heads, mlp_ratio) for _ in range(depth))
        self.norm = nn.LayerNorm(dim, eps=1e-6)  # 꺼내는 특징마다 함께 쓰는 층 정규화
        self.patch_resize_fn = resize_patch_embed_simple  # 12장이 FlexiViT 식 변환으로 갈아 끼울 수 있다
        nn.init.trunc_normal_(self.cls_token, std=0.02)
        nn.init.trunc_normal_(self.pos_embed, std=0.02)
        for module in self.modules():
            if isinstance(module, (nn.Linear, nn.Conv2d)):
                nn.init.trunc_normal_(module.weight, std=0.02)
                nn.init.zeros_(module.bias)

    def interpolate_pos_embed(self, grid_h: int, grid_w: int) -> torch.Tensor:
        """위치 임베딩 (1, 1 + G², C) 을 h×w 격자에 맞춘다. 격자가 같으면 그대로, 다르면 쌍삼차 보간 (CLS 자리는 그대로)."""
        if grid_h == self.pos_grid and grid_w == self.pos_grid:
            return self.pos_embed
        cls_pos, patch_pos = self.pos_embed[:, :1], self.pos_embed[:, 1:]
        patch_pos = patch_pos.reshape(1, self.pos_grid, self.pos_grid, self.dim).permute(0, 3, 1, 2)  # (1, C, G, G)
        patch_pos = F.interpolate(patch_pos, size=(grid_h, grid_w), mode="bicubic", align_corners=False,
                                  antialias=True)
        return torch.cat([cls_pos, patch_pos.permute(0, 2, 3, 1).reshape(1, grid_h * grid_w, self.dim)], dim=1)

    def embed(self, images: torch.Tensor, patch_size: int | None = None, mask: torch.Tensor | None = None):
        """1) – 2) 단계. 돌려주는 값: 토큰 (B, 1 + h·w, C) — 행 우선, 맨 앞이 CLS — 와 격자 크기 (h, w).

        mask: (B, h·w) bool — True 인 패치의 임베딩을 mask_token 으로 바꾼다 (11장의 사전 학습용).
        """
        patch_size = patch_size or self.patch_size
        batch, _, height, width = images.shape
        assert height % patch_size == 0 and width % patch_size == 0, "그림 크기는 패치 크기의 배수여야 한다"
        weight = self.patch_resize_fn(self.patch_embed.weight, patch_size)  # 기본 패치 크기면 그대로
        x = F.conv2d((images - 0.5) / 0.25, weight, self.patch_embed.bias, stride=patch_size)  # (B, C, h, w)
        grid_h, grid_w = x.shape[-2:]
        x = x.flatten(2).transpose(1, 2)  # (B, h·w, C) 행 우선
        if mask is not None:
            x = torch.where(mask[..., None], self.mask_token.to(x.dtype)[None], x)
        x = torch.cat([self.cls_token.expand(batch, -1, -1), x], dim=1)  # (B, 1 + h·w, C)
        return x + self.interpolate_pos_embed(grid_h, grid_w), (grid_h, grid_w)

    def forward(self, images: torch.Tensor, num_windows: int | None = None, patch_size: int | None = None,
                mask: torch.Tensor | None = None):
        """images: (B, 3, H, W), 값 0 – 1.  돌려주는 값: 길이 len(out_feature_indexes) 의 목록, 각각 (B, C, h, w)."""
        num_windows = num_windows or self.num_windows
        x, (grid_h, grid_w) = self.embed(images, patch_size, mask)
        batch = x.shape[0]
        assert grid_h % num_windows == 0 and grid_w % num_windows == 0, "토큰 격자는 윈도 수의 배수여야 한다"
        # 3) 윈도 우선 배치. CLS 는 위치 임베딩까지 더한 것을 윈도마다 한 벌씩 복제한다 (윈도가 많을수록 CLS 도 많다)
        cls, patches = x[:, :1], x[:, 1:]
        patches = to_window_major(patches, grid_h, grid_w, num_windows)  # (B·W_n², T_w, C)
        cls = cls.repeat_interleave(num_windows**2, dim=0)  # (B·W_n², 1, C)
        x = torch.cat([cls, patches], dim=1)  # (B·W_n², 1 + T_w, C)
        # 4) 블록
        features = []
        for i, block in enumerate(self.blocks):
            if i >= self.out_feature_indexes[-1]:
                break  # 마지막으로 꺼낼 특징 뒤의 블록은 돌릴 필요가 없다
            x = block(x, merge=1 if i in self.window_block_indexes else num_windows**2)
            if i + 1 in self.out_feature_indexes:  # 5) "블록 i+1 개를 지난 뒤" 의 특징을 꺼낸다
                tokens = self.norm(x)[:, 1:]  # CLS 를 뗀다: (B·W_n², T_w, C)
                tokens = from_window_major(tokens, grid_h, grid_w, num_windows)  # (B, h·w, C) 행 우선
                features.append(tokens.transpose(1, 2).reshape(batch, self.dim, grid_h, grid_w))
        return features
# --8<-- [end:windowed-vit]


def influence_map(vit: WindowedViT, image: torch.Tensor, token: tuple, feature: int = -1) -> np.ndarray:
    """출력 특징 맵의 한 칸이 입력의 어느 패치에 영향을 받는가: 그 칸의 출력을 입력으로 미분한 크기 (h, w).

    층 정규화를 거친 출력은 채널 합이 늘 0 이라 합을 미분하면 0 이 된다. 그래서 고정된 무작위 방향 10개로
    내적한 값을 각각 미분해 절댓값을 더한다.
    """
    image = image.clone().requires_grad_(True)
    out = vit(image[None])[feature][0, :, token[0], token[1]]  # (C,)
    directions = torch.randn(10, out.shape[0], generator=torch.Generator().manual_seed(0))
    grad = torch.zeros_like(image)
    for direction in directions:
        grad += torch.autograd.grad((out * direction).sum(), image, retain_graph=True)[0].abs()
    patch = vit.patch_size
    return grad.sum(0).unfold(0, patch, patch).unfold(1, patch, patch).sum((-1, -2)).numpy()


def vit_checks():
    """WindowedViT 의 모양 추적과 "윈도 밖으로 정보가 새는가" 확인."""
    torch.manual_seed(0)
    vit = WindowedViT().eval()
    images = torch.rand(2, 3, 96, 96)
    print("[WindowedViT] 기본 설정: 그림 96, 패치 8, 차원 96, 블록 6, 머리 4, 꺼내는 층 [2, 4, 6], 윈도 2×2")
    print(f"  윈도 블록 {vit.window_block_indexes}, 전역 블록 "
          f"{[i for i in range(len(vit.blocks)) if i not in vit.window_block_indexes]}, "
          f"매개변수 {count_parameters(vit):,}개")
    print(f"  공식 규칙 확인: compute_window_block_indexes([3, 6, 9, 12]) = {compute_window_block_indexes([3, 6, 9, 12])}")
    tokens, grid = vit.embed(images)
    patches = to_window_major(tokens[:, 1:], *grid, 2)
    print("  모양 추적 (B = 2)")
    print(f"    그림                         {tuple(images.shape)}")
    print(f"    패치 임베딩 + CLS + 위치      {tuple(tokens.shape)}   (1 + 12·12 토큰)")
    print(f"    윈도 우선 재배열 (패치만)     {tuple(patches.shape)}    (B·4 윈도, 6·6 토큰)")
    print(f"    윈도마다 CLS 를 붙인 뒤       {(patches.shape[0], patches.shape[1] + 1, patches.shape[2])}    ← 윈도 블록의 입력")
    print(f"    전역 블록 안에서의 view       {(2, 4 * (patches.shape[1] + 1), patches.shape[2])}   (4·37 토큰: CLS 4개 포함)")
    with torch.no_grad():
        features = vit(images)
    print(f"    꺼낸 특징 맵 {len(features)}개              각각 {tuple(features[0].shape)}")

    # 윈도 블록만 있으면 한 윈도의 입력을 바꿔도 다른 윈도의 출력은 그대로여야 한다
    only_window = WindowedViT(window_block_indexes=range(6)).eval()
    changed = images.clone()
    changed[:, :, :48, :48] = torch.rand(2, 3, 48, 48)  # 왼쪽 위 윈도(격자 0 – 5 행 · 열)만 바꾼다
    with torch.no_grad():
        diff_window = (only_window(changed)[-1] - only_window(images)[-1]).abs().amax(dim=(0, 1))  # (12, 12)
        diff_mixed = (vit(changed)[-1] - vit(images)[-1]).abs().amax(dim=(0, 1))
    outside = torch.ones(12, 12, dtype=torch.bool)
    outside[:6, :6] = False
    print("  왼쪽 위 윈도의 픽셀만 바꿨을 때, 마지막 특징 맵에서 **다른 윈도** 칸의 최대 변화")
    print(f"    check 윈도 블록만 6개: {float(diff_window[outside].max()):.2e} (0 이어야 한다),  "
          f"바꾼 윈도 안: {float(diff_window[~outside].max()):.3f}")
    print(f"    윈도 + 전역 (기본): {float(diff_mixed[outside].max()):.3f}  ← 전역 블록이 윈도 사이로 정보를 나른다")

    # 손잡이: 해상도 · 패치 크기 · 윈도 수를 바꿔도 같은 가중치로 돌아간다
    print("  손잡이 (가중치는 그대로, 호출 인자만 바꿈)")
    with torch.no_grad():
        for size, patch, windows in ((96, 8, 2), (96, 8, 1), (96, 8, 3), (64, 8, 2), (128, 8, 2), (96, 12, 2),
                                     (96, 6, 2), (96, 16, 1)):
            out = vit(torch.rand(1, 3, size, size), num_windows=windows, patch_size=patch)[-1]
            grid_size = size // patch
            note = "" if grid_size == vit.pos_grid else " (위치 임베딩 보간)"
            note += "" if patch == vit.patch_size else " (패치 임베딩 보간)"
            print(f"    해상도 {size:3d}, 패치 {patch:2d}, 윈도 {windows}×{windows} → 특징 맵 {tuple(out.shape)}{note}")
    return vit


# ── 4. 프로젝터 ──────────────────────────────────────────────────────────────


# --8<-- [start:projector-parts]
class ChannelLayerNorm(nn.Module):
    """(B, C, H, W) 특징 맵용 층 정규화: 칸마다 채널 C 개에 걸쳐 평균 0 · 분산 1 로 맞춘다.

    nn.LayerNorm 은 마지막 축을 정규화하므로, 채널 축을 맨 뒤로 보냈다가 되돌린다.
    배치 정규화와 달리 배치의 다른 그림을 보지 않는다 → 배치가 작아도 (기울기 누적을 써도) 동작이 같다.
    """

    def __init__(self, channels: int, eps: float = 1e-6):
        super().__init__()
        self.weight = nn.Parameter(torch.ones(channels))
        self.bias = nn.Parameter(torch.zeros(channels))
        self.eps = eps

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = F.layer_norm(x.permute(0, 2, 3, 1), self.weight.shape, self.weight, self.bias, self.eps)
        return x.permute(0, 3, 1, 2)


class ConvX(nn.Module):
    """합성곱(편향 없음) → 정규화 → 활성 함수. layer_norm=True 면 층 정규화(RF-DETR), False 면 배치 정규화(LW-DETR)."""

    def __init__(self, cin: int, cout: int, kernel: int = 3, stride: int = 1, act: str = "relu",
                 layer_norm: bool = True):
        super().__init__()
        self.conv = nn.Conv2d(cin, cout, kernel, stride, padding=kernel // 2, bias=False)
        self.bn = ChannelLayerNorm(cout) if layer_norm else nn.BatchNorm2d(cout)  # 이름은 공식 구현을 따라 bn
        self.act = nn.SiLU() if act == "silu" else nn.ReLU()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.act(self.bn(self.conv(x)))


class Bottleneck(nn.Module):
    """3×3 ConvX 두 번. shortcut=True 이고 채널 수가 같으면 입력을 더한다 (C2f 안에서는 기본이 False)."""

    def __init__(self, c1: int, c2: int, shortcut: bool = True, e: float = 0.5, act: str = "silu",
                 layer_norm: bool = True):
        super().__init__()
        hidden = int(c2 * e)
        self.cv1 = ConvX(c1, hidden, 3, act=act, layer_norm=layer_norm)
        self.cv2 = ConvX(hidden, c2, 3, act=act, layer_norm=layer_norm)
        self.add = shortcut and c1 == c2

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))


class C2f(nn.Module):
    """C2f 블록 (YOLOv8). 입력 (B, c1, H, W) → 출력 (B, c2, H, W), 해상도는 그대로.

    1) 1×1 ConvX 로 2c 채널 (c = c2/2) → 반씩 둘로 나눈다: y₀, y₁
    2) 병목 n 개를 차례로: y₂ = m₁(y₁), y₃ = m₂(y₂), …
    3) y₀ … y_{n+1} 을 모두 채널 방향으로 이어 붙여 ((2 + n)·c 채널) 1×1 ConvX 로 c2 채널
    중간 결과를 전부 마지막에 모으므로, 얕은 경로와 깊은 경로의 특징이 함께 쓰인다.
    """

    def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = False, e: float = 0.5, act: str = "silu",
                 layer_norm: bool = True):
        super().__init__()
        self.c = int(c2 * e)
        self.cv1 = ConvX(c1, 2 * self.c, 1, act=act, layer_norm=layer_norm)
        self.cv2 = ConvX((2 + n) * self.c, c2, 1, act=act, layer_norm=layer_norm)
        self.m = nn.ModuleList(Bottleneck(self.c, self.c, shortcut, e=1.0, act=act, layer_norm=layer_norm)
                               for _ in range(n))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        y = list(self.cv1(x).split((self.c, self.c), dim=1))
        y.extend(m(y[-1]) for m in self.m)
        return self.cv2(torch.cat(y, dim=1))
# --8<-- [end:projector-parts]


# --8<-- [start:projector]
SCALE_FACTORS = {"P3": 2.0, "P4": 1.0, "P5": 0.5}  # ViT 특징 맵(P4) 기준의 배율


class MultiScaleProjector(nn.Module):
    """ViT 의 여러 층 특징 맵을 받아 디코더가 읽을 특징 맵(들)을 만든다 (공식 projector.py 와 같은 구조).

    입력: 목록 [(B, C_j, h, w), …] — 모두 같은 해상도 (ViT 는 층이 달라도 해상도가 같다).
    scale_factors 의 배율마다 한 단계(stage)씩:
      배율 2.0 (P3): 입력마다 전치 합성곱(2×2, 스트라이드 2)으로 2배 키우고 채널은 절반
      배율 1.0 (P4): 그대로
      배율 0.5 (P5): 입력마다 3×3 스트라이드 2 ConvX 로 절반
      → 입력들을 채널 방향으로 이어 붙임 → C2f(num_blocks) → 층 정규화
    돌려주는 값: 목록 [(B, out_channels, h·배율, w·배율), …]  (배율 순서대로).
    RF-DETR 의 기본은 P4 한 단계뿐이다 (단일 스케일).
    """

    def __init__(self, in_channels, out_channels: int, scale_factors=(1.0,), num_blocks: int = 3,
                 layer_norm: bool = True):
        super().__init__()
        self.scale_factors = list(scale_factors)
        sampling, stages = [], []
        for scale in self.scale_factors:
            layers = []
            for cin in in_channels:
                if scale == 2.0:
                    layers.append(nn.Sequential(nn.ConvTranspose2d(cin, cin // 2, kernel_size=2, stride=2)))
                elif scale == 1.0:
                    layers.append(nn.Sequential())
                elif scale == 0.5:
                    layers.append(nn.Sequential(ConvX(cin, cin, 3, 2, layer_norm=layer_norm)))
                else:
                    raise NotImplementedError(f"지원하지 않는 배율: {scale}")
            sampling.append(nn.ModuleList(layers))
            fused = sum(cin // 2 if scale == 2.0 else cin for cin in in_channels)
            stages.append(nn.Sequential(C2f(fused, out_channels, num_blocks, layer_norm=layer_norm),
                                        ChannelLayerNorm(out_channels)))
        self.stages_sampling = nn.ModuleList(sampling)
        self.stages = nn.ModuleList(stages)

    def forward(self, features):
        results = []
        for sampling, stage in zip(self.stages_sampling, self.stages):
            fused = torch.cat([layer(x) for layer, x in zip(sampling, features)], dim=1)  # 여러 층을 채널로 잇는다
            results.append(stage(fused))
        return results
# --8<-- [end:projector]


def projector_checks(vit: WindowedViT):
    torch.manual_seed(0)
    with torch.no_grad():
        features = vit(torch.rand(2, 3, 96, 96))
    print("[프로젝터] 입력: WindowedViT 의 특징 맵 3개, 각각", tuple(features[0].shape))
    projector = MultiScaleProjector([96, 96, 96], 128, scale_factors=[1.0]).eval()
    stage = projector.stages[0][0]  # C2f
    with torch.no_grad():
        fused = torch.cat(features, dim=1)
        y = list(stage.cv1(fused).split((stage.c, stage.c), dim=1))
        print("  P4 한 단계의 모양 추적 (out_channels = 128, 병목 3개)")
        print(f"    세 층을 채널로 이어 붙임         {tuple(fused.shape)}")
        print(f"    cv1 (1×1) → 2c = {2 * stage.c} 채널       {tuple(stage.cv1(fused).shape)} → 둘로 나눔: 각각 {tuple(y[0].shape)}")
        for k, m in enumerate(stage.m):
            y.append(m(y[-1]))
            print(f"    병목 {k + 1} (3×3 두 번)              {tuple(y[-1].shape)}")
        joined = torch.cat(y, dim=1)
        print(f"    모두 이어 붙임 (2 + 3)·c         {tuple(joined.shape)}")
        print(f"    cv2 (1×1) → 층 정규화            {tuple(projector(features)[0].shape)}")
        manual = projector.stages[0][1](stage.cv2(joined))
        print(f"    check 단계별 계산 = projector(features): 최대 차이 "
              f"{float((manual - projector(features)[0]).abs().max()):.2e}")
    print(f"    매개변수 {count_parameters(projector):,}개")
    for names in (["P3", "P4"], ["P3", "P4", "P5"]):
        multi = MultiScaleProjector([96, 96, 96], 128, [SCALE_FACTORS[n] for n in names]).eval()
        with torch.no_grad():
            shapes = [tuple(o.shape) for o in multi(features)]
        print(f"  {' · '.join(names)}: 출력 {shapes}, 매개변수 {count_parameters(multi):,}개")
    x = torch.randn(2, 8, 5, 7)
    norm = ChannelLayerNorm(8)
    reference = F.layer_norm(x.permute(0, 2, 3, 1), (8,), eps=1e-6).permute(0, 3, 1, 2)
    y = norm(x).detach()
    print(f"  check ChannelLayerNorm vs F.layer_norm: 최대 차이 {float((y - reference).abs().max()):.2e}, "
          f"칸마다 채널 평균 {float(y.mean(1).abs().max()):.1e} · 표준편차 {float(y.std(1, unbiased=False).mean()):.4f}")


# ── 5. IoU 인지 BCE 손실 ─────────────────────────────────────────────────────


# --8<-- [start:ia-bce]
def ia_bce_loss(logits: torch.Tensor, matched, tgt_classes: torch.Tensor, ious: torch.Tensor, num_boxes: float,
                alpha: float = 0.25, gamma: float = 2.0) -> torch.Tensor:
    """IoU 인지 BCE 손실 (IA-BCE). RF-DETR 공식 구현 criterion.py 의 loss_labels (ia_bce_loss=True) 와 같은 계산.

    logits       (B, N, K)  클래스별 로짓 (시그모이드 방식, ∅ 칸 없음)
    matched      (batch_idx, query_idx) — 각각 (M,). 매칭된 예측은 logits[batch_idx[k], query_idx[k]]
    tgt_classes  (M,)  그 예측의 짝인 정답의 클래스
    ious         (M,)  그 예측 박스와 짝 정답 박스의 IoU (기울기 없음)
    num_boxes    손실을 나눌 수 (배치의 정답 수 × 질의 묶음 수)

    p = σ(로짓). 칸 (b, n, c) 마다
      매칭된 칸 (짝 정답의 클래스 칸):  목표 t = p^α · IoU^(1−α)  (최소 0.01, 기울기 차단)
                                        손실 = −t·log p − (1 − t)·log(1 − p)          ← 목표가 t 인 BCE
      그 밖의 모든 칸:                  손실 = −p^γ · log(1 − p)                        ← p^γ 로 가중한 "목표 0" BCE
    전부 더해 num_boxes 로 나눈다.
    """
    prob = logits.sigmoid()
    batch_idx, query_idx = matched
    pos_weights = torch.zeros_like(logits)  # log p 에 곱할 가중치: 매칭된 칸만 t, 나머지 0
    neg_weights = prob**gamma  # log(1 − p) 에 곱할 가중치: 기본 p^γ (기울기가 흐른다)
    target = prob[batch_idx, query_idx, tgt_classes].pow(alpha) * ious.pow(1 - alpha)
    target = target.clamp(min=0.01).detach()  # 목표는 상수로 본다 (기울기 차단)
    pos_weights[batch_idx, query_idx, tgt_classes] = target
    neg_weights[batch_idx, query_idx, tgt_classes] = 1 - target
    # −pos·log p − neg·log(1 − p) 를 수치적으로 안정되게: log(1 − p) = log σ(−x) = log σ(x) − x
    loss = neg_weights * logits - F.logsigmoid(logits) * (pos_weights + neg_weights)
    return loss.sum() / num_boxes
# --8<-- [end:ia-bce]


def ia_bce_checks():
    """손계산 예와 정의대로 다시 계산한 값의 대조."""
    alpha, gamma = 0.25, 2.0
    print("[IA-BCE] 손계산 예: 질의 3개 × 클래스 3개. 질의 0 ↔ 정답(클래스 1, IoU 0.80), 질의 1 ↔ 정답(클래스 0, IoU 0.50)")
    prob = torch.tensor([[0.10, 0.60, 0.05], [0.90, 0.20, 0.02], [0.03, 0.40, 0.01]])
    logits = torch.log(prob / (1 - prob))[None]  # (1, 3, 3)
    matched = (torch.tensor([0, 0]), torch.tensor([0, 1]))
    tgt_classes, ious = torch.tensor([1, 0]), torch.tensor([0.80, 0.50])
    for q in range(3):
        print(f"  질의 {q} 의 p = " + ", ".join(f"{float(v):.2f}" for v in prob[q]))
    total = 0.0
    for q, c, u in ((0, 1, 0.80), (1, 0, 0.50)):
        p = float(prob[q, c])
        t = p**alpha * u ** (1 - alpha)
        loss = -t * math.log(p) - (1 - t) * math.log(1 - p)
        total += loss
        print(f"  매칭된 칸 (질의 {q}, 클래스 {c}): p = {p:.2f}, IoU = {u:.2f} → t = {p:.2f}^0.25 · {u:.2f}^0.75 = "
              f"{p**alpha:.4f} · {u ** (1 - alpha):.4f} = {t:.4f}")
        print(f"      손실 = −t·log p − (1 − t)·log(1 − p) = {-t * math.log(p):.4f} + {-(1 - t) * math.log(1 - p):.4f} = {loss:.4f}")
    negative = 0.0
    for q in range(3):
        for c in range(3):
            if (q, c) in ((0, 1), (1, 0)):
                continue
            p = float(prob[q, c])
            term = -(p**gamma) * math.log(1 - p)
            negative += term
            if p >= 0.2:
                print(f"  그 밖의 칸 (질의 {q}, 클래스 {c}): p = {p:.2f} → −p²·log(1 − p) = {p**2:.4f} · {-math.log(1 - p):.4f} = {term:.4f}")
    print(f"  그 밖의 칸 7개의 합 = {negative:.4f} (p 가 작은 칸은 거의 0)")
    mine = float(ia_bce_loss(logits, matched, tgt_classes, ious, num_boxes=2.0))
    print(f"  전체 = ({total:.4f} + {negative:.4f}) / 정답 2개 = {(total + negative) / 2:.4f}")
    print(f"  check 손계산 {(total + negative) / 2:.6f} vs ia_bce_loss {mine:.6f}")

    # 무작위 입력에서, 정의(−pos·log p − neg·log(1−p))를 F.binary_cross_entropy 로 다시 계산해 대조
    generator = torch.Generator().manual_seed(0)
    logits = torch.randn(4, 12, 3, generator=generator) * 2
    batch_idx = torch.tensor([0, 0, 1, 2, 2, 2, 3])
    query_idx = torch.tensor([3, 7, 0, 1, 5, 9, 11])
    tgt_classes = torch.randint(0, 3, (7,), generator=generator)
    ious = torch.rand(7, generator=generator)
    prob = logits.sigmoid()
    t = (prob[batch_idx, query_idx, tgt_classes] ** alpha * ious ** (1 - alpha)).clamp(min=0.01)
    soft_target = torch.zeros_like(prob)
    soft_target[batch_idx, query_idx, tgt_classes] = t
    is_matched = torch.zeros_like(prob, dtype=torch.bool)
    is_matched[batch_idx, query_idx, tgt_classes] = True
    bce = F.binary_cross_entropy(prob, soft_target, reduction="none")  # 매칭된 칸: 목표 t, 나머지: 목표 0
    reference = torch.where(is_matched, bce, prob**gamma * bce).sum() / 7
    mine = ia_bce_loss(logits, (batch_idx, query_idx), tgt_classes, ious, num_boxes=7.0)
    print(f"  check 무작위 (4, 12, 3) 로짓: ia_bce_loss {float(mine):.6f} vs F.binary_cross_entropy 로 다시 계산 "
          f"{float(reference):.6f} (차이 {abs(float(mine - reference)):.2e})")

    # 목표가 고정일 때 BCE 의 기울기는 p − t. p = IoU 에서 t = p 가 되어 기울기가 0 이다 → 점수가 IoU 로 끌려간다
    for u in (0.5, 0.9):
        points = []
        for p0 in (0.2, u, 0.95):
            x = torch.log(torch.tensor([[[p0 / (1 - p0)]]])).requires_grad_(True)
            loss = ia_bce_loss(x, (torch.tensor([0]), torch.tensor([0])), torch.tensor([0]), torch.tensor([u]), 1.0)
            grad, = torch.autograd.grad(loss, x)
            points.append(f"p = {p0:.2f}: t = {p0**alpha * u ** (1 - alpha):.4f}, ∂손실/∂로짓 = {float(grad):+.4f}")
        print(f"  IoU = {u}: " + " | ".join(points))
    print("  → 로짓에 대한 기울기는 p − t. p < IoU 면 음수(점수를 올린다), p > IoU 면 양수(내린다), p = IoU 에서 0.")


# ── 6. Group DETR ────────────────────────────────────────────────────────────


# --8<-- [start:group-attn]
def group_self_attention(attn: nn.MultiheadAttention, query: torch.Tensor, value: torch.Tensor, groups: int):
    """질의 묶음 안에서만 하는 자기 어텐션 (Group DETR). RF-DETR 공식 디코더 층이 학습 때 하는 방식 그대로다.

    query (B, G·N, D): 질의 + 위치 임베딩 (질의 · 열쇠로 쓴다).  value (B, G·N, D): 질의 (값으로 쓴다).
    질의 G·N 개를 N 개씩 G 묶음으로 잘라 **배치 축**으로 이어 붙이면 (G·B, N, D) —
    어텐션은 배치의 다른 줄을 보지 않으므로, 저절로 같은 묶음의 질의끼리만 서로 본다.
    돌려주는 값: (B, G·N, D).  groups = 1 이면 보통의 자기 어텐션과 같다 (추론).
    """
    batch, total, _ = query.shape
    if groups > 1:
        query = torch.cat(query.split(total // groups, dim=1), dim=0)  # (G·B, N, D): [묶음 0 의 B 줄, 묶음 1 의 B 줄, …]
        value = torch.cat(value.split(total // groups, dim=1), dim=0)
    out = attn(query, query, value, need_weights=False)[0]
    if groups > 1:
        out = torch.cat(out.split(batch, dim=0), dim=1)  # (B, G·N, D) 로 되돌린다
    return out


def group_attention_mask(num_queries: int, groups: int) -> torch.Tensor:
    """같은 일을 어텐션 마스크로 한다면: (G·N, G·N) bool, True = "보지 못하게 막는다". 대각선 블록만 False."""
    group_id = torch.arange(num_queries * groups) // num_queries
    return group_id[:, None] != group_id[None, :]
# --8<-- [end:group-attn]


# --8<-- [start:group-matcher]
class GroupHungarianMatcher(HungarianMatcher):
    """묶음마다 따로 하는 헝가리안 매칭. 7장 HungarianMatcher (포컬 꼴 비용) 에 묶음 나누기만 더했다.

    예측 G·N 개를 N 개씩 G 묶음으로 나누고, 묶음마다 그림의 정답 전체와 일대일 매칭을 푼다.
    → 정답 하나가 묶음마다 한 번씩, 모두 G 번 짝을 얻는다 (학습 신호가 G 배). 추론 때는 묶음이 하나뿐이다.
    """

    def __init__(self, cost_class: float = 2.0, cost_bbox: float = 5.0, cost_giou: float = 2.0):
        super().__init__(cost_class, cost_bbox, cost_giou, class_cost="focal")

    @torch.no_grad()
    def cost_parts(self, logits, boxes, tgt_labels, tgt_boxes):
        """7장과 같은 세 비용 (포컬 꼴 분류 비용, L1, −GIoU), 각각 (Q, T). L1 만 torch.cdist 대신 뺄셈으로 계산한다

        (값은 같고, 이렇게 작은 행렬에서는 GPU 에서 훨씬 빠르다 — 학습 스텝마다 불리므로 차이가 쌓인다).
        """
        prob = logits.sigmoid()[:, tgt_labels]  # (Q, T): 열 j 는 정답 j 의 클래스에 준 확률
        alpha, gamma = self.focal_alpha, self.focal_gamma
        c_cls = (alpha * (1 - prob) ** gamma * (-(prob + 1e-8).log())
                 - (1 - alpha) * prob**gamma * (-(1 - prob + 1e-8).log()))
        c_l1 = (boxes[:, None] - tgt_boxes[None]).abs().sum(-1)
        c_giou = -generalized_box_iou(box_cxcywh_to_xyxy(boxes), box_cxcywh_to_xyxy(tgt_boxes))
        return c_cls, c_l1, c_giou

    @staticmethod
    def assign_groups(cost: np.ndarray, group_detr: int):
        """그림 한 장의 비용 행렬 (G·N, T) 을 묶음별로 잘라 각각 헝가리안 풀이를 한다.

        돌려주는 값: (예측 번호 (G·T,), 정답 번호 (G·T,)) — 예측 번호는 0 … G·N−1.
        """
        per_group = cost.shape[0] // group_detr
        rows, cols = [], []
        for g in range(group_detr):
            r, c = linear_sum_assignment(cost[g * per_group:(g + 1) * per_group])  # 묶음 g 안에서만 푼다
            rows.append(r + g * per_group)
            cols.append(c)
        return np.concatenate(rows), np.concatenate(cols)

    @torch.no_grad()
    def forward(self, outputs, targets, group_detr: int = 1):
        """outputs: {"pred_logits": (B, G·N, K), "pred_boxes": (B, G·N, 4)}.

        돌려주는 값: 길이 B 의 목록. b 번째는 (pred_idx, tgt_idx) — 길이 G·T_b. pred_idx 는 0 … G·N−1 의 번호.
        """
        batch, total = outputs["pred_logits"].shape[:2]
        sizes = [len(t["labels"]) for t in targets]
        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, total, -1).cpu().numpy()  # (B, G·N, ΣT)
        offsets = np.cumsum([0] + sizes)
        indices = []
        for b in range(batch):  # block: (G·N, T_b) — 이 그림의 예측 × 이 그림의 정답
            rows, cols = self.assign_groups(cost[b, :, offsets[b]:offsets[b + 1]], group_detr)
            indices.append((torch.as_tensor(rows, dtype=torch.long), torch.as_tensor(cols, dtype=torch.long)))
        return indices
# --8<-- [end:group-matcher]


def group_checks():
    torch.manual_seed(0)
    dim, heads, num_queries, groups, batch = 32, 4, 3, 2, 2
    attn = nn.MultiheadAttention(dim, heads, batch_first=True).eval()
    tgt = torch.randn(batch, groups * num_queries, dim)
    pos = torch.randn(batch, groups * num_queries, dim)
    mask = group_attention_mask(num_queries, groups)
    print(f"[Group DETR] 질의 {num_queries}개 × 묶음 {groups}개의 어텐션 마스크 (1 = 막음)")
    for row in mask.int().tolist():
        print("   ", row)
    with torch.no_grad():
        by_split = group_self_attention(attn, tgt + pos, tgt, groups)
        by_mask = attn(tgt + pos, tgt + pos, tgt, attn_mask=mask, need_weights=False)[0]
        plain = attn(tgt + pos, tgt + pos, tgt, need_weights=False)[0]
    print(f"  check 질의를 잘라 배치로 붙이는 방식 vs 마스크 방식: 최대 차이 {float((by_split - by_mask).abs().max()):.2e}")
    print(f"  참고: 마스크 없는 보통 자기 어텐션과의 차이 {float((by_split - plain).abs().max()):.3f} (다른 계산이다)")
    with torch.no_grad():
        first = group_self_attention(attn, (tgt + pos)[:, :num_queries], tgt[:, :num_queries], 1)
    print(f"  check 첫 묶음만 떼어 따로 돌린 결과 = 묶음 학습 때의 첫 묶음 출력: 최대 차이 "
          f"{float((first - by_split[:, :num_queries]).abs().max()):.2e}  → 추론 때 첫 묶음만 써도 된다")

    # 묶음별 매칭: 정답마다 묶음 수만큼 짝이 생긴다
    generator = torch.Generator().manual_seed(1)
    groups, num_queries = 4, 12
    outputs = {"pred_logits": torch.randn(2, groups * num_queries, 3, generator=generator),
               "pred_boxes": torch.rand(2, groups * num_queries, 4, generator=generator) * 0.4 + 0.2}
    targets = [{"labels": torch.tensor([0, 2]), "boxes": torch.tensor([[0.3, 0.3, 0.2, 0.2], [0.7, 0.6, 0.3, 0.2]])},
               {"labels": torch.tensor([1, 1, 0]),
                "boxes": torch.tensor([[0.2, 0.7, 0.2, 0.3], [0.5, 0.5, 0.3, 0.3], [0.8, 0.2, 0.2, 0.2]])}]
    matcher = GroupHungarianMatcher()
    indices = matcher(outputs, targets, group_detr=groups)
    print(f"  묶음별 매칭 (질의 {num_queries} × 묶음 {groups}, 그림 2장 · 정답 2개 / 3개)")
    for b, (pred_idx, tgt_idx) in enumerate(indices):
        pairs = [f"{int(p)}(묶음 {int(p) // num_queries})→정답 {int(t)}" for p, t in zip(pred_idx, tgt_idx)]
        print(f"    그림 {b}: 짝 {len(pred_idx)}개 = 정답 {len(targets[b]['labels'])}개 × 묶음 {groups}개:", ", ".join(pairs))
    single = HungarianMatcher(2.0, 5.0, 2.0, class_cost="focal")
    same = True
    for g in range(groups):
        part = {k: v[:, g * num_queries:(g + 1) * num_queries] for k, v in outputs.items()}
        for b, (rows, cols) in enumerate(single(part, targets)):
            keep = indices[b][0] // num_queries == g
            same &= torch.equal(indices[b][0][keep] - g * num_queries, rows) and torch.equal(indices[b][1][keep], cols)
    print(f"  check 묶음을 하나씩 떼어 7장 HungarianMatcher 로 매칭한 결과와 같은가: {same}")


# ── 7. 박스 재매개변수화 ─────────────────────────────────────────────────────


# --8<-- [start:reparam]
def box_reparam(delta: torch.Tensor, reference: torch.Tensor) -> torch.Tensor:
    """박스 재매개변수화: 머리가 낸 델타 (δx, δy, δw, δh) 로 기준 박스 (cx, cy, w, h) 를 고친다.

      cx' = δx · w + cx        cy' = δy · h + cy        (중심은 "기준 박스 크기의 몇 배" 만큼 움직인다)
      w'  = exp(δw) · w        h'  = exp(δh) · h        (크기는 "몇 배" 로 바뀐다)

    delta · reference: (..., 4), 기준 박스는 정규화 좌표 (로짓 아님). 시그모이드를 거치지 않으므로 결과가 0 – 1 을
    벗어날 수 있다. δ = 0 이면 기준 박스 그대로다.
    """
    cxcy = delta[..., :2] * reference[..., 2:] + reference[..., :2]
    wh = delta[..., 2:].exp() * reference[..., 2:]
    return torch.cat([cxcy, wh], dim=-1)


def box_reparam_inverse(box: torch.Tensor, reference: torch.Tensor) -> torch.Tensor:
    """box_reparam 의 역: 기준 박스를 box 로 옮기는 델타. (머리가 맞혀야 하는 값이 얼마인지 볼 때 쓴다.)"""
    return torch.cat([(box[..., :2] - reference[..., :2]) / reference[..., 2:],
                      (box[..., 2:] / reference[..., 2:]).log()], dim=-1)


def box_sigmoid_update(delta: torch.Tensor, reference: torch.Tensor) -> torch.Tensor:
    """비교용 — 8장(Deformable DETR)의 방식: 로짓 공간에서 더하고 시그모이드. σ(δ + σ⁻¹(기준 박스))."""
    return (delta + inverse_sigmoid(reference)).sigmoid()
# --8<-- [end:reparam]


def fmt_box(box) -> str:
    return ", ".join(f"{float(v):.4f}" for v in box)


def reparam_checks():
    print("[박스 재매개변수화] 같은 델타 δ = (0.5, 0, 0.2, 0) 를 크기가 다른 두 기준 박스에 적용")
    delta = torch.tensor([0.5, 0.0, 0.2, 0.0])
    rows = []
    for name, ref in (("작은 기준 박스", [0.50, 0.50, 0.05, 0.05]), ("큰 기준 박스  ", [0.50, 0.50, 0.40, 0.40])):
        ref = torch.tensor(ref)
        a, b = box_reparam(delta, ref), box_sigmoid_update(delta, ref)
        rows.append((ref, a, b))
        print(f"  {name} ({fmt_box(ref)})")
        print(f"    재매개변수화: cx = 0.5·{float(ref[2]):.2f} + 0.50 = {float(a[0]):.4f}, w = e^0.2·{float(ref[2]):.2f} = "
              f"{float(a[2]):.4f}  → ({fmt_box(a)})")
        print(f"    시그모이드  : cx = σ(0.5 + σ⁻¹(0.50)) = {float(b[0]):.4f}, w = σ(0.2 + σ⁻¹({float(ref[2]):.2f})) = "
              f"{float(b[2]):.4f}  → ({fmt_box(b)})")
        print(f"    중심 이동량 / 기준 너비: 재매개변수화 {float((a[0] - ref[0]) / ref[2]):.3f}, "
              f"시그모이드 {float((b[0] - ref[0]) / ref[2]):.3f} | 너비 배율: 재매개변수화 {float(a[2] / ref[2]):.3f}, "
              f"시그모이드 {float(b[2] / ref[2]):.3f}")
    generator = torch.Generator().manual_seed(0)
    ref = torch.cat([torch.rand(100, 2, generator=generator), torch.rand(100, 2, generator=generator) * 0.4 + 0.05], -1)
    box = torch.cat([torch.rand(100, 2, generator=generator), torch.rand(100, 2, generator=generator) * 0.4 + 0.05], -1)
    back = box_reparam(box_reparam_inverse(box, ref), ref)
    print(f"  check box_reparam(box_reparam_inverse(box, ref), ref) = box: 최대 차이 {float((back - box).abs().max()):.2e}")
    print(f"  check δ = 0 이면 기준 박스 그대로: {torch.equal(box_reparam(torch.zeros(100, 4), ref), ref)}")
    # 도형 세상의 정답을 12×12 격자의 제안 박스(너비 · 높이 0.05)에서 맞히려면 델타가 얼마나 커야 하는가
    dataset = ShapesDataset(200, seed=1)
    boxes = torch.cat([t["boxes"] for t in dataset.targets])
    cells = ((boxes[:, :2] * 12).floor() + 0.5) / 12  # 정답 중심이 놓인 칸의 중심
    proposal = torch.cat([cells, torch.full_like(cells, 0.05)], dim=-1)
    need = box_reparam_inverse(boxes, proposal)
    print(f"  도형 세상 정답 {len(boxes)}개를 '중심이 놓인 칸의 제안 박스 (칸 중심, 0.05, 0.05)' 에서 맞히는 데 필요한 델타")
    print(f"    |δx|, |δy| 최대 {float(need[:, :2].abs().max()):.3f} (반 칸 = 0.0417 / 0.05 = 0.833 이하), "
          f"δw, δh 범위 {float(need[:, 2:].min()):.3f} – {float(need[:, 2:].max()):.3f} "
          f"(= log(정답 크기 / 0.05), 정답 크기 {float(boxes[:, 2:].min()):.3f} – {float(boxes[:, 2:].max()):.3f})")
    return rows


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

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


def plot_window_order(path):
    import matplotlib.pyplot as plt

    fig, axes = plt.subplots(1, 3, figsize=(11, 3.9), gridspec_kw={"width_ratios": [1, 1, 1.25]})
    for ax, (grid, windows, title) in zip(axes, ((4, 2, "4 x 4 tokens: row-major position"),
                                                (4, 2, "4 x 4 tokens: window-major position"),
                                                (12, 2, "12 x 12 tokens (mini model), 2 x 2 windows"))):
        order = window_major_order(grid, grid, windows)
        position = torch.empty_like(order)
        position[order] = torch.arange(grid * grid)  # 행 우선 번호 → 윈도 우선 자리
        use_window = ax is not axes[0]
        win = grid // windows
        for r in range(grid):
            for c in range(grid):
                window_id = (r // win) * windows + c // win
                ax.add_patch(plt.Rectangle((c, r), 1, 1, facecolor=COLORS[window_id], alpha=0.28, edgecolor="#555555",
                                           linewidth=0.6))
                number = int(position[r * grid + c]) if use_window else r * grid + c
                ax.text(c + 0.5, r + 0.5, str(number), ha="center", va="center", fontsize=11 if grid == 4 else 6.5)
        for k in range(1, windows):
            ax.plot([k * win, k * win], [0, grid], color="black", lw=2)
            ax.plot([0, grid], [k * win, k * win], color="black", lw=2)
        ax.set_xlim(0, grid)
        ax.set_ylim(grid, 0)
        ax.set_aspect("equal")
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_title(title, fontsize=10)
    fig.suptitle("number = position of the token in the sequence; colour = window", fontsize=10)
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


def plot_window_cost(pair_rows, time_rows, device, path):
    import matplotlib.pyplot as plt

    fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))
    ax = axes[0]
    grids = [g for g, _ in pair_rows]
    labels = ["global: N^2", "2 x 2 windows: N^2 / 4", "3 x 3 windows: N^2 / 9", "4 x 4 windows: N^2 / 16"]
    for k, (label, style) in enumerate(zip(labels, ("o-", "s--", "^-.", "d:"))):
        ax.plot(grids, [row[k] for _, row in pair_rows], style, color=COLORS[k], label=label)
    ax.set_yscale("log")
    ax.set_xticks(grids)
    ax.set_xticklabels([f"{g}x{g}\n(N={g * g})" for g in grids])
    ax.set_xlabel("token grid")
    ax.set_ylabel("(query, key) pairs per attention")
    ax.set_title("attention pairs: global vs window", fontsize=10)
    ax.grid(alpha=0.3, which="both")
    ax.legend(fontsize=8)
    ax = axes[1]
    grids = [row[0] for row in time_rows]
    x = np.arange(len(grids))
    for k, (label, hatch) in enumerate((("all 6 blocks global", ""), ("4 window + 2 global, row-major (permute)", "//"),
                                         ("4 window + 2 global, window-major", ".."))):
        ax.bar(x + (k - 1) * 0.27, [row[k + 1] for row in time_rows], 0.27, color=COLORS[k], hatch=hatch,
               edgecolor="white", label=label)
        for xi, row in zip(x, time_rows):
            ax.text(xi + (k - 1) * 0.27, row[k + 1], f"{row[k + 1]:.1f}", ha="center", va="bottom", fontsize=7)
    ax.set_xticks(x)
    ax.set_xticklabels([f"{g}x{g}" for g in grids])
    ax.set_xlabel("token grid")
    ax.set_ylabel("time for 6 blocks, batch 8 (ms)")
    ax.set_title(f"measured time on {device} (min over runs)", fontsize=10)
    ax.grid(alpha=0.3, axis="y")
    ax.legend(fontsize=8)
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


def plot_influence(path):
    """출력 한 칸이 입력의 어느 패치를 보는가: 윈도 블록만 / 윈도 + 전역 / 전역만."""
    import matplotlib.pyplot as plt
    from matplotlib.colors import LogNorm

    torch.manual_seed(0)
    image = torch.rand(3, 96, 96)
    token = (2, 3)  # 왼쪽 위 윈도 안의 칸 (행 2, 열 3)
    settings = (("window blocks only (0-5)", range(6)), ("window 0,1,3,5 + global 2,4 (mini model)", None),
                ("global blocks only", []))
    fig, axes = plt.subplots(1, 3, figsize=(11, 3.9))
    values = []
    for ax, (title, window_blocks) in zip(axes, settings):
        torch.manual_seed(1)
        vit = WindowedViT(window_block_indexes=window_blocks).eval()
        grid = influence_map(vit, image, token)
        grid = grid / grid.sum()
        values.append(grid)
        cmap = plt.get_cmap("viridis").copy()
        cmap.set_bad("#dddddd")  # 정확히 0 인 칸 (영향이 전혀 없음) 은 회색
        im = ax.imshow(np.ma.masked_equal(grid, 0.0), cmap=cmap, norm=LogNorm(vmin=1e-5, vmax=1.0))
        ax.plot([5.5, 5.5], [-0.5, 11.5], color="white", lw=1.2, ls="--")
        ax.plot([-0.5, 11.5], [5.5, 5.5], color="white", lw=1.2, ls="--")
        ax.plot(token[1], token[0], marker="*", color="red", markersize=12)
        ax.set_title(f"{title}\nshare inside own window: {grid[:6, :6].sum():.2f}", fontsize=9)
        ax.set_xticks([])
        ax.set_yticks([])
        fig.colorbar(im, ax=ax, fraction=0.046, pad=0.03)
    fig.suptitle("which input patches influence the output token at the red star (|gradient| share, log colour scale; "
                 "grey = exactly 0; untrained weights)", fontsize=10)
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)
    return [float(v[:6, :6].sum()) for v in values]


def plot_ia_bce(path, alpha=0.25, gamma=2.0):
    import matplotlib.pyplot as plt

    p = np.linspace(0.001, 0.999, 500)
    fig, axes = plt.subplots(1, 3, figsize=(13, 3.9))
    styles = ("-", "--", "-.", ":")
    ax = axes[0]
    for k, u in enumerate((0.3, 0.5, 0.7, 0.9)):
        t = p**alpha * u ** (1 - alpha)
        ax.plot(p, t, styles[k], color=COLORS[k], label=f"IoU = {u}")
        ax.plot(u, u, "o", color=COLORS[k], markersize=6)
    ax.plot(p, p, color="gray", lw=0.8)
    ax.text(0.32, 0.20, "t = p", color="gray", fontsize=8, rotation=38)
    ax.set_xlabel("predicted score p")
    ax.set_ylabel("target t")
    ax.set_title("target t = p^0.25 * IoU^0.75  (dots: t = p at p = IoU)", fontsize=9.5)
    ax.grid(alpha=0.3)
    ax.legend(fontsize=8, loc="lower right")
    ax = axes[1]
    for k, u in enumerate((0.3, 0.5, 0.7, 0.9)):
        ax.plot(p, p - p**alpha * u ** (1 - alpha), styles[k], color=COLORS[k], label=f"IoU = {u}")
        ax.plot(u, 0, "o", color=COLORS[k], markersize=6)
    ax.plot(p, p - 1, color="black", lw=1, label="plain BCE, target 1")
    ax.axhline(0, color="gray", lw=0.8)
    ax.set_xlabel("predicted score p")
    ax.set_ylabel("d loss / d logit = p - t")
    ax.set_title("matched cell: gradient is zero at p = IoU", fontsize=9.5)
    ax.grid(alpha=0.3)
    ax.legend(fontsize=8, loc="upper left")
    ax = axes[2]
    bce = -np.log(1 - p)
    ax.plot(p, bce, "-", color="black", lw=1, label="plain BCE: -log(1 - p)")
    ax.plot(p, p**gamma * bce, "--", color=COLORS[1], lw=2, label="IA-BCE: p^2 * (-log(1 - p))")
    ax.plot(p, (1 - 0.25) * p**gamma * bce, ":", color=COLORS[0], lw=2, label="focal: 0.75 * p^2 * (-log(1 - p))")
    ax.set_xlabel("predicted score p")
    ax.set_ylabel("loss of an unmatched cell")
    ax.set_yscale("log")
    ax.set_ylim(1e-6, 10)
    ax.set_title("unmatched cell: small p is down-weighted", fontsize=9.5)
    ax.grid(alpha=0.3, which="both")
    ax.legend(fontsize=8, loc="lower right")
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


def plot_reparam(path):
    """같은 델타를 크기가 다른 기준 박스에 적용했을 때: 재매개변수화 vs 시그모이드 방식."""
    import matplotlib.patches as patches
    import matplotlib.pyplot as plt

    delta = torch.tensor([0.5, 0.25, 0.4, 0.0])
    refs = [torch.tensor([0.22, 0.24, 0.10, 0.10]), torch.tensor([0.52, 0.60, 0.30, 0.30])]
    fig, axes = plt.subplots(1, 2, figsize=(9.4, 4.6))
    for ax, (fn, title) in zip(axes, ((box_reparam, "reparameterization: cx' = dx * w + cx,  w' = exp(dw) * w"),
                                      (box_sigmoid_update, "sigmoid update: sigmoid(delta + logit(reference))"))):
        for k, ref in enumerate(refs):
            new = fn(delta, ref)
            for box, style, label in ((ref, "--", "reference box"), (new, "-", "updated box")):
                x0, y0, x1, y1 = box_cxcywh_to_xyxy(box).tolist()
                ax.add_patch(patches.Rectangle((x0, y0), x1 - x0, y1 - y0, fill=False, edgecolor=COLORS[k],
                                               linestyle=style, linewidth=2, label=label if k == 0 else None))
            ax.annotate("", xy=new[:2].tolist(), xytext=ref[:2].tolist(),
                        arrowprops={"arrowstyle": "->", "color": COLORS[k], "lw": 1.5})
            shift, scale = float((new[0] - ref[0]) / ref[2]), float(new[2] / ref[2])
            ax.text(float(ref[0]) - float(ref[2]) / 2, float(ref[1]) - float(ref[3]) / 2 - 0.035,
                    f"shift = {shift:.2f} x w,  w' = {scale:.2f} x w", color=COLORS[k], fontsize=8.5)
        ax.set_xlim(0, 1)
        ax.set_ylim(1, 0)
        ax.set_aspect("equal")
        ax.set_title(title, fontsize=9)
        ax.grid(alpha=0.3)
        ax.legend(fontsize=8, loc="lower left")
    fig.suptitle("the same delta = (0.5, 0.25, 0.4, 0) applied to a small and a large reference box", fontsize=10)
    fig.tight_layout()
    fig.savefig(path, dpi=120, facecolor="white")
    plt.close(fig)


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


# --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)
    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}")

    toy_window_order()
    pair_rows, time_rows = window_checks(device, args.quick)
    vit = vit_checks()
    projector_checks(vit)
    ia_bce_checks()
    group_checks()
    reparam_checks()

    plot_window_order(os.path.join(args.fig_dir, "ch09-window-order.png"))
    plot_window_cost(pair_rows, time_rows, device, os.path.join(args.fig_dir, "ch09-window-cost.png"))
    shares = plot_influence(os.path.join(args.fig_dir, "ch09-window-influence.png"))
    print("[그림 ch09-window-influence] 출력 칸 (행 2, 열 3) 이 받는 영향 가운데 자기 윈도 안 패치의 몫: "
          f"윈도 블록만 {shares[0]:.3f}, 윈도 + 전역 {shares[1]:.3f}, 전역만 {shares[2]:.3f}")
    plot_ia_bce(os.path.join(args.fig_dir, "ch09-ia-bce.png"))
    plot_reparam(os.path.join(args.fig_dir, "ch09-reparam.png"))
    print(f"그림 5장 저장: {args.fig_dir}/ch09-*.png  |  전체 {time.time() - start:.1f}초")
# --8<-- [end:main]


if __name__ == "__main__":
    main()
