Skip to content

mlx3d.splatting.spaghetti

mlx3d.splatting.spaghetti

Spaghetti Splatting: radiance fields of Gaussian-blurred curve segments.

An MLX / Metal implementation of Spaghetti Splatting: Differentiating Curvilinear Dirac Masses via Convolution (Shramko, Govindarajan, Lam, Xie, Rebain, Lindell, Tagliasacchi, 2026). Each primitive is a line segment convolved with a 3D Gaussian kernel; chains of segments represent curves — hair, wires, grass — far more economically than strings of blobs, and a zero-length segment is exactly a 3D Gaussian, so the representation is a strict superset of 3D Gaussian Splatting.

SpaghettiModel

Gaussian-blurred line segments with spherical-harmonic colors.

Parameters (params, all (N, ...)):

  • means, halves: segment midpoint and half-vector (segment = m ± h);
  • quats, scales: kernel rotation and log standard deviations;
  • opacities: logit of the peak point opacity o. The density is rho = -ln(1 - o) / (sqrt(2 pi) sigma) with sigma the kernel's geometric-mean scale, so a zero-length segment seen through its center has opacity ~o, exactly like a 3DGS splat; and rho (density per unit length) is what splitting preserves.
  • sh_dc (N, 1, 3), sh_rest (N, K-1, 3).
Source code in src/mlx3d/splatting/spaghetti/model.py
 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
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
class SpaghettiModel:
    """Gaussian-blurred line segments with spherical-harmonic colors.

    Parameters (``params``, all ``(N, ...)``):

    - ``means``, ``halves``: segment midpoint and half-vector (segment = ``m ± h``);
    - ``quats``, ``scales``: kernel rotation and log standard deviations;
    - ``opacities``: logit of the *peak point opacity* ``o``. The density is
      ``rho = -ln(1 - o) / (sqrt(2 pi) sigma)`` with ``sigma`` the kernel's
      geometric-mean scale, so a zero-length segment seen through its center
      has opacity ~``o``, exactly like a 3DGS splat; and ``rho`` (density per
      unit length) is what splitting preserves.
    - ``sh_dc`` (N, 1, 3), ``sh_rest`` (N, K-1, 3).
    """

    def __init__(self, params: dict[str, mx.array], sh_degree: int = 3):
        self.params = params
        self.sh_degree = sh_degree
        self.active_sh_degree = 0

    # ------------------------------------------------------------- construction
    @classmethod
    def from_points(
        cls,
        points: mx.array,
        colors: mx.array | None = None,
        sh_degree: int = 3,
        initial_opacity: float = 0.1,
        initial_length: float = 2.0,
        max_scale: float | None = None,
        seed: int = 0,
    ) -> SpaghettiModel:
        """Short segments at ``points`` in random directions.

        Kernel scales come from nearest-neighbor spacing; each segment is
        ``initial_length`` kernel widths long (a nonzero length is needed: at
        exactly zero the gradient with respect to it vanishes by symmetry).
        """
        from ...ops import knn_points

        points = mx.array(points, dtype=mx.float32)
        n = points.shape[0]
        if n > 20_000:  # a reference subsample keeps the k-NN cheap for big clouds
            pick = np.random.default_rng(seed).choice(n, 20_000, replace=False)
            ref = points[mx.array(pick)]
        else:
            ref = points
        dists, _ = knn_points(points, ref, K=4)
        spacing = mx.sqrt(mx.maximum(mx.mean(dists[:, 1:], axis=-1), 1e-14))
        if max_scale is not None:
            spacing = mx.minimum(spacing, max_scale)
        rng = np.random.default_rng(seed)
        dirs = rng.normal(size=(n, 3))
        dirs /= np.linalg.norm(dirs, axis=1, keepdims=True)
        quats = rng.normal(size=(n, 4))
        colors = mx.full((n, 3), 0.5) if colors is None else mx.array(colors, dtype=mx.float32)
        k = num_sh_bases(sh_degree)
        params = {
            "means": points,
            "halves": mx.array(dirs, dtype=mx.float32) * (0.5 * initial_length * spacing[:, None]),
            "quats": mx.array(
                quats / np.linalg.norm(quats, axis=1, keepdims=True), dtype=mx.float32
            ),
            "scales": mx.broadcast_to(mx.log(spacing)[:, None], (n, 3)),
            "opacities": mx.full((n,), _logit(initial_opacity)),
            "sh_dc": rgb_to_sh(colors)[:, None, :],
            "sh_rest": mx.zeros((n, k - 1, 3)),
        }
        return cls(params, sh_degree)

    @classmethod
    def from_gaussians(cls, gaussians, length_frac: float = 1e-3) -> SpaghettiModel:
        """Lift a :class:`~mlx3d.splatting.GaussianModel` to (near-)zero-length
        segments along each Gaussian's major axis — the representation is a
        strict superset of 3DGS, so this is a valid starting point."""
        from ...transforms import quaternion_to_matrix

        p = gaussians.params
        R = quaternion_to_matrix(p["quats"] / mx.linalg.norm(p["quats"], axis=-1, keepdims=True))
        major = mx.argmax(p["scales"], axis=-1)
        axis = mx.take_along_axis(R, major[:, None, None].astype(mx.int32), axis=2)[..., 0]
        halves = axis * (length_frac * mx.exp(mx.max(p["scales"], axis=-1)))[:, None]
        params = {
            "means": p["means"],
            "halves": halves,
            "quats": p["quats"],
            "scales": p["scales"],
            "opacities": p["opacities"],
            "sh_dc": p["sh_dc"],
            "sh_rest": p["sh_rest"],
        }
        model = cls({k: mx.array(v) for k, v in params.items()}, gaussians.sh_degree)
        model.active_sh_degree = gaussians.active_sh_degree
        return model

    # --------------------------------------------------------------- accessors
    @property
    def num_segments(self) -> int:
        return int(self.params["means"].shape[0])

    def __len__(self) -> int:
        return self.num_segments

    @staticmethod
    def density(params: dict[str, mx.array]) -> mx.array:
        """Density ``rho`` (per unit length) from the opacity / scale parameters."""
        o = mx.sigmoid(params["opacities"])
        sigma = mx.exp(mx.mean(params["scales"], axis=-1))
        return -mx.log(mx.maximum(1.0 - o, 1e-6)) / (_SQRT_2PI * sigma)

    @property
    def opacities_act(self) -> mx.array:
        return mx.sigmoid(self.params["opacities"])

    @property
    def scales_act(self) -> mx.array:
        return mx.exp(self.params["scales"])

    @property
    def lengths(self) -> mx.array:
        return 2.0 * mx.linalg.norm(self.params["halves"], axis=-1)

    @property
    def endpoints(self) -> tuple[mx.array, mx.array]:
        m, h = self.params["means"], self.params["halves"]
        return m - h, m + h

    def one_up_sh_degree(self) -> None:
        self.active_sh_degree = min(self.active_sh_degree + 1, self.sh_degree)

    # --------------------------------------------------------------- rendering
    def render_params(self, params: dict[str, mx.array], camera: Camera, background=None):
        """Differentiable render of an explicit parameter dict."""
        sh = mx.concatenate([params["sh_dc"], params["sh_rest"]], axis=1)
        colors = segment_colors(camera, params["means"], sh, self.active_sh_degree)
        return render_spaghetti(
            camera,
            params["means"],
            params["halves"],
            params["quats"],
            mx.exp(params["scales"]),
            self.density(params),
            colors,
            background=background,
        )

    def render(self, camera: Camera, background: mx.array | None = None) -> dict[str, mx.array]:
        return self.render_params(self.params, camera, background)

    # ----------------------------------------------------- density control ops
    def append(self, new: dict[str, mx.array]) -> None:
        self.params = {k: mx.concatenate([v, new[k]], axis=0) for k, v in self.params.items()}

    def select(self, keep: mx.array) -> None:
        self.params = {k: v[keep] for k, v in self.params.items()}

    def split_or_clone(self, idx: mx.array, split_min_length: mx.array) -> dict[str, mx.array]:
        """Duplicate rows ``idx`` without changing the rendered image.

        Rows longer than ``split_min_length`` are split at their midpoint (the
        row keeps one half, the returned copy is the other); shorter rows are
        cloned with half the optical depth each. Optical depth is additive
        along rays, so both are exact. Updates rows ``idx`` in place and
        returns the new rows to place elsewhere.
        """
        p = self.params
        rows = {k: v[idx] for k, v in p.items()}
        split = (2.0 * mx.linalg.norm(rows["halves"], axis=-1) > split_min_length)[:, None]
        h = rows["halves"]
        first = mx.where(split, rows["means"] - 0.5 * h, rows["means"])
        second = mx.where(split, rows["means"] + 0.5 * h, rows["means"])
        halves = mx.where(split, 0.5 * h, h)
        # Clone: tau -> tau / 2, i.e. 1 - o -> sqrt(1 - o).
        o = mx.sigmoid(rows["opacities"])
        cloned = mx.log(mx.maximum(1.0 - mx.sqrt(mx.maximum(1.0 - o, 1e-12)), 1e-12))
        cloned = cloned - mx.log(mx.maximum(mx.sqrt(mx.maximum(1.0 - o, 1e-12)), 1e-12))
        opac = mx.where(split[:, 0], rows["opacities"], cloned)

        updated = {**rows, "means": first, "halves": halves, "opacities": opac}
        new = {**rows, "means": second, "halves": halves, "opacities": opac}
        for k in p:
            p[k] = p[k].at[idx].add(updated[k] - p[k][idx])
        return new

    def copy(self) -> SpaghettiModel:
        model = SpaghettiModel({k: mx.array(v) for k, v in self.params.items()}, self.sh_degree)
        model.active_sh_degree = self.active_sh_degree
        return model

    # ---------------------------------------------------------------- polylines
    def snap_endpoints(self, radius: float | mx.array) -> int:
        """Merge nearby endpoints of different segments into shared joints.

        Every endpoint whose nearest other-segment endpoint lies within
        ``radius`` (scalar, or per-segment) is moved, together with that
        neighbor, to their midpoint. Returns the number of joints created.
        """
        a, b = self.endpoints
        pts = np.concatenate([np.array(a), np.array(b)])
        n = self.num_segments
        owner = np.concatenate([np.arange(n), np.arange(n)])
        r = np.broadcast_to(np.asarray(radius, dtype=np.float64), (n,))
        r = np.concatenate([r, r])
        nbr = nearest_other_within(pts, owner, r)
        k = np.arange(len(pts))
        safe = np.maximum(nbr, 0)
        mutual = (nbr >= 0) & (nbr[safe] == k) & (k < nbr)
        i, j = np.nonzero(mutual)[0], nbr[mutual]
        mid = 0.5 * (pts[i] + pts[j])
        pts[i], pts[j] = mid, mid
        a, b = pts[:n], pts[n:]
        self.params["means"] = mx.array(0.5 * (a + b), dtype=mx.float32)
        self.params["halves"] = mx.array(0.5 * (b - a), dtype=mx.float32)
        return int(len(i))

    def polylines(self, tolerance: float) -> list[np.ndarray]:
        """Chain segments that share endpoints (within ``tolerance``) into
        polylines; returns a list of ``(K, 3)`` vertex arrays."""
        a, b = (np.array(x) for x in self.endpoints)
        n = self.num_segments
        pts = np.concatenate([a, b])
        q = np.round(pts / max(tolerance, 1e-12)).astype(np.int64)
        keys = {}
        vertex = np.empty(2 * n, dtype=np.int64)
        for k, key in enumerate(map(tuple, q)):
            vertex[k] = keys.setdefault(key, len(keys))
        va, vb = vertex[:n], vertex[n:]
        positions = np.zeros((len(keys), 3))
        np.add.at(positions, vertex, pts)
        positions /= np.bincount(vertex, minlength=len(keys))[:, None]
        adj: dict[int, list[int]] = {}
        for s, (u, w) in enumerate(zip(va, vb)):
            adj.setdefault(u, []).append(s)
            adj.setdefault(w, []).append(s)
        used = np.zeros(n, dtype=bool)
        lines = []
        # Start walks at chain ends (degree != 2) first, then close remaining loops.
        starts = [v for v, segs in adj.items() if len(segs) != 2] + list(adj)
        for v0 in starts:
            for s0 in adj[v0]:
                if used[s0]:
                    continue
                chain, v, s = [v0], v0, s0
                while s is not None and not used[s]:
                    used[s] = True
                    v = vb[s] if va[s] == v else va[s]
                    chain.append(v)
                    nxt = [t for t in adj[v] if not used[t]]
                    s = nxt[0] if len(adj[v]) == 2 and nxt else None
                lines.append(positions[chain])
        return lines

    # ----------------------------------------------------------------- PLY IO
    def save_ply(self, path: str) -> None:
        """Save as a PLY vertex list with spaghetti-specific properties."""
        from ...io import save_ply

        p = self.params
        n = self.num_segments
        extra = {}
        for name, key, width in (
            ("h", "halves", 3),
            ("scale", "scales", 3),
            ("rot", "quats", 4),
        ):
            for c in range(width):
                extra[f"{name}_{c}"] = p[key][:, c]
        extra["opacity"] = p["opacities"]
        for c in range(3):
            extra[f"f_dc_{c}"] = p["sh_dc"][:, 0, c]
        rest = p["sh_rest"].transpose(0, 2, 1).reshape(n, -1)
        for c in range(rest.shape[1]):
            extra[f"f_rest_{c}"] = rest[:, c]
        save_ply(path, p["means"], extra=extra)

    @classmethod
    def load_ply(cls, path: str) -> SpaghettiModel:
        from ...io import load_ply

        ply = load_ply(path)
        props = ply.extra
        n = ply.verts.shape[0]

        def stack(prefix, width):
            return mx.stack([props[f"{prefix}_{c}"] for c in range(width)], axis=-1)

        n_rest = sum(1 for k in props if k.startswith("f_rest_"))
        k = n_rest // 3 + 1
        sh_degree = int(round(math.sqrt(k))) - 1
        if n_rest:
            rest = stack("f_rest", n_rest).reshape(n, 3, k - 1).transpose(0, 2, 1)
        else:
            rest = mx.zeros((n, 0, 3))
        params = {
            "means": ply.verts,
            "halves": stack("h", 3),
            "quats": stack("rot", 4),
            "scales": stack("scale", 3),
            "opacities": props["opacity"],
            "sh_dc": stack("f_dc", 3)[:, None, :],
            "sh_rest": rest,
        }
        model = cls({k: mx.array(v, dtype=mx.float32) for k, v in params.items()}, sh_degree)
        model.active_sh_degree = sh_degree
        return model

from_points(points, colors=None, sh_degree=3, initial_opacity=0.1, initial_length=2.0, max_scale=None, seed=0) classmethod

Short segments at points in random directions.

Kernel scales come from nearest-neighbor spacing; each segment is initial_length kernel widths long (a nonzero length is needed: at exactly zero the gradient with respect to it vanishes by symmetry).

Source code in src/mlx3d/splatting/spaghetti/model.py
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
@classmethod
def from_points(
    cls,
    points: mx.array,
    colors: mx.array | None = None,
    sh_degree: int = 3,
    initial_opacity: float = 0.1,
    initial_length: float = 2.0,
    max_scale: float | None = None,
    seed: int = 0,
) -> SpaghettiModel:
    """Short segments at ``points`` in random directions.

    Kernel scales come from nearest-neighbor spacing; each segment is
    ``initial_length`` kernel widths long (a nonzero length is needed: at
    exactly zero the gradient with respect to it vanishes by symmetry).
    """
    from ...ops import knn_points

    points = mx.array(points, dtype=mx.float32)
    n = points.shape[0]
    if n > 20_000:  # a reference subsample keeps the k-NN cheap for big clouds
        pick = np.random.default_rng(seed).choice(n, 20_000, replace=False)
        ref = points[mx.array(pick)]
    else:
        ref = points
    dists, _ = knn_points(points, ref, K=4)
    spacing = mx.sqrt(mx.maximum(mx.mean(dists[:, 1:], axis=-1), 1e-14))
    if max_scale is not None:
        spacing = mx.minimum(spacing, max_scale)
    rng = np.random.default_rng(seed)
    dirs = rng.normal(size=(n, 3))
    dirs /= np.linalg.norm(dirs, axis=1, keepdims=True)
    quats = rng.normal(size=(n, 4))
    colors = mx.full((n, 3), 0.5) if colors is None else mx.array(colors, dtype=mx.float32)
    k = num_sh_bases(sh_degree)
    params = {
        "means": points,
        "halves": mx.array(dirs, dtype=mx.float32) * (0.5 * initial_length * spacing[:, None]),
        "quats": mx.array(
            quats / np.linalg.norm(quats, axis=1, keepdims=True), dtype=mx.float32
        ),
        "scales": mx.broadcast_to(mx.log(spacing)[:, None], (n, 3)),
        "opacities": mx.full((n,), _logit(initial_opacity)),
        "sh_dc": rgb_to_sh(colors)[:, None, :],
        "sh_rest": mx.zeros((n, k - 1, 3)),
    }
    return cls(params, sh_degree)

from_gaussians(gaussians, length_frac=0.001) classmethod

Lift a :class:~mlx3d.splatting.GaussianModel to (near-)zero-length segments along each Gaussian's major axis — the representation is a strict superset of 3DGS, so this is a valid starting point.

Source code in src/mlx3d/splatting/spaghetti/model.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
@classmethod
def from_gaussians(cls, gaussians, length_frac: float = 1e-3) -> SpaghettiModel:
    """Lift a :class:`~mlx3d.splatting.GaussianModel` to (near-)zero-length
    segments along each Gaussian's major axis — the representation is a
    strict superset of 3DGS, so this is a valid starting point."""
    from ...transforms import quaternion_to_matrix

    p = gaussians.params
    R = quaternion_to_matrix(p["quats"] / mx.linalg.norm(p["quats"], axis=-1, keepdims=True))
    major = mx.argmax(p["scales"], axis=-1)
    axis = mx.take_along_axis(R, major[:, None, None].astype(mx.int32), axis=2)[..., 0]
    halves = axis * (length_frac * mx.exp(mx.max(p["scales"], axis=-1)))[:, None]
    params = {
        "means": p["means"],
        "halves": halves,
        "quats": p["quats"],
        "scales": p["scales"],
        "opacities": p["opacities"],
        "sh_dc": p["sh_dc"],
        "sh_rest": p["sh_rest"],
    }
    model = cls({k: mx.array(v) for k, v in params.items()}, gaussians.sh_degree)
    model.active_sh_degree = gaussians.active_sh_degree
    return model

density(params) staticmethod

Density rho (per unit length) from the opacity / scale parameters.

Source code in src/mlx3d/splatting/spaghetti/model.py
126
127
128
129
130
131
@staticmethod
def density(params: dict[str, mx.array]) -> mx.array:
    """Density ``rho`` (per unit length) from the opacity / scale parameters."""
    o = mx.sigmoid(params["opacities"])
    sigma = mx.exp(mx.mean(params["scales"], axis=-1))
    return -mx.log(mx.maximum(1.0 - o, 1e-6)) / (_SQRT_2PI * sigma)

render_params(params, camera, background=None)

Differentiable render of an explicit parameter dict.

Source code in src/mlx3d/splatting/spaghetti/model.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def render_params(self, params: dict[str, mx.array], camera: Camera, background=None):
    """Differentiable render of an explicit parameter dict."""
    sh = mx.concatenate([params["sh_dc"], params["sh_rest"]], axis=1)
    colors = segment_colors(camera, params["means"], sh, self.active_sh_degree)
    return render_spaghetti(
        camera,
        params["means"],
        params["halves"],
        params["quats"],
        mx.exp(params["scales"]),
        self.density(params),
        colors,
        background=background,
    )

split_or_clone(idx, split_min_length)

Duplicate rows idx without changing the rendered image.

Rows longer than split_min_length are split at their midpoint (the row keeps one half, the returned copy is the other); shorter rows are cloned with half the optical depth each. Optical depth is additive along rays, so both are exact. Updates rows idx in place and returns the new rows to place elsewhere.

Source code in src/mlx3d/splatting/spaghetti/model.py
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
def split_or_clone(self, idx: mx.array, split_min_length: mx.array) -> dict[str, mx.array]:
    """Duplicate rows ``idx`` without changing the rendered image.

    Rows longer than ``split_min_length`` are split at their midpoint (the
    row keeps one half, the returned copy is the other); shorter rows are
    cloned with half the optical depth each. Optical depth is additive
    along rays, so both are exact. Updates rows ``idx`` in place and
    returns the new rows to place elsewhere.
    """
    p = self.params
    rows = {k: v[idx] for k, v in p.items()}
    split = (2.0 * mx.linalg.norm(rows["halves"], axis=-1) > split_min_length)[:, None]
    h = rows["halves"]
    first = mx.where(split, rows["means"] - 0.5 * h, rows["means"])
    second = mx.where(split, rows["means"] + 0.5 * h, rows["means"])
    halves = mx.where(split, 0.5 * h, h)
    # Clone: tau -> tau / 2, i.e. 1 - o -> sqrt(1 - o).
    o = mx.sigmoid(rows["opacities"])
    cloned = mx.log(mx.maximum(1.0 - mx.sqrt(mx.maximum(1.0 - o, 1e-12)), 1e-12))
    cloned = cloned - mx.log(mx.maximum(mx.sqrt(mx.maximum(1.0 - o, 1e-12)), 1e-12))
    opac = mx.where(split[:, 0], rows["opacities"], cloned)

    updated = {**rows, "means": first, "halves": halves, "opacities": opac}
    new = {**rows, "means": second, "halves": halves, "opacities": opac}
    for k in p:
        p[k] = p[k].at[idx].add(updated[k] - p[k][idx])
    return new

snap_endpoints(radius)

Merge nearby endpoints of different segments into shared joints.

Every endpoint whose nearest other-segment endpoint lies within radius (scalar, or per-segment) is moved, together with that neighbor, to their midpoint. Returns the number of joints created.

Source code in src/mlx3d/splatting/spaghetti/model.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def snap_endpoints(self, radius: float | mx.array) -> int:
    """Merge nearby endpoints of different segments into shared joints.

    Every endpoint whose nearest other-segment endpoint lies within
    ``radius`` (scalar, or per-segment) is moved, together with that
    neighbor, to their midpoint. Returns the number of joints created.
    """
    a, b = self.endpoints
    pts = np.concatenate([np.array(a), np.array(b)])
    n = self.num_segments
    owner = np.concatenate([np.arange(n), np.arange(n)])
    r = np.broadcast_to(np.asarray(radius, dtype=np.float64), (n,))
    r = np.concatenate([r, r])
    nbr = nearest_other_within(pts, owner, r)
    k = np.arange(len(pts))
    safe = np.maximum(nbr, 0)
    mutual = (nbr >= 0) & (nbr[safe] == k) & (k < nbr)
    i, j = np.nonzero(mutual)[0], nbr[mutual]
    mid = 0.5 * (pts[i] + pts[j])
    pts[i], pts[j] = mid, mid
    a, b = pts[:n], pts[n:]
    self.params["means"] = mx.array(0.5 * (a + b), dtype=mx.float32)
    self.params["halves"] = mx.array(0.5 * (b - a), dtype=mx.float32)
    return int(len(i))

polylines(tolerance)

Chain segments that share endpoints (within tolerance) into polylines; returns a list of (K, 3) vertex arrays.

Source code in src/mlx3d/splatting/spaghetti/model.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def polylines(self, tolerance: float) -> list[np.ndarray]:
    """Chain segments that share endpoints (within ``tolerance``) into
    polylines; returns a list of ``(K, 3)`` vertex arrays."""
    a, b = (np.array(x) for x in self.endpoints)
    n = self.num_segments
    pts = np.concatenate([a, b])
    q = np.round(pts / max(tolerance, 1e-12)).astype(np.int64)
    keys = {}
    vertex = np.empty(2 * n, dtype=np.int64)
    for k, key in enumerate(map(tuple, q)):
        vertex[k] = keys.setdefault(key, len(keys))
    va, vb = vertex[:n], vertex[n:]
    positions = np.zeros((len(keys), 3))
    np.add.at(positions, vertex, pts)
    positions /= np.bincount(vertex, minlength=len(keys))[:, None]
    adj: dict[int, list[int]] = {}
    for s, (u, w) in enumerate(zip(va, vb)):
        adj.setdefault(u, []).append(s)
        adj.setdefault(w, []).append(s)
    used = np.zeros(n, dtype=bool)
    lines = []
    # Start walks at chain ends (degree != 2) first, then close remaining loops.
    starts = [v for v, segs in adj.items() if len(segs) != 2] + list(adj)
    for v0 in starts:
        for s0 in adj[v0]:
            if used[s0]:
                continue
            chain, v, s = [v0], v0, s0
            while s is not None and not used[s]:
                used[s] = True
                v = vb[s] if va[s] == v else va[s]
                chain.append(v)
                nxt = [t for t in adj[v] if not used[t]]
                s = nxt[0] if len(adj[v]) == 2 and nxt else None
            lines.append(positions[chain])
    return lines

save_ply(path)

Save as a PLY vertex list with spaghetti-specific properties.

Source code in src/mlx3d/splatting/spaghetti/model.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def save_ply(self, path: str) -> None:
    """Save as a PLY vertex list with spaghetti-specific properties."""
    from ...io import save_ply

    p = self.params
    n = self.num_segments
    extra = {}
    for name, key, width in (
        ("h", "halves", 3),
        ("scale", "scales", 3),
        ("rot", "quats", 4),
    ):
        for c in range(width):
            extra[f"{name}_{c}"] = p[key][:, c]
    extra["opacity"] = p["opacities"]
    for c in range(3):
        extra[f"f_dc_{c}"] = p["sh_dc"][:, 0, c]
    rest = p["sh_rest"].transpose(0, 2, 1).reshape(n, -1)
    for c in range(rest.shape[1]):
        extra[f"f_rest_{c}"] = rest[:, c]
    save_ply(path, p["means"], extra=extra)

SegmentProjection

Bases: dict

Per-segment camera-space quantities (a dict of (N, ...) arrays).

Keys: W (N, 3, 3) whitening map, a / v (N, 3) whitened start / direction, rho (N,); for tile binning means2d (N, 2) projected midpoints, radii (N,) pixel radii bounding the footprint (0 = culled) and depths (N,) midpoint depths; and conics (N, 3), the (a, b, c) of a pixel-space ellipse x^T C x <= 1 around the projected midpoint that contains the whole footprint.

Source code in src/mlx3d/splatting/spaghetti/projection.py
72
73
74
75
76
77
78
79
80
81
class SegmentProjection(dict):
    """Per-segment camera-space quantities (a dict of ``(N, ...)`` arrays).

    Keys: ``W`` (N, 3, 3) whitening map, ``a`` / ``v`` (N, 3) whitened start /
    direction, ``rho`` (N,); for tile binning ``means2d`` (N, 2) projected
    midpoints, ``radii`` (N,) pixel radii bounding the footprint (0 = culled)
    and ``depths`` (N,) midpoint depths; and ``conics`` (N, 3), the
    ``(a, b, c)`` of a pixel-space ellipse ``x^T C x <= 1`` around the
    projected midpoint that contains the whole footprint.
    """

SpaghettiTrainer

Optimizes a :class:SpaghettiModel against posed images.

Source code in src/mlx3d/splatting/spaghetti/trainer.py
 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
class SpaghettiTrainer:
    """Optimizes a :class:`SpaghettiModel` against posed images."""

    def __init__(
        self,
        model: SpaghettiModel,
        config: SpaghettiTrainerConfig | None = None,
        scene_extent: float = 1.0,
    ):
        self.model = model
        self.config = config or SpaghettiTrainerConfig()
        self.scene_extent = float(scene_extent)
        self.step_count = 0
        self._pairs: mx.array | None = None
        c = self.config
        means_lr = optim.exponential_decay(
            c.lr_means * self.scene_extent,
            (c.lr_means_final / c.lr_means) ** (1.0 / max(c.lr_means_max_steps, 1)),
        )
        lrs = {
            "means": means_lr,
            "halves": c.lr_halves * self.scene_extent,
            "scales": c.lr_scales,
            "quats": c.lr_quats,
            "opacities": c.lr_opacities,
            "sh_dc": c.lr_sh_dc,
            "sh_rest": c.lr_sh_rest,
        }
        self.optimizers = {k: optim.Adam(learning_rate=lr, eps=1e-15) for k, lr in lrs.items()}

    # ------------------------------------------------------------------ loss
    def _attraction(self, params: dict[str, mx.array]) -> mx.array:
        """Mean squared distance between paired nearby endpoints of different
        segments. Pairs are ``(segment, side, segment, side)`` rows with side
        -1 / +1 for ``m - h`` / ``m + h``; they are refreshed every
        ``connect_every`` steps and dropped whenever densification changes
        the rows."""
        pairs = self._pairs
        if pairs is None or pairs.shape[0] == 0:
            return mx.array(0.0)
        m, h = params["means"], params["halves"]

        def end(seg, side):
            return m[seg] + side[:, None].astype(m.dtype) * h[seg]

        diff = end(pairs[:, 0], pairs[:, 1]) - end(pairs[:, 2], pairs[:, 3])
        return mx.mean(mx.sum(diff * diff, axis=-1))

    def _refresh_pairs(self) -> None:
        from .model import nearest_other_within

        n = self.model.num_segments
        a, b = self.model.endpoints
        pts = np.concatenate([np.array(a), np.array(b)])
        owner = np.concatenate([np.arange(n), np.arange(n)])
        width = np.array(mx.mean(self.model.scales_act, axis=-1))
        radius = self.config.connect_radius * np.concatenate([width, width])
        nbr = nearest_other_within(pts, owner, radius)
        i = np.nonzero(nbr >= 0)[0]
        j = nbr[i]
        side = np.where(np.arange(2 * n) < n, -1, 1)
        rows = np.stack([i % n, side[i], j % n, side[j]], axis=1)
        self._pairs = mx.array(rows.astype(np.int32))

    def loss(self, params, camera: Camera, target: mx.array, background: mx.array):
        c = self.config
        out = self.model.render_params(params, camera, background)
        img = out["image"]
        loss = (1.0 - c.lambda_dssim) * mx.abs(img - target).mean()
        loss = loss + c.lambda_dssim * (1.0 - ssim(img, target))
        if c.lambda_opacity > 0:
            loss = loss + c.lambda_opacity * mx.mean(mx.sigmoid(params["opacities"]))
        if c.lambda_scale > 0:
            loss = loss + c.lambda_scale * mx.mean(mx.exp(params["scales"]))
        if c.lambda_connect > 0 and self.step_count >= c.connect_from:
            loss = loss + c.lambda_connect * self._attraction(params) / self.scene_extent**2
        return loss, img

    # ------------------------------------------------------------------ step
    def step(self, camera: Camera, target: mx.array) -> dict[str, object]:
        """One optimization step on one view; returns logging info."""
        self.step_count += 1
        c = self.config
        bg = mx.ones((3,)) if c.white_background else mx.zeros((3,))
        if c.lambda_connect > 0 and self.step_count >= c.connect_from:
            if self._pairs is None or self.step_count % c.connect_every == 0:
                self._refresh_pairs()

        (loss, _), grads = mx.value_and_grad(lambda p: self.loss(p, camera, target, bg))(
            self.model.params
        )
        for k, opt in self.optimizers.items():
            self.model.params[k] = opt.apply_gradients({k: grads[k]}, {k: self.model.params[k]})[k]
        del grads
        self._add_noise()
        mx.eval(self.model.params)

        density = None
        if (
            c.densify_from < self.step_count <= c.densify_until
            and self.step_count % c.densify_every == 0
        ):
            density = self._relocate_and_grow()
            self._pairs = None  # rows moved: endpoint pairs are stale

        if self.step_count % c.sh_increase_every == 0:
            self.model.one_up_sh_degree()
        return {
            "loss": float(loss),
            "num_segments": self.model.num_segments,
            "step": self.step_count,
            "density": density,
        }

    def _add_noise(self) -> None:
        """MCMC exploration: Sigma-shaped position noise, gated by 3DGS-MCMC's
        ``sigmoid(-100 (o - min_opacity))``: strong for near-dead segments,
        negligible for ones that are contributing."""
        c = self.config
        if c.noise_lr <= 0:
            return
        p = self.model.params
        lr = float(self.optimizers["means"].learning_rate)
        o = mx.sigmoid(p["opacities"])
        gate = mx.sigmoid(-100.0 * (o - c.min_opacity))
        # As in 3DGS-MCMC, the noise is multiplied by the kernel covariance
        # Sigma = R S^2 R^T itself (not its square root).
        R = quaternion_to_matrix(p["quats"] / mx.linalg.norm(p["quats"], axis=-1, keepdims=True))
        eps = mx.random.normal(p["means"].shape)
        local = (mx.swapaxes(R, -1, -2) @ eps[..., None])[..., 0] * mx.exp(2.0 * p["scales"])
        noise = (R @ local[..., None])[..., 0] * (gate * c.noise_lr * lr)[:, None]
        p["means"] = p["means"] + mx.stop_gradient(noise)

    # ------------------------------------------------------- density control
    def _sample_sources(self, k: int, exclude: mx.array | None = None) -> mx.array:
        """``k`` distinct live segments sampled proportionally to opacity
        (Gumbel top-k)."""
        o = self.model.opacities_act
        logits = mx.log(mx.maximum(o, 1e-12))
        if exclude is not None:
            logits = mx.where(exclude, -1e30, logits)
        gumbel = -mx.log(-mx.log(mx.random.uniform(shape=o.shape, low=1e-12, high=1.0)))
        return mx.argpartition(-(logits + gumbel), kth=k - 1)[:k]

    def _relocate_and_grow(self) -> dict[str, int]:
        c = self.config
        model = self.model
        n = model.num_segments
        width = mx.mean(model.scales_act, axis=-1)
        dead = model.opacities_act < c.min_opacity
        n_dead = int(dead.sum())
        relocated = 0
        if 0 < n_dead < n:
            dst = mx.argpartition(-dead.astype(mx.float32), kth=n_dead - 1)[:n_dead]
            src = self._sample_sources(n_dead, exclude=dead)
            new = model.split_or_clone(src, c.split_ratio * width[src])
            for k, v in model.params.items():
                model.params[k] = v.at[dst].add(new[k] - v[dst])
            self._reset_moments(mx.concatenate([src, dst]))
            relocated = n_dead

        n_add = min(c.max_segments - n, int(c.grow_rate * n))
        if n_add > 0:
            src = self._sample_sources(n_add)
            width = mx.mean(model.scales_act, axis=-1)
            new = model.split_or_clone(src, c.split_ratio * width[src])
            model.append(new)
            self._grow_moments(n_add)
            self._reset_moments(src)
        mx.eval(model.params)
        return {"relocated": relocated, "added": max(n_add, 0)}

    def _reset_moments(self, rows: mx.array) -> None:
        for name, opt in self.optimizers.items():
            state = opt.state.get(name)
            if isinstance(state, dict):
                for slot in ("m", "v"):
                    if slot in state:
                        state[slot] = state[slot].at[rows].multiply(0.0)

    def _grow_moments(self, count: int) -> None:
        for name, opt in self.optimizers.items():
            state = opt.state.get(name)
            if isinstance(state, dict):
                for slot in ("m", "v"):
                    if slot in state:
                        old = state[slot]
                        pad = mx.zeros((count, *old.shape[1:]), dtype=old.dtype)
                        state[slot] = mx.concatenate([old, pad], axis=0)

    def finalize_polylines(self, radius_widths: float | None = None) -> int:
        """Snap nearby endpoints into shared joints (the paper's merging step);
        returns the number of joints created."""
        r = self.config.connect_radius if radius_widths is None else radius_widths
        width = np.array(mx.mean(self.model.scales_act, axis=-1))
        return self.model.snap_endpoints(r * width)

step(camera, target)

One optimization step on one view; returns logging info.

Source code in src/mlx3d/splatting/spaghetti/trainer.py
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
def step(self, camera: Camera, target: mx.array) -> dict[str, object]:
    """One optimization step on one view; returns logging info."""
    self.step_count += 1
    c = self.config
    bg = mx.ones((3,)) if c.white_background else mx.zeros((3,))
    if c.lambda_connect > 0 and self.step_count >= c.connect_from:
        if self._pairs is None or self.step_count % c.connect_every == 0:
            self._refresh_pairs()

    (loss, _), grads = mx.value_and_grad(lambda p: self.loss(p, camera, target, bg))(
        self.model.params
    )
    for k, opt in self.optimizers.items():
        self.model.params[k] = opt.apply_gradients({k: grads[k]}, {k: self.model.params[k]})[k]
    del grads
    self._add_noise()
    mx.eval(self.model.params)

    density = None
    if (
        c.densify_from < self.step_count <= c.densify_until
        and self.step_count % c.densify_every == 0
    ):
        density = self._relocate_and_grow()
        self._pairs = None  # rows moved: endpoint pairs are stale

    if self.step_count % c.sh_increase_every == 0:
        self.model.one_up_sh_degree()
    return {
        "loss": float(loss),
        "num_segments": self.model.num_segments,
        "step": self.step_count,
        "density": density,
    }

finalize_polylines(radius_widths=None)

Snap nearby endpoints into shared joints (the paper's merging step); returns the number of joints created.

Source code in src/mlx3d/splatting/spaghetti/trainer.py
260
261
262
263
264
265
def finalize_polylines(self, radius_widths: float | None = None) -> int:
    """Snap nearby endpoints into shared joints (the paper's merging step);
    returns the number of joints created."""
    r = self.config.connect_radius if radius_widths is None else radius_widths
    width = np.array(mx.mean(self.model.scales_act, axis=-1))
    return self.model.snap_endpoints(r * width)

SpaghettiTrainerConfig dataclass

Source code in src/mlx3d/splatting/spaghetti/trainer.py
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
@dataclass
class SpaghettiTrainerConfig:
    lr_means: float = 1.6e-4
    lr_means_final: float = 1.6e-6
    lr_means_max_steps: int = 30_000
    lr_halves: float = 1.6e-4
    """Half-vector learning rate (scaled by the scene extent, like means)."""
    lr_scales: float = 5e-3
    lr_quats: float = 1e-3
    lr_opacities: float = 5e-2
    lr_sh_dc: float = 2.5e-3
    lr_sh_rest: float = 2.5e-3 / 20.0
    lambda_dssim: float = 0.2
    lambda_opacity: float = 0.01
    """MCMC regularizer: mean peak opacity (encourages few, opaque segments)."""
    lambda_scale: float = 0.01
    """MCMC regularizer: mean kernel scale (encourages thin kernels)."""
    # Density control.
    max_segments: int = 200_000
    densify_from: int = 500
    densify_until: int = 25_000
    densify_every: int = 100
    grow_rate: float = 0.05
    min_opacity: float = 0.005
    split_ratio: float = 2.0
    """Duplicated segments longer than this many kernel widths are split."""
    noise_lr: float = 5e5
    # Polyline formation.
    lambda_connect: float = 0.0
    """Endpoint attraction weight (applied from ``connect_from``)."""
    connect_from: int = 25_000
    connect_radius: float = 3.0
    """Endpoints closer than this many kernel widths attract each other."""
    connect_every: int = 100
    sh_increase_every: int = 1000
    white_background: bool = False

lr_halves = 0.00016 class-attribute instance-attribute

Half-vector learning rate (scaled by the scene extent, like means).

lambda_opacity = 0.01 class-attribute instance-attribute

MCMC regularizer: mean peak opacity (encourages few, opaque segments).

lambda_scale = 0.01 class-attribute instance-attribute

MCMC regularizer: mean kernel scale (encourages thin kernels).

split_ratio = 2.0 class-attribute instance-attribute

Duplicated segments longer than this many kernel widths are split.

lambda_connect = 0.0 class-attribute instance-attribute

Endpoint attraction weight (applied from connect_from).

connect_radius = 3.0 class-attribute instance-attribute

Endpoints closer than this many kernel widths attract each other.

project_segments(camera, means, halves, quats, scales, rho)

Map world-space segments into whitened camera space (differentiable).

Parameters:

Name Type Description Default
means array

(N, 3) segment midpoints.

required
halves array

(N, 3) half-vectors: the segment runs from m - h to m + h.

required
quats array

(N, 4) kernel rotations (w, x, y, z).

required
scales array

(N, 3) kernel standard deviations (activated).

required
rho array

(N,) densities (activated).

required
Source code in src/mlx3d/splatting/spaghetti/projection.py
 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
def project_segments(
    camera: Camera,
    means: mx.array,
    halves: mx.array,
    quats: mx.array,
    scales: mx.array,
    rho: mx.array,
) -> SegmentProjection:
    """Map world-space segments into whitened camera space (differentiable).

    Args:
        means: (N, 3) segment midpoints.
        halves: (N, 3) half-vectors: the segment runs from ``m - h`` to ``m + h``.
        quats: (N, 4) kernel rotations (w, x, y, z).
        scales: (N, 3) kernel standard deviations (activated).
        rho: (N,) densities (activated).
    """
    if camera.distortion is not None or camera.orthographic:
        raise ValueError("Spaghetti splatting supports undistorted pinhole cameras.")
    R_cam = mx.array(camera.R).astype(mx.float32)
    t_cam = mx.array(camera.t).astype(mx.float32)

    start = (means - halves) @ R_cam.T + t_cam  # camera space
    end = (means + halves) @ R_cam.T + t_cam
    mid = (start + end) * 0.5

    # Q = Sigma^-1 / 2 = W^T W with W = S^-1 Rc^T / sqrt(2), Rc = R_cam R_kernel.
    R_kernel = quaternion_to_matrix(quats / mx.linalg.norm(quats, axis=-1, keepdims=True))
    Rc = R_cam[None] @ R_kernel
    W = mx.swapaxes(Rc, -1, -2) / (math.sqrt(2.0) * scales[..., None])
    a_w = (W @ start[..., None])[..., 0]
    v_w = (W @ (end - start)[..., None])[..., 0]

    # Screen footprint: the projected segment swept by the kernel's cut-off
    # radius (a capsule), bounded by an ellipse. The cut-off is opacity-aware:
    # where the peak optical depth falls below 1/255 (the compositing
    # threshold), so dense thin strands keep their visible tails.
    fx, fy, cx, cy = camera.fx, camera.fy, camera.cx, camera.cy

    def to_pixels(p):
        z = mx.maximum(p[:, 2], 1e-6)
        return mx.stack([fx * p[:, 0] / z + cx, fy * p[:, 1] / z + cy], axis=-1)

    sg = mx.stop_gradient
    s_max = sg(mx.max(scales, axis=-1))
    # Peak optical depth over all rays: a ray along the segment also crosses
    # its full length.
    seg_len = mx.linalg.norm(sg(end - start), axis=-1)
    tau_peak = sg(rho) * (math.sqrt(2.0 * math.pi) * s_max + seg_len)
    sigmas = mx.sqrt(2.0 * mx.log(mx.maximum(255.0 * tau_peak, math.e)))
    sigmas = mx.clip(sigmas, MIN_FOOTPRINT_SIGMAS, MAX_FOOTPRINT_SIGMAS)
    p0, p1 = to_pixels(sg(start)), to_pixels(sg(end))
    mid_px = (p0 + p1) * 0.5
    axis = p1 - p0
    length = mx.linalg.norm(axis, axis=-1)
    half_len = length * 0.5
    z_min = mx.maximum(mx.minimum(sg(start[:, 2]), sg(end[:, 2])), 1e-6)
    kernel_px = sigmas * max(fx, fy) * s_max / z_min
    radius = mx.ceil(half_len + kernel_px)

    # Ellipse containing the capsule: semi-axes sqrt(2) (h + r) along the
    # segment and sqrt(2) r across it.
    u = mx.where(
        length[:, None] > 1e-6, axis / mx.maximum(length, 1e-6)[:, None], mx.array([1.0, 0.0])
    )
    inv_a2 = 1.0 / (2.0 * (half_len + kernel_px) ** 2)
    inv_b2 = 1.0 / (2.0 * kernel_px**2)
    ux, uy = u[:, 0], u[:, 1]
    conics = mx.stack(
        [
            ux * ux * inv_a2 + uy * uy * inv_b2,
            ux * uy * (inv_a2 - inv_b2),
            uy * uy * inv_a2 + ux * ux * inv_b2,
        ],
        axis=-1,
    )

    near = camera.znear
    visible = (start[:, 2] > near) & (end[:, 2] > near)
    on_screen = (
        (mid_px[:, 0] + radius > 0)
        & (mid_px[:, 0] - radius < camera.width)
        & (mid_px[:, 1] + radius > 0)
        & (mid_px[:, 1] - radius < camera.height)
    )
    radii = mx.where(visible & on_screen, radius, 0.0).astype(mx.int32)

    return SegmentProjection(
        W=W,
        a=a_w,
        v=v_w,
        rho=rho,
        means2d=mid_px,
        radii=radii,
        depths=mx.stop_gradient(mid[:, 2]),
        conics=conics,
    )

segment_optical_depth(e, a, v, rho)

Closed-form optical depth tau (pure MLX, differentiable).

Parameters:

Name Type Description Default
e array

(..., 3) whitened ray directions W d.

required
a array

(..., 3) whitened segment start.

required
v array

(..., 3) whitened segment direction (end minus start).

required
rho array

(...) densities.

required
Source code in src/mlx3d/splatting/spaghetti/projection.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def segment_optical_depth(e: mx.array, a: mx.array, v: mx.array, rho: mx.array) -> mx.array:
    """Closed-form optical depth ``tau`` (pure MLX, differentiable).

    Args:
        e: ``(..., 3)`` whitened ray directions ``W d``.
        a: ``(..., 3)`` whitened segment start.
        v: ``(..., 3)`` whitened segment direction (end minus start).
        rho: ``(...)`` densities.
    """
    n = mx.sum(e * e, axis=-1, keepdims=True)
    y = -(a - e * mx.sum(e * a, axis=-1, keepdims=True) / n)
    z = v - e * mx.sum(e * v, axis=-1, keepdims=True) / n
    k2 = mx.sum(z * z, axis=-1)
    is_line = k2 > POINT_EPS * POINT_EPS
    k2_safe = mx.where(is_line, k2, 1.0)
    k = mx.sqrt(k2_safe)
    ub = mx.where(is_line, mx.sum(z * y, axis=-1) / k2_safe, 0.0)
    r = y - ub[..., None] * z
    E = mx.sum(r * r, axis=-1)
    integral = _SQRT_PI / (2.0 * k) * (mx.erf(k * (1.0 - ub)) + mx.erf(k * ub))
    integral = mx.where(is_line, integral, 1.0)
    return rho * mx.sqrt(math.pi / n[..., 0]) * mx.exp(-E) * integral

pack_segments(W, a, v, rho)

Pack per-segment kernel inputs into the (N, 16) layout the kernels read.

Source code in src/mlx3d/splatting/spaghetti/rasterize.py
346
347
348
349
def pack_segments(W: mx.array, a: mx.array, v: mx.array, rho: mx.array) -> mx.array:
    """Pack per-segment kernel inputs into the ``(N, 16)`` layout the kernels read."""
    n = W.shape[0]
    return mx.concatenate([W.reshape(n, 9), a, v, rho[:, None]], axis=1).astype(mx.float32)

rasterize_segments(segments, colors, means2d, conics, sorted_ids, tile_ranges, intrinsics, width, height, tiles_x, tiles_y, background=None)

Composite binned segments into an image (differentiable).

Parameters:

Name Type Description Default
segments array

(N, 16) packed segments (:func:pack_segments).

required
colors array

(N, 3) RGB.

required
means2d array

(N, 2) footprint-ellipse centers in pixels.

required
conics array

(N, 3) footprint ellipses x^T C x <= 1 around means2d; pixels outside are skipped.

required
intrinsics tuple[float, float, float, float]

pinhole (fx, fy, cx, cy) for per-pixel ray directions.

required

Returns:

Type Description
dict[str, array]

dict with image (H, W, 3), alpha (H, W), final_T and

dict[str, array]

n_contrib.

Source code in src/mlx3d/splatting/spaghetti/rasterize.py
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
def rasterize_segments(
    segments: mx.array,
    colors: mx.array,
    means2d: mx.array,
    conics: mx.array,
    sorted_ids: mx.array,
    tile_ranges: mx.array,
    intrinsics: tuple[float, float, float, float],
    width: int,
    height: int,
    tiles_x: int,
    tiles_y: int,
    background: mx.array | None = None,
) -> dict[str, mx.array]:
    """Composite binned segments into an image (differentiable).

    Args:
        segments: (N, 16) packed segments (:func:`pack_segments`).
        colors: (N, 3) RGB.
        means2d: (N, 2) footprint-ellipse centers in pixels.
        conics: (N, 3) footprint ellipses ``x^T C x <= 1`` around ``means2d``;
            pixels outside are skipped.
        intrinsics: pinhole ``(fx, fy, cx, cy)`` for per-pixel ray directions.

    Returns:
        dict with ``image`` (H, W, 3), ``alpha`` (H, W), ``final_T`` and
        ``n_contrib``.
    """
    if background is None:
        background = mx.zeros((3,))
    params = mx.array([width, height, tiles_x, tiles_y], dtype=mx.int32)
    intr = mx.array(intrinsics, dtype=mx.float32)
    ellipses = mx.stop_gradient(mx.concatenate([means2d, conics], axis=1)).astype(mx.float32)
    image, final_T, n_contrib = _rasterize_core(
        segments.astype(mx.float32),
        colors.astype(mx.float32),
        ellipses,
        sorted_ids,
        tile_ranges,
        background.astype(mx.float32),
        params,
        intr,
    )
    return {"image": image, "alpha": 1.0 - final_T, "final_T": final_T, "n_contrib": n_contrib}

render_spaghetti(camera, means, halves, quats, scales, rho, colors, background=None)

Render Gaussian-blurred segments with the tiled Metal rasterizer.

Differentiable with respect to every per-segment input and, through camera's extrinsics, the pose (e.g. via :func:~mlx3d.cameras.refine_camera).

Parameters:

Name Type Description Default
camera Camera

the pinhole camera to render from.

required
means array

(N, 3) segment midpoints.

required
halves array

(N, 3) half-vectors; each segment spans m - h to m + h.

required
quats array

(N, 4) kernel rotations (w, x, y, z).

required
scales array

(N, 3) kernel standard deviations.

required
rho array

(N,) densities.

required
colors array

(N, 3) RGB.

required
background array | None

optional (3,) background color (default black).

None

Returns:

Type Description
dict[str, array]

dict with image (H, W, 3), alpha (H, W) and the projection

dict[str, array]

(radii, means2d, depths) used for binning.

Source code in src/mlx3d/splatting/spaghetti/render.py
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
def render_spaghetti(
    camera: Camera,
    means: mx.array,
    halves: mx.array,
    quats: mx.array,
    scales: mx.array,
    rho: mx.array,
    colors: mx.array,
    background: mx.array | None = None,
) -> dict[str, mx.array]:
    """Render Gaussian-blurred segments with the tiled Metal rasterizer.

    Differentiable with respect to every per-segment input and, through
    ``camera``'s extrinsics, the pose (e.g. via :func:`~mlx3d.cameras.refine_camera`).

    Args:
        camera: the pinhole camera to render from.
        means: (N, 3) segment midpoints.
        halves: (N, 3) half-vectors; each segment spans ``m - h`` to ``m + h``.
        quats: (N, 4) kernel rotations (w, x, y, z).
        scales: (N, 3) kernel standard deviations.
        rho: (N,) densities.
        colors: (N, 3) RGB.
        background: optional (3,) background color (default black).

    Returns:
        dict with ``image`` (H, W, 3), ``alpha`` (H, W) and the projection
        (``radii``, ``means2d``, ``depths``) used for binning.
    """
    proj = project_segments(camera, means, halves, quats, scales, rho)
    sorted_ids, tile_ranges, tiles_x, tiles_y = bin_gaussians(
        proj["means2d"], proj["radii"], proj["depths"], camera.width, camera.height
    )
    out = rasterize_segments(
        pack_segments(proj["W"], proj["a"], proj["v"], proj["rho"]),
        colors,
        proj["means2d"],
        proj["conics"],
        sorted_ids,
        tile_ranges,
        (camera.fx, camera.fy, camera.cx, camera.cy),
        camera.width,
        camera.height,
        tiles_x,
        tiles_y,
        background=background,
    )
    out.update(radii=proj["radii"], means2d=proj["means2d"], depths=proj["depths"])
    return out

render_spaghetti_reference(camera, means, halves, quats, scales, rho, colors, background=None)

Dense pure-MLX renderer with the same semantics (tests / small scenes).

Evaluates every segment at every pixel (O(H W N) memory) with the rasterizer's depth order, opacity clamp and cut-off, but no early termination. Differentiable via MLX autodiff.

Source code in src/mlx3d/splatting/spaghetti/render.py
 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
def render_spaghetti_reference(
    camera: Camera,
    means: mx.array,
    halves: mx.array,
    quats: mx.array,
    scales: mx.array,
    rho: mx.array,
    colors: mx.array,
    background: mx.array | None = None,
) -> dict[str, mx.array]:
    """Dense pure-MLX renderer with the same semantics (tests / small scenes).

    Evaluates every segment at every pixel (``O(H W N)`` memory) with the
    rasterizer's depth order, opacity clamp and cut-off, but no early
    termination. Differentiable via MLX autodiff.
    """
    proj = project_segments(camera, means, halves, quats, scales, rho)
    keep = mx.array(proj["radii"] > 0)
    order = mx.argsort(proj["depths"])
    d = pixel_rays(camera)  # (H, W, 3)
    e = mx.einsum("nij,hwj->hwni", proj["W"][order], d)  # (H, W, N, 3)
    tau = segment_optical_depth(e, proj["a"][order], proj["v"][order], proj["rho"][order])
    alpha = mx.minimum(0.99, 1.0 - mx.exp(-tau))
    alpha = mx.where((alpha >= 1.0 / 255.0) & keep[order], alpha, 0.0)
    T = mx.cumprod(1.0 - alpha, axis=-1)
    T_before = mx.concatenate([mx.ones_like(T[..., :1]), T[..., :-1]], axis=-1)
    weights = alpha * T_before
    image = mx.einsum("hwn,nc->hwc", weights, colors[order])
    bg = mx.zeros((3,)) if background is None else background
    final_T = T[..., -1]
    return {"image": image + final_T[..., None] * bg, "alpha": 1.0 - final_T}

segment_colors(camera, means, sh, sh_degree)

View-dependent RGB per segment: SH evaluated toward the segment midpoint.

Source code in src/mlx3d/splatting/spaghetti/render.py
16
17
18
19
20
def segment_colors(camera: Camera, means: mx.array, sh: mx.array, sh_degree: int) -> mx.array:
    """View-dependent RGB per segment: SH evaluated toward the segment midpoint."""
    dirs = means - camera.camera_center
    dirs = dirs * mx.rsqrt(mx.maximum(mx.sum(dirs * dirs, axis=-1, keepdims=True), 1e-16))
    return mx.maximum(eval_sh(sh_degree, sh, mx.stop_gradient(dirs)), 0.0)

default_config_for(iterations, **overrides)

Schedule scaled to iterations: densify until 5/6 of the run, attract endpoints in the final sixth (the paper's 25k / 30k split).

Source code in src/mlx3d/splatting/spaghetti/trainer.py
268
269
270
271
272
273
274
275
276
277
278
279
def default_config_for(iterations: int, **overrides) -> SpaghettiTrainerConfig:
    """Schedule scaled to ``iterations``: densify until 5/6 of the run, attract
    endpoints in the final sixth (the paper's 25k / 30k split)."""
    stop = int(iterations * 5 / 6)
    base = dict(
        lr_means_max_steps=iterations,
        densify_until=stop,
        connect_from=stop,
        densify_from=min(500, max(iterations // 20, 1)),
    )
    base.update(overrides)
    return SpaghettiTrainerConfig(**base)