File size: 19,635 Bytes
76ec265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
"""

KoreanOCRNet + TrafficSignNet μ–‘μžν™” μ‹€ν—˜ 슀크립트.



Phase 1 base_W8A8.py / base_train_1bit_kd.py νŒ¨ν„΄ μž¬ν™œμš©.

fake-quant PTQ (W8A8 / W4A16 / 1-Bit) + ONNX 내보내기 + val 평가.



μ‹€ν—˜ λ§€ν•‘:

  E2: FP16 κ²€μΆœκΈ° + W8A8 인식기 β†’ λ³Έ 슀크립트둜 w8a8 내보내기 ν›„ 정확도 μΈ‘μ •

  E3: W8A8 전체 β†’ κ²€μΆœκΈ°(E1) + 인식기(E2)

  E4-recog: W4A16 인식기

  E7-recog: 1-Bit 인식기



μ‚¬μš©λ²•:

  python src/quant/quantize_recognizers.py              # 전체 (w8a8/w4a16/1bit)

  python src/quant/quantize_recognizers.py --mode w8a8  # νŠΉμ • λͺ¨λ“œ

  python src/quant/quantize_recognizers.py --eval_only  # κΈ°μ‘΄ ONNX ν‰κ°€λ§Œ

"""

import argparse
import io
import sys
import time
from pathlib import Path

import numpy as np
import torch
import torch.nn as nn

# Windows 터미널 인코딩 문제 ν•΄κ²°
if sys.platform.startswith("win"):
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
    sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace")

ROOT = Path(__file__).parent.parent.parent
sys.path.insert(0, str(ROOT))

MODEL_SPACE = ROOT / "model_space"
MODEL_DIR = ROOT / "models"
OCR_CKPT = MODEL_DIR / "korean_ocr_best.pth"
TSIGN_CKPT = MODEL_SPACE / "traffic_sign_net_best.pth"
OCR_DATA = ROOT / "data" / "korean_ocr"
GTSDB_DIR = ROOT / "data" / "GTSDB" / "FullIJCNN2013"

MODEL_SPACE.mkdir(parents=True, exist_ok=True)

# ─────────────────────────────────────────────
# 곡톡 μ–‘μžν™” ν•¨μˆ˜ (Phase 1 νŒ¨ν„΄ μž¬ν™œμš©)
# ─────────────────────────────────────────────


def _quantizable(name: str, module: nn.Module) -> bool:
    """Conv2d / Linear λ ˆμ΄μ–΄λ§Œ λŒ€μƒ (BN, Activation μ œμ™Έ)."""
    return isinstance(module, (nn.Conv2d, nn.Linear))


def apply_w8a8_ptq(model: nn.Module) -> int:
    """Per-output-channel MinMax W8A8 fake-quantization (base_W8A8.py 동일 방식)."""
    count = 0
    for name, module in model.named_modules():
        if not _quantizable(name, module):
            continue
        with torch.no_grad():
            w = module.weight.data
            if w.dim() == 4:  # Conv2d
                max_val = w.view(w.size(0), -1).abs().max(dim=1)[0].view(-1, 1, 1, 1)
            else:  # Linear
                max_val = w.abs().max(dim=1)[0].view(-1, 1)
            scale = (max_val / 127.0).clamp(min=1e-8)
            q_w = torch.round(w / scale).clamp(-128, 127)
            module.weight.data = q_w * scale
        count += 1
    return count


def apply_w4a16_ptq(model: nn.Module) -> int:
    """Per-output-channel MinMax W4A16 fake-quantization."""
    count = 0
    for name, module in model.named_modules():
        if not _quantizable(name, module):
            continue
        with torch.no_grad():
            w = module.weight.data
            if w.dim() == 4:
                max_val = w.view(w.size(0), -1).abs().max(dim=1)[0].view(-1, 1, 1, 1)
            else:
                max_val = w.abs().max(dim=1)[0].view(-1, 1)
            scale = (max_val / 7.0).clamp(min=1e-8)
            q_w = torch.round(w / scale).clamp(-8, 7)
            module.weight.data = q_w * scale
        count += 1
    return count


def apply_1bit_ptq(model: nn.Module) -> int:
    """PTB: Post-Training Binarization (sign(W) Γ— ||W||_1 / n, base_train_1bit_kd.py νŒ¨ν„΄)."""
    count = 0
    for name, module in model.named_modules():
        if not _quantizable(name, module):
            continue
        with torch.no_grad():
            w = module.weight.data
            if w.dim() == 4:
                scale = w.abs().mean(dim=(1, 2, 3), keepdim=True)
            else:
                scale = w.abs().mean(dim=1, keepdim=True)
            binary_w = torch.sign(w)
            binary_w[binary_w == 0] = 1.0  # 0은 +1둜 처리
            module.weight.data = binary_w * scale
        count += 1
    return count


# ─────────────────────────────────────────────
# ONNX 내보내기
# ─────────────────────────────────────────────


def export_to_onnx(

    model: nn.Module,

    dummy: torch.Tensor,

    out_path: Path,

    input_names: list,

    output_names: list,

    opset: int = 14,

):
    """PyTorch λͺ¨λΈ β†’ ONNX (dynamo=False)."""
    try:
        import onnxslim

        use_slim = True
    except ImportError:
        use_slim = False

    import tempfile

    with tempfile.NamedTemporaryFile(suffix=".onnx", delete=False) as tmp:
        tmp_path = Path(tmp.name)

    torch.onnx.export(
        model.cpu().eval(),
        dummy.cpu(),
        str(tmp_path),
        opset_version=opset,
        input_names=input_names,
        output_names=output_names,
        dynamic_axes={input_names[0]: {0: "batch"}, output_names[0]: {0: "batch"}},
        do_constant_folding=True,
        dynamo=False,
    )

    if use_slim:
        onnxslim.slim(str(tmp_path), str(out_path))
        tmp_path.unlink(missing_ok=True)
    else:
        tmp_path.rename(out_path)

    size_mb = out_path.stat().st_size / 1024 / 1024
    print(f"    -> {out_path.name}  ({size_mb:.3f} MB)")
    return out_path


# ─────────────────────────────────────────────
# KoreanOCRNet λ‘œλ“œ + μ–‘μžν™” + ONNX
# ─────────────────────────────────────────────


def load_ocr_model() -> nn.Module:
    from src.korean_ocr_model import KoreanOCRNet

    model = KoreanOCRNet(num_classes=2350)
    if OCR_CKPT.exists():
        state = torch.load(str(OCR_CKPT), map_location="cpu", weights_only=True)
        model.load_state_dict(state)
        print(f"  OCR 체크포인트 λ‘œλ“œ: {OCR_CKPT}")
    else:
        print(f"  [WARN] OCR 체크포인트 μ—†μŒ: {OCR_CKPT}")
    return model.eval()


def quantize_ocr(mode: str) -> Path:
    """KoreanOCRNet μ–‘μžν™” + ONNX 내보내기."""
    model = load_ocr_model()
    dummy = torch.zeros(1, 1, 64, 64)

    if mode == "fp32":
        out = MODEL_SPACE / "korean_ocr_net_fp32.onnx"
    elif mode == "w8a8":
        n = apply_w8a8_ptq(model)
        print(f"    W8A8 fake-quant: {n} λ ˆμ΄μ–΄")
        out = MODEL_SPACE / "korean_ocr_net_w8a8.onnx"
    elif mode == "w4a16":
        n = apply_w4a16_ptq(model)
        print(f"    W4A16 fake-quant: {n} λ ˆμ΄μ–΄")
        out = MODEL_SPACE / "korean_ocr_net_w4a16.onnx"
    elif mode == "1bit":
        n = apply_1bit_ptq(model)
        print(f"    1-Bit PTB: {n} λ ˆμ΄μ–΄")
        out = MODEL_SPACE / "korean_ocr_net_1bit.onnx"
    else:
        raise ValueError(f"Unknown mode: {mode}")

    return export_to_onnx(model, dummy, out, ["image"], ["logits"])


# ─────────────────────────────────────────────
# TrafficSignNet λ‘œλ“œ + μ–‘μžν™” + ONNX
# ─────────────────────────────────────────────


def load_tsign_model(num_classes: int = 43) -> nn.Module:
    from src.model import TrafficSignNet

    model = TrafficSignNet(num_classes=num_classes)
    if TSIGN_CKPT.exists():
        ckpt = torch.load(str(TSIGN_CKPT), map_location="cpu", weights_only=False)
        nc = ckpt.get("num_classes", num_classes)
        if nc != num_classes:
            model = TrafficSignNet(num_classes=nc)
        model.load_state_dict(ckpt["model_state"])
        print(f"  TrafficSignNet 체크포인트 λ‘œλ“œ: {TSIGN_CKPT} (num_classes={nc})")
    else:
        print(f"  [WARN] TrafficSignNet 체크포인트 μ—†μŒ: {TSIGN_CKPT}")
    return model.eval()


def quantize_tsign(mode: str) -> Path:
    """TrafficSignNet μ–‘μžν™” + ONNX 내보내기."""
    model = load_tsign_model()
    dummy = torch.zeros(1, 3, 32, 32)

    if mode == "fp32":
        out = MODEL_SPACE / "traffic_sign_net_fp32.onnx"  # 이미 쑴재
    elif mode == "w8a8":
        n = apply_w8a8_ptq(model)
        print(f"    W8A8 fake-quant: {n} λ ˆμ΄μ–΄")
        out = MODEL_SPACE / "traffic_sign_net_w8a8.onnx"
    elif mode == "w4a16":
        n = apply_w4a16_ptq(model)
        print(f"    W4A16 fake-quant: {n} λ ˆμ΄μ–΄")
        out = MODEL_SPACE / "traffic_sign_net_w4a16.onnx"
    elif mode == "1bit":
        n = apply_1bit_ptq(model)
        print(f"    1-Bit PTB: {n} λ ˆμ΄μ–΄")
        out = MODEL_SPACE / "traffic_sign_net_1bit.onnx"
    else:
        raise ValueError(f"Unknown mode: {mode}")

    if mode != "fp32" or not out.exists():
        export_to_onnx(model, dummy, out, ["images"], ["logits"])
    return out


# ─────────────────────────────────────────────
# 평가: KoreanOCRNet (val set)
# ─────────────────────────────────────────────


def eval_ocr_onnx(onnx_path: Path, max_samples: int = 5000) -> dict:
    """KoreanOCRNet ONNX 평가 (data/korean_ocr/val/)."""
    import onnxruntime as ort
    from torchvision import datasets, transforms

    val_dir = OCR_DATA / "val"
    if not val_dir.exists():
        print(f"  [SKIP] OCR val 데이터 μ—†μŒ: {val_dir}")
        return {}

    # NumericalImageFolder: 클래슀 이름을 숫자둜 μ •λ ¬
    class NumericalImageFolder(datasets.ImageFolder):
        def find_classes(self, directory):
            import os

            classes = sorted([d.name for d in os.scandir(directory) if d.is_dir()], key=int)
            class_to_idx = {cls: int(cls) for cls in classes}
            return classes, class_to_idx

    transform = transforms.Compose(
        [
            transforms.Grayscale(num_output_channels=1),
            transforms.Resize((64, 64)),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.5], std=[0.5]),
        ]
    )

    val_ds = NumericalImageFolder(root=str(val_dir), transform=transform)
    # 평가 속도λ₯Ό μœ„ν•΄ μ΅œλŒ€ max_samples개만 μ‚¬μš©
    indices = list(range(min(max_samples, len(val_ds))))
    from torch.utils.data import DataLoader, Subset

    subset = Subset(val_ds, indices)
    loader = DataLoader(subset, batch_size=256, shuffle=False, num_workers=0)

    sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
    input_name = sess.get_inputs()[0].name
    output_name = sess.get_outputs()[0].name

    correct1 = correct5 = total = 0
    t0 = time.time()

    for imgs, labels in loader:
        imgs_np = imgs.numpy()
        out = sess.run([output_name], {input_name: imgs_np})[0]  # [B, 2350]
        top5 = np.argsort(out, axis=1)[:, -5:][:, ::-1]  # [B, 5] λ‚΄λ¦Όμ°¨μˆœ
        labels_np = labels.numpy()
        correct1 += (top5[:, 0] == labels_np).sum()
        correct5 += sum(labels_np[i] in top5[i] for i in range(len(labels_np)))
        total += len(labels_np)

    elapsed = time.time() - t0
    top1 = correct1 / total * 100
    top5 = correct5 / total * 100
    fps = total / elapsed

    return {"top1": round(top1, 2), "top5": round(top5, 2), "samples": total, "fps": round(fps, 1)}


# ─────────────────────────────────────────────
# 평가: TrafficSignNet (GTSDB val 크둭)
# ─────────────────────────────────────────────


def eval_tsign_onnx(onnx_path: Path) -> dict:
    """TrafficSignNet ONNX 평가 (GTSDB val 크둭)."""
    import onnxruntime as ort
    from torch.utils.data import random_split

    from src.detect.train_traffic_sign_net import GTSDBCropDataset

    full_ds = GTSDBCropDataset(GTSDB_DIR, img_size=32, augment=False)
    n_val = max(1, int(len(full_ds) * 0.2))
    n_train = len(full_ds) - n_val
    _, val_ds = random_split(full_ds, [n_train, n_val], generator=torch.Generator().manual_seed(42))

    # DataLoader λŒ€μ‹  직접 배치 처리 (PIL β†’ numpy λ³€ν™˜ 포함)
    sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
    input_name = sess.get_inputs()[0].name
    output_name = sess.get_outputs()[0].name

    _MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
    _STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)

    correct1 = correct5 = 0
    t0 = time.time()

    for img_tensor, label in val_ds:
        # img_tensor: [3, 32, 32] float32
        img_np = img_tensor.numpy()[np.newaxis]  # [1, 3, 32, 32]
        out = sess.run([output_name], {input_name: img_np})[0]  # [1, 43]
        top5 = np.argsort(out[0])[::-1][:5]
        if top5[0] == label:
            correct1 += 1
        if label in top5:
            correct5 += 1

    total = len(val_ds)
    elapsed = time.time() - t0
    top1 = correct1 / total * 100
    top5 = correct5 / total * 100

    return {
        "top1": round(top1, 2),
        "top5": round(top5, 2),
        "samples": total,
        "fps": round(total / elapsed, 1),
    }


# ─────────────────────────────────────────────
# 메인: μ–‘μžν™” + 평가 + κ²°κ³Ό 좜λ ₯
# ─────────────────────────────────────────────

MODES = ["fp32", "w8a8", "w4a16", "1bit"]

EXP_MAP = {
    "fp32": "E0 κΈ°μ€€μ„ ",
    "w8a8": "E2/E3 W8A8",
    "w4a16": "E4 W4A16",
    "1bit": "E7 1-Bit PTB",
}


def run_all(

    modes: list[str], eval_ocr: bool = True, eval_tsign: bool = True, ocr_samples: int = 5000

):
    results = []

    for mode in modes:
        print(f"\n{'=' * 55}")
        print(f"[{mode.upper()}] KoreanOCRNet + TrafficSignNet")
        print(f"{'=' * 55}")

        # ── KoreanOCRNet
        print("  [OCR] μ–‘μžν™” 내보내기...")
        try:
            ocr_path = quantize_ocr(mode)
        except Exception as e:
            print(f"  [OCR] 내보내기 μ‹€νŒ¨: {e}")
            ocr_path = None

        ocr_metrics = {}
        if eval_ocr and ocr_path and ocr_path.exists():
            print(f"  [OCR] 평가 쀑 (μ΅œλŒ€ {ocr_samples}개)...")
            ocr_metrics = eval_ocr_onnx(ocr_path, max_samples=ocr_samples)
            if ocr_metrics:
                print(
                    f"    Top-1={ocr_metrics['top1']:.2f}%  "
                    f"Top-5={ocr_metrics['top5']:.2f}%  "
                    f"({ocr_metrics['samples']}개, {ocr_metrics['fps']:.0f} FPS)"
                )

        # ── TrafficSignNet
        print("  [TrafficSign] μ–‘μžν™” 내보내기...")
        try:
            ts_path = quantize_tsign(mode)
        except Exception as e:
            print(f"  [TrafficSign] 내보내기 μ‹€νŒ¨: {e}")
            ts_path = None

        ts_metrics = {}
        if eval_tsign and ts_path and ts_path.exists():
            print("  [TrafficSign] 평가 쀑...")
            ts_metrics = eval_tsign_onnx(ts_path)
            if ts_metrics:
                print(
                    f"    Top-1={ts_metrics['top1']:.2f}%  "
                    f"Top-5={ts_metrics['top5']:.2f}%  "
                    f"({ts_metrics['samples']}개, {ts_metrics['fps']:.0f} FPS)"
                )

        # OCR ONNX 크기
        ocr_size = ocr_path.stat().st_size / 1024 / 1024 if ocr_path and ocr_path.exists() else 0
        ts_size = ts_path.stat().st_size / 1024 / 1024 if ts_path and ts_path.exists() else 0

        results.append(
            {
                "mode": mode,
                "exp": EXP_MAP.get(mode, mode),
                "ocr_top1": ocr_metrics.get("top1", "β€”"),
                "ocr_top5": ocr_metrics.get("top5", "β€”"),
                "ts_top1": ts_metrics.get("top1", "β€”"),
                "ts_top5": ts_metrics.get("top5", "β€”"),
                "ocr_size": round(ocr_size, 3),
                "ts_size": round(ts_size, 3),
            }
        )

    # ── κ²°κ³Ό μš”μ•½ν‘œ
    print(f"\n{'=' * 70}")
    print("인식기 μ–‘μžν™” κ²°κ³Ό μš”μ•½")
    print(f"{'=' * 70}")
    hdr = (
        f"{'λͺ¨λ“œ':<8} {'μ‹€ν—˜':<12} "
        f"{'OCR Top1':>9} {'OCR Top5':>9} {'TS Top1':>8} {'TS Top5':>8} "
        f"{'OCR MB':>7} {'TS MB':>6}"
    )
    print(hdr)
    print("-" * 70)

    e0 = next((r for r in results if r["mode"] == "fp32"), None)

    for r in results:
        ocr1 = r["ocr_top1"]
        ts1 = r["ts_top1"]
        # λ³€ν™”λŸ‰
        if e0 and r["mode"] != "fp32":
            if isinstance(ocr1, float) and isinstance(e0["ocr_top1"], float):
                ocr1_str = f"{ocr1:.1f} ({ocr1 - e0['ocr_top1']:+.1f})"
            else:
                ocr1_str = str(ocr1)
            if isinstance(ts1, float) and isinstance(e0["ts_top1"], float):
                ts1_str = f"{ts1:.1f} ({ts1 - e0['ts_top1']:+.1f})"
            else:
                ts1_str = str(ts1)
        else:
            ocr1_str = f"{ocr1:.1f}" if isinstance(ocr1, float) else str(ocr1)
            ts1_str = f"{ts1:.1f}" if isinstance(ts1, float) else str(ts1)

        print(
            f"{r['mode']:<8} {r['exp']:<12} "
            f"{ocr1_str:>9} {str(r['ocr_top5']):>9} "
            f"{ts1_str:>8} {str(r['ts_top5']):>8} "
            f"{r['ocr_size']:>7.3f} {r['ts_size']:>6.3f}"
        )

    print("\n[민감도 뢄석]")
    if e0:
        for r in results:
            if r["mode"] == "fp32":
                continue
            for name, base_key, key in [
                ("OCR Top-1", "ocr_top1", "ocr_top1"),
                ("TrafficSign Top-1", "ts_top1", "ts_top1"),
            ]:
                bv = e0[base_key]
                v = r[key]
                if isinstance(v, float) and isinstance(bv, float):
                    d = v - bv
                    p = d / bv * 100
                    print(f"  {r['mode']} {name}: {bv:.1f}% -> {v:.1f}% ({d:+.1f}pp, {p:+.1f}%)")

    print("\nμœ„ κ²°κ³Όλ₯Ό docs/EXPERIMENTS.md 인식 κ²°κ³Ό ν‘œμ— κΈ°μž…ν•˜μ„Έμš”.")
    return results


def main():
    parser = argparse.ArgumentParser(description="인식기 μ–‘μžν™” + 평가")
    parser.add_argument("--mode", choices=MODES + ["all"], default="all")
    parser.add_argument("--no_ocr", action="store_true", help="OCR 평가 κ±΄λ„ˆλ›°κΈ°")
    parser.add_argument("--no_tsign", action="store_true", help="TrafficSign 평가 κ±΄λ„ˆλ›°κΈ°")
    parser.add_argument(
        "--ocr_samples", type=int, default=5000, help="OCR val μ΅œλŒ€ μƒ˜ν”Œ 수 (κΈ°λ³Έ 5000)"
    )
    args = parser.parse_args()

    modes = MODES if args.mode == "all" else [args.mode]
    run_all(
        modes, eval_ocr=not args.no_ocr, eval_tsign=not args.no_tsign, ocr_samples=args.ocr_samples
    )


if __name__ == "__main__":
    main()