Download code/tt_depthpro2/tt/ttnn_kv.py from changh95/DepthPro2: direct link, hf CLI and curl.
- Browser
- Download file 10.7 kB
-
https://huggingface.co/changh95/DepthPro2/resolve/main/code/tt_depthpro2/tt/ttnn_kv.py
- Command line
-
hf download hf://changh95/DepthPro2/code/tt_depthpro2/tt/ttnn_kv.py
-
curl -L -o ttnn_kv.py https://huggingface.co/changh95/DepthPro2/resolve/main/code/tt_depthpro2/tt/ttnn_kv.py
10.7 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Unbuffered video on the device: one-frame ENC step attending a key-value cache of the last frames (ttnn). | |
| Semantics = ``cpu_engine.CPUEngine.inverse_depth_step`` / ``CPUKVCache`` (SPEC §1 "Unbuffered"): within-frame blocks | |
| as usual; each cross-frame block takes this frame's patch queries over [pooled prefix ; the patch keys / values of | |
| the last ``fill = min(frames seen + 1, window)`` frames, this one included] and keeps the frame's own prefix rows; | |
| the pooled prefix is the mean of the block-input prefix of those ``fill`` frames. | |
| Device design (compiled once per bucket for a ring of ``W = max_frames`` frames; any cache window ``<= W``): | |
| * per cache (:class:`KVState`) and cross-frame block: ``k_old`` / ``v_old`` ``[1, H, (W - 1) * N, 64]`` bf16 TILE | |
| (the patch K / V of the ``W - 1`` previous frames, newest first, compact rows), ``p_old`` ``[W - 1, 1, 5, C]`` | |
| float32 TILE (their block-input prefix rows); | |
| * step, per cross-frame block: ``kseq = [pk (5) ; k_new (N) ; k_old]`` (one ``ttnn.concat``), ONE windowed SDPA | |
| (``cu_window_seqlens`` = ``step_cu`` = ``[0, 5 + fill * N, 5 + W * N]``: window 0 = the live keys), pooled prefix | |
| = ``sum(step_w * [prefix_new ; p_old])`` (``step_w`` = ``1 / fill`` on the first ``fill`` slots); then the ring | |
| shifts in place: ``k_old <- kseq[5 : 5 + (W - 1) * N]``, ``p_old <- [prefix_new ; p_old][: W - 1]`` | |
| (``ttnn.copy`` into the persistent state, inside the trace); | |
| * ``step_cu`` / ``step_w`` are per-bucket persistent inputs the host writes before each replay: one trace per | |
| cache serves every fill state (no re-capture). | |
| """ | |
| from __future__ import annotations | |
| from typing import List, Optional | |
| import torch | |
| from . import NUM_PREFIX, StageShape, ceil32 | |
| from .ttnn_enc import HEAD_DIM, Configs, Trunk, _ttnn, fp32_attn_blocks, free_unless_shared, full_view, view | |
| from .weights import BlockWeights, TrunkWeights, dev_tensor | |
| def step_cu(window_ring: int, fill: int, n_patches: int) -> torch.Tensor: | |
| """``step_cu`` (int32, 3 values): window 0 = ``[pooled prefix ; the fill newest frames]`` of | |
| ``kseq = [pk (5) ; k_new (N) ; k_old ((W - 1) * N)]``.""" | |
| return torch.tensor([0, NUM_PREFIX + fill * n_patches, NUM_PREFIX + window_ring * n_patches], dtype=torch.int32) | |
| def step_weights(window_ring: int, fill: int) -> torch.Tensor: | |
| w = torch.zeros(window_ring, 1, 1, 1) | |
| w[:fill] = 1.0 / fill | |
| return w | |
| class KVState: | |
| """Device ring state of ONE cache (one stream) for one bucket: per cross-frame block ``k_old``, ``v_old``, | |
| ``p_old`` (module doc). Allocated before any trace capture (``DepthPro2Device`` keeps a pool).""" | |
| def __init__(self, device, shape: StageShape, cfg, window_ring: int, cross_blocks): | |
| ttnn = _ttnn() | |
| self.window_ring = window_ring | |
| self.blocks = {} | |
| rows = (window_ring - 1) * shape.n | |
| self.nbytes = 0 | |
| if window_ring > 1: | |
| for i in cross_blocks: | |
| kv = [] | |
| for _ in range(2): | |
| t = ttnn.reshape(dev_tensor(torch.zeros(1, cfg.heads, ceil32(rows), HEAD_DIM), device), | |
| ttnn.Shape([1, cfg.heads, rows, HEAD_DIM]), | |
| ttnn.Shape([1, cfg.heads, ceil32(rows), HEAD_DIM])) | |
| kv.append(t) | |
| p = view(dev_tensor(torch.zeros(window_ring - 1, 1, 32, cfg.dim), device, dtype=ttnn.float32), | |
| [window_ring - 1, 1, NUM_PREFIX, cfg.dim], [window_ring - 1, 1, 32, cfg.dim]) | |
| self.blocks[i] = (kv[0], kv[1], p) | |
| self.nbytes += 2 * cfg.heads * ceil32(rows) * HEAD_DIM * 2 + (window_ring - 1) * 32 * cfg.dim * 4 | |
| def free(self) -> None: | |
| ttnn = _ttnn() | |
| for k, v, p in self.blocks.values(): | |
| for t in (k, v, p): | |
| ttnn.deallocate(t) | |
| self.blocks = {} | |
| class StepEncoder: | |
| """ttnn ENC in step mode for one bucket (``shape.frames == 1``): ``run(patches, state) -> 4 taps`` | |
| (``[1, 1, Np, C]`` bf16, the ENC.out contract with T = 1).""" | |
| def __init__(self, device, weights: TrunkWeights, shape: StageShape, window_ring: int): | |
| ttnn = _ttnn() | |
| if shape.frames != 1: | |
| raise ValueError("StepEncoder works on one frame") | |
| self.device = device | |
| self.w = weights | |
| self.cfg = weights.cfg | |
| self.shape = shape | |
| self.window_ring = int(window_ring) | |
| self.cfgs = Configs(device) | |
| self.trunk = Trunk(device, weights, shape, joint_cross=False, tap_blocks=self.cfg.reassembled_blocks, | |
| cross_blocks=self.cfg.cross_frame_blocks, fp32_blocks=fp32_attn_blocks(self.cfg.name), | |
| cfgs=self.cfgs) | |
| n = shape.n | |
| self.np_ = ceil32(n) | |
| # RoPE table of the patch rows alone ([N] rows padded to Np) | |
| from .ttnn_enc import rope_rows | |
| cos, sin = rope_rows(shape.gh, shape.gw, self.np_) | |
| self.trunk.add_rope_table("patch", cos, sin) | |
| self.s_keys = NUM_PREFIX + self.window_ring * n | |
| self.pc = self.cfgs.sdpa_program(n, self.s_keys) | |
| self.cu = self.trunk._dev_cu(step_cu(self.window_ring, 1, n)) | |
| self.wts = dev_tensor(step_weights(self.window_ring, 1), device, dtype=ttnn.float32) | |
| def set_fill(self, fill: int) -> None: | |
| """Host call before a replay: ``fill`` live frames (this one included).""" | |
| ttnn = _ttnn() | |
| if not 1 <= fill <= self.window_ring: | |
| raise ValueError(f"fill {fill} outside 1..{self.window_ring}") | |
| ttnn.copy_host_to_device_tensor(ttnn.from_torch(step_cu(self.window_ring, fill, self.shape.n), dtype=ttnn.int32, | |
| layout=ttnn.ROW_MAJOR_LAYOUT), self.cu, cq_id=0) | |
| ttnn.copy_host_to_device_tensor(ttnn.from_torch(step_weights(self.window_ring, fill), dtype=ttnn.float32, | |
| layout=ttnn.TILE_LAYOUT), self.wts, cq_id=0) | |
| def block_step(self, x, bw: BlockWeights, st): | |
| """Cross-frame block in step mode on ``x`` [1, 1, Lp, C] (module doc).""" | |
| ttnn = _ttnn() | |
| tr = self.trunk | |
| n, c, lp, W = self.shape.n, self.cfg.dim, self.shape.lp, self.window_ring | |
| np_, H = self.np_, self.cfg.heads | |
| mem = tr.mem | |
| prefix_in = ttnn.slice(x, [0, 0, n, 0], [1, 1, n + NUM_PREFIX, c], memory_config=mem) # [1, 1, 5, C] | |
| p_all = ttnn.concat([prefix_in, st[2]], dim=0, memory_config=mem) if W > 1 else prefix_in # [W, 1, 5, C] | |
| wp = ttnn.multiply(p_all, self.wts, memory_config=mem, dtype=tr.resid_dtype) | |
| pooled = ttnn.sum(wp, dim=0, keepdim=True, memory_config=mem) # [1, 1, 5, C] | |
| ttnn.deallocate(wp) | |
| if lp == np_: | |
| xp = view(x, [1, 1, n, c], [1, 1, lp, c]) | |
| else: | |
| xp = ttnn.slice(x, [0, 0, 0, 0], [1, 1, n, c], memory_config=mem) | |
| h = tr._ln(xp, bw.n1_w, bw.n1_b) | |
| qkv = tr._qkv(h, bw) | |
| ttnn.deallocate(h) | |
| q, k, v = tr._heads(qkv, n, np_, 1, "patch") | |
| ttnn.deallocate(qkv) | |
| hp = tr._ln(pooled, bw.n1_w, bw.n1_b) | |
| ttnn.deallocate(pooled) | |
| qkvp = tr._qkv(hp, bw) | |
| ttnn.deallocate(hp) | |
| qp, kp, vp = tr._heads(qkvp, NUM_PREFIX, 32, 1) | |
| ttnn.deallocate(qkvp) | |
| ttnn.deallocate(qp) | |
| if W > 1: | |
| kseq = ttnn.concat([kp, k, st[0]], dim=2, memory_config=mem) # [1, H, 5 + W * N, 64] | |
| vseq = ttnn.concat([vp, v, st[1]], dim=2, memory_config=mem) | |
| else: | |
| kseq = ttnn.concat([kp, k], dim=2, memory_config=mem) | |
| vseq = ttnn.concat([vp, v], dim=2, memory_config=mem) | |
| for t in (k, v, kp, vp): | |
| ttnn.deallocate(t) | |
| o = ttnn.transformer.scaled_dot_product_attention( | |
| q, kseq, vseq, is_causal=False, scale=HEAD_DIM ** -0.5, program_config=self.pc, | |
| compute_kernel_config=self.cfgs.sdpa, memory_config=mem, cu_window_seqlens=self.cu) | |
| ttnn.deallocate(q) | |
| if W > 1: # ring shift: the W - 1 newest frames (this one first) become the old slots | |
| rows = (W - 1) * n | |
| for seq, dst in ((kseq, st[0]), (vseq, st[1])): | |
| nxt = ttnn.slice(seq, [0, 0, NUM_PREFIX, 0], [1, H, NUM_PREFIX + rows, HEAD_DIM], memory_config=mem) | |
| ttnn.copy(nxt, dst) | |
| ttnn.deallocate(nxt) | |
| pn = ttnn.slice(p_all, [0, 0, 0, 0], [W - 1, 1, NUM_PREFIX, c], memory_config=mem) | |
| ttnn.copy(pn, st[2]) | |
| ttnn.deallocate(pn) | |
| ttnn.deallocate(p_all) | |
| ttnn.deallocate(kseq) | |
| ttnn.deallocate(vseq) | |
| a = ttnn.experimental.nlp_concat_heads(full_view(o), memory_config=mem) # [1, 1, Np, C] | |
| ttnn.deallocate(o) | |
| p = tr._lin(a, bw.proj_w, bw.proj_b, dtype=tr.branch_dtype) | |
| ttnn.deallocate(a) | |
| x1 = ttnn.add(full_view(xp), p, memory_config=mem, dtype=tr.resid_dtype) | |
| ttnn.deallocate(p) | |
| if lp != np_: | |
| ttnn.deallocate(xp) | |
| h = tr._ln(x1, bw.n2_w, bw.n2_b) | |
| f = tr._mlp(h, bw) | |
| ttnn.deallocate(h) | |
| x2 = ttnn.add(x1, f, memory_config=mem, dtype=tr.resid_dtype) | |
| ttnn.deallocate(f) | |
| ttnn.deallocate(x1) | |
| out = ttnn.concat([view(x2, [1, 1, n, c], [1, 1, np_, c]), prefix_in], dim=2, memory_config=mem) # [1, 1, N + 5, C] | |
| ttnn.deallocate(x2) | |
| ttnn.deallocate(prefix_in) | |
| return full_view(out) | |
| def run(self, patches, state: KVState) -> List[object]: | |
| ttnn = _ttnn() | |
| tr = self.trunk | |
| s = self.shape | |
| np_, lp, c = s.np_, s.lp, self.cfg.dim | |
| x = tr.embed(patches) | |
| taps = [] | |
| for i in range(self.cfg.depth): | |
| bw = self.w.blocks[i] | |
| if i in self.cfg.cross_frame_blocks: | |
| y = self.block_step(x, bw, state.blocks.get(i)) | |
| else: | |
| y = tr.block_within(x, bw, fp32_attn=i in tr.fp32_blocks) | |
| if not any(x is t for t in taps): | |
| ttnn.deallocate(x) | |
| x = y | |
| if i in self.cfg.reassembled_blocks: | |
| taps.append(x) | |
| if not any(x is t for t in taps): | |
| ttnn.deallocate(x) | |
| out = [] | |
| for x in taps: | |
| y = ttnn.slice(x, [0, 0, 0, 0], [1, 1, np_, c], memory_config=tr.mem) if lp != np_ else x | |
| if y is not x: | |
| ttnn.deallocate(x) | |
| if y.dtype != ttnn.bfloat16: | |
| y2 = ttnn.typecast(y, ttnn.bfloat16, memory_config=tr.mem) | |
| ttnn.deallocate(y) | |
| y = y2 | |
| out.append(view(y, [1, 1, np_, c], [1, 1, np_, c])) | |
| return out | |