Image Classification
vision
cnn
mobile
mathmanu commited on
Commit
1dd5596
Β·
verified Β·
1 Parent(s): 8f9c187

Add mobilenetv3 model files

Browse files
Files changed (3) hide show
  1. README.md +184 -0
  2. mobilenetv3_large_config.yaml +36 -0
  3. prepare_model.py +502 -0
README.md ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: bsd-3-clause
3
+ tags:
4
+ - vision
5
+ - image-classification
6
+ - cnn
7
+ - mobile
8
+ datasets:
9
+ - imagenet-1k
10
+ ---
11
+
12
+ <div align="center">
13
+
14
+ # MobileNetV3 for TI EdgeAI
15
+
16
+ ### Efficient Mobile CNN for Image Classification
17
+
18
+ [![License](https://img.shields.io/badge/License-BSD--3--Clause-blue?style=for-the-badge)](https://opensource.org/licenses/BSD-3-Clause)
19
+ [![Framework](https://img.shields.io/badge/Framework-ONNX-orange?style=for-the-badge)](https://onnx.ai/)
20
+ [![Task](https://img.shields.io/badge/Task-Classification-green?style=for-the-badge)](https://github.com/TexasInstruments/edgeai)
21
+ [![Dataset](https://img.shields.io/badge/Dataset-ImageNet--1K-blueviolet?style=for-the-badge)](http://www.image-net.org/)
22
+
23
+ </div>
24
+
25
+ ---
26
+
27
+ ## Overview
28
+
29
+ **MobileNetV3** ([Searching for MobileNetV3](https://arxiv.org/abs/1905.02244), Howard et al., 2019) combines hardware-aware Neural Architecture Search (NAS) with NetAdapt and a redesigned last stage to deliver state-of-the-art accuracy for mobile and edge inference. Key improvements over MobileNetV2 include hard-swish activations, squeeze-and-excitation modules in the bottleneck layers, and an optimized final classifier.
30
+
31
+ Both variants are evaluated at **224Γ—224** input resolution on **ImageNet-1K** and distributed via [torchvision](https://pytorch.org/vision/stable/models/mobilenetv3.html).
32
+
33
+ ---
34
+
35
+ ## Model Variants
36
+
37
+ | Model | Architecture | Params | GFLOPs | Top-1 Acc | Top-5 Acc | Validated Devices | Config |
38
+ |-------|---------------|--------|--------|-----------|-----------|--------------------|--------|
39
+ | `mobilenetv3_large` | MobileNetV3-Large | 5.48M | 0.22 | **75.274%** | 92.566% | TDA4VH | [mobilenetv3_large_config.yaml](mobilenetv3_large_config.yaml) |
40
+ | `mobilenetv3_small` | MobileNetV3-Small | 2.54M | 0.06 | 67.668% | 87.402% | N/A | N/A |
41
+
42
+ `mobilenetv3_large` uses `IMAGENET1K_V2` weights (improved training recipe). `mobilenetv3_small` is excluded from `prepare_model.py`'s export catalog because it produces poor accuracy under TIDL compilation β€” the `mobilenetv3_small.onnx` bundled in this folder is provided for reference only and has no validated TIDL config.
43
+
44
+ **Recommended for edge deployment:** `mobilenetv3_large` (best accuracy/compute trade-off with a validated TIDL config)
45
+
46
+ ---
47
+
48
+ ## Quick Start
49
+
50
+ ### Prerequisites
51
+
52
+ ```bash
53
+ pip install torch torchvision onnx>=1.14.0 onnxruntime>=1.16.0
54
+ # Optional but recommended for model optimization:
55
+ pip install onnx-simplifier
56
+ ```
57
+
58
+ ### Export the Model
59
+
60
+ ```bash
61
+ # Export the default model (MobileNetV3-Large)
62
+ python prepare_model.py
63
+
64
+ # Export a specific model variant
65
+ python prepare_model.py --model mobilenetv3_large
66
+
67
+ # Export with a custom input resolution
68
+ python prepare_model.py --model mobilenetv3_large --shape 224 224
69
+
70
+ # List all available variants
71
+ python prepare_model.py --list-models
72
+ ```
73
+
74
+ The script automatically:
75
+ - Downloads pretrained ImageNet-1K weights from torchvision (`MobileNet_V3_Large_Weights.IMAGENET1K_V2`)
76
+ - Exports to ONNX (opset 17) with a static `[1, 3, 224, 224]` input shape
77
+ - Runs ONNX shape inference across all intermediate tensors
78
+ - Optionally simplifies the graph with onnxsim (use `--no-simplify` to skip)
79
+
80
+ > Note: `mobilenetv3_small` is currently excluded from the export catalog (poor accuracy under TIDL compilation), so `--model mobilenetv3_small` and `--model all` only produce `mobilenetv3_large`.
81
+
82
+ ### Compile and Infer uing edgeai-tidlrunner
83
+
84
+ > **Note:** Run the commands below from inside the `tidlrunner` directory (the cloned [edgeai-tidlrunner](https://github.com/TexasInstruments/edgeai-tidlrunner) repository), with `--config_path` pointing to this model's config file.
85
+
86
+ **Compile using edgeai-tidlrunner - on PC**
87
+
88
+ ```bash
89
+ cd /path/to/edgeai-tidlrunner
90
+ tidlrunner-cli compile --target_device J784S4 \
91
+ --config_path /path/to/mobilenetv3_large_config.yaml
92
+ ```
93
+
94
+ **Run Inference Benchmark - on device**
95
+
96
+ ```bash
97
+ cd /path/to/edgeai-tidlrunner
98
+ tidlrunner-cli infer --target_device J784S4 \
99
+ --config_path /path/to/mobilenetv3_large_config.yaml
100
+ ```
101
+
102
+ ### Compile and Infer using edgeai-tidl-tools (Advanced):
103
+
104
+ Follow the instructions at https://github.com/TexasInstruments/edgeai-tidl-tools
105
+
106
+ ### Deploy using edgeai-tidl-tools:
107
+
108
+ Deplyment can be done using **[edgeai-tidl-tools](https://github.com/TexasInstruments/edgeai-tidl-tools)**. For ONNX models, onnxruntime-tidl with TIDL acceleration can be used. Consult the documentation of edgeai-tidl-tools for more details.
109
+
110
+ ---
111
+
112
+ ## Citation
113
+
114
+ If you use these models, please cite:
115
+
116
+ ```bibtex
117
+ @inproceedings{Howard2019MobileNetV3,
118
+ title = {Searching for MobileNetV3},
119
+ author = {Howard, Andrew and Sandler, Mark and Chu, Grace and Chen, Liang-Chieh
120
+ and Chen, Bo and Tan, Mingxing and Wang, Weijun and Zhu, Yukun
121
+ and Pang, Ruoming and Vasudevan, Vijay and Le, Quoc V. and Adam, Hartwig},
122
+ booktitle = {Proceedings of the IEEE/CVF International Conference on Computer Vision (ICCV)},
123
+ year = {2019}
124
+ }
125
+ ```
126
+
127
+ ---
128
+
129
+ ## πŸ”— Resources
130
+
131
+ | Resource | Link |
132
+ |----------|------|
133
+ | **Paper** | [arXiv:1905.02244](https://arxiv.org/abs/1905.02244) |
134
+ | **PyTorch Docs** | [torchvision MobileNetV3](https://pytorch.org/vision/stable/models/mobilenetv3.html) |
135
+ | **Source Code** | [pytorch/vision](https://github.com/pytorch/vision/blob/main/torchvision/models/mobilenetv3.py) |
136
+ | **edgeai-tidl-tools** | [GitHub](https://github.com/TexasInstruments/edgeai-tidl-tools) |
137
+ | **edgeai-tidlrunner** | [GitHub](https://github.com/TexasInstruments/edgeai-tidlrunner) |
138
+ | **EdgeAI SDK** | [Documentation](https://github.com/TexasInstruments/edgeai/blob/main/edgeai-mpu/readme_sdk.md) |
139
+
140
+ ---
141
+
142
+ ## Related Models
143
+
144
+ <table>
145
+ <tr>
146
+ <td align="center">
147
+
148
+ **ResNet**
149
+ Deeper CNN
150
+ Higher accuracy
151
+
152
+ </td>
153
+ <td align="center">
154
+
155
+ **ConvNeXt**
156
+ Modern CNN
157
+ ViT-inspired design
158
+
159
+ </td>
160
+ <td align="center">
161
+
162
+ **ViT**
163
+ Vision Transformer
164
+ Attention-based
165
+
166
+ </td>
167
+ <td align="center">
168
+
169
+ **DINOv2**
170
+ Self-supervised
171
+ Rich feature embeddings
172
+
173
+ </td>
174
+ </tr>
175
+ </table>
176
+
177
+ ---
178
+
179
+ <div align="center">
180
+
181
+ **Maintained by:** Texas Instruments EdgeAI Team
182
+ **Last Updated:** August 2026
183
+
184
+ </div>
mobilenetv3_large_config.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ task_type: classification
2
+ #dataset_category: imagenet
3
+ #calibration_dataset: imagenet
4
+ #input_dataset: imagenet
5
+ dataloader:
6
+ name: image_classification_dataloader
7
+ path: ./data/datasets/imagenetv2c/val
8
+ postprocess: {}
9
+ preprocess:
10
+ resize: 256
11
+ crop: 224
12
+ data_layout: NCHW
13
+ reverse_channels: false
14
+ backend: pil
15
+ interpolation: null
16
+ resize_with_pad: false
17
+ pad_color: 0
18
+ session:
19
+ session_name: onnxrt
20
+ target_device: null
21
+ input_optimization: false
22
+ input_data_layout: NCHW
23
+ input_mean: [123.675, 116.28, 103.53]
24
+ input_scale: [0.017125, 0.017507, 0.017429]
25
+ model_path: mobilenetv3_large.onnx
26
+ model_id: cl-mh6025
27
+ input_details: null
28
+ output_details: null
29
+ num_inputs: 1
30
+ model_info:
31
+ metric_reference:
32
+ accuracy_top1%: 75.274
33
+ model_shortlist: 10
34
+ compact_name: mobilenetv3-large-224x224
35
+ shortlisted: true
36
+ recommended: true
prepare_model.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Export MobileNetV3 classification models from torchvision to ONNX
4
+ for TI EdgeAI hardware deployment.
5
+
6
+ Model variants (BSD-3-Clause, ImageNet-1K pretrained):
7
+ mobilenetv3_large – 224Γ—224, 5.48M params, 0.22G FLOPs, top-1 75.274% [default]
8
+
9
+ Usage:
10
+ python prepare_model.py
11
+ python prepare_model.py --model mobilenetv3_large
12
+ python prepare_model.py --model mobilenetv3_large --shape 224 224
13
+ python prepare_model.py --model all
14
+ python prepare_model.py --model mobilenetv3_large --weights /path/to/custom.pth
15
+ python prepare_model.py --list-models
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import importlib
22
+ import os
23
+ import shutil
24
+ import subprocess
25
+ import sys
26
+ import tempfile
27
+
28
+
29
+ # ─────────────────────────────────────────────
30
+ # Model catalogue
31
+ # ─────────────────────────────────────────────
32
+
33
+ MODEL_CATALOG: dict[str, dict] = {
34
+ "mobilenetv3_large": {
35
+ "tv_weights": "MobileNet_V3_Large_Weights.IMAGENET1K_V2",
36
+ "backbone": "MobileNetV3-Large",
37
+ "shape": (224, 224),
38
+ "params_m": 5.48,
39
+ "flops_g": 0.22,
40
+ "top1_acc": 75.274,
41
+ "top5_acc": 92.566,
42
+ "license": "BSD-3-Clause",
43
+ },
44
+ # "mobilenetv3_small": excluded β€” produces poor accuracy under TIDL compilation
45
+ # {
46
+ # "tv_weights": "MobileNet_V3_Small_Weights.IMAGENET1K_V1",
47
+ # "backbone": "MobileNetV3-Small",
48
+ # "shape": (224, 224),
49
+ # "params_m": 2.54,
50
+ # "flops_g": 0.06,
51
+ # "top1_acc": 67.668,
52
+ # "top5_acc": 87.402,
53
+ # "license": "BSD-3-Clause",
54
+ # },
55
+ }
56
+
57
+ DEFAULT_MODEL = "mobilenetv3_large"
58
+
59
+
60
+ # ─────────────────────────────────────────────
61
+ # Dependency installer
62
+ # ─────────────────────────────────────────────
63
+
64
+ def _pip_install(*packages: str) -> None:
65
+ """Install *packages* via pip, suppressing verbose output."""
66
+ print(f"[DEP] Installing: {', '.join(packages)} …")
67
+ result = subprocess.run(
68
+ [sys.executable, "-m", "pip", "install", *packages],
69
+ stdout=subprocess.DEVNULL,
70
+ stderr=subprocess.PIPE,
71
+ text=True,
72
+ )
73
+ if result.returncode != 0:
74
+ print(f"[DEP] ERROR: pip install failed (exit code {result.returncode}).")
75
+ if result.stderr:
76
+ print(result.stderr.strip())
77
+ print("[DEP] Please install manually and re-run:")
78
+ print(f" pip install {' '.join(packages)}")
79
+ sys.exit(1)
80
+ print("[DEP] Installation complete.\n")
81
+
82
+
83
+ def ensure_dependencies() -> None:
84
+ """Ensure all runtime dependencies are available."""
85
+ needed: list[str] = []
86
+ checks = {
87
+ "torch": "torch",
88
+ "torchvision": "torchvision",
89
+ "onnx": "onnx",
90
+ "onnxsim": "onnx-simplifier",
91
+ }
92
+ for mod, pkg in checks.items():
93
+ try:
94
+ importlib.import_module(mod)
95
+ print(f"[DEP] βœ” {mod} is already installed.")
96
+ except ImportError:
97
+ print(f"[DEP] ✘ {mod} not found – will install '{pkg}'.")
98
+ needed.append(pkg)
99
+ if needed:
100
+ _pip_install(*needed)
101
+ else:
102
+ print("[DEP] All dependencies satisfied.\n")
103
+
104
+
105
+ # ─────────────────────────────────────────────
106
+ # ONNX post-processing helpers
107
+ # ─────────────────────────────────────────────
108
+
109
+ def _run_shape_inference(onnx_path: str) -> None:
110
+ """Run ONNX shape inference in-place."""
111
+ try:
112
+ import onnx
113
+ import onnx.shape_inference
114
+ print("[POST] Running ONNX shape inference …")
115
+ model = onnx.load(onnx_path)
116
+ model = onnx.shape_inference.infer_shapes(model)
117
+ onnx.save(model, onnx_path)
118
+ print("[POST] Shape inference complete.\n")
119
+ except Exception as exc:
120
+ print(f"[POST] WARNING: shape inference failed ({exc}) – model unchanged.\n")
121
+
122
+
123
+ def _maybe_simplify(onnx_path: str) -> None:
124
+ """Simplify the ONNX model in-place using onnxsim."""
125
+ try:
126
+ import onnx
127
+ import onnxsim
128
+ except ImportError:
129
+ print("[POST] onnxsim not installed – skipping simplification.\n")
130
+ print("[POST] Install with: pip install onnx-simplifier\n")
131
+ return
132
+
133
+ print("[POST] Simplifying ONNX model with onnxsim …")
134
+ try:
135
+ model = onnx.load(onnx_path)
136
+ model_simp, ok = onnxsim.simplify(model)
137
+ if ok:
138
+ onnx.save(model_simp, onnx_path)
139
+ print("[POST] Simplification complete.\n")
140
+ else:
141
+ print("[POST] WARNING: onnxsim validation failed – using original.\n")
142
+ except Exception as exc:
143
+ print(f"[POST] WARNING: onnxsim failed ({exc}) – using original.\n")
144
+
145
+
146
+ # ─────────────────────────────────────────────
147
+ # Model catalogue helpers
148
+ # ─────────────────────────────────────────────
149
+
150
+ def print_model_table() -> None:
151
+ """Print a formatted table of all available models."""
152
+ col = 22
153
+ header = (
154
+ f" {'Variant':<{col}} {'Backbone':<18} {'Shape':<10} "
155
+ f"{'Params(M)':<10} {'FLOPs(G)':<9} {'Top-1 %':<9} Top-5 %"
156
+ )
157
+ sep = " " + "-" * (len(header) - 2)
158
+ print("\n" + "=" * len(header))
159
+ print(" Available MobileNetV3 model variants")
160
+ print("=" * len(header))
161
+ print(header)
162
+ print(sep)
163
+
164
+ for key, info in MODEL_CATALOG.items():
165
+ h, w = info["shape"]
166
+ print(
167
+ f" {key:<{col}} {info['backbone']:<18} {h}Γ—{w:<5} "
168
+ f"{info['params_m']:<10.2f} {info['flops_g']:<9.2f} "
169
+ f"{info['top1_acc']:<9.3f} {info['top5_acc']:.3f}"
170
+ )
171
+ print("=" * len(header) + "\n")
172
+ print(" Accuracy evaluated on ImageNet-1K val (torchvision pretrained weights).")
173
+ print(" License: BSD-3-Clause (torchvision / PyTorch).\n")
174
+
175
+
176
+ # ─────────────────────────────────────────────
177
+ # Core export
178
+ # ─────────────────────────────────────────────
179
+
180
+ def export_model(
181
+ model_key: str,
182
+ output_dir: str,
183
+ shape: tuple[int, int] | None,
184
+ opset: int,
185
+ batch_size: int,
186
+ verbose: bool,
187
+ custom_weights: str | None,
188
+ force: bool,
189
+ simplify: bool = True,
190
+ ) -> str:
191
+ """
192
+ Load MobileNetV3 model from torchvision and export to ONNX.
193
+
194
+ The exported graph has a single image input (NCHW) and one output:
195
+ output [batch_size, 1000] – raw class logits (ImageNet-1K)
196
+
197
+ Shape inference and optional onnxsim simplification are applied.
198
+
199
+ Args:
200
+ model_key : Key from MODEL_CATALOG (e.g. "mobilenetv3_large").
201
+ output_dir : Directory where the .onnx file will be saved.
202
+ shape : Custom (H, W) override, or None for model default.
203
+ opset : ONNX opset version (default 17).
204
+ batch_size : Batch size in the exported graph (default 1).
205
+ verbose : Print detailed loading messages.
206
+ custom_weights: Path to a local .pth checkpoint; None = torchvision pretrained.
207
+ force : Re-export even if the destination .onnx already exists.
208
+ simplify : Apply onnxsim after export (default: True).
209
+
210
+ Returns:
211
+ Absolute path of the saved .onnx file.
212
+ """
213
+ import torch
214
+ import torchvision.models as tvm
215
+
216
+ info = MODEL_CATALOG[model_key]
217
+ export_h, export_w = shape if shape is not None else info["shape"]
218
+
219
+ # ── Destination path ──────────────────────────────────────────────────────
220
+ os.makedirs(output_dir, exist_ok=True)
221
+ shape_tag = f"_{export_h}x{export_w}" if shape is not None else ""
222
+ dst_name = f"{model_key}{shape_tag}.onnx"
223
+ dst_path = os.path.join(output_dir, dst_name)
224
+
225
+ if not force and os.path.exists(dst_path):
226
+ print(f"[SKIP] {dst_name} already exists. Use --force to re-export.\n")
227
+ return dst_path
228
+
229
+ print(f"[INFO] Model variant : {model_key}")
230
+ print(f"[INFO] Backbone : {info['backbone']}")
231
+ print(f"[INFO] TV weights : {info['tv_weights']}")
232
+ print(f"[INFO] Input shape : {export_h}Γ—{export_w}")
233
+ print(f"[INFO] Batch size : {batch_size}")
234
+ print(f"[INFO] ONNX opset : {opset}")
235
+ print()
236
+
237
+ # ── Load model ───────────────────────────────────────────────────────────
238
+ if custom_weights:
239
+ print(f"[INFO] Loading architecture from torchvision, weights from: {custom_weights}")
240
+ if model_key == "mobilenetv3_large":
241
+ model = tvm.mobilenet_v3_large(weights=None)
242
+ else:
243
+ model = tvm.mobilenet_v3_small(weights=None)
244
+ checkpoint = torch.load(custom_weights, map_location="cpu", weights_only=True)
245
+ state = checkpoint.get("model", checkpoint)
246
+ if isinstance(state, dict) and "module" in state:
247
+ state = state["module"]
248
+ model.load_state_dict(state)
249
+ else:
250
+ print(f"[INFO] Loading pretrained weights from torchvision …")
251
+ print(f"[INFO] (First run may download weights ~10–20 MB)")
252
+ if model_key == "mobilenetv3_large":
253
+ weights = tvm.MobileNet_V3_Large_Weights.IMAGENET1K_V2
254
+ model = tvm.mobilenet_v3_large(weights=weights)
255
+ else:
256
+ weights = tvm.MobileNet_V3_Small_Weights.IMAGENET1K_V1
257
+ model = tvm.mobilenet_v3_small(weights=weights)
258
+
259
+ model.eval()
260
+ print(f"[INFO] Model loaded.\n")
261
+
262
+ # ── Dry-run to confirm output shape ──────────────────────────────────────
263
+ dummy = torch.zeros(batch_size, 3, export_h, export_w)
264
+ with torch.no_grad():
265
+ out = model(dummy)
266
+ print(f"[INFO] Output shape : {list(out.shape)}")
267
+ print()
268
+
269
+ # ── Export to ONNX ────────────────────────────────────────────────────────
270
+ print(f"[INFO] Exporting to ONNX (opset {opset}) …")
271
+ with tempfile.TemporaryDirectory(prefix="mobilenetv3_export_") as tmp_dir:
272
+ tmp_path = os.path.join(tmp_dir, dst_name)
273
+
274
+ torch.onnx.export(
275
+ model,
276
+ dummy,
277
+ tmp_path,
278
+ input_names=["input"],
279
+ output_names=["output"],
280
+ opset_version=opset,
281
+ do_constant_folding=True,
282
+ verbose=False,
283
+ )
284
+
285
+ shutil.move(tmp_path, dst_path)
286
+
287
+ print(f"[INFO] Raw ONNX written to: {dst_path}")
288
+
289
+ # ── Post-processing ───────────────────────────────────────────────────────
290
+ _run_shape_inference(dst_path)
291
+ if simplify:
292
+ _maybe_simplify(dst_path)
293
+
294
+ size_mb = os.path.getsize(dst_path) / (1024 * 1024)
295
+ print(f"\n[SUCCESS] ONNX model saved to: {dst_path} ({size_mb:.1f} MB)\n")
296
+ return dst_path
297
+
298
+
299
+ # ─────────────────────────────────────────────
300
+ # CLI
301
+ # ─────────────────────────────────────────────
302
+
303
+ def build_parser() -> argparse.ArgumentParser:
304
+ default_output = os.path.dirname(os.path.abspath(__file__))
305
+
306
+ parser = argparse.ArgumentParser(
307
+ description=(
308
+ "Export MobileNetV3 pretrained ONNX models.\n\n"
309
+ "Pretrained ImageNet-1K weights are downloaded automatically from\n"
310
+ "torchvision on first use. Run --list-models to see all variants."
311
+ ),
312
+ formatter_class=argparse.RawDescriptionHelpFormatter,
313
+ epilog=(
314
+ "Examples:\n"
315
+ " %(prog)s\n"
316
+ " %(prog)s --model mobilenetv3_large\n"
317
+ " %(prog)s --model mobilenetv3_large mobilenetv3_small\n"
318
+ " %(prog)s --model mobilenetv3_large --shape 224 224\n"
319
+ " %(prog)s --model all\n"
320
+ " %(prog)s --model mobilenetv3_large --weights /path/to/custom.pth\n"
321
+ " %(prog)s --list-models"
322
+ ),
323
+ )
324
+
325
+ # ── Model selection ───────────────────────────────────────────────────────
326
+ parser.add_argument(
327
+ "--model",
328
+ nargs="+",
329
+ default=[DEFAULT_MODEL],
330
+ choices=list(MODEL_CATALOG.keys()) + ["all"],
331
+ metavar="VARIANT",
332
+ help=(
333
+ f"Model variant(s) to export. Use 'all' for all variants. "
334
+ f"Default: {DEFAULT_MODEL}. Run --list-models to see all options."
335
+ ),
336
+ )
337
+
338
+ # ── Export parameters ─────────────────────────────────────────────────────
339
+ parser.add_argument(
340
+ "--shape",
341
+ nargs=2,
342
+ type=int,
343
+ default=None,
344
+ metavar=("H", "W"),
345
+ help=(
346
+ "Custom input resolution (height width). "
347
+ "Default: each model's native resolution (224Γ—224)."
348
+ ),
349
+ )
350
+ parser.add_argument(
351
+ "--opset",
352
+ type=int,
353
+ default=17,
354
+ metavar="N",
355
+ help="ONNX opset version. Default: 17.",
356
+ )
357
+ parser.add_argument(
358
+ "--batch-size",
359
+ type=int,
360
+ default=1,
361
+ metavar="N",
362
+ help="Batch size embedded in the exported ONNX graph. Default: 1.",
363
+ )
364
+
365
+ # ── Weight source ─────────────────────────────────────────────────────────
366
+ parser.add_argument(
367
+ "--weights",
368
+ default=None,
369
+ metavar="PATH",
370
+ help=(
371
+ "Path to a local .pth checkpoint (optional). "
372
+ "When omitted the official ImageNet-1K pretrained weights are "
373
+ "downloaded automatically from torchvision."
374
+ ),
375
+ )
376
+
377
+ # ── Output ────────��───────────────────────────────────────────────────────
378
+ parser.add_argument(
379
+ "--output-dir",
380
+ default=default_output,
381
+ metavar="DIR",
382
+ help=f"Directory where .onnx files will be saved. Default: {default_output}",
383
+ )
384
+ parser.add_argument(
385
+ "--force",
386
+ action="store_true",
387
+ default=False,
388
+ help="Re-export even if the destination .onnx file already exists.",
389
+ )
390
+
391
+ # ── Simplification ────────────────────────────────────────────────────────
392
+ parser.add_argument(
393
+ "--simplify",
394
+ action="store_true",
395
+ default=True,
396
+ help=(
397
+ "Apply onnx-simplifier after export (default: enabled). "
398
+ "Requires: pip install onnx-simplifier. Use --no-simplify to disable."
399
+ ),
400
+ )
401
+ parser.add_argument(
402
+ "--no-simplify",
403
+ dest="simplify",
404
+ action="store_false",
405
+ help="Disable onnx-simplifier after export.",
406
+ )
407
+
408
+ # ── Verbosity ─────────────────────────────────────────────────────────────
409
+ parser.add_argument(
410
+ "--quiet",
411
+ action="store_true",
412
+ default=False,
413
+ help="Suppress verbose output during model loading.",
414
+ )
415
+
416
+ # ── Utility ───────────────────────────────────────────────────────────────
417
+ parser.add_argument(
418
+ "--list-models",
419
+ action="store_true",
420
+ default=False,
421
+ help="Print the model catalogue table and exit.",
422
+ )
423
+
424
+ return parser
425
+
426
+
427
+ # ─────────────────────────────────────────────
428
+ # Entry point
429
+ # ─────────────────────────────────────────────
430
+
431
+ def main() -> None:
432
+ parser = build_parser()
433
+ args = parser.parse_args()
434
+
435
+ if args.list_models:
436
+ print_model_table()
437
+ return
438
+
439
+ # ── Expand "all" keyword ──────────────────────────────────────────────────
440
+ if "all" in args.model:
441
+ args.model = list(MODEL_CATALOG.keys())
442
+
443
+ # ── Warn when --weights is used with multiple models ──────────────────────
444
+ if args.weights and len(args.model) > 1:
445
+ print(
446
+ "[WARN] --weights applies the same checkpoint to every model in "
447
+ "--model.\n This is unusual; pass a single --model variant "
448
+ "when using custom weights.\n"
449
+ )
450
+
451
+ # ── Install dependencies ──────────────────────────────────────────────────
452
+ ensure_dependencies()
453
+
454
+ # ── Export each model ─────────────────────────────────────────────────────
455
+ shape = (args.shape[0], args.shape[1]) if args.shape else None
456
+ output_dir = os.path.abspath(args.output_dir)
457
+
458
+ exported: list[str] = []
459
+ failed: list[str] = []
460
+
461
+ for model_key in args.model:
462
+ print(f"\n{'='*60}")
463
+ print(f" Exporting: {model_key}")
464
+ print(f"{'='*60}\n")
465
+
466
+ try:
467
+ out_path = export_model(
468
+ model_key = model_key,
469
+ output_dir = output_dir,
470
+ shape = shape,
471
+ opset = args.opset,
472
+ batch_size = args.batch_size,
473
+ verbose = not args.quiet,
474
+ custom_weights = args.weights,
475
+ force = args.force,
476
+ simplify = args.simplify,
477
+ )
478
+ exported.append(out_path)
479
+ except SystemExit:
480
+ raise
481
+ except Exception as exc:
482
+ print(f"[ERROR] Export failed for '{model_key}': {exc}")
483
+ failed.append(model_key)
484
+
485
+ # ── Summary ───────────────────────────────────────────────────────────────
486
+ print("\n" + "=" * 60)
487
+ print(" Export Summary")
488
+ print("=" * 60)
489
+ for path in exported:
490
+ size_mb = os.path.getsize(path) / (1024 * 1024)
491
+ print(f" βœ” {os.path.basename(path)} ({size_mb:.1f} MB)")
492
+ print(f" {path}")
493
+ if failed:
494
+ for key in failed:
495
+ print(f" ✘ {key}")
496
+ print(f"\n {len(exported)}/{len(args.model)} model(s) exported successfully.")
497
+ if failed:
498
+ sys.exit(1)
499
+
500
+
501
+ if __name__ == "__main__":
502
+ main()