Download code/tt_depthpro2/tt/weights.py from changh95/DepthPro2: direct link, hf CLI and curl.
- Browser
- Download file 14 kB
-
https://huggingface.co/changh95/DepthPro2/resolve/main/code/tt_depthpro2/tt/weights.py
- Command line
-
hf download hf://changh95/DepthPro2/code/tt_depthpro2/tt/weights.py
-
curl -L -o weights.py https://huggingface.co/changh95/DepthPro2/resolve/main/code/tt_depthpro2/tt/weights.py
14 kB
| # 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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(), | |
| ) | |
| 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) | |