# SPDX-License-Identifier: Apache-2.0 """DEC stage, ttnn baseline: per frame reassemble + DPT decoder + head -> inverse depth. Stage contract (SPEC ยง3): * ``DEC.in`` the 4 taps ``[1, 1, T * Np, C]`` bf16 TILE DRAM (rows ``>= N`` of each frame ignored). * ``DEC.out`` ``inv`` ``[T, Hp, Wp]`` **float32 TILE DRAM**, the reference ``inverse_depth`` before the crop (``head.out[:, 0]``). ``ttnn.to_torch(inv)`` gives ``[T, Hp, Wp]`` directly. Feature maps are NHWC rows ``[1, 1, B * H * W, C]`` (bf16 TILE, DRAM interleaved) for a group of ``B`` frames. 3x3 convs = ``ttnn.conv2d`` (auto DRAM slicing), conv-transposes = ``ttnn.conv_transpose2d`` (DRAM height slicing), 1x1 convs = ``ttnn.linear`` on the rows. Conv weights are prepared by the op on the first (warm-up) call and cached per engine (so per shape). The last 1x1 conv (32 -> 1) runs on the transposed map: ``w^T @ y^T`` -> one float32 row of ``B * Hp * Wp`` pixels -> ``[B, Hp, Wp]`` (no 32x padded column). Frames are decoded in groups of ``B`` frames (``DEPTHPRO2_TTNN_DEC_PIX`` = max pixels per group, default 2^21 = 2.1 M ~ 6 VGA frames or one 1088x1920 frame; full-resolution maps hold ``B * Hp * Wp * max(dim_decoder / 2, 32)`` bf16 values); ``B`` divides T. The group is validated by the first (eager, warm-up) run of the engine: ttnn's conv2d / conv_transpose2d DRAM slicing picks its slice count from an L1 estimate that does not hold for large batches (L at 256x320, T = 16, group 16: "Statically allocated circular buffers ... clash with L1 buffers", the L1 buffer being the op's own per-slice input; nothing of ours is resident in L1). When that first run fails with an L1 circular-buffer clash or an L1 out-of-memory, the engine retries with the next smaller divisor of T (16 -> 8 -> 4 -> 2 -> 1) and keeps the group that works; later runs (trace capture, replays) use it unchanged. ``DEPTHPRO2_TTNN_DEC_GROUP`` (frames) caps the group. """ from __future__ import annotations import gc import logging import os from typing import Dict, List, Optional, Tuple import torch from ..reference import model as ref from . import StageShape from .ttnn_enc import Configs, _ttnn, free_unless_shared, kernel_config, view from .weights import ConvSpec, DecWeights, MatSpec, dev_tensor, upload_dec log = logging.getLogger(__name__) def l1_capacity_error(e: BaseException) -> bool: """A host-side L1 placement failure of an op (raised before anything is enqueued): CB / L1 buffer clash or L1 OOM.""" m = str(e) return "clash with L1 buffers" in m or ("Out of Memory" in m and "L1" in m) class Engine: """ttnn DEC engine for one :class:`StageShape`: ``run(taps) -> inv [T, Hp, Wp] float32``.""" def __init__(self, device, weights, shape: StageShape, size: Optional[str] = None): ttnn = _ttnn() if isinstance(weights, dict): if size is None: raise ValueError("size is required with host weights") weights = Engine.prepare_weights(device, weights, size) self.device = device self.w: DecWeights = weights self.shape = shape self.cfgs = Configs(device) self.conv_cfg = kernel_config(device, os.environ.get("DEPTHPRO2_TTNN_CONV_FID", "hifi4"), True) self.mem = ttnn.DRAM_MEMORY_CONFIG self.relu = ttnn.UnaryWithParam(ttnn.UnaryOpType.RELU) self.prepared: Dict[int, Tuple[object, object]] = {} T = shape.frames # 2^21: a 1088x1920 frame decodes alone (2 frames per group at that size: conv2d static CBs clash with an L1 # buffer for dim_decoder 256, L / H) max_pix = int(os.environ.get("DEPTHPRO2_TTNN_DEC_PIX", str(1 << 21))) self.group = max(1, min(T, max_pix // (shape.hp * shape.wp), int(os.environ.get("DEPTHPRO2_TTNN_DEC_GROUP", "16")))) while T % self.group: self.group -= 1 self.group_checked = False # set by the first successful run (see the module doc) # last 1x1 conv: row 0 of a [32, 32] tile holds the weights wr = torch.zeros(1, 1, 32, 32) wr[0, 0, 0] = self.w.head4_w self.head4_row = view(dev_tensor(wr, device), [1, 1, 1, 32], [1, 1, 32, 32]) self.slice_cfg = ttnn.Conv2dSliceConfig(slice_type=ttnn.Conv2dDRAMSliceHeight, num_slices=0) @staticmethod def prepare_weights(device, host_weights, size: str) -> DecWeights: # reassemble.0.1 (k4s4 conv-transpose) runs as ttnn.conv_transpose2d (no stock tile-friendly depth-to-space) return upload_dec(device, host_weights, ref.SIZES[size], convt4_matmul=False) # -- pieces def _conv(self, x, spec: ConvSpec, b: int, h: int, w: int, act: bool = False): ttnn = _ttnn() # config tensors in DRAM: they live as long as the cached program, and the 32 KB L1_SMALL per core fills up # after one shape's decoder (a second bucket / T then fails with an L1_SMALL OOM) cc = ttnn.Conv2dConfig(weights_dtype=ttnn.bfloat16, activation=self.relu if act else None, output_layout=ttnn.TILE_LAYOUT, config_tensors_in_dram=True) wt, bt = self.prepared.get(id(spec), (spec.w_host, spec.b_host)) common = dict(input_tensor=x, weight_tensor=wt, bias_tensor=bt, device=self.device, in_channels=spec.cin, out_channels=spec.cout, batch_size=b, input_height=h, input_width=w, kernel_size=(spec.k, spec.k), stride=(spec.stride, spec.stride), padding=(spec.pad, spec.pad), dilation=(1, 1), groups=1, conv_config=cc, compute_config=self.conv_cfg, dtype=ttnn.bfloat16, memory_config=self.mem, return_output_dim=True, return_weights_and_bias=True) if spec.transpose: y, (ho, wo), (pw, pb) = ttnn.conv_transpose2d(output_padding=(0, 0), dram_slice_config=self.slice_cfg, **common) else: y, (ho, wo), (pw, pb) = ttnn.conv2d(**common) self.prepared[id(spec)] = (pw, pb) if y.layout != ttnn.TILE_LAYOUT: y2 = ttnn.to_layout(y, ttnn.TILE_LAYOUT, memory_config=self.mem) ttnn.deallocate(y) y = y2 if y.is_sharded(): y2 = ttnn.sharded_to_interleaved(y, self.mem) ttnn.deallocate(y) y = y2 return y, ho, wo def _mm(self, x, spec: MatSpec): ttnn = _ttnn() return ttnn.linear(x, spec.w, bias=spec.b, memory_config=self.mem, dtype=ttnn.bfloat16, compute_kernel_config=self.cfgs.mm) def _residual(self, x, key: str, b: int, h: int, w: int): ttnn = _ttnn() r = ttnn.relu(x, memory_config=self.mem) y, _, _ = self._conv(r, self.w.res[key + ".c1"], b, h, w, act=True) ttnn.deallocate(r) y2, _, _ = self._conv(y, self.w.res[key + ".c3"], b, h, w) ttnn.deallocate(y) out = ttnn.add(x, y2, memory_config=self.mem) ttnn.deallocate(y2) return out def _fusion(self, x, i: int, skip, b: int, h: int, w: int): ttnn = _ttnn() if skip is not None: r = self._residual(skip, f"f{i}.r1", b, h, w) x2 = ttnn.add(x, r, memory_config=self.mem) ttnn.deallocate(r) ttnn.deallocate(x) x = x2 y = self._residual(x, f"f{i}.r2", b, h, w) ttnn.deallocate(x) d, h2, w2 = self._conv(y, self.w.deconv[i], b, h, w) ttnn.deallocate(y) o = self._mm(d, self.w.out_conv[i]) ttnn.deallocate(d) return o, h2, w2 def _nhwc(self, tap, b: int, i: int): """tap rows [1, 1, b * Np, C] -> reassemble.i.0 (1x1) -> NHWC rows [1, 1, b * N, d_i].""" ttnn = _ttnn() s = self.shape y = self._mm(tap, self.w.reassemble_mm[i]) d = self.w.reassemble_mm[i].cout if s.n == s.np_: return y if b == 1: return view(y, [1, 1, s.n, d], [1, 1, s.np_, d]) z = ttnn.reshape(view(y, [b, 1, s.n, d], [b, 1, s.np_, d]), [1, 1, b * s.n, d], memory_config=self.mem) free_unless_shared(y, z) return z def _pyramid(self, taps, b: int): s = self.shape gh, gw = s.gh, s.gw out = [] for i in range(4): x = self._nhwc(taps[i], b, i) if i in (0, 1): y, h, w = self._conv(x, self.w.reassemble_up[i], b, gh, gw) _ttnn().deallocate(x) elif i == 3: y, h, w = self._conv(x, self.w.reassemble_up[3], b, gh, gw) _ttnn().deallocate(x) else: y, h, w = x, gh, gw out.append((y, h, w)) return out def _final(self, x, b: int): """head.4 (1x1, 32 -> 1) + ReLU on NHWC rows [1, 1, P, 32] -> float32 [b, Hp, Wp].""" ttnn = _ttnn() s = self.shape xt = ttnn.transpose(x, -2, -1, memory_config=self.mem) # [1, 1, 32, P] z = ttnn.matmul(self.head4_row, xt, memory_config=self.mem, dtype=ttnn.float32, compute_kernel_config=self.cfgs.mm) ttnn.deallocate(xt) z2 = ttnn.relu(ttnn.add(z, self.w.head4_b, memory_config=self.mem), memory_config=self.mem) ttnn.deallocate(z) out = ttnn.reshape(z2, [b, s.hp, s.wp], memory_config=self.mem) free_unless_shared(z2, out) return out def decode(self, taps, b: int): """``taps``: 4 x [1, 1, b * Np, C] -> float32 [b, Hp, Wp].""" ttnn = _ttnn() pyr = self._pyramid(taps, b) (p3, h3, w3) = pyr[3] x, _, _ = self._conv(p3, self.w.convs[3], b, h3, w3) ttnn.deallocate(p3) x, h, w = self._fusion(x, 3, None, b, h3, w3) for i in (2, 1, 0): (pi, hi, wi) = pyr[i] skip, _, _ = self._conv(pi, self.w.convs[i], b, hi, wi) ttnn.deallocate(pi) assert (h, w) == (hi, wi), f"fusion {i}: {(h, w)} vs {(hi, wi)}" x, h, w = self._fusion(x, i, skip, b, hi, wi) ttnn.deallocate(skip) # head at 1/2 then 1/1 y, h, w = self._conv(x, self.w.head0, b, h, w) ttnn.deallocate(x) y2, h, w = self._conv(y, self.w.head1, b, h, w) ttnn.deallocate(y) y3, h, w = self._conv(y2, self.w.head2, b, h, w, act=True) ttnn.deallocate(y2) assert (h, w) == (self.shape.hp, self.shape.wp) out = self._final(y3, b) ttnn.deallocate(y3) return out def run(self, taps) -> object: if self.group_checked: return self._run(taps) while True: err = None try: out = self._run(taps) except RuntimeError as e: if self.group == 1 or not l1_capacity_error(e): raise err = str(e).split("info:")[-1].strip().splitlines()[0][:200] if err is None: self.group_checked = True return out # the failed attempt's tensors die with its traceback (outside the except block) gc.collect() g = self.group - 1 while self.shape.frames % g: g -= 1 log.warning("ttnn DEC %s: frame group %d does not fit in L1 (%s); retrying with group %d", self.shape, self.group, err, g) self.group = g self.prepared.clear() # prepared conv weights depend on the batch (shard / block config) def _run(self, taps) -> object: ttnn = _ttnn() s = self.shape T, g = s.frames, self.group if g == T: return self.decode(taps, T) outs = [] rows = g * s.np_ for f0 in range(0, T, g): part = [ttnn.slice(t, [0, 0, f0 * s.np_, 0], [1, 1, f0 * s.np_ + rows, t.shape[-1]], memory_config=self.mem) for t in taps] outs.append(self.decode(part, g)) for p in part: ttnn.deallocate(p) out = ttnn.concat(outs, dim=0, memory_config=self.mem) for o in outs: ttnn.deallocate(o) return out