Add dinov2 model files
Browse files- README.md +193 -0
- dinov2_vitb14_lc_config.yaml +31 -0
- dinov2_vitb14_reg_lc_config.yaml +31 -0
- dinov2_vits14_lc_config.yaml +31 -0
- dinov2_vits14_reg_lc_config.yaml +31 -0
- prepare_model.py +526 -0
README.md
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
tags:
|
| 4 |
+
- vision
|
| 5 |
+
- image-classification
|
| 6 |
+
- transformer
|
| 7 |
+
- self-supervised
|
| 8 |
+
datasets:
|
| 9 |
+
- imagenet-1k
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
<div align="center">
|
| 13 |
+
|
| 14 |
+
# DINOv2 for TI EdgeAI
|
| 15 |
+
|
| 16 |
+
### Self-Supervised Vision Transformer Backbone for Image Classification
|
| 17 |
+
|
| 18 |
+
[](https://opensource.org/licenses/Apache-2.0)
|
| 19 |
+
[](https://onnx.ai/)
|
| 20 |
+
[](https://github.com/TexasInstruments/edgeai)
|
| 21 |
+
[](http://www.image-net.org/)
|
| 22 |
+
|
| 23 |
+
</div>
|
| 24 |
+
|
| 25 |
+
---
|
| 26 |
+
|
| 27 |
+
## Overview
|
| 28 |
+
|
| 29 |
+
**DINOv2** (Self-**Di**stillation with **No** Labels v2) is a self-supervised Vision Transformer pre-training method from Meta AI. It produces high-performance visual features using a purely self-supervised training regime on 142M images — no labels required during pre-training. The pretrained backbones are paired with a lightweight linear classification head for ImageNet-1K inference, outputting 1000-class logits.
|
| 30 |
+
|
| 31 |
+
All models use a **ViT/14** patch size (14x14 patches) and are evaluated at **224x224** input resolution. Some variants add **register tokens** ([arXiv:2309.16588](https://arxiv.org/abs/2309.16588)) — extra learnable tokens that absorb the attention artifacts otherwise seen in patch-token feature maps, giving slightly better accuracy with the same backbone size.
|
| 32 |
+
|
| 33 |
+
> See [DINO](../DINO/) for the original first-generation models.
|
| 34 |
+
|
| 35 |
+
---
|
| 36 |
+
|
| 37 |
+
## Model Variants
|
| 38 |
+
|
| 39 |
+
| Model | Architecture | Params | GFLOPs | Top-1 Acc | Validated Devices | Config |
|
| 40 |
+
|-------|-------------|--------|--------|-----------|----------|--------|
|
| 41 |
+
| `dinov2_vits14_lc` | ViT-S/14 distilled | 21M | 4.6 | 81.1% | TDA4VH | [dinov2_vits14_lc_config.yaml](dinov2_vits14_lc_config.yaml) |
|
| 42 |
+
| `dinov2_vits14_reg_lc` | ViT-S/14 distilled + registers | 21M | 4.6 | 80.9% | TDA4VH | [dinov2_vits14_reg_lc_config.yaml](dinov2_vits14_reg_lc_config.yaml) |
|
| 43 |
+
| `dinov2_vitb14_lc` | ViT-B/14 distilled | 86M | 17.6 | 84.5% | TDA4VH | [dinov2_vitb14_lc_config.yaml](dinov2_vitb14_lc_config.yaml) |
|
| 44 |
+
| `dinov2_vitb14_reg_lc` | ViT-B/14 distilled + registers | 86M | 17.6 | 84.6% | TDA4VH | [dinov2_vitb14_reg_lc_config.yaml](dinov2_vitb14_reg_lc_config.yaml) |
|
| 45 |
+
|
| 46 |
+
**Recommended for edge deployment:** `dinov2_vits14_lc` (best accuracy/compute trade-off)
|
| 47 |
+
|
| 48 |
+
> **Note:** ViT-L/14 and ViT-g/14 variants (`dinov2_vitl14_lc`, `dinov2_vitg14_lc`, and their `_reg_lc` counterparts) are excluded from this repo — they require ~16 GB+ RAM to export and are not suitable for edge (TIDL) deployment.
|
| 49 |
+
|
| 50 |
+
---
|
| 51 |
+
|
| 52 |
+
## Quick Start
|
| 53 |
+
|
| 54 |
+
### Prerequisites
|
| 55 |
+
|
| 56 |
+
```bash
|
| 57 |
+
pip install torch torchvision onnx>=1.22.0 onnxruntime>=1.23.2 onnx-simplifier
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
### Export the Model
|
| 61 |
+
|
| 62 |
+
```bash
|
| 63 |
+
# Export the default model (ViT-S/14 distilled)
|
| 64 |
+
python prepare_model.py
|
| 65 |
+
|
| 66 |
+
# Export a specific model variant
|
| 67 |
+
python prepare_model.py --model dinov2_vitb14_lc
|
| 68 |
+
|
| 69 |
+
# Export the registers variant
|
| 70 |
+
python prepare_model.py --model dinov2_vits14_reg_lc
|
| 71 |
+
|
| 72 |
+
# Export all edge-suitable models
|
| 73 |
+
python prepare_model.py --model all
|
| 74 |
+
|
| 75 |
+
# Re-run shape fixing on an already-exported ONNX
|
| 76 |
+
python prepare_model.py --model dinov2_vits14_lc --skip-export
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
The script automatically:
|
| 80 |
+
- Loads the pretrained backbone + linear classification head from PyTorch Hub (`facebookresearch/dinov2`)
|
| 81 |
+
- Exports to ONNX (opset 17) with a dynamic batch axis
|
| 82 |
+
- Fixes input shapes to `[1, 3, 224, 224]` and propagates shapes via ONNX shape inference
|
| 83 |
+
- Runs onnx-simplifier (`onnxsim`) and validates the final model with `onnx.checker`
|
| 84 |
+
|
| 85 |
+
### Compile and Infer uing edgeai-tidlrunner
|
| 86 |
+
|
| 87 |
+
> **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.
|
| 88 |
+
|
| 89 |
+
**Compile using edgeai-tidlrunner - on PC**
|
| 90 |
+
|
| 91 |
+
```bash
|
| 92 |
+
cd /path/to/edgeai-tidlrunner
|
| 93 |
+
tidlrunner-cli compile --target_device J784S4 \
|
| 94 |
+
--config_path /path/to/dinov2_vits14_lc_config.yaml
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
**Run Inference Benchmark - on device**
|
| 98 |
+
|
| 99 |
+
```bash
|
| 100 |
+
cd /path/to/edgeai-tidlrunner
|
| 101 |
+
tidlrunner-cli infer --target_device J784S4 \
|
| 102 |
+
--config_path /path/to/dinov2_vits14_lc_config.yaml
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
### Compile and Infer using edgeai-tidl-tools (Advanced):
|
| 106 |
+
|
| 107 |
+
Follow the instructions at https://github.com/TexasInstruments/edgeai-tidl-tools
|
| 108 |
+
|
| 109 |
+
### Deploy using edgeai-tidl-tools:
|
| 110 |
+
|
| 111 |
+
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.
|
| 112 |
+
|
| 113 |
+
---
|
| 114 |
+
|
| 115 |
+
## Citation
|
| 116 |
+
|
| 117 |
+
If you use these models, please cite:
|
| 118 |
+
|
| 119 |
+
```bibtex
|
| 120 |
+
@misc{oquab2023dinov2,
|
| 121 |
+
title={DINOv2: Learning Robust Visual Features without Supervision},
|
| 122 |
+
author={Oquab, Maxime and Darcet, Timothée and Moutakanni, Theo and others},
|
| 123 |
+
journal={arXiv:2304.07193},
|
| 124 |
+
year={2023}
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
@misc{darcet2023vitneedreg,
|
| 128 |
+
title={Vision Transformers Need Registers},
|
| 129 |
+
author={Darcet, Timothée and Oquab, Maxime and Mairal, Julien and Bojanowski, Piotr},
|
| 130 |
+
journal={arXiv:2309.16588},
|
| 131 |
+
year={2023}
|
| 132 |
+
}
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
---
|
| 136 |
+
|
| 137 |
+
## 🔗 Resources
|
| 138 |
+
|
| 139 |
+
| Resource | Link |
|
| 140 |
+
|----------|------|
|
| 141 |
+
| **Paper** | [arXiv:2304.07193](https://arxiv.org/abs/2304.07193) |
|
| 142 |
+
| **Registers Paper** | [arXiv:2309.16588](https://arxiv.org/abs/2309.16588) |
|
| 143 |
+
| **Source Code** | [facebookresearch/dinov2](https://github.com/facebookresearch/dinov2) |
|
| 144 |
+
| **edgeai-tidl-tools** | [GitHub](https://github.com/TexasInstruments/edgeai-tidl-tools) |
|
| 145 |
+
| **edgeai-tidlrunner** | [GitHub](https://github.com/TexasInstruments/edgeai-tidlrunner) |
|
| 146 |
+
| **EdgeAI SDK** | [Documentation](https://github.com/TexasInstruments/edgeai/blob/main/edgeai-mpu/readme_sdk.md) |
|
| 147 |
+
| **DINO** | [Predecessor model](../DINO/) |
|
| 148 |
+
|
| 149 |
+
---
|
| 150 |
+
|
| 151 |
+
## Related Models
|
| 152 |
+
|
| 153 |
+
<table>
|
| 154 |
+
<tr>
|
| 155 |
+
<td align="center">
|
| 156 |
+
|
| 157 |
+
**DINO**
|
| 158 |
+
Predecessor
|
| 159 |
+
First-generation self-supervised ViT
|
| 160 |
+
|
| 161 |
+
</td>
|
| 162 |
+
<td align="center">
|
| 163 |
+
|
| 164 |
+
**ViT**
|
| 165 |
+
Alternative backbone
|
| 166 |
+
Supervised transformer
|
| 167 |
+
|
| 168 |
+
</td>
|
| 169 |
+
<td align="center">
|
| 170 |
+
|
| 171 |
+
**ResNet**
|
| 172 |
+
CNN backbone
|
| 173 |
+
Lower compute
|
| 174 |
+
|
| 175 |
+
</td>
|
| 176 |
+
<td align="center">
|
| 177 |
+
|
| 178 |
+
**ConvNeXt**
|
| 179 |
+
Modern CNN
|
| 180 |
+
Transformer-inspired design
|
| 181 |
+
|
| 182 |
+
</td>
|
| 183 |
+
</tr>
|
| 184 |
+
</table>
|
| 185 |
+
|
| 186 |
+
---
|
| 187 |
+
|
| 188 |
+
<div align="center">
|
| 189 |
+
|
| 190 |
+
**Maintained by:** Texas Instruments EdgeAI Team
|
| 191 |
+
**Last Updated:** August 2026
|
| 192 |
+
|
| 193 |
+
</div>
|
dinov2_vitb14_lc_config.yaml
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
task_type: classification
|
| 2 |
+
dataloader:
|
| 3 |
+
name: image_classification_dataloader
|
| 4 |
+
path: ./data/datasets/imagenetv2c/val
|
| 5 |
+
postprocess: {}
|
| 6 |
+
preprocess:
|
| 7 |
+
resize: 256
|
| 8 |
+
crop: 224
|
| 9 |
+
data_layout: NCHW
|
| 10 |
+
reverse_channels: false
|
| 11 |
+
backend: pil
|
| 12 |
+
interpolation: null
|
| 13 |
+
resize_with_pad: false
|
| 14 |
+
pad_color: 0
|
| 15 |
+
session:
|
| 16 |
+
session_name: onnxrt
|
| 17 |
+
target_device: null
|
| 18 |
+
input_optimization: false
|
| 19 |
+
input_data_layout: NCHW
|
| 20 |
+
input_mean: [123.675, 116.28, 103.53]
|
| 21 |
+
input_scale: [0.017125, 0.017507, 0.017429]
|
| 22 |
+
model_path: dinov2_vitb14_lc.onnx
|
| 23 |
+
model_id: cl-mh6011
|
| 24 |
+
input_details: null
|
| 25 |
+
output_details: null
|
| 26 |
+
num_inputs: 1
|
| 27 |
+
model_info:
|
| 28 |
+
metric_reference:
|
| 29 |
+
accuracy_top1%: 84.5
|
| 30 |
+
compact_name: DINOv2-ViT-B/14
|
| 31 |
+
shortlisted: true
|
dinov2_vitb14_reg_lc_config.yaml
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
task_type: classification
|
| 2 |
+
dataloader:
|
| 3 |
+
name: image_classification_dataloader
|
| 4 |
+
path: ./data/datasets/imagenetv2c/val
|
| 5 |
+
postprocess: {}
|
| 6 |
+
preprocess:
|
| 7 |
+
resize: 256
|
| 8 |
+
crop: 224
|
| 9 |
+
data_layout: NCHW
|
| 10 |
+
reverse_channels: false
|
| 11 |
+
backend: pil
|
| 12 |
+
interpolation: null
|
| 13 |
+
resize_with_pad: false
|
| 14 |
+
pad_color: 0
|
| 15 |
+
session:
|
| 16 |
+
session_name: onnxrt
|
| 17 |
+
target_device: null
|
| 18 |
+
input_optimization: false
|
| 19 |
+
input_data_layout: NCHW
|
| 20 |
+
input_mean: [123.675, 116.28, 103.53]
|
| 21 |
+
input_scale: [0.017125, 0.017507, 0.017429]
|
| 22 |
+
model_path: dinov2_vitb14_reg_lc.onnx
|
| 23 |
+
model_id: cl-mh6014
|
| 24 |
+
input_details: null
|
| 25 |
+
output_details: null
|
| 26 |
+
num_inputs: 1
|
| 27 |
+
model_info:
|
| 28 |
+
metric_reference:
|
| 29 |
+
accuracy_top1%: 84.6
|
| 30 |
+
compact_name: DINOv2-ViT-B/14-reg
|
| 31 |
+
shortlisted: true
|
dinov2_vits14_lc_config.yaml
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
task_type: classification
|
| 2 |
+
dataloader:
|
| 3 |
+
name: image_classification_dataloader
|
| 4 |
+
path: ./data/datasets/imagenetv2c/val
|
| 5 |
+
postprocess: {}
|
| 6 |
+
preprocess:
|
| 7 |
+
resize: 256
|
| 8 |
+
crop: 224
|
| 9 |
+
data_layout: NCHW
|
| 10 |
+
reverse_channels: false
|
| 11 |
+
backend: pil
|
| 12 |
+
interpolation: null
|
| 13 |
+
resize_with_pad: false
|
| 14 |
+
pad_color: 0
|
| 15 |
+
session:
|
| 16 |
+
session_name: onnxrt
|
| 17 |
+
target_device: null
|
| 18 |
+
input_optimization: false
|
| 19 |
+
input_data_layout: NCHW
|
| 20 |
+
input_mean: [123.675, 116.28, 103.53]
|
| 21 |
+
input_scale: [0.017125, 0.017507, 0.017429]
|
| 22 |
+
model_path: dinov2_vits14_lc.onnx
|
| 23 |
+
model_id: cl-mh6010
|
| 24 |
+
input_details: null
|
| 25 |
+
output_details: null
|
| 26 |
+
num_inputs: 1
|
| 27 |
+
model_info:
|
| 28 |
+
metric_reference:
|
| 29 |
+
accuracy_top1%: 81.1
|
| 30 |
+
compact_name: DINOv2-ViT-S/14
|
| 31 |
+
shortlisted: true
|
dinov2_vits14_reg_lc_config.yaml
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
task_type: classification
|
| 2 |
+
dataloader:
|
| 3 |
+
name: image_classification_dataloader
|
| 4 |
+
path: ./data/datasets/imagenetv2c/val
|
| 5 |
+
postprocess: {}
|
| 6 |
+
preprocess:
|
| 7 |
+
resize: 256
|
| 8 |
+
crop: 224
|
| 9 |
+
data_layout: NCHW
|
| 10 |
+
reverse_channels: false
|
| 11 |
+
backend: pil
|
| 12 |
+
interpolation: null
|
| 13 |
+
resize_with_pad: false
|
| 14 |
+
pad_color: 0
|
| 15 |
+
session:
|
| 16 |
+
session_name: onnxrt
|
| 17 |
+
target_device: null
|
| 18 |
+
input_optimization: false
|
| 19 |
+
input_data_layout: NCHW
|
| 20 |
+
input_mean: [123.675, 116.28, 103.53]
|
| 21 |
+
input_scale: [0.017125, 0.017507, 0.017429]
|
| 22 |
+
model_path: dinov2_vits14_reg_lc.onnx
|
| 23 |
+
model_id: cl-mh6013
|
| 24 |
+
input_details: null
|
| 25 |
+
output_details: null
|
| 26 |
+
num_inputs: 1
|
| 27 |
+
model_info:
|
| 28 |
+
metric_reference:
|
| 29 |
+
accuracy_top1%: 80.9
|
| 30 |
+
compact_name: DINOv2-ViT-S/14-reg
|
| 31 |
+
shortlisted: true
|
prepare_model.py
ADDED
|
@@ -0,0 +1,526 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Export DINOv2 classification models (backbone + linear head) from PyTorch Hub
|
| 4 |
+
to ONNX with fixed input shapes for TI EdgeAI hardware deployment.
|
| 5 |
+
|
| 6 |
+
Supported models (backbone + linear classification head, 1000-class ImageNet):
|
| 7 |
+
dinov2_vits14_lc - ViT-S/14 distilled, 21M params, 81.1% top-1
|
| 8 |
+
dinov2_vitb14_lc - ViT-B/14 distilled, 86M params, 84.5% top-1
|
| 9 |
+
dinov2_vitl14_lc - ViT-L/14 distilled, 307M params, 86.3% top-1
|
| 10 |
+
dinov2_vitg14_lc - ViT-g/14, 1100M params, 86.5% top-1
|
| 11 |
+
dinov2_vits14_reg_lc - ViT-S/14 + registers, 21M params, 80.9% top-1
|
| 12 |
+
dinov2_vitb14_reg_lc - ViT-B/14 + registers, 86M params, 84.6% top-1
|
| 13 |
+
dinov2_vitl14_reg_lc - ViT-L/14 + registers, 307M params, 86.7% top-1
|
| 14 |
+
dinov2_vitg14_reg_lc - ViT-g/14 + registers, 1100M params, 87.1% top-1
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
python prepare_model.py --model dinov2_vits14_lc
|
| 18 |
+
python prepare_model.py --model dinov2_vitb14_lc --no-simplifier
|
| 19 |
+
python prepare_model.py --model dinov2_vitl14_lc --skip-export
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
import sys
|
| 23 |
+
import subprocess
|
| 24 |
+
import tempfile
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
SUPPORTED_MODELS = {
|
| 28 |
+
'dinov2_vits14_lc': {'params': '21M', 'accuracy_top1': 81.1, 'gflops': 4.6, 'edge_suitable': True},
|
| 29 |
+
'dinov2_vitb14_lc': {'params': '86M', 'accuracy_top1': 84.5, 'gflops': 17.6, 'edge_suitable': True},
|
| 30 |
+
'dinov2_vitl14_lc': {'params': '307M', 'accuracy_top1': 86.3, 'gflops': 61.6, 'edge_suitable': False},
|
| 31 |
+
'dinov2_vitg14_lc': {'params': '1100M', 'accuracy_top1': 86.5, 'gflops': 314.0, 'edge_suitable': False},
|
| 32 |
+
'dinov2_vits14_reg_lc': {'params': '21M', 'accuracy_top1': 80.9, 'gflops': 4.6, 'edge_suitable': True},
|
| 33 |
+
'dinov2_vitb14_reg_lc': {'params': '86M', 'accuracy_top1': 84.6, 'gflops': 17.6, 'edge_suitable': True},
|
| 34 |
+
'dinov2_vitl14_reg_lc': {'params': '307M', 'accuracy_top1': 86.7, 'gflops': 61.6, 'edge_suitable': False},
|
| 35 |
+
'dinov2_vitg14_reg_lc': {'params': '1100M', 'accuracy_top1': 87.1, 'gflops': 314.0, 'edge_suitable': False},
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
# Models exported with --model all (edge-suitable only; ViT-g excluded due to ~16GB RAM requirement)
|
| 39 |
+
EDGE_MODELS = [name for name, info in SUPPORTED_MODELS.items() if info['edge_suitable']]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _ensure_dependencies():
|
| 43 |
+
required = {
|
| 44 |
+
'onnx': 'onnx',
|
| 45 |
+
'onnxsim': 'onnx-simplifier',
|
| 46 |
+
'torch': 'torch',
|
| 47 |
+
}
|
| 48 |
+
for module, package in required.items():
|
| 49 |
+
try:
|
| 50 |
+
__import__(module)
|
| 51 |
+
except ImportError:
|
| 52 |
+
print(f"Installing missing dependency: {package}")
|
| 53 |
+
subprocess.check_call([sys.executable, '-m', 'pip', 'install', package])
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
_ensure_dependencies()
|
| 57 |
+
|
| 58 |
+
import torch
|
| 59 |
+
import onnx
|
| 60 |
+
from onnx import shape_inference
|
| 61 |
+
import argparse
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _consolidate_external_data(src_onnx_path, dst_onnx_path):
|
| 65 |
+
"""
|
| 66 |
+
Consolidate scattered per-tensor external data files into a single .data file
|
| 67 |
+
by streaming — never loads all tensor weights into RAM at once.
|
| 68 |
+
|
| 69 |
+
Used for models > 2 GB where onnx.load() would cause an OOM kill.
|
| 70 |
+
Produces two files: dst_onnx_path (proto) and dst_onnx_path.name + '.data'.
|
| 71 |
+
"""
|
| 72 |
+
from onnx import TensorProto, AttributeProto
|
| 73 |
+
|
| 74 |
+
src_dir = src_onnx_path.parent
|
| 75 |
+
data_filename = dst_onnx_path.name + '.data'
|
| 76 |
+
data_path = dst_onnx_path.parent / data_filename
|
| 77 |
+
|
| 78 |
+
# Load proto structure only — tensor data stays on disk
|
| 79 |
+
model = onnx.load(str(src_onnx_path), load_external_data=False)
|
| 80 |
+
|
| 81 |
+
def _external_tensors(model_proto):
|
| 82 |
+
for t in model_proto.graph.initializer:
|
| 83 |
+
if t.data_location == TensorProto.EXTERNAL:
|
| 84 |
+
yield t
|
| 85 |
+
for node in model_proto.graph.node:
|
| 86 |
+
for attr in node.attribute:
|
| 87 |
+
if attr.type == AttributeProto.TENSOR and attr.t.data_location == TensorProto.EXTERNAL:
|
| 88 |
+
yield attr.t
|
| 89 |
+
elif attr.type == AttributeProto.TENSORS:
|
| 90 |
+
for t in attr.tensors:
|
| 91 |
+
if t.data_location == TensorProto.EXTERNAL:
|
| 92 |
+
yield t
|
| 93 |
+
|
| 94 |
+
offset = 0
|
| 95 |
+
with open(str(data_path), 'wb') as out_f:
|
| 96 |
+
for tensor in _external_tensors(model):
|
| 97 |
+
info = {e.key: e.value for e in tensor.external_data}
|
| 98 |
+
src_file = src_dir / info['location']
|
| 99 |
+
t_offset = int(info.get('offset', 0))
|
| 100 |
+
t_length = int(info['length'])
|
| 101 |
+
|
| 102 |
+
with open(str(src_file), 'rb') as src_f:
|
| 103 |
+
src_f.seek(t_offset)
|
| 104 |
+
out_f.write(src_f.read(t_length))
|
| 105 |
+
|
| 106 |
+
del tensor.external_data[:]
|
| 107 |
+
for k, v in [('location', data_filename), ('offset', str(offset)), ('length', str(t_length))]:
|
| 108 |
+
e = tensor.external_data.add()
|
| 109 |
+
e.key = k
|
| 110 |
+
e.value = v
|
| 111 |
+
offset += t_length
|
| 112 |
+
|
| 113 |
+
# Save only the proto — tensor data lives in data_path
|
| 114 |
+
onnx.save(model, str(dst_onnx_path))
|
| 115 |
+
print(f"✓ Proto: {dst_onnx_path.name}")
|
| 116 |
+
print(f"✓ Tensor data: {data_filename} ({data_path.stat().st_size / 1024**3:.2f} GB)")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def export_to_onnx(model_name, output_path, height=224, width=224):
|
| 120 |
+
"""
|
| 121 |
+
Load DINOv2 classifier from PyTorch Hub and export to ONNX.
|
| 122 |
+
|
| 123 |
+
torch.onnx.export writes per-tensor external data files alongside its output
|
| 124 |
+
for models exceeding the 2 GB protobuf limit. The export runs inside a
|
| 125 |
+
TemporaryDirectory so those files never appear in the destination directory.
|
| 126 |
+
|
| 127 |
+
Small models (S/B/L, < 2 GB): external data is merged inline → single ONNX file.
|
| 128 |
+
Large models (g, > 2 GB): _consolidate_external_data streams tensors into a
|
| 129 |
+
single .data file without loading all weights into RAM.
|
| 130 |
+
"""
|
| 131 |
+
info = SUPPORTED_MODELS[model_name]
|
| 132 |
+
print(f"\nLoading model from PyTorch Hub:")
|
| 133 |
+
print("=" * 80)
|
| 134 |
+
print(f"Model: {model_name}")
|
| 135 |
+
print(f"Params: {info['params']}")
|
| 136 |
+
print(f"Top-1: {info['accuracy_top1']}%")
|
| 137 |
+
print(f"GFLOPs: {info['gflops']}")
|
| 138 |
+
print()
|
| 139 |
+
|
| 140 |
+
try:
|
| 141 |
+
model = torch.hub.load('facebookresearch/dinov2', model_name, pretrained=True)
|
| 142 |
+
except Exception as e:
|
| 143 |
+
print(f"✗ Failed to load model: {e}")
|
| 144 |
+
print(" Ensure you have an internet connection and PyTorch installed.")
|
| 145 |
+
return False
|
| 146 |
+
|
| 147 |
+
model.eval()
|
| 148 |
+
|
| 149 |
+
# aten::_upsample_bicubic2d_aa (antialias=True) has no opset-17 ONNX handler.
|
| 150 |
+
# Register models set interpolate_antialias=True on the backbone for positional
|
| 151 |
+
# embedding interpolation. Patching it to False uses standard bicubic, which
|
| 152 |
+
# is fully supported and has negligible quality difference at fixed 224x224.
|
| 153 |
+
for module in model.modules():
|
| 154 |
+
if hasattr(module, 'interpolate_antialias'):
|
| 155 |
+
module.interpolate_antialias = False
|
| 156 |
+
|
| 157 |
+
dummy_input = torch.randn(1, 3, height, width)
|
| 158 |
+
|
| 159 |
+
print(f"\nExporting to ONNX (opset 17):")
|
| 160 |
+
print("-" * 80)
|
| 161 |
+
print(f"Input shape: [1, 3, {height}, {width}]")
|
| 162 |
+
print(f"Output path: {output_path}")
|
| 163 |
+
|
| 164 |
+
try:
|
| 165 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 166 |
+
tmp_onnx = Path(tmpdir) / f"{model_name}.onnx"
|
| 167 |
+
|
| 168 |
+
torch.onnx.export(
|
| 169 |
+
model,
|
| 170 |
+
dummy_input,
|
| 171 |
+
str(tmp_onnx),
|
| 172 |
+
export_params=True,
|
| 173 |
+
opset_version=17,
|
| 174 |
+
do_constant_folding=True,
|
| 175 |
+
input_names=['input'],
|
| 176 |
+
output_names=['output'],
|
| 177 |
+
dynamic_axes={
|
| 178 |
+
'input': {0: 'batch_size'},
|
| 179 |
+
'output': {0: 'batch_size'},
|
| 180 |
+
},
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
# Probe proto (no data loaded) to detect external data format
|
| 184 |
+
probe = onnx.load(str(tmp_onnx), load_external_data=False)
|
| 185 |
+
has_external = any(
|
| 186 |
+
t.data_location == onnx.TensorProto.EXTERNAL
|
| 187 |
+
for t in probe.graph.initializer
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
if has_external:
|
| 191 |
+
# Model > 2 GB: stream-consolidate without loading all weights into RAM
|
| 192 |
+
print("\nModel exceeds 2 GB — streaming consolidation (no full RAM load)...")
|
| 193 |
+
_consolidate_external_data(tmp_onnx, output_path)
|
| 194 |
+
else:
|
| 195 |
+
# Model fits inline: load and save as single self-contained ONNX
|
| 196 |
+
print("\nMerging external data into single ONNX file...")
|
| 197 |
+
exported = onnx.load(str(tmp_onnx))
|
| 198 |
+
onnx.save(exported, str(output_path))
|
| 199 |
+
# tmpdir and all scattered tensor files are deleted here
|
| 200 |
+
|
| 201 |
+
except Exception as e:
|
| 202 |
+
print(f"✗ ONNX export failed: {e}")
|
| 203 |
+
return False
|
| 204 |
+
|
| 205 |
+
if output_path.exists():
|
| 206 |
+
file_size = output_path.stat().st_size
|
| 207 |
+
print(f"\n✓ Export completed successfully!")
|
| 208 |
+
print(f"✓ File size: {file_size:,} bytes ({file_size / 1024 / 1024:.2f} MB)")
|
| 209 |
+
return True
|
| 210 |
+
|
| 211 |
+
print("✗ Export failed: output file not created")
|
| 212 |
+
return False
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def fix_model_shape(model_path, output_path, batch_size=1, channels=3, height=224, width=224, use_simplifier=True):
|
| 216 |
+
"""
|
| 217 |
+
Convert dynamic ONNX model input shape to fixed shape in all layers.
|
| 218 |
+
|
| 219 |
+
Uses ONNX shape inference to propagate fixed shapes through all intermediate
|
| 220 |
+
layers. Optionally runs onnxsim for additional simplification and optimization.
|
| 221 |
+
"""
|
| 222 |
+
print(f"\nFixing Model Shapes:")
|
| 223 |
+
print("=" * 80)
|
| 224 |
+
print(f"Input model: {model_path}")
|
| 225 |
+
print(f"Output model: {output_path}")
|
| 226 |
+
|
| 227 |
+
print(f"\nLoading model...")
|
| 228 |
+
model = onnx.load(str(model_path))
|
| 229 |
+
|
| 230 |
+
graph = model.graph
|
| 231 |
+
input_tensor = None
|
| 232 |
+
for inp in graph.input:
|
| 233 |
+
if any(init.name == inp.name for init in graph.initializer):
|
| 234 |
+
continue
|
| 235 |
+
input_tensor = inp
|
| 236 |
+
break
|
| 237 |
+
|
| 238 |
+
if input_tensor is None:
|
| 239 |
+
print("✗ Error: No input tensor found!")
|
| 240 |
+
return False
|
| 241 |
+
|
| 242 |
+
print(f"\nOriginal Shape:")
|
| 243 |
+
print("-" * 80)
|
| 244 |
+
print(f"Input name: {input_tensor.name}")
|
| 245 |
+
original_shape = []
|
| 246 |
+
for dim in input_tensor.type.tensor_type.shape.dim:
|
| 247 |
+
if dim.dim_value:
|
| 248 |
+
original_shape.append(str(dim.dim_value))
|
| 249 |
+
elif dim.dim_param:
|
| 250 |
+
original_shape.append(f"'{dim.dim_param}'")
|
| 251 |
+
else:
|
| 252 |
+
original_shape.append("?")
|
| 253 |
+
print(f"Shape: [{', '.join(original_shape)}]")
|
| 254 |
+
|
| 255 |
+
print(f"\nSetting Fixed Shape:")
|
| 256 |
+
print("-" * 80)
|
| 257 |
+
new_shape = [batch_size, channels, height, width]
|
| 258 |
+
print(f"New shape: {new_shape}")
|
| 259 |
+
print(f"Format: [batch_size, channels, height, width]")
|
| 260 |
+
|
| 261 |
+
input_tensor.type.tensor_type.shape.ClearField('dim')
|
| 262 |
+
for dim_value in new_shape:
|
| 263 |
+
dim = input_tensor.type.tensor_type.shape.dim.add()
|
| 264 |
+
dim.dim_value = dim_value
|
| 265 |
+
|
| 266 |
+
print(f"\nRunning Shape Inference:")
|
| 267 |
+
print("-" * 80)
|
| 268 |
+
try:
|
| 269 |
+
model = shape_inference.infer_shapes(model)
|
| 270 |
+
value_info_count = len(model.graph.value_info)
|
| 271 |
+
print(f"✓ Propagated shapes through {value_info_count} intermediate tensors")
|
| 272 |
+
except Exception as e:
|
| 273 |
+
print(f"⚠ Warning: Shape inference issue: {e}")
|
| 274 |
+
print(" Continuing with partial inference...")
|
| 275 |
+
|
| 276 |
+
print(f"\nValidating Model:")
|
| 277 |
+
print("-" * 80)
|
| 278 |
+
try:
|
| 279 |
+
onnx.checker.check_model(model)
|
| 280 |
+
print("✓ Model validation passed")
|
| 281 |
+
except Exception as e:
|
| 282 |
+
print(f"✗ Model validation failed: {e}")
|
| 283 |
+
return False
|
| 284 |
+
|
| 285 |
+
if use_simplifier:
|
| 286 |
+
print(f"\nRunning ONNX Simplifier:")
|
| 287 |
+
print("-" * 80)
|
| 288 |
+
try:
|
| 289 |
+
import onnxsim
|
| 290 |
+
model_simplified, check = onnxsim.simplify(
|
| 291 |
+
model,
|
| 292 |
+
check_n=3,
|
| 293 |
+
perform_optimization=True,
|
| 294 |
+
skip_fuse_bn=False,
|
| 295 |
+
overwrite_input_shapes={input_tensor.name: new_shape},
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
if check:
|
| 299 |
+
print("✓ Model simplified and optimized")
|
| 300 |
+
model = model_simplified
|
| 301 |
+
|
| 302 |
+
original_nodes = len(graph.node)
|
| 303 |
+
simplified_nodes = len(model.graph.node)
|
| 304 |
+
if simplified_nodes < original_nodes:
|
| 305 |
+
print(f"✓ Reduced nodes: {original_nodes} → {simplified_nodes}")
|
| 306 |
+
else:
|
| 307 |
+
print("⚠ Simplification validation failed, using non-simplified version")
|
| 308 |
+
|
| 309 |
+
except ImportError:
|
| 310 |
+
print("⚠ onnx-simplifier not installed, skipping")
|
| 311 |
+
except Exception as e:
|
| 312 |
+
print(f"⚠ Simplification failed: {e}")
|
| 313 |
+
print(" Continuing with non-simplified model")
|
| 314 |
+
|
| 315 |
+
print(f"\nSaving Fixed Model:")
|
| 316 |
+
print("-" * 80)
|
| 317 |
+
onnx.save(model, str(output_path))
|
| 318 |
+
output_size = output_path.stat().st_size
|
| 319 |
+
print(f"✓ Saved to: {output_path}")
|
| 320 |
+
print(f"✓ File size: {output_size:,} bytes ({output_size / 1024 / 1024:.2f} MB)")
|
| 321 |
+
|
| 322 |
+
print(f"\nFinal Verification:")
|
| 323 |
+
print("-" * 80)
|
| 324 |
+
try:
|
| 325 |
+
verified_model = onnx.load(str(output_path))
|
| 326 |
+
onnx.checker.check_model(verified_model)
|
| 327 |
+
|
| 328 |
+
verified_graph = verified_model.graph
|
| 329 |
+
for inp in verified_graph.input:
|
| 330 |
+
if any(init.name == inp.name for init in verified_graph.initializer):
|
| 331 |
+
continue
|
| 332 |
+
shape = [dim.dim_value for dim in inp.type.tensor_type.shape.dim]
|
| 333 |
+
all_fixed = all(isinstance(s, int) and s > 0 for s in shape)
|
| 334 |
+
if all_fixed:
|
| 335 |
+
print(f"✓ Input '{inp.name}': {shape}")
|
| 336 |
+
else:
|
| 337 |
+
print(f"⚠ Input '{inp.name}' has dynamic dimensions")
|
| 338 |
+
|
| 339 |
+
if verified_graph.value_info:
|
| 340 |
+
fixed_count = sum(
|
| 341 |
+
1 for vi in verified_graph.value_info
|
| 342 |
+
if all(dim.dim_value > 0 for dim in vi.type.tensor_type.shape.dim)
|
| 343 |
+
)
|
| 344 |
+
total_count = len(verified_graph.value_info)
|
| 345 |
+
print(f"✓ Fixed shapes: {fixed_count}/{total_count} intermediate tensors")
|
| 346 |
+
|
| 347 |
+
print(f"\n✨ Success! Fixed model ready for deployment")
|
| 348 |
+
return True
|
| 349 |
+
|
| 350 |
+
except Exception as e:
|
| 351 |
+
print(f"✗ Final verification failed: {e}")
|
| 352 |
+
return False
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def _prepare_single_model(model_name, args, script_dir):
|
| 356 |
+
"""Export and fix shapes for one model. Returns True on success."""
|
| 357 |
+
onnx_filename = f"{model_name}.onnx"
|
| 358 |
+
final_output = script_dir / onnx_filename
|
| 359 |
+
|
| 360 |
+
info = SUPPORTED_MODELS[model_name]
|
| 361 |
+
if not info['edge_suitable']:
|
| 362 |
+
print(f"\n⚠ Warning: {model_name} has {info['params']} parameters (~"
|
| 363 |
+
f"{int(info['gflops'])} GFLOPs).")
|
| 364 |
+
print(f" This model requires ~16 GB+ RAM and is not suitable for edge deployment.")
|
| 365 |
+
print(f" Shape inference and onnxsim will be skipped to reduce memory usage.")
|
| 366 |
+
print()
|
| 367 |
+
|
| 368 |
+
print(f"\nDINOv2 Model Preparation")
|
| 369 |
+
print("=" * 80)
|
| 370 |
+
print(f"Model: {model_name}")
|
| 371 |
+
print(f"Output: {onnx_filename}")
|
| 372 |
+
print(f"Input shape: [{args.batch_size}, {args.channels}, {args.height}, {args.width}]")
|
| 373 |
+
|
| 374 |
+
if args.skip_export:
|
| 375 |
+
if not final_output.exists():
|
| 376 |
+
print(f"\n✗ Error: ONNX file not found: {final_output}")
|
| 377 |
+
print(" Run without --skip-export to export it first.")
|
| 378 |
+
return False
|
| 379 |
+
print(f"\nUsing existing ONNX file: {final_output.name}")
|
| 380 |
+
else:
|
| 381 |
+
if final_output.exists() and not args.force_export:
|
| 382 |
+
print(f"\nONNX file already exists: {final_output}")
|
| 383 |
+
file_size = final_output.stat().st_size
|
| 384 |
+
print(f"File size: {file_size:,} bytes ({file_size / 1024 / 1024:.2f} MB)")
|
| 385 |
+
print("Use --force-export to re-export.")
|
| 386 |
+
return True
|
| 387 |
+
|
| 388 |
+
success = export_to_onnx(model_name, final_output, args.height, args.width)
|
| 389 |
+
if not success:
|
| 390 |
+
return False
|
| 391 |
+
|
| 392 |
+
# Disable onnxsim for non-edge models (>2 GB) to avoid OOM during shape fixing
|
| 393 |
+
use_simplifier = not args.no_simplifier and info['edge_suitable']
|
| 394 |
+
success = fix_model_shape(
|
| 395 |
+
final_output,
|
| 396 |
+
final_output,
|
| 397 |
+
batch_size=args.batch_size,
|
| 398 |
+
channels=args.channels,
|
| 399 |
+
height=args.height,
|
| 400 |
+
width=args.width,
|
| 401 |
+
use_simplifier=use_simplifier,
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
if success:
|
| 405 |
+
print("\n" + "=" * 80)
|
| 406 |
+
print("COMPLETE!")
|
| 407 |
+
print("=" * 80)
|
| 408 |
+
print(f"Model: {model_name}")
|
| 409 |
+
print(f"Output: {final_output.name}")
|
| 410 |
+
print(f"Location: {script_dir}")
|
| 411 |
+
print(f"Input shape: [{args.batch_size}, {args.channels}, {args.height}, {args.width}]")
|
| 412 |
+
print(f"Config: {model_name}_config.yaml")
|
| 413 |
+
else:
|
| 414 |
+
print("\n✗ Shape fixing failed")
|
| 415 |
+
|
| 416 |
+
return success
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def main():
|
| 420 |
+
parser = argparse.ArgumentParser(
|
| 421 |
+
description=(
|
| 422 |
+
'Export DINOv2 classification models (backbone + linear head) from PyTorch Hub\n'
|
| 423 |
+
'to ONNX format with fixed static shapes for TI EdgeAI hardware deployment.\n'
|
| 424 |
+
'\n'
|
| 425 |
+
'Processing pipeline:\n'
|
| 426 |
+
' 1. Load pretrained model from torch.hub (facebookresearch/dinov2)\n'
|
| 427 |
+
' 2. Export to ONNX (opset 17) with dynamic batch axis\n'
|
| 428 |
+
' 3. Fix dynamic input shapes to static [batch, channels, height, width]\n'
|
| 429 |
+
' 4. Run ONNX shape inference to propagate fixed shapes through all layers\n'
|
| 430 |
+
' 5. Run ONNX simplification via onnxsim (use --no-simplifier to skip)\n'
|
| 431 |
+
' 6. Validate the final model with onnx.checker'
|
| 432 |
+
),
|
| 433 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 434 |
+
epilog="""
|
| 435 |
+
Examples:
|
| 436 |
+
# Export default model (ViT-S/14)
|
| 437 |
+
%(prog)s
|
| 438 |
+
|
| 439 |
+
# Export a specific variant
|
| 440 |
+
%(prog)s --model dinov2_vitb14_lc
|
| 441 |
+
|
| 442 |
+
# Export all supported models in sequence
|
| 443 |
+
%(prog)s --model all
|
| 444 |
+
|
| 445 |
+
# Export all models, skip onnxsim
|
| 446 |
+
%(prog)s --model all --no-simplifier
|
| 447 |
+
|
| 448 |
+
# Export with registers variant
|
| 449 |
+
%(prog)s --model dinov2_vits14_reg_lc
|
| 450 |
+
|
| 451 |
+
# Skip onnxsim (faster export, larger model file, shape inference still runs)
|
| 452 |
+
%(prog)s --model dinov2_vitl14_lc --no-simplifier
|
| 453 |
+
|
| 454 |
+
# Re-run shape inference + onnxsim on an already-exported ONNX file
|
| 455 |
+
%(prog)s --model dinov2_vits14_lc --skip-export
|
| 456 |
+
|
| 457 |
+
# Force re-export even if ONNX file exists
|
| 458 |
+
%(prog)s --model dinov2_vits14_lc --force-export
|
| 459 |
+
|
| 460 |
+
Available models:
|
| 461 |
+
all Export all models listed below in sequence
|
| 462 |
+
dinov2_vits14_lc ViT-S/14 distilled, 21M params, 81.1%% top-1 (recommended)
|
| 463 |
+
dinov2_vitb14_lc ViT-B/14 distilled, 86M params, 84.5%% top-1
|
| 464 |
+
dinov2_vitl14_lc ViT-L/14 distilled, 307M params, 86.3%% top-1
|
| 465 |
+
dinov2_vitg14_lc ViT-g/14, 1100M params, 86.5%% top-1 (not for edge)
|
| 466 |
+
dinov2_vits14_reg_lc ViT-S/14 + registers, 21M params, 80.9%% top-1 (recommended)
|
| 467 |
+
dinov2_vitb14_reg_lc ViT-B/14 + registers, 86M params, 84.6%% top-1
|
| 468 |
+
dinov2_vitl14_reg_lc ViT-L/14 + registers, 307M params, 86.7%% top-1
|
| 469 |
+
dinov2_vitg14_reg_lc ViT-g/14 + registers, 1100M params, 87.1%% top-1 (not for edge)
|
| 470 |
+
"""
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
parser.add_argument(
|
| 474 |
+
'--model', type=str, default='dinov2_vits14_lc',
|
| 475 |
+
choices=list(SUPPORTED_MODELS.keys()) + ['all'],
|
| 476 |
+
help=(
|
| 477 |
+
'Model variant to export, or "all" to export every supported model '
|
| 478 |
+
'(default: dinov2_vits14_lc)'
|
| 479 |
+
),
|
| 480 |
+
)
|
| 481 |
+
parser.add_argument('--batch-size', type=int, default=1,
|
| 482 |
+
help='Fixed batch size (default: 1)')
|
| 483 |
+
parser.add_argument('--channels', type=int, default=3,
|
| 484 |
+
help='Number of channels (default: 3)')
|
| 485 |
+
parser.add_argument('--height', type=int, default=224,
|
| 486 |
+
help='Image height (default: 224)')
|
| 487 |
+
parser.add_argument('--width', type=int, default=224,
|
| 488 |
+
help='Image width (default: 224)')
|
| 489 |
+
parser.add_argument('--force-export', action='store_true',
|
| 490 |
+
help='Force re-export even if ONNX file already exists')
|
| 491 |
+
parser.add_argument('--skip-export', action='store_true',
|
| 492 |
+
help='Skip export, only re-run shape inference + onnxsim on existing ONNX')
|
| 493 |
+
parser.add_argument('--no-simplifier', action='store_true',
|
| 494 |
+
help='Skip onnx-simplifier (onnxsim) step; shape inference still runs')
|
| 495 |
+
|
| 496 |
+
args = parser.parse_args()
|
| 497 |
+
script_dir = Path(__file__).parent
|
| 498 |
+
|
| 499 |
+
if args.model == 'all':
|
| 500 |
+
models = EDGE_MODELS
|
| 501 |
+
skipped = [m for m in SUPPORTED_MODELS if m not in EDGE_MODELS]
|
| 502 |
+
print(f"Exporting {len(models)} edge-suitable DINOv2 models...")
|
| 503 |
+
if skipped:
|
| 504 |
+
print(f"Skipping (not for edge, ~16 GB RAM required): {', '.join(skipped)}")
|
| 505 |
+
results = {}
|
| 506 |
+
for model_name in models:
|
| 507 |
+
results[model_name] = _prepare_single_model(model_name, args, script_dir)
|
| 508 |
+
|
| 509 |
+
print("\n" + "=" * 80)
|
| 510 |
+
print("ALL MODELS SUMMARY")
|
| 511 |
+
print("=" * 80)
|
| 512 |
+
succeeded = [m for m, ok in results.items() if ok]
|
| 513 |
+
failed = [m for m, ok in results.items() if not ok]
|
| 514 |
+
for m in succeeded:
|
| 515 |
+
print(f" ✓ {m}")
|
| 516 |
+
for m in failed:
|
| 517 |
+
print(f" ✗ {m}")
|
| 518 |
+
print(f"\n{len(succeeded)}/{len(models)} models completed successfully.")
|
| 519 |
+
sys.exit(0 if not failed else 1)
|
| 520 |
+
else:
|
| 521 |
+
ok = _prepare_single_model(args.model, args, script_dir)
|
| 522 |
+
sys.exit(0 if ok else 1)
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
if __name__ == '__main__':
|
| 526 |
+
main()
|