Upload folder using huggingface_hub
Browse files- .gitattributes +3 -0
- README.md +126 -0
- config.json +3 -0
- export_iat_onnx.py +372 -0
- onnx/iat_exposure.onnx +3 -0
- onnx/iat_exposure.onnx.data +3 -0
- onnx/iat_lol_v1.onnx +3 -0
- onnx/iat_lol_v1.onnx.data +3 -0
- onnx/iat_lol_v2.onnx +3 -0
- onnx/iat_lol_v2.onnx.data +3 -0
- preprocessor_config.json +5 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
onnx/iat_exposure.onnx.data filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
onnx/iat_lol_v1.onnx.data filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
onnx/iat_lol_v2.onnx.data filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
base_model: cuiziteng/Illumination-Adaptive-Transformer
|
| 4 |
+
pipeline_tag: image-to-image
|
| 5 |
+
tags:
|
| 6 |
+
- low-light-enhancement
|
| 7 |
+
- exposure-correction
|
| 8 |
+
- image-enhancement
|
| 9 |
+
- onnx
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# IAT — Illumination Adaptive Transformer (ONNX)
|
| 13 |
+
|
| 14 |
+
**First public ONNX export** of the [Illumination Adaptive Transformer (IAT)](https://github.com/cuiziteng/Illumination-Adaptive-Transformer) by Cui et al.
|
| 15 |
+
|
| 16 |
+
This repo contains three ONNX variants exported from the official PyTorch checkpoints, covering both low-light enhancement and exposure correction tasks.
|
| 17 |
+
|
| 18 |
+
## Variants
|
| 19 |
+
|
| 20 |
+
| File | Checkpoint | Training Data | Use Case |
|
| 21 |
+
|------|-----------|---------------|----------|
|
| 22 |
+
| `onnx/iat_exposure.onnx` | `best_Epoch_exposure.pth` | [Exposure Errors](https://github.com/mahmoudnafifi/Exposure_Correction) | Over/under-exposure correction |
|
| 23 |
+
| `onnx/iat_lol_v1.onnx` | `best_Epoch_lol_v1.pth` | [LOL-V1](https://daooshee.github.io/BMVC2018website/) | Low-light enhancement |
|
| 24 |
+
| `onnx/iat_lol_v2.onnx` | `best_Epoch_lol.pth` | [LOL-V2](https://github.com/flyywh/CVPR-2020-Semi-Low-Light) | Low-light enhancement (improved) |
|
| 25 |
+
|
| 26 |
+
## Model Specs
|
| 27 |
+
|
| 28 |
+
| Property | Value |
|
| 29 |
+
|----------|-------|
|
| 30 |
+
| Parameters | ~90K |
|
| 31 |
+
| File size | ~0.1 MB per variant |
|
| 32 |
+
| Input shape | `(1, 3, H, W)` float32, values in `[0, 1]` |
|
| 33 |
+
| Normalization | **None** — just rescale to [0,1], no ImageNet mean/std |
|
| 34 |
+
| Output names | `mul`, `add`, `enhanced` |
|
| 35 |
+
| Which output to use | `enhanced` (index 2) |
|
| 36 |
+
| Dynamic axes | batch, height, width |
|
| 37 |
+
| ONNX opset | 17 |
|
| 38 |
+
|
| 39 |
+
## Preprocessing
|
| 40 |
+
|
| 41 |
+
```python
|
| 42 |
+
import numpy as np
|
| 43 |
+
from PIL import Image
|
| 44 |
+
|
| 45 |
+
img = Image.open("dark_photo.jpg").convert("RGB")
|
| 46 |
+
img_np = np.array(img).astype(np.float32) / 255.0 # [0, 1]
|
| 47 |
+
# Transpose to CHW and add batch dim
|
| 48 |
+
input_tensor = img_np.transpose(2, 0, 1)[np.newaxis, ...] # (1, 3, H, W)
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
**Important:** Do NOT apply ImageNet normalization. The model expects raw `[0, 1]` pixel values.
|
| 52 |
+
|
| 53 |
+
## Usage with ONNX Runtime
|
| 54 |
+
|
| 55 |
+
```python
|
| 56 |
+
import numpy as np
|
| 57 |
+
import onnxruntime as ort
|
| 58 |
+
from PIL import Image
|
| 59 |
+
|
| 60 |
+
# Load model
|
| 61 |
+
session = ort.InferenceSession("onnx/iat_lol_v2.onnx", providers=["CPUExecutionProvider"])
|
| 62 |
+
|
| 63 |
+
# Preprocess
|
| 64 |
+
img = Image.open("dark_photo.jpg").convert("RGB")
|
| 65 |
+
img_np = np.array(img).astype(np.float32) / 255.0
|
| 66 |
+
input_tensor = img_np.transpose(2, 0, 1)[np.newaxis, ...] # (1, 3, H, W)
|
| 67 |
+
|
| 68 |
+
# Run inference — use "enhanced" (index 2)
|
| 69 |
+
mul, add, enhanced = session.run(None, {"input": input_tensor})
|
| 70 |
+
|
| 71 |
+
# Post-process
|
| 72 |
+
enhanced = np.clip(enhanced[0], 0, 1) # (3, H, W)
|
| 73 |
+
enhanced = (enhanced.transpose(1, 2, 0) * 255).astype(np.uint8) # (H, W, 3)
|
| 74 |
+
result = Image.fromarray(enhanced)
|
| 75 |
+
result.save("enhanced.jpg")
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
## ONNX Export Fixes
|
| 79 |
+
|
| 80 |
+
The original PyTorch code required three monkey-patches for clean ONNX tracing:
|
| 81 |
+
|
| 82 |
+
1. **`IAT.apply_color`**: Replaced `torch.tensordot(image, ccm, dims=[[-1], [-1]])` with `torch.matmul(image, ccm.T)` — `tensordot` with negative dimension indices is not supported by the ONNX exporter.
|
| 83 |
+
|
| 84 |
+
2. **`IAT.forward`**: Replaced Python for-loop over the batch dimension (`for i in range(b)`) with vectorized `torch.bmm` for the color matrix multiply and broadcast `**` for gamma correction. Python loops produce unrollable static graphs that break with dynamic batch sizes.
|
| 85 |
+
|
| 86 |
+
3. **`Aff_channel.forward`**: Same `tensordot` to `matmul` fix as patch 1, applied to the channel affinity block in the local branch.
|
| 87 |
+
|
| 88 |
+
See `export_iat_onnx.py` in this repo for the full export script with patches.
|
| 89 |
+
|
| 90 |
+
## Architecture
|
| 91 |
+
|
| 92 |
+
IAT is a lightweight image enhancement model with two branches:
|
| 93 |
+
|
| 94 |
+
- **Local branch**: Learns per-pixel multiplicative (`mul`) and additive (`add`) adjustment maps via a shallow transformer. `enhanced_local = input * mul + add`
|
| 95 |
+
- **Global branch**: Learns a 3x3 color correction matrix (CCM) and a scalar gamma value. Applied after local enhancement: `enhanced = (enhanced_local @ CCM^T) ^ gamma`
|
| 96 |
+
|
| 97 |
+
The combination of local pixel-wise adjustments and global color/tone correction makes it effective for both low-light enhancement and exposure correction, while keeping the model extremely small (~90K parameters).
|
| 98 |
+
|
| 99 |
+
## Benchmark Results
|
| 100 |
+
|
| 101 |
+
Results from the original paper:
|
| 102 |
+
|
| 103 |
+
| Dataset | PSNR | SSIM |
|
| 104 |
+
|---------|------|------|
|
| 105 |
+
| LOL-V1 | 23.38 | 0.809 |
|
| 106 |
+
| LOL-V2 | 23.50 | 0.824 |
|
| 107 |
+
|
| 108 |
+
## Citation
|
| 109 |
+
|
| 110 |
+
```bibtex
|
| 111 |
+
@InProceedings{Cui_2022_BMVC,
|
| 112 |
+
title = {Illumination Adaptive Transformer},
|
| 113 |
+
author = {Cui, Ziteng and Li, Kunchang and Gu, Lin and Su, Shenghan and Gao, Peng and Jiang, Zhengkai and Qiao, Yu and Harada, Tatsuya},
|
| 114 |
+
booktitle = {British Machine Vision Conference (BMVC)},
|
| 115 |
+
year = {2022}
|
| 116 |
+
}
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
## License
|
| 120 |
+
|
| 121 |
+
Apache-2.0 — same as the original IAT repository.
|
| 122 |
+
|
| 123 |
+
## Acknowledgments
|
| 124 |
+
|
| 125 |
+
- Original model and research by [Cui et al.](https://github.com/cuiziteng/Illumination-Adaptive-Transformer)
|
| 126 |
+
- ONNX export and this model card by [ListingLens](https://github.com/Pezhgorski/listinglens)
|
config.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "iat"
|
| 3 |
+
}
|
export_iat_onnx.py
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
IAT (Illumination Adaptive Transformer) → ONNX Export Script
|
| 4 |
+
|
| 5 |
+
Monkey-patches ONNX-incompatible patterns in IAT source, exports all 3
|
| 6 |
+
checkpoints (exposure, lol_v1, lol_v2), and verifies each numerically
|
| 7 |
+
at multiple resolutions.
|
| 8 |
+
|
| 9 |
+
Patches applied:
|
| 10 |
+
1. IAT.apply_color: tensordot → matmul (ONNX-friendly)
|
| 11 |
+
2. IAT.forward: Python for-loop over batch → vectorized bmm + broadcast pow
|
| 12 |
+
3. Aff_channel.forward: tensordot → matmul (fallback — needed for tracing)
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import sys
|
| 17 |
+
import os
|
| 18 |
+
import time
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn as nn
|
| 24 |
+
|
| 25 |
+
# ---------------------------------------------------------------------------
|
| 26 |
+
# Add IAT source to path, fix Python 3.12+ compatibility
|
| 27 |
+
# ---------------------------------------------------------------------------
|
| 28 |
+
IAT_ROOT = Path(__file__).parent / "iat" / "IAT_enhance"
|
| 29 |
+
sys.path.insert(0, str(IAT_ROOT))
|
| 30 |
+
|
| 31 |
+
# IAT's global_net.py has `import imp` which was removed in Python 3.12.
|
| 32 |
+
# It's unused, so we provide a dummy module before importing IAT.
|
| 33 |
+
import importlib
|
| 34 |
+
if not importlib.util.find_spec("imp"):
|
| 35 |
+
import types
|
| 36 |
+
sys.modules["imp"] = types.ModuleType("imp")
|
| 37 |
+
|
| 38 |
+
from model.IAT_main import IAT # noqa: E402
|
| 39 |
+
from model.blocks import Aff_channel # noqa: E402
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# ===========================================================================
|
| 43 |
+
# Monkey-patches
|
| 44 |
+
# ===========================================================================
|
| 45 |
+
|
| 46 |
+
def _patched_apply_color(self, image, ccm):
|
| 47 |
+
"""Replace tensordot with matmul for ONNX compatibility.
|
| 48 |
+
|
| 49 |
+
Original: torch.tensordot(image, ccm, dims=[[-1], [-1]])
|
| 50 |
+
which computes image @ ccm.T (contract last dim of both)
|
| 51 |
+
Replacement: torch.matmul(image, ccm.T)
|
| 52 |
+
"""
|
| 53 |
+
shape = image.shape
|
| 54 |
+
image = image.view(-1, 3)
|
| 55 |
+
image = torch.matmul(image, ccm.permute(1, 0))
|
| 56 |
+
image = image.view(shape)
|
| 57 |
+
return torch.clamp(image, 1e-8, 1.0)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _patched_forward(self, img_low):
|
| 61 |
+
"""Vectorized forward — no Python for-loop over batch dimension.
|
| 62 |
+
|
| 63 |
+
Original:
|
| 64 |
+
img_high = torch.stack([self.apply_color(img_high[i,:,:,:], color[i,:,:])
|
| 65 |
+
**gamma[i,:] for i in range(b)], dim=0)
|
| 66 |
+
|
| 67 |
+
Replacement:
|
| 68 |
+
1. bmm for batched color matrix multiply
|
| 69 |
+
2. broadcast pow for gamma
|
| 70 |
+
"""
|
| 71 |
+
mul, add = self.local_net(img_low)
|
| 72 |
+
img_high = (img_low.mul(mul)).add(add)
|
| 73 |
+
|
| 74 |
+
if not self.with_global:
|
| 75 |
+
return mul, add, img_high
|
| 76 |
+
|
| 77 |
+
gamma, color = self.global_net(img_low)
|
| 78 |
+
# img_high: (B, C, H, W) → (B, H, W, C) → (B, H*W, C)
|
| 79 |
+
b, c, h, w = img_high.shape
|
| 80 |
+
img_high = img_high.permute(0, 2, 3, 1).reshape(b, h * w, c)
|
| 81 |
+
|
| 82 |
+
# Batched color matrix: (B, H*W, 3) @ (B, 3, 3) → (B, H*W, 3)
|
| 83 |
+
# color is (B, 3, 3), we need img @ color^T for each batch element
|
| 84 |
+
color_t = color.permute(0, 2, 1) # (B, 3, 3)
|
| 85 |
+
img_high = torch.bmm(img_high, color_t)
|
| 86 |
+
img_high = torch.clamp(img_high, 1e-8, 1.0)
|
| 87 |
+
|
| 88 |
+
# Reshape back to (B, H, W, C) for broadcast pow
|
| 89 |
+
img_high = img_high.view(b, h, w, c)
|
| 90 |
+
|
| 91 |
+
# gamma is (B, 1) — reshape to (B, 1, 1, 1) for broadcast
|
| 92 |
+
gamma_broadcast = gamma.unsqueeze(-1).unsqueeze(-1) # (B, 1, 1, 1)
|
| 93 |
+
img_high = img_high ** gamma_broadcast
|
| 94 |
+
|
| 95 |
+
# (B, H, W, C) → (B, C, H, W)
|
| 96 |
+
img_high = img_high.permute(0, 3, 1, 2)
|
| 97 |
+
return mul, add, img_high
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _patched_aff_channel_forward(self, x):
|
| 101 |
+
"""Replace tensordot with matmul in Aff_channel for ONNX compatibility.
|
| 102 |
+
|
| 103 |
+
Original: torch.tensordot(x, self.color, dims=[[-1], [-1]])
|
| 104 |
+
Replacement: torch.matmul(x, self.color.T)
|
| 105 |
+
"""
|
| 106 |
+
if self.channel_first:
|
| 107 |
+
x1 = torch.matmul(x, self.color.permute(1, 0))
|
| 108 |
+
x2 = x1 * self.alpha + self.beta
|
| 109 |
+
else:
|
| 110 |
+
x1 = x * self.alpha + self.beta
|
| 111 |
+
x2 = torch.matmul(x1, self.color.permute(1, 0))
|
| 112 |
+
return x2
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# ===========================================================================
|
| 116 |
+
# Fallback patches (not needed for current export, documented for reference)
|
| 117 |
+
# ===========================================================================
|
| 118 |
+
|
| 119 |
+
# --- Fallback: query_Attention expand ---
|
| 120 |
+
# If export fails on expand in global attention (global_net.py):
|
| 121 |
+
#
|
| 122 |
+
# def _patched_query_attention_forward(self, x):
|
| 123 |
+
# B, N, C = x.shape
|
| 124 |
+
# # Original: self.q.expand(B, -1, -1) -- can fail with dynamic batch
|
| 125 |
+
# # Fix: use repeat which traces cleanly
|
| 126 |
+
# q = self.q.repeat(B, 1, 1).view(B, -1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
|
| 127 |
+
# ... rest of forward unchanged ...
|
| 128 |
+
#
|
| 129 |
+
# from model.global_net import query_Attention
|
| 130 |
+
# query_Attention.forward = _patched_query_attention_forward
|
| 131 |
+
|
| 132 |
+
# --- Fallback: gamma power operator ---
|
| 133 |
+
# If ** operator traces incorrectly for broadcast shapes:
|
| 134 |
+
#
|
| 135 |
+
# Replace in _patched_forward:
|
| 136 |
+
# img_high = torch.pow(torch.clamp(img_high, 1e-8), gamma)
|
| 137 |
+
# With:
|
| 138 |
+
# img_high = torch.exp(torch.log(torch.clamp(img_high, 1e-8)) * gamma)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# ===========================================================================
|
| 142 |
+
# Checkpoint configurations
|
| 143 |
+
# ===========================================================================
|
| 144 |
+
|
| 145 |
+
CHECKPOINTS = {
|
| 146 |
+
"exposure": {
|
| 147 |
+
"path": IAT_ROOT / "best_Epoch_exposure.pth",
|
| 148 |
+
"model_kwargs": {"type": "exp"},
|
| 149 |
+
"description": "Exposure correction",
|
| 150 |
+
},
|
| 151 |
+
"lol_v1": {
|
| 152 |
+
"path": IAT_ROOT / "best_Epoch_lol_v1.pth",
|
| 153 |
+
"model_kwargs": {"type": "lol"},
|
| 154 |
+
"description": "LOL v1 low-light enhancement",
|
| 155 |
+
},
|
| 156 |
+
"lol_v2": {
|
| 157 |
+
"path": IAT_ROOT / "best_Epoch_lol.pth",
|
| 158 |
+
"model_kwargs": {"type": "lol"},
|
| 159 |
+
"description": "LOL v2 low-light enhancement",
|
| 160 |
+
},
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
VERIFICATION_RESOLUTIONS = [
|
| 164 |
+
(256, 256),
|
| 165 |
+
(512, 512),
|
| 166 |
+
(768, 1024), # H, W — non-square
|
| 167 |
+
]
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
# ===========================================================================
|
| 171 |
+
# Apply patches
|
| 172 |
+
# ===========================================================================
|
| 173 |
+
|
| 174 |
+
def apply_patches():
|
| 175 |
+
"""Monkey-patch IAT classes at runtime. Does not modify source files."""
|
| 176 |
+
# Patch 1 & 2: IAT.apply_color and IAT.forward
|
| 177 |
+
IAT.apply_color = _patched_apply_color
|
| 178 |
+
IAT.forward = _patched_forward
|
| 179 |
+
|
| 180 |
+
# Patch 3 (fallback — needed for Aff_channel tensordot tracing):
|
| 181 |
+
Aff_channel.forward = _patched_aff_channel_forward
|
| 182 |
+
|
| 183 |
+
print("[PATCH] IAT.apply_color: tensordot -> matmul")
|
| 184 |
+
print("[PATCH] IAT.forward: for-loop -> vectorized bmm + broadcast pow")
|
| 185 |
+
print("[PATCH] Aff_channel.forward: tensordot -> matmul")
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
# ===========================================================================
|
| 189 |
+
# Export
|
| 190 |
+
# ===========================================================================
|
| 191 |
+
|
| 192 |
+
def load_model(name: str) -> nn.Module:
|
| 193 |
+
"""Load an IAT model from checkpoint."""
|
| 194 |
+
cfg = CHECKPOINTS[name]
|
| 195 |
+
model = IAT(in_dim=3, with_global=True, **cfg["model_kwargs"])
|
| 196 |
+
state_dict = torch.load(str(cfg["path"]), map_location="cpu", weights_only=True)
|
| 197 |
+
model.load_state_dict(state_dict)
|
| 198 |
+
model.train(False)
|
| 199 |
+
return model
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def export_onnx(model: nn.Module, output_path: Path, opset: int) -> None:
|
| 203 |
+
"""Export a single IAT model to ONNX."""
|
| 204 |
+
dummy_input = torch.randn(1, 3, 256, 256)
|
| 205 |
+
|
| 206 |
+
torch.onnx.export(
|
| 207 |
+
model,
|
| 208 |
+
(dummy_input,),
|
| 209 |
+
str(output_path),
|
| 210 |
+
opset_version=opset,
|
| 211 |
+
input_names=["input"],
|
| 212 |
+
output_names=["mul", "add", "enhanced"],
|
| 213 |
+
dynamic_axes={
|
| 214 |
+
"input": {0: "batch", 2: "height", 3: "width"},
|
| 215 |
+
"mul": {0: "batch", 2: "height", 3: "width"},
|
| 216 |
+
"add": {0: "batch", 2: "height", 3: "width"},
|
| 217 |
+
"enhanced": {0: "batch", 2: "height", 3: "width"},
|
| 218 |
+
},
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def verify_onnx(model: nn.Module, onnx_path: Path) -> bool:
|
| 223 |
+
"""Numerical verification of ONNX vs PyTorch at multiple resolutions."""
|
| 224 |
+
import onnxruntime as ort
|
| 225 |
+
|
| 226 |
+
session = ort.InferenceSession(
|
| 227 |
+
str(onnx_path),
|
| 228 |
+
providers=["CPUExecutionProvider"],
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
all_ok = True
|
| 232 |
+
for h, w in VERIFICATION_RESOLUTIONS:
|
| 233 |
+
dummy = torch.randn(1, 3, h, w)
|
| 234 |
+
|
| 235 |
+
# PyTorch reference
|
| 236 |
+
with torch.no_grad():
|
| 237 |
+
pt_mul, pt_add, pt_enhanced = model(dummy)
|
| 238 |
+
|
| 239 |
+
# ONNX Runtime
|
| 240 |
+
ort_inputs = {"input": dummy.numpy()}
|
| 241 |
+
ort_mul, ort_add, ort_enhanced = session.run(None, ort_inputs)
|
| 242 |
+
|
| 243 |
+
# Compare enhanced output (the one that matters most)
|
| 244 |
+
for name, pt_out, ort_out in [
|
| 245 |
+
("mul", pt_mul, ort_mul),
|
| 246 |
+
("add", pt_add, ort_add),
|
| 247 |
+
("enhanced", pt_enhanced, ort_enhanced),
|
| 248 |
+
]:
|
| 249 |
+
max_diff = np.max(np.abs(pt_out.numpy() - ort_out))
|
| 250 |
+
if max_diff < 1e-5:
|
| 251 |
+
status = "OK"
|
| 252 |
+
symbol = "+"
|
| 253 |
+
elif max_diff < 1e-3:
|
| 254 |
+
status = "WARN"
|
| 255 |
+
symbol = "~"
|
| 256 |
+
else:
|
| 257 |
+
status = "FAIL"
|
| 258 |
+
symbol = "X"
|
| 259 |
+
|
| 260 |
+
print(f" [{symbol}] {h}x{w} {name:10s} max_diff={max_diff:.2e} [{status}]")
|
| 261 |
+
|
| 262 |
+
if max_diff >= 1e-3:
|
| 263 |
+
print(f" FAIL: max abs diff {max_diff:.6f} >= 1e-3")
|
| 264 |
+
all_ok = False
|
| 265 |
+
|
| 266 |
+
return all_ok
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
# ===========================================================================
|
| 270 |
+
# Main
|
| 271 |
+
# ===========================================================================
|
| 272 |
+
|
| 273 |
+
def main():
|
| 274 |
+
parser = argparse.ArgumentParser(description="Export IAT checkpoints to ONNX")
|
| 275 |
+
parser.add_argument(
|
| 276 |
+
"--checkpoints",
|
| 277 |
+
type=str,
|
| 278 |
+
default="all",
|
| 279 |
+
choices=["all", "exposure", "lol_v1", "lol_v2"],
|
| 280 |
+
help="Which checkpoint(s) to export",
|
| 281 |
+
)
|
| 282 |
+
parser.add_argument(
|
| 283 |
+
"--output-dir",
|
| 284 |
+
type=str,
|
| 285 |
+
default=str(Path(__file__).parent / "outputs"),
|
| 286 |
+
help="Directory for exported ONNX files",
|
| 287 |
+
)
|
| 288 |
+
parser.add_argument(
|
| 289 |
+
"--opset",
|
| 290 |
+
type=int,
|
| 291 |
+
default=17,
|
| 292 |
+
help="ONNX opset version",
|
| 293 |
+
)
|
| 294 |
+
args = parser.parse_args()
|
| 295 |
+
|
| 296 |
+
output_dir = Path(args.output_dir)
|
| 297 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 298 |
+
|
| 299 |
+
# Determine which checkpoints to export
|
| 300 |
+
if args.checkpoints == "all":
|
| 301 |
+
names = list(CHECKPOINTS.keys())
|
| 302 |
+
else:
|
| 303 |
+
names = [args.checkpoints]
|
| 304 |
+
|
| 305 |
+
# Apply monkey-patches
|
| 306 |
+
print("=" * 60)
|
| 307 |
+
print("Applying ONNX-compatibility patches...")
|
| 308 |
+
print("=" * 60)
|
| 309 |
+
apply_patches()
|
| 310 |
+
print()
|
| 311 |
+
|
| 312 |
+
results = {}
|
| 313 |
+
for name in names:
|
| 314 |
+
cfg = CHECKPOINTS[name]
|
| 315 |
+
onnx_path = output_dir / f"iat_{name}.onnx"
|
| 316 |
+
|
| 317 |
+
print("=" * 60)
|
| 318 |
+
print(f"Exporting: {name} ({cfg['description']})")
|
| 319 |
+
print(f" Checkpoint: {cfg['path']}")
|
| 320 |
+
print(f" Output: {onnx_path}")
|
| 321 |
+
print("=" * 60)
|
| 322 |
+
|
| 323 |
+
# Check checkpoint exists
|
| 324 |
+
if not cfg["path"].exists():
|
| 325 |
+
print(f" SKIP: checkpoint not found at {cfg['path']}")
|
| 326 |
+
results[name] = "SKIP"
|
| 327 |
+
continue
|
| 328 |
+
|
| 329 |
+
# Load
|
| 330 |
+
t0 = time.time()
|
| 331 |
+
model = load_model(name)
|
| 332 |
+
print(f" Loaded model in {time.time() - t0:.2f}s")
|
| 333 |
+
|
| 334 |
+
# Export
|
| 335 |
+
t0 = time.time()
|
| 336 |
+
export_onnx(model, onnx_path, args.opset)
|
| 337 |
+
export_time = time.time() - t0
|
| 338 |
+
file_size_mb = onnx_path.stat().st_size / (1024 * 1024)
|
| 339 |
+
print(f" Exported in {export_time:.2f}s ({file_size_mb:.1f} MB)")
|
| 340 |
+
|
| 341 |
+
# Verify
|
| 342 |
+
print(f" Verifying at {len(VERIFICATION_RESOLUTIONS)} resolutions...")
|
| 343 |
+
ok = verify_onnx(model, onnx_path)
|
| 344 |
+
results[name] = "PASS" if ok else "FAIL"
|
| 345 |
+
print()
|
| 346 |
+
|
| 347 |
+
# Summary
|
| 348 |
+
print("=" * 60)
|
| 349 |
+
print("SUMMARY")
|
| 350 |
+
print("=" * 60)
|
| 351 |
+
all_pass = True
|
| 352 |
+
for name, status in results.items():
|
| 353 |
+
if status == "PASS":
|
| 354 |
+
symbol = "+"
|
| 355 |
+
elif status == "SKIP":
|
| 356 |
+
symbol = "-"
|
| 357 |
+
else:
|
| 358 |
+
symbol = "X"
|
| 359 |
+
print(f" [{symbol}] {name}: {status}")
|
| 360 |
+
if status == "FAIL":
|
| 361 |
+
all_pass = False
|
| 362 |
+
|
| 363 |
+
if not all_pass:
|
| 364 |
+
print("\nSome exports FAILED numerical verification!")
|
| 365 |
+
sys.exit(1)
|
| 366 |
+
else:
|
| 367 |
+
print("\nAll exports passed!")
|
| 368 |
+
sys.exit(0)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
if __name__ == "__main__":
|
| 372 |
+
main()
|
onnx/iat_exposure.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bd16c959a336b99ff15bef071ad6e9b081017241e5575d9e391653b676f2a5c6
|
| 3 |
+
size 66820
|
onnx/iat_exposure.onnx.data
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f92c0ab92266a096d117d3747fbbce244ca91e8a3f28f70db5b2048f478418a8
|
| 3 |
+
size 355264
|
onnx/iat_lol_v1.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cfc50128b40b65edd0dbeeb724d283639d129f70fd838c159f9106c463277fca
|
| 3 |
+
size 66698
|
onnx/iat_lol_v1.onnx.data
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fc59e6ecbcff44683654c318b50e649321d83050528a14165f059b70d24d1901
|
| 3 |
+
size 355264
|
onnx/iat_lol_v2.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:139d90e61bd8ae71dc7ac00c93a27c242f97876351f288713bc158cb5d04d3e5
|
| 3 |
+
size 66698
|
onnx/iat_lol_v2.onnx.data
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fa9af18c4ae6e7f91ca41a895dec0188343bfcc4112e162ac92cee708f52cdcf
|
| 3 |
+
size 355264
|
preprocessor_config.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"do_normalize": false,
|
| 3 |
+
"do_rescale": true,
|
| 4 |
+
"rescale_factor": 0.00392156862745098
|
| 5 |
+
}
|