# SPDX-License-Identifier: Apache-2.0 """RDT2-FM on one p150: VISION | PREFIX | EXPERT on ttnn, fixed input buffers, one Metal trace per prompt bucket. host pre : cameras -> window-order normalized patch rows (1, 1, 1536, 608) fp32; prompt -> bucket ids (1, L) uint32 (image rows -> zero embedding row); key mask (1, 1, 32, L); noise (1, 1, 32, 32); state write : 5 host tensors copied into device buffers allocated once (fixed addresses) device : VISION (32 ViT blocks + merger) -> PREFIX (embedding + scatter, 13 layers + layer-13 K/V) -> EXPERT (prologue: state MLP + adaLN state half; 5 x [14 RDT blocks + final layer + Euler update]) read : normalized action (1, 1, 32, 32) fp32 -> [:24, :20] host post : UMI unnormalize -> (24, 20) Prompt buckets (default 416 / 448 / 512) are all resident: per bucket, the ids / key-mask input buffers, the PREFIX tables (mRoPE cos / sin, scatter matrix) and one Metal trace of the whole call (vision + prefix + 5 steps). The pixel, noise and state buffers are shared. ``__call__`` tokenizes, picks the smallest bucket that holds the prompt, writes the inputs and replays that bucket's trace. ``run_eager`` runs the same graph op by op (gates compare the two bit for bit). Engines (megakernel workflow + optimization round 3): ``engine={"vision": "ttnn" | "mk", "prefix": "ttnn" | "fused" | "mk", "expert": "ttnn" | "mk"}`` selects per program the ttnn op-by-op baseline or the persistent megakernel (``tt/mk_expert``: the whole action head of a call as one ``generic_op`` program; ``tt/mk_prefix``: the LLM prefill of a bucket as one program; ``tt/mk_vision``: the 32 ViT blocks + the merger norm as one program between the ttnn patch embedding and the ttnn merger MLP; PREFIX "fused": the ttnn PREFIX graph with tuned matmul configs and two fused generic_op programs per layer, tt/px_fused.py). Mixed engines share the same buffers: both VISION engines return the (1, 1, 384, 3584) merger rows the PREFIX scatters; the EXPERT megakernel reads the K / V the PREFIX writes (the ttnn PREFIX allocates them per call, the PREFIX megakernel writes the bucket's persistent K / V buffers) and writes the normalized action into its persistent per-bucket output tile. ``DEFAULT_ENGINE`` flips a program to "mk" only when the full device suite passes with it; ``RDT2_ENGINE="expert=mk"`` overrides it (tests, benches). ``prefix=mk`` is EXPERIMENTAL (it hangs the device on repeated replays at bucket 512) and is refused unless ``RDT2_EXPERIMENTAL_PREFIX_MK=1`` is set (:func:`check_engine_allowed`). Device-memory contract (trace safety; VLA-JEPA verifier r1 F2, kept by the megakernel stage): * every persistent buffer (weights, arenas, per-bucket tables, input buffers, the megakernel's per-bucket output and debug buffers) is allocated in ``__init__``; from the first ``begin_trace_capture`` on the model is *sealed*: ``_persistent`` (and ``PrefixTT.add_bucket``) refuse any new persistent allocation, the recorded persistent addresses are re-checked at every capture and replay (``check_persistent``), and the device allocator state (DRAM and L1 bytes allocated per bank, ``ttnn.get_memory_view``) recorded at the end of ``capture()`` must be unchanged at every replay: any buffer allocated after the capture and still alive at a replay (a persistent allocation after the seal or a leak) raises (VERIFY_MK_r1 R1-F2; ``strict_memory = False`` turns this last check off for a caller that deliberately keeps its own device tensors alive across replays); * ``capture()`` first runs every bucket eagerly (kernel JIT, program cache, kernel-binary buffers), then captures the buckets one after the other; nothing else is allocated between a capture and the replays; * a later capture may reuse freed scratch of an earlier trace, so the outputs of bucket L (action, stage outputs) are valid only until another bucket's trace is replayed: read them right after ``replay(L)`` (``__call__`` does); * ``run_eager`` refuses to run while any trace is alive (its outputs could land in a trace's scratch). """ from __future__ import annotations import os import time from typing import Any, Dict, Optional, Sequence import numpy as np import torch from ..reference.config import CONFIG, DEFAULT_DIRS from ..reference.expert import unnormalize_action from ..reference.geometry import DEFAULT_NUM_CAMERAS, Geometry, geometry from ..reference.preprocess import PROMPT_BUCKETS, choose_bucket, tokenize from ..reference.weights import load_action_normalizer, load_expert_state_dict, load_vlm_index from .common import resolve_precision, upload from .expert import ACT_P, ROWS, ExpertTT, host_mask, host_noise, host_state from .prefix import PrefixTT, host_ids from .vision import K_PE, N_ROWS, VisionTT, host_pixels E = CONFIG.expert DEFAULT_BUCKET = PROMPT_BUCKETS[0] TRACE_REGION_SIZE = 512 << 20 # one trace per bucket (3 x ~3 400 ops) ENGINES = ("ttnn", "mk") # engines per program: the PREFIX also has "fused" (optimization round 3: the ttnn graph with tuned matmul configs and # the fused addnorm / qkvpost generic_op programs of tt/px_fused.py; OPT_REPORT.md round 3) PROGRAM_ENGINES = {"vision": ("ttnn", "mk"), "prefix": ("ttnn", "fused", "mk"), "expert": ("ttnn", "mk")} # EXPERT default flipped to the megakernel on 2026-11-17: the full device suite (10 tests incl. the hold-out set) passes # with it under ETH (12 x 10) and WORKER (11 x 10) dispatch (MK_LOG.md section 2); "ttnn" stays the fallback path # PREFIX megakernel (tt/mk_prefix, stage 2): passes the full device suite with prefix=mk (ETH; MK_LOG.md section 4) # but its program is slower than the ttnn PREFIX (71 vs 37 ms at 416) and it HANGS the device on repeated trace replays # at bucket 512 (VERIFY_MK_r2 R2-F1: 4 hangs in 4 runs, after 5..325 replays): EXPERIMENTAL. The default stays "ttnn"; # RDT2_ENGINE="prefix=mk" is refused at construction unless RDT2_EXPERIMENTAL_PREFIX_MK=1 (check_engine_allowed) # VISION default flipped to the megakernel (tt/mk_vision, stage 3) on 2026-11-17: the full device suite (10 tests incl. # the hold-out set) passes with it (ETH 12 x 10 and WORKER 11 x 10, MK_LOG.md section 5) and the stage is faster than # the ttnn VISION; "ttnn" stays the fallback (RDT2_ENGINE="vision=ttnn") # PREFIX default flipped to "fused" on 2026-11-18 (optimization round 3, OPT_REPORT.md): the full device suite (incl. the # hold-out set) passes with it on ETH and WORKER, plus the 500-request stress gate; PREFIX 38.9 -> 32.1 ms at 416 # (same host); "ttnn" (op by op) stays the fallback (RDT2_ENGINE="prefix=ttnn") DEFAULT_ENGINE = {"vision": "mk", "prefix": "fused", "expert": "mk"} def resolve_engine(engine=None) -> Dict[str, str]: """``engine`` dict (or "expert=mk,..." string) over DEFAULT_ENGINE; ``RDT2_ENGINE`` applies when engine is None.""" import os out = dict(DEFAULT_ENGINE) if engine is None: engine = os.environ.get("RDT2_ENGINE", "") if isinstance(engine, str): engine = dict(kv.split("=") for kv in engine.split(",") if kv) for k, v in engine.items(): if k not in out or v not in PROGRAM_ENGINES[k]: raise ValueError(f"engine {k}={v}: programs {tuple(out)}, engines {PROGRAM_ENGINES}") out[k] = v return out def explicit_engine(engine=None) -> Dict[str, str]: """The engines named explicitly (``engine`` argument, else ``RDT2_ENGINE``), without the defaults.""" if engine is None: engine = os.environ.get("RDT2_ENGINE", "") if isinstance(engine, str): engine = dict(kv.split("=") for kv in engine.split(",") if kv) return dict(engine) def engine_unsupported(engine: Dict[str, str], geom: Geometry, buckets: Sequence[int], grid) -> Dict[str, str]: """Per program, why its engine cannot run these resident buckets on this grid (empty = all supported): * EXPERT "mk": its cross-attention splits a bucket's keys into 4 chunks of at most 4 tiles per head (buckets of at most 512 keys, every chunk starting below the shortest prompt); * PREFIX "fused": its addnorm program needs <= 32 column tiles per core and qkvpost <= 13 heads per core. The 2-camera buckets 416 / 448 / 512 pass both on the 12 x 10 (ETH) and 11 x 10 (WORKER) grids for every step count, so a served configuration never falls back (``engine_fallbacks`` is empty, tests/test_config_host.py); the checks remain for a developer ``RDT2FMTT(buckets=...)`` outside them. (Round 4's 1 / 3 / 4-camera fallbacks of the VISION megakernel and the PREFIX megakernel's geometry check were removed with the fixed camera count.)""" out: Dict[str, str] = {} gx, gy = int(grid[0]), int(grid[1]) if engine.get("expert") == "mk": from .mk_expert.plan import Plan try: for L in buckets: Plan(gx, gy, int(L) // 32, geom.min_valid_keys) except ValueError as e: out["expert"] = f"the EXPERT megakernel cannot hold bucket {L}: {e}" if engine.get("prefix") == "fused": from ..reference.config import CONFIG as _C from .px_fused import addnorm_plan, qkv_plan try: for L in buckets: addnorm_plan(int(L) // 32, _C.lm.hidden // 32, (gx, gy)) qkv_plan(int(L) // 32, _C.lm.heads + 2 * _C.lm.kv_heads, gx * gy) except ValueError as e: out["prefix"] = f"the fused PREFIX cannot run bucket {L} on a {gx} x {gy} grid: {e}" return out def config_engine(engine, geom: Geometry, buckets: Sequence[int], grid): """(engines, fallbacks) of the resident buckets: ``resolve_engine(engine)`` with every default engine that cannot run them replaced by ttnn (also when ``engine`` / ``RDT2_ENGINE`` restates the default, as the serve profile does); a non-default engine that cannot run them raises. Empty fallbacks for the served buckets (416 / 448 / 512).""" eng = resolve_engine(engine) expl = {k: v for k, v in explicit_engine(engine).items() if v != DEFAULT_ENGINE.get(k)} fallbacks: Dict[str, str] = {} for prog, why in engine_unsupported(eng, geom, buckets, grid).items(): if prog in expl: raise ValueError(f"engine {prog}={eng[prog]} cannot run buckets {list(buckets)}: {why}") fallbacks[prog] = f"{eng[prog]} -> ttnn: {why}" eng[prog] = "ttnn" return eng, fallbacks EXPERIMENTAL_PREFIX_MK_ENV = "RDT2_EXPERIMENTAL_PREFIX_MK" PREFIX_MK_HANG = ("the PREFIX megakernel (engine prefix=mk) is experimental: it hangs the device on repeated trace " "replays at prompt bucket 512 (known hang, reproduced in 4 of 4 runs after 5 to 325 replays; the " "card had to be reset each time) and it is slower than the default ttnn PREFIX") def check_engine_allowed(engine: Dict[str, str], env=None) -> None: """Refuse the experimental engines unless explicitly opted in: ``prefix=mk`` needs RDT2_EXPERIMENTAL_PREFIX_MK=1. Called by :class:`RDT2FMTT` before anything touches the device, so no default, serve profile or ``RDT2_ENGINE`` value alone can build the PREFIX megakernel.""" import os env = os.environ if env is None else env if engine.get("prefix") == "mk" and str(env.get(EXPERIMENTAL_PREFIX_MK_ENV, "")).strip() != "1": raise ValueError(f"{PREFIX_MK_HANG}. Refused: set {EXPERIMENTAL_PREFIX_MK_ENV}=1 to build it anyway " "(development only; never in a served configuration), or use the default prefix=fused (or prefix=ttnn)") def open_rdt2_device(dispatch: str = "eth", trace_region_size: int = TRACE_REGION_SIZE, device_id: int = 0): """ETH dispatch (12 x 10) by default; ``dispatch="worker"`` is the A/B switch (11 x 10).""" from ..ttaw.device import open_device return open_device(device_id, dispatch=dispatch, trace_region_size=trace_region_size, num_command_queues=1) def ack_trace_outputs(tensors) -> None: """Mark trace outputs as intentionally overwritten by replays for TT_METAL_TRACE_ALLOC_TRACKING (no-op when the tracking is off): the stage outputs (image rows, K / V) and the action of a bucket's trace are written by every replay of that trace and are documented as valid only until another trace is replayed (module docstring), so the tracker must not report them as buffers a replay would corrupt. Persistent buffers are never tracked (no-op).""" try: from ttnn.tools import trace_allocation_tracker as tracker except Exception: # noqa: BLE001 - older ttnn without the tracker return if not getattr(tracker, "TRACE_ALLOC_TRACKING", False): return for t in tensors: if t is not None and t.is_allocated(): tracker.acknowledge_corruptible(t) class RDT2FMTT: geom: Geometry = geometry(DEFAULT_NUM_CAMERAS) # set per object in __init__ (class default: host-only stubs) def __init__(self, device, buckets: Optional[Sequence[int]] = None, precision: Any = None, num_steps: int = E.num_steps, vlm_dir: Optional[str] = None, expert_dir: Optional[str] = None, normalizer_dir: Optional[str] = None, processor_dir: Optional[str] = None, stages: Sequence[str] = ("vision", "prefix", "expert"), log=print, bucket: Optional[int] = None, engine=None, num_cameras: int = DEFAULT_NUM_CAMERAS): """``buckets``: the resident prompt buckets (default 416 / 448 / 512; ``bucket=L`` is shorthand for ``buckets=(L,)``). ``num_steps`` (1..16, default 5) is fixed for the object. ``num_cameras`` must be 2 (the checkpoint's two wrist cameras; any other value raises ValueError, round 5). A default engine that cannot run developer buckets outside 416 / 448 / 512 falls back to the program's ttnn engine, also when it is restated in ``engine`` / ``RDT2_ENGINE`` (:func:`engine_unsupported`, recorded in ``engine_fallbacks``; empty for the served buckets at every step count); a non-default engine that cannot run them raises.""" from ..reference.geometry import check_num_steps self.geom = geometry(num_cameras) self.engine = resolve_engine(engine) check_engine_allowed(self.engine) # prefix=mk is experimental (known hang): refused before any device work import ttnn self.device = device if bucket is not None: buckets = (bucket,) if buckets is None: buckets = self.geom.buckets self.buckets = tuple(sorted({int(b) for b in buckets})) check_num_steps(num_steps) g = device.compute_with_storage_grid_size() self.engine, self.engine_fallbacks = config_engine(engine, self.geom, self.buckets, (int(g.x), int(g.y))) for prog, why in self.engine_fallbacks.items(): log(f"[rdt2] {prog}: default engine falls back to ttnn ({why})") self.prec = resolve_precision(precision) self._sealed = False self._mem_seal: Optional[Dict[str, int]] = None # allocator state at the end of the last capture() self.strict_memory = True # __call__: "overlap" = the allocator-state check runs on a helper thread during the host pre-processing # (still before any write / replay); "pre" = serially inside replay() (package-time behaviour) self.memory_check = os.environ.get("RDT2_MEMORY_CHECK", "overlap") self._check_pool = None if self.memory_check not in ("overlap", "pre"): raise ValueError(f"RDT2_MEMORY_CHECK must be 'overlap' or 'pre', got {self.memory_check!r}") self.num_steps = int(num_steps) self.processor_dir = processor_dir or DEFAULT_DIRS["processor"] self.timings: Dict[str, float] = {} t0 = time.time() self.vision = self.prefix = self.expert = None index = load_vlm_index(vlm_dir) if ("vision" in stages or "prefix" in stages) else None if "vision" in stages: if self.engine["vision"] == "mk": from .mk_vision.program import VisionMK self.vision = VisionMK(device, index.load_prefix("visual."), self.prec, log=log) else: self.vision = VisionTT(device, index.load_prefix("visual."), self.prec, geom=self.geom) index.drop("visual.") log(f"[rdt2] vision ({self.engine['vision']}) weights on device ({time.time() - t0:.1f} s)") if "prefix" in stages: if self.engine["prefix"] == "mk": from .mk_prefix.program import PrefixMK self.prefix = PrefixMK(device, index, self.buckets, log=log) else: self.prefix = PrefixTT(device, index, self.prec, self.buckets, fused=self.engine["prefix"] == "fused", geom=self.geom) self.prefix.sealed_check = lambda: self._sealed # add_bucket refuses new tables once sealed log(f"[rdt2] prefix ({self.engine['prefix']}) weights on device ({time.time() - t0:.1f} s)") if "expert" in stages: sd = load_expert_state_dict(expert_dir) if self.engine["expert"] == "mk": from .mk_expert.program import ExpertMK self.expert = ExpertMK(device, sd, self.buckets, self.num_steps, log=log, min_valid_keys=self.geom.min_valid_keys) else: self.expert = ExpertTT(device, sd, self.prec, self.num_steps) log(f"[rdt2] expert ({self.engine['expert']}) weights on device ({time.time() - t0:.1f} s)") self.timings["load_s"] = time.time() - t0 self.norm = load_action_normalizer(normalizer_dir) mk = lambda shape, dt, lay: self._persistent(lambda: ttnn.from_torch( torch.zeros(shape), dtype=dt, layout=lay, device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG)) shared = {"pix": mk((1, 1, self.geom.n_rows, K_PE), ttnn.float32, ttnn.TILE_LAYOUT), "noise": mk((1, 1, ROWS, ACT_P), ttnn.float32, ttnn.TILE_LAYOUT), "state": mk((1, 1, 1, ACT_P), ttnn.float32, ttnn.TILE_LAYOUT)} self.inputs: Dict[int, Dict[str, Any]] = {} for L in self.buckets: ids = self._persistent(lambda: ttnn.from_torch(torch.zeros(1, L, dtype=torch.int32), dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG)) self.inputs[L] = dict(shared, ids=ids, mask=mk((1, 1, ROWS, L), ttnn.bfloat16, ttnn.TILE_LAYOUT)) self._spec = {"pix": (ttnn.float32, ttnn.TILE_LAYOUT), "ids": (ttnn.uint32, ttnn.ROW_MAJOR_LAYOUT), "mask": (ttnn.bfloat16, ttnn.TILE_LAYOUT), "noise": (ttnn.float32, ttnn.TILE_LAYOUT), "state": (ttnn.float32, ttnn.TILE_LAYOUT)} # round 5 state cache (EXPERT megakernel): the adaLN state half S_all is recomputed (one small prologue trace, # or eagerly) only when the state written into the shared state buffer differs from the cached one; # RDT2_STATE_CACHE=0 restores the per-call prologue inside the bucket traces self._s_cache_on = (self.expert is not None and hasattr(self.expert, "S_cache") and os.environ.get("RDT2_STATE_CACHE", "1") != "0") self._s_buf_host = host_state(np.zeros(E.state_dim, np.float32)) # content of the state buffer self._s_cached = None # state whose S_all is in S_cache (None: not computed yet) self._s_trace = None self._persist_addr = self._persistent_addresses() self.traces: Dict[int, Optional[int]] = {L: None for L in self.buckets} self.out: Dict[int, Any] = {L: None for L in self.buckets} self.stage_out: Dict[int, Dict[str, Any]] = {L: {} for L in self.buckets} self._stage_traces = None # ------------------------------------------------------------------------------------------------- memory contract def _persistent_tensors(self) -> Dict[str, Any]: out = {f"in.{L}.{k}": t for L, inp in self.inputs.items() for k, t in inp.items()} ex = self.expert if ex is not None and hasattr(ex, "out"): # megakernel: per-bucket outputs, debug buffers, arenas for L in self.buckets: out[f"mk.out.{L}"] = ex.out[L] out[f"mk.dbg.{L}"] = ex.dbg[L] out["mk.arena"], out["mk.ttab"], out["mk.wall"] = ex.arena, ex.ttab, ex.w_all if hasattr(ex, "S_cache"): out["mk.scache"] = ex.S_cache if self.prefix is not None and getattr(self.prefix, "persistent_outputs", False): out.update(self.prefix.persistent_tensors()) # PREFIX megakernel: streams, tables, the K / V buffers elif self.prefix is not None and isinstance(getattr(self.prefix, "tables", None), dict): for L, t in self.prefix.tables.items(): # ttnn / fused PREFIX: per-bucket tables (R2-F4, opt round 3) for k in ("cos", "sin", "scatter", "q_dummy", "cs"): if t.get(k) is not None: out[f"px.{L}.{k}"] = t[k] for k in ("kT", "kD"): for i, x in enumerate(t.get(k) or ()): out[f"px.{L}.{k}{i}"] = x if self.vision is not None and getattr(self.vision, "persistent_outputs", False): out.update(self.vision.persistent_tensors()) # VISION megakernel: streams, tables, scratch, output return out def _persistent_addresses(self) -> Dict[str, int]: return {k: int(t.buffer_address()) for k, t in self._persistent_tensors().items()} def _persistent(self, alloc): """Allocate a persistent buffer: refused once the model is sealed (first trace capture).""" if self._sealed: raise RuntimeError("persistent allocation after the first trace capture (memory contract): allocate every " "persistent buffer in __init__") return alloc() def memory_totals(self) -> Dict[str, int]: """Bytes allocated per bank of the device's DRAM and L1 allocators (``ttnn.get_memory_view``).""" import ttnn return {name: int(ttnn.get_memory_view(self.device, bt).total_bytes_allocated_per_bank) for name, bt in (("dram", ttnn.BufferType.DRAM), ("l1", ttnn.BufferType.L1))} def check_persistent(self) -> None: """Persistent addresses unchanged; once traces are captured, also the allocator state of the capture.""" self.check_addresses() self.check_allocator() def check_addresses(self) -> None: """The persistent buffers (inputs, outputs, streams, tables) are the objects and addresses of __init__ (~0.03 ms).""" now = self._persistent_addresses() if now != self._persist_addr: moved = [k for k in set(now) | set(self._persist_addr) if now.get(k) != self._persist_addr.get(k)] raise RuntimeError(f"persistent buffers moved: {sorted(moved)[:6]}") def check_allocator(self) -> None: """Once a full-call trace is alive: the device allocator holds exactly the bytes per bank of the capture (``ttnn.get_memory_view`` builds the allocator block tables: ~0.57 ms of host time).""" if self._mem_seal is not None and self.strict_memory: mem = self.memory_totals() if mem != self._mem_seal: raise RuntimeError( "device allocations changed since the trace capture (memory contract): bytes per bank " f"{self._mem_seal} -> {mem}; free every buffer allocated after capture() before replaying (or set " "strict_memory = False if the caller keeps its own device tensors alive on purpose)") def _reseal_memory(self) -> None: """Record the allocator state the replays are checked against (None while no full-call trace is alive).""" alive = any(t is not None for t in self.traces.values()) self._mem_seal = self.memory_totals() if alive else None @property def sealed(self) -> bool: return self._sealed @property def bucket(self) -> int: """The default (smallest) bucket.""" return self.buckets[0] def bucket_for(self, n_tokens: int) -> int: return choose_bucket(int(n_tokens), self.buckets) def _L(self, L: Optional[int]) -> int: L = self.buckets[0] if L is None else int(L) if L not in self.inputs: raise KeyError(f"bucket {L} is not resident (buckets {self.buckets})") return L # ------------------------------------------------------------------------------------------------- host def host_inputs(self, images, instruction: str, state, noise: torch.Tensor, bucket: Optional[int] = None) -> Dict[str, Any]: """Format one request (host only): images in model order (left_stereo, right_stereo), 384 x 384 x 3 uint8. The bucket is the smallest resident one that holds the prompt, or ``bucket`` if given (must hold it).""" ids = tokenize(instruction, self.geom.n_img, self.processor_dir) n = int(ids.shape[1]) L = self.bucket_for(n) if bucket is None else self._L(bucket) bids, kmask = host_ids(ids, L, self.geom) # raises if the prompt exceeds L (never truncated) return {"pix": host_pixels(images, self.geom), "ids": bids, "mask": host_mask(kmask), "noise": host_noise(noise), "state": host_state(state), "n_tokens": torch.tensor(n), "bucket": L} def write_inputs(self, host: Dict[str, Any]) -> None: import ttnn dst = self.inputs[self._L(host["bucket"])] for k, dev in dst.items(): dt, lay = self._spec[k] t = host[k] if k == "ids": t = t.to(torch.int32) ttnn.copy_host_to_device_tensor(ttnn.from_torch(t, dtype=dt, layout=lay), dev, cq_id=0) if "state" in dst: self._s_buf_host = host["state"].to(torch.float32).clone() def _refresh_state(self, traced: bool) -> None: """State cache: recompute S_all (prologue trace or eager) if the state buffer holds another state than the cached one. Runs before the bucket's trace / eager graph on the same command queue (in order).""" if not getattr(self, "_s_cache_on", False): return if self._s_cached is not None and torch.equal(self._s_buf_host, self._s_cached): return import ttnn if traced: ttnn.execute_trace(self.device, self._s_trace, cq_id=0, blocking=False) else: self.expert.prologue_cached(self.inputs[self.buckets[0]]["state"]) self._s_cached = self._s_buf_host.clone() # ------------------------------------------------------------------------------------------------- device def forward_device(self, L: Optional[int] = None): """The whole device graph of bucket L on its fixed input buffers. Returns the normalized action (1,1,32,32).""" L = self._L(L) inp = self.inputs[L] self.prefix.select(L) img = self.vision.forward(inp["pix"]) Ks, Vs = self.prefix.forward(inp["ids"], img) if getattr(self, "_s_cache_on", False): # S_all from the state cache (_refresh_state ran before) a = self.expert.forward_cached(inp["noise"], Ks, Vs, inp["mask"]) else: a = self.expert.forward(inp["noise"], inp["state"], Ks, Vs, inp["mask"]) self.stage_out[L] = {"img": img, "K": Ks, "V": Vs} return a def _free_out(self, L: int) -> None: """Free the action output of bucket L unless it is the megakernel's persistent output tile.""" import ttnn if self.out[L] is not None and self.engine["expert"] == "ttnn": ttnn.deallocate(self.out[L]) self.out[L] = None def release_stage_outputs(self, L: Optional[int] = None) -> None: import ttnn L = self._L(L) so = self.stage_out[L] if so: kv_owned = not getattr(self.prefix, "persistent_outputs", False) # the megakernel's K / V are persistent for t in [so["img"]] + ((list(so["K"]) + list(so["V"])) if kv_owned else []): ttnn.deallocate(t) self.stage_out[L] = {} def run_eager(self, L: Optional[int] = None): import ttnn L = self._L(L) if any(t is not None for t in self.traces.values()) or self._stage_traces: raise RuntimeError("release the traces before running eagerly (eager outputs could land in trace scratch)") self.release_stage_outputs(L) self._free_out(L) self._refresh_state(traced=False) self.out[L] = self.forward_device(L) return self.out[L] def capture(self, buckets: Optional[Sequence[int]] = None) -> None: """Warm-up eager run of every bucket (kernel JIT, program cache, kernel binaries), then one trace per bucket.""" import ttnn buckets = self.buckets if buckets is None else tuple(self._L(b) for b in buckets) self.release_trace() for L in buckets: self.run_eager(L) ttnn.synchronize_device(self.device) self.release_stage_outputs(L) self._free_out(L) self.check_persistent() self._sealed = True # from here on no persistent allocation (memory contract) if getattr(self, "_s_cache_on", False) and self._s_trace is None: tid = ttnn.begin_trace_capture(self.device, cq_id=0) try: self.expert.prologue_cached(self.inputs[self.buckets[0]]["state"]) finally: ttnn.end_trace_capture(self.device, tid, cq_id=0) self._s_trace = tid for L in buckets: tid = ttnn.begin_trace_capture(self.device, cq_id=0) try: out = self.forward_device(L) finally: ttnn.end_trace_capture(self.device, tid, cq_id=0) self.traces[L] = tid self.out[L] = out so = self.stage_out[L] ack_trace_outputs([out, so["img"]] + list(so["K"]) + list(so["V"])) self._reseal_memory() def release_trace(self, L: Optional[int] = None) -> None: """Release the trace of bucket L (all buckets if None).""" import ttnn for b in (self.buckets if L is None else (self._L(L),)): if self.traces[b] is not None: ttnn.release_trace(self.device, self.traces[b]) self.traces[b] = None self.stage_out[b] = {} self.out[b] = None if L is None and getattr(self, "_s_trace", None) is not None: ttnn.release_trace(self.device, self._s_trace) self._s_trace = None self._reseal_memory() def release(self) -> None: """Release every trace and every stage output (weights are freed with the object).""" import ttnn if getattr(self, "_check_pool", None) is not None: self._check_pool.shutdown(wait=True) self._check_pool = None self.release_stage_traces() self.release_trace() for L in self.buckets: self.release_stage_outputs(L) self._free_out(L) # ------------------------------------------------------------------------------------------------- stage traces def capture_stages(self, L: Optional[int] = None) -> Dict[str, int]: """Measurement aid: one trace per stage (VISION | PREFIX | EXPERT prologue | EXPERT step k) of bucket L chained through persistent stage outputs; replaying them in order equals one call. Releases the full-call traces.""" import ttnn L = self._L(L) self.release_trace() self.release_stage_outputs(L) self.prefix.select(L) inp = self.inputs[L] ex = self.expert st: Dict[str, Any] = {} def step(k): a_in = inp["noise"] if k == 0 else st[f"a{k}"] v = ex.velocity(a_in, k, st["S"], st["KV"][0], st["KV"][1], inp["mask"]) st[f"a{k + 1}"] = ttnn.addcmul(a_in, v, ex.upd, memory_config=ttnn.DRAM_MEMORY_CONFIG) ttnn.deallocate(v) fns = {"vision": lambda: st.__setitem__("img", self.vision.forward(inp["pix"])), "prefix": lambda: st.__setitem__("KV", self.prefix.forward(inp["ids"], st["img"]))} mk = self.engine["expert"] == "mk" if mk: # the whole action head is one program (prologue matmul + the megakernel) fns["expert"] = lambda: st.__setitem__(f"a{self.num_steps}", ex.forward( inp["noise"], inp["state"], st["KV"][0], st["KV"][1], inp["mask"])) else: fns["prologue"] = lambda: st.__setitem__("S", ex.prologue(inp["state"])) for k in range(self.num_steps): fns[f"step{k}"] = (lambda k=k: step(k)) kv_owned = not getattr(self.prefix, "persistent_outputs", False) def free(): for key, t in list(st.items()): if key == "KV": for x in (t[0] + t[1]) if kv_owned else []: ttnn.deallocate(x) elif key == "S": for x in t.values(): ttnn.deallocate(x) elif not (mk and key == f"a{self.num_steps}"): ttnn.deallocate(t) st.clear() for fn in fns.values(): # warm-up (compiles anything not compiled yet) fn() ttnn.synchronize_device(self.device) free() tids: Dict[str, int] = {} for name, fn in fns.items(): tid = ttnn.begin_trace_capture(self.device, cq_id=0) try: fn() finally: ttnn.end_trace_capture(self.device, tid, cq_id=0) tids[name] = tid flat = [] for key, t in st.items(): flat += (list(t[0]) + list(t[1])) if key == "KV" else (list(t.values()) if key == "S" else [t]) ack_trace_outputs(flat) # the chained stage outputs: written by their stage's replay self._stage_traces = (tids, st) return tids def read_stage_action(self) -> torch.Tensor: import ttnn st = self._stage_traces[1] a = ttnn.to_torch(st[f"a{self.num_steps}"]).float().reshape(ROWS, ACT_P) return a[:E.horizon, :E.action_dim].reshape(1, E.horizon, E.action_dim) def time_stages(self, n: int = 50) -> Dict[str, float]: """Median ms per stage trace (blocking replays of each stage in call order).""" import ttnn tids, _ = self._stage_traces ts: Dict[str, list] = {k: [] for k in tids} for _ in range(n): for name, tid in tids.items(): t0 = time.perf_counter() ttnn.execute_trace(self.device, tid, cq_id=0, blocking=False) ttnn.synchronize_device(self.device) ts[name].append((time.perf_counter() - t0) * 1e3) return {k: sorted(v)[len(v) // 2] for k, v in ts.items()} def release_stage_traces(self) -> None: import ttnn if getattr(self, "_stage_traces", None): for tid in self._stage_traces[0].values(): ttnn.release_trace(self.device, tid) self._stage_traces = None def replay(self, L: Optional[int] = None, blocking: bool = True, allocator_checked: bool = False) -> None: """Replay the trace of bucket L after the memory-contract check (both halves before ``execute_trace``: a violation refuses the replay). ``allocator_checked``: the caller ran :meth:`check_allocator` itself earlier in the same call with no device allocation since (``__call__`` overlaps it with the host pre-processing); the persistent-address check still runs here.""" import ttnn if allocator_checked: self.check_addresses() else: self.check_persistent() self._refresh_state(traced=True) ttnn.execute_trace(self.device, self.traces[self._L(L)], cq_id=0, blocking=blocking) def _allocator_check_async(self): """Start :meth:`check_allocator` on a helper thread (``get_memory_view`` builds the allocator block tables, ~0.57 ms of host time; the host pre-processing's torch kernels release the GIL, so the two overlap).""" if self._check_pool is None: from concurrent.futures import ThreadPoolExecutor self._check_pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="rdt2-memcheck") return self._check_pool.submit(self.check_allocator) def read_action_normalized(self, L: Optional[int] = None) -> torch.Tensor: import ttnn a = ttnn.to_torch(self.out[self._L(L)]).float().reshape(ROWS, ACT_P) return a[:E.horizon, :E.action_dim].reshape(1, E.horizon, E.action_dim) def expert_on_kv(self, K: torch.Tensor, V: torch.Tensor, noise, state, L: int) -> torch.Tensor: """Debug / gate helper (eager, no trace alive): the device EXPERT on given K / V (14, 1, 4, n, 128) -> (1, 24, 20).""" import ttnn if any(t is not None for t in self.traces.values()) or self._stage_traces: raise RuntimeError("release the traces first (eager temporaries could land in trace scratch)") n = K.shape[3] Kp = torch.zeros(14, 1, 4, L, 128) Vp = torch.zeros(14, 1, 4, L, 128) Kp[..., :n, :] = K Vp[..., :n, :] = V Kt = [upload(Kp[i], self.device, "bf16") for i in range(14)] Vt = [upload(Vp[i], self.device, "bf16") for i in range(14)] km = torch.zeros(L, dtype=torch.bool) km[:n] = True ts = [upload(host_mask(km), self.device, "bf16"), upload(host_noise(noise), self.device, "fp32"), upload(host_state(state), self.device, "fp32")] y = self.expert.forward(ts[1], ts[2], Kt, Vt, ts[0]) ns = ttnn.to_torch(y).float()[0, 0, :E.horizon, :E.action_dim][None] for t in Kt + Vt + ts: ttnn.deallocate(t) if self.engine["expert"] == "ttnn": ttnn.deallocate(y) return ns # ------------------------------------------------------------------------------------------------- API @torch.no_grad() def __call__(self, images, instruction: str, state=None, noise: Optional[torch.Tensor] = None, traced: bool = True, generator: Optional[torch.Generator] = None, bucket: Optional[int] = None) -> Dict[str, Any]: t0 = time.perf_counter() if state is None: state = np.zeros(E.state_dim, np.float32) if noise is None: noise = torch.randn((1, E.horizon, E.action_dim), generator=generator) # memory contract, allocator half: checked on a helper thread while the host formats the request (before # any write or replay; nothing in between allocates device memory); RDT2_MEMORY_CHECK=pre runs it serially chk = (self._allocator_check_async() if traced and self.memory_check == "overlap" and self._mem_seal is not None else None) try: host = self.host_inputs(images, instruction, state, noise, bucket=bucket) finally: if chk is not None: chk.result() # re-raises a contract violation: refused before any device work of this call L = host["bucket"] t1 = time.perf_counter() self.write_inputs(host) if traced: if self.traces[L] is None: self.capture() chk = None self.replay(L, blocking=False, allocator_checked=chk is not None) else: self.run_eager(L) nsample = self.read_action_normalized(L) t2 = time.perf_counter() action = unnormalize_action(nsample, self.norm)[0] t3 = time.perf_counter() self.timings.update(host_pre_ms=(t1 - t0) * 1e3, device_ms=(t2 - t1) * 1e3, host_post_ms=(t3 - t2) * 1e3) return {"nsample": nsample, "action": action, "n_tokens": int(host["n_tokens"]), "bucket": L}