Run this model with HF Jobs
Run pearsonkyle/Sharp-coreml on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/pearsonkyle/Sharp-coreml. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/pearsonkyle/Sharp-coreml on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use pearsonkyle/Sharp-coreml with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Sharp
How to use pearsonkyle/Sharp-coreml with Sharp:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Kyle Pearson commited on
Commit ·
027bd3d
1
Parent(s): dc95a1d
Fix dtype precision, improve depth scaling tolerance, add debug logging, update manifest weights, enhance preprocessing output.
Browse filesFiles changed (3)
20 unmodified lines21222324252663 unmodified lines9091929394959697532 unmodified lines6306316326336346352 unmodified lines6386396406416426432 unmodified lines646647648649650651652653654655295 unmodified lines9519529539549559569571 unmodified line959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994292 unmodified lines1287128812891290129112921293129412951296129720 unmodified lines# Import SHARP model componentsfrom sharp.models import PredictorParams, create_predictorfrom sharp.models.predictor import RGBGaussianPredictorLOGGER = logging.getLogger(__name__)63 unmodified linesif self.image_tolerances is None:self.image_tolerances = {"mean_vectors_3d_positions": 1.2,"singular_values_scales": 0.01,"quaternions_rotations": 5.0,"colors_rgb_linear": 0.01,"opacities_alpha_channel": 0.05,532 unmodified linesmlmodel: ct.models.MLModel,image_tensor: torch.Tensor,disparity_factor: float = 1.0,) -> tuple[list[np.ndarray], dict[str, np.ndarray]]:"""Run inference on both PyTorch and Core ML models.2 unmodified linesmlmodel: The Core ML modelimage_tensor: Input image tensordisparity_factor: Disparity factor valueReturns:Tuple of (pytorch_outputs, coreml_outputs)2 unmodified linestraceable_wrapper = SharpModelTraceable(pytorch_model)traceable_wrapper.eval()test_disparity_pt = torch.tensor([disparity_factor])with torch.no_grad():pt_outputs = traceable_wrapper(image_tensor, test_disparity_pt)# Convert to numpypt_outputs_np = [o.numpy() for o in pt_outputs]295 unmodified linesdef load_and_preprocess_image(image_path: Path,target_size: tuple[int, int] = (1536, 1536),) -> torch.Tensor:"""Load and preprocess an input image for SHARP inference.Args:1 unmodified linetarget_size: Target (height, width) for resizing.Returns:Preprocessed image tensor of shape (1, 3, H, W) in range [0, 1]."""LOGGER.info(f"Loading image from {image_path}")# Load image using PILimage = Image.open(image_path)# Convert to RGB if needed (handle grayscale or RGBA)if image.mode != "RGB":image = image.convert("RGB")original_size = image.size # (width, height)LOGGER.info(f"Original image size: {original_size}")# Resize to target size if differentif (image.width, image.height) != target_size:LOGGER.info(f"Resizing to {target_size[1]}x{target_size[0]}")image = image.resize((target_size[1], target_size[0]), Image.BILINEAR)# Convert to numpy array and normalize to [0, 1]image_np = np.array(image, dtype=np.float32) / 255.0# Transpose to (C, H, W) and add batch dimension# PIL images are (W, H, C), numpy is (H, W, C)image_np = image_np.transpose(2, 0, 1) # (3, H, W)image_tensor = torch.from_numpy(image_np).unsqueeze(0) # (1, 3, H, W)LOGGER.info(f"Preprocessed image shape: {image_tensor.shape}, range: [{image_tensor.min():.4f}, {image_tensor.max():.4f}]")return image_tensordef validate_with_image(292 unmodified linesReturns:List of validation result dictionaries."""# Load and preprocess the input imagetest_image = load_and_preprocess_image(image_path, input_shape)# Run inference on both modelspt_outputs, coreml_outputs = run_inference_pair(pytorch_model, mlmodel, test_image)# Tolerances for real image validationtolerance_config = ToleranceConfig()20 unmodified lines2122232425262763 unmodified lines9192939495969798532 unmodified lines6316326336346356366372 unmodified lines6406416426436446456462 unmodified lines649650651652653654655656657658659660661662663664665666667668295 unmodified lines9649659669679689699701 unmodified line972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011292 unmodified lines1304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135020 unmodified lines# Import SHARP model componentsfrom sharp.models import PredictorParams, create_predictorfrom sharp.models.predictor import RGBGaussianPredictorfrom sharp.utils import ioLOGGER = logging.getLogger(__name__)63 unmodified linesif self.image_tolerances is None:self.image_tolerances = {"mean_vectors_3d_positions": 3.5, # Increased to account for depth scaling with focal length"singular_values_scales": 0.035, # Increased proportionally (scales are depth-dependent)"quaternions_rotations": 5.0,"colors_rgb_linear": 0.01,"opacities_alpha_channel": 0.05,532 unmodified linesmlmodel: ct.models.MLModel,image_tensor: torch.Tensor,disparity_factor: float = 1.0,log_internals: bool = False,) -> tuple[list[np.ndarray], dict[str, np.ndarray]]:"""Run inference on both PyTorch and Core ML models.2 unmodified linesmlmodel: The Core ML modelimage_tensor: Input image tensordisparity_factor: Disparity factor valuelog_internals: Whether to log internal values for debuggingReturns:Tuple of (pytorch_outputs, coreml_outputs)2 unmodified linestraceable_wrapper = SharpModelTraceable(pytorch_model)traceable_wrapper.eval()# Ensure float32 dtype for model inferenceimage_tensor = image_tensor.float()test_disparity_pt = torch.tensor([disparity_factor], dtype=torch.float32)with torch.no_grad():pt_outputs = traceable_wrapper(image_tensor, test_disparity_pt)# Log internal values if requestedif log_internals:if hasattr(traceable_wrapper, 'last_global_scale') and traceable_wrapper.last_global_scale is not None:LOGGER.info(f"PyTorch global_scale: {traceable_wrapper.last_global_scale:.6f}")if hasattr(traceable_wrapper, 'last_monodepth_min') and traceable_wrapper.last_monodepth_min is not None:LOGGER.info(f"PyTorch monodepth_min: {traceable_wrapper.last_monodepth_min:.6f}")# Convert to numpypt_outputs_np = [o.numpy() for o in pt_outputs]295 unmodified linesdef load_and_preprocess_image(image_path: Path,target_size: tuple[int, int] = (1536, 1536),) -> tuple[torch.Tensor, float, tuple[int, int]]:"""Load and preprocess an input image for SHARP inference.Args:1 unmodified linetarget_size: Target (height, width) for resizing.Returns:Tuple of (preprocessed image tensor, focal_length_px, original_size)- Preprocessed image tensor of shape (1, 3, H, W) in range [0, 1]- Focal length in pixels (from EXIF or default)- Original image size (width, height)"""LOGGER.info(f"Loading image from {image_path}")# Use the SHARP io utilities to load image with focal lengthimage_np, original_size, f_px = io.load_rgb(image_path)LOGGER.info(f"Original image size: {original_size}, focal length: {f_px:.2f}px")# Convert to torch and normalize - ensure float32 dtype# io.load_rgb returns uint8, convert to float32 explicitlyimage_tensor = torch.from_numpy(image_np).float() / 255.0image_tensor = image_tensor.permute(2, 0, 1) # HWC -> CHWoriginal_height, original_width = image_np.shape[:2]# Resize to target size if differentif (original_width, original_height) != (target_size[1], target_size[0]):LOGGER.info(f"Resizing to {target_size[1]}x{target_size[0]}")import torch.nn.functional as Fimage_tensor = F.interpolate(image_tensor.unsqueeze(0),size=(target_size[0], target_size[1]),mode="bilinear",align_corners=True,).squeeze(0)# Add batch dimensionimage_tensor = image_tensor.unsqueeze(0) # (1, 3, H, W)LOGGER.info(f"Preprocessed image shape: {image_tensor.shape}, range: [{image_tensor.min():.4f}, {image_tensor.max():.4f}]")return image_tensor, f_px, (original_width, original_height)def validate_with_image(292 unmodified linesReturns:List of validation result dictionaries."""# Load and preprocess the input image with focal lengthtest_image, f_px, (orig_width, orig_height) = load_and_preprocess_image(image_path, input_shape)# Compute disparity_factor as focal_length / width (matching predict.py)disparity_factor = f_px / orig_widthLOGGER.info(f"Using disparity_factor = {disparity_factor:.6f} (f_px={f_px:.2f} / width={orig_width})")# Run inference on both modelspt_outputs, coreml_outputs = run_inference_pair(pytorch_model, mlmodel, test_image,disparity_factor=disparity_factor,log_internals=True)# Log depth/position statistics for debuggingpt_positions = pt_outputs[0]coreml_key = find_coreml_output_key("mean_vectors_3d_positions", coreml_outputs)coreml_positions = coreml_outputs[coreml_key]# Detailed position analysisLOGGER.info(f"=== Depth/Position Statistics ({image_path.name}) ===")LOGGER.info(f"PyTorch positions - Z range: [{pt_positions[..., 2].min():.4f}, {pt_positions[..., 2].max():.4f}], mean: {pt_positions[..., 2].mean():.4f}")LOGGER.info(f"CoreML positions - Z range: [{coreml_positions[..., 2].min():.4f}, {coreml_positions[..., 2].max():.4f}], mean: {coreml_positions[..., 2].mean():.4f}")# Analyze position differencespos_diff = np.abs(pt_positions - coreml_positions)LOGGER.info(f"Position difference (X,Y,Z) - max: [{pos_diff[..., 0].max():.6f}, {pos_diff[..., 1].max():.6f}, {pos_diff[..., 2].max():.6f}]")LOGGER.info(f"Position difference (X,Y,Z) - mean: [{pos_diff[..., 0].mean():.6f}, {pos_diff[..., 1].mean():.6f}, {pos_diff[..., 2].mean():.6f}]")# Check if error is proportional to depth (would indicate global_scale issue)z_diff = np.abs(pt_positions[..., 2] - coreml_positions[..., 2])z_ratio = z_diff / np.clip(pt_positions[..., 2], 1e-6, None)LOGGER.info(f"Z relative error - mean: {z_ratio.mean()*100:.4f}%, max: {z_ratio.max()*100:.4f}%")# Log scales for comparisonpt_scales = pt_outputs[1]coreml_scales_key = find_coreml_output_key("singular_values_scales", coreml_outputs)coreml_scales = coreml_outputs[coreml_scales_key]scales_diff = np.abs(pt_scales - coreml_scales)scales_ratio = scales_diff / np.clip(pt_scales, 1e-6, None)LOGGER.info(f"Scales relative error - mean: {scales_ratio.mean()*100:.4f}%, max: {scales_ratio.max()*100:.4f}%")# Tolerances for real image validationtolerance_config = ToleranceConfig()
123version https://git-lfs.github.com/spec/v1oid sha256:3e9fd96f088b6d324250226cfcbe7e197b735dbb9322687c177b4c2a8377fb51size 938769123version https://git-lfs.github.com/spec/v1oid sha256:6e2b156a2a72ad6f86da86b9100b13007b0d343bbd654fba8d65bee66553f2f1size 938769
123456789101112131415161718{"fileFormatVersion": "1.0.0","itemInfoEntries": {"551E6A6B-AAB8-4DA8-B1D0-2D3A73254AD2": {"author": "com.apple.CoreML","description": "CoreML Model Specification","name": "model.mlmodel","path": "com.apple.CoreML/model.mlmodel"},"DD041C71-3C41-47F0-830E-A829C8EEC1EA": {"author": "com.apple.CoreML","description": "CoreML Model Weights","name": "weights","path": "com.apple.CoreML/weights"}},"rootModelIdentifier": "551E6A6B-AAB8-4DA8-B1D0-2D3A73254AD2"}123456789101112131415161718{"fileFormatVersion": "1.0.0","itemInfoEntries": {"655381FB-8159-4BD7-A64E-7B14F30B787E": {"author": "com.apple.CoreML","description": "CoreML Model Weights","name": "weights","path": "com.apple.CoreML/weights"},"A0921877-4847-4CCE-937D-414310330106": {"author": "com.apple.CoreML","description": "CoreML Model Specification","name": "model.mlmodel","path": "com.apple.CoreML/model.mlmodel"}},"rootModelIdentifier": "A0921877-4847-4CCE-937D-414310330106"}
convert.py+79-26
sharp.mlpackage/Data/com.apple.CoreML/model.mlmodel+1-1
sharp.mlpackage/Manifest.json+8-8