180 lines
6.9 KiB
Python
180 lines
6.9 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
convert.py - convert best_weld.pt -> best_weld.onnx -> best_weld.engine
|
|
|
|
RUN THIS ON THE JETSON. A TensorRT engine only works on the GPU / TensorRT
|
|
version it was built on, so an engine built in Colab will NOT run on the Orin Nano.
|
|
|
|
Project root : /home/jetson/projects_2026/welding
|
|
models/best_weld.pt (input)
|
|
models/best_weld.onnx (created)
|
|
models/best_weld.engine (created)
|
|
|
|
USAGE
|
|
-----
|
|
Default (FP16, Ultralytics builds the engine):
|
|
python3 convert.py
|
|
|
|
Explicit ONNX -> engine with trtexec (class-name metadata is added so the
|
|
inference script still knows the class names):
|
|
python3 convert.py --method trtexec
|
|
|
|
Other options:
|
|
python3 convert.py --imgsz 640 --precision fp32 --force
|
|
python3 convert.py --precision int8 --data weld_data.yaml # needs calibration data
|
|
"""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
|
|
from ultralytics import YOLO
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# CONFIG
|
|
# ---------------------------------------------------------------------------
|
|
# Override without editing the file: export WELD_HOME=/other/path
|
|
BASE_DIR = Path(os.environ.get("WELD_HOME", "/home/jetson/projects_2026/welding"))
|
|
MODELS_DIR = BASE_DIR / "models"
|
|
|
|
PT_PATH = MODELS_DIR / "best_weld.pt"
|
|
ONNX_PATH = MODELS_DIR / "best_weld.onnx"
|
|
ENGINE_PATH = MODELS_DIR / "best_weld.engine"
|
|
|
|
# The engine is locked to this size. Training used 640.
|
|
IMGSZ = 640
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Step 1: .pt -> .onnx
|
|
# ---------------------------------------------------------------------------
|
|
def pt_to_onnx(pt_path: Path, imgsz: int, force: bool) -> Path:
|
|
if ONNX_PATH.exists() and not force:
|
|
print(f"[1/2] ONNX already exists, skipping: {ONNX_PATH} (use --force to rebuild)")
|
|
return ONNX_PATH
|
|
|
|
print(f"[1/2] Exporting {pt_path.name} -> ONNX (imgsz={imgsz}) ...")
|
|
out = YOLO(str(pt_path)).export(
|
|
format="onnx", imgsz=imgsz, opset=12, simplify=True, dynamic=False)
|
|
out = Path(out)
|
|
if out.resolve() != ONNX_PATH.resolve():
|
|
shutil.move(str(out), str(ONNX_PATH))
|
|
print(f" Saved: {ONNX_PATH}")
|
|
return ONNX_PATH
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Step 2a: engine via Ultralytics (recommended)
|
|
# ---------------------------------------------------------------------------
|
|
def build_engine_ultralytics(pt_path: Path, imgsz: int, precision: str,
|
|
data: str, workspace: int) -> None:
|
|
print(f"[2/2] Building TensorRT engine with Ultralytics ({precision}) ...")
|
|
print(" This can take several minutes on the Orin Nano. Please wait.")
|
|
kwargs = dict(format="engine", imgsz=imgsz, device=0, workspace=workspace,
|
|
half=(precision == "fp16"), int8=(precision == "int8"))
|
|
if precision == "int8":
|
|
if not data:
|
|
sys.exit("INT8 needs calibration images: pass --data your_dataset.yaml")
|
|
kwargs["data"] = data
|
|
out = Path(YOLO(str(pt_path)).export(**kwargs))
|
|
if out.resolve() != ENGINE_PATH.resolve():
|
|
shutil.move(str(out), str(ENGINE_PATH))
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Step 2b: engine via trtexec (explicit route)
|
|
# ---------------------------------------------------------------------------
|
|
def find_trtexec() -> str:
|
|
found = shutil.which("trtexec")
|
|
if found:
|
|
return found
|
|
for p in ("/usr/src/tensorrt/bin/trtexec", "/usr/local/bin/trtexec"):
|
|
if Path(p).exists():
|
|
return p
|
|
sys.exit("trtexec not found. Try: export PATH=$PATH:/usr/src/tensorrt/bin "
|
|
"or use the default --method ultralytics")
|
|
|
|
|
|
def build_engine_trtexec(pt_path: Path, onnx_path: Path, imgsz: int,
|
|
precision: str, workspace: int) -> None:
|
|
trtexec = find_trtexec()
|
|
raw_engine = ENGINE_PATH.with_suffix(".raw.engine")
|
|
|
|
cmd = [trtexec, f"--onnx={onnx_path}", f"--saveEngine={raw_engine}",
|
|
f"--memPoolSize=workspace:{workspace * 1024}M"]
|
|
if precision == "fp16":
|
|
cmd.append("--fp16")
|
|
elif precision == "int8":
|
|
sys.exit("INT8 with trtexec needs a calibration cache; use --method ultralytics.")
|
|
|
|
print(f"[2/2] Building TensorRT engine with trtexec ({precision}) ...")
|
|
print(" " + " ".join(cmd))
|
|
subprocess.run(cmd, check=True)
|
|
|
|
# Ultralytics expects: [4-byte metadata length][JSON metadata][engine bytes].
|
|
# trtexec engines have no such header, so class names would be lost.
|
|
model = YOLO(str(pt_path))
|
|
meta = {
|
|
"description": "Weld detection (Bad Weld / Good Weld / Defect)",
|
|
"author": "custom",
|
|
"date": datetime.now().isoformat(),
|
|
"version": "custom",
|
|
"task": "detect",
|
|
"batch": 1,
|
|
"imgsz": [imgsz, imgsz],
|
|
"names": {int(k): v for k, v in model.names.items()},
|
|
"stride": 32,
|
|
}
|
|
meta_bytes = json.dumps(meta).encode("utf-8")
|
|
with open(ENGINE_PATH, "wb") as f:
|
|
f.write(len(meta_bytes).to_bytes(4, byteorder="little", signed=True))
|
|
f.write(meta_bytes)
|
|
f.write(raw_engine.read_bytes())
|
|
raw_engine.unlink()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
def parse_args():
|
|
p = argparse.ArgumentParser(description="Convert best_weld.pt -> ONNX -> TensorRT engine")
|
|
p.add_argument("--weights", type=str, default=str(PT_PATH), help="Path to the .pt file.")
|
|
p.add_argument("--imgsz", type=int, default=IMGSZ,
|
|
help="Input size baked into the engine (use your training size).")
|
|
p.add_argument("--precision", choices=["fp16", "fp32", "int8"], default="fp16")
|
|
p.add_argument("--method", choices=["ultralytics", "trtexec"], default="ultralytics",
|
|
help="How to build the engine.")
|
|
p.add_argument("--data", type=str, default=None, help="Dataset yaml (INT8 calibration only).")
|
|
p.add_argument("--workspace", type=int, default=4, help="TensorRT workspace in GB.")
|
|
p.add_argument("--force", action="store_true", help="Rebuild even if outputs exist.")
|
|
return p.parse_args()
|
|
|
|
|
|
def main():
|
|
args = parse_args()
|
|
pt_path = Path(args.weights)
|
|
if not pt_path.exists():
|
|
sys.exit(f"Weights not found: {pt_path}")
|
|
|
|
MODELS_DIR.mkdir(parents=True, exist_ok=True)
|
|
onnx_path = pt_to_onnx(pt_path, args.imgsz, args.force)
|
|
|
|
if ENGINE_PATH.exists() and not args.force:
|
|
print(f"Engine already exists, skipping: {ENGINE_PATH} (use --force to rebuild)")
|
|
return
|
|
|
|
if args.method == "ultralytics":
|
|
build_engine_ultralytics(pt_path, args.imgsz, args.precision, args.data, args.workspace)
|
|
else:
|
|
build_engine_trtexec(pt_path, onnx_path, args.imgsz, args.precision, args.workspace)
|
|
|
|
print(f"\nDone.\n ONNX : {ONNX_PATH}\n Engine: {ENGINE_PATH}")
|
|
print("Next: python3 infer.py")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|