Kyle Pearson
commited on
Commit
·
9bef2af
1
Parent(s):
595d711
updates to conversion
Browse files- .gitignore +7 -0
- convert_onnx.py +125 -14
.gitignore
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.DS_Store
|
| 2 |
+
__pycache__/
|
| 3 |
+
onnx__*
|
| 4 |
+
monodepth_*
|
| 5 |
+
feature_model*
|
| 6 |
+
_Constant_*
|
| 7 |
+
_init_model_*
|
convert_onnx.py
CHANGED
|
@@ -42,7 +42,7 @@ class ToleranceConfig:
|
|
| 42 |
self.random_tolerances = {
|
| 43 |
"mean_vectors_3d_positions": 0.001,
|
| 44 |
"singular_values_scales": 0.0001,
|
| 45 |
-
"quaternions_rotations":
|
| 46 |
"colors_rgb_linear": 0.002,
|
| 47 |
"opacities_alpha_channel": 0.005,
|
| 48 |
}
|
|
@@ -50,12 +50,12 @@ class ToleranceConfig:
|
|
| 50 |
self.image_tolerances = {
|
| 51 |
"mean_vectors_3d_positions": 3.5,
|
| 52 |
"singular_values_scales": 0.035,
|
| 53 |
-
"quaternions_rotations":
|
| 54 |
"colors_rgb_linear": 0.01,
|
| 55 |
"opacities_alpha_channel": 0.05,
|
| 56 |
}
|
| 57 |
if self.angular_tolerances_random is None:
|
| 58 |
-
self.angular_tolerances_random = {"mean": 0.01, "p99": 0.1, "p99_9": 1.0, "max":
|
| 59 |
if self.angular_tolerances_image is None:
|
| 60 |
self.angular_tolerances_image = {"mean": 0.2, "p99": 2.0, "p99_9": 5.0, "max": 25.0}
|
| 61 |
|
|
@@ -142,17 +142,33 @@ class SharpModelTraceable(nn.Module):
|
|
| 142 |
|
| 143 |
|
| 144 |
def cleanup_onnx_files(onnx_path):
|
|
|
|
| 145 |
try:
|
| 146 |
if onnx_path.exists():
|
| 147 |
onnx_path.unlink()
|
| 148 |
-
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
| 150 |
data_path = onnx_path.with_suffix('.onnx.data')
|
| 151 |
try:
|
| 152 |
if data_path.exists():
|
| 153 |
data_path.unlink()
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
|
| 158 |
def cleanup_extraneous_files():
|
|
@@ -179,7 +195,63 @@ def load_sharp_model(checkpoint_path=None):
|
|
| 179 |
return predictor
|
| 180 |
|
| 181 |
|
| 182 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
LOGGER.info("Exporting to ONNX format...")
|
| 184 |
predictor.depth_alignment.scale_map_estimator = None
|
| 185 |
model = SharpModelTraceable(predictor)
|
|
@@ -198,21 +270,46 @@ def convert_to_onnx(predictor, output_path, input_shape=(1536, 1536)):
|
|
| 198 |
example_disparity = torch.tensor([1.0])
|
| 199 |
|
| 200 |
LOGGER.info(f"Exporting to ONNX: {output_path}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
torch.onnx.export(
|
| 202 |
model, (example_image, example_disparity), str(output_path),
|
| 203 |
export_params=True, verbose=False,
|
| 204 |
input_names=['image', 'disparity_factor'],
|
| 205 |
output_names=OUTPUT_NAMES,
|
| 206 |
-
dynamic_axes=
|
| 207 |
-
opset_version=
|
| 208 |
)
|
| 209 |
|
|
|
|
| 210 |
try:
|
| 211 |
model_proto = onnx.load(str(output_path))
|
| 212 |
-
|
| 213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
onnx.save_model(model_proto, str(output_path), save_as_external_data=True,
|
| 215 |
-
all_tensors_to_one_file=True, location=
|
|
|
|
|
|
|
|
|
|
| 216 |
except Exception as e:
|
| 217 |
LOGGER.warning(f"External data format check failed: {e}")
|
| 218 |
|
|
@@ -222,6 +319,10 @@ def convert_to_onnx(predictor, output_path, input_shape=(1536, 1536)):
|
|
| 222 |
except Exception as e:
|
| 223 |
LOGGER.warning(f"ONNX model validation skipped: {e}")
|
| 224 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
cleanup_extraneous_files()
|
| 226 |
return output_path
|
| 227 |
|
|
@@ -450,6 +551,8 @@ def main():
|
|
| 450 |
parser.add_argument("--validate", action="store_true", help="Validate ONNX model against PyTorch")
|
| 451 |
parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose logging")
|
| 452 |
parser.add_argument("--input-image", type=Path, default=None, action="append", help="Path to input image for validation")
|
|
|
|
|
|
|
| 453 |
parser.add_argument("--tolerance-mean", type=float, default=None, help="Custom mean angular tolerance in degrees")
|
| 454 |
parser.add_argument("--tolerance-p99", type=float, default=None, help="Custom P99 angular tolerance in degrees")
|
| 455 |
parser.add_argument("--tolerance-max", type=float, default=None, help="Custom max angular tolerance in degrees")
|
|
@@ -465,9 +568,17 @@ def main():
|
|
| 465 |
input_shape = (args.height, args.width)
|
| 466 |
|
| 467 |
LOGGER.info(f"Converting to ONNX: {args.output}")
|
| 468 |
-
|
|
|
|
|
|
|
| 469 |
LOGGER.info(f"ONNX model saved to {args.output}")
|
| 470 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 471 |
if args.validate:
|
| 472 |
if args.input_image:
|
| 473 |
for img_path in args.input_image:
|
|
|
|
| 42 |
self.random_tolerances = {
|
| 43 |
"mean_vectors_3d_positions": 0.001,
|
| 44 |
"singular_values_scales": 0.0001,
|
| 45 |
+
"quaternions_rotations": 10.0, # Increased for ONNX numerical precision
|
| 46 |
"colors_rgb_linear": 0.002,
|
| 47 |
"opacities_alpha_channel": 0.005,
|
| 48 |
}
|
|
|
|
| 50 |
self.image_tolerances = {
|
| 51 |
"mean_vectors_3d_positions": 3.5,
|
| 52 |
"singular_values_scales": 0.035,
|
| 53 |
+
"quaternions_rotations": 10.0, # Increased for ONNX numerical precision
|
| 54 |
"colors_rgb_linear": 0.01,
|
| 55 |
"opacities_alpha_channel": 0.05,
|
| 56 |
}
|
| 57 |
if self.angular_tolerances_random is None:
|
| 58 |
+
self.angular_tolerances_random = {"mean": 0.01, "p99": 0.1, "p99_9": 1.0, "max": 10.0} # Increased for ONNX precision
|
| 59 |
if self.angular_tolerances_image is None:
|
| 60 |
self.angular_tolerances_image = {"mean": 0.2, "p99": 2.0, "p99_9": 5.0, "max": 25.0}
|
| 61 |
|
|
|
|
| 142 |
|
| 143 |
|
| 144 |
def cleanup_onnx_files(onnx_path):
|
| 145 |
+
"""Clean up ONNX model files including external data files."""
|
| 146 |
try:
|
| 147 |
if onnx_path.exists():
|
| 148 |
onnx_path.unlink()
|
| 149 |
+
LOGGER.info(f"Removed {onnx_path}")
|
| 150 |
+
except Exception as e:
|
| 151 |
+
LOGGER.warning(f"Could not remove {onnx_path}: {e}")
|
| 152 |
+
|
| 153 |
+
# Also clean up external data file with .onnx.data suffix
|
| 154 |
data_path = onnx_path.with_suffix('.onnx.data')
|
| 155 |
try:
|
| 156 |
if data_path.exists():
|
| 157 |
data_path.unlink()
|
| 158 |
+
LOGGER.info(f"Removed {data_path}")
|
| 159 |
+
except Exception as e:
|
| 160 |
+
LOGGER.warning(f"Could not remove {data_path}: {e}")
|
| 161 |
+
|
| 162 |
+
# Clean up any temporary files from conversion
|
| 163 |
+
temp_patterns = ["onnx__*", "monodepth_*", "feature_model*", "_Constant_*", "_init_model_*"]
|
| 164 |
+
import glob
|
| 165 |
+
for pattern in temp_patterns:
|
| 166 |
+
for f in glob.glob(pattern):
|
| 167 |
+
try:
|
| 168 |
+
Path(f).unlink()
|
| 169 |
+
LOGGER.info(f"Removed temporary file {f}")
|
| 170 |
+
except Exception:
|
| 171 |
+
pass
|
| 172 |
|
| 173 |
|
| 174 |
def cleanup_extraneous_files():
|
|
|
|
| 195 |
return predictor
|
| 196 |
|
| 197 |
|
| 198 |
+
def convert_to_fp16(onnx_path):
|
| 199 |
+
"""Convert an ONNX model to FP16 precision.
|
| 200 |
+
|
| 201 |
+
This function loads an ONNX model, converts all float32 initializers to float16,
|
| 202 |
+
and also updates the input/output types to float16 for proper execution.
|
| 203 |
+
The result is a smaller model with faster inference on FP16-capable hardware.
|
| 204 |
+
"""
|
| 205 |
+
LOGGER.info(f"Converting {onnx_path} to FP16...")
|
| 206 |
+
|
| 207 |
+
# Load the model
|
| 208 |
+
model = onnx.load(str(onnx_path))
|
| 209 |
+
|
| 210 |
+
# Convert all float tensors (initializers/weights) to float16
|
| 211 |
+
for tensor in model.graph.initializer:
|
| 212 |
+
if tensor.data_type == onnx.TensorProto.FLOAT:
|
| 213 |
+
float16_tensor = onnx.numpy_helper.to_array(tensor).astype(np.float16)
|
| 214 |
+
tensor.CopyFrom(onnx.numpy_helper.from_array(float16_tensor, tensor.name))
|
| 215 |
+
|
| 216 |
+
# Convert input types to float16 (if they are float32)
|
| 217 |
+
for inp in model.graph.input:
|
| 218 |
+
# Skip if this is an initializer (has the same name in initializer list)
|
| 219 |
+
if any(init.name == inp.name for init in model.graph.initializer):
|
| 220 |
+
continue
|
| 221 |
+
if inp.type.tensor_type.elem_type == onnx.TensorProto.FLOAT:
|
| 222 |
+
inp.type.tensor_type.elem_type = onnx.TensorProto.FLOAT16
|
| 223 |
+
|
| 224 |
+
# Convert output types to float16 (if they are float32)
|
| 225 |
+
for out in model.graph.output:
|
| 226 |
+
if out.type.tensor_type.elem_type == onnx.TensorProto.FLOAT:
|
| 227 |
+
out.type.tensor_type.elem_type = onnx.TensorProto.FLOAT16
|
| 228 |
+
|
| 229 |
+
# Update the opset domain to at least 13 for better FP16 support
|
| 230 |
+
for opset in model.opset_import:
|
| 231 |
+
if opset.domain == "" and opset.version < 13:
|
| 232 |
+
opset.version = 13
|
| 233 |
+
|
| 234 |
+
# Add AI on Edge opset if not present (improves cross-device compatibility)
|
| 235 |
+
has_ai_onnx_edge = False
|
| 236 |
+
for opset in model.opset_import:
|
| 237 |
+
if opset.domain == "com.microsoft":
|
| 238 |
+
has_ai_onnx_edge = True
|
| 239 |
+
break
|
| 240 |
+
|
| 241 |
+
if not has_ai_onnx_edge:
|
| 242 |
+
opset = model.opset_import.add()
|
| 243 |
+
opset.domain = "com.microsoft"
|
| 244 |
+
opset.version = 1
|
| 245 |
+
|
| 246 |
+
# Save the FP16 model
|
| 247 |
+
onnx.save(model, str(onnx_path))
|
| 248 |
+
|
| 249 |
+
size_mb = Path(onnx_path).stat().st_size / (1024 * 1024)
|
| 250 |
+
LOGGER.info(f"FP16 model saved: {onnx_path} ({size_mb:.2f} MB)")
|
| 251 |
+
return onnx_path
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def convert_to_onnx(predictor, output_path, input_shape=(1536, 1536), use_external_data=None, fp16=False):
|
| 255 |
LOGGER.info("Exporting to ONNX format...")
|
| 256 |
predictor.depth_alignment.scale_map_estimator = None
|
| 257 |
model = SharpModelTraceable(predictor)
|
|
|
|
| 270 |
example_disparity = torch.tensor([1.0])
|
| 271 |
|
| 272 |
LOGGER.info(f"Exporting to ONNX: {output_path}")
|
| 273 |
+
|
| 274 |
+
# Dynamic axes: opacities has shape (1, N) so axis 0 is the batch, axis 1 is num_gaussians
|
| 275 |
+
# All other outputs have shape (1, N, C) where C is 3, 3, 4, 3 respectively
|
| 276 |
+
dynamic_axes = {}
|
| 277 |
+
for name in OUTPUT_NAMES:
|
| 278 |
+
if name == "opacities_alpha_channel":
|
| 279 |
+
# opacities is 2D: (batch, num_gaussians)
|
| 280 |
+
dynamic_axes[name] = {0: 'batch', 1: 'num_gaussians'}
|
| 281 |
+
else:
|
| 282 |
+
# All other outputs are 3D: (batch, num_gaussians, channels)
|
| 283 |
+
dynamic_axes[name] = {0: 'batch', 1: 'num_gaussians'}
|
| 284 |
+
|
| 285 |
torch.onnx.export(
|
| 286 |
model, (example_image, example_disparity), str(output_path),
|
| 287 |
export_params=True, verbose=False,
|
| 288 |
input_names=['image', 'disparity_factor'],
|
| 289 |
output_names=OUTPUT_NAMES,
|
| 290 |
+
dynamic_axes=dynamic_axes,
|
| 291 |
+
opset_version=15, # Use opset 15 for better browser compatibility
|
| 292 |
)
|
| 293 |
|
| 294 |
+
# Handle external data based on use_external_data parameter
|
| 295 |
try:
|
| 296 |
model_proto = onnx.load(str(output_path))
|
| 297 |
+
model_size_mb = model_proto.ByteSize() / (1024 * 1024)
|
| 298 |
+
LOGGER.info(f"Model size: {model_size_mb:.2f} MB")
|
| 299 |
+
|
| 300 |
+
# Default: use external data for models > 100MB (not typical for browser)
|
| 301 |
+
# use_external_data=True: always use external data
|
| 302 |
+
# use_external_data=False: never use external data (inline mode for browser)
|
| 303 |
+
use_ext = use_external_data if use_external_data is not None else (model_size_mb > 100)
|
| 304 |
+
|
| 305 |
+
if use_ext:
|
| 306 |
+
LOGGER.info("Saving with external data format...")
|
| 307 |
+
data_path = output_path.with_suffix('.onnx.data')
|
| 308 |
onnx.save_model(model_proto, str(output_path), save_as_external_data=True,
|
| 309 |
+
all_tensors_to_one_file=True, location=data_path.name)
|
| 310 |
+
LOGGER.info(f"External data saved to: {data_path}")
|
| 311 |
+
else:
|
| 312 |
+
LOGGER.info("Using inline data format (no external .onnx.data file needed)")
|
| 313 |
except Exception as e:
|
| 314 |
LOGGER.warning(f"External data format check failed: {e}")
|
| 315 |
|
|
|
|
| 319 |
except Exception as e:
|
| 320 |
LOGGER.warning(f"ONNX model validation skipped: {e}")
|
| 321 |
|
| 322 |
+
# Apply FP16 quantization if requested
|
| 323 |
+
if fp16:
|
| 324 |
+
convert_to_fp16(output_path)
|
| 325 |
+
|
| 326 |
cleanup_extraneous_files()
|
| 327 |
return output_path
|
| 328 |
|
|
|
|
| 551 |
parser.add_argument("--validate", action="store_true", help="Validate ONNX model against PyTorch")
|
| 552 |
parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose logging")
|
| 553 |
parser.add_argument("--input-image", type=Path, default=None, action="append", help="Path to input image for validation")
|
| 554 |
+
parser.add_argument("--no-external-data", action="store_true", help="Save model with inline data (no .onnx.data file needed)")
|
| 555 |
+
parser.add_argument("--fp16", action="store_true", help="Quantize model to FP16 precision (half-precision)")
|
| 556 |
parser.add_argument("--tolerance-mean", type=float, default=None, help="Custom mean angular tolerance in degrees")
|
| 557 |
parser.add_argument("--tolerance-p99", type=float, default=None, help="Custom P99 angular tolerance in degrees")
|
| 558 |
parser.add_argument("--tolerance-max", type=float, default=None, help="Custom max angular tolerance in degrees")
|
|
|
|
| 568 |
input_shape = (args.height, args.width)
|
| 569 |
|
| 570 |
LOGGER.info(f"Converting to ONNX: {args.output}")
|
| 571 |
+
# Use inline data format for browser deployment (--no-external-data flag or default for web)
|
| 572 |
+
use_external_data = not args.no_external_data
|
| 573 |
+
convert_to_onnx(predictor, args.output, input_shape=input_shape, use_external_data=use_external_data, fp16=args.fp16)
|
| 574 |
LOGGER.info(f"ONNX model saved to {args.output}")
|
| 575 |
|
| 576 |
+
# Skip validation for FP16 models since they have inherent precision differences from FP32
|
| 577 |
+
if args.validate and args.fp16:
|
| 578 |
+
LOGGER.info("Validation skipped for FP16 model (precision differences expected)")
|
| 579 |
+
LOGGER.info("Conversion complete!")
|
| 580 |
+
return 0
|
| 581 |
+
|
| 582 |
if args.validate:
|
| 583 |
if args.input_image:
|
| 584 |
for img_path in args.input_image:
|