Skip to content

mlx3d.models

Pretrained 3D foundation models. Install the models extra to download weights: pip install "mlx3d[models]".

mlx3d.models.depth_anything3.DepthAnything3

Bases: Module

DA3 any-view geometry model (MLX port of ByteDance-Seed/Depth-Anything-3).

From one or more images of a static scene it predicts, in a single forward pass, a depth map and confidence per view plus every view's intrinsics and pose — the job usually done by structure-from-motion. Load pretrained weights with :meth:from_pretrained and run :meth:predict.

The backbone may run in reduced precision (dtype); the dense head and camera decoder always run in float32, as in the reference implementation.

Source code in src/mlx3d/models/depth_anything3/model.py
 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
class DepthAnything3(nn.Module):
    """DA3 any-view geometry model (MLX port of ByteDance-Seed/Depth-Anything-3).

    From one or more images of a static scene it predicts, in a single forward
    pass, a depth map and confidence per view plus every view's intrinsics and
    pose — the job usually done by structure-from-motion. Load pretrained
    weights with :meth:`from_pretrained` and run :meth:`predict`.

    The backbone may run in reduced precision (``dtype``); the dense head and
    camera decoder always run in float32, as in the reference implementation.
    """

    def __init__(self, config: DA3Config, dtype: mx.Dtype = mx.float32):
        super().__init__()
        self.config = config
        self.dtype = dtype
        self.backbone = DinoBackbone(config)
        self.head = DualDPT(
            dim_in=2 * config.embed_dim,
            features=config.head_features,
            out_channels=config.head_out_channels,
            patch_size=config.patch_size,
        )
        self.cam_dec = CameraDecoder(2 * config.embed_dim)

    # ------------------------------------------------------------------ #
    # Construction
    # ------------------------------------------------------------------ #

    @classmethod
    def from_pretrained(
        cls,
        name: str = "da3-base",
        weights: str | None = None,
        dtype: mx.Dtype = mx.float32,
    ) -> DepthAnything3:
        """Build a preset and load its pretrained weights.

        Args:
            name: a preset in :data:`~mlx3d.models.depth_anything3.PRESETS`
                (``"da3-small"``, ``"da3-base"``: Apache-2.0; ``"da3-large"``:
                CC BY-NC 4.0, non-commercial).
            weights: local ``model.safetensors`` (or its directory). Defaults
                to downloading the preset's Hub repository once.
            dtype: backbone compute dtype. ``mx.float16`` tracks float32
                closely (~0.03% median depth difference); ``mx.bfloat16``'s
                shorter mantissa costs visibly more accuracy.
        """
        if name not in PRESETS:
            raise ValueError(f"Unknown DA3 preset {name!r}; choose from {sorted(PRESETS)}.")
        config = PRESETS[name]
        model = cls(config, dtype=dtype)
        path = resolve_weights(weights or config.repo_id, repo_id=config.repo_id)
        model.load_weights(list(convert_checkpoint(mx.load(str(path))).items()), strict=True)
        if dtype != mx.float32:
            model.backbone.set_dtype(dtype)
        model.eval()
        mx.eval(model.parameters())
        return model

    # ------------------------------------------------------------------ #
    # Forward
    # ------------------------------------------------------------------ #

    def encode(
        self, pixels: mx.array, ref_view_strategy: RefViewStrategy = "saddle_balanced"
    ) -> list[LayerOutput]:
        """Backbone taps for normalized ``(B, S, H, W, 3)`` pixels, in float32."""
        taps = self.backbone(pixels.astype(self.dtype), ref_view_strategy)
        return [
            LayerOutput(t.patch_tokens.astype(mx.float32), t.camera_token.astype(mx.float32))
            for t in taps
        ]

    def __call__(
        self,
        pixels: mx.array,
        ref_view_strategy: RefViewStrategy = "saddle_balanced",
        with_rays: bool = False,
    ) -> dict[str, mx.array]:
        """Full forward pass on normalized ``(B, S, H, W, 3)`` pixels.

        Returns ``(B, S, ...)`` arrays: ``depth``, ``depth_conf``, ``R``, ``t``,
        ``K`` (and ``ray``, ``ray_conf`` with ``with_rays``).
        """
        image_hw = (pixels.shape[2], pixels.shape[3])
        taps = self.encode(pixels, ref_view_strategy)
        out = self.head.decode(taps, image_hw, with_rays)
        out["R"], out["t"], out["K"] = decode_pose_encoding(
            self.cam_dec(taps[-1].camera_token), image_hw
        )
        return out

    def predict(
        self,
        images: Sequence[ImageInput],
        resolution: int = 504,
        ref_view_strategy: RefViewStrategy = "saddle_balanced",
        with_rays: bool = False,
        max_views: int = 32,
        num_anchors: int = 8,
        head_chunk: int = 8,
    ) -> GeometryPrediction:
        """Predict depth and cameras for a set of views of one scene.

        Up to ``max_views`` views are processed jointly in one forward pass.
        Longer sequences run in chunks that all share ``num_anchors`` evenly
        spaced anchor views; each chunk is mapped into the first chunk's frame
        by the similarity that best aligns its anchor cameras, so cost grows
        linearly instead of quadratically and nothing drifts along the sequence.

        Args:
            images: file paths, PIL images, or ``(H, W, 3)`` arrays — all with
                the same aspect ratio.
            resolution: longest processing side (the model was trained at 504).
            ref_view_strategy: how the view defining the world frame is chosen.
            with_rays: also return DA3's per-pixel ray maps (joint pass only).
            max_views: most views per forward pass.
            num_anchors: views shared by every chunk of a long sequence.
            head_chunk: views decoded per dense-head pass; lower it to reduce
                peak memory.
        """
        pixels, rgb, sizes = load_views(images, resolution, self.config.patch_size)
        n_views = pixels.shape[1]
        if n_views <= max_views:
            out = self._forward_views(pixels, ref_view_strategy, with_rays, head_chunk)
        elif with_rays:
            raise ValueError(f"with_rays needs a single pass: pass max_views >= {n_views}.")
        else:
            out = self._forward_chunked(
                pixels, ref_view_strategy, max_views, num_anchors, head_chunk
            )
        return GeometryPrediction(rgb=rgb, original_sizes=sizes, **out)

    def _forward_views(
        self,
        pixels: mx.array,
        ref_view_strategy: RefViewStrategy,
        with_rays: bool,
        head_chunk: int,
    ) -> dict[str, mx.array]:
        """One joint pass over ``(1, S, H, W, 3)`` pixels, decoding the dense head
        a few views at a time to bound memory. Returns ``(S, ...)`` arrays.

        The attention and decoder buffers differ in size between passes, so
        MLX's buffer cache is released after each stage; otherwise it keeps
        growing across calls and, on unified memory, slows the whole system.
        """
        image_hw = (pixels.shape[2], pixels.shape[3])
        taps = self.encode(pixels, ref_view_strategy)
        R, t, K = decode_pose_encoding(self.cam_dec(taps[-1].camera_token), image_hw)
        mx.eval([tap.arrays() for tap in taps], R, t, K)
        mx.clear_cache()

        maps: dict[str, list[mx.array]] = {}
        for start in range(0, pixels.shape[1], head_chunk):
            chunk = [
                LayerOutput(tap.patch_tokens[:, start : start + head_chunk], tap.camera_token)
                for tap in taps
            ]
            out = self.head.decode(chunk, image_hw, with_rays)
            mx.eval(out)
            for key, value in out.items():
                maps.setdefault(key, []).append(value[0])
        mx.clear_cache()
        result = {key: mx.concatenate(parts, axis=0) for key, parts in maps.items()}
        result.update(R=R[0], t=t[0], K=K[0])
        return result

    def _forward_chunked(
        self,
        pixels: mx.array,
        ref_view_strategy: RefViewStrategy,
        max_views: int,
        num_anchors: int,
        head_chunk: int,
    ) -> dict[str, mx.array]:
        n_views = pixels.shape[1]
        if not 0 < num_anchors < max_views:
            raise ValueError("Need 0 < num_anchors < max_views.")
        anchors = np.unique(np.linspace(0, n_views - 1, num_anchors).round().astype(int))
        others = np.setdiff1d(np.arange(n_views), anchors)
        step = max_views - len(anchors)

        depth = [None] * n_views
        conf = [None] * n_views
        R = np.zeros((n_views, 3, 3))
        t = np.zeros((n_views, 3))
        K = np.zeros((n_views, 3, 3))
        reference = None  # anchor cameras of the first chunk define the world frame
        for start in range(0, len(others), step):
            views = np.concatenate([anchors, others[start : start + step]])
            out = self._forward_views(
                pixels[:, mx.array(views)], ref_view_strategy, False, head_chunk
            )
            Rc, tc = np.array(out["R"], np.float64), np.array(out["t"], np.float64)
            n_a = len(anchors)
            if reference is None:
                reference = (Rc[:n_a], tc[:n_a])
                sim = Similarity(1.0, np.eye(3), np.zeros(3))
            else:
                sim = fit_similarity(Rc[:n_a], tc[:n_a], *reference)
            Rc, tc = sim.apply_to_cameras(Rc, tc)
            # Anchors keep the first chunk's estimate; each other view is seen once.
            keep = slice(0, None) if start == 0 else slice(n_a, None)
            for local, view in zip(range(len(views))[keep], views[keep]):
                depth[view] = out["depth"][local] * sim.scale
                conf[view] = out["depth_conf"][local]
                R[view], t[view], K[view] = Rc[local], tc[local], np.array(out["K"][local])
        return {
            "depth": mx.stack(depth),
            "depth_conf": mx.stack(conf),
            "R": mx.array(R, dtype=mx.float32),
            "t": mx.array(t, dtype=mx.float32),
            "K": mx.array(K, dtype=mx.float32),
        }

from_pretrained(name='da3-base', weights=None, dtype=mx.float32) classmethod

Build a preset and load its pretrained weights.

Parameters:

Name Type Description Default
name str

a preset in :data:~mlx3d.models.depth_anything3.PRESETS ("da3-small", "da3-base": Apache-2.0; "da3-large": CC BY-NC 4.0, non-commercial).

'da3-base'
weights str | None

local model.safetensors (or its directory). Defaults to downloading the preset's Hub repository once.

None
dtype Dtype

backbone compute dtype. mx.float16 tracks float32 closely (~0.03% median depth difference); mx.bfloat16's shorter mantissa costs visibly more accuracy.

float32
Source code in src/mlx3d/models/depth_anything3/model.py
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
@classmethod
def from_pretrained(
    cls,
    name: str = "da3-base",
    weights: str | None = None,
    dtype: mx.Dtype = mx.float32,
) -> DepthAnything3:
    """Build a preset and load its pretrained weights.

    Args:
        name: a preset in :data:`~mlx3d.models.depth_anything3.PRESETS`
            (``"da3-small"``, ``"da3-base"``: Apache-2.0; ``"da3-large"``:
            CC BY-NC 4.0, non-commercial).
        weights: local ``model.safetensors`` (or its directory). Defaults
            to downloading the preset's Hub repository once.
        dtype: backbone compute dtype. ``mx.float16`` tracks float32
            closely (~0.03% median depth difference); ``mx.bfloat16``'s
            shorter mantissa costs visibly more accuracy.
    """
    if name not in PRESETS:
        raise ValueError(f"Unknown DA3 preset {name!r}; choose from {sorted(PRESETS)}.")
    config = PRESETS[name]
    model = cls(config, dtype=dtype)
    path = resolve_weights(weights or config.repo_id, repo_id=config.repo_id)
    model.load_weights(list(convert_checkpoint(mx.load(str(path))).items()), strict=True)
    if dtype != mx.float32:
        model.backbone.set_dtype(dtype)
    model.eval()
    mx.eval(model.parameters())
    return model

encode(pixels, ref_view_strategy='saddle_balanced')

Backbone taps for normalized (B, S, H, W, 3) pixels, in float32.

Source code in src/mlx3d/models/depth_anything3/model.py
88
89
90
91
92
93
94
95
96
def encode(
    self, pixels: mx.array, ref_view_strategy: RefViewStrategy = "saddle_balanced"
) -> list[LayerOutput]:
    """Backbone taps for normalized ``(B, S, H, W, 3)`` pixels, in float32."""
    taps = self.backbone(pixels.astype(self.dtype), ref_view_strategy)
    return [
        LayerOutput(t.patch_tokens.astype(mx.float32), t.camera_token.astype(mx.float32))
        for t in taps
    ]

__call__(pixels, ref_view_strategy='saddle_balanced', with_rays=False)

Full forward pass on normalized (B, S, H, W, 3) pixels.

Returns (B, S, ...) arrays: depth, depth_conf, R, t, K (and ray, ray_conf with with_rays).

Source code in src/mlx3d/models/depth_anything3/model.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def __call__(
    self,
    pixels: mx.array,
    ref_view_strategy: RefViewStrategy = "saddle_balanced",
    with_rays: bool = False,
) -> dict[str, mx.array]:
    """Full forward pass on normalized ``(B, S, H, W, 3)`` pixels.

    Returns ``(B, S, ...)`` arrays: ``depth``, ``depth_conf``, ``R``, ``t``,
    ``K`` (and ``ray``, ``ray_conf`` with ``with_rays``).
    """
    image_hw = (pixels.shape[2], pixels.shape[3])
    taps = self.encode(pixels, ref_view_strategy)
    out = self.head.decode(taps, image_hw, with_rays)
    out["R"], out["t"], out["K"] = decode_pose_encoding(
        self.cam_dec(taps[-1].camera_token), image_hw
    )
    return out

predict(images, resolution=504, ref_view_strategy='saddle_balanced', with_rays=False, max_views=32, num_anchors=8, head_chunk=8)

Predict depth and cameras for a set of views of one scene.

Up to max_views views are processed jointly in one forward pass. Longer sequences run in chunks that all share num_anchors evenly spaced anchor views; each chunk is mapped into the first chunk's frame by the similarity that best aligns its anchor cameras, so cost grows linearly instead of quadratically and nothing drifts along the sequence.

Parameters:

Name Type Description Default
images Sequence[ImageInput]

file paths, PIL images, or (H, W, 3) arrays — all with the same aspect ratio.

required
resolution int

longest processing side (the model was trained at 504).

504
ref_view_strategy RefViewStrategy

how the view defining the world frame is chosen.

'saddle_balanced'
with_rays bool

also return DA3's per-pixel ray maps (joint pass only).

False
max_views int

most views per forward pass.

32
num_anchors int

views shared by every chunk of a long sequence.

8
head_chunk int

views decoded per dense-head pass; lower it to reduce peak memory.

8
Source code in src/mlx3d/models/depth_anything3/model.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def predict(
    self,
    images: Sequence[ImageInput],
    resolution: int = 504,
    ref_view_strategy: RefViewStrategy = "saddle_balanced",
    with_rays: bool = False,
    max_views: int = 32,
    num_anchors: int = 8,
    head_chunk: int = 8,
) -> GeometryPrediction:
    """Predict depth and cameras for a set of views of one scene.

    Up to ``max_views`` views are processed jointly in one forward pass.
    Longer sequences run in chunks that all share ``num_anchors`` evenly
    spaced anchor views; each chunk is mapped into the first chunk's frame
    by the similarity that best aligns its anchor cameras, so cost grows
    linearly instead of quadratically and nothing drifts along the sequence.

    Args:
        images: file paths, PIL images, or ``(H, W, 3)`` arrays — all with
            the same aspect ratio.
        resolution: longest processing side (the model was trained at 504).
        ref_view_strategy: how the view defining the world frame is chosen.
        with_rays: also return DA3's per-pixel ray maps (joint pass only).
        max_views: most views per forward pass.
        num_anchors: views shared by every chunk of a long sequence.
        head_chunk: views decoded per dense-head pass; lower it to reduce
            peak memory.
    """
    pixels, rgb, sizes = load_views(images, resolution, self.config.patch_size)
    n_views = pixels.shape[1]
    if n_views <= max_views:
        out = self._forward_views(pixels, ref_view_strategy, with_rays, head_chunk)
    elif with_rays:
        raise ValueError(f"with_rays needs a single pass: pass max_views >= {n_views}.")
    else:
        out = self._forward_chunked(
            pixels, ref_view_strategy, max_views, num_anchors, head_chunk
        )
    return GeometryPrediction(rgb=rgb, original_sizes=sizes, **out)

mlx3d.models.depth_anything3.GeometryPrediction dataclass

Per-view depth, confidence and cameras for S views at processing size.

