Kyle Pearson commited on
Commit
af51a4d
·
1 Parent(s): 1dd5974
Files changed (1) hide show
  1. convert_onnx.py +286 -10
convert_onnx.py CHANGED
@@ -3,6 +3,7 @@
3
  from __future__ import annotations
4
 
5
  import argparse
 
6
  import logging
7
  from dataclasses import dataclass
8
  from pathlib import Path
@@ -38,6 +39,9 @@ class ToleranceConfig:
38
  image_tolerances: dict = None
39
  angular_tolerances_random: dict = None
40
  angular_tolerances_image: dict = None
 
 
 
41
 
42
  def __post_init__(self):
43
  if self.random_tolerances is None:
@@ -60,6 +64,17 @@ class ToleranceConfig:
60
  self.angular_tolerances_random = {"mean": 0.01, "p99": 0.1, "p99_9": 1.0, "max": 10.0}
61
  if self.angular_tolerances_image is None:
62
  self.angular_tolerances_image = {"mean": 0.2, "p99": 2.0, "p99_9": 5.0, "max": 25.0}
 
 
 
 
 
 
 
 
 
 
 
63
 
64
 
65
  class QuaternionValidator:
@@ -143,6 +158,230 @@ class SharpModelTraceable(nn.Module):
143
  return (gaussians.mean_vectors, gaussians.singular_values, quats, gaussians.colors, gaussians.opacities)
144
 
145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  def cleanup_onnx_files(onnx_path):
147
  """Clean up ONNX model files including external data files."""
148
  try:
@@ -396,22 +635,35 @@ def validate_with_image(onnx_path, pytorch_model, image_path, input_shape=(1536,
396
  return all_passed
397
 
398
 
399
- def validate_onnx_model(onnx_path, pytorch_model, input_shape=(1536, 1536), angular_tolerances=None):
400
  LOGGER.info("Validating ONNX model against PyTorch...")
401
  np.random.seed(42)
402
  torch.manual_seed(42)
403
 
404
- test_image = np.random.rand(1, 3, input_shape[0], input_shape[1]).astype(np.float32)
405
- test_disp = np.array([1.0], dtype=np.float32)
 
 
406
 
 
407
  wrapper = SharpModelTraceable(pytorch_model)
408
  wrapper.eval()
409
 
 
 
 
 
 
 
 
 
 
410
  with torch.no_grad():
411
- pt_out = wrapper(torch.from_numpy(test_image), torch.from_numpy(test_disp))
412
 
 
413
  session = ort.InferenceSession(str(onnx_path), providers=['CPUExecutionProvider'])
414
- onnx_raw = session.run(None, {"image": test_image, "disparity_factor": test_disp})
415
 
416
  # Use same splitting logic as run_inference_pair
417
  if len(onnx_raw) == 5:
@@ -427,8 +679,14 @@ def validate_onnx_model(onnx_path, pytorch_model, input_shape=(1536, 1536), angu
427
  onnx_splits = list(onnx_raw)
428
 
429
  tolerance_config = ToleranceConfig()
430
- tolerances = tolerance_config.random_tolerances
431
- quat_validator = QuaternionValidator(angular_tolerances=angular_tolerances or tolerance_config.angular_tolerances_random)
 
 
 
 
 
 
432
 
433
  all_passed = True
434
  results = []
@@ -475,6 +733,7 @@ def main():
475
  parser = argparse.ArgumentParser(description="Convert SHARP PyTorch model to ONNX format")
476
  parser.add_argument("-c", "--checkpoint", type=Path, default=None, help="Path to PyTorch checkpoint")
477
  parser.add_argument("-o", "--output", type=Path, default=Path("sharp.onnx"), help="Output path for ONNX model")
 
478
  parser.add_argument("--height", type=int, default=1536, help="Input image height")
479
  parser.add_argument("--width", type=int, default=1536, help="Input image width")
480
  parser.add_argument("--validate", action="store_true", help="Validate ONNX model against PyTorch")
@@ -484,6 +743,8 @@ def main():
484
  parser.add_argument("--tolerance-mean", type=float, default=None, help="Custom mean angular tolerance for quaternion validation")
485
  parser.add_argument("--tolerance-p99", type=float, default=None, help="Custom p99 angular tolerance for quaternion validation")
486
  parser.add_argument("--tolerance-max", type=float, default=None, help="Custom max angular tolerance for quaternion validation")
 
 
487
 
488
  args = parser.parse_args()
489
 
@@ -496,8 +757,21 @@ def main():
496
  input_shape = (args.height, args.width)
497
 
498
  LOGGER.info(f"Converting to ONNX: {args.output}")
499
- # Always use inline data for simplicity and compatibility
500
- convert_to_onnx(predictor, args.output, input_shape=input_shape, use_external_data=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
501
  LOGGER.info(f"ONNX model saved to {args.output}")
502
 
503
  if args.validate:
@@ -519,7 +793,9 @@ def main():
519
  "p99_9": 2.0,
520
  "max": args.tolerance_max if args.tolerance_max else 15.0,
521
  }
522
- passed = validate_onnx_model(args.output, predictor, input_shape, angular_tolerances=angular_tolerances)
 
 
523
  if passed:
524
  LOGGER.info("Validation passed!")
525
  else:
 
3
  from __future__ import annotations
4
 
5
  import argparse
6
+ import copy
7
  import logging
8
  from dataclasses import dataclass
9
  from pathlib import Path
 
39
  image_tolerances: dict = None
40
  angular_tolerances_random: dict = None
41
  angular_tolerances_image: dict = None
42
+ # FP16-specific tolerances (looser due to reduced precision)
43
+ fp16_random_tolerances: dict = None
44
+ fp16_angular_tolerances_random: dict = None
45
 
46
  def __post_init__(self):
47
  if self.random_tolerances is None:
 
64
  self.angular_tolerances_random = {"mean": 0.01, "p99": 0.1, "p99_9": 1.0, "max": 10.0}
65
  if self.angular_tolerances_image is None:
66
  self.angular_tolerances_image = {"mean": 0.2, "p99": 2.0, "p99_9": 5.0, "max": 25.0}
67
+ # FP16 tolerances - much looser due to float16 precision (~3-4 decimal digits)
68
+ if self.fp16_random_tolerances is None:
69
+ self.fp16_random_tolerances = {
70
+ "mean_vectors_3d_positions": 0.1, # ~100x looser
71
+ "singular_values_scales": 0.01, # ~100x looser
72
+ "quaternions_rotations": 10.0, # ~5x looser
73
+ "colors_rgb_linear": 0.05, # ~25x looser
74
+ "opacities_alpha_channel": 0.1, # ~20x looser
75
+ }
76
+ if self.fp16_angular_tolerances_random is None:
77
+ self.fp16_angular_tolerances_random = {"mean": 1.0, "p99": 5.0, "p99_9": 15.0, "max": 45.0}
78
 
79
 
80
  class QuaternionValidator:
 
158
  return (gaussians.mean_vectors, gaussians.singular_values, quats, gaussians.colors, gaussians.opacities)
159
 
160
 
161
+ class FP16Quantizer:
162
+ """FP16 Quantizer for static quantization of SHARP model.
163
+
164
+ Converts model weights from float32 to float16 for reduced memory
165
+ footprint and faster inference while maintaining accuracy.
166
+ """
167
+
168
+ def __init__(self, model: nn.Module, input_shape: tuple = (1536, 1536)):
169
+ """Initialize FP16 quantizer.
170
+
171
+ Args:
172
+ model: The PyTorch model to quantize
173
+ input_shape: Input image shape (height, width)
174
+ """
175
+ self.model = model
176
+ self.input_shape = input_shape
177
+ self._calibration_stats = {}
178
+
179
+ def _convert_parameters_to_fp16(self, module: nn.Module) -> nn.Module:
180
+ """Recursively convert all parameters to float16."""
181
+ for name, param in module.named_parameters():
182
+ if param.dtype == torch.float32:
183
+ param.data = param.data.to(torch.float16)
184
+ for name, buffer in module.named_buffers():
185
+ if buffer.dtype == torch.float32:
186
+ buffer.data = buffer.data.to(torch.float16)
187
+ return module
188
+
189
+ def _convert_module_to_fp16(self, module: nn.Module) -> nn.Module:
190
+ """Convert a single module's parameters to float16."""
191
+ for name, param in module.named_parameters(recurse=False):
192
+ if param.dtype == torch.float32:
193
+ param.data = param.data.to(torch.float16)
194
+ for name, buffer in module.named_buffers(recurse=False):
195
+ if buffer.dtype == torch.float32:
196
+ buffer.data = buffer.data.to(torch.float16)
197
+ return module
198
+
199
+ def quantize_monodepth(self) -> nn.Module:
200
+ """Quantize monodepth model components separately."""
201
+ model = self.model
202
+ # Quantize encoder and decoder (most compute-intensive parts)
203
+ if hasattr(model, 'monodepth_model'):
204
+ mono = model.monodepth_model
205
+ # Quantize the predictor components
206
+ if hasattr(mono, 'monodepth_predictor'):
207
+ predictor = mono.monodepth_predictor
208
+ if hasattr(predictor, 'encoder'):
209
+ self._convert_module_to_fp16(predictor.encoder)
210
+ if hasattr(predictor, 'decoder'):
211
+ self._convert_module_to_fp16(predictor.decoder)
212
+ if hasattr(predictor, 'head'):
213
+ self._convert_module_to_fp16(predictor.head)
214
+ return model
215
+
216
+ def quantize_feature_model(self) -> nn.Module:
217
+ """Quantize feature model (UNet encoder)."""
218
+ model = self.model
219
+ if hasattr(model, 'feature_model'):
220
+ self._convert_module_to_fp16(model.feature_model)
221
+ return model
222
+
223
+ def quantize_init_model(self) -> nn.Module:
224
+ """Quantize initializer model."""
225
+ model = self.model
226
+ if hasattr(model, 'init_model'):
227
+ self._convert_module_to_fp16(model.init_model)
228
+ return model
229
+
230
+ def quantize_prediction_head(self) -> nn.Module:
231
+ """Quantize prediction head (Gaussian decoder)."""
232
+ model = self.model
233
+ if hasattr(model, 'prediction_head'):
234
+ self._convert_module_to_fp16(model.prediction_head)
235
+ return model
236
+
237
+ def quantize_gaussian_composer(self) -> nn.Module:
238
+ """Quantize Gaussian composer (smaller, optional for accuracy)."""
239
+ model = self.model
240
+ if hasattr(model, 'gaussian_composer'):
241
+ self._convert_module_to_fp16(model.gaussian_composer)
242
+ return model
243
+
244
+ def quantize_full_model(self) -> nn.Module:
245
+ """Quantize the entire model to FP16."""
246
+ model = copy.deepcopy(self.model)
247
+ model.eval()
248
+ return self._convert_parameters_to_fp16(model)
249
+
250
+ def calibrate(self, num_samples: int = 20) -> dict:
251
+ """Run calibration to collect statistics.
252
+
253
+ Args:
254
+ num_samples: Number of calibration samples to run
255
+
256
+ Returns:
257
+ Dictionary of calibration statistics
258
+ """
259
+ self.model.eval()
260
+ calibration_stats = {}
261
+
262
+ LOGGER.info(f"Running FP16 calibration with {num_samples} samples...")
263
+
264
+ with torch.no_grad():
265
+ for i in range(num_samples):
266
+ test_image = torch.randn(1, 3, self.input_shape[0], self.input_shape[1])
267
+ test_disp = torch.tensor([1.0])
268
+ try:
269
+ _ = self.model(test_image, test_disp)
270
+ except Exception as e:
271
+ LOGGER.warning(f"Calibration sample {i} failed: {e}")
272
+ continue
273
+
274
+ if (i + 1) % 5 == 0:
275
+ LOGGER.info(f"Calibration progress: {i + 1}/{num_samples}")
276
+
277
+ LOGGER.info("Calibration complete.")
278
+ return calibration_stats
279
+
280
+
281
+ def generate_calibration_data(num_samples: int = 20, input_shape: tuple = (1536, 1536)):
282
+ """Generate calibration data for FP16 quantization.
283
+
284
+ Args:
285
+ num_samples: Number of calibration samples to generate
286
+ input_shape: Input image shape (height, width)
287
+
288
+ Yields:
289
+ Tuples of (image_tensor, disparity_factor)
290
+ """
291
+ for _ in range(num_samples):
292
+ image = torch.randn(1, 3, input_shape[0], input_shape[1])
293
+ disparity = torch.tensor([1.0])
294
+ yield image, disparity
295
+
296
+
297
+ def convert_to_onnx_fp16(
298
+ predictor: RGBGaussianPredictor,
299
+ output_path: Path,
300
+ input_shape: tuple = (1536, 1536),
301
+ calibrate: bool = True,
302
+ calibration_samples: int = 20
303
+ ) -> Path:
304
+ """Convert SHARP model to ONNX with FP16 quantization.
305
+
306
+ Args:
307
+ predictor: The SHARP predictor model
308
+ output_path: Output path for ONNX model
309
+ input_shape: Input image shape (height, width)
310
+ calibrate: Whether to run calibration before quantization
311
+ calibration_samples: Number of calibration samples
312
+
313
+ Returns:
314
+ Path to the exported ONNX model
315
+ """
316
+ LOGGER.info("Exporting to ONNX format with FP16 quantization...")
317
+
318
+ # Remove scale_map_estimator for inference
319
+ predictor.depth_alignment.scale_map_estimator = None
320
+
321
+ # Create traceable model
322
+ model = SharpModelTraceable(predictor)
323
+ model.eval()
324
+
325
+ # Quantize to FP16
326
+ quantizer = FP16Quantizer(model, input_shape)
327
+
328
+ # Run calibration if requested
329
+ if calibrate:
330
+ cal_data = list(generate_calibration_data(calibration_samples, input_shape))
331
+ quantizer.model = model # Reset model for calibration
332
+ quantizer.calibrate(num_samples=calibration_samples)
333
+
334
+ # Convert to FP16
335
+ model_fp16 = quantizer.quantize_full_model()
336
+
337
+ # Pre-warm the quantized model (inputs must also be float16)
338
+ LOGGER.info("Pre-warming FP16 model...")
339
+ with torch.no_grad():
340
+ for _ in range(3):
341
+ _ = model_fp16(torch.randn(1, 3, input_shape[0], input_shape[1], dtype=torch.float16), torch.tensor([1.0], dtype=torch.float16))
342
+
343
+ # Clean up output files
344
+ cleanup_onnx_files(output_path)
345
+
346
+ h, w = input_shape
347
+ torch.manual_seed(42)
348
+ example_image = torch.randn(1, 3, h, w)
349
+ example_disparity = torch.tensor([1.0])
350
+
351
+ # Convert to float16 to match quantized model weights
352
+ example_image = example_image.to(torch.float16)
353
+ example_disparity = example_disparity.to(torch.float16)
354
+
355
+ LOGGER.info(f"Exporting FP16 quantized model to ONNX: {output_path}")
356
+
357
+ # Define dynamic axes
358
+ dynamic_axes = {}
359
+ for name in OUTPUT_NAMES:
360
+ dynamic_axes[name] = {0: 'batch', 1: 'num_gaussians'}
361
+
362
+ # Export to ONNX with FP16 weights
363
+ torch.onnx.export(
364
+ model_fp16,
365
+ (example_image, example_disparity),
366
+ str(output_path),
367
+ export_params=True,
368
+ verbose=False,
369
+ input_names=['image', 'disparity_factor'],
370
+ output_names=OUTPUT_NAMES,
371
+ dynamic_axes=dynamic_axes,
372
+ opset_version=15,
373
+ external_data=False, # Inline for single self-contained file
374
+ )
375
+
376
+ # Check file size
377
+ if output_path.exists():
378
+ file_size_mb = output_path.stat().st_size / (1024**2)
379
+ LOGGER.info(f"FP16 ONNX model saved: {output_path} ({file_size_mb:.2f} MB)")
380
+
381
+ LOGGER.info(f"FP16 ONNX model saved to {output_path}")
382
+ return output_path
383
+
384
+
385
  def cleanup_onnx_files(onnx_path):
386
  """Clean up ONNX model files including external data files."""
387
  try:
 
635
  return all_passed
636
 
637
 
638
+ def validate_onnx_model(onnx_path, pytorch_model, input_shape=(1536, 1536), angular_tolerances=None, input_dtype=np.float32):
639
  LOGGER.info("Validating ONNX model against PyTorch...")
640
  np.random.seed(42)
641
  torch.manual_seed(42)
642
 
643
+ # For FP16 comparison, use float16 for both PyTorch and ONNX
644
+ # For FP32 comparison, use float32
645
+ test_image_np = np.random.rand(1, 3, input_shape[0], input_shape[1]).astype(input_dtype)
646
+ test_disp_np = np.array([1.0], dtype=input_dtype)
647
 
648
+ # Create a wrapper for PyTorch model
649
  wrapper = SharpModelTraceable(pytorch_model)
650
  wrapper.eval()
651
 
652
+ # Convert wrapper to same dtype as ONNX model for fair comparison
653
+ if input_dtype == np.float16:
654
+ wrapper = wrapper.to(torch.float16)
655
+ test_image = torch.from_numpy(test_image_np).to(torch.float16)
656
+ test_disp = torch.from_numpy(test_disp_np).to(torch.float16)
657
+ else:
658
+ test_image = torch.from_numpy(test_image_np)
659
+ test_disp = torch.from_numpy(test_disp_np)
660
+
661
  with torch.no_grad():
662
+ pt_out = wrapper(test_image, test_disp)
663
 
664
+ # ONNX inference with correct dtype
665
  session = ort.InferenceSession(str(onnx_path), providers=['CPUExecutionProvider'])
666
+ onnx_raw = session.run(None, {"image": test_image_np, "disparity_factor": test_disp_np})
667
 
668
  # Use same splitting logic as run_inference_pair
669
  if len(onnx_raw) == 5:
 
679
  onnx_splits = list(onnx_raw)
680
 
681
  tolerance_config = ToleranceConfig()
682
+ # Use FP16 tolerances if validating FP16 model
683
+ if input_dtype == np.float16:
684
+ tolerances = tolerance_config.fp16_random_tolerances
685
+ quat_validator = QuaternionValidator(angular_tolerances=angular_tolerances or tolerance_config.fp16_angular_tolerances_random)
686
+ LOGGER.info("Using FP16 validation tolerances (looser due to float16 precision)")
687
+ else:
688
+ tolerances = tolerance_config.random_tolerances
689
+ quat_validator = QuaternionValidator(angular_tolerances=angular_tolerances or tolerance_config.angular_tolerances_random)
690
 
691
  all_passed = True
692
  results = []
 
733
  parser = argparse.ArgumentParser(description="Convert SHARP PyTorch model to ONNX format")
734
  parser.add_argument("-c", "--checkpoint", type=Path, default=None, help="Path to PyTorch checkpoint")
735
  parser.add_argument("-o", "--output", type=Path, default=Path("sharp.onnx"), help="Output path for ONNX model")
736
+ parser.add_argument("-q", "--quantize", type=str, default=None, choices=["fp16"], help="Quantization type (fp16 for float16)")
737
  parser.add_argument("--height", type=int, default=1536, help="Input image height")
738
  parser.add_argument("--width", type=int, default=1536, help="Input image width")
739
  parser.add_argument("--validate", action="store_true", help="Validate ONNX model against PyTorch")
 
743
  parser.add_argument("--tolerance-mean", type=float, default=None, help="Custom mean angular tolerance for quaternion validation")
744
  parser.add_argument("--tolerance-p99", type=float, default=None, help="Custom p99 angular tolerance for quaternion validation")
745
  parser.add_argument("--tolerance-max", type=float, default=None, help="Custom max angular tolerance for quaternion validation")
746
+ parser.add_argument("--calibration-samples", type=int, default=20, help="Number of calibration samples for FP16 quantization")
747
+ parser.add_argument("--no-calibration", action="store_true", help="Skip calibration step for FP16 quantization")
748
 
749
  args = parser.parse_args()
750
 
 
757
  input_shape = (args.height, args.width)
758
 
759
  LOGGER.info(f"Converting to ONNX: {args.output}")
760
+
761
+ # Handle quantization
762
+ if args.quantize == "fp16":
763
+ LOGGER.info("Using FP16 quantization...")
764
+ convert_to_onnx_fp16(
765
+ predictor,
766
+ args.output,
767
+ input_shape=input_shape,
768
+ calibrate=not args.no_calibration,
769
+ calibration_samples=args.calibration_samples
770
+ )
771
+ else:
772
+ # Standard float32 conversion
773
+ convert_to_onnx(predictor, args.output, input_shape=input_shape, use_external_data=False)
774
+
775
  LOGGER.info(f"ONNX model saved to {args.output}")
776
 
777
  if args.validate:
 
793
  "p99_9": 2.0,
794
  "max": args.tolerance_max if args.tolerance_max else 15.0,
795
  }
796
+ # Use float16 for FP16 model validation
797
+ input_dtype = np.float16 if args.quantize == "fp16" else np.float32
798
+ passed = validate_onnx_model(args.output, predictor, input_shape, angular_tolerances=angular_tolerances, input_dtype=input_dtype)
799
  if passed:
800
  LOGGER.info("Validation passed!")
801
  else: