File size: 10,550 Bytes
5b86813 | 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 | #!/usr/bin/env python3
"""
Deployment & Optimization Utilities
Based on: Nature Scientific Reports (Nov 2025) - YOLOv11 + CNN-BiGRU
Features:
β’ TensorRT FP16 export (105 FPS on RTX 3090)
β’ ONNX export (cross-platform)
β’ TFLite export (Raspberry Pi / edge)
β’ INT8 post-training quantization
β’ Benchmark latency / throughput
"""
import os
import sys
import time
import logging
from pathlib import Path
from typing import Optional, Dict, Any
import numpy as np
import torch
from ultralytics import YOLO
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s - %(message)s",
)
logger = logging.getLogger("deploy")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Export helpers
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def export_tensorrt(
weights: str = "best.pt",
imgsz: int = 416,
half: bool = True,
int8: bool = False,
workspace: int = 2,
) -> str:
"""
Export YOLOv11 to TensorRT engine (.engine).
Tuned for RTX 2050 (4 GB VRAM) β workspace=2 GB, imgsz=416.
"""
model = YOLO(weights)
path = model.export(
format="engine",
imgsz=imgsz,
half=half,
int8=int8,
workspace=workspace,
device=0,
)
logger.info("TensorRT engine saved β %s", path)
return str(path)
def export_onnx(
weights: str = "best.pt",
imgsz: int = 416,
half: bool = False,
simplify: bool = True,
) -> str:
"""Export to ONNX for cross-platform inference."""
model = YOLO(weights)
path = model.export(
format="onnx",
imgsz=imgsz,
half=half,
simplify=simplify,
)
logger.info("ONNX model saved β %s", path)
return str(path)
def export_tflite(
weights: str = "best.pt",
imgsz: int = 416,
int8: bool = False,
) -> str:
"""Export to TFLite for Raspberry Pi / mobile deployment."""
model = YOLO(weights)
path = model.export(
format="tflite",
imgsz=imgsz,
int8=int8,
)
logger.info("TFLite model saved β %s", path)
return str(path)
def export_torchscript(
weights: str = "best.pt",
imgsz: int = 640,
) -> str:
"""Export to TorchScript."""
model = YOLO(weights)
path = model.export(format="torchscript", imgsz=imgsz)
logger.info("TorchScript model saved β %s", path)
return str(path)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# INT8 Post-Training Quantization (PyTorch)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def quantize_int8(
weights: str = "best.pt",
output_path: str = "best_quantized.pt",
) -> str:
"""
Apply dynamic INT8 quantization to linear & conv layers.
Reduces model size ~4Γ with minimal accuracy loss.
"""
from torch.quantization import quantize_dynamic
model = YOLO(weights).model
quantized = quantize_dynamic(
model,
{torch.nn.Linear, torch.nn.Conv2d},
dtype=torch.qint8,
)
torch.save(quantized.state_dict(), output_path)
logger.info("INT8 quantized model β %s", output_path)
return output_path
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Benchmark
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def benchmark(
weights: str = "best.pt",
imgsz: int = 416,
warmup: int = 20,
runs: int = 100,
device: int = 0,
half: bool = True,
) -> Dict[str, Any]:
"""
Measure inference latency and throughput.
Returns dict with:
mean_ms, std_ms, min_ms, max_ms, fps
"""
model = YOLO(weights)
# Warm-up
dummy = np.random.randint(0, 255, (imgsz, imgsz, 3), dtype=np.uint8)
for _ in range(warmup):
model.predict(dummy, imgsz=imgsz, device=device, verbose=False)
times = []
for _ in range(runs):
t0 = time.perf_counter()
model.predict(dummy, imgsz=imgsz, device=device, verbose=False)
times.append(time.perf_counter() - t0)
times_ms = np.array(times) * 1000
results = {
"model": weights,
"imgsz": imgsz,
"device": str(device),
"runs": runs,
"mean_ms": float(times_ms.mean()),
"std_ms": float(times_ms.std()),
"min_ms": float(times_ms.min()),
"max_ms": float(times_ms.max()),
"fps": float(1000.0 / times_ms.mean()),
}
logger.info(
"Benchmark: %.1f Β± %.1f ms (%.1f FPS) [%s]",
results["mean_ms"], results["std_ms"], results["fps"], weights,
)
return results
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Raspberry Pi packaging helper
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def package_for_edge(
yolo_weights: str = "best.pt",
bigru_weights: Optional[str] = None,
imgsz: int = 416,
output_dir: str = "edge_package",
) -> str:
"""
Create a self-contained deployment package for edge devices.
Package contents:
edge_package/
model.tflite β quantised YOLO
bigru.pth β severity model (if available)
inference.py β standalone inference script
config.yaml β runtime config
"""
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
# Export TFLite
tflite_path = export_tflite(yolo_weights, imgsz=imgsz, int8=True)
import shutil
shutil.copy2(tflite_path, out / "model.tflite")
# Copy BiGRU weights
if bigru_weights and Path(bigru_weights).exists():
shutil.copy2(bigru_weights, out / "bigru.pth")
# Runtime config
import yaml
config = {
"model": "model.tflite",
"bigru": "bigru.pth" if bigru_weights else None,
"imgsz": imgsz,
"conf_threshold": 0.5,
"iou_threshold": 0.45,
"classes": ["Alligator Crack", "Longitudinal Crack", "Pothole", "Transverse Crack"],
"severity_labels": ["Minor", "Moderate", "Severe", "Critical"],
}
with open(out / "config.yaml", "w") as f:
yaml.dump(config, f)
# Copy inference script
inference_src = Path(__file__).parent / "inference.py"
if inference_src.exists():
shutil.copy2(inference_src, out / "inference.py")
logger.info("Edge package created β %s", out)
return str(out)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# CLI
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Deploy & Optimise Road Anomaly Models")
sub = parser.add_subparsers(dest="cmd", required=True)
# export
p_exp = sub.add_parser("export", help="Export model")
p_exp.add_argument("--weights", default="best.pt")
p_exp.add_argument("--format", default="engine",
choices=["engine", "onnx", "tflite", "torchscript"])
p_exp.add_argument("--imgsz", type=int, default=416)
p_exp.add_argument("--half", action="store_true", default=True)
p_exp.add_argument("--int8", action="store_true")
# quantize
p_q = sub.add_parser("quantize", help="INT8 quantization")
p_q.add_argument("--weights", default="best.pt")
p_q.add_argument("--output", default="best_quantized.pt")
# benchmark
p_b = sub.add_parser("benchmark", help="Measure speed")
p_b.add_argument("--weights", default="best.pt")
p_b.add_argument("--imgsz", type=int, default=416)
p_b.add_argument("--runs", type=int, default=100)
# package
p_p = sub.add_parser("package", help="Package for edge deployment")
p_p.add_argument("--weights", default="best.pt")
p_p.add_argument("--bigru", default=None)
p_p.add_argument("--imgsz", type=int, default=416)
p_p.add_argument("--output-dir", default="edge_package")
args = parser.parse_args()
if args.cmd == "export":
dispatch = {
"engine": export_tensorrt,
"onnx": export_onnx,
"tflite": export_tflite,
"torchscript": export_torchscript,
}
fn = dispatch[args.format]
kwargs = {"weights": args.weights, "imgsz": args.imgsz}
if args.format == "engine":
kwargs.update(half=args.half, int8=args.int8)
elif args.format == "tflite":
kwargs["int8"] = args.int8
fn(**kwargs)
elif args.cmd == "quantize":
quantize_int8(args.weights, args.output)
elif args.cmd == "benchmark":
results = benchmark(args.weights, imgsz=args.imgsz, runs=args.runs)
import json
print(json.dumps(results, indent=2))
elif args.cmd == "package":
package_for_edge(
yolo_weights=args.weights,
bigru_weights=args.bigru,
imgsz=args.imgsz,
output_dir=args.output_dir,
)
|