mr2.nn.make_functional
- mr2.nn.make_functional(module: Module) tuple[Operator[Unpack[tuple[Tensor, ...]], tuple[Tensor, ...]], tuple[Tensor, ...]][source]
Expose module weights and forward inputs as explicit operator arguments.
The returned operator represents
G(*params, *inputs) = module(*inputs)evaluated with the supplied weights. Compose it with MR2 operators and functionals to optimize network weights and, optionally, inputs.- Parameters:
module (
Module) – Module whose parameters withrequires_grad=Trueare exposed. Frozen parameters remain part of the stored module. Parameter sharing and PyTorch parametrizations are preserved byfunctional_call.- Returns:
operator – Operator taking the trainable weights first, followed by the module’s positional tensor inputs. The parameter count determines the split. A tensor output is wrapped in a tuple; tuple outputs are retained.
parameters – Initial trainable parameters in the operator’s argument order. These are references to the original tensors, without cloning or detaching. A module with no trainable parameters returns an empty tuple.
Notes
Buffers are captured once and copied per call; updates do not persist. The module is held by reference: prepare its device, dtype and mode first, and keep its parameter structure unchanged. In-place changes to weights or inputs are unsupported. Disable checkpointing inside the module: backward would use the original weights. Checkpoint the returned operator instead.
Examples
Fit weights and input jointly, or keep the input fixed with a closure:
>>> from mr2.algorithms.optimizers import adam >>> from mr2.operators.functionals import L2NormSquared >>> generator, params = make_functional(nn.Linear(2, 1)) >>> z = torch.ones(1, 2) >>> objective = L2NormSquared(torch.ones(1, 1)) @ generator >>> fitted = adam(objective, (*params, z)) # fit weights and input >>> fitted_params = adam(lambda *p: objective(*p, z), params) # fit weights only