File size: 14,021 Bytes
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
328
329
330
331
# SPDX-License-Identifier: Apache-2.0
"""Safetensors -> device tensors, per stage (ttnn baseline engines).

Host preparation happens in float32 and every device tensor is rounded to its device dtype exactly once:

* linear weights are stored transposed (``[in, out]``, what ``ttnn.linear`` wants);
* LayerScale is folded into the projection it scales: ``gamma * (a @ W^T + b) = a @ (W^T * gamma) + b * gamma``;
* 16x16 patch embedding = matmul with ``W.reshape(C, 768).T``; the host unfolds patches in ``(c, ky, kx)`` order
  (:func:`unfold_patches`);
* decoder convolutions stay ``[O, I, kh, kw]`` host tensors (``ttnn.conv2d`` prepares them on its first call);
  1x1 convolutions become matmul weights.

``load_weights(dir)`` reads ``model.safetensors`` into a name -> float32 torch dict (same as the reference loader).
"""

from __future__ import annotations

import math
import os
from dataclasses import dataclass, field
from typing import Dict, List, Optional

import torch

from ..reference import model as ref
from . import PATCH

HostDict = Dict[str, torch.Tensor]


def load_weights(model_dir: str) -> HostDict:
    """``<model_dir>/model.safetensors`` -> name -> float32 tensor."""
    return ref.load_safetensors(os.path.join(model_dir, "model.safetensors"))


def unfold_patches(x: torch.Tensor, np_rows: Optional[int] = None) -> torch.Tensor:
    """Padded frames ``[T, 3, Hp, Wp]`` -> patches ``[T * Np, 768]`` (float32), rows ``(gy, gx)`` raster order, columns
    ``(c, ky, kx)`` (= ``patch_embed.proj.weight.reshape(C, 768)`` order); rows ``>= N`` of each frame are zero."""
    t, c, h, w = x.shape
    gh, gw = h // PATCH, w // PATCH
    n = gh * gw
    np_rows = np_rows or (n + 31) // 32 * 32
    p = x.reshape(t, c, gh, PATCH, gw, PATCH).permute(0, 2, 4, 1, 3, 5).reshape(t, n, c * PATCH * PATCH)
    if np_rows > n:
        p = torch.cat([p, p.new_zeros(t, np_rows - n, p.shape[-1])], dim=1)
    return p.reshape(t * np_rows, c * PATCH * PATCH)


# ----------------------------------------------------------------------------------------------- device helpers


def _ttnn():
    import ttnn

    return ttnn


def dev_tensor(t: torch.Tensor, device, dtype=None, layout=None, mem=None):
    ttnn = _ttnn()
    return ttnn.from_torch(t.contiguous(), dtype=dtype or ttnn.bfloat16, layout=layout or ttnn.TILE_LAYOUT, device=device,
                           memory_config=mem or ttnn.DRAM_MEMORY_CONFIG)


def _wdtype(name: str):
    """Weight dtype for matmul weights (``DEPTHPRO2_TTNN_WDTYPE`` = bf16 | bfp8; A/B knob, default bf16)."""
    ttnn = _ttnn()
    return ttnn.bfloat8_b if os.environ.get("DEPTHPRO2_TTNN_WDTYPE", "bf16") == "bfp8" else ttnn.bfloat16


# ----------------------------------------------------------------------------------------------- ViT trunk


@dataclass
class BlockWeights:
    n1_w: object
    n1_b: object
    qkv_w: object
    qkv_b: Optional[object]
    proj_w: object
    proj_b: object
    n2_w: object
    n2_b: object
    fc1_w: object = None  # GELU MLP
    fc1_b: object = None
    fcg_w: object = None  # SwiGLU gate (SiLU) branch
    fcg_b: object = None
    fcx_w: object = None  # SwiGLU linear branch
    fcx_b: object = None
    fc2_w: object = None
    fc2_b: object = None


@dataclass
class TrunkWeights:
    """A DINOv3 trunk (encoder of S/B/L/H+, or the FOV trunk) on the device."""

    cfg: ref.SizeConfig
    pe_w: object  # [768, C]
    pe_b_host: torch.Tensor  # [C] float32 (added through the per-shape row-constant)
    prefix_host: torch.Tensor  # [5, C] float32: cls, reg0..3
    blocks: List[BlockWeights] = field(default_factory=list)


def trunk_host_block(w: HostDict, p: str, swiglu: bool) -> Dict[str, Optional[torch.Tensor]]:
    """Float32 host tensors of one block in matmul layout, LayerScale folded."""
    g1, g2 = w[p + ".gamma_1"], w[p + ".gamma_2"]
    out = {
        "n1_w": w[p + ".norm1.weight"], "n1_b": w[p + ".norm1.bias"],
        "qkv_w": w[p + ".attn.qkv.weight"].t(), "qkv_b": w.get(p + ".attn.qkv.bias"),
        "proj_w": w[p + ".attn.proj.weight"].t() * g1[None, :], "proj_b": w[p + ".attn.proj.bias"] * g1,
        "n2_w": w[p + ".norm2.weight"], "n2_b": w[p + ".norm2.bias"],
        "fc2_w": w[p + ".mlp.fc2.weight"].t() * g2[None, :], "fc2_b": w[p + ".mlp.fc2.bias"] * g2,
    }
    if swiglu:
        out.update(fcg_w=w[p + ".mlp.fc1_g.weight"].t(), fcg_b=w[p + ".mlp.fc1_g.bias"],
                   fcx_w=w[p + ".mlp.fc1_x.weight"].t(), fcx_b=w[p + ".mlp.fc1_x.bias"])
    else:
        out.update(fc1_w=w[p + ".mlp.fc1.weight"].t(), fc1_b=w[p + ".mlp.fc1.bias"])
    return out


def upload_trunk(device, w: HostDict, cfg: ref.SizeConfig, pfx: str) -> TrunkWeights:
    """``pfx``: ``"encoder."`` (depth model) or ``"trunk."`` (FOV)."""
    ttnn = _ttnn()
    c = cfg.dim
    pe = w[pfx + "patch_embed.proj.weight"].reshape(c, -1).t()
    tw = TrunkWeights(
        cfg=cfg,
        pe_w=dev_tensor(pe, device, dtype=ttnn.bfloat16),
        pe_b_host=w[pfx + "patch_embed.proj.bias"].clone(),
        prefix_host=torch.cat([w[pfx + "cls_token"].reshape(1, c), w[pfx + "reg_token"].reshape(-1, c)], 0).clone(),
    )
    row = lambda v: dev_tensor(v.reshape(1, -1), device)  # noqa: E731
    row32 = lambda v: dev_tensor(v.reshape(1, -1), device, dtype=ttnn.float32)  # noqa: E731  (LayerNorm affine)
    for i in range(cfg.depth):
        h = trunk_host_block(w, f"{pfx}blocks.{i}", cfg.swiglu)
        wd = lambda k: None if h.get(k) is None else dev_tensor(h[k], device, dtype=_wdtype(k))  # noqa: E731
        rb = lambda k: None if h.get(k) is None else row(h[k])  # noqa: E731
        tw.blocks.append(BlockWeights(
            n1_w=row32(h["n1_w"]), n1_b=row32(h["n1_b"]), qkv_w=wd("qkv_w"), qkv_b=rb("qkv_b"), proj_w=wd("proj_w"),
            proj_b=rb("proj_b"), n2_w=row32(h["n2_w"]), n2_b=row32(h["n2_b"]), fc1_w=wd("fc1_w"), fc1_b=rb("fc1_b"), fcg_w=wd("fcg_w"), fcg_b=rb("fcg_b"),
            fcx_w=wd("fcx_w"), fcx_b=rb("fcx_b"), fc2_w=wd("fc2_w"), fc2_b=rb("fc2_b")))
    return tw


# ----------------------------------------------------------------------------------------------- DPT decoder


@dataclass
class ConvSpec:
    """A conv / conv-transpose for ``ttnn.conv2d`` / ``ttnn.conv_transpose2d`` (host weights; prepared per shape)."""

    w_host: object  # ttnn host tensor [O, I, k, k] (conv) or [I, O, k, k] (conv-transpose), bf16
    b_host: Optional[object]  # ttnn host tensor [1, 1, 1, O]
    cin: int
    cout: int
    k: int
    stride: int
    pad: int
    transpose: bool = False


@dataclass
class MatSpec:
    """A 1x1 conv (or kernel == stride conv-transpose) as ``x @ w + b`` on NHWC rows."""

    w: object  # device [Cin, Cout'] TILE
    b: Optional[object]  # device [1, Cout'] TILE
    cin: int
    cout: int


@dataclass
class DecWeights:
    cfg: ref.SizeConfig
    reassemble_mm: List[MatSpec]  # reassemble.i.0 (1x1)
    reassemble_up: Dict[int, object]  # i -> ConvSpec / MatSpec (i = 0: k4s4, 1: k2s2, 3: conv3x3 s2)
    convs: List[ConvSpec]  # decoder.convs.i (3x3, no bias)
    res: Dict[str, ConvSpec]  # "f{i}.r{1|2}.c{1|3}"
    deconv: List[ConvSpec]  # decoder.fusions.i.deconv (k2s2, no bias)
    out_conv: List[MatSpec]  # decoder.fusions.i.out_conv (1x1)
    head0: ConvSpec
    head1: ConvSpec
    head2: ConvSpec
    head4_w: torch.Tensor  # [32] float32
    head4_b: float
    host: Dict[str, torch.Tensor] = field(default_factory=dict)


def _host_tt(t: torch.Tensor):
    ttnn = _ttnn()
    return ttnn.from_torch(t.to(torch.bfloat16).contiguous(), dtype=ttnn.bfloat16)


def conv_spec(w: HostDict, name: str, stride: int = 1, pad: int = 0, bias: bool = True, transpose: bool = False) -> ConvSpec:
    wt = w[name + ".weight"]
    b = w.get(name + ".bias") if bias else None
    if transpose:
        cin, cout, k = wt.shape[0], wt.shape[1], wt.shape[2]
    else:
        cout, cin, k = wt.shape[0], wt.shape[1], wt.shape[2]
    return ConvSpec(w_host=_host_tt(wt), b_host=None if b is None else _host_tt(b.reshape(1, 1, 1, -1)), cin=cin, cout=cout,
                    k=k, stride=stride, pad=pad, transpose=transpose)


def mat_spec_1x1(device, w: HostDict, name: str) -> MatSpec:
    wt = w[name + ".weight"]  # [O, I, 1, 1]
    cout, cin = wt.shape[0], wt.shape[1]
    b = w.get(name + ".bias")
    return MatSpec(w=dev_tensor(wt.reshape(cout, cin).t(), device),
                   b=None if b is None else dev_tensor(b.reshape(1, -1), device), cin=cin, cout=cout)


def mat_spec_convt(device, w: HostDict, name: str) -> MatSpec:
    """ConvTranspose2d with kernel == stride as one matmul: ``[*, Cin] @ [Cin, (a, b, co)]`` + depth-to-space."""
    wt = w[name + ".weight"]  # [I, O, k, k]
    cin, cout, k = wt.shape[0], wt.shape[1], wt.shape[2]
    m = wt.permute(0, 2, 3, 1).reshape(cin, k * k * cout)
    b = w.get(name + ".bias")
    return MatSpec(w=dev_tensor(m, device),
                   b=None if b is None else dev_tensor(b.repeat(k * k).reshape(1, -1), device), cin=cin, cout=cout)


def upload_dec(device, w: HostDict, cfg: ref.SizeConfig, convt4_matmul: bool = True) -> DecWeights:
    rm = [mat_spec_1x1(device, w, f"encoder.reassemble.{i}.0") for i in range(4)]
    up = {
        0: mat_spec_convt(device, w, "encoder.reassemble.0.1") if convt4_matmul else conv_spec(w, "encoder.reassemble.0.1", 4, 0, True, True),
        1: conv_spec(w, "encoder.reassemble.1.1", 2, 0, True, True),
        3: conv_spec(w, "encoder.reassemble.3.1", 2, 1),
    }
    convs = [conv_spec(w, f"decoder.convs.{i}", 1, 1, bias=False) for i in range(4)]
    res = {}
    for i in range(4):
        for r in (1, 2):
            if i == 3 and r == 1:
                continue
            for c in (1, 3):
                res[f"f{i}.r{r}.c{c}"] = conv_spec(w, f"decoder.fusions.{i}.resnet{r}.residual.{c}", 1, 1)
    deconv = [conv_spec(w, f"decoder.fusions.{i}.deconv", 2, 0, bias=False, transpose=True) for i in range(4)]
    out_conv = [mat_spec_1x1(device, w, f"decoder.fusions.{i}.out_conv") for i in range(4)]
    return DecWeights(
        cfg=cfg, reassemble_mm=rm, reassemble_up=up, convs=convs, res=res, deconv=deconv, out_conv=out_conv,
        head0=conv_spec(w, "head.0", 1, 1), head1=conv_spec(w, "head.1", 2, 0, True, True), head2=conv_spec(w, "head.2", 1, 1),
        head4_w=w["head.4.weight"].reshape(-1).clone(), head4_b=float(w["head.4.bias"].reshape(-1)[0]),
    )


# ----------------------------------------------------------------------------------------------- FOV head

FOV_HD = ref.FOV_HEAD_DIM  # 248
FOV_HEADS = ref.FOV_HEAD_HEADS  # 4
FOV_HDIM = FOV_HD // FOV_HEADS  # 62
FOV_HDIM_P = 64  # per-head width on the device (zero-padded)
FOV_MLP = 4 * FOV_HD  # 992


@dataclass
class FovHeadWeights:
    tap_n_w: List[object]
    tap_n_b: List[object]
    proj_w: object  # [1536, 248]
    proj_b: object  # [1, 248]
    blocks: List[Dict[str, object]]
    norm_w: object
    norm_b: object
    out_w: object  # [248, 2]
    out_b: object  # [1, 2]
    query_host: torch.Tensor  # [248]
    prefix_embed_host: torch.Tensor  # [5, 248]


def _head_qkv_padded(wq: torch.Tensor, bq: torch.Tensor):
    """timm qkv [744, 248] (+ bias) -> [248, 3 * 4 * 64] / [768]: each head's 62 dims padded to 64 with zeros."""
    w_t = wq.t()  # [248, 744], columns (s, h, d)
    w_p = torch.zeros(FOV_HD, 3, FOV_HEADS, FOV_HDIM_P)
    b_p = torch.zeros(3, FOV_HEADS, FOV_HDIM_P)
    w_p[..., :FOV_HDIM] = w_t.reshape(FOV_HD, 3, FOV_HEADS, FOV_HDIM)
    b_p[..., :FOV_HDIM] = bq.reshape(3, FOV_HEADS, FOV_HDIM)
    return w_p.reshape(FOV_HD, -1), b_p.reshape(-1)


def _head_proj_padded(wp: torch.Tensor):
    """proj [248, 248] -> [4 * 64, 248]: rows at the per-head padding dims are zero."""
    w_t = wp.t().reshape(FOV_HEADS, FOV_HDIM, FOV_HD)
    w_p = torch.zeros(FOV_HEADS, FOV_HDIM_P, FOV_HD)
    w_p[:, :FOV_HDIM] = w_t
    return w_p.reshape(FOV_HEADS * FOV_HDIM_P, FOV_HD)


def upload_fov_head(device, w: HostDict) -> FovHeadWeights:
    """bf16 head weights, or float32 ones with ``DEPTHPRO2_TTNN_FOV_HEAD=fp32`` (default; the official head is fp32)."""
    ttnn = _ttnn()
    hd = ttnn.float32 if os.environ.get("DEPTHPRO2_TTNN_FOV_HEAD", "fp32") == "fp32" else ttnn.bfloat16
    row = lambda v: dev_tensor(v.reshape(1, -1), device, dtype=hd)  # noqa: E731
    hdev = lambda t: dev_tensor(t, device, dtype=hd)  # noqa: E731

    blocks = []
    for i in range(2):
        p = f"head.blocks.{i}"
        qkv_w, qkv_b = _head_qkv_padded(w[p + ".attn.qkv.weight"], w[p + ".attn.qkv.bias"])
        blocks.append({
            "n1_w": row(w[p + ".norm1.weight"]), "n1_b": row(w[p + ".norm1.bias"]),
            "qkv_w": hdev(qkv_w), "qkv_b": row(qkv_b),
            "proj_w": hdev(_head_proj_padded(w[p + ".attn.proj.weight"])), "proj_b": row(w[p + ".attn.proj.bias"]),
            "n2_w": row(w[p + ".norm2.weight"]), "n2_b": row(w[p + ".norm2.bias"]),
            "fc1_w": hdev(w[p + ".mlp.fc1.weight"].t()), "fc1_b": row(w[p + ".mlp.fc1.bias"]),
            "fc2_w": hdev(w[p + ".mlp.fc2.weight"].t()), "fc2_b": row(w[p + ".mlp.fc2.bias"]),
        })
    return FovHeadWeights(
        tap_n_w=[dev_tensor(w[f"head.tap_norms.{i}.weight"].reshape(1, -1), device, dtype=_ttnn().float32) for i in range(4)],
        tap_n_b=[dev_tensor(w[f"head.tap_norms.{i}.bias"].reshape(1, -1), device, dtype=_ttnn().float32) for i in range(4)],
        proj_w=hdev(w["head.proj.weight"].t()), proj_b=row(w["head.proj.bias"]),
        blocks=blocks, norm_w=row(w["head.norm.weight"]), norm_b=row(w["head.norm.bias"]),
        out_w=hdev(w["head.out.weight"].t()), out_b=row(w["head.out.bias"]),
        query_host=w["head.query"].reshape(-1).clone(), prefix_embed_host=w["head.prefix_embed"].reshape(5, -1).clone(),
    )


@dataclass
class FovWeights:
    trunk: TrunkWeights
    head: FovHeadWeights


def upload_fov(device, w: HostDict) -> FovWeights:
    return FovWeights(trunk=upload_trunk(device, w, ref.FOV_TRUNK, "trunk."), head=upload_fov_head(device, w))


def fov_head_scale() -> float:
    return 1.0 / math.sqrt(FOV_HDIM)