File size: 27,770 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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# SPDX-License-Identifier: Apache-2.0
"""``DepthPro2Device``: the host/device boundary of the DepthPro2 port (SPEC §3).

Per compiled configuration (T frames at a padded bucket ``Hp x Wp``) the device holds one persistent input tensor
(the unfolded patches), the ENC and DEC engines and ONE trace (ENC + DEC). ``inverse_depth(x)`` = host unfold ->
``copy_host_to_device_tensor`` -> ``execute_trace`` -> readback. The FOV estimator has its own traces per
``(T, h, w)`` of the fov-resized frames.

Engines per stage (``engine={"enc": "mk"|"ttnn", "dec": ..., "fov": ...}``, default all ``"ttnn"``): the module
``tt.<engine>_<stage>`` must export ``Engine`` (contract in ``tt/__init__.py``); ``mk`` modules are imported lazily.

Configurations are compiled in three phases: (1) every engine and persistent tensor is created, (2) every engine runs
once eagerly (program compile, conv weight preparation), (3) every trace is captured. Nothing is allocated after the
first capture. A call with a (T, size) that was not compiled releases every trace, compiles the new configuration and
recaptures everything (slow; logged as a warning).

Runtime valid-frame count: an n-frame call runs the smallest compiled T >= n (zero frames in slots n..T-1) after
``Engine.set_valid_frames(n)`` when the ENC engine has ``supports_valid_frames`` (ttnn: yes); else T = n exactly.

Unbuffered video: ``kv_cache(bucket, window)`` / ``inverse_depth_step(x, cache)`` (``tt/ttnn_kv.py``; the semantics
of ``cpu_engine.CPUEngine``), one step trace per cache slot, ring of ``max_frames`` frames.

Trace-region sizing: :func:`trace_region_bytes`; one KV cache's DRAM: :func:`kv_state_bytes`.

Device-open requirements (ttnn engines): ``l1_small_size >= 32768`` (conv2d), a trace region large enough for all
traces (measured per configuration, ENC + DEC + FOV: ~16 MB (S) to ~28 MB (H+) at 480x640 T=1; the DEC trace grows
with T x resolution, ~142 MB at 1088x1920 T=16; logs/depthpro2/baseline/BASELINE.md §5), ETH dispatch recommended.

Example::

    import ttnn
    from tt_depthpro2.reference import model as ref
    from tt_depthpro2.tt.model import DepthPro2Device
    from tt_depthpro2.tt.weights import load_weights

    dev = ttnn.open_device(device_id=0, l1_small_size=32768, trace_region_size=256 << 20,
                           dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH))
    m = DepthPro2Device(dev, "S", load_weights(".../DepthPro2-S"), load_weights(".../DepthPro2-focal"),
                        buckets=[(480, 640)], max_frames=4, frames=(1,))
    x = ref.pad_to_multiple(ref.preprocess(frames_u8))           # [T, 3, 480, 640]
    inv = m.inverse_depth(x)                                      # [T, 480, 640] float32
    logits = m.fov_logits(ref.fov_resize(ref.preprocess(frames_u8)))
    m.close(); ttnn.close_device(dev)
"""

from __future__ import annotations

import importlib
import logging
import os
import time
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Sequence, Tuple

import torch

from ..reference import model as ref
from . import StageShape
from .weights import unfold_patches

log = logging.getLogger(__name__)

STAGES = ("enc", "dec", "fov")
ENGINES = ("ttnn", "mk")


def _norm_size(size: str) -> str:
    s = size.strip().upper().rstrip("+")
    if s not in ref.SIZES:
        raise ValueError(f"unknown DepthPro2 size {size!r} (S, B, L, H)")
    return s


def engine_class(stage: str, engine: str):
    """``tt.<engine>_<stage>.Engine`` (``mk`` modules are imported only when requested)."""
    if stage not in STAGES or engine not in ENGINES:
        raise ValueError(f"engine {engine!r} for stage {stage!r}: expected stage in {STAGES}, engine in {ENGINES}")
    mod = f"{__package__}.{engine}_{stage}"
    try:
        m = importlib.import_module(mod)
        cls = getattr(m, "Engine", None)  # a package may import its Engine lazily
    except Exception as e:  # noqa: BLE001  (missing / half-written mk module: a clear error naming it)
        raise RuntimeError(f"DepthPro2 engine {engine!r} for stage {stage!r} needs module {mod}, which is not usable "
                           f"({type(e).__name__}: {e}); use engine {{'{stage}': 'ttnn'}} instead") from e
    if cls is None:
        raise RuntimeError(f"{mod} does not export Engine")
    return cls


@dataclass
class _Program:
    """One traced configuration: engines, persistent input, output of the last capture, trace id."""

    shape: StageShape
    engines: List[object]
    inp: object
    out: object = None
    trace: Optional[int] = None
    warm: bool = False
    stats: Dict[str, float] = field(default_factory=dict)
    run: Optional[object] = None  # callable(inp) -> output (else the engines are chained)


def parse_engine(engine) -> Dict[str, str]:
    """``None`` | ``"mk"`` | ``"ttnn"`` | ``"enc=mk,dec=ttnn"`` | dict -> ``{stage: kind}`` for every stage (default ttnn)."""
    out = {s: "ttnn" for s in STAGES}
    if engine is None:
        return out
    if isinstance(engine, str):
        e = engine.strip()
        if e in ENGINES:
            return {s: e for s in STAGES}
        engine = dict(kv.split("=", 1) for kv in e.split(",") if kv.strip())
    for k, v in dict(engine).items():
        k, v = str(k).strip(), str(v).strip()
        if k not in STAGES or v not in ENGINES:
            raise ValueError(f"engine {k}={v!r}: stages {STAGES}, kinds {ENGINES}")
        out[k] = v
    return out


class KVCache:
    """Handle of one unbuffered-video key-value cache (one stream) for one bucket (``DepthPro2Device.kv_cache``):
    ``reset()``, ``close()``, ``frames`` (frames held, ``<= window``). Same semantics as ``cpu_engine.CPUKVCache``."""

    def __init__(self, owner: "DepthPro2Device", bucket: Tuple[int, int], window: int, slot: "_KVSlot"):
        self._owner = owner
        self.bucket = tuple(bucket)
        self.window = int(window)
        self._slot = slot
        self.seen = 0
        self.closed = False

    @property
    def frames(self) -> int:
        return min(self.seen, self.window)

    @property
    def nbytes(self) -> int:
        """Device bytes of this cache's ring state (the compiled ring holds ``max_frames - 1`` previous frames)."""
        return self._slot.state.nbytes

    def reset(self) -> None:
        self.seen = 0

    def close(self) -> None:
        if not self.closed:
            self.closed = True
            self._owner._release_kv(self)


@dataclass
class _KVSlot:
    """A device ring state plus the step trace bound to it (one per concurrently open cache)."""

    state: object
    program: _Program
    in_use: bool = False


class DepthPro2Device:
    """See the module doc.

    Keywords beyond SPEC §3 (``api.py`` passes them when present):

    * ``fov_shapes``: the fov-resized ``(h, w)`` sizes to compile (default ``fov_size`` of every bucket);
    * ``clip_lengths``: clip lengths the caller will use (``"all"`` = 1..max_frames). With an ENC engine that has a
      runtime valid-frame count (``Engine.supports_valid_frames``; the ttnn engine has it) only T = ``max_frames``
      and (if 1 is asked for) T = 1 are compiled and any n <= max_frames is served by the smallest compiled T >= n;
      otherwise every asked length is compiled exactly;
    * ``precision``: ``None`` / ``"bf16"`` (the only gated precision; bf16 weights, fp32 residual stream);
    * ``kv_cache``: build the unbuffered-video step programs (``kv_cache`` / ``inverse_depth_step``) for every bucket
      with a ring of ``max_frames`` frames; ``kv_streams`` caches per bucket are allocated up front (more are added on
      demand: all traces are recaptured, slow).
    """

    supports_kv_cache = True

    def __init__(self, device, size: str, size_weights: dict, fov_weights: Optional[dict],
                 buckets: Sequence[Tuple[int, int]], max_frames: int, engine: Optional[dict] = None,
                 frames: Optional[Sequence[int]] = None, fov_shapes: Optional[Sequence[Tuple[int, int]]] = None,
                 clip_lengths=None, precision: Optional[str] = None, kv_cache: bool = False,
                 kv_streams: Optional[int] = None):
        import ttnn

        self.device = device
        self.size = _norm_size(size)
        self.cfg = ref.SIZES[self.size]
        self.engine = parse_engine(engine)
        if precision not in (None, "bf16"):
            raise ValueError(f"precision={precision!r}: the device engines run bf16 weights (the only gated precision)")
        self.precision = "bf16"
        self.buckets = [(int(h), int(w)) for h, w in buckets]
        for h, w in self.buckets:
            if h % 32 or w % 32:
                raise ValueError(f"bucket {h}x{w}: padded sizes must be multiples of 32")
        self.max_frames = int(max_frames)
        if not 1 <= self.max_frames <= 64:
            raise ValueError(f"max_frames {max_frames} outside 1..64")
        self._cls = {s: engine_class(s, self.engine[s]) for s in ("enc", "dec")}
        self.valid_frames = bool(getattr(self._cls["enc"], "supports_valid_frames", False))
        if isinstance(clip_lengths, str):
            if clip_lengths != "all":
                raise ValueError(f"clip_lengths={clip_lengths!r}: 'all' or a list of lengths")
            asked = set(range(1, self.max_frames + 1))
        else:
            asked = {int(t) for t in (clip_lengths or ())}
        asked |= {self.max_frames, *(int(t) for t in (frames or ()))}
        if any(not 1 <= t <= self.max_frames for t in asked):
            raise ValueError(f"clip lengths {sorted(asked)} outside 1..{self.max_frames}")
        if self.valid_frames:
            self.frame_counts = sorted({self.max_frames} | ({1} if 1 in asked else set()))
            self.clip_lengths = tuple(range(1, self.max_frames + 1))
        else:
            self.frame_counts = sorted(asked)
            self.clip_lengths = tuple(self.frame_counts)
        self._weights = {
            "enc": self._prepare(self._cls["enc"], size_weights, self.size),
            "dec": self._prepare(self._cls["dec"], size_weights, self.size),
        }
        self.has_fov = fov_weights is not None
        if self.has_fov:
            self._cls["fov"] = engine_class("fov", self.engine["fov"])
            self._weights["fov"] = self._prepare(self._cls["fov"], fov_weights, "fov")
        self.last_timing: Dict[str, float] = {}
        self._depth: Dict[Tuple[int, int, int], _Program] = {}
        self._fov: Dict[Tuple[int, int, int], _Program] = {}
        self._kv: Dict[Tuple[int, int], dict] = {}
        self._size_weights = size_weights
        self._captured = False
        t0 = time.perf_counter()
        if self.has_fov:
            fs = fov_shapes if fov_shapes is not None else [self.fov_size(h, w) for h, w in self.buckets]
            self.fov_shapes = sorted({(int(h), int(w)) for h, w in fs})
        else:
            self.fov_shapes = []
        for h, w in self.buckets:
            for t in self.frame_counts:
                self._build_depth(StageShape(t, h, w))
        for h, w in self.fov_shapes:
            for t in self.frame_counts:
                self._build_fov(StageShape(t, h, w))
        self.kv_streams = int(kv_streams if kv_streams is not None else os.environ.get("DEPTHPRO2_KV_STREAMS", "1"))
        if kv_cache:
            for h, w in self.buckets:
                for _ in range(max(1, self.kv_streams)):
                    self._add_kv_slot((h, w))
        self._warm_all()
        self._capture_all()
        self.compile_seconds = time.perf_counter() - t0
        self._ttnn = ttnn

    # ------------------------------------------------------------------------------------------- setup
    def _prepare(self, cls, host, size):
        prep = getattr(cls, "prepare_weights", None)
        return prep(self.device, host, size) if prep is not None else host

    @staticmethod
    def fov_size(h: int, w: int) -> Tuple[int, int]:
        """Size of ``reference.fov_resize`` output for an ``h x w`` frame."""
        y = ref.fov_resize(torch.zeros(1, 3, h, w))
        return int(y.shape[-2]), int(y.shape[-1])

    def _alloc_input(self, rows: int):
        import ttnn

        host = ttnn.from_torch(torch.zeros(1, 1, rows, 768, dtype=torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT)
        return ttnn.to_device(host, self.device, memory_config=ttnn.DRAM_MEMORY_CONFIG)

    def _build_depth(self, shape: StageShape) -> _Program:
        key = (shape.frames, shape.hp, shape.wp)
        if key not in self._depth:
            enc = self._cls["enc"](self.device, self._weights["enc"], shape)
            dec = self._cls["dec"](self.device, self._weights["dec"], shape)
            self._depth[key] = _Program(shape, [enc, dec], self._alloc_input(shape.frames * shape.np_))
        return self._depth[key]

    def _build_fov(self, shape: StageShape) -> _Program:
        key = (shape.frames, shape.hp, shape.wp)
        if key not in self._fov:
            fov = self._cls["fov"](self.device, self._weights["fov"], shape)
            self._fov[key] = _Program(shape, [fov], self._alloc_input(shape.frames * shape.np_))
        return self._fov[key]

    def _kv_bucket(self, bucket: Tuple[int, int]) -> dict:
        """Per-bucket step machinery: ttnn step encoder (always ttnn), T=1 decoder, shared persistent input."""
        from .ttnn_enc import Engine as TtnnEnc
        from .ttnn_kv import StepEncoder

        kb = self._kv.get(bucket)
        if kb is None:
            shape = StageShape(1, *bucket)
            if self.engine["enc"] == "ttnn":
                tw = self._weights["enc"]
            else:
                tw = self._weights.setdefault("enc_ttnn", TtnnEnc.prepare_weights(self.device, self._size_weights, self.size))
            p1 = self._depth.get((1,) + tuple(bucket))
            dec = p1.engines[1] if p1 is not None else self._cls["dec"](self.device, self._weights["dec"], shape)
            kb = self._kv[bucket] = {"shape": shape, "enc": StepEncoder(self.device, tw, shape, self.max_frames),
                                     "dec": dec, "inp": self._alloc_input(shape.np_), "slots": []}
        return kb

    def _add_kv_slot(self, bucket: Tuple[int, int]) -> _KVSlot:
        from .ttnn_kv import KVState

        kb = self._kv_bucket(bucket)
        state = KVState(self.device, kb["shape"], self.cfg, self.max_frames, self.cfg.cross_frame_blocks)
        enc, dec = kb["enc"], kb["dec"]
        prog = _Program(kb["shape"], [], kb["inp"], run=lambda inp, e=enc, d=dec, st=state: d.run(e.run(inp, st)))
        slot = _KVSlot(state, prog)
        kb["slots"].append(slot)
        return slot

    @staticmethod
    def _run_program(p: _Program):
        if p.run is not None:
            return p.run(p.inp)
        x = p.inp
        for e in p.engines:
            x = e.run(x)
        return x

    def _programs(self) -> List[_Program]:
        kv = [s.program for kb in self._kv.values() for s in kb["slots"]]
        return list(self._depth.values()) + list(self._fov.values()) + kv

    def _warm_all(self) -> None:
        import ttnn

        for p in self._programs():
            if not p.warm:
                t0 = time.perf_counter()
                out = self._run_program(p)
                ttnn.synchronize_device(self.device)
                ttnn.deallocate(out)
                p.warm = True
                p.stats["warm_s"] = time.perf_counter() - t0

    def _capture_all(self) -> None:
        import ttnn

        for p in self._programs():
            if p.trace is None:
                tid = ttnn.begin_trace_capture(self.device, cq_id=0)
                p.out = self._run_program(p)
                ttnn.end_trace_capture(self.device, tid, cq_id=0)
                p.trace = tid
        ttnn.synchronize_device(self.device)
        self._captured = True

    def _release_all(self) -> None:
        import ttnn

        for p in self._programs():
            if p.trace is not None:
                ttnn.release_trace(self.device, p.trace)
                p.trace = None
                if p.out is not None:
                    ttnn.deallocate(p.out)
                    p.out = None
        self._captured = False

    def _recompile(self, build, *args):
        """Release every trace, build something new (allocations), warm it, recapture everything."""
        log.warning("DepthPro2Device: building %s at run time (all traces are recaptured)", args)
        self._release_all()
        r = build(*args)
        self._warm_all()
        self._capture_all()
        return r

    def _ensure(self, table: dict, build, shape: StageShape) -> _Program:
        key = (shape.frames, shape.hp, shape.wp)
        p = table.get(key)
        if p is not None and p.trace is not None:
            return p
        return self._recompile(build, shape)

    def _pick(self, table: dict, build, n: int, h: int, w: int, padded_ok: bool) -> _Program:
        """The program for an n-frame call: the smallest compiled T >= n when ``padded_ok``, else exactly n."""
        if padded_ok:
            ts = sorted(t for (t, hh, ww) in table if (hh, ww) == (h, w) and t >= n)
            if ts:
                return self._ensure(table, build, StageShape(ts[0], h, w))
        return self._ensure(table, build, StageShape(n, h, w))

    # ------------------------------------------------------------------------------------------- run
    def _upload(self, p: _Program, patches: torch.Tensor) -> None:
        import ttnn

        t0 = time.perf_counter()
        host = ttnn.from_torch(patches.to(torch.bfloat16).reshape(1, 1, -1, 768), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT)
        t1 = time.perf_counter()
        ttnn.copy_host_to_device_tensor(host, p.inp, cq_id=0)
        self.last_timing.update(tilize_ms=(t1 - t0) * 1e3, upload_ms=(time.perf_counter() - t1) * 1e3)

    def _run_traced(self, p: _Program, frames: torch.Tensor, before=None):
        """unfold -> upload -> (``before()``: runtime inputs) -> replay -> readback (``last_timing``: host ms)."""
        import ttnn

        self.last_timing = {}
        t0 = time.perf_counter()
        t = p.shape.frames
        x = frames.float()
        if x.shape[0] < t:  # runtime valid-frame count: zero frames in the unused slots
            x = torch.cat([x, x.new_zeros((t - x.shape[0],) + tuple(x.shape[1:]))])
        patches = unfold_patches(x, p.shape.np_)
        self.last_timing["unfold_ms"] = (time.perf_counter() - t0) * 1e3
        self._upload(p, patches)
        if before is not None:
            before()
        t1 = time.perf_counter()
        ttnn.execute_trace(self.device, p.trace, cq_id=0, blocking=False)
        out = ttnn.to_torch(p.out).float()
        self.last_timing["replay_readback_ms"] = (time.perf_counter() - t1) * 1e3
        return out

    def inverse_depth(self, x: torch.Tensor) -> torch.Tensor:
        """Normalized, padded frames ``[n, 3, Hp, Wp]`` float32 -> inverse depth ``[n, Hp, Wp]`` float32 (pre-crop).
        Runs the smallest compiled T >= n with a runtime valid-frame count n (exactly n-frame semantics)."""
        if x.ndim != 4 or x.shape[1] != 3:
            raise ValueError(f"expected [T, 3, Hp, Wp], got {tuple(x.shape)}")
        n, _, h, w = (int(v) for v in x.shape)
        if n < 1:
            raise ValueError("inverse_depth: empty clip")
        p = self._pick(self._depth, self._build_depth, n, h, w, self.valid_frames)
        enc = p.engines[0]
        before = (lambda: enc.set_valid_frames(n)) if p.shape.frames > 1 and self.valid_frames else None
        return self._run_traced(p, x, before).reshape(p.shape.frames, h, w)[:n]

    def fov_logits(self, y: torch.Tensor) -> torch.Tensor:
        """fov_resize'd frames ``[n, 3, h, w]`` float32 -> logits ``[n, 2]`` float32 (frames are independent: the
        smallest compiled T >= n runs with zero frames in the unused slots)."""
        if not self.has_fov:
            raise RuntimeError("DepthPro2Device was created without FOV weights")
        if y.ndim != 4 or y.shape[1] != 3:
            raise ValueError(f"expected [T, 3, h, w], got {tuple(y.shape)}")
        n, _, h, w = (int(v) for v in y.shape)
        p = self._pick(self._fov, self._build_fov, n, h, w, True)
        return self._run_traced(p, y).reshape(p.shape.frames, 2)[:n]

    # ------------------------------------------------------------------------------------------- unbuffered video
    def kv_cache(self, bucket: Tuple[int, int], window: int) -> KVCache:
        """Open a key-value cache of the last ``window`` frames (``1 <= window <= max_frames``) for one padded bucket
        (one per stream). Step programs of the bucket are built on first use if ``kv_cache=False`` was passed."""
        bucket = (int(bucket[0]), int(bucket[1]))
        if bucket not in self.buckets:
            raise ValueError(f"kv_cache: {bucket} is not a compiled size {self.buckets}")
        if not 1 <= int(window) <= self.max_frames:
            raise ValueError(f"kv_cache: window {window} outside 1..{self.max_frames}")
        kb = self._kv.get(bucket)
        free = [s for s in (kb["slots"] if kb else []) if not s.in_use]
        slot = free[0] if free else self._recompile(self._add_kv_slot, bucket)
        slot.in_use = True
        return KVCache(self, bucket, int(window), slot)

    def _release_kv(self, cache: KVCache) -> None:
        cache._slot.in_use = False

    def inverse_depth_step(self, x: torch.Tensor, cache: KVCache) -> torch.Tensor:
        """One normalized, padded frame ``[1, 3, Hp, Wp]`` attending the cache -> inverse depth ``[1, Hp, Wp]``
        (``cpu_engine.CPUEngine.inverse_depth_step`` semantics); the frame is added to the cache."""
        if not isinstance(cache, KVCache) or cache._owner is not self:
            raise ValueError("inverse_depth_step: the cache must come from this device's kv_cache()")
        if cache.closed:
            raise RuntimeError("inverse_depth_step: the cache is closed")
        if x.ndim != 4 or x.shape[0] != 1 or x.shape[1] != 3:
            raise ValueError(f"inverse_depth_step takes one frame (1, 3, H, W), got {tuple(x.shape)}")
        if tuple(int(v) for v in x.shape[-2:]) != cache.bucket:
            raise ValueError(f"inverse_depth_step: frame {tuple(x.shape[-2:])} != the cache's {cache.bucket}")
        kb = self._kv[cache.bucket]
        p = cache._slot.program
        fill = min(cache.seen + 1, cache.window)
        out = self._run_traced(p, x, lambda: kb["enc"].set_fill(fill))
        cache.seen += 1
        return out.reshape(1, *cache.bucket)

    def kv_cache_bytes(self) -> int:
        """Device bytes of one cache's ring state for each bucket (the largest)."""
        sizes = [s.state.nbytes for kb in self._kv.values() for s in kb["slots"]]
        return max(sizes) if sizes else kv_state_bytes(self.size, self.buckets, self.max_frames)

    # ------------------------------------------------------------------------------------------- info
    def configurations(self) -> Dict[str, List[Tuple[int, int, int]]]:
        return {"depth": sorted(self._depth), "fov": sorted(self._fov),
                "kv": [(b, len(kb["slots"])) for b, kb in self._kv.items()]}

    def close(self) -> None:
        if getattr(self, "_depth", None) is None:
            return
        try:
            self._release_all()
        finally:
            for kb in self._kv.values():
                for s in kb["slots"]:
                    s.state.free()
            self._kv.clear()
            self._depth.clear()
            self._fov.clear()


# ----------------------------------------------------------------------------------------------- sizing

# measured trace bytes of the ttnn engines (logs/depthpro2/baseline/bench.jsonl): ENC base per size (VGA, T=1),
# per fp32-attention query chunk; DEC per frame group = a + b * Mpixels of the group; FOV per (shape, T)
_ENC_BASE_MB = {"S": 7.5, "B": 7.5, "L": 14.5, "H": 21.0}
_FP32_CHUNK_MB = 0.05
_DEC_GROUP_MB = {"S": (0.9, 0.7), "B": (0.95, 1.4), "L": (0.9, 4.0), "H": (0.9, 4.0)}
_FOV_MB = 8.0
_STEP_EXTRA_MB = 3.0


def _enc_trace_mb(size: str, t: int, hp: int, wp: int) -> float:
    from .ttnn_enc import FP32_ATTN_BLOCKS

    s = StageShape(t, hp, wp)
    heads = ref.SIZES[size].heads
    budget = 256 << 20
    q_rows = max(32, min(s.lp, budget // (t * heads * s.lp * 4) // 32 * 32))
    chunks = -(-s.lp // q_rows) * len(FP32_ATTN_BLOCKS[size])
    return _ENC_BASE_MB[size] + _FP32_CHUNK_MB * chunks


def _dec_trace_mb(size: str, t: int, hp: int, wp: int) -> float:
    max_pix = int(os.environ.get("DEPTHPRO2_TTNN_DEC_PIX", str(1 << 21)))
    g = max(1, min(t, max_pix // (hp * wp)))
    while t % g:
        g -= 1
    a, b = _DEC_GROUP_MB[size]
    return (t // g) * (a + b * g * hp * wp / 1e6)


def trace_region_bytes(size: str, buckets: Sequence[Tuple[int, int]], frames: Sequence[int], engine=None,
                       fov_shapes: Optional[Sequence[Tuple[int, int]]] = None, kv_cache: bool = False,
                       kv_streams: int = 1, margin: float = 1.3) -> int:
    """Estimated trace-region bytes for a ``DepthPro2Device`` of ``size`` with these padded ``buckets`` and compiled
    clip lengths ``frames`` (the T values that get a program: ``max_frames`` and 1 if images are served), ``fov_shapes``
    (default: ``fov_size`` of each bucket; ``[]`` = no FOV) and the unbuffered step programs (``kv_cache``, one per
    stream and bucket). From the measured ttnn trace sizes, times ``margin``, plus 32 MiB, rounded up to 32 MiB.
    ``mk`` stages are estimated with the ttnn numbers (an upper bound for megakernels)."""
    size = _norm_size(size)
    frames = sorted({int(t) for t in frames})
    if fov_shapes is None:
        fov_shapes = [DepthPro2Device.fov_size(h, w) for h, w in buckets]
    mb = 0.0
    for hp, wp in buckets:
        for t in frames:
            mb += _enc_trace_mb(size, t, hp, wp) + _dec_trace_mb(size, t, hp, wp)
        if kv_cache:
            mb += kv_streams * (_enc_trace_mb(size, 1, hp, wp) + _dec_trace_mb(size, 1, hp, wp) + _STEP_EXTRA_MB)
    for h, w in fov_shapes:
        for t in frames:  # the FOV trunk is ViT-S: its fp32-attention chunks as for S
            mb += _FOV_MB + (_enc_trace_mb("S", t, h, w) - _ENC_BASE_MB["S"])
    total = int(mb * margin * (1 << 20)) + (32 << 20)
    return -(-total // (32 << 20)) * (32 << 20)


def planned_frames(max_frames: int, frames: Optional[Sequence[int]] = None, clip_lengths=None, engine=None) -> List[int]:
    """The T values ``DepthPro2Device`` compiles for these arguments (``trace_region_bytes``' ``frames``): with an ENC
    engine that supports a runtime valid-frame count, ``max_frames`` and 1 (if 1 is asked for); else every asked
    length."""
    asked = set(range(1, max_frames + 1)) if clip_lengths == "all" else {int(t) for t in (clip_lengths or ())}
    asked |= {int(max_frames), *(int(t) for t in (frames or ()))}
    enc = engine_class("enc", parse_engine(engine)["enc"])
    if getattr(enc, "supports_valid_frames", False):
        return sorted({int(max_frames)} | ({1} if 1 in asked else set()))
    return sorted(asked)


def kv_state_bytes(size: str, buckets: Sequence[Tuple[int, int]], max_frames: int) -> int:
    """Device bytes of ONE unbuffered-video cache (the largest bucket): per cross-frame block K and V of
    ``max_frames - 1`` frames (bf16) + their prefix rows (fp32)."""
    from . import ceil32

    cfg = ref.SIZES[_norm_size(size)]
    best = 0
    for hp, wp in buckets:
        n = (hp // 16) * (wp // 16)
        rows = (max_frames - 1) * n
        per = 2 * cfg.heads * ceil32(rows) * 64 * 2 + (max_frames - 1) * 32 * cfg.dim * 4 if max_frames > 1 else 0
        best = max(best, per * len(cfg.cross_frame_blocks))
    return best