Cameras follow mlx3d's OpenCV convention (world-to-camera R, t); the world frame is the reference view's camera frame, at an arbitrary but consistent scale.

Attributes:

Name Type Description
depth array

(S, H, W) z-depth.

depth_conf array

(S, H, W) confidence (>= 1; higher is better).

R, t

(S, 3, 3) / (S, 3) world-to-camera extrinsics.

K array

(S, 3, 3) intrinsics at the processing size.

rgb ndarray

(S, H, W, 3) uint8 frames the model saw.

original_sizes list[tuple[int, int]]

each input's (width, height).

ray, ray_conf

optional per-pixel ray maps, when requested.

Source code in src/mlx3d/models/depth_anything3/prediction.py
 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
@dataclass
class GeometryPrediction:
    """Per-view depth, confidence and cameras for ``S`` views at processing size.

    Cameras follow mlx3d's OpenCV convention (world-to-camera ``R``, ``t``); the
    world frame is the reference view's camera frame, at an arbitrary but
    consistent scale.

    Attributes:
        depth: ``(S, H, W)`` z-depth.
        depth_conf: ``(S, H, W)`` confidence (``>= 1``; higher is better).
        R, t: ``(S, 3, 3)`` / ``(S, 3)`` world-to-camera extrinsics.
        K: ``(S, 3, 3)`` intrinsics at the processing size.
        rgb: ``(S, H, W, 3)`` uint8 frames the model saw.
        original_sizes: each input's ``(width, height)``.
        ray, ray_conf: optional per-pixel ray maps, when requested.
    """

    depth: mx.array
    depth_conf: mx.array
    R: mx.array
    t: mx.array
    K: mx.array
    rgb: np.ndarray
    original_sizes: list[tuple[int, int]]
    ray: mx.array | None = None
    ray_conf: mx.array | None = None

    def __len__(self) -> int:
        return int(self.depth.shape[0])

    @property
    def image_size(self) -> tuple[int, int]:
        """Processing ``(width, height)``."""
        return int(self.depth.shape[2]), int(self.depth.shape[1])

    def camera(self, i: int, original_size: bool = False) -> Camera:
        """View ``i`` as a :class:`~mlx3d.cameras.Camera`.

        With ``original_size`` the intrinsics are rescaled to the input image
        resolution (e.g. for training on the full-resolution photos).
        """
        w, h = self.image_size
        K = np.array(self.K[i])
        sx = sy = 1.0
        if original_size:
            ow, oh = self.original_sizes[i]
            sx, sy, w, h = ow / w, oh / h, ow, oh
        return Camera(
            R=self.R[i],
            t=self.t[i],
            fx=float(K[0, 0] * sx),
            fy=float(K[1, 1] * sy),
            cx=float(K[0, 2] * sx),
            cy=float(K[1, 2] * sy),
            width=int(w),
            height=int(h),
        )

    def cameras(self, original_size: bool = False) -> list[Camera]:
        return [self.camera(i, original_size) for i in range(len(self))]

    def confidence_mask(self, quantile: float = 0.3) -> mx.array:
        """``(S, H, W)`` mask keeping pixels above the global confidence quantile."""
        conf = np.array(self.depth_conf)
        return mx.array(conf >= np.quantile(conf, quantile))

    def world_points(self, i: int) -> mx.array:
        """``(H, W, 3)`` world-space points of view ``i`` (pixel-center unprojection)."""
        w, h = self.image_size
        u = mx.arange(w, dtype=mx.float32) + 0.5
        v = mx.arange(h, dtype=mx.float32) + 0.5
        xy = mx.stack(mx.meshgrid(u, v, indexing="xy"), axis=-1)
        return self.camera(i).unproject_points(xy, self.depth[i])

    def point_cloud(
        self, conf_quantile: float = 0.3, max_points: int | None = 500_000, seed: int = 0
    ) -> tuple[np.ndarray, np.ndarray]:
        """Fuse all views into one colored point cloud.

        Pixels below the ``conf_quantile`` confidence quantile are dropped, then
        the rest is uniformly subsampled to ``max_points``.

        Returns:
            ``(points, colors)``: ``(P, 3)`` float32 positions and ``(P, 3)``
            float32 colors in ``[0, 1]``.
        """
        mask = np.array(self.confidence_mask(conf_quantile))
        points = np.stack([np.array(self.world_points(i)) for i in range(len(self))])
        points, colors = points[mask], self.rgb[mask].astype(np.float32) / 255.0
        if max_points is not None and len(points) > max_points:
            keep = np.random.default_rng(seed).choice(len(points), max_points, replace=False)
            points, colors = points[keep], colors[keep]
        return points.astype(np.float32), colors

    def to_pointclouds(self, **kwargs) -> Pointclouds:
        """:meth:`point_cloud` as a single-element :class:`~mlx3d.structures.Pointclouds`."""
        points, colors = self.point_cloud(**kwargs)
        return Pointclouds(points=[mx.array(points)], features=[mx.array(colors)])

image_size property

Processing (width, height).

camera(i, original_size=False)

View i as a :class:~mlx3d.cameras.Camera.

With original_size the intrinsics are rescaled to the input image resolution (e.g. for training on the full-resolution photos).

Source code in src/mlx3d/models/depth_anything3/prediction.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def camera(self, i: int, original_size: bool = False) -> Camera:
    """View ``i`` as a :class:`~mlx3d.cameras.Camera`.

    With ``original_size`` the intrinsics are rescaled to the input image
    resolution (e.g. for training on the full-resolution photos).
    """
    w, h = self.image_size
    K = np.array(self.K[i])
    sx = sy = 1.0
    if original_size:
        ow, oh = self.original_sizes[i]
        sx, sy, w, h = ow / w, oh / h, ow, oh
    return Camera(
        R=self.R[i],
        t=self.t[i],
        fx=float(K[0, 0] * sx),
        fy=float(K[1, 1] * sy),
        cx=float(K[0, 2] * sx),
        cy=float(K[1, 2] * sy),
        width=int(w),
        height=int(h),
    )

confidence_mask(quantile=0.3)

(S, H, W) mask keeping pixels above the global confidence quantile.

Source code in src/mlx3d/models/depth_anything3/prediction.py
78
79
80
81
def confidence_mask(self, quantile: float = 0.3) -> mx.array:
    """``(S, H, W)`` mask keeping pixels above the global confidence quantile."""
    conf = np.array(self.depth_conf)
    return mx.array(conf >= np.quantile(conf, quantile))

world_points(i)

(H, W, 3) world-space points of view i (pixel-center unprojection).

Source code in src/mlx3d/models/depth_anything3/prediction.py
83
84
85
86
87
88
89
def world_points(self, i: int) -> mx.array:
    """``(H, W, 3)`` world-space points of view ``i`` (pixel-center unprojection)."""
    w, h = self.image_size
    u = mx.arange(w, dtype=mx.float32) + 0.5
    v = mx.arange(h, dtype=mx.float32) + 0.5
    xy = mx.stack(mx.meshgrid(u, v, indexing="xy"), axis=-1)
    return self.camera(i).unproject_points(xy, self.depth[i])

point_cloud(conf_quantile=0.3, max_points=500000, seed=0)

Fuse all views into one colored point cloud.

Pixels below the conf_quantile confidence quantile are dropped, then the rest is uniformly subsampled to max_points.

Returns:

Type Description
ndarray

(points, colors): (P, 3) float32 positions and (P, 3)

ndarray

float32 colors in [0, 1].

Source code in src/mlx3d/models/depth_anything3/prediction.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def point_cloud(
    self, conf_quantile: float = 0.3, max_points: int | None = 500_000, seed: int = 0
) -> tuple[np.ndarray, np.ndarray]:
    """Fuse all views into one colored point cloud.

    Pixels below the ``conf_quantile`` confidence quantile are dropped, then
    the rest is uniformly subsampled to ``max_points``.

    Returns:
        ``(points, colors)``: ``(P, 3)`` float32 positions and ``(P, 3)``
        float32 colors in ``[0, 1]``.
    """
    mask = np.array(self.confidence_mask(conf_quantile))
    points = np.stack([np.array(self.world_points(i)) for i in range(len(self))])
    points, colors = points[mask], self.rgb[mask].astype(np.float32) / 255.0
    if max_points is not None and len(points) > max_points:
        keep = np.random.default_rng(seed).choice(len(points), max_points, replace=False)
        points, colors = points[keep], colors[keep]
    return points.astype(np.float32), colors

to_pointclouds(**kwargs)

:meth:point_cloud as a single-element :class:~mlx3d.structures.Pointclouds.

Source code in src/mlx3d/models/depth_anything3/prediction.py
111
112
113
114
def to_pointclouds(self, **kwargs) -> Pointclouds:
    """:meth:`point_cloud` as a single-element :class:`~mlx3d.structures.Pointclouds`."""
    points, colors = self.point_cloud(**kwargs)
    return Pointclouds(points=[mx.array(points)], features=[mx.array(colors)])

mlx3d.models.depth_anything3.DA3Config dataclass

Hyperparameters of a DA3 network (DINOv2 backbone + DualDPT head).

Attributes:

Name Type Description
repo_id str

Hugging Face repository holding the pretrained weights.

license str

license of those weights (the MLX code itself is MIT).

embed_dim, (depth, num_heads)

ViT width, number of blocks, attention heads.

out_layers tuple[int, ...]

blocks whose tokens feed the dense head (and camera decoder).

alt_start int

first block that alternates frame-local and cross-view (global) attention; odd blocks from here on are global.

qknorm_start, rope_start

first block using QK-LayerNorm / 2D RoPE.

head_features int

DPT fusion width.

head_out_channels tuple[int, int, int, int]

per-stage DPT projection widths.

Source code in src/mlx3d/models/depth_anything3/config.py
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
@dataclass(frozen=True)
class DA3Config:
    """Hyperparameters of a DA3 network (DINOv2 backbone + DualDPT head).

    Attributes:
        repo_id: Hugging Face repository holding the pretrained weights.
        license: license of those weights (the MLX code itself is MIT).
        embed_dim, depth, num_heads: ViT width, number of blocks, attention heads.
        out_layers: blocks whose tokens feed the dense head (and camera decoder).
        alt_start: first block that alternates frame-local and cross-view
            (global) attention; odd blocks from here on are global.
        qknorm_start, rope_start: first block using QK-LayerNorm / 2D RoPE.
        head_features: DPT fusion width.
        head_out_channels: per-stage DPT projection widths.
    """

    repo_id: str
    license: str
    embed_dim: int
    depth: int
    num_heads: int
    out_layers: tuple[int, ...]
    alt_start: int
    qknorm_start: int
    rope_start: int
    head_features: int
    head_out_channels: tuple[int, int, int, int]
    patch_size: int = 14
    pretrain_grid: int = 37
    """Side length of the patch grid the positional embedding was trained at
    (518 px / 14)."""
    rope_frequency: float = 100.0
    mlp_ratio: int = 4

    @property
    def head_dim(self) -> int:
        return self.embed_dim // self.num_heads

pretrain_grid = 37 class-attribute instance-attribute

Side length of the patch grid the positional embedding was trained at (518 px / 14).

mlx3d.models.depth_anything3.convert_checkpoint(weights)

Convert a DA3 model.safetensors dict to MLX parameter names/layouts.

Linear weights keep PyTorch's (out, in) layout; convolution kernels move from (out, in, kh, kw) to MLX's (out, kh, kw, in) and transposed convolutions from (in, out, kh, kw) to (out, kh, kw, in).

Source code in src/mlx3d/models/depth_anything3/convert.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def convert_checkpoint(weights: dict[str, mx.array]) -> dict[str, mx.array]:
    """Convert a DA3 ``model.safetensors`` dict to MLX parameter names/layouts.

    Linear weights keep PyTorch's ``(out, in)`` layout; convolution kernels move
    from ``(out, in, kh, kw)`` to MLX's ``(out, kh, kw, in)`` and transposed
    convolutions from ``(in, out, kh, kw)`` to ``(out, kh, kw, in)``.
    """
    converted: dict[str, mx.array] = {}
    for raw_key, value in weights.items():
        key = raw_key.removeprefix("model.")
        if _UNUSED.match(key):
            continue
        key = _rename(key)
        if value.ndim == 4:
            axes = (1, 2, 3, 0) if _CONV_TRANSPOSE.match(key) else (0, 2, 3, 1)
            value = value.transpose(axes)
        if key in converted:
            raise ValueError(f"Two checkpoint tensors map onto {key!r}.")
        converted[key] = value
    return converted