Thread-local op recorder consumed by OpScopeFull.
Constructing a Tracer is cheap — the underlying TraceGraph
starts empty. Hooks fire only between set_current_tracer
(this) and set_current_tracer (nullptr); outside that
window the tracer accumulates nothing.
Attributes
graph_TraceGraphon_op_enter and exposed read-only via graph.Notes
Non-copyable, non-movable — the active-tracer slot is a raw pointer owned by the caller; copying or moving the Tracer would either invalidate that pointer or duplicate the recording sink.
Examples
Native usage (Python binding mirrors this):: Tracer t;
set_current_tracer(&t);
// ... run a forward pass — every OpScopeFull ctor records ...
set_current_tracer(nullptr);
const auto& g = t.graph(); // inspect recorded nodesConstructors
1Operators
1Methods
35commit_vjp_region
void commit_vjp_region(int fwd_begin, int fwd_end, int input_ids, int output_metas, int cotangent_ids, int input_grad_ids, int bwd_begin)Moves graph_.ops[bwd_begin .. end) into a VjpRegion covering forward ops [fwd_begin, fwd_end) and appends it to graph_.vjp_regions.
Drops any ops recorded at or after idx (used when tracing a custom Function's backward fails and falls back to eager).
Returns impl's existing TensorId or mints an external-feed id for it when impl has not been seen yet.
Returns the id → external TensorImplPtr map populated by on_op_io when an input wasn't produced by any earlier traced op. The builder uses this to materialise an MPSGraph placeholder per external feed and to bind the corresponding input data at execution time.
The Tracer holds an owning TensorImplPtr for every
external feed so the underlying buffers cannot be released
mid-trace.
impl's id, minting a feed for it when the trace has not seen it.
With folding on, whether this on_op_io call is absorbed: every input is a constant made inside this trace, so the op is held out.
Whether an op that reads nothing the trace sees is left out of the recording: its output stays unseen, and an op that the trace does record reads it as one constant feed, already on that op's device. lucid.tensor([...]).to(x.device) then costs a feed, not a CPU op in a Metal trace (which ran the whole call eagerly). Off by default, because "unseen" means "constant" only to a consumer that watches every live tensor the call reads — its arguments and its model's state. The optimizer, decode and segmented tracers do not, and an op on their state would be frozen at its trace-time value; Core ML export folds on its own, knowing which shapes follow a flexible input. lucid.compile.compile turns it on.
const TraceGraph & graph()Returns a read-only reference to the recorded graph.
Returns
const TraceGraph&The op DAG accumulated so far. Caller must not access this reference after the Tracer is destroyed or a subsequent on_op_enter invalidates iterators into ops.
Notes what a held-out op made.
Reverse lookup: find the TensorId for impl if it was observed during the trace (either as an external feed or as the output of a traced op). Returns -1 when impl is not in the trace — used by the Python compile harness to map the user's return-value tensors back to graph ids so they can be passed to compile_or_cached as explicit graph outputs (which lets the builder drop "unconsumed but Python-discarded" intermediates like RNN's h_n tensor when the user only kept out).
Whether impl is a constant the trace made itself — a factory's output, or a left-out op's — which no tensor outside the trace shares.
Marks the recording as one no executable can stand for (see TraceGraph::unsupported). The first reason given is kept.
Give later reads of a live buffer the SSA id of its updated value, without mutating trace-time storage or losing the original feed.
out was made from src outside the op dispatcher — a device transfer, an alias with other autograd flags, a shared-buffer relabel (the TensorImpl bindings, bind_tensor.cpp). When the trace knows src, out is recorded as op name reading it, so a later op or host read of out reaches the traced value. Unrecorded, out was a tensor the trace had never seen: a host read of it went unnoticed, and an op reading it took it as a feed pinned at its trace-time value — every compiled call answered with the first call's data. name is an emitter's when out holds src's values on src's device ("detach"); any other name has no emitter and sends the call to eager. A src the trace has not seen is a constant to it, and so is out: nothing is recorded. With several sources (a fused kernel, a custom Metal kernel) the op reads all of them, and is recorded when the trace sees any one.
out was made from nothing by the op now recording — a factory (zeros / arange / eye …), never a random draw. With folding on and out off Metal, the op is left out and out is a constant; on Metal the compiled graph makes it itself, and otherwise nothing changes.
A value the trace knows — an op's output, an input, a parameter or a random draw — read on the host (item / tolist / numpy, and so float(t) or if t > 0). What the host does with it is invisible to the recording, which would bake this call's value into every later one: the trace is marked unsupported. A tensor the trace has not seen — a constant made on the spot — is left alone.
target now holds what value holds: an in-place op computed value out of place and spliced it into target (TensorImpl::take_storage_from / write_through). Later reads of target resolve to value's id — without this, a.mul_(b) .add_(c) recorded the add reading a from before the mul. A target from outside the trace keeps its feed id in external_feeds while its current id moves, which is how a write to a buffer is found (lucid/compile/_core/buffer_writes.py); one the trace has not read yet becomes a feed first. A value the trace has not seen becomes a feed of its own.
Attach a single attribute to the most recently recorded OpNode. Used by op forwards via OpScopeFull::set_attr to thread payloads (permutation, axis, stride, padding, …) that the emitter would otherwise be unable to recover from inputs + output shapes alone.
Parameters
keystd::string_view"permutation", "stride", "padding", "axis", "keepdim", "eps", …).valueAttributeValueNotes
Calling this with an empty TraceGraph (no preceding
on_op_enter) is a no-op — defensive against ordering
mistakes at hook sites. Overwrites any prior value under
key on the same node, so duplicate calls report the last
value (matches unordered_map semantics).
Records the entry of a new op into the active scope.
Parameters
namestd::string_viewOpScopeFull. Copied into the resulting OpNode::name.deviceDeviceTensorMeta appended to outputs.dtypeDtypeshapeShapeTensorMeta.Notes
Phase 1.1 appends one OpNode per call with an empty
inputs vector and a single-element outputs vector.
Phase 1.2 backfills inputs from the autograd wiring site
and may append additional outputs for multi-output ops.
Wires the input/output TensorImpl identities of the most recently recorded OpNode into the trace IR.
Parameters
inputsconst std::vector<TensorImplPtr>&nullptr slots (e.g. an optional bias) are passed through as -1 in the resulting OpNode::inputs``. The Tracer retains a strong reference to every external feed (input not produced by an earlier traced op) so the MpsBuilder` can read its shape/dtype + the run path can bind its data buffer.outputconst TensorImplPtr&on_op_enter (stored in node.outputs[0].id) is associated with this pointer in the internal map so subsequent ops that consume this tensor can resolve it back to the same id. Only the raw pointer is kept (no strong ref) — the output's lifetime is the caller's responsibility.Notes
Phase 1.1 wires only kernel families that go through
kernel::NaryKernel or kernel::VariadicKernel's
wire_autograd boundary (Conv / Linear / BatchNorm / Norm /
Loss / …). Ops dispatched through UnaryKernel or
BinaryKernel's in-line forward() reach
on_op_enter but skip this step — their inputs slot
stays empty, marking the node "pending" for the Phase 1.2
builder, which then routes that signature to the eager path.
Calling this with an empty TraceGraph (no preceding
on_op_enter) is a no-op — defensive against ordering
mistakes at hook sites.
Records output — just drawn by the RNG op name — as an external feed instead of as that op's output, and drops the op's node: the executable takes the draw as an input, and redraw_rng_feeds draws it again on every run. See RngFeeds.h.
Number of recorded forward ops currently in graph_.ops.
Number of outside buffers mutated in-place so far in this trace.
on_op_io for an op the recording keeps.
Whether a draw from the default generator becomes a feed drawn again on every run (the compile path, RngFeeds.h) — on by default — or stays an op in the recording. Core ML export turns it off: it lifts each recorded draw into a model input, which needs the op.
Mints a symbolic cotangent TensorId for impl without adding impl to external_feeds_. Used while tracing a custom Function's backward so the dummy cotangent tensor is bound by BackwardWalker from the upstream gradient tensor.
Puts every tensor from outside the trace that the trace wrote in place back to its value from before the trace, from the copy on_inplace_write kept at the first write. The trace-time call ran those writes eagerly; whatever runs next — an executable or an eager fallback — applies them itself, and would otherwise apply them twice. Call once the trace has finished.
Every traced value that the tracer still holds, keyed by id.
live_refs_ already owns each TensorImpl observed
during the trace, so this costs a walk rather than a copy. It
exists for a consumer that wants a traced value's contents and
not only its shape — constant folding an export, where a
subgraph that depends on no input can be replaced by the value it
produced.
A buffer written in place carries the id it had when the mapping was last updated, which is the post-mutation state; a caller that needs the earlier value must not use this.
Returns
std::unordered_map<TensorId, TensorImplPtr>Built fresh on each call.
Whether impl is an op's output, a feed, or an argument of the traced call.
impl is an argument of the traced call. Its values are the call's data before any op has consumed it, so on_host_read treats a read of it as a read of a traced value from the start of the trace.
on_inplace_write for a target the trace made itself.
The id an in-place write's value goes by from now on.