pratikgx commited on
Commit
db009bf
·
verified ·
1 Parent(s): 113e01c

Add unofficial 4-bit MLX conversion of Apple Depth Pro 2 (L and H+)

Browse files
.gitattributes CHANGED
@@ -1,35 +1 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  *.safetensors filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
H/config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "depth-pro-2-mlx-4bit",
3
+ "size": "H+",
4
+ "preset": "depthpro2-h",
5
+ "original_repo": "apple/DepthPro2-H",
6
+ "focal_repo": "apple/DepthPro2-focal",
7
+ "library": "depth_pro_2_mlx",
8
+ "library_version": "0.1.0",
9
+ "mlx_version": "0.32.4",
10
+ "precision_unquantized": "bf16",
11
+ "head_precision": "fp32",
12
+ "quantization": {
13
+ "bits": 4,
14
+ "group_size": 64,
15
+ "mode": "affine",
16
+ "applied_to": "encoder nn.Linear layers whose in_features is divisible by group_size",
17
+ "skipped": [
18
+ "LayerNorm",
19
+ "embeddings (cls_token, reg_token)",
20
+ "Conv2d / ConvTranspose2d (patch embed, reassemble, DPT decoder)",
21
+ "inverse-depth head (kept fp32)",
22
+ "FOV estimator (kept bf16/fp32; included in this bundle for a one-folder load)"
23
+ ]
24
+ },
25
+ "conversion": "Unofficial community 4-bit MLX conversion of Apple Depth Pro 2. Model derivative.",
26
+ "weight_bytes": 589911729,
27
+ "original_weight_bytes": 3488493012,
28
+ "encoder_quantized_linear": 160,
29
+ "encoder_linear_before": 160
30
+ }
H/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6702e487a3f7e4bd729b58c6d21bcb18e3a68fdd228cbb7f8fc6180c8ad873df
3
+ size 589911729
L/config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "depth-pro-2-mlx-4bit",
3
+ "size": "L",
4
+ "preset": "depthpro2-l",
5
+ "original_repo": "apple/DepthPro2-L",
6
+ "focal_repo": "apple/DepthPro2-focal",
7
+ "library": "depth_pro_2_mlx",
8
+ "library_version": "0.1.0",
9
+ "mlx_version": "0.32.4",
10
+ "precision_unquantized": "bf16",
11
+ "head_precision": "fp32",
12
+ "quantization": {
13
+ "bits": 4,
14
+ "group_size": 64,
15
+ "mode": "affine",
16
+ "applied_to": "encoder nn.Linear layers whose in_features is divisible by group_size",
17
+ "skipped": [
18
+ "LayerNorm",
19
+ "embeddings (cls_token, reg_token)",
20
+ "Conv2d / ConvTranspose2d (patch embed, reassemble, DPT decoder)",
21
+ "inverse-depth head (kept fp32)",
22
+ "FOV estimator (kept bf16/fp32; included in this bundle for a one-folder load)"
23
+ ]
24
+ },
25
+ "conversion": "Unofficial community 4-bit MLX conversion of Apple Depth Pro 2. Model derivative.",
26
+ "weight_bytes": 285331193,
27
+ "original_weight_bytes": 1335873268,
28
+ "encoder_quantized_linear": 96,
29
+ "encoder_linear_before": 96
30
+ }
L/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dd5a7d574af2fa734b0b1fd83374536aa3865de00d80239e414c8a481f808494
3
+ size 285331193
LICENSE ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Disclaimer: IMPORTANT: This Apple Machine Learning Research Model is
2
+ specifically developed and released by Apple Inc. ("Apple") for the sole purpose
3
+ of scientific research of artificial intelligence and machine-learning
4
+ technology. “Apple Machine Learning Research Model” means the model, including
5
+ but not limited to algorithms, formulas, trained model weights, parameters,
6
+ configurations, checkpoints, and any related materials (including
7
+ documentation).
8
+
9
+ This Apple Machine Learning Research Model is provided to You by
10
+ Apple in consideration of your agreement to the following terms, and your use,
11
+ modification, creation of Model Derivatives, and or redistribution of the Apple
12
+ Machine Learning Research Model constitutes acceptance of this Agreement. If You
13
+ do not agree with these terms, please do not use, modify, create Model
14
+ Derivatives of, or distribute this Apple Machine Learning Research Model or
15
+ Model Derivatives.
16
+
17
+ * License Scope: In consideration of your agreement to abide by the following
18
+ terms, and subject to these terms, Apple hereby grants you a personal,
19
+ non-exclusive, worldwide, non-transferable, royalty-free, revocable, and
20
+ limited license, to use, copy, modify, distribute, and create Model
21
+ Derivatives (defined below) of the Apple Machine Learning Research Model
22
+ exclusively for Research Purposes. You agree that any Model Derivatives You
23
+ may create or that may be created for You will be limited to Research Purposes
24
+ as well. “Research Purposes” means non-commercial scientific research and
25
+ academic development activities, such as experimentation, analysis, testing
26
+ conducted by You with the sole intent to advance scientific knowledge and
27
+ research. “Research Purposes” does not include any commercial exploitation,
28
+ product development or use in any commercial product or service.
29
+
30
+ * Distribution of Apple Machine Learning Research Model and Model Derivatives:
31
+ If you choose to redistribute Apple Machine Learning Research Model or its
32
+ Model Derivatives, you must provide a copy of this Agreement to such third
33
+ party, and ensure that the following attribution notice be provided: “Apple
34
+ Machine Learning Research Model is licensed under the Apple Machine Learning
35
+ Research Model License Agreement.” Additionally, all Model Derivatives must
36
+ clearly be identified as such, including disclosure of modifications and
37
+ changes made to the Apple Machine Learning Research Model. The name,
38
+ trademarks, service marks or logos of Apple may not be used to endorse or
39
+ promote Model Derivatives or the relationship between You and Apple. “Model
40
+ Derivatives” means any models or any other artifacts created by modifications,
41
+ improvements, adaptations, alterations to the architecture, algorithm or
42
+ training processes of the Apple Machine Learning Research Model, or by any
43
+ retraining, fine-tuning of the Apple Machine Learning Research Model.
44
+
45
+ * No Other License: Except as expressly stated in this notice, no other rights
46
+ or licenses, express or implied, are granted by Apple herein, including but
47
+ not limited to any patent, trademark, and similar intellectual property rights
48
+ worldwide that may be infringed by the Apple Machine Learning Research Model,
49
+ the Model Derivatives or by other works in which the Apple Machine Learning
50
+ Research Model may be incorporated.
51
+
52
+ * Compliance with Laws: Your use of Apple Machine Learning Research Model must
53
+ be in compliance with all applicable laws and regulations.
54
+
55
+ * Term and Termination: The term of this Agreement will begin upon your
56
+ acceptance of this Agreement or use of the Apple Machine Learning Research
57
+ Model and will continue until terminated in accordance with the following
58
+ terms. Apple may terminate this Agreement at any time if You are in breach of
59
+ any term or condition of this Agreement. Upon termination of this Agreement,
60
+ You must cease to use all Apple Machine Learning Research Models and Model
61
+ Derivatives and permanently delete any copy thereof. Sections 3, 6 and 7 will
62
+ survive termination.
63
+
64
+ * Disclaimer and Limitation of Liability: This Apple Machine Learning Research
65
+ Model and any outputs generated by the Apple Machine Learning Research Model
66
+ are provided on an “AS IS” basis. APPLE MAKES NO WARRANTIES, EXPRESS OR
67
+ IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF
68
+ NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE,
69
+ REGARDING THE APPLE MACHINE LEARNING RESEARCH MODEL OR OUTPUTS GENERATED BY
70
+ THE APPLE MACHINE LEARNING RESEARCH MODEL. You are solely responsible for
71
+ determining the appropriateness of using or redistributing the Apple Machine
72
+ Learning Research Model and any outputs of the Apple Machine Learning Research
73
+ Model and assume any risks associated with Your use of the Apple Machine
74
+ Learning Research Model and any output and results. IN NO EVENT SHALL APPLE BE
75
+ LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
76
+ IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF
77
+ THE APPLE MACHINE LEARNING RESEARCH MODEL AND ANY OUTPUTS OF THE APPLE MACHINE
78
+ LEARNING RESEARCH MODEL, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT,
79
+ TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS
80
+ BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
81
+
82
+ * Governing Law: This Agreement will be governed by and construed under the laws
83
+ of the State of California without regard to its choice of law principles. The
84
+ Convention on Contracts for the International Sale of Goods shall not apply to
85
+ the Agreement except that the arbitration clause and any arbitration hereunder
86
+ shall be governed by the Federal Arbitration Act, Chapters 1 and 2.
87
+
88
+ Copyright (C) 2026 Apple Inc. All Rights Reserved.
README.md ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: apple-amlr
4
+ license_link: LICENSE
5
+ pipeline_tag: depth-estimation
6
+ library_name: mlx
7
+ base_model:
8
+ - apple/DepthPro2-L
9
+ - apple/DepthPro2-H
10
+ - apple/DepthPro2-focal
11
+ tags:
12
+ - depth-estimation
13
+ - metric-depth
14
+ - monocular-depth
15
+ - mlx
16
+ - 4-bit
17
+ - quantized
18
+ ---
19
+
20
+ # Depth Pro 2 MLX 4-bit (unofficial)
21
+
22
+ This is an **unofficial community Model Derivative**: a 4-bit [MLX](https://github.com/ml-explore/mlx) conversion of [Apple Depth Pro 2](https://huggingface.co/apple/DepthPro2), Apple's metric monocular depth model. It is not an Apple product, and Apple does not endorse it.
23
+
24
+ Original weights and research release: [apple/DepthPro2](https://huggingface.co/apple/DepthPro2), [apple/DepthPro2-L](https://huggingface.co/apple/DepthPro2-L), [apple/DepthPro2-H](https://huggingface.co/apple/DepthPro2-H), and the shared focal-length estimator [apple/DepthPro2-focal](https://huggingface.co/apple/DepthPro2-focal). Upstream code: [apple-aiml-research/ml-depth-pro-2](https://github.com/apple-aiml-research/ml-depth-pro-2).
25
+
26
+ **Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement.** This conversion is a Model Derivative and is for **research use only** (non-commercial scientific research and academic development). See [LICENSE](LICENSE).
27
+
28
+ The MLX port this conversion was built with (`depth_pro_2_mlx` 0.1.0, on MLX 0.32.4) was built by [@SpaceXSI](https://x.com/SpaceXSI) with a coding agent.
29
+
30
+ ## What's in this repo
31
+
32
+ Only the sizes that met the inclusion bar below are uploaded.
33
+
34
+ | Folder | Size | Original repo | 4-bit bundle | Official Apple download |
35
+ |---|---|---|---:|---:|
36
+ | `L/` | L (334M) | [apple/DepthPro2-L](https://huggingface.co/apple/DepthPro2-L) | 272.1 MiB | 1,274.0 MiB |
37
+ | `H/` | H+ (872M) | [apple/DepthPro2-H](https://huggingface.co/apple/DepthPro2-H) | 562.6 MiB | 3,326.9 MiB |
38
+
39
+ Each folder contains `model.safetensors` and `config.json`. The bundle includes the encoder (4-bit), the DPT decoder (BF16), the inverse-depth head (FP32), and the shared FOV estimator (BF16 trunk, FP32 head) so a size can be loaded from one folder. `load_4bit.py` is at the repo root.
40
+
41
+ ## How it was converted
42
+
43
+ This is a weight-only conversion. There was no retraining or fine-tuning.
44
+
45
+ - MLX affine quantization, 4 bits, group size 64, applied to the encoder's `nn.Linear` layers.
46
+ - Kept at higher precision: LayerNorms; class and register-token embeddings; all `Conv2d` / `ConvTranspose2d` layers (patch embedding, reassemble, DPT decoder; MLX does not quantize convs this way); the inverse-depth head (FP32, as in the MLX port); and the FOV estimator (BF16/FP32), both for stability and because some FOV linear widths are not divisible by 64.
47
+ - Conv weights are stored in the MLX NHWC layout used by the port.
48
+
49
+ S and B were converted with the same recipe and checked, but they did not meet the inclusion bar and are not in this repo. For those sizes, use the original Apple weights with the MLX port in BF16.
50
+
51
+ ## Accuracy
52
+
53
+ Measured on a 64GB M5 Pro Mac mini. The inclusion bar was: **no NaNs**, and inverse-depth **Pearson r ≥ 0.999** against the Phase 1 PyTorch MPS BF16 reference (`.npz` from Apple's official `assets/example.jpg` at native 1920×1440). MLX BF16 numbers are from the same photo and the same references, for comparison.
54
+
55
+ Focal length is estimated by the FOV head, which was **not** quantized. The 0.581 px difference versus the PyTorch reference is the same as MLX BF16.
56
+
57
+ ### Official photo (1920×1440) vs Phase 1 reference
58
+
59
+ | Size | Uploaded | 4-bit Pearson r | BF16 Pearson r | 4-bit median rel. error | BF16 median rel. error | 4-bit NaNs | FOV error vs ref (px) |
60
+ |---|---|---:|---:|---:|---:|---:|---:|
61
+ | S | no | 0.99499 | 0.99996 | 0.0489 | 0.00336 | 0 | 0.581 |
62
+ | B | no | 0.99653 | 0.99998 | 0.1552 | 0.00217 | 0 | 0.581 |
63
+ | L | yes | 0.99959 | 0.99999 | 0.0123 | 0.00204 | 0 | 0.581 |
64
+ | H+ | yes | 0.99986 | 1.00000 | 0.0311 | 0.00230 | 0 | 0.581 |
65
+
66
+ ![4-bit vs BF16 parity](assets/mlx_4bit_vs_bf16_parity.png)
67
+
68
+ ### 1280×720 cover-crop, 4-bit vs same-session MLX BF16
69
+
70
+ There is no Phase 1 720p reference file. This comparison uses the same cover-crop of `example.jpg` that the Phase 1/2 speed tests used (first frame, no pan), and compares 4-bit inverse depth to a same-session MLX BF16 run.
71
+
72
+ | Size | 4-bit vs BF16 Pearson r | 4-bit vs BF16 median rel. error | 4-bit NaNs |
73
+ |---|---:|---:|---:|
74
+ | S | 0.99421 | 0.0446 | 0 |
75
+ | B | 0.99714 | 0.1569 | 0 |
76
+ | L | 0.99897 | 0.0416 | 0 |
77
+ | H+ | 0.99973 | 0.0405 | 0 |
78
+
79
+ Load memory, informational only (Metal peak after loading the 4-bit bundle, not a speed test): L 282.8 MiB, H+ 576.2 MiB.
80
+
81
+ ## How to run it
82
+
83
+ Install the community MLX port (`depth_pro_2_mlx` 0.1.0) and MLX 0.32.4 or later, then:
84
+
85
+ ```python
86
+ from pathlib import Path
87
+ from huggingface_hub import snapshot_download
88
+ from depth_pro_2_mlx import load_rgb, to_normalized
89
+
90
+ repo = snapshot_download("pratikgx/Depth-Pro-2-MLX-4bit")
91
+ # load_4bit.py lives at the repo root
92
+ import sys
93
+ sys.path.insert(0, repo)
94
+ from load_4bit import load_depth_pro_2_mlx_4bit
95
+
96
+ model = load_depth_pro_2_mlx_4bit(Path(repo) / "L") # or Path(repo) / "H" for H+
97
+ image, f_px = load_rgb("photo.jpg")
98
+ prediction = model.infer(to_normalized(image), f_px=f_px)
99
+ depth = prediction["depth"] # meters
100
+ inverse_depth = prediction["inverse_depth"]
101
+ focal = prediction["focallength_px"]
102
+ ```
103
+
104
+ Use BF16 for full-precision work with the MLX port (the loader already builds the unquantized parts in BF16 / FP32). Prefer size `L` or `H+` from this repo when you want the 4-bit weights.
105
+
106
+ ## Caveats
107
+
108
+ - These 4-bit quality numbers come from a small test set: one official photo at native resolution, plus one 1280×720 cover-crop of that photo. They are not a dataset-wide accuracy claim.
109
+ - In earlier full-precision MLX tests, **FP16** produced all-NaN depth maps on some inputs. Use **BF16** for full precision, not FP16.
110
+ - This conversion does not change the original research-only license. Do not use the original weights or this derivative in a commercial product or service.
111
+ - Depth Pro 2 is Apple's model. This repository only provides a quantized MLX packing of it.
112
+
113
+ ## License and attribution
114
+
115
+ Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement.
116
+
117
+ This repository redistributes a Model Derivative of Apple Depth Pro 2. The modifications are: conversion to the MLX weight layout, and affine 4-bit weight-only quantization (group size 64) of encoder linear layers, with the layers listed above left in BF16 or FP32. The `LICENSE` file in this repository is a copy of that agreement.
118
+
119
+ The name, trademarks, service marks, or logos of Apple may not be used to endorse or promote this derivative.
assets/mlx_4bit_vs_bf16_parity.png ADDED
load_4bit.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load a 4-bit Depth Pro 2 MLX bundle from pratikgx/Depth-Pro-2-MLX-4bit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import mlx.core as mx
8
+ import mlx.nn as nn
9
+ from depth_pro_2_mlx.model import DepthPro2MLX
10
+
11
+ BITS = 4
12
+ GROUP_SIZE = 64
13
+ MODE = "affine"
14
+
15
+
16
+ def _should_quantize(path: str, module) -> bool:
17
+ if not hasattr(module, "to_quantized"):
18
+ return False
19
+ if not isinstance(module, nn.Linear):
20
+ return False
21
+ weight = getattr(module, "weight", None)
22
+ if weight is not None:
23
+ in_features = int(weight.shape[-1] if weight.ndim >= 2 else weight.shape[0])
24
+ if in_features % GROUP_SIZE != 0:
25
+ return False
26
+ return True
27
+
28
+
29
+ def _immediate_child_modules(module):
30
+ seen = []
31
+ if hasattr(module, "items"):
32
+ try:
33
+ for key, value in list(module.items()):
34
+ if isinstance(value, nn.Module):
35
+ seen.append((str(key), value))
36
+ except Exception:
37
+ seen = []
38
+ if seen:
39
+ return seen
40
+ children = []
41
+ for key, value in vars(module).items():
42
+ if key.startswith("_"):
43
+ continue
44
+ if isinstance(value, nn.Module):
45
+ children.append((key, value))
46
+ return children
47
+
48
+
49
+ def _quantize_linears_inplace(module, prefix: str = "") -> int:
50
+ replaced = 0
51
+ for name, child in _immediate_child_modules(module):
52
+ path = f"{prefix}.{name}" if prefix else name
53
+ if isinstance(child, nn.Linear) and _should_quantize(path, child):
54
+ setattr(
55
+ module,
56
+ name,
57
+ child.to_quantized(group_size=GROUP_SIZE, bits=BITS, mode=MODE),
58
+ )
59
+ replaced += 1
60
+ elif not isinstance(child, nn.Linear):
61
+ replaced += _quantize_linears_inplace(child, path)
62
+ return replaced
63
+
64
+
65
+ def _size_key(name: str) -> str:
66
+ key = name.lower().replace("h+", "h")
67
+ if key.endswith("h"):
68
+ return "h"
69
+ if key.endswith("l"):
70
+ return "l"
71
+ if key.endswith("b"):
72
+ return "b"
73
+ if key.endswith("s"):
74
+ return "s"
75
+ return key
76
+
77
+
78
+ def load_depth_pro_2_mlx_4bit(
79
+ folder: str | Path,
80
+ size: str | None = None,
81
+ *,
82
+ precision: str = "bf16",
83
+ compile: bool = False,
84
+ ) -> DepthPro2MLX:
85
+ """Load one size folder (L or H) from pratikgx/Depth-Pro-2-MLX-4bit.
86
+
87
+ The folder must contain model.safetensors written by the conversion script.
88
+ Encoder Linear layers are quantized in place to match that file, then the
89
+ weights are loaded. The FOV estimator in the bundle is BF16/FP32.
90
+
91
+ This walks modules and calls Linear.to_quantized() directly. The port's
92
+ Indexed containers are not compatible with mlx.nn.quantize's update_modules.
93
+ """
94
+ folder = Path(folder)
95
+ if not (folder / "model.safetensors").is_file():
96
+ raise FileNotFoundError(f"No model.safetensors in {folder}")
97
+ weight_path = folder / "model.safetensors"
98
+ size_key = _size_key(size or folder.name)
99
+
100
+ model = DepthPro2MLX(f"depthpro2-{size_key}", precision=precision, fov=True, compile=compile)
101
+ _quantize_linears_inplace(model.encoder)
102
+ weights = dict(mx.load(str(weight_path)))
103
+
104
+ def load_prefixed(module, prefix: str) -> None:
105
+ p = prefix + "."
106
+ subset = {k[len(p):]: v for k, v in weights.items() if k.startswith(p)}
107
+ if not subset:
108
+ raise RuntimeError(f"No weights with prefix {prefix!r} in {weight_path}")
109
+ module.load_weights(list(subset.items()), strict=True)
110
+
111
+ load_prefixed(model.encoder, "encoder")
112
+ load_prefixed(model.decoder, "decoder")
113
+ load_prefixed(model.head, "head")
114
+ if model.fov is not None:
115
+ load_prefixed(model.fov, "fov")
116
+ return model