# SPDX-License-Identifier: Apache-2.0 """Metal traces vs later device allocations. A trace records the device addresses of every buffer its operations allocate (and free again) while it is captured. A buffer allocated after the capture may get one of those addresses and is then overwritten whenever the trace replays (tt-metal warns "Allocating device buffers is potentially unsafe due to the existence of an active trace"). Every engine that captures traces registers here; an engine that must allocate persistent device buffers after construction (the tt-nn engine's first launch of a new (batch, length) bucket: its inputs, RoPE tables, band mask) first calls ``invalidate(device)``: every registered engine on that device releases its traces and captures them again at its next launch (no recompilation; ~tens of ms once). Trace outputs are read right after their own trace runs, so outputs allocated during a later capture are safe. """ from __future__ import annotations import weakref _REG: "dict[int, weakref.WeakSet]" = {} def register(device, engine) -> None: _REG.setdefault(id(device), weakref.WeakSet()).add(engine) def invalidate(device) -> int: """Release the traces of every engine registered on ``device``; the number of engines that held traces.""" n = 0 for eng in list(_REG.get(id(device), ())): n += 1 if eng.drop_traces() else 0 return n