"""Load a 4-bit Depth Pro 2 MLX bundle from pratikgx/Depth-Pro-2-MLX-4bit.""" from __future__ import annotations from pathlib import Path import mlx.core as mx import mlx.nn as nn from depth_pro_2_mlx.model import DepthPro2MLX BITS = 4 GROUP_SIZE = 64 MODE = "affine" def _should_quantize(path: str, module) -> bool: if not hasattr(module, "to_quantized"): return False if not isinstance(module, nn.Linear): return False weight = getattr(module, "weight", None) if weight is not None: in_features = int(weight.shape[-1] if weight.ndim >= 2 else weight.shape[0]) if in_features % GROUP_SIZE != 0: return False return True def _immediate_child_modules(module): seen = [] if hasattr(module, "items"): try: for key, value in list(module.items()): if isinstance(value, nn.Module): seen.append((str(key), value)) except Exception: seen = [] if seen: return seen children = [] for key, value in vars(module).items(): if key.startswith("_"): continue if isinstance(value, nn.Module): children.append((key, value)) return children def _quantize_linears_inplace(module, prefix: str = "") -> int: replaced = 0 for name, child in _immediate_child_modules(module): path = f"{prefix}.{name}" if prefix else name if isinstance(child, nn.Linear) and _should_quantize(path, child): setattr( module, name, child.to_quantized(group_size=GROUP_SIZE, bits=BITS, mode=MODE), ) replaced += 1 elif not isinstance(child, nn.Linear): replaced += _quantize_linears_inplace(child, path) return replaced def _size_key(name: str) -> str: key = name.lower().replace("h+", "h") if key.endswith("h"): return "h" if key.endswith("l"): return "l" if key.endswith("b"): return "b" if key.endswith("s"): return "s" return key def load_depth_pro_2_mlx_4bit( folder: str | Path, size: str | None = None, *, precision: str = "bf16", compile: bool = False, ) -> DepthPro2MLX: """Load one size folder (L or H) from pratikgx/Depth-Pro-2-MLX-4bit. The folder must contain model.safetensors written by the conversion script. Encoder Linear layers are quantized in place to match that file, then the weights are loaded. The FOV estimator in the bundle is BF16/FP32. This walks modules and calls Linear.to_quantized() directly. The port's Indexed containers are not compatible with mlx.nn.quantize's update_modules. """ folder = Path(folder) if not (folder / "model.safetensors").is_file(): raise FileNotFoundError(f"No model.safetensors in {folder}") weight_path = folder / "model.safetensors" size_key = _size_key(size or folder.name) model = DepthPro2MLX(f"depthpro2-{size_key}", precision=precision, fov=True, compile=compile) _quantize_linears_inplace(model.encoder) weights = dict(mx.load(str(weight_path))) def load_prefixed(module, prefix: str) -> None: p = prefix + "." subset = {k[len(p):]: v for k, v in weights.items() if k.startswith(p)} if not subset: raise RuntimeError(f"No weights with prefix {prefix!r} in {weight_path}") module.load_weights(list(subset.items()), strict=True) load_prefixed(model.encoder, "encoder") load_prefixed(model.decoder, "decoder") load_prefixed(model.head, "head") if model.fov is not None: load_prefixed(model.fov, "fov") return model