File size: 3,712 Bytes
db009bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""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