Repository navigation
[torch.compile][PyTorch] Prepare linear for torch compile - #2967
Conversation
Three small refactors that make the module easier to reason about and pave the way for the dataclass / saved-tensor refactors: - Add a TensorOrQuantized type alias (Union[Tensor, QuantizedTensorStorage]) used pervasively in helper signatures. - Hoist the conditional bias argument into a local linear_bias_tensor variable instead of an inline expression at the linear_fn() call site. - Only forward self.wgrad_store into the autograd Function when it is actually active (delay_wgrad_compute() is True); pass None otherwise so the autograd graph does not carry an unused Python object. Pure rename / hoisting; no behavioural change. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> Co-authored-by: Cursor <cursoragent@cursor.com>
Replace the loosely typed ``non_tensor_args`` tuple and the ad-hoc ``ctx.<attr>`` plumbing with two dataclasses, ``LinearFwdArgs`` and ``LinearBwdArgs``, that act as the single argument to every helper in the forward/backward pipeline. What changes: * ``LinearFwdArgs`` carries the (positional) tensors ``weight``, ``inp`` and ``bias`` plus all quantizers, ``requires_grad`` flags, the cached ``weight_workspace`` and every former ``non_tensor_args`` knob. ``_Linear.forward`` still takes ``weight/inp/bias`` as positional Tensor inputs so autograd tracks them, then immediately re-attaches them to ``fwd_args`` so every downstream helper has a single-argument signature. * ``LinearBwdArgs`` mirrors that on the backward side: it owns the saved tensors (``inputmat``, ``weight_fp8``, ``saved_weight``, ``bias``), the per-call quantizers, every flag previously stored directly on ``ctx`` and a ``setup_saved_tensors(saved_tensors, tensor_objects)`` helper that rehydrates the saved-tensor fields. * ``ctx.backward_objects = bwd_args`` is now the single attribute the autograd context needs (besides ``saved_tensors``/``tensor_objects``). * ``weight_workspace`` is no longer a positional Tensor arg of the autograd Function; it is read from ``fwd_args.weight_workspace`` and the freshly produced workspace is returned alongside ``out`` so the module can refresh its cache without autograd tracking the cache. * ``prepare_for_saving`` now lives at the autograd boundary in ``_Linear.forward``; ``_linear_setup_ctx`` only returns the merged list of tensors that should be saved. * ``grad_output_preprocess`` is invoked with ``bwd_args`` directly (it is duck-typed on the same attribute names) so backward never reaches into ``ctx.<attr>`` for non-tensor state. Behaviour preserved (verified numerically against ``torch.nn.Linear`` and on FP8 + workspace-cache paths). Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> Co-authored-by: Cursor <cursoragent@cursor.com>
When ``saved_inputmat is inp``, ``wt_save is weight`` or ``bias`` is the exact bias passed in, there is no point asking ``prepare_for_saving`` to serialize the same Python object twice. Make ``_linear_forward_impl`` emit ``None`` in those slots (and a parallel ``saved_tensor_aliases`` tuple in ``ctx_attrs`` describing which slot points where), and have ``_linear_setup_ctx`` rebuild the tuple with the original references before handing it to ``prepare_for_saving``. Saves a Python ref per alias in eager and, more importantly, keeps the forward helper from "returning" a tensor that aliases its own inputs -- a pattern ``torch.compile`` would otherwise need to reason about when the helper is wrapped in an opaque op. Numerically equivalent (validated against ``torch.nn.Linear`` and on a multi-iteration FP8 path with workspace caching). Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> Co-authored-by: Cursor <cursoragent@cursor.com>
for more information, see https://pre-commit.ci
Follow-up cleanups on top of the dataclass refactor:
* Sort ``LinearFwdArgs`` / ``LinearBwdArgs`` fields into labelled groups
(tensors, requires_grad flags, quantizers, dtype/numerical config,
parallelism, userbuffers, FSDP, wgrad scheduling, misc) and mirror that
ordering in their construction sites.
* Add ``slots=True`` to both dataclasses so typos in
``fwd_args.X`` / ``bwd_args.X`` raise ``AttributeError`` immediately
instead of silently creating a new attribute.
* Inline single-use ``args.X`` aliases in ``_linear_forward_impl``
(``weight_workspace``, ``fp8_calibration``, ``tp_size``,
``tensor_parallel``, ``cache_weight``, ``skip_fp8_weight_update``,
``custom``, ``backward_input_needs_gather``) so the prelude only keeps
aliases that are actually reused.
* Shrink ``ctx_attrs`` to ``{fsdp_shapes, saved_tensor_aliases}``:
``weight_quantizer`` is re-derived in ``_linear_setup_ctx`` from
``fwd_args.weight`` (matching the resolution done in forward),
``is_fsdp2`` already lives on ``fwd_args``, and ``owns_input`` is
equivalent to ``saved_tensor_aliases[0] != "inp"``.
* Replace ``setup_saved_tensors(saved_tensors, tensor_objects)`` with
``setup_saved_tensors(ctx)`` backed by ``restore_from_func_ctx``,
matching ``layernorm_mlp`` / ``layernorm_linear`` /
``grouped_linear`` and dropping the manual
``ctx.tensor_objects = None`` cleanup.
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
for more information, see https://pre-commit.ci
After packing the Linear backward state into ``LinearBwdArgs`` the attributes the test was reading (``backward_override``, ``fp8``, ``grad_output_quantizer``, ``reduce_and_update_bwd_fp8_tensors``) no longer live directly on ``grad_fn``. Read them from ``grad_fn.backward_objects`` when present, falling back to ``grad_fn`` for the linear-like modules that have not been refactored yet (``layernorm_linear``, ``ops_linear``). Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> Co-authored-by: Cursor <cursoragent@cursor.com>
for more information, see https://pre-commit.ci
Restore the one-line class docstrings dropped during the field reorganization so pylint stops warning about C0115. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> Co-authored-by: Cursor <cursoragent@cursor.com>
Greptile SummaryThis PR is a large refactor of
Confidence Score: 4/5The refactor is internally consistent and the new dataclass contract is well-structured, but the backward path has a known crash when the same graph node is traversed a second time. The forward→backward data handoff via LinearFwdArgs/LinearBwdArgs is clean and the alias-deduplication logic is correct. However, ctx.backward_objects is nulled after the first backward call; a second backward on the same node (retain_graph=True) immediately dereferences None and raises AttributeError, which is a real behavioral regression from the prior flat-ctx approach. transformer_engine/pytorch/module/linear.py — specifically the _Linear.backward method and the ctx.backward_objects lifecycle under retain_graph. Important Files Changed
Sequence DiagramsequenceDiagram
participant L as Linear.forward
participant FA as LinearFwdArgs
participant FI as _linear_forward_impl
participant SC as _linear_setup_ctx
participant BA as LinearBwdArgs
participant CTX as autograd ctx
participant BW as _Linear.backward
participant BI as _linear_backward
L->>FA: construct(weight, inp, bias, ...)
L->>FI: _linear_forward_impl(fwd_args)
FI-->>L: out, new_wks, tensors_to_save_from_forward, ctx_attrs
L->>BA: LinearBwdArgs()
L->>SC: _linear_setup_ctx(bwd_args, fwd_args, out, ctx_attrs, tensors)
SC-->>BA: populate all backward fields
SC-->>L: (saved_inputmat, wt_save, saved_weight, saved_bias)
L->>CTX: "prepare_for_saving(*tensors)"
L->>CTX: ctx.save_for_backward(...)
L->>CTX: "ctx.backward_objects = bwd_args"
BW->>CTX: "bwd_args = ctx.backward_objects"
BW->>BA: "bwd_args.grad_output = grad_output"
BW->>BA: bwd_args.setup_saved_tensors(ctx)
BW->>BI: _linear_backward(bwd_args)
BI-->>BW: (wgrad, dgrad, grad_bias)
BW->>CTX: "ctx.backward_objects = None"
Reviews (3): Last reviewed commit: "Merge branch 'main' into prepare_linear_..." | Re-trigger Greptile |
Saved tensors, quantizers, weakrefs and main_grad closures referenced from LinearBwdArgs survived until ctx GC, extending peak GPU memory under retain_graph=True. Null out ctx.backward_objects right after _linear_backward so they are released as soon as backward returns. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
|
/te-ci pytorch L1 |
| # Drop all references held by bwd_args (saved tensors, quantizers, weakrefs, | ||
| # main_grad closure) so they don't outlive backward via ctx under retain_graph. | ||
| ctx.backward_objects = None | ||
| del bwd_args |
There was a problem hiding this comment.
If we destroy the cached state, we should also mark backward with function.once_differentiable.
|
|
||
|
|
||
| @dataclass(slots=True) | ||
| class LinearFwdArgs: |
There was a problem hiding this comment.
This design is nicer than exposing a long list of positional args or passing in a tuple of args, but it is less nice than exposing kwargs. However, it has some advantages for this case:
torch.compileinfrastructure will only need to handle one non-tensor arg to the autograd function.- Autograd functions do some processing on each arg, so minimizing the number of non-tensor args reduces CPU overhead.
_Linear.forwardcalls_linear_forward_impland it doesn't need to be aware of the impl specifics.
|
|
||
|
|
||
| @dataclass(slots=True) | ||
| class LinearBwdArgs: |
There was a problem hiding this comment.
In typical usage, LinearBwdArgs is somewhat redundant with the autograd context class. But we need it so that the forward-context-saving and backward are less entangled with autograd, which will allow code reuse when we implement an alternate torch.compile code path.
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
|
/te-ci pytorch L1 |
* [PyTorch] Linear: minor cleanups for compile-friendliness Three small refactors that make the module easier to reason about and pave the way for the dataclass / saved-tensor refactors: - Add a TensorOrQuantized type alias (Union[Tensor, QuantizedTensorStorage]) used pervasively in helper signatures. - Hoist the conditional bias argument into a local linear_bias_tensor variable instead of an inline expression at the linear_fn() call site. - Only forward self.wgrad_store into the autograd Function when it is actually active (delay_wgrad_compute() is True); pass None otherwise so the autograd graph does not carry an unused Python object. Pure rename / hoisting; no behavioural change. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> Co-authored-by: Cursor <cursoragent@cursor.com> * [PyTorch] Linear: pack forward/backward state into dataclasses Replace the loosely typed ``non_tensor_args`` tuple and the ad-hoc ``ctx.<attr>`` plumbing with two dataclasses, ``LinearFwdArgs`` and ``LinearBwdArgs``, that act as the single argument to every helper in the forward/backward pipeline. What changes: * ``LinearFwdArgs`` carries the (positional) tensors ``weight``, ``inp`` and ``bias`` plus all quantizers, ``requires_grad`` flags, the cached ``weight_workspace`` and every former ``non_tensor_args`` knob. ``_Linear.forward`` still takes ``weight/inp/bias`` as positional Tensor inputs so autograd tracks them, then immediately re-attaches them to ``fwd_args`` so every downstream helper has a single-argument signature. * ``LinearBwdArgs`` mirrors that on the backward side: it owns the saved tensors (``inputmat``, ``weight_fp8``, ``saved_weight``, ``bias``), the per-call quantizers, every flag previously stored directly on ``ctx`` and a ``setup_saved_tensors(saved_tensors, tensor_objects)`` helper that rehydrates the saved-tensor fields. * ``ctx.backward_objects = bwd_args`` is now the single attribute the autograd context needs (besides ``saved_tensors``/``tensor_objects``). * ``weight_workspace`` is no longer a positional Tensor arg of the autograd Function; it is read from ``fwd_args.weight_workspace`` and the freshly produced workspace is returned alongside ``out`` so the module can refresh its cache without autograd tracking the cache. * ``prepare_for_saving`` now lives at the autograd boundary in ``_Linear.forward``; ``_linear_setup_ctx`` only returns the merged list of tensors that should be saved. * ``grad_output_preprocess`` is invoked with ``bwd_args`` directly (it is duck-typed on the same attribute names) so backward never reaches into ``ctx.<attr>`` for non-tensor state. Behaviour preserved (verified numerically against ``torch.nn.Linear`` and on FP8 + workspace-cache paths). Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> Co-authored-by: Cursor <cursoragent@cursor.com> * [PyTorch] Linear: deduplicate saved tensors that alias forward inputs When ``saved_inputmat is inp``, ``wt_save is weight`` or ``bias`` is the exact bias passed in, there is no point asking ``prepare_for_saving`` to serialize the same Python object twice. Make ``_linear_forward_impl`` emit ``None`` in those slots (and a parallel ``saved_tensor_aliases`` tuple in ``ctx_attrs`` describing which slot points where), and have ``_linear_setup_ctx`` rebuild the tuple with the original references before handing it to ``prepare_for_saving``. Saves a Python ref per alias in eager and, more importantly, keeps the forward helper from "returning" a tensor that aliases its own inputs -- a pattern ``torch.compile`` would otherwise need to reason about when the helper is wrapped in an opaque op. Numerically equivalent (validated against ``torch.nn.Linear`` and on a multi-iteration FP8 path with workspace caching). Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> Co-authored-by: Cursor <cursoragent@cursor.com> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [PyTorch] Linear: tighten LinearFwdArgs/BwdArgs and trim ctx_attrs Follow-up cleanups on top of the dataclass refactor: * Sort ``LinearFwdArgs`` / ``LinearBwdArgs`` fields into labelled groups (tensors, requires_grad flags, quantizers, dtype/numerical config, parallelism, userbuffers, FSDP, wgrad scheduling, misc) and mirror that ordering in their construction sites. * Add ``slots=True`` to both dataclasses so typos in ``fwd_args.X`` / ``bwd_args.X`` raise ``AttributeError`` immediately instead of silently creating a new attribute. * Inline single-use ``args.X`` aliases in ``_linear_forward_impl`` (``weight_workspace``, ``fp8_calibration``, ``tp_size``, ``tensor_parallel``, ``cache_weight``, ``skip_fp8_weight_update``, ``custom``, ``backward_input_needs_gather``) so the prelude only keeps aliases that are actually reused. * Shrink ``ctx_attrs`` to ``{fsdp_shapes, saved_tensor_aliases}``: ``weight_quantizer`` is re-derived in ``_linear_setup_ctx`` from ``fwd_args.weight`` (matching the resolution done in forward), ``is_fsdp2`` already lives on ``fwd_args``, and ``owns_input`` is equivalent to ``saved_tensor_aliases[0] != "inp"``. * Replace ``setup_saved_tensors(saved_tensors, tensor_objects)`` with ``setup_saved_tensors(ctx)`` backed by ``restore_from_func_ctx``, matching ``layernorm_mlp`` / ``layernorm_linear`` / ``grouped_linear`` and dropping the manual ``ctx.tensor_objects = None`` cleanup. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> Co-authored-by: Cursor <cursoragent@cursor.com> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [PyTorch] tests: snapshot backward ctx state from LinearBwdArgs After packing the Linear backward state into ``LinearBwdArgs`` the attributes the test was reading (``backward_override``, ``fp8``, ``grad_output_quantizer``, ``reduce_and_update_bwd_fp8_tensors``) no longer live directly on ``grad_fn``. Read them from ``grad_fn.backward_objects`` when present, falling back to ``grad_fn`` for the linear-like modules that have not been refactored yet (``layernorm_linear``, ``ops_linear``). Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> Co-authored-by: Cursor <cursoragent@cursor.com> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [PyTorch] Linear: add docstrings to LinearFwdArgs / LinearBwdArgs Restore the one-line class docstrings dropped during the field reorganization so pylint stops warning about C0115. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> Co-authored-by: Cursor <cursoragent@cursor.com> * [PyTorch] Linear: drop ctx.backward_objects after backward Saved tensors, quantizers, weakrefs and main_grad closures referenced from LinearBwdArgs survived until ctx GC, extending peak GPU memory under retain_graph=True. Null out ctx.backward_objects right after _linear_backward so they are released as soon as backward returns. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> --------- Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…r torch.compile Restructure the two modules the same way Linear was restructured in NVIDIA#2967, so the follow-up custom-op registration is a pure wiring change: - LayerNormLinearFwdArgs / LayerNormLinearBwdArgs and LayerNormMLPFwdArgs / LayerNormMLPBwdArgs dataclasses replace the positional non_tensor_args tuple and the ad-hoc ctx.<attr> plumbing. - The autograd Functions shrink to thin wrappers around module-level _layernorm_{linear,mlp}_forward_impl / _setup_ctx / _backward_impl that take one dataclass argument. Saved tensors that alias forward inputs or outputs are deduplicated by name and rebuilt in setup_ctx. - LayerNormMLP keeps activation checkpointing: the forward saves only its inputs, and _layernorm_mlp_recompute re-runs the forward impl in backward with recompute_for_bwd set, filling the backward args from the recomputed state. - The weight workspaces move from positional autograd inputs into the args bag and are returned as extra outputs; backward-only recipe knobs (split accumulators, backward_override, debug UB flags, delayed wgrad_store) are resolved in Module.forward. - check_fp8_reduce_and_update moves to module/_common.py and is shared with Linear. No functional change. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
…elpers Behavior-neutral restructuring of the cuDNN fused attention autograd function, mirroring what NVIDIA#2967 did for Linear: FusedAttnFwdArgs / FusedAttnBwdArgs dataclasses, module-level _fused_attn_forward_impl, _fused_attn_setup_ctx and _fused_attn_backward_impl, and a thin FusedAttnFunc wrapper taking the differentiable tensors plus one args object instead of 37 positional arguments. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
…elpers (#3480) * [PyTorch] Split FusedAttnFunc into single-argument forward/backward helpers Behavior-neutral restructuring of the cuDNN fused attention autograd function, mirroring what #2967 did for Linear: FusedAttnFwdArgs / FusedAttnBwdArgs dataclasses, module-level _fused_attn_forward_impl, _fused_attn_setup_ctx and _fused_attn_backward_impl, and a thin FusedAttnFunc wrapper taking the differentiable tensors plus one args object instead of 37 positional arguments. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * [PyTorch] Match the fused attention aux pack split to the C++ conditions The bias / softmax_offset aux entries exist only when the tensor was passed, not merely when the bias / softmax type asks for one. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * [PyTorch] Make fused attention saved tensor sources explicit Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * [PyTorch] Preserve separate attention page tables and unset backward defaults Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> --------- Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
…r torch.compile (#3493) * [PyTorch] [torch.compile] Prepare LayerNormLinear and LayerNormMLP for torch.compile Restructure the two modules the same way Linear was restructured in #2967, so the follow-up custom-op registration is a pure wiring change: - LayerNormLinearFwdArgs / LayerNormLinearBwdArgs and LayerNormMLPFwdArgs / LayerNormMLPBwdArgs dataclasses replace the positional non_tensor_args tuple and the ad-hoc ctx.<attr> plumbing. - The autograd Functions shrink to thin wrappers around module-level _layernorm_{linear,mlp}_forward_impl / _setup_ctx / _backward_impl that take one dataclass argument. Saved tensors that alias forward inputs or outputs are deduplicated by name and rebuilt in setup_ctx. - LayerNormMLP keeps activation checkpointing: the forward saves only its inputs, and _layernorm_mlp_recompute re-runs the forward impl in backward with recompute_for_bwd set, filling the backward args from the recomputed state. - The weight workspaces move from positional autograd inputs into the args bag and are returned as extra outputs; backward-only recipe knobs (split accumulators, backward_override, debug UB flags, delayed wgrad_store) are resolved in Module.forward. - check_fp8_reduce_and_update moves to module/_common.py and is shared with Linear. No functional change. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * Re-mark rebuilt saved-tensor views for CPU offload setup_ctx rebuilds the inp/ln_out save slots as fresh views, which drop the activation-offload mark set in forward, so the V1 offload path kept these activations on GPU. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * Preserve delayed wgrad store across forward and backward Pass the live weight-gradient store to LayerNormLinear and LayerNormMLP backward regardless of its state during forward. This preserves mode changes before backward and prevents backward_dw from reading an empty queue. Add numerical regressions for both toggle directions, including LayerNormMLP activation checkpointing. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * Remove delayed wgrad toggle regression tests Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * Remove duplicate Dynamo decorator from LayerNormMLP Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> --------- Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
…rm modules for compile wiring Behavior-neutral groundwork for registering LayerNormLinear and LayerNormMLP as torch.compile custom ops (follows the Linear split NVIDIA#2967 / NVIDIA#3053). dynamo/custom_op.py: - A bwd args dataclass may declare GRAD_OUTPUT_FIELDS naming one grad field per user output; the LN modules have two differentiable outputs (out and the returned norm output), so a single grad_output slot is not enough. - Dict[str, <simple>] annotations are bundle-simple (activation_params). module/_common.py: sp_out_leading / sp_inp_leading / fake_workspace_valid shared by Linear and the LN modules (moved out of linear.py). layernorm_linear.py / layernorm_mlp.py: - GRAD_OUTPUT_FIELDS on the bwd args; fp8_output carried in the fwd args. - inp_shape is rederived from grad_output in backward instead of being stored on the bwd args (SymInt dims are not hashable in the value bundle). - LayerNormMLP: the recipe object no longer rides on the backward args; the properties the backward needs (float8_block_scaling, custom, dbias-dact fusion availability) are bools computed in Module.forward. The activation tables are split into per-activation (act, dact) pairs plus the fused dbias kernels so the backward looks them up without a recipe. - The returned-norm-output grad is tolerated as None in backward. No functional change. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
…rm modules for compile wiring Behavior-neutral groundwork for registering LayerNormLinear and LayerNormMLP as torch.compile custom ops (follows the Linear split NVIDIA#2967 / NVIDIA#3053). dynamo/custom_op.py: - A bwd args dataclass may declare GRAD_OUTPUT_FIELDS naming one grad field per user output; the LN modules have two differentiable outputs (out and the returned norm output), so a single grad_output slot is not enough. - Dict[str, <simple>] annotations are bundle-simple (activation_params). module/_common.py: sp_out_leading / sp_inp_leading / fake_workspace_valid shared by Linear and the LN modules (moved out of linear.py). layernorm_linear.py / layernorm_mlp.py: - GRAD_OUTPUT_FIELDS on the bwd args; fp8_output carried in the fwd args. - inp_shape is rederived from grad_output in backward instead of being stored on the bwd args (SymInt dims are not hashable in the value bundle). - LayerNormMLP: the recipe object no longer rides on the backward args; the properties the backward needs (float8_block_scaling, custom, dbias-dact fusion availability) are bools computed in Module.forward. The activation tables are split into per-activation (act, dact) pairs plus the fused dbias kernels so the backward looks them up without a recipe. - The returned-norm-output grad is tolerated as None in backward. No functional change. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
* [PyTorch] Split FusedAttnFunc into single-argument forward/backward helpers Behavior-neutral restructuring of the cuDNN fused attention autograd function, mirroring what #2967 did for Linear: FusedAttnFwdArgs / FusedAttnBwdArgs dataclasses, module-level _fused_attn_forward_impl, _fused_attn_setup_ctx and _fused_attn_backward_impl, and a thin FusedAttnFunc wrapper taking the differentiable tensors plus one args object instead of 37 positional arguments. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * [PyTorch] Match the fused attention aux pack split to the C++ conditions The bias / softmax_offset aux entries exist only when the tensor was passed, not merely when the bias / softmax type asks for one. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * [PyTorch] torch.compile support for FusedAttention Register the cuDNN fused attention forward/backward as a torch custom op through dynamo/custom_op.py, reusing the single-argument helpers behind FusedAttnFunc, so DotProductAttention with the fused backend traces under torch.compile(fullgraph=True), including KV caching. F16/BF16 only; FP8, context parallelism, score_mod, FAv2 backward and CPU offloading keep falling back to eager via no_torch_dynamo(when=...). Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * [PyTorch] Preserve packed gradients in compiled fused attention Differentiate packed QKV and KV inputs directly and return their native packed gradient buffers without contiguous copies or repacking. Cover packed backward graphs, FP16/BF16 gradients and CUDA graph replay, and rename the custom-op-unavailable fallback test. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * [PyTorch] Simplify compiled fused attention output handling Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * [PyTorch] Remove redundant fused attention gradient conversions DPA routes undeclared packed QKV views to eager before custom-op dispatch. Return the independently allocated gradients directly for the remaining unpacked path. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * [PyTorch] Unify fused attention backward state setup Store packed gradient metadata in FusedAttnBwdArgs and initialize all backward state in the shared setup function. Reconstruct omitted QKV views in the shared forward and setup, removing the custom-op-specific dataclass and forwarding wrappers. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * Keep fused attention packed inputs in saved backward state Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * Consolidate packed attention compile tests into shared configurations Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * Declare fused attention RNG effects and align fake statistics Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> * Address fused attention compile review feedback Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com> --------- Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Description
Refactor of
transformer_engine/pytorch/module/linear.pyto lift theLinearmodule into a shape that can be wrapped in atorch.library.custom_op(and matching backward op) in a follow-up PR.Type of change
Changes
LinearFwdArgs/LinearBwdArgsdataclasses.
_linear_forward_impl,_linear_setup_ctx,_linear_backwardand the_Linear.{forward,backward}autogradmethods all take a single structured argument instead of 25+
positional ones. A custom op requires a fully-declared signature on
both sides; the previous pattern of writing arbitrary
ctx.something = ...attributes scattered throughout forward madeit impossible to tell from the call site what state backward
actually consumes. The dataclasses make the read/write contract
explicit and grep-able. Concretely, things that used to be re-queried
from tensor objects (
input.requires_grad,weight.requires_grad,bias.requires_grad) are now captured up front asinput_requires_grad/weight_requires_grad/bias_requires_gradand consumed asrequires_dgrad/requires_wgradin backward — backward no longer has to assume thePython tensor objects survive the op boundary.
prepare_for_saving/ctx.save_for_backwardto the autogradboundary.
_linear_forward_implreturns the raw tensors itproduced (along with
tensors_to_save_from_forwardaliases) and_linear_setup_ctxreturns the raw merged tensor list it wantssaved;
_Linear.forwardis the only place that actually callsprepare_for_saving(*tensors_to_save_from_setup)andctx.save_for_backward(...). This shape fell out of the compile-pathexperiments: under
torch.library.register_autograd, thesetup_contextcallback is the only legal place to callsave_for_backward, and the helper has to hand back tensors ratherthan mutate the autograd ctx itself. Same contract is now used in
eager so a single helper serves both modes.
that would alias
inp/weight/biasare emitted asNoneandreconstructed in
_linear_setup_ctxfrom the original refs. Anopaque custom op cannot return aliases of its inputs (the tracer
has no way to reason about the aliasing).
ctx_attrsblob plumbed from forward to backwardsetup. Anything that can be re-derived from
LinearFwdArgs(
weight_quantizer,is_fsdp2,owns_input) is recomputed in_linear_setup_ctx. The compile path needs the fake forward implto return a structurally identical
ctx_attrs, so a smaller surfaceis a smaller cross-impl contract.
Checklist: