File size: 10,940 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
# SPDX-License-Identifier: Apache-2.0
"""FOV stage, ttnn baseline: DINOv3 ViT-S/16 trunk (taps incl. prefix) + attention head -> logits.

Stage contract (SPEC §3):

* ``FOV.in``  ``fpatches`` ``[1, 1, T * Nfp, 768]`` bf16 TILE DRAM, from the host-resized frames
  (``reference.fov_resize``, then ``tt.weights.unfold_patches``); ``Nfp = ceil32(gh * gw)``.
* ``FOV.out`` ``logits`` ``[1, 1, T, 2]`` float32 TILE DRAM (``ttnn.to_torch(...).reshape(T, 2)``); degrees on the host
  with ``reference.fov_logits_to_deg``.

Trunk: :class:`tt.ttnn_enc.Trunk` with ``joint_cross=False`` (blocks 5/7/9/11 keep their input prefix rows, no joint
attention). Head (``reference.fov_head``), all on the device:

* ``y = Linear(1536 -> 248)(cat_i LN_i(tap_i))`` on every token row ``[T, 1, Lp, 248]``;
* the head sequence ``[query ; prefix + prefix_embed ; avgpool2x2(patches) + sincos]`` is ONE matmul with a constant
  gather / pooling matrix ``G`` (``[S_h, Lp]``: prefix-row selection and the ceil-mode 2x2 average weights 1, 1/2, 1/4,
  all exact in bf16) plus a constant row tensor (query, prefix_embed, sincos code);
* 2 timm ViT blocks (dim 248, 4 heads of 62 dims zero-padded to 64 on the device, scale 1/sqrt(62)), LN, Linear(248 -> 2)
  on the query row.
"""

from __future__ import annotations

import os
from typing import List, Optional, Tuple

import torch

from ..reference import model as ref
from . import NUM_PREFIX, StageShape, ceil32
from .ttnn_enc import Configs, Trunk, _ttnn, fp32_attn_blocks, full_view, sdpa_windowed, view
from .weights import FOV_HD, FOV_HDIM_P, FOV_HEADS, FovWeights, dev_tensor, fov_head_scale, upload_fov


def head_gather(shape: StageShape) -> Tuple[torch.Tensor, int]:
    """``G^T`` ``[Lp, S_hp]`` (float32) and ``S_h``: head row 0 = query slot (zero), rows 1..5 = prefix rows N..N+4,
    rows 6.. = ceil-mode 2x2 average of the patch grid (raster order)."""
    gh, gw, n, lp = shape.gh, shape.gw, shape.n, shape.lp
    ph, pw = -(-gh // 2), -(-gw // 2)
    s_h = 1 + NUM_PREFIX + ph * pw
    g = torch.zeros(ceil32(s_h), lp)
    for j in range(NUM_PREFIX):
        g[1 + j, n + j] = 1.0
    for a in range(ph):
        for b in range(pw):
            rows = [r for r in (2 * a, 2 * a + 1) if r < gh]
            cols = [c for c in (2 * b, 2 * b + 1) if c < gw]
            wgt = 1.0 / (len(rows) * len(cols))
            for r in rows:
                for c in cols:
                    g[1 + NUM_PREFIX + a * pw + b, r * gw + c] = wgt
    return g.t().contiguous(), s_h


class Engine:
    """ttnn FOV engine for one :class:`StageShape` (the fov-resized frame size): ``run(fpatches) -> logits [1, 1, T, 2]``."""

    def __init__(self, device, weights, shape: StageShape, size: Optional[str] = None):
        ttnn = _ttnn()
        if isinstance(weights, dict):
            weights = Engine.prepare_weights(device, weights, "fov")
        self.device = device
        self.w: FovWeights = weights
        self.shape = shape
        self.cfgs = Configs(device)
        self.mem = ttnn.DRAM_MEMORY_CONFIG
        cfg = ref.FOV_TRUNK
        self.trunk = Trunk(device, weights.trunk, shape, joint_cross=False, tap_blocks=cfg.reassembled_blocks,
                           cross_blocks=cfg.cross_frame_blocks, fp32_blocks=fp32_attn_blocks("fov"), cfgs=self.cfgs)
        gt, s_h = head_gather(shape)
        self.s_h, self.s_hp = s_h, gt.shape[1]
        self.gather_t = dev_tensor(gt.reshape(1, 1, *gt.shape), device)
        ph, pw = -(-shape.gh // 2), -(-shape.gw // 2)
        add = torch.zeros(1, 1, self.s_hp, FOV_HD)
        add[0, 0, 0] = weights.head.query_host
        add[0, 0, 1:1 + NUM_PREFIX] = weights.head.prefix_embed_host
        add[0, 0, 1 + NUM_PREFIX:s_h] = ref.sincos_2d(ph, pw, FOV_HD)
        self.head_add_host = add
        self.head_add = dev_tensor(add, device)
        self.head_pc = self.cfgs.sdpa_program(s_h, s_h)
        self.head_cu = (self.trunk._dev_cu(torch.tensor([0, s_h], dtype=torch.int32))
                        if sdpa_windowed(shape.frames, FOV_HEADS) else None)
        # DEPTHPRO2_TTNN_FOV_HEAD = fp32 (default: the official head runs in float32 -- fp32 activations, exact
        # LayerNorm over the 248 columns, fp32-score attention on fp32 q / k / v) | bf16 (bf16 activations, SDPA)
        self.head32 = os.environ.get("DEPTHPRO2_TTNN_FOV_HEAD", "fp32") == "fp32"
        self.act = ttnn.float32 if self.head32 else ttnn.bfloat16
        if self.head32:
            cm = torch.zeros(1, 1, 1, FOV_HD)
            cm[...] = 1.0
            self.colmask = dev_tensor(cm, device, dtype=ttnn.float32)  # logical 248 columns, padding 0
            add = self.head_add_host
            self.head_add = dev_tensor(add, device, dtype=ttnn.float32)

    @staticmethod
    def prepare_weights(device, host_weights, size: str = "fov") -> FovWeights:
        return upload_fov(device, host_weights)

    def _ln(self, x, w, b):
        """LayerNorm over the 248 logical columns (padding columns are zero in and out)."""
        ttnn = _ttnn()
        if not self.head32:
            return ttnn.layer_norm(x, epsilon=ref.LN_EPS, weight=w, bias=b, memory_config=self.mem,
                                   compute_kernel_config=self.cfgs.ln)
        mem, cfg = self.mem, self.cfgs.ln
        s1 = ttnn.sum(x, dim=-1, keepdim=True, memory_config=mem, compute_kernel_config=cfg)
        mu = ttnn.multiply(s1, 1.0 / FOV_HD, memory_config=mem)
        ttnn.deallocate(s1)
        d = ttnn.subtract(x, mu, memory_config=mem)
        ttnn.deallocate(mu)
        xc = ttnn.multiply(d, self.colmask, memory_config=mem)
        ttnn.deallocate(d)
        sq = ttnn.multiply(xc, xc, memory_config=mem)
        s2 = ttnn.sum(sq, dim=-1, keepdim=True, memory_config=mem, compute_kernel_config=cfg)
        ttnn.deallocate(sq)
        var = ttnn.multiply(s2, 1.0 / FOV_HD, memory_config=mem)
        ttnn.deallocate(s2)
        ve = ttnn.add(var, ref.LN_EPS, memory_config=mem)
        ttnn.deallocate(var)
        rs = ttnn.rsqrt(ve, memory_config=mem)
        ttnn.deallocate(ve)
        xn = ttnn.multiply(xc, rs, memory_config=mem)
        ttnn.deallocate(xc)
        ttnn.deallocate(rs)
        y = ttnn.multiply(xn, w, memory_config=mem)
        ttnn.deallocate(xn)
        out = ttnn.add(y, b, memory_config=mem)
        ttnn.deallocate(y)
        return out

    def _lin(self, x, w, b=None, act=None, dtype=None):
        ttnn = _ttnn()
        return ttnn.linear(x, w, bias=b, activation=act, memory_config=self.mem, dtype=dtype or self.act,
                           compute_kernel_config=self.cfgs.mm)

    def _attn32(self, q, k, v):
        """fp32-score attention on fp32 q / k / v [T, 4, S_h (logical), 64] (scale 1/sqrt(62))."""
        ttnn = _ttnn()
        mem = self.mem
        qs = ttnn.multiply(q, fov_head_scale(), memory_config=mem)
        kt = ttnn.transpose(k, -2, -1, memory_config=mem)
        sc = ttnn.matmul(qs, kt, memory_config=mem, dtype=ttnn.float32, compute_kernel_config=self.cfgs.mm)
        ttnn.deallocate(qs)
        ttnn.deallocate(kt)
        pr = ttnn.softmax(sc, dim=-1, numeric_stable=True, memory_config=mem, compute_kernel_config=self.cfgs.mm)
        ttnn.deallocate(sc)
        o = ttnn.matmul(pr, v, memory_config=mem, dtype=ttnn.float32, compute_kernel_config=self.cfgs.mm)
        ttnn.deallocate(pr)
        return o

    def _head_block(self, x, p):
        ttnn = _ttnn()
        T, s_h, s_hp = self.shape.frames, self.s_h, self.s_hp
        h = self._ln(x, p["n1_w"], p["n1_b"])
        qkv = self._lin(h, p["qkv_w"], p["qkv_b"])
        ttnn.deallocate(h)
        q, k, v = ttnn.experimental.nlp_create_qkv_heads(qkv, num_heads=FOV_HEADS, num_kv_heads=FOV_HEADS,
                                                         transpose_k_heads=False, memory_config=self.mem)
        ttnn.deallocate(qkv)
        shp, pad = [T, FOV_HEADS, s_h, FOV_HDIM_P], [T, FOV_HEADS, s_hp, FOV_HDIM_P]
        if self.head32:
            o = self._attn32(view(q, shp, pad), view(k, shp, pad), view(v, shp, pad))
        else:
            o = ttnn.transformer.scaled_dot_product_attention(view(q, shp, pad), view(k, shp, pad), view(v, shp, pad),
                                                              is_causal=False, scale=fov_head_scale(), program_config=self.head_pc,
                                                              compute_kernel_config=self.cfgs.sdpa, memory_config=self.mem,
                                                              cu_window_seqlens=self.head_cu)
        for t in (q, k, v):
            ttnn.deallocate(t)
        a = ttnn.experimental.nlp_concat_heads(full_view(o), memory_config=self.mem)
        ttnn.deallocate(o)
        pr = self._lin(a, p["proj_w"], p["proj_b"])
        ttnn.deallocate(a)
        x1 = ttnn.add(x, pr, memory_config=self.mem)
        ttnn.deallocate(pr)
        h = self._ln(x1, p["n2_w"], p["n2_b"])
        m = self._lin(h, p["fc1_w"], p["fc1_b"], act="gelu")
        ttnn.deallocate(h)
        f = self._lin(m, p["fc2_w"], p["fc2_b"])
        ttnn.deallocate(m)
        x2 = ttnn.add(x1, f, memory_config=self.mem)
        ttnn.deallocate(f)
        ttnn.deallocate(x1)
        return x2

    def run(self, fpatches) -> object:
        ttnn = _ttnn()
        T = self.shape.frames
        hw = self.w.head
        taps = self.trunk.run(fpatches)  # 4 x [T, 1, Lp, 384], incl. prefix rows
        normed = [self.trunk._ln(t, hw.tap_n_w[i], hw.tap_n_b[i]) for i, t in enumerate(taps)]  # 384-wide: exact LN
        for t in taps:
            ttnn.deallocate(t)
        cat = ttnn.concat(normed, dim=-1, memory_config=self.mem)  # [T, 1, Lp, 1536]
        for t in normed:
            ttnn.deallocate(t)
        y = self._lin(cat, hw.proj_w, hw.proj_b)  # [T, 1, Lp, 248]
        ttnn.deallocate(cat)
        yt = ttnn.transpose(y, -2, -1, memory_config=self.mem)  # [T, 1, 248, Lp]
        ttnn.deallocate(y)
        zt = ttnn.matmul(yt, self.gather_t, memory_config=self.mem, dtype=self.act, compute_kernel_config=self.cfgs.mm)
        ttnn.deallocate(yt)
        z = ttnn.transpose(zt, -2, -1, memory_config=self.mem)  # [T, 1, S_hp, 248]
        ttnn.deallocate(zt)
        x = ttnn.add(z, self.head_add, memory_config=self.mem)
        ttnn.deallocate(z)
        for p in hw.blocks:
            x2 = self._head_block(x, p)
            ttnn.deallocate(x)
            x = x2
        q0 = ttnn.slice(full_view(x), [0, 0, 0, 0], [T, 1, 32, FOV_HD], memory_config=self.mem)
        ttnn.deallocate(x)
        h = self._ln(q0, hw.norm_w, hw.norm_b)
        ttnn.deallocate(q0)
        lg = ttnn.linear(h, hw.out_w, bias=hw.out_b, memory_config=self.mem, dtype=ttnn.float32,
                         compute_kernel_config=self.cfgs.mm)  # [T, 1, 32, 2] float32
        ttnn.deallocate(h)
        r0 = ttnn.slice(lg, [0, 0, 0, 0], [T, 1, 1, 2], memory_config=self.mem)
        ttnn.deallocate(lg)
        return ttnn.reshape(r0, [1, 1, T, 2], memory_config=self.mem)