File size: 14,709 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
"""

YOLOv8s ๊ฒ€์ถœ๊ธฐ ์–‘์žํ™” ์Šคํฌ๋ฆฝํŠธ.



Phase 1์˜ base_W8A8.py / multimodal_w8a8_smoothquant.py ํŒจํ„ด์„ YOLOv8์— ํฌํŒ….

PyTorch ๋ ˆ๋ฒจ fake-quantization ํ›„ ONNX ๋‚ด๋ณด๋‚ด๊ธฐ.



์ง€์› ๋ชจ๋“œ:

  w8a8     โ€” W8A8 PTQ (per-channel MinMax, Phase 1 base_W8A8 ๋™์ผ ๋ฐฉ์‹)

  w4a16    โ€” W4A16 PTQ (4-bit ๊ฐ€์ค‘์น˜ / 16-bit ํ™œ์„ฑํ™”)

  smoothquant โ€” SmoothQuant + W8A8 (Phase 1 multimodal_smoothquant ๋™์ผ ๋ฐฉ์‹)



์‚ฌ์šฉ๋ฒ•:

  python src/quant/quantize_yolo.py --mode w8a8

  python src/quant/quantize_yolo.py --mode w4a16

  python src/quant/quantize_yolo.py --mode smoothquant --calib_batches 10

"""

import argparse
import shutil
from pathlib import Path

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

ROOT = Path(__file__).parent.parent.parent
MODEL_SPACE = ROOT / "model_space"
WEIGHTS = ROOT / "runs" / "detect" / "edge_sign_v2_e0_full3" / "weights" / "best.pt"
DATA_DIR = ROOT / "data" / "yolo_signs"
YOLO_DATASET = DATA_DIR / "dataset.yaml"

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

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# ๊ณตํ†ต ์œ ํ‹ธ
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


def load_yolo_model(weights=WEIGHTS):
    from ultralytics import YOLO

    return YOLO(str(weights))


def _is_quantizable(name: str, module: nn.Module) -> bool:
    """Conv2d / Linear ์ค‘ Detection Head ์ œ์™ธ."""
    if not isinstance(module, (nn.Conv2d, nn.Linear)):
        return False
    # YOLO detection head (model.22.*) โ€” ๋งˆ์ง€๋ง‰ ์ถœ๋ ฅ ๋ณดํ˜ธ
    skip_keywords = ["dfl", "detect"]
    return not any(k in name.lower() for k in skip_keywords)


def export_to_onnx(yolo_model, out_name: str, opset: int = 14) -> Path:
    """์ˆ˜์ •๋œ PyTorch ๋ชจ๋ธ์„ ONNX๋กœ ๋‚ด๋ณด๋‚ด๊ธฐ (ultralytics .export() ์‚ฌ์šฉ)."""
    result = yolo_model.export(
        format="onnx",
        imgsz=640,
        half=False,
        simplify=True,
        opset=opset,
        dynamic=False,
    )
    src = Path(result)
    dst = MODEL_SPACE / out_name
    shutil.copy2(src, dst)
    size_mb = dst.stat().st_size / 1024 / 1024
    print(f"  โ†’ ์ €์žฅ: {dst} ({size_mb:.2f} MB)")
    return dst


def export_nn_to_onnx(nn_model: nn.Module, out_name: str, opset: int = 14) -> Path:
    """

    ์ด๋ฏธ ์ˆ˜์ •๋œ nn.Module์„ torch.onnx.export๋กœ ์ง์ ‘ ๋‚ด๋ณด๋‚ด๊ธฐ.

    SmoothQuant์ฒ˜๋Ÿผ wrapper๊ฐ€ ํฌํ•จ๋œ ๊ฒฝ์šฐ ์‚ฌ์šฉ (ultralytics .export()์˜ fuse() ์ถฉ๋Œ ํšŒํ”ผ).

    """
    import onnx
    import onnxslim

    MODEL_SPACE.mkdir(parents=True, exist_ok=True)
    dst = MODEL_SPACE / out_name
    tmp = MODEL_SPACE / ("_tmp_" + out_name)

    nn_model.eval()
    dummy = torch.randn(1, 3, 640, 640)
    with torch.no_grad():
        torch.onnx.export(
            nn_model,
            dummy,
            str(tmp),
            opset_version=opset,
            input_names=["images"],
            output_names=["output0"],
            do_constant_folding=True,
            dynamo=False,  # TorchScript ๊ธฐ๋ฐ˜ exporter ์‚ฌ์šฉ (PyTorch 2.x ํ˜ธํ™˜)
        )

    # onnxslim์œผ๋กœ ์ตœ์ ํ™”
    try:
        slimmed = onnxslim.slim(str(tmp))
        onnx.save(slimmed, str(dst))
        tmp.unlink(missing_ok=True)
    except Exception:
        tmp.rename(dst)

    size_mb = dst.stat().st_size / 1024 / 1024
    print(f"  โ†’ ์ €์žฅ: {dst} ({size_mb:.2f} MB)")
    return dst


def verify_onnx(path: Path):
    import onnxruntime as ort

    sess = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
    dummy = np.random.randn(1, 3, 640, 640).astype(np.float32)
    out = sess.run(None, {sess.get_inputs()[0].name: dummy})
    print(f"  ๊ฒ€์ฆ OK: output shape = {out[0].shape}")


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# W8A8 PTQ (Phase 1 base_W8A8.py ๋™์ผ ๋ฐฉ์‹)
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


def apply_w8a8_ptq(model_nn: nn.Module) -> int:
    """

    Conv2d / Linear ๋ ˆ์ด์–ด์— per-channel MinMax W8A8 fake-quantization ์ ์šฉ.

    Phase 1์˜ apply_w8a8_ptq() ์™€ ๋™์ผํ•œ ๋กœ์ง.

    """
    quantized = 0
    for name, module in model_nn.named_modules():
        if not _is_quantizable(name, module):
            continue
        with torch.no_grad():
            w = module.weight.data
            # Per-output-channel MinMax scale
            if w.dim() == 4:  # Conv2d: [out, in, kH, kW]
                max_val = w.view(w.size(0), -1).abs().max(dim=1)[0].view(-1, 1, 1, 1)
            else:  # Linear: [out, in]
                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  # fake-dequant
        quantized += 1
    return quantized


def run_w8a8(weights=WEIGHTS):
    print("\n[W8A8 PTQ] ์‹œ์ž‘")
    yolo = load_yolo_model(weights)
    nn_model = yolo.model

    n = apply_w8a8_ptq(nn_model)
    print(f"  ์–‘์žํ™” ๋ ˆ์ด์–ด: {n}๊ฐœ (Detection Head ์ œ์™ธ)")

    out = export_to_onnx(yolo, "yolov8s_signs_w8a8.onnx")
    verify_onnx(out)
    return out


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# W4A16 PTQ (4-bit ๊ฐ€์ค‘์น˜ / FP16 ํ™œ์„ฑํ™”)
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


def apply_w4a16_ptq(model_nn: nn.Module) -> int:
    """

    4-bit ๊ฐ€์ค‘์น˜ ์–‘์žํ™” ์‹œ๋ฎฌ๋ ˆ์ด์…˜ (ํ™œ์„ฑํ™”๋Š” FP32 ์œ ์ง€).

    Phase 1์˜ W4A16 QAT ๊ฐ€์ค‘์น˜ ํ‘œํ˜„๊ณผ ๋™์ผํ•œ INT4 ๋ฒ”์œ„(-8 ~ 7).

    """
    quantized = 0
    for name, module in model_nn.named_modules():
        if not _is_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)  # INT4: [-8, 7]
            q_w = torch.round(w / scale).clamp(-8, 7)
            module.weight.data = q_w * scale
        quantized += 1
    return quantized


def run_w4a16(weights=WEIGHTS):
    print("\n[W4A16 PTQ] ์‹œ์ž‘")
    yolo = load_yolo_model(weights)
    nn_model = yolo.model

    n = apply_w4a16_ptq(nn_model)
    print(f"  ์–‘์žํ™” ๋ ˆ์ด์–ด: {n}๊ฐœ (4-bit ๊ฐ€์ค‘์น˜)")

    out = export_to_onnx(yolo, "yolov8s_signs_w4a16.onnx")
    verify_onnx(out)
    return out


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# SmoothQuant + W8A8 (Phase 1 ๋™์ผ ๋ฐฉ์‹)
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


def _build_calib_loader(num_batches=10, batch_size=4):
    """val ์ด๋ฏธ์ง€๋ฅผ ์บ˜๋ฆฌ๋ธŒ๋ ˆ์ด์…˜ ๋ฐ์ดํ„ฐ๋กœ ์‚ฌ์šฉ."""
    import cv2
    from torch.utils.data import DataLoader, Dataset

    img_dir = DATA_DIR / "images" / "val"
    img_paths = sorted(img_dir.rglob("*.jpg"))[: num_batches * batch_size]

    class YOLOImageDataset(Dataset):
        def __init__(self, paths, imgsz=640):
            self.paths = paths
            self.imgsz = imgsz

        def __len__(self):
            return len(self.paths)

        def __getitem__(self, idx):
            img = cv2.imread(str(self.paths[idx]))
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            img = cv2.resize(img, (self.imgsz, self.imgsz))
            tensor = torch.from_numpy(img).permute(2, 0, 1).float() / 255.0
            return tensor

    ds = YOLOImageDataset(img_paths)
    return DataLoader(ds, batch_size=batch_size, shuffle=False, num_workers=0)


class _SmoothWrapper(nn.Module):
    """

    SmoothQuant Wrapper: forward์—์„œ ์ž…๋ ฅ์„ 1/s๋กœ ์Šค์ผ€์ผ๋ง ํ›„ ๊ฐ€์ค‘์น˜(s ํก์ˆ˜+W8) ๋ ˆ์ด์–ด ์‹คํ–‰.

    ONNX export ์‹œ ์Šค์ผ€์ผ ๋‚˜๋ˆ—์…ˆ์ด ๊ทธ๋ž˜ํ”„์— ํฌํ•จ๋จ (Phase 1 SmoothQuantWrapper ๋™์ผ ๋ฐฉ์‹).

    """

    def __init__(self, module: nn.Module, smooth_scale: torch.Tensor):
        super().__init__()
        self.module = module
        self.register_buffer("smooth_scale", smooth_scale)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        if x.dim() == 4:
            x = x / self.smooth_scale.view(1, -1, 1, 1)
        else:
            x = x / self.smooth_scale
        return self.module(x)


def apply_smoothquant(model_nn: nn.Module, calib_loader, alpha: float = 0.5) -> int:
    """

    SmoothQuant: ํ™œ์„ฑํ™” ์บ˜๋ฆฌ๋ธŒ๋ ˆ์ด์…˜ โ†’ wrapper๋กœ ์ž…๋ ฅ ์Šค์ผ€์ผ๋ง + ๊ฐ€์ค‘์น˜ ํก์ˆ˜ + W8A8.

    wrapper.forward()์— x/s ์—ฐ์‚ฐ์ด ํฌํ•จ๋ผ ONNX export ์‹œ ๊ทธ๋ž˜ํ”„์— ๋ฐ˜์˜๋จ.

    """
    device = next(model_nn.parameters()).device
    model_nn.eval()

    # 1. ํ™œ์„ฑํ™” ์ตœ๋Œ€๊ฐ’ ์ˆ˜์ง‘ (per-input-channel)
    act_max: dict = {}
    hooks = []

    def make_hook(name):
        def hook(module, inp, out):
            x = inp[0].detach().abs()
            if x.dim() == 4:
                ch_max = x.amax(dim=(0, 2, 3))
            else:
                ch_max = x.amax(dim=0) if x.dim() >= 2 else x
            act_max[name] = torch.max(act_max[name], ch_max) if name in act_max else ch_max

        return hook

    target_names = [name for name, m in model_nn.named_modules() if _is_quantizable(name, m)]
    target_mods = dict(model_nn.named_modules())

    for name in target_names:
        hooks.append(target_mods[name].register_forward_hook(make_hook(name)))

    print(f"  ์บ˜๋ฆฌ๋ธŒ๋ ˆ์ด์…˜ ์ค‘ ({len(calib_loader)} ๋ฐฐ์น˜)...")
    with torch.no_grad():
        for batch in calib_loader:
            model_nn(batch.to(device))
    for h in hooks:
        h.remove()

    # 2. Wrapper ๊ต์ฒด + ๊ฐ€์ค‘์น˜ W8A8 ์ ์šฉ
    def _set_module(root, dotted_name, new_module):
        parts = dotted_name.split(".")
        parent = root
        for p in parts[:-1]:
            parent = getattr(parent, p)
        setattr(parent, parts[-1], new_module)

    quantized = 0
    for name in target_names:
        if name not in act_max:
            continue
        module = target_mods[name]
        w = module.weight.data
        a_max = act_max[name].to(device).clamp(min=1e-8)

        if w.dim() == 4:
            in_ch = w.size(1)
        else:
            in_ch = w.size(1)

        # a_max ์ฑ„๋„ ์ˆ˜ ๋งž์ถ”๊ธฐ
        if a_max.shape[0] != in_ch:
            if a_max.shape[0] > in_ch:
                a_max = a_max[:in_ch]
            else:
                pad = a_max.mean().expand(in_ch - a_max.shape[0])
                a_max = torch.cat([a_max, pad])

        # per-input-channel weight max
        if w.dim() == 4:
            w_max = w.abs().amax(dim=(0, 2, 3)).clamp(min=1e-8)
        else:
            w_max = w.abs().amax(dim=0).clamp(min=1e-8)

        smooth_s = (a_max**alpha) / (w_max ** (1 - alpha) + 1e-8)
        smooth_s = smooth_s.clamp(1e-3, 1e3)

        # ๊ฐ€์ค‘์น˜์— smooth_s ํก์ˆ˜ + W8 fake-quant
        with torch.no_grad():
            if w.dim() == 4:
                w_scaled = w * smooth_s.view(1, in_ch, 1, 1)
                out_max = w_scaled.view(w.size(0), -1).abs().max(dim=1)[0].view(-1, 1, 1, 1)
            else:
                w_scaled = w * smooth_s.view(1, in_ch)
                out_max = w_scaled.abs().max(dim=1)[0].view(-1, 1)
            q_scale = (out_max / 127.0).clamp(min=1e-8)
            q_w = torch.round(w_scaled / q_scale).clamp(-128, 127)
            module.weight.data = q_w * q_scale

        # Wrapper ๊ต์ฒด (ONNX export ์‹œ x/smooth_s ์—ฐ์‚ฐ ํฌํ•จ)
        wrapper = _SmoothWrapper(module, smooth_s)
        _set_module(model_nn, name, wrapper)
        quantized += 1

    return quantized


def run_smoothquant(weights=WEIGHTS, calib_batches=10, alpha=0.5):
    print("\n[SmoothQuant + W8A8] ์‹œ์ž‘")
    yolo = load_yolo_model(weights)
    nn_model = yolo.model

    # โ˜… fuse() ๋จผ์ €: Conv+BN ์œตํ•ฉ ํ›„ SmoothWrapper ๊ต์ฒด
    #   ๊ทธ๋ž˜์•ผ ultralytics fuse() ์žฌํ˜ธ์ถœ ์—†์ด torch.onnx.export ๊ฐ€๋Šฅ
    nn_model = nn_model.fuse()
    nn_model.eval()

    calib_loader = _build_calib_loader(num_batches=calib_batches)
    n = apply_smoothquant(nn_model, calib_loader, alpha=alpha)
    print(f"  SmoothQuant ์ ์šฉ ๋ ˆ์ด์–ด: {n}๊ฐœ (alpha={alpha})")

    # torch.onnx.export ์ง์ ‘ ์‚ฌ์šฉ (ultralytics .export()์˜ fuse() ์žฌํ˜ธ์ถœ ํšŒํ”ผ)
    out = export_nn_to_onnx(nn_model, "yolov8s_signs_smoothquant.onnx")
    verify_onnx(out)
    return out


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# CLI
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


def main():
    parser = argparse.ArgumentParser(description="YOLOv8s ๊ฒ€์ถœ๊ธฐ ์–‘์žํ™”")
    parser.add_argument(
        "--mode", choices=["w8a8", "w4a16", "smoothquant", "all"], default="all", help="์–‘์žํ™” ๋ชจ๋“œ"
    )
    parser.add_argument("--weights", type=str, default=str(WEIGHTS), help="ํ•™์Šต๋œ best.pt ๊ฒฝ๋กœ")
    parser.add_argument(
        "--calib_batches", type=int, default=10, help="SmoothQuant ์บ˜๋ฆฌ๋ธŒ๋ ˆ์ด์…˜ ๋ฐฐ์น˜ ์ˆ˜"
    )
    parser.add_argument(
        "--alpha", type=float, default=0.5, help="SmoothQuant alpha (0=weight๋งŒ, 1=activation๋งŒ)"
    )
    args = parser.parse_args()

    modes = ["w8a8", "w4a16", "smoothquant"] if args.mode == "all" else [args.mode]

    for mode in modes:
        if mode == "w8a8":
            run_w8a8(args.weights)
        elif mode == "w4a16":
            run_w4a16(args.weights)
        elif mode == "smoothquant":
            run_smoothquant(args.weights, args.calib_batches, args.alpha)

    print("\n๋ชจ๋“  ์–‘์žํ™” ์™„๋ฃŒ. model_space/ ๋””๋ ‰ํ† ๋ฆฌ ํ™•์ธ:")
    for f in sorted(MODEL_SPACE.glob("yolov8s_signs_*.onnx")):
        print(f"  {f.name}: {f.stat().st_size / 1024 / 1024:.2f} MB")


if __name__ == "__main__":
    main()