Context manager that annotates GPU work captured within its scope.
Must be used inside an active torch.cuda.graph capture with
. Every kernel, memcpy, and memset node the
capture adds within the scope is tagged with . Outside
a capture, with annotations disabled, or when is
, the context manager is a no-op.
When scopes overlap on the same node (e.g. nested scopes), their
annotation dicts are merged key-by-key with the inner scope winning
common keys.
By default backward work is annotated too: autograd nodes created by
forward operations inside the scope get hooks (via
torch.autograd.graph.node_creation_hook) that bracket their
backward execution, so when the backward pass is itself captured –
in the same capture as the forward or in a later one – its kernels
are tagged with the same annotation, plus an "autograd_phase":"backward" key marking them as backward work ("autograd_phase"
is therefore reserved: backward annotation overwrites it). When
backward runs outside a capture the hooks are a no-op. Ownership
extends to higher-order gradients: nodes created while a hooked node
executes (create_graph=True, checkpoint recomputation) inherit its
annotations, so a later grad-of-grad capture is attributed too.
AccumulateGrad nodes are never annotated: a leaf’s node is created
once and cached, so scope ownership would be an accident of first use.
Pass backward=False to annotate only the forward work, e.g. when a
wrapper implements its own backward attribution. The keyword’s
presence also serves as the feature probe for that native backward
support: "backward"ininspect.signature(mark_kernels).parameters.
Implementation: on entry, records the current stream’s capture frontier
and its existing direct dependents; on scope exit, walks only the
dependent nodes added since entry (falling back to newly created graph
roots when the scope is the first captured work).
Parameters:
annotation (str or dict) – Metadata to attach to each captured node.
A string s is recorded as {"name":s}. Dict values must
be picklable. The key "name" names the region in trace
tooling; "stream" is reserved for stream-lane assignment.
backward (bool) – Whether to also annotate the backward kernels of
autograd nodes created inside the scope. Default: True.