Repository navigation
FSDP: allow extensions to release all-gather outputs - #194114
anijain2305 wants to merge 2 commits into
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/194114
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (3 Unrelated Failures)As of commit 7b1594f with merge base ab5fb26 ( BROKEN TRUNK - The following job failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
weifengpy
left a comment
There was a problem hiding this comment.
considering bc and not changing function signature, this getattr approach is easiest
Failing jobs: lintrunner-pyrefly-all / lint and lintrunner-pyrefly-partial / lint Failing target: torch/distributed/fsdp/_fully_shard/_fsdp_param.py CI command: LINTER_GROUP=pyrefly .github/scripts/lintrunner.sh Error: PYREFLY not-callable Expected a callable, got `None` should_release = release_all_gather_outputs_fn() The presence boolean did not narrow the optional hook for Pyrefly. Check the hook itself for None at the call site so the type checker knows it is callable while preserving the existing runtime behavior. Test Plan: ``` lintrunner -a torch/distributed/fsdp/_fully_shard/_fsdp_param.py ``` This CI fix was authored with an AI assistant. [ghstack-poisoned]
| if has_fsdp_pre_all_gather: | ||
| self._extensions_data = ExtensionsData() | ||
| self._release_all_gather_outputs_after_post_all_gather = False | ||
| if release_all_gather_outputs_fn is not None: |
There was a problem hiding this comment.
This hunk was LLM-generated by mergedog in commit 4ae652e4afdf. Review that commit for context and justification.
Note
This PR is being shepherded by mergedog, an automation tool run by a maintainer. It watches CI and may push fixes; the PR author does not need to act unless a maintainer asks.
|
@pytorchbot merge |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
Adds an optional per-parameter FSDP tensor-subclass hook allowing post-all-gather transformations to release the original all-gather buffers immediately while retaining transformed tensors until normal resharding. Using this capability requires a tensor-subclass parameter implementing the FSDP extension hooks; existing extensions remain unchanged. Pull Request resolved: pytorch#194114 Approved by: https://github.com/weifengpy
## Summary This PR overhauls MXFP8 linear training in TorchTitan. The key design choice is a narrow TorchAO/TorchTitan boundary: **TorchTitan relies on TorchAO only for MXFP8 quantization and layout kernels, while TorchTitan owns autograd, FSDP cache management, and model policy.** Thanks to Vasiliy Kuznetsov for adding the TorchAO kernel support used here. The main changes are: - FSDP owns the quantized weights and scales, so their lifetime follows the normal FSDP unshard/reshard lifecycle and composes with both values of `reshard_after_forward`. - Weight quantization is pluggable. The built-in strategy uses 2D `32x32` scaling for weights, while inputs use standard 1D scaling. - `MXFP8Linear` can save either the original BF16 input or its columnwise-quantized representation for WGRAD. TorchTitan model configs select the optimized policy only where the BF16 input is not retained elsewhere. ## TorchAO and TorchTitan boundary TorchTitan currently uses the following kernel-level operations from TorchAO: - `mxfp8_quantize_cuda` for rowwise and columnwise activation quantization. - `triton_to_mxfp8_32x32_swizzle_dim0_and_dim1` for 2D weight quantization and Blackwell-ready layouts. - `triton_mx_block_rearrange` for scale layout conversion. TorchTitan owns everything that interacts with training structure: - `_MXFP8LinearFunction` and `MXFP8Linear`. - FSDP tensor subclasses and pre/post-all-gather hooks. - Quantized-weight storage and lifetime. - The pluggable weight strategy. - Model-specific activation-storage policy. The current kernels are sufficient for this integration. More heavily fused kernels can be added later as small, independent TorchAO changes without moving FSDP or parallelism policy into TorchAO. ## FSDP-managed quantized weights The FSDP post-all-gather hook quantizes the unsharded BF16 weight and returns the independent MXFP8 qdata and scale tensors for FSDP to manage. There is no separate module-level or autograd-level weight cache. This gives the quantized representation the same lifecycle as the unsharded FSDP parameter: | `reshard_after_forward` | Behavior | |---|---| | `False` | Quantize on the first unshard and reuse the MXFP8 operands across PP microbatches. PP can retain them through the microbatch sequence and release them after the final backward. | | `True` | Reshard after forward. Backward performs another BF16 all-gather and post-all-gather quantization. | FSDP keeps the compute-weight object stable and allocates, frees, or refills its inner tensors through the post-all-gather `out=` contract. This lets us reuse the existing FSDP state machine instead of maintaining a second cache lifecycle in `MXFP8Linear`. The implementation also uses the tensor-subclass API from [pytorch/pytorch#194114](pytorch/pytorch#194114), which allows FSDP to release the BF16 all-gather output after the independent MXFP8 representation has been constructed. ## Pluggable quantization strategy The practical default used by this PR is: | Operand | Scaling | |---|---| | Weights | 2D `32x32` | | FPROP inputs | 1D `1x32` | | WGRAD inputs | 1D `32x1` | There are two reasons for this choice: 1. With 1D weight scaling, the scale groups needed by FPROP and DGRAD have different orientations. The two weight representations must therefore be quantized separately and may contain different quantized values. With square `32x32` tiles, the quantization groups are invariant under transpose, so DGRAD qdata can be a transpose view of the FPROP qdata. 2. Inputs remain one-dimensional because a 2D activation scale may span multiple sequence positions. In causal attention, that would allow a token's quantization scale to depend on future tokens. The PR intentionally provides only the built-in 2D weight strategy. The implementation remains extensible through `MXFP8WeightQuantizationStrategy`: a different strategy supplies its quantization implementation, and strategies with aliased storage can additionally describe how their logical GEMM operands are reconstructed from the independent tensors managed by FSDP. Every strategy must return qdata and blocked scales compatible with the `scaled_mm` scaling and swizzle contract used by `MXFP8Linear`. ## Revamped `MXFP8Linear` The previous activation path was: ```text Forward: rowwise-quantize X + save BF16 X Backward: retrieve BF16 X + columnwise-quantize X for WGRAD ``` This remains the conservative default, but the PR adds an optimized policy: ```text Forward: rowwise- and columnwise-quantize X + save columnwise MXFP8 X Backward: retrieve the saved columnwise MXFP8 X ``` | `wgrad_input_storage` | Forward quantization | Saved for WGRAD | Backward work | |---|---|---|---| | `high_precision` (default) | Rowwise only | Original BF16 `X` | Columnwise-quantize `X` | | `quantized` | Fused rowwise + columnwise | Columnwise qdata and scales | Reuse saved operand | The quantized policy can reduce saved-activation memory and avoids a quantization pass during backward. It also allows the rowwise and columnwise outputs to be produced in one kernel call, reducing HBM traffic. This design is similar to the activation handling used by NVIDIA Transformer Engine. The important caveat is that this saves memory only when no other operation retains the same BF16 `X`. If BF16 `X` is already retained elsewhere, saving an additional quantized representation increases memory. We therefore keep `high_precision` as the default to avoid an unexpected memory regression or OOM, and select `quantized` explicitly for audited modules. | Is the same BF16 input retained elsewhere? | Policy | Reason | |---|---|---| | Yes or unknown | `high_precision` | Avoid keeping both BF16 and quantized WGRAD inputs. | | No | `quantized` | Replace the saved BF16 WGRAD input with the smaller quantized representation. | The current TorchTitan policies are: | Model | Modules using `quantized` | |---|---| | Llama 3 | `attention.qkv_linear.wqkv`, `feed_forward.w2` | | DeepSeek V3 | `attention.wkv_b`, `feed_forward.w2`, `shared_experts.w2` | | Flux | None; it retains the conservative default | All other converted linears use `high_precision`. The standard Trainer and GraphTrainer share these model policies. The grouped-expert/Grouped GEMM path is unchanged by this PR. ## Testing - Unit coverage for activation policies, pluggable weight strategies, and FSDP tensor reconstruction. - FSDP lifecycle coverage for both values of `reshard_after_forward`, including PP cache reuse and final-backward release. - Compiled FSDP, PP, and GraphTrainer training runs. ## Appendix: RAF and activation-checkpointing trade-offs Activation checkpointing affects which weight representations are needed during the backward unshard. It does not change the WGRAD input-storage policy described above. The current post-all-gather hook constructs both FPROP and DGRAD weight operands on every actual unshard: | RAF | AC | Current behavior | Ideal behavior | |---|---|---|---| | `False` | Off | Construct both once and reuse | Construct both once and reuse | | `False` | On | Construct both once and reuse | Construct both once and reuse | | `True` | Off | Construct both in forward and both again in backward | FPROP in forward, DGRAD in backward | | `True` | On | Construct both in forward and both again before backward | FPROP in forward, both before backward | For `RAF=False`, the current behavior is already ideal because both representations are constructed once and reused. For `RAF=True`, the initial forward only needs FPROP. Without AC, the backward unshard only needs DGRAD. With AC, however, the backward unshard must support both the recomputed forward and DGRAD. FSDP internally knows its training phase and RAF setting, but this context is not currently exposed through the post-all-gather hook. In addition, checkpoint recomputation is not always known when the backward unshard begins. This PR deliberately keeps the hook simple and correct by constructing both representations. A future FSDP hook extension could expose the unshard context and enable phase-specific construction.
Stack from ghstack (oldest at bottom):
Adds an optional per-parameter FSDP tensor-subclass hook allowing post-all-gather transformations to release the original all-gather buffers immediately while retaining transformed tensors until normal resharding. Using this capability requires a tensor-subclass parameter implementing the FSDP extension hooks; existing extensions remain unchanged.