[PyTorch] [torch.compile] torch.compile support for Linear - #3053
Open
pggPL wants to merge 5 commits into
Open
Conversation
Register the Linear forward/backward as torch.library custom ops on top of the TensorSpec mechanism (NVIDIA#3153), so Linear traces under fullgraph compile with FP8/MXFP8/NVFP4 recipes. - transformer_engine/pytorch/dynamo/custom_op.py: custom-op registration framework (arg bundles, fake impls, autograd wiring) - module/linear.py: split forward into compute + ctx save, fake forward/backward - tests/pytorch/test_torch_compile.py: coverage for the compiled path Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
pggPL
force-pushed
the
linear_torch_compile_final_attempt
branch
from
August 5, 2026 16:07
98cd401 to
c6544d0
Compare
for more information, see https://pre-commit.ci
black wrapped the 122-char except clause, moving Exception onto its own line while the disable comment stayed on the closing paren, so pylint's W0718 no longer saw it. Shorten the line instead. Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Contributor
Greptile SummaryThis PR adds full-graph
Confidence Score: 5/5The PR appears safe to merge based on the eligible follow-up findings available for this review. No blocking failure remains in the available follow-up review scope. Important Files Changed
Sequence DiagramsequenceDiagram
participant User
participant Linear
participant Wrapper as Custom-op wrapper
participant Base as Base custom op
participant Kernel as Linear implementation
participant Autograd
User->>Linear: forward(input)
Linear->>Wrapper: structured LinearFwdArgs
Wrapper->>Wrapper: flatten tensors, quantized storage, and opaque values
Wrapper->>Base: flat custom-op inputs
Base->>Kernel: reconstructed argument bundle
Kernel-->>Base: output, workspace, and saved tensors
Base-->>Wrapper: flat Tensor[] payload
Wrapper-->>Linear: reconstructed outputs
Linear-->>User: output
User->>Autograd: backward(grad_output)
Autograd->>Base: saved state and flat gradient inputs
Base->>Kernel: Linear backward implementation
Kernel-->>Autograd: input, weight, and bias gradients
Reviews (2): Last reviewed commit: "[pre-commit.ci] auto fixes from pre-comm..." | Re-trigger Greptile |
Naming consistency and de-duplication in the torch.compile custom-op framework and its Linear user. No functional change. Naming: - unify the register_custom_op API on fwd_*/bwd_* (backward_arg_type, backward_impl, backward_obj_type -> bwd_arg_type, bwd_impl) - _register_kernel -> _register_base_op, pairing with _register_wrapper_op - _format_*_result / _split_fwd_fake_result -> _pack_*_result / _unpack_fwd_fake_result - _value_to_flat_tensors / _spec_reassemble -> _flatten_value / _unflatten_value, matching _storage_flatten / _storage_unflatten - adapter slots: tensor_slot / inner_slot / meta_slot, META_SLOT, QUANTIZER_KEY - _linear_backward -> _linear_backward_impl and *_fake twins, so the real and fake implementations pair up by name - ctx attrs: drop the lone _te_ prefix, and use ctx.backward_objects as the eager path already does - move warn_compile_unsupported to utils as warn_compile_disabled, next to warn_compile_eager_fallback, so the two "unsupported" meanings are distinguishable - move the TensorOrQuantized alias next to the adapter that matches it De-duplication: - _unflatten_values() replaces three copies of the cursor/reassemble loop - _make_slot_forwarder() / _make_dispatch_rule() replace three copies of the subclass-flattening forward path - _sp_out_leading() / _sp_inp_leading() replace three copies of the sequence-parallel leading-dim arithmetic (two of them inverses) - check_gemm_dims() moves the fp8 dimension checks to utils - drop the duplicate backward_needs_input assignment in the forward impl Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
for more information, see https://pre-commit.ci
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
This PR adds
torch.compilesupport forte.pytorch.Linear, building on theTensorSpecmechanism already inmain._Linear's forward and backward are registered astorch.librarycustom ops, so a module containingte.Lineartraces undertorch.compile(fullgraph=True)without graph breaks. The fake (meta) implementations describe the produced tensors throughTensorSpecinstead of allocating them, which is what makes the quantized outputs traceable — the compiler sees the full quantized-tensor structure (data, scales, transposes) without any device allocation at trace time.The bulk of the diff is
transformer_engine/pytorch/dynamo/custom_op.py: a declarativeregister_custom_ophelper. Custom ops require flat lists of tensors, while the TE forward/backward take dataclass "argument bundles" holding tensors, quantized tensors, quantizers, process groups and plain Python values. The helper derives the op schema from the dataclass field annotations, flattens each field to op slots via a per-kind adapter, and rebuilds the bundle on the other side, so ops are declared by writing a dataclass rather than by hand-maintaining a schema string.Type of change
Changes
dynamo/custom_op.py(new):register_custom_op— declarative registration of forward/backward custom ops from dataclass argument bundles. Handles per-field adapters for plain tensors, quantized tensors, quantizers, opaque value bundles and reference-opaque types (e.g. process groups), schema generation,TensorSpec-based fake outputs and autograd wiring. Falls back to eager with a single warning if registration fails.dynamo/__init__.py: exportregister_custom_op.module/linear.py: split the forward into pure computation and context saving, add allocation-free fake forward/backward onTensorSpec, and register_Linearthroughregister_custom_op. Eager behavior is unchanged.dynamo/quantizer_opaque.py,dynamo/tensor_spec.py,tensor/_quantization_helpers.py,tensor/float8_tensor.py,tensor/storage/float8_tensor_storage.py,utils.py: small supporting changes (idempotent spec conversion, weight-workspace quantizer preservation, keeping attributes attached to quantized parameters across_apply).tests/pytorch/test_torch_compile.py: coverage for the compiled Linear — fullgraph compilation, quantized FP8 weights, FP8 output,is_first_microbatch, dynamic shapes, parametrized over the supported recipes (FP8 per-tensor/current scaling, MXFP8, NVFP4).tests/pytorch/distributed/*: exercise the compiled path in the distributed numerics and comm-GEMM-overlap runs.Checklist: