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 ·
dc95a1d
1
Parent(s): cfcc093
Add validation utilities, update model conversion logic, fix manifest.json, rename deprecated flags, improve docs
Browse filesFiles changed (4)
62 unmodified lines6364656667686962 unmodified linesswiftc -O -o run_sharp sharp.swift -framework CoreML -framework CoreImage -framework AppKit# Run inference on an image and decimate the output by 50%./run_sharp sharp.mlpackage city.png city.ply -d 0.5```> Inference on an Apple M4 Max takes ~1.9 seconds.62 unmodified lines6364656667686962 unmodified linesswiftc -O -o run_sharp sharp.swift -framework CoreML -framework CoreImage -framework AppKit# Run inference on an image and decimate the output by 50%./run_sharp sharp.mlpackage test.png test.ply -d 0.5```> Inference on an Apple M4 Max takes ~1.9 seconds.
7 unmodified lines891011121311 unmodified lines2526272829303132333435363738394041424317 unmodified lines6162636465666768697024 unmodified lines9596979899100101102103104105106251 unmodified lines358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499158 unmodified lines658659660661662663558 unmodified lines12221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310158 unmodified lines1469147014711472147314741475147614771478147942 unmodified lines15221523152415251526152715281529153015311532153315341535153615371538153915401541154227 unmodified lines1570157115727 unmodified linesimport argparseimport loggingfrom pathlib import Pathfrom typing import Any11 unmodified linesDEFAULT_MODEL_URL = "https://ml-site.cdn-apple.com/models/sharp/sharp_2572gikvuh.pt"class SafeClamp(nn.Module):"""Safe clamp operation that avoids tracing issues."""def forward(self, x, min_val=1e-4, max_val=1e4):return torch.clamp(x, min=min_val, max=max_val)class SafeDivision(nn.Module):"""Safe division that avoids division by zero."""def forward(self, numerator, denominator):return numerator / torch.clamp(denominator, min=1e-8)class SharpModelTraceable(nn.Module):17 unmodified linesself.prediction_head = predictor.prediction_headself.gaussian_composer = predictor.gaussian_composerself.depth_alignment = predictor.depth_alignment# Replace problematic operations with custom modulesself.safe_clamp = SafeClamp()self.safe_div = SafeDivision()def forward(self,24 unmodified lines# Apply depth alignment (inference mode)monodepth, _ = self.depth_alignment(monodepth, None, monodepth_output.decoder_features)# Initialize gaussiansinit_output = self.init_model(image, monodepth)# Store global_scale for debugging if in eval mode (not during tracing)if hasattr(self, '_store_global_scale'):self._stored_global_scale = init_output.global_scale# Extract featuresimage_features = self.feature_model(251 unmodified linesreturn mlmodeldef convert_to_coreml_with_preprocessing(predictor: RGBGaussianPredictor,output_path: Path,input_shape: tuple[int, int] = (1536, 1536),) -> ct.models.MLModel:"""Convert SHARP model to Core ML with built-in image preprocessing.This version includes image normalization as part of the model,accepting uint8 images as input.Args:predictor: The SHARP RGBGaussianPredictor model.output_path: Path to save the .mlmodel file.input_shape: Input image shape (height, width).Returns:The converted Core ML model."""class SharpWithPreprocessing(nn.Module):"""SHARP model with integrated preprocessing."""def __init__(self, base_model: SharpModelTraceable):super().__init__()self.base_model = base_modeldef forward(self,image: torch.Tensor,disparity_factor: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:# Normalize image from [0, 255] to [0, 1]image_normalized = image / 255.0return self.base_model(image_normalized, disparity_factor)model_wrapper = SharpWithPreprocessing(SharpModelTraceable(predictor))model_wrapper.eval()height, width = input_shapeexample_image = torch.randint(0, 256, (1, 3, height, width), dtype=torch.float32)example_disparity_factor = torch.tensor([1.0])LOGGER.info("Tracing model with preprocessing...")with torch.no_grad():traced_model = torch.jit.trace(model_wrapper,(example_image, example_disparity_factor),strict=False,)inputs = [ct.ImageType(name="image",shape=(1, 3, height, width),scale=1.0, # Will be normalized in the modelcolor_layout=ct.colorlayout.RGB,),ct.TensorType(name="disparity_factor",shape=(1,),dtype=np.float32,),]# Define output names with clear, descriptive labelsoutput_names = ["mean_vectors_3d_positions", # 3D positions (NDC space)"singular_values_scales", # Scale parameters (diagonal of covariance)"quaternions_rotations", # Rotation as quaternions"colors_rgb_linear", # RGB colors in linear color space"opacities_alpha_channel", # Opacity values (alpha)]# Define outputs with proper names for Core ML conversionoutputs = [ct.TensorType(name=output_names[0], dtype=np.float32),ct.TensorType(name=output_names[1], dtype=np.float32),ct.TensorType(name=output_names[2], dtype=np.float32),ct.TensorType(name=output_names[3], dtype=np.float32),ct.TensorType(name=output_names[4], dtype=np.float32),]mlmodel = ct.convert(traced_model,inputs=inputs,outputs=outputs, # Specify output names during conversionconvert_to="mlprogram",compute_precision=ct.precision.FLOAT16,)mlmodel.author = "Apple Inc."mlmodel.short_description = "SHARP model with integrated image preprocessing"mlmodel.version = "1.0.0"# Output descriptions with clear intent and unitsoutput_descriptions = {"mean_vectors_3d_positions": ("3D positions of Gaussian splats in normalized device coordinates (NDC). ""Shape: (1, N, 3), where N is the number of Gaussians."),"singular_values_scales": ("Scale factors for each Gaussian along its principal axes. ""Represents size and anisotropy. Shape: (1, N, 3)."),"quaternions_rotations": ("Rotation of each Gaussian as a unit quaternion [w, x, y, z]. ""Used to orient the ellipsoid. Shape: (1, N, 4)."),"colors_rgb_linear": ("RGB color values in linear RGB space (not gamma-corrected). ""Shape: (1, N, 3), with range [0, 1]."),"opacities_alpha_channel": ("Opacity value per Gaussian (alpha channel), used for blending. ""Shape: (1, N), where values are in [0, 1]."),}# Update output names and descriptions via spec BEFORE savingspec = mlmodel.get_spec()# Set output descriptionsfor i, name in enumerate(output_names):if i < len(spec.description.output):output = spec.description.output[i]output.name = nameoutput.shortDescription = output_descriptions[name]LOGGER.info("Output names after update: %s", [o.name for o in spec.description.output])# Save the model with correct namesmlmodel.save(str(output_path))return mlmodelclass QuaternionValidator:"""Validator for quaternion comparisons with configurable tolerances and outlier analysis."""158 unmodified lines}def format_validation_table(validation_results: list[dict],image_name: str,558 unmodified lines"""# Load and preprocess the input imagetest_image = load_and_preprocess_image(image_path, input_shape)test_disparity = np.array([1.0], dtype=np.float32)# Run PyTorch modeltraceable_wrapper = SharpModelTraceable(pytorch_model)traceable_wrapper.eval()with torch.no_grad():pt_outputs = traceable_wrapper(test_image, torch.from_numpy(test_disparity))# Run Core ML modeltest_image_np = test_image.numpy()coreml_inputs = {"image": test_image_np,"disparity_factor": test_disparity,}coreml_outputs = mlmodel.predict(coreml_inputs)# Output configurationoutput_names = ["mean_vectors_3d_positions", "singular_values_scales", "quaternions_rotations", "colors_rgb_linear", "opacities_alpha_channel"]# Tolerances for real image validationtolerances = {"mean_vectors_3d_positions": 1.2,"singular_values_scales": 0.01,"colors_rgb_linear": 0.01,"opacities_alpha_channel": 0.05,"quaternions_rotations": 5.0,}# Use provided validator or create defaultif quat_validator is None:quat_validator = QuaternionValidator()# Collect validation resultsvalidation_results = []for i, name in enumerate(output_names):pt_output = pt_outputs[i].numpy()# Find matching Core ML outputcoreml_key = Noneif name in coreml_outputs:coreml_key = nameelse:for key in coreml_outputs:base_name = name.split('_')[0]if base_name in key.lower():coreml_key = keybreakif coreml_key is None:coreml_key = list(coreml_outputs.keys())[i]coreml_output = coreml_outputs[coreml_key]result = {"output": name, "passed": True, "failure_reason": ""}if name == "quaternions_rotations":# Use QuaternionValidatorquat_result = quat_validator.validate(pt_output, coreml_output, image_name=image_path.name)result.update({"max_diff": f"{quat_result['stats']['max']:.6f}","mean_diff": f"{quat_result['stats']['mean']:.6f}","p99_diff": f"{quat_result['stats']['p99']:.6f}","passed": quat_result["passed"],"failure_reason": "; ".join(quat_result["failure_reasons"]) if quat_result["failure_reasons"] else "",})else:diff = np.abs(pt_output - coreml_output)output_tolerance = tolerances.get(name, 0.01)max_diff = np.max(diff)result.update({"max_diff": f"{max_diff:.6f}","mean_diff": f"{np.mean(diff):.6f}","p99_diff": f"{np.percentile(diff, 99):.6f}",})if max_diff > output_tolerance:result["passed"] = Falseresult["failure_reason"] = f"max diff {max_diff:.6f} > tolerance {output_tolerance:.6f}"validation_results.append(result)return validation_results158 unmodified linesaction="store_true",help="Validate Core ML model against PyTorch",)parser.add_argument("--with-preprocessing",action="store_true",help="Include image preprocessing (uint8 -> float normalization)",)parser.add_argument("-v", "--verbose",action="store_true",42 unmodified linesprecision = ct.precision.FLOAT16 if args.precision == "float16" else ct.precision.FLOAT32# Convert to Core MLif args.with_preprocessing:LOGGER.info("Converting with integrated preprocessing...")mlmodel = convert_to_coreml_with_preprocessing(predictor,args.output,input_shape=input_shape,)else:LOGGER.info("Converting using direct tracing...")mlmodel = convert_to_coreml(predictor,args.output,input_shape=input_shape,compute_precision=precision,)LOGGER.info(f"Core ML model saved to {args.output}")27 unmodified linesif __name__ == "__main__":exit(main())7 unmodified lines89101112131411 unmodified lines262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611717 unmodified lines13513613713813914014114214314424 unmodified lines169170171172173174175176177178179180181182183184185251 unmodified lines437438439440441442158 unmodified lines601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730558 unmodified lines12891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317158 unmodified lines14761477147814791480148142 unmodified lines152415251526152715281529153015311532153315341535153627 unmodified lines15641565156615677 unmodified linesimport argparseimport loggingfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any11 unmodified linesDEFAULT_MODEL_URL = "https://ml-site.cdn-apple.com/models/sharp/sharp_2572gikvuh.pt"# ============================================================================# Constants & Configuration# ============================================================================# Output names for Core ML modelOUTPUT_NAMES = ["mean_vectors_3d_positions","singular_values_scales","quaternions_rotations","colors_rgb_linear","opacities_alpha_channel",]# Output descriptions for Core ML metadataOUTPUT_DESCRIPTIONS = {"mean_vectors_3d_positions": ("3D positions of Gaussian splats in normalized device coordinates (NDC). ""Shape: (1, N, 3), where N is the number of Gaussians."),"singular_values_scales": ("Scale factors for each Gaussian along its principal axes. ""Represents size and anisotropy. Shape: (1, N, 3)."),"quaternions_rotations": ("Rotation of each Gaussian as a unit quaternion [w, x, y, z]. ""Used to orient the ellipsoid. Shape: (1, N, 4)."),"colors_rgb_linear": ("RGB color values in linear RGB space (not gamma-corrected). ""Shape: (1, N, 3), with range [0, 1]."),"opacities_alpha_channel": ("Opacity value per Gaussian (alpha channel), used for blending. ""Shape: (1, N), where values are in [0, 1]."),}@dataclassclass ToleranceConfig:"""Tolerance configuration for validation."""# Tolerances for random validation (tight)random_tolerances: dict[str, float] = None# Tolerances for real image validation (more lenient)image_tolerances: dict[str, float] = None# Angular tolerances for quaternions (in degrees)angular_tolerances_random: dict[str, float] = Noneangular_tolerances_image: dict[str, float] = Nonedef __post_init__(self):if self.random_tolerances is None:self.random_tolerances = {"mean_vectors_3d_positions": 0.001,"singular_values_scales": 0.0001,"quaternions_rotations": 2.0,"colors_rgb_linear": 0.002,"opacities_alpha_channel": 0.005,}if 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,}if self.angular_tolerances_random is None:self.angular_tolerances_random = {"mean": 0.01,"p99": 0.1,"p99_9": 1.0,"max": 5.0,}if self.angular_tolerances_image is None:self.angular_tolerances_image = {"mean": 0.2,"p99": 2.0,"p99_9": 5.0,"max": 25.0,}class SharpModelTraceable(nn.Module):17 unmodified linesself.prediction_head = predictor.prediction_headself.gaussian_composer = predictor.gaussian_composerself.depth_alignment = predictor.depth_alignment# For debugging: store global_scaleself.last_global_scale = Noneself.last_monodepth_min = Nonedef forward(self,24 unmodified lines# Apply depth alignment (inference mode)monodepth, _ = self.depth_alignment(monodepth, None, monodepth_output.decoder_features)# Store monodepth min for debugging (before normalization)if not torch.jit.is_scripting() and not torch.jit.is_tracing():self.last_monodepth_min = monodepth.flatten().min().item()# Initialize gaussiansinit_output = self.init_model(image, monodepth)# Store global_scale for debuggingif not torch.jit.is_scripting() and not torch.jit.is_tracing():if init_output.global_scale is not None:self.last_global_scale = init_output.global_scale.item()# Extract featuresimage_features = self.feature_model(251 unmodified linesreturn mlmodelclass QuaternionValidator:"""Validator for quaternion comparisons with configurable tolerances and outlier analysis."""158 unmodified lines}def find_coreml_output_key(name: str, coreml_outputs: dict) -> str:"""Find matching Core ML output key for a given output name.Args:name: The expected output namecoreml_outputs: Dictionary of Core ML outputsReturns:The matching key from coreml_outputs"""if name in coreml_outputs:return name# Try partial matchfor key in coreml_outputs:base_name = name.split('_')[0]if base_name in key.lower():return key# Fallback to index-based lookupoutput_index = OUTPUT_NAMES.index(name) if name in OUTPUT_NAMES else 0return list(coreml_outputs.keys())[output_index]def run_inference_pair(pytorch_model: RGBGaussianPredictor,mlmodel: 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.Args:pytorch_model: The PyTorch modelmlmodel: The Core ML modelimage_tensor: Input image tensordisparity_factor: Disparity factor valueReturns:Tuple of (pytorch_outputs, coreml_outputs)"""# Run PyTorch modeltraceable_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]# Run Core ML modeltest_image_np = image_tensor.numpy()test_disparity_np = np.array([disparity_factor], dtype=np.float32)coreml_inputs = {"image": test_image_np,"disparity_factor": test_disparity_np,}coreml_outputs = mlmodel.predict(coreml_inputs)return pt_outputs_np, coreml_outputsdef compare_outputs(pt_outputs: list[np.ndarray],coreml_outputs: dict[str, np.ndarray],tolerances: dict[str, float],quat_validator: QuaternionValidator,image_name: str = "Unknown",) -> list[dict]:"""Compare PyTorch and Core ML outputs.Args:pt_outputs: List of PyTorch outputscoreml_outputs: Dictionary of Core ML outputstolerances: Tolerance values per output typequat_validator: QuaternionValidator instanceimage_name: Name of the image being validatedReturns:List of validation result dictionaries"""validation_results = []for i, name in enumerate(OUTPUT_NAMES):pt_output = pt_outputs[i]coreml_key = find_coreml_output_key(name, coreml_outputs)coreml_output = coreml_outputs[coreml_key]result = {"output": name, "passed": True, "failure_reason": ""}if name == "quaternions_rotations":# Use QuaternionValidator for quaternionsquat_result = quat_validator.validate(pt_output, coreml_output, image_name=image_name)result.update({"max_diff": f"{quat_result['stats']['max']:.6f}","mean_diff": f"{quat_result['stats']['mean']:.6f}","p99_diff": f"{quat_result['stats']['p99']:.6f}","passed": quat_result["passed"],"failure_reason": "; ".join(quat_result["failure_reasons"]) if quat_result["failure_reasons"] else "",})else:# Standard numerical comparisondiff = np.abs(pt_output - coreml_output)output_tolerance = tolerances.get(name, 0.01)max_diff = np.max(diff)result.update({"max_diff": f"{max_diff:.6f}","mean_diff": f"{np.mean(diff):.6f}","p99_diff": f"{np.percentile(diff, 99):.6f}",})if max_diff > output_tolerance:result["passed"] = Falseresult["failure_reason"] = f"max diff {max_diff:.6f} > tolerance {output_tolerance:.6f}"validation_results.append(result)return validation_resultsdef format_validation_table(validation_results: list[dict],image_name: str,558 unmodified lines"""# 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()tolerances = tolerance_config.image_tolerances# Use provided validator or create default with image tolerancesif quat_validator is None:quat_validator = QuaternionValidator(angular_tolerances=tolerance_config.angular_tolerances_image)# Compare outputsvalidation_results = compare_outputs(pt_outputs,coreml_outputs,tolerances,quat_validator,image_name=image_path.name)return validation_results158 unmodified linesaction="store_true",help="Validate Core ML model against PyTorch",)parser.add_argument("-v", "--verbose",action="store_true",42 unmodified linesprecision = ct.precision.FLOAT16 if args.precision == "float16" else ct.precision.FLOAT32# Convert to Core MLLOGGER.info("Converting using direct tracing...")mlmodel = convert_to_coreml(predictor,args.output,input_shape=input_shape,compute_precision=precision,)LOGGER.info(f"Core ML model saved to {args.output}")27 unmodified linesif __name__ == "__main__":exit(main())exit(main())
123version https://git-lfs.github.com/spec/v1oid sha256:ca2a548947bdf1616a9c7ddf093c27dc0aeb8225a1e50cb40eb098d7aa47a2b5size 938769123version https://git-lfs.github.com/spec/v1oid sha256:3e9fd96f088b6d324250226cfcbe7e197b735dbb9322687c177b4c2a8377fb51size 938769
123456789101112131415161718{"fileFormatVersion": "1.0.0","itemInfoEntries": {"1504890B-E584-4EC2-A1CF-F87AE1A1BAA0": {"author": "com.apple.CoreML","description": "CoreML Model Weights","name": "weights","path": "com.apple.CoreML/weights"},"D59C5780-FA59-423A-8088-BCF64225C1B3": {"author": "com.apple.CoreML","description": "CoreML Model Specification","name": "model.mlmodel","path": "com.apple.CoreML/model.mlmodel"}},"rootModelIdentifier": "D59C5780-FA59-423A-8088-BCF64225C1B3"}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"}
README.md+1-1
convert.py+252-257
sharp.mlpackage/Data/com.apple.CoreML/model.mlmodel+1-1
sharp.mlpackage/Manifest.json+8-8