cctv-object-detection / scripts /export_onnx.py
openscopelabs's picture
feat(deploy): HF Spaces / CPU production stack
ed450db
Raw History Blame Contribute Delete
5.09 kB
"""Export a YOLO-World ``.pt`` checkpoint to ONNX for CPU production.
Why: PyTorch CPU inference of YOLO-World M @ 640 sits around 3 fps on
a shared HF Spaces basic tier (2 vCPU). ONNX Runtime — the C++ runtime
with SIMD + multi-threading + native graph optimisation — typically
delivers 3-5× on the same hardware. That brings single-camera demos
into 9-15 fps territory, which is "smooth enough" for a public Space.
Usage:
.venv/bin/python -m scripts.export_onnx # default: imgsz=640, fp32, dynamic=False
.venv/bin/python -m scripts.export_onnx --imgsz 960 --half
Trade-offs (honest):
• --half : FP16 weights → 1.5-2× more throughput, accuracy
drop typically <1%. Safe for production.
• --imgsz 640 : Matches the production inference window. Hard-
coded shape gives the runtime more graph fusion
opportunities than dynamic=True.
• YOLO-World has a text-encoder branch; the export bakes the *current*
class list into the graph. To change classes,
regenerate the .pt with scripts/setup_yolo_world.py
then re-export.
After export, point ``MODEL_PATH`` at the .onnx and ultralytics' YOLO()
auto-dispatches to onnxruntime — no other code changes needed. Set
``MODEL_BACKEND=onnx`` for explicit acknowledgement in startup logs.
"""
from __future__ import annotations
import argparse
import logging
import sys
from pathlib import Path
from ultralytics import YOLO
REPO_ROOT = Path(__file__).resolve().parents[1]
DEFAULT_PT = REPO_ROOT / "models" / "yolo-world-id.pt"
log = logging.getLogger("export_onnx")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument(
"--model", type=Path, default=DEFAULT_PT,
help=f"Source .pt checkpoint (default: {DEFAULT_PT.relative_to(REPO_ROOT)})",
)
parser.add_argument(
"--imgsz", type=int, default=640,
help="Image size baked into the graph (must match INFERENCE_SIZE at runtime).",
)
parser.add_argument(
"--half", action="store_true",
help="Export FP16 weights — ~2× faster, ~1% mAP drop. Recommended for CPU prod.",
)
parser.add_argument(
"--opset", type=int, default=12,
help="ONNX opset version. 12 is broadly compatible with onnxruntime CPU.",
)
parser.add_argument(
"--simplify", action="store_true", default=True,
help="Run onnx-simplifier post-export (folds constants, removes dead nodes).",
)
args = parser.parse_args()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
src: Path = args.model
if not src.exists():
log.error(
"model not found: %s — run scripts/setup_yolo_world.py first to "
"generate the YOLO-World checkpoint with your class list.",
src,
)
return 1
# Ultralytics rejects --half on non-CUDA exporters with only a warning,
# then silently produces an FP32 file. Make the trade-off explicit so
# the user can convert to FP16 post-export via onnxconverter-common
# rather than expecting half=True to "just work" on CPU.
try:
import torch # local import keeps CLI fast when torch is missing
cuda_available = torch.cuda.is_available()
except Exception:
cuda_available = False
if args.half and not cuda_available:
log.warning(
"--half requested but no CUDA device detected. Ultralytics only "
"honours FP16 export on GPU; the produced ONNX will be FP32. "
"For FP16 on CPU production, run a one-shot quantisation after "
"this script: "
"`from onnxconverter_common import float16; "
"float16.convert_float_to_float16_model_path(...)`."
)
args.half = False
log.info("loading %s", src)
model = YOLO(str(src))
log.info(
"exporting → ONNX (imgsz=%d, half=%s, opset=%d, simplify=%s)",
args.imgsz, args.half, args.opset, args.simplify,
)
# Ultralytics' export() returns the path to the produced file.
out = model.export(
format="onnx",
imgsz=args.imgsz,
half=args.half,
opset=args.opset,
simplify=args.simplify,
# Static shape gives onnxruntime more fusion headroom than dynamic.
# Set dynamic=True only if you must serve multiple input sizes from
# one .onnx (uncommon — re-export per imgsz is cheaper).
dynamic=False,
)
out_path = Path(out)
log.info("wrote %s (%.1f MB)", out_path, out_path.stat().st_size / 1_000_000)
log.info("")
log.info("Next step: point MODEL_PATH at the new file in your .env:")
log.info(" MODEL_PATH=%s", out_path.relative_to(REPO_ROOT))
log.info(" MODEL_BACKEND=onnx")
log.info("Restart cakra; the Detector log line will show 'backend=onnx'.")
return 0
if __name__ == "__main__":
sys.exit(main())