Repository navigation
Expand file tree
/
Copy pathexport_models.py
More file actions
executable file
·1552 lines (1276 loc) · 52.1 KB
/
Copy pathexport_models.py
File metadata and controls
executable file
·1552 lines (1276 loc) · 52.1 KB
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Unified YOLO Model Export Script
=================================
Export YOLO models in multiple formats for Triton deployment.
Formats:
--------
1. onnx - Standard ONNX (no NMS, needs CPU post-processing)
2. trt - Native TensorRT engine (no NMS, needs CPU post-processing)
3. onnx_end2end - ONNX with TensorRT EfficientNMS operators (GPU NMS)
4. trt_end2end - TRT engine with compiled NMS (fastest, built from onnx_end2end)
5. all - Export all formats (default)
Usage:
------
# Export all formats (default)
docker compose exec yolo-api python /app/export/export_models.py
# Export only end2end models
docker compose exec yolo-api python /app/export/export_models.py --formats onnx_end2end trt_end2end
# Export specific models
docker compose exec yolo-api python /app/export/export_models.py --models nano small
# Export everything
docker compose exec yolo-api python /app/export/export_models.py --formats all
"""
import os
import sys
from pathlib import Path
sys.path.insert(0, '/app/src')
# ----------------------------------------------------------------------------
# Toolchain guard — this exporter REQUIRES ultralytics < 8.4
# ----------------------------------------------------------------------------
# The EfficientNMS end2end patch (src/ultralytics_patches) targets the 8.3.x
# exporter API; ultralytics 8.4 (YOLO26) changed the end2end property and
# breaks it. The image ships a dedicated venv at /opt/venv-y11 with the pinned
# toolchain; when this script is launched under a newer ultralytics it
# transparently re-execs into that venv. YOLO26 exports (natively NMS-free,
# no patch needed) live in export/export_yolo26.py.
_Y11_VENV_PYTHON = os.environ.get('YOLO11_EXPORT_PYTHON', '/opt/venv-y11/bin/python')
def _ultralytics_is_pre_84() -> bool:
try:
from importlib.metadata import version
major, minor, *_rest = version('ultralytics').split('.')
return (int(major), int(minor)) < (8, 4)
except Exception:
return False
if not _ultralytics_is_pre_84():
if Path(_Y11_VENV_PYTHON).exists() and os.environ.get('_Y11_REEXEC') != '1':
os.environ['_Y11_REEXEC'] = '1'
os.execv(_Y11_VENV_PYTHON, [_Y11_VENV_PYTHON, *sys.argv])
raise SystemExit(
'export_models.py requires ultralytics<8.4 (EfficientNMS end2end patch) '
f'and no pinned toolchain was found at {_Y11_VENV_PYTHON}. '
'For YOLO26 models use export/export_yolo26.py instead.'
)
import argparse # noqa: E402
import gc # noqa: E402
import json # noqa: E402
import logging # noqa: E402
import re # noqa: E402
import shutil # noqa: E402
from typing import Any # noqa: E402
import yaml # noqa: E402
# Apply end2end patch for onnx_trt format
from config_write import write_generated_config # noqa: E402
from ultralytics_patches import apply_end2end_patch # noqa: E402
apply_end2end_patch()
# Import after patch (REQUIRED - patch must be applied before importing ultralytics)
import onnx # noqa: E402
import tensorrt as trt # noqa: E402
import torch # noqa: E402
from trt_utils import ( # noqa: E402
bake_fp16_onnx,
create_explicit_network,
enable_fp16,
engine_output_dtypes,
)
from ultralytics import YOLO # noqa: E402
from ultralytics.cfg import get_cfg # noqa: E402
from ultralytics.engine.exporter import Exporter # noqa: E402
# ============================================================================
# Logging Configuration
# ============================================================================
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s | %(levelname)-8s | %(message)s',
datefmt='%H:%M:%S',
)
logger = logging.getLogger(__name__)
# ============================================================================
# Configuration
# ============================================================================
# Default configurations for standard YOLO11 model sizes
# These can be overridden via --config-file or extended via --custom-model
DEFAULT_MODELS: dict[str, dict[str, Any]] = {
'nano': {
'pt_file': '/app/pytorch_models/yolo11n.pt',
'triton_name': 'yolov11_nano',
'max_batch': 128, # Nano is small, A6000 can handle this
'topk': 300,
},
'small': {
'pt_file': '/app/pytorch_models/yolo11s.pt',
'triton_name': 'yolov11_small',
'max_batch': 64,
'topk': 300,
},
'medium': {
'pt_file': '/app/pytorch_models/yolo11m.pt',
'triton_name': 'yolov11_medium',
'max_batch': 32,
'topk': 300,
},
'large': {
'pt_file': '/app/pytorch_models/yolo11l.pt',
'triton_name': 'yolov11_large',
'max_batch': 16, # Large model needs more memory
'topk': 300,
},
'xlarge': {
'pt_file': '/app/pytorch_models/yolo11x.pt',
'triton_name': 'yolov11_xlarge',
'max_batch': 8, # XLarge is very memory intensive
'topk': 300,
},
}
# Export settings
IMG_SIZE = 640
DEVICE = 0 if torch.cuda.is_available() else 'cpu' # GPU 0 or CPU fallback
HALF = bool(torch.cuda.is_available()) # FP16 on GPU, FP32 on CPU
WORKSPACE_GB = 4 # TensorRT workspace size in GB
# NMS settings (for end2end exports)
IOU_THRESHOLD = 0.7
CONF_THRESHOLD = 0.25
# ============================================================================
# Helper Functions
# ============================================================================
def validate_pt_file(pt_file: str) -> bool:
"""Validate that PyTorch model file exists and is readable."""
path = Path(pt_file)
if not path.exists():
logger.error(f'Model file not found: {pt_file}')
return False
if not path.is_file():
logger.error(f'Model path is not a file: {pt_file}')
return False
if path.stat().st_size == 0:
logger.error(f'Model file is empty: {pt_file}')
return False
return True
def check_gpu_memory(required_gb: float = 4.0) -> bool:
"""Check if sufficient GPU memory is available."""
try:
if torch.cuda.is_available():
free_memory = torch.cuda.get_device_properties(DEVICE).total_memory
free_memory_gb = free_memory / (1024**3)
if free_memory_gb < required_gb:
logger.warning(
f'Low GPU memory: {free_memory_gb:.1f}GB available, {required_gb}GB recommended'
)
return True
logger.warning('CUDA not available to PyTorch, but continuing (TensorRT may still work)')
return True # TensorRT export doesn't require torch.cuda.is_available()
except Exception as e:
logger.warning(f'Could not check GPU memory: {e}')
return True # Continue anyway
def backup_existing_file(file_path: Path, suffix: str = '.old') -> None:
"""Backup existing file if it exists."""
if file_path.exists():
backup_path = file_path.with_suffix(file_path.suffix + suffix)
if backup_path.exists():
backup_path.unlink()
shutil.move(file_path, backup_path)
logger.debug(f'Backed up existing file to: {backup_path}')
def setup_trt_builder(
workspace_gb: int = WORKSPACE_GB,
) -> tuple[trt.Builder, trt.IBuilderConfig, trt.INetworkDefinition, trt.Logger]:
"""
Set up TensorRT builder with common configuration.
Args:
workspace_gb: Workspace size in GB
Returns:
Tuple of (builder, config, network, logger)
"""
# F-09/F-12 (fresh-start E2E findings 2026-09-25): this script runs
# under /opt/venv-y11's deliberately CPU-only torch (see
# requirements-export-y11.txt), so the ONNX-export step above always
# passes device='cpu' to Ultralytics. Ultralytics' own
# select_device('cpu') sets os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
# as a side effect, in-process -- CUDA_VISIBLE_DEVICES is read by the
# driver, not by torch, so it blinds the TensorRT builder below too
# (createInferBuilder fails with a CUDA initialization error), even
# though a bare tensorrt.Builder() in an unpoisoned process works
# fine. The engine build never uses torch's CUDA (see that same
# requirements file's own comment), so clearing the poisoned value
# here is safe and restores what this process would see without
# Ultralytics having touched it.
if os.environ.get('CUDA_VISIBLE_DEVICES') == '-1':
logger.warning(
"Clearing CUDA_VISIBLE_DEVICES=-1 (set by Ultralytics' CPU-mode "
'ONNX export in this process) before building the TensorRT engine'
)
os.environ.pop('CUDA_VISIBLE_DEVICES', None)
trt_logger = trt.Logger(trt.Logger.INFO)
trt.init_libnvinfer_plugins(trt_logger, '')
builder = trt.Builder(trt_logger)
config = builder.create_builder_config()
# Set workspace size (TRT >= 10 memory-pool API; requirements pin TRT 11)
workspace_bytes = int(workspace_gb * (1 << 30))
config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace_bytes)
network = create_explicit_network(builder)
return builder, config, network, trt_logger
def add_optimization_profile(
builder: trt.Builder,
config: trt.IBuilderConfig,
network: trt.INetworkDefinition,
max_batch: int,
) -> None:
"""Add optimization profile for dynamic batching."""
profile = builder.create_optimization_profile()
min_shape = (1, 3, IMG_SIZE, IMG_SIZE)
opt_shape = (max_batch // 2, 3, IMG_SIZE, IMG_SIZE)
max_shape = (max_batch, 3, IMG_SIZE, IMG_SIZE)
for i in range(network.num_inputs):
inp = network.get_input(i)
profile.set_shape(inp.name, min=min_shape, opt=opt_shape, max=max_shape)
logger.debug(f' {inp.name}: min={min_shape}, opt={opt_shape}, max={max_shape}')
config.add_optimization_profile(profile)
# ============================================================================
# Configuration Loading Functions
# ============================================================================
def load_config_file(config_path: str) -> dict[str, dict[str, Any]]:
"""
Load model configurations from a YAML file.
Expected YAML format:
```yaml
models:
my_custom_model:
pt_file: /path/to/model.pt
triton_name: my_model_name # optional, auto-generated if not provided
max_batch: 32 # optional, default 32
topk: 300 # optional, default 300
num_classes: 80 # optional, auto-detected from model
class_names: # optional, auto-detected from model
- person
- car
- ...
```
Args:
config_path: Path to YAML configuration file
Returns:
Dictionary of model configurations
"""
path = Path(config_path)
if not path.exists():
raise FileNotFoundError(f'Config file not found: {config_path}')
with open(path) as f:
config = yaml.safe_load(f)
if 'models' not in config:
raise ValueError("Config file must have a 'models' section")
models = {}
for model_id, model_config in config['models'].items():
if 'pt_file' not in model_config:
raise ValueError(f"Model '{model_id}' must have 'pt_file' specified")
# Set defaults
models[model_id] = {
'pt_file': model_config['pt_file'],
'triton_name': model_config.get('triton_name', _generate_triton_name(model_id)),
'max_batch': model_config.get('max_batch', 32),
'topk': model_config.get('topk', 300),
}
# Optional class configuration
if 'num_classes' in model_config:
models[model_id]['num_classes'] = model_config['num_classes']
if 'class_names' in model_config:
models[model_id]['class_names'] = model_config['class_names']
logger.info(f'Loaded {len(models)} model(s) from config: {config_path}')
return models
def parse_custom_model(custom_model_arg: str) -> tuple[str, dict[str, Any]]:
"""
Parse a custom model argument string.
Format: path/to/model.pt[:name][:max_batch]
Examples:
- /path/to/my_model.pt -> auto name, batch=32
- /path/to/my_model.pt:custom_name -> custom_name, batch=32
- /path/to/my_model.pt:custom_name:64 -> custom_name, batch=64
- /path/to/my_model.pt::16 -> auto name, batch=16
Args:
custom_model_arg: Custom model specification string
Returns:
Tuple of (model_id, config_dict)
"""
parts = custom_model_arg.split(':')
pt_file = parts[0]
if not Path(pt_file).exists():
# Try with /app prefix for container paths
container_path = f'/app/{pt_file.lstrip("/")}'
if Path(container_path).exists():
pt_file = container_path
else:
raise FileNotFoundError(f'Model file not found: {parts[0]}')
# Extract model ID from filename
model_id = Path(pt_file).stem
# Parse optional name
triton_name = parts[1] if len(parts) > 1 and parts[1] else _generate_triton_name(model_id)
# Parse optional max_batch
max_batch = int(parts[2]) if len(parts) > 2 and parts[2] else 32
config = {
'pt_file': pt_file,
'triton_name': triton_name,
'max_batch': max_batch,
'topk': 300,
}
logger.info(f'Custom model: {model_id} -> {triton_name} (batch={max_batch})')
return model_id, config
def _generate_triton_name(model_id: str) -> str:
"""
Generate a Triton-compatible model name from model ID.
Converts names like 'yolo11s' to 'yolov11_small', 'my-custom-model' to 'my_custom_model'.
"""
# Known YOLO11 size mappings
size_map = {
'n': 'nano',
's': 'small',
'm': 'medium',
'l': 'large',
'x': 'xlarge',
}
# Check for yolo11X pattern
match = re.match(r'yolo11([nsmxl])$', model_id.lower())
if match:
size = size_map.get(match.group(1), match.group(1))
return f'yolov11_{size}'
# General cleanup: replace hyphens with underscores, lowercase
name = model_id.lower().replace('-', '_')
# Remove .pt extension if present
if name.endswith('.pt'):
name = name[:-3]
return name
# ============================================================================
# Class Name Extraction and Labels
# ============================================================================
def extract_class_names(model: 'YOLO') -> list[str]:
"""
Extract class names from a loaded YOLO model.
Args:
model: Loaded YOLO model instance
Returns:
List of class names in order (index = class_id)
"""
try:
# YOLO models store class names in model.names
if hasattr(model, 'names'):
names = model.names
if isinstance(names, dict):
# Convert dict {0: 'person', 1: 'bicycle', ...} to list
max_idx = max(names.keys())
return [names.get(i, f'class_{i}') for i in range(max_idx + 1)]
if isinstance(names, list):
return names
# Fallback: check model.model.names
if hasattr(model, 'model') and hasattr(model.model, 'names'):
names = model.model.names
if isinstance(names, dict):
max_idx = max(names.keys())
return [names.get(i, f'class_{i}') for i in range(max_idx + 1)]
if isinstance(names, list):
return names
logger.warning('Could not extract class names from model')
return []
except Exception as e:
logger.warning(f'Error extracting class names: {e}')
return []
def save_labels_file(class_names: list[str], model_dir: Path) -> Path | None:
"""
Save class names to labels.txt file in model directory.
Args:
class_names: List of class names
model_dir: Model directory path (e.g., /app/models/yolov11_small_trt)
Returns:
Path to saved labels file, or None if no classes to save
"""
if not class_names:
return None
labels_path = model_dir / 'labels.txt'
with open(labels_path, 'w') as f:
for name in class_names:
f.write(f'{name}\n')
logger.info(f'Saved {len(class_names)} class names to: {labels_path}')
return labels_path
# ============================================================================
# Triton Config Generation
# ============================================================================
def generate_triton_config(
triton_name: str,
model_format: str,
max_batch: int,
num_classes: int = 80,
has_nms: bool = False,
output_dtypes: dict[str, str] | None = None,
) -> str:
"""
Generate Triton config.pbtxt content for a model.
Args:
triton_name: Triton model name
model_format: Model format ('onnx', 'trt', 'trt_end2end')
max_batch: Maximum batch size
num_classes: Number of classes (default 80 for COCO)
has_nms: Whether model has built-in NMS (end2end models)
Returns:
config.pbtxt content as string
"""
# Determine backend
if model_format in ('trt', 'trt_end2end'):
backend = 'tensorrt'
else:
backend = 'onnxruntime'
# Calculate preferred batch sizes
preferred_batches = [size for size in [8, 16, 32, 64] if size <= max_batch]
if not preferred_batches:
preferred_batches = [1]
preferred_batch_str = ', '.join(str(b) for b in preferred_batches)
# Determine platform string
platform = f'{backend}_plan' if backend == 'tensorrt' else 'onnxruntime_onnx'
if has_nms:
# End2End model with NMS outputs. Box/score precision follows the
# BUILT engine (differs across TRT releases) — see engine_output_dtypes.
dtypes = output_dtypes or {}
box_dtype = dtypes.get('det_boxes', 'TYPE_FP32')
score_dtype = dtypes.get('det_scores', 'TYPE_FP32')
config = f"""name: "{triton_name}"
platform: "{platform}"
max_batch_size: {max_batch}
input [
{{
name: "images"
data_type: TYPE_FP32
dims: [ 3, {IMG_SIZE}, {IMG_SIZE} ]
}}
]
output [
{{
name: "num_dets"
data_type: TYPE_INT32
dims: [ 1 ]
}},
{{
name: "det_boxes"
data_type: {box_dtype}
dims: [ 300, 4 ]
}},
{{
name: "det_scores"
data_type: {score_dtype}
dims: [ 300 ]
}},
{{
name: "det_classes"
data_type: TYPE_INT32
dims: [ 300 ]
}}
]
dynamic_batching {{
preferred_batch_size: [ {preferred_batch_str} ]
max_queue_delay_microseconds: 5000
}}
instance_group [
{{
count: 2
kind: KIND_GPU
gpus: [ 0 ]
}}
]
"""
else:
# Standard model without NMS
# Output shape: [batch, 84, 8400] for YOLO11 with 80 classes
output_dim_1 = 4 + num_classes # 4 bbox coords + num_classes
config = f"""name: "{triton_name}"
platform: "{platform}"
max_batch_size: {max_batch}
input [
{{
name: "images"
data_type: TYPE_FP32
dims: [ 3, {IMG_SIZE}, {IMG_SIZE} ]
}}
]
output [
{{
name: "output0"
data_type: TYPE_FP32
dims: [ {output_dim_1}, 8400 ]
}}
]
dynamic_batching {{
preferred_batch_size: [ {preferred_batch_str} ]
max_queue_delay_microseconds: 5000
}}
instance_group [
{{
count: 2
kind: KIND_GPU
gpus: [ 0 ]
}}
]
"""
return config
def save_triton_config(
model_dir: Path,
triton_name: str,
model_format: str,
max_batch: int,
num_classes: int = 80,
has_nms: bool = False,
output_dtypes: dict[str, str] | None = None,
overwrite: bool = False,
) -> Path:
"""
Save Triton config.pbtxt file for a model (see ``config_write``: an
existing config that differs is kept unless ``overwrite``).
Args:
model_dir: Model directory path
triton_name: Triton model name
model_format: Model format
max_batch: Maximum batch size
num_classes: Number of classes
has_nms: Whether model has built-in NMS
Returns:
Path to saved config file
"""
config_content = generate_triton_config(
triton_name=triton_name,
model_format=model_format,
max_batch=max_batch,
num_classes=num_classes,
has_nms=has_nms,
output_dtypes=output_dtypes,
)
return write_generated_config(model_dir / 'config.pbtxt', config_content, overwrite=overwrite)
def enable_fp16_if_available(builder: trt.Builder, config: trt.IBuilderConfig) -> bool:
"""Enable FP16 precision where supported (see trt_utils.enable_fp16)."""
if enable_fp16(builder, config):
logger.info('FP16 precision enabled')
return True
logger.info(
'Building typed precision (TRT 11 strongly-typed: FP32 weights + TF32 '
'tensor cores; bake FP16 into the ONNX via ModelOpt AutoCast to go faster)'
)
return False
def parse_onnx_model(
parser: trt.OnnxParser,
onnx_path: Path,
) -> bool:
"""Parse ONNX model and report any errors."""
logger.info('Baking FP16 (ModelOpt AutoCast, TRT 11 typed builds)...')
onnx_path = bake_fp16_onnx(onnx_path)
if not parser.parse_from_file(str(onnx_path)):
logger.error('Failed to parse ONNX model:')
for i in range(parser.num_errors):
error = parser.get_error(i)
logger.error(f' [{i}] {error}')
return False
return True
def build_and_save_engine(
builder: trt.Builder,
network: trt.INetworkDefinition,
config: trt.IBuilderConfig,
output_path: Path,
) -> bool:
"""Build TensorRT engine and save to file."""
# Free memory before building
gc.collect()
torch.cuda.empty_cache()
logger.info('Building TensorRT engine (this may take 5-10 minutes)...')
try:
serialized_engine = builder.build_serialized_network(network, config)
if serialized_engine is None:
logger.error('Failed to build engine - builder returned None')
return False
with open(output_path, 'wb') as f:
f.write(serialized_engine)
file_size_mb = output_path.stat().st_size / (1024 * 1024)
logger.info(f'Engine saved: {output_path} ({file_size_mb:.2f} MB)')
return True
except Exception as e:
logger.error(f'Engine build failed: {e}')
return False
# ============================================================================
# Export Functions
# ============================================================================
def export_onnx_standard(model: YOLO, config: dict[str, Any]) -> dict[str, Any]:
"""
Export standard ONNX model (no NMS).
Args:
model: Loaded YOLO model
config: Model configuration dict with triton_name, max_batch, etc.
Returns:
Dict with status, path, and output format info
"""
logger.info('=' * 60)
logger.info('[1/4] Standard ONNX Export (ONNX Runtime + TensorRT EP)')
logger.info('=' * 60)
try:
logger.info('Exporting ONNX with dynamic batching...')
logger.info(' - dynamic=True: Variable batch, height, width')
logger.info(' - simplify=True: Optimizes graph for TensorRT')
onnx_path = model.export(
format='onnx',
imgsz=IMG_SIZE,
device=DEVICE,
dynamic=True,
simplify=True,
half=HALF,
verbose=False,
)
# Move to Triton model repository
triton_name = config['triton_name']
onnx_model_dir = Path(f'/app/models/{triton_name}/1')
onnx_model_dir.mkdir(parents=True, exist_ok=True)
onnx_dest = onnx_model_dir / 'model.onnx'
backup_existing_file(onnx_dest)
shutil.copy2(onnx_path, onnx_dest)
logger.info(f'ONNX saved to: {onnx_dest}')
logger.info('Output: [84, 8400] - needs CPU NMS post-processing')
return {
'status': 'success',
'path': str(onnx_dest),
'host_path': str(onnx_dest).replace('/app/models', './models'),
'output_format': '[84, 8400] - raw detections',
}
except Exception as e:
logger.exception(f'ONNX export failed: {e}')
return {'status': 'error', 'error': str(e)}
def export_trt_standard(model: YOLO, config: dict[str, Any]) -> dict[str, Any]:
"""
Export native TensorRT engine from standard ONNX (no NMS).
Args:
model: Loaded YOLO model
config: Model configuration dict
Returns:
Dict with status, path, and output format info
"""
logger.info('=' * 60)
logger.info('[2/4] Standard TensorRT Engine Export (no NMS)')
logger.info('=' * 60)
try:
triton_name = config['triton_name']
max_batch = config['max_batch']
# First, check if we have standard ONNX, if not export it
onnx_path = Path(f'/app/models/{triton_name}/1/model.onnx')
if not onnx_path.exists():
logger.info('Standard ONNX not found, exporting first...')
result = export_onnx_standard(model, config)
if result.get('status') != 'success':
return result
logger.info(f'Using standard ONNX: {onnx_path}')
logger.info(f'Dynamic batch: min=1, opt={max_batch // 2}, max={max_batch}')
logger.info(f'Workspace: {WORKSPACE_GB}GB, Precision: {"FP16" if HALF else "FP32"}')
# Check GPU memory
check_gpu_memory(WORKSPACE_GB)
# Setup TensorRT builder using helper
builder, config_trt, network, trt_logger = setup_trt_builder()
# Parse ONNX
logger.info('Parsing ONNX model...')
parser = trt.OnnxParser(network, trt_logger)
if not parse_onnx_model(parser, onnx_path):
return {'status': 'error', 'error': 'ONNX parsing failed'}
# Set optimization profile
logger.info('Setting optimization profile...')
add_optimization_profile(builder, config_trt, network, max_batch)
# Set FP16
enable_fp16_if_available(builder, config_trt)
# Prepare output path
trt_model_dir = Path(f'/app/models/{triton_name}_trt/1')
trt_model_dir.mkdir(parents=True, exist_ok=True)
trt_dest = trt_model_dir / 'model.plan'
backup_existing_file(trt_dest)
# Build and save engine
if not build_and_save_engine(builder, network, config_trt, trt_dest):
return {'status': 'error', 'error': 'Failed to build engine'}
logger.info('Output format: [84, 8400] - raw detections (CPU NMS needed)')
return {
'status': 'success',
'path': str(trt_dest),
'host_path': str(trt_dest).replace('/app/models', './models'),
'output_format': '[84, 8400] - raw detections',
}
except Exception as e:
logger.exception(f'TensorRT export failed: {e}')
return {'status': 'error', 'error': str(e)}
def export_onnx_end2end(
model: YOLO, config: dict[str, Any], normalize_boxes: bool = True
) -> dict[str, Any]:
"""
Export ONNX with TensorRT EfficientNMS operators (GPU NMS).
Args:
model: Loaded YOLO model
config: Model configuration dict
normalize_boxes: If True, output boxes in [0,1] range; otherwise pixel coords
Returns:
Dict with status, path, and output format info
"""
logger.info('=' * 60)
logger.info('[3/4] ONNX End2End Export (with GPU NMS operators)')
logger.info('=' * 60)
try:
topk = config['topk']
box_format_str = '[0,1] range' if normalize_boxes else 'pixel coords (640x640)'
logger.info('Exporting ONNX with EfficientNMS plugin...')
logger.info(f' topk_all={topk}, iou_thres={IOU_THRESHOLD}, conf_thres={CONF_THRESHOLD}')
logger.info(f' normalize_boxes={normalize_boxes}: {box_format_str}')
# Create export arguments with standard ONNX format
args = get_cfg(
overrides={
'format': 'onnx',
'imgsz': IMG_SIZE,
'dynamic': True,
'simplify': True,
'half': HALF,
'device': DEVICE,
'opset': 17,
}
)
# Add custom End2End arguments
args.topk_all = topk
args.iou_thres = IOU_THRESHOLD
args.conf_thres = CONF_THRESHOLD
args.class_agnostic = True
args.mask_resolution = 56
args.pooler_scale = 0.25
args.sampling_ratio = 0
args.normalize_boxes = normalize_boxes
# Create and configure exporter
exporter = Exporter(cfg=args, _callbacks=model.callbacks)
exporter.args = args
exporter.model = model.model.to(DEVICE)
if hasattr(model, 'overrides'):
exporter.model.args = model.overrides
exporter.im = torch.zeros(1, 3, IMG_SIZE, IMG_SIZE).to(DEVICE)
exporter.file = Path(config['pt_file'])
# Call export_onnx_trt directly
logger.info('Calling patched export_onnx_trt() method...')
export_path, _ = exporter.export_onnx_trt(prefix='ONNX TRT:')
# Move to Triton model repository
triton_name = config['triton_name']
onnx_model_dir = Path(f'/app/models/{triton_name}_end2end/1')
onnx_model_dir.mkdir(parents=True, exist_ok=True)
onnx_dest = onnx_model_dir / 'model.onnx'
export_file = Path(export_path)
if not export_file.exists():
logger.error(f'Export failed, file not found: {export_file}')
return {'status': 'error', 'error': 'Export file not found'}
backup_existing_file(onnx_dest)
shutil.copy2(export_file, onnx_dest)
logger.info(f'ONNX End2End saved to: {onnx_dest}')
logger.info('Contains: TRT::EfficientNMS_TRT operators')
logger.info('Output: num_dets, det_boxes, det_scores, det_classes')
# Verify NMS plugin is present
try:
onnx_model = onnx.load(str(onnx_dest))
ops = [node.op_type for node in onnx_model.graph.node]
has_nms = any('NMS' in op or 'TRT' in op for op in ops)
if has_nms:
logger.info('Verified: NMS plugin in ONNX graph')
else:
logger.warning('No NMS operators found in ONNX graph!')
except Exception as e:
logger.debug(f'Could not verify ONNX operators: {e}')
box_format = '[0,1] normalized' if normalize_boxes else 'pixel coords (640x640)'
return {
'status': 'success',
'path': str(onnx_dest),
'host_path': str(onnx_dest).replace('/app/models', './models'),
'has_nms': True,
'output_format': 'num_dets, det_boxes, det_scores, det_classes',
'box_format': box_format,
}
except Exception as e:
logger.exception(f'ONNX End2End export failed: {e}')
return {'status': 'error', 'error': str(e)}
def export_trt_end2end(config: dict[str, Any]) -> dict[str, Any]:
"""
Export TensorRT engine from end2end ONNX (compiled GPU NMS).
Args:
config: Model configuration dict
Returns:
Dict with status, path, and output format info
"""
logger.info('=' * 60)
logger.info('[4/4] TensorRT End2End Export (compiled GPU NMS)')
logger.info('=' * 60)
try:
triton_name = config['triton_name']
max_batch = config['max_batch']
# Check for end2end ONNX
onnx_end2end_path = Path(f'/app/models/{triton_name}_end2end/1/model.onnx')
if not onnx_end2end_path.exists():
logger.error(f'End2End ONNX not found: {onnx_end2end_path}')
logger.error('Run with --formats onnx_end2end first!')
return {'status': 'error', 'error': 'End2End ONNX not found'}
logger.info(f'Using end2end ONNX: {onnx_end2end_path}')
logger.info(f'Dynamic batch: min=1, opt={max_batch // 2}, max={max_batch}')
logger.info(f'Workspace: {WORKSPACE_GB}GB, Precision: {"FP16" if HALF else "FP32"}')
# Check GPU memory
check_gpu_memory(WORKSPACE_GB)
# Setup TensorRT builder using helper
builder, config_trt, network, trt_logger = setup_trt_builder()
logger.info('TensorRT plugins initialized (EfficientNMS available)')
# Parse ONNX
logger.info('Parsing ONNX model...')
parser = trt.OnnxParser(network, trt_logger)
if not parse_onnx_model(parser, onnx_end2end_path):
return {'status': 'error', 'error': 'ONNX parsing failed'}
# Log network structure