Shared state shuttled between the input-side and output-side hook barriers of a single nn.Module invocation.
A Module with registered backward hooks is wrapped at forward time with
two barriers — ModuleOutputHookNode on each output edge and
ModuleInputHookNode on each gradient-receiving input edge. Both
barriers hold a shared_ptr to the same ModuleBackwardHookState so
that the gradients arriving at the outputs (from downstream nodes) are
available to the input-side hook callbacks, and any replacement gradients
returned by the Python full-backward hook flow back through the inputs.
Attributes
pre_ runnerpy::objectfull_ runnerpy::objectn_ inputsstd::size_trequires_grad=False and therefore no edge).n_ outputsstd::size_tpre_ hooks_ ranboolfull_ hooks_ ranbooloutputs_ ranboolgrad_output to hand them.BackwardPass the per-pass members above belong to, and those an outer pass set aside while a nested one crosses the module.input_ arg_ indicesstd::vector<std::uint32_t>grad_inputs back to its original positional argument index in the Python signature.input_ metasstd::vector<ModuleHookTensorMeta>grad_inputs.grad_ inputsstd::vector<TensorImplPtr>output_ metasstd::vector<ModuleHookTensorMeta>size() == n_outputs).grad_ outputsstd::vector<TensorImplPtr>output_ edge_ indicesstd::vector<std::uint32_t>grad_outputs.A slot sums what reaches it, as the reference's input buffer doesamodule whose output feeds two consumers, or whose body reads an inputtwice, receives one gradient per use, and the hooks — and everythingupstream — must see their sum. Overwriting kept only the last one.The gradients are held as tensors in both modesunder ``create_graph``they carry their graph, and the sums are graph ops.Notes
The two py::object runners are the Python-side loops over the module's
hooks of each kind. They are held as opaque py::object (the GIL is
acquired only when they are actually invoked inside apply_barrier).
Each is a generator: it calls the hooks in turn and yields every result
that is not None, and the barrier checks that result against the
slots it replaces — count, then each gradient's dtype, device and shape
(autograd/TensorHooks.h) — and puts it in place before the generator goes
on, so the next hook is handed only a tuple the engine accepted.
Constructors
1ModuleBackwardHookState
void ModuleBackwardHookState(int n_inputs, int pre_runner, int full_runner)Construct fresh hook state for a module forward call.
Parameters
n_ inputsstd::size_tpre_ runnerpy::objectfull_ runnerpy::objectDestructor
1~ModuleBackwardHookState
void ~ModuleBackwardHookState()Methods
3Release all Python runners and saved gradients under the GIL.
Make the per-pass members the running pass's (PassSlots): what an earlier pass left is dropped, what an outer pass still running left is set aside. Called before every read or write of the slots.
Forget every gradient and hook guard of the current pass — once the module's backward is complete, so the next pass starts empty and fires the hooks again.