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()
|