Repository navigation
Conversation
…lexShardConfig() Stacked on #5842, the expert-parallelism PR, the chunked-loss PR and the checkpointing PR. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Description The checkpointing PR rejects `checkpointer.initial_load_in_hf` with `parallelism.fsdp_backend=FlexShardConfig()`, so a FlexShard run can't start from a Hugging Face checkpoint, which is how fine-tuning and continued pretraining start. Lifting the rejection alone fails the load. The state dict adapters' `to_hf` and `from_hf` convert FSDP2's DTensors and full tensors, and take each of FlexShard's plain local shards for the whole tensor. The layouts that the checkpointing PR declares on the state dict's tensors (DCP's `CheckpointableTensor`) don't help: the new tensors `to_hf` makes from them (a split stacked linear, a permuted query weight, one expert's slice) have none. On 2 GPUs, the Llama 3 debug model's load fails with DCP's size mismatch, saved `[768, 256]` against current `[384, 256]`, for `model.layers.0.mlp.gate_proj.weight`. This PR loads Hugging Face checkpoints into FlexShard's local shards, with each rank reading only its part of each tensor. As in #5842, nothing on the FlexShard path creates a DTensor. The earlier revision of this PR viewed each FlexShard parameter as the DTensor FSDP2 would give it (`as_fsdp2_dtensor`), which #5842 has since deleted. The Llama 3 and Qwen3 adapters' conversions only move rows: each Hugging Face tensor holds rows of one parameter, with its leading dims re-indexed and its last dim kept whole and in order. That holds for the renames, the stacked `w13` split, the packed QKV split, Llama 3's permutation of the query and key rows for rotary embeddings, and the split of the routed experts into one tensor per expert. So the new `load_hf_into_local_shards` (in `flex_shard_fsdp.py`) asks the adapter where each row goes. For each local shard, it runs `to_hf` on a probe with the full parameter's shape but a last dim of 2, whose rows hold their own indices: each Hugging Face output then says which row of the parameter each of its rows holds. The largest probe of the Qwen3 MoE debug model, for a routed `w13`, is 1.6 MB. Each region of the shard's layout is a box of the parameter: it holds only some columns of its rows if the shard splits the last dim, as tensor parallelism does for row-wise parallel weights later in this stack. For each region, the function finds the Hugging Face rows that hold the region's rows and declares them, with the region's columns, on a plain tensor as `CheckpointableTensor` chunks, one per run of consecutive rows, so `dcp.load` with the adapter's Hugging Face reader reads only this rank's elements. - Where those rows come from one region and are consecutive rows of the shard, in order (the renames, the `w13` split and the experts), the tensor is a view of the shard, and the load fills the parameter in place, as it fills FSDP2's DTensors. - Otherwise (the QKV split and the rotary permutation), the tensor is a buffer, whose rows are copied into the shard after the load. The buffers hold this rank's share of the QKV weights. - A shard that ends inside a head gets that head's rows in two chunks after the rotary permutation, so a tensor has at most five chunks, and no rank reads a row it doesn't hold. - It raises if `to_hf` changes the last dim (the probe's second column shows it) or doesn't give each of the shard's rows exactly once. - Entries without a layout go through `to_hf` and `from_hf`, as for FSDP2. `from_hf` runs even without such entries, as for the Llama 3 and Qwen3 models, whose state dicts hold only parameters, so its checks of the model config, such as Llama 3's check of its rotary embeddings, run as for FSDP2. `from_hf` isn't used for the shards: it rebuilds whole tensors (all experts, whole QKV groups). The inverse of `to_hf`'s row map is what `from_hf` computes, since `from_hf` inverts `to_hf`. `CheckpointManager._load_checkpoint` calls the function when an entry of the model state dict declares a layout, which only FlexShard's do: DTensors and plain tensors aren't `CheckpointableTensor`s. The simpler alternatives hold the whole model on every rank. Loading into full tensors through today's adapter code and keeping each rank's part, or gathering the parameters before the conversion, makes every rank allocate and read the whole checkpoint. For a DeepSeek-V3-sized model (671B parameters, 1.34 TB in bf16) on 256 ranks, that is 2.7 TB of fp32 tensors per rank and 343 TB read in total, where this PR reads 1.34 TB in total and allocates only buffers for the QKV split on top of the shards. Writing the layout arithmetic into each adapter instead would give every conversion a second description, next to the code that moves the data, that the two would have to keep in step. For comparison, FSDP2's own Hugging Face load replicates the query, key and value weights of every layer on every rank, since `_split_qkv_linear` redistributes them to `Replicate()`. `validate_flex_shard_training` allows `initial_load_in_hf` with `Llama3StateDictAdapter` and `Qwen3StateDictAdapter`, the two checked against FSDP2, and rejects it with other adapters. The function doesn't depend on the adapter, so allowing another one takes a parity case, unless its `to_hf` changes the last dim or combines parameters, which the checks above reject. Validation now rejects `initial_load_in_hf_quantized` by name, which it rejected through `initial_load_in_hf` before, and still rejects `last_save_in_hf`. Both come later in this stack. The parity test file gains `test_hf_loads_match_fsdp2`, on the Llama 3 debug model, and `test_hf_loads_match_fsdp2_with_expert_parallelism`, on the Qwen3 MoE debug model with `ep=2`. FSDP2 trains three steps and exports a Hugging Face checkpoint (`last_save_in_hf`, float32). A fresh FSDP2 model and a fresh FlexShard model, each from its own initialization, load it with `initial_load_in_hf`. FSDP2's parameters must equal the exported ones, each FlexShard shard must equal its slice of them (by the layouts flex_shard reports), and three AdamW steps from the loaded parameters must give bitwise-equal losses, grad norms, grads and parameters on both backends. That covers the views (embeddings, `w13`, the experts), the buffers (QKV split, rotary permutation) and EP's split of the experts. In CI the tests run on 4 GPUs, where `ep=2` leaves `edp_shard=2`. Both pass on 2 GB200 GPUs with `world_size` set to 2, in 45 s. Without the new branch in `_load_checkpoint`, the Llama 3 test fails with the size mismatch above. Without the copy of the buffers into the shards, it fails on `layers.0.attention.qkv_linear.wqkv.weight`. The comparison of training histories moves, unchanged, into `_assert_equal_histories`. The debug models' shards end on head boundaries at 2 and 4 ranks, so those tests don't cut a head. `test_hf_load_into_uneven_shards` does, on CPU and without a process group (it sits in the same file because it needs flex_shard). It loads a Hugging Face checkpoint of the Llama 3 debug model into simulated FlexShard shards at `torch.chunk`'s boundaries over 5 ranks, which cuts heads, and over 5 x 2 ranks whose shards also split the last dim, and every simulated rank's shards must equal their boxes of the checkpoint. Of the Hugging Face tensors loaded, 30 and 60 come in several chunks and 90 and 180 go through a buffer. With the chunks of a tensor declared in reverse order, the test fails on `layers.0.attention.qkv_linear.wqkv.weight`. One-off CPU checks (not part of the PR) also load the Qwen3 MoE debug model over 3 ranks by experts and over 5 ranks by expert rows, entries without a layout through `to_hf` and `from_hf`, and tensor-parallel layouts (`tp` x `dp_shard` of 2 x 1, 2 and 3 and 3 x 5 for Llama 3, 2 x 3 for Qwen3 MoE, and two column regions per rank of `wo` and `w2`). Every rank's shards equal their boxes of the checkpoint, and DCP reads exactly as many elements as each rank's shards hold. Training runs agree too. `scripts/loss_compare.py` (seed 42, deterministic, 50 steps, 2 GB200 GPUs) ran the Llama 3 debug model loading, with `initial_load_in_hf`, a float32 Hugging Face checkpoint that FSDP2 exported after 10 steps. With FSDP2 as the baseline and FlexShard as the test, both at this PR, `--assert-equal --metrics loss,grad_norm` reports equal loss and grad norm at every step (step-1 loss 3.99885, against 8.11912 without the load; step-50 loss 2.81281). The runs use flex attention because the environment has no FA4, and skip the seed checkpoint, since the load sets the parameters. The CPU test `test_flex_shard_rejects_checkpointers_that_drop_shard_layouts` now accepts `initial_load_in_hf` for the Llama 3 debug model. FSDP2's Hugging Face load runs the new check, which is false for its DTensors, and then today's code. No other FSDP2 code changes. In both new tests, FSDP2's load gives exactly the exported parameters, and `scripts/loss_compare.py 49bc1817f <this PR>` with the FSDP2 run above reports equal loss and grad norm at every step. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 151502c Pull-Request: #6013
|
@claude review this pr |
|
Claude finished @anshul-si's task in 3m 24s —— View job Request changes: the PR description documents a different implementation from the code at HEAD. Review |
There was a problem hiding this comment.
Verdict: Request changes -- The description documents a different implementation from the code at HEAD (7815210), so a maintainer can't check the design or the numerics claims against what would land.
What this PR does (at HEAD). For FlexShard runs, the HF branch of CheckpointManager._load_checkpoint (dcp.py:401-410) calls a new load_hf_into_local_shards. For each parameter, that function runs to_hf on an arange probe to learn which parameter row each HF row holds. It then gives each HF tensor a chunk layout (CheckpointableTensor) covering only this rank's rows, and dcp.load fills either a view of the local shard or a buffer that is then index_copy_'d into the shard. Validation allows initial_load_in_hf, but only with the Llama 3 and Qwen3 adapters.
Example. dp_shard=2 with the Llama 3 debug model: rank 0's w13 shard is [2, 384, 256]. The probe maps HF gate_proj rows 0..383 to local rows 0..383 and up_proj rows 0..383 to local rows 384..767. Each becomes a view with chunk global_offsets=(0, 0), local_sizes=(384, 256) in the [768, 256] HF tensor, so the load fills the parameter in place. Before this PR the config raised ValueError.
Must fix
- The PR description doesn't match the code. It describes
as_fsdp2_state_dict/from_fsdp2_state_dict/_flex_shard_params(remove_duplicate=False) built on #5842'sas_fsdp2_dtensor, plus a redistribute and HF loads folded intotest_checkpoints_across_backends*. None of these exist at HEAD;as_fsdp2_dtensorisn't in the tree. The code instead adds the probe-based loader, an adapter allowlist, newtest_hf_loads_match_fsdp2*tests and a CPUtest_hf_load_into_uneven_shards. The "Alternatives", "Numerics" and "Testing" sections, including the revert table, therefore describe code reviewers can't see. Please push the intended revision or rewrite the description. The human-written summary is also empty. torchtitan/distributed/flex_shard_fsdp.py:262: whichever design lands, it needs a decision and aTODOwith the flex_shard issue link (inline).torchtitan/distributed/flex_shard_fsdp.py:584-590: a model-specific adapter allowlist intorchtitan/distributed/(inline).
Should consider
torchtitan/distributed/flex_shard_fsdp.py:405-426: the column-split (TP) path has no consumer because TP is rejected; delete it (inline).tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:573: a CPU-only test sits in the multi-GPU suite, and itstp=2case covers an unsupported configuration (inline).tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:431: two new multi-GPU tests where the description says the coverage was folded into the existing tests (inline).
Questions
- Which design is meant to land: the DTensor views or the row probe? If it's the probe, why was the view approach dropped, given that the view approach runs the adapters' FSDP2 path unchanged?
Details
- I traced
_hf_local_tensorsby hand for the Llama 3 fused QKV, the q/k permute, thew13split and the Qwen3 per-expert split, including the case with multiple regions per shard. The view path's chunk offsets and the buffer path'sindex_copy_targets look consistent. The checks for "row loaded twice", "row missing" and "last dim changed" raiseValueError. - The probe can't see transforms that act on values rather than indices. FlexShard keys also skip
from_hfentirely. That's presumably why the allowlist exists, but the code doesn't say so. from_quantizedis ignored on the FlexShard branch ofdcp.py. This is fine only because validation rejectsinitial_load_in_hf_quantized.- The model is fully trusted to be untied, since tied models are rejected elsewhere in validation.
Not verified: the GPU parity tests and the loss_compare numbers (no GPU here; they also refer to a revision that isn't pushed). A maintainer still needs to review, since this touches the core checkpointer.
| register_optimizer_checkpoint_hook(optimizer, model) | ||
|
|
||
|
|
||
| def load_hf_into_local_shards( |
There was a problem hiding this comment.
This is about 200 lines of index inference: run to_hf on an arange probe, recover the row permutation, then build chunk layouts plus a view or buffer per HF tensor. It's correct only while every adapter conversion is a pure row re-indexing whose inverse is from_hf. FlexShard keys never go through from_hf here. Two things to settle before line-level polish:
- The PR description says the load goes through
as_fsdp2_state_dict/from_fsdp2_state_dicton top of Add parallelism.storage to shard decoders with FlexShard #5842'sas_fsdp2_dtensor, so the adapters run unchanged. None of those symbols exist at HEAD. Which design is meant to land? The DTensor-view design reuses existing code paths and avoids this machinery. If it was dropped, the PR should say why. - Either way, this works around flex_shard's missing DTensor view and its inverse. Per CLAUDE.md principle 3 it needs a
TODOwith the flex_shard issue link. The description says one exists, but the diff has none.
| # load_hf_into_local_shards has been checked against FSDP2 for these | ||
| # adapters only. | ||
| adapter_cls = getattr(model_cls, "state_dict_adapter_cls", None) | ||
| if checkpointer.initial_load_in_hf and adapter_cls not in ( | ||
| Llama3StateDictAdapter, | ||
| Qwen3StateDictAdapter, | ||
| ): | ||
| name = getattr(adapter_cls, "__name__", "no state dict adapter") | ||
| unsupported.append(f"checkpointer.initial_load_in_hf=True with {name}") |
There was a problem hiding this comment.
This puts a model allowlist in torchtitan/distributed/, which now imports Llama3StateDictAdapter and Qwen3StateDictAdapter. That breaks the "keep shared code oblivious to specific models" rule. The exact-class not in check also rejects any subclass of these adapters.
_hf_local_tensors already raises ValueError when a conversion isn't a row re-indexing (last dim changed, rows in more than one dim, a row missing or duplicated). So the open question is which adapter transform the probe can't detect and the allowlist is there to catch. If there is one, name it in the comment. If not, drop the allowlist and rely on those checks. Note that the raise then happens at load time, not config time.
| num_rows = 0 | ||
| for starts, ends, index, global_offset, local_offset, size in blocks: | ||
| width = size[row_dims:] | ||
| local_columns = tuple( | ||
| slice(start, start + length) | ||
| for start, length in zip(local_offset[row_dims:], width) | ||
| ) | ||
| dest = local_rows[(slice(None), *local_columns)] | ||
| copies.append((dest, index, num_rows, width)) | ||
| for start, end in zip(starts, ends, strict=True): | ||
| global_offsets.append((start, *global_offset[row_dims:])) | ||
| local_offsets.append((num_rows, *(0 for _ in width))) | ||
| local_sizes.append((end - start, *width)) | ||
| num_rows += end - start | ||
| dest, index, _, _ = copies[0] | ||
| first = int(index[0]) | ||
| if len(copies) == 1 and torch.equal( | ||
| index, torch.arange(first, first + len(index)) | ||
| ): | ||
| tensor, copies = dest[first : first + len(index)], [] | ||
| else: | ||
| widest = tuple(map(max, zip(*(width for *_, width in copies)))) |
There was a problem hiding this comment.
The column-subset handling (local_columns, per-region width, widest, and the docstring and comments about shards that split the last dim "as tensor parallelism does") has no consumer. validate_flex_shard_training rejects tensor_parallel_degree != 1 (line 485). FlexShard's placement_fn (fsdp.py:558) only shards a non-last dim of multi-dim params: 0, or 1 for the stacked w13. So at HEAD every region spans all columns. Please delete this path, and the tp=2 test case that exercises it, until TP is allowed. That would make the function noticeably smaller and easier to check.
| @pytest.mark.parametrize("dp_shard, tp", [(5, 1), (5, 2)]) | ||
| def test_hf_load_into_uneven_shards(tmp_path, dp_shard: int, tp: int) -> None: |
There was a problem hiding this comment.
This test needs no GPU or process group, but the module-level pytestmark = pytest.mark.multi_gpu puts it in the multi-GPU job. Move it to a CPU suite such as tests/unit_tests/cpu/distributed/. The (5, 2) case simulates TP, which FlexShard rejects, so it tests a configuration nobody can run (see the comment on _hf_local_tensors). Keep only dp_shard=5, which covers the real shard-ends-inside-a-head case.
| for name, value in states[param].items() | ||
| } | ||
|
|
||
| def _check_hf_loads_match_fsdp2(self, build_config, flavor: str, *, ep: int): |
There was a problem hiding this comment.
This adds two new multi-GPU tests, and each trains an FSDP2 model and builds three models. The PR description instead says the HF load is folded into the existing test_checkpoints_across_backends and test_checkpoints_across_backends_with_expert_parallelism, reusing FSDP2's uninterrupted run as the export. Per .claude/rules/tests.md, folding it in is cheaper and preferred. The extra FSDP2 HF load here also only re-checks existing FSDP2 behavior. Please fold the coverage into the existing tests as described, or explain why it can't be.
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
|
@claude review this pr |
|
Claude finished @anshul-si's task in 3m 52s —— View job Request changes: HEAD loads full parameter tensors on every rank, a third design the PR description doesn't describe. Review |
There was a problem hiding this comment.
Verdict: Request changes -- HEAD (fe1298e) uses a third design, which the description doesn't describe. That design has every rank materialize and read each parameter's full tensor, which doesn't scale to the large models HF loads are for.
What this PR does (at HEAD). For FlexShard, the HF branch of _load_checkpoint (dcp.py:403-410) calls load_hf_into_local_shards. That function groups the parameters into groups of at most 1 GiB; a larger parameter gets a group of its own. For each group it:
- allocates the full tensors, passing meta tensors for all other keys;
- runs
to_hf, thendcp.loadon the non-meta HF tensors, thenfrom_hf; - copies each shard's regions out of the full tensors.
Keys with no HF tensor of their own, such as a tied lm_head, are accepted when they share storage with a loaded shard. Validation allows initial_load_in_hf and now rejects initial_load_in_hf_quantized by name.
Example. Llama 3 debug model, dp_shard=2, initial_load_in_hf=True:
Before: ValueError: ... does not support checkpointer.initial_load_in_hf=True yet.
After: each rank allocates w13's full [2, 768, 256] tensor, loads gate_proj and up_proj
into it, from_hf rebuilds it, and the rank copies its rows [:, 0:384] (or
[:, 384:768]) into its [2, 384, 256] shard.
Must fix
-
The description still doesn't match the code. This was raised in the last review and is still open, and the code has changed design again. The description describes
as_fsdp2_state_dict/from_fsdp2_state_dict/_flex_shard_params, none of which exist. It also makes these claims:- "the load allocates nothing FSDP2's doesn't" -- this is false at HEAD.
- "Tied models stay rejected" -- HEAD adds
test_hf_loads_match_fsdp2_with_tied_weights. - "HF loads folded into
test_checkpoints_across_backends*" -- HEAD instead adds three new multi-GPU tests plus a CPU test. - It rejects "all-gather full tensors before
to_hf" as an alternative, and HEAD does a per-parameter version of exactly that.
The numerics come from an older revision. The human-written summary is empty.
-
torchtitan/distributed/flex_shard_fsdp.py:325-333-- per-rank memory and reads both scale with the full parameter, not the shard (inline). Settle which design lands before line-level polish.
Should consider (still open from the last review)
tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:625--test_hf_load_into_uneven_shardsneeds no GPU or process group, but the module'spytestmark = pytest.mark.multi_gpuputs it in the multi-GPU job. Move it totests/unit_tests/cpu/distributed/.tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:467-578-- three new multi-GPU tests. Each one trains FSDP2, exports, and builds two more models. Folding the export and load into the existingtest_checkpoints_across_backends*runs, as the description says was done, would save that cost (.claude/rules/tests.md).
Questions
- This PR has gone through three designs: DTensor views, the row probe, and now full tensors per group. Which one is meant to land, and why were the two that read only local regions dropped?
Details
- Resolved since the last review: the model-specific adapter allowlist and the unused TP column-split path are gone.
- The grouping is deterministic across ranks:
ownand the group sizes depend only on keys, global shapes and dtypes. So every rank issues the same number of collectivedcp.loadcalls. - A conversion that spans two titan keys fails with
ValueErrorwhenever the 1 GiB boundary splits them, so whether such a model loads depends on its size. No in-repo adapter I checked (Llama 3, Qwen3 MoE) does this, and the_HF_LOAD_GROUP_BYTES=1patch in the GPU tests guards it for those. CheckpointableTensoris a protocol on layout attributes that DTensors don't carry. So FSDP2 keeps the old branch, which is consistent with the claim that FSDP2's numerics are unchanged.- The memory estimate for Qwen3 235B-A22B (dim 4096, 128 experts,
moe_hidden_dim=1536, 94 layers) assumes fp32 params and an HF checkpoint stored in bf16.
Not verified: the GPU parity tests and the loss_compare numbers (no GPU here; they also come from an earlier revision). A maintainer still needs to review, since this touches the core checkpointer.
| for group in groups: | ||
| hf_state_dict = sd_adapter.to_hf( | ||
| meta | {key: shards[key][0].new_empty(meta[key].shape) for key in group} | ||
| ) | ||
| dcp.load( | ||
| {k: v for k, v in hf_state_dict.items() if not v.is_meta}, | ||
| storage_reader=storage_reader, | ||
| ) | ||
| full = sd_adapter.from_hf(hf_state_dict) |
There was a problem hiding this comment.
Every rank allocates each parameter's full tensor on the accelerator (new_empty) and reads it whole from storage. from_hf usually allocates a second full copy on top, e.g. the MoE adapter's torch.stack (moe/state_dict_adapter.py:392). _HF_LOAD_GROUP_BYTES doesn't bound any of this for a parameter bigger than 1 GiB, because such a parameter forms a group of its own.
Concrete case: Qwen3 235B-A22B, the model this load exists for (fine-tuning from HF). Each layer's routed w13 is [128, 2*1536, 4096], which is 6.4 GB in fp32. So each rank holds about 13 GB of transient memory per expert param, on top of its shards. Each rank also reads the whole checkpoint, roughly 470 GB in bf16. On 256 ranks that is about 120 TB of reads, where FSDP2 reads about 470 GB in total.
FSDP2's path avoids exactly this: it reads only local experts via _get_local_experts_weights, and the adapter's docstring at moe/state_dict_adapter.py:351 warns that full-tensor conversion online OOMs. The PR description also lists "all-gather full tensors... every rank would hold the full model" as a rejected alternative, and this design is a per-parameter version of that.
The TODO above covers the read amplification but not the memory. Either restore a design that reads only each rank's region (the DTensor-view approach in the description, or the previous probe-based one), or state the per-rank peak and read volume in the PR and get a maintainer's OK. The 1 << 30 constant also needs a reason for its value.
[ghstack-poisoned]
|
@claude review this pr |
|
Claude finished @anshul-si's task in 3m 16s —— View job Needs discussion: the description now matches the code; what's left is a maintainer call on the load cost (full-model broadcast to every rank, reads that run one rank at a time). Review |
There was a problem hiding this comment.
Verdict: Needs discussion -- The description now matches the code. What's left is a maintainer call on the cost: every rank receives the whole model, the reads run one rank at a time, and each rank briefly holds full copies of the largest parameter. All of this is in the core checkpointer's HF load path.
What this PR does. In a FlexShard run, the HF branch of _load_checkpoint (dcp.py:401-410) calls load_hf_into_local_shards when any state dict entry is a CheckpointableTensor. That function groups the parameters into groups of at most 1 GiB, and a larger parameter forms a group of its own. Each group is handled by one reader rank, in turn:
- the reader runs
to_hfon full tensors, with meta tensors for every other key; - it reads them with
dcp.load(no_dist=True)and runsfrom_hf; - it broadcasts the full tensors over the world group, sending a tied weight once;
- every rank copies its regions into its shards.
Buffers load last, read by rank 0. FSDP2's DTensors fail the CheckpointableTensor check, so FSDP2 keeps today's path.
Example. Llama 3 debug model, dp_shard=2, initial_load_in_hf=True:
Before: ValueError: ... does not support checkpointer.initial_load_in_hf=True yet
After: group 0 (all params, < 1 GiB) -> rank 0: to_hf -> dcp.load -> from_hf
-> broadcast w13 [2, 768, 256] etc.; rank 0 copies [:, 0:384], rank 1 [:, 384:768]
Must fix
- The "Summary (human-written)" section is still empty. The author needs to write it. The rest of the description now matches HEAD (
265f119).
Should consider
torchtitan/distributed/flex_shard_fsdp.py:328-- the reads are serialized across ranks, so load time doesn't shrink as ranks are added. Read in waves, or report the wall time in Cost. The 1 GiB constant also needs a reason (inline).torchtitan/distributed/flex_shard_fsdp.py:311-- "every rank holds the same keys" and the world-group broadcasts hold only because PP is rejected. Say so (inline).- Still open from the last review:
test_hf_loads_match_fsdp2*(tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:468-591) add two multi-GPU tests. Each one trains FSDP2 and builds two models. Folding the export into the existingtest_checkpoints_across_backends*runs would save that (.claude/rules/tests.md). If they can't be folded, the description should say why.
Questions
- For maintainers: is this cost acceptable for the HF load path? Every rank receives the whole model (
epx for routed experts), and each rank briefly holds the largest parameter in full, which is a few times 6.4 GB for Qwen3 235B's routedw13in fp32. Or should the "send each rank only its regions" TODO land before this?
Details
- Resolved since the last review:
- The description now matches the code.
- Reads are no longer per-rank: each HF tensor is read once.
- The CPU test with its TP case is gone.
- The memory cost is now stated.
- Rank consistency:
- Groups depend only on keys and global shapes, in
state_dictorder. - The reader broadcasts the keys, shapes and dtypes it got back, and the aliases. So every rank enters the same broadcasts.
- A failing reader broadcasts
None, and the other ranks raiseRuntimeError. - The
missingcheck runs on broadcast keys, so it raises on every rank alike.
- Groups depend only on keys and global shapes, in
- Tied weights: Llama 3's
from_hfsetshf_state_dict["lm_head.weight"] = hf_state_dict["model.embed_tokens.weight"](llama3/state_dict_adapter.py:131). Theid()alias therefore catches it.- In
lm_head's own group,to_hfdrops it, andfrom_hfreturns a meta tensor, which is skipped. - The cost is an unused full
new_emptyforlm_headon that group's reader.
- In
- A conversion that mixes a real tensor with a meta one from another group (e.g.
torch.cat) fails on the reader and is reported to every rank. The_HF_LOAD_GROUP_BYTES=1cases in the tests exercise this for Llama 3 (tied) and Qwen3 MoE. - Quantized loads: the
from_quantizedreader is never built on this branch, which is safe only because validation now rejectsinitial_load_in_hf_quantized.
Not verified: the GPU parity tests and any load-time numbers (no GPU here). A maintainer still needs to review, since this touches the core checkpointer.
| for i, group in enumerate(groups): | ||
| reader = i % world_size |
There was a problem hiding this comment.
The reads are fully serialized. Group i is read by rank i % world_size, and every other rank sits in broadcast_object_list until that read and its broadcasts finish. Rank i + 1 doesn't start reading group i + 1 until then. So the checkpoint is read once in total, but by one process at a time. FSDP2 reads with every rank in parallel.
The Cost table compares bytes read and network traffic, but not wall time. For Qwen3 235B-A22B (about 470 GB in bf16), the whole load is one process's sequential read throughput (the HF reader defaults to 2 threads) plus the broadcasts. That's minutes of idle GPUs at startup, and it doesn't shrink as you add ranks. Unverified: I have no measured numbers.
A small fix that keeps one reader per group is to read in waves. Each rank r reads group w * world_size + r at the same time as the others. Then the wave's world_size broadcasts run in order, and each rank copies out its regions and frees each received group. Peak memory becomes one group read plus one group received, and the read time divides by world_size. If you keep the serial loop, please add the measured load time to the Cost section, so a maintainer can weigh it.
Separately, _HF_LOAD_GROUP_BYTES = 1 << 30 (line 273) still has no reason for its value (.claude/rules/config.md: no magic numbers without a comment).
| # Every rank holds the same keys, and the groups depend only on the keys and | ||
| # full shapes, so every rank loads as often. |
There was a problem hiding this comment.
"Every rank holds the same keys" is true only because validate_flex_shard_training rejects PP. _read_and_broadcast also broadcasts over the default (world) group. With PP, each stage has different keys, so the ranks would build different groups and hang in mismatched broadcasts. Please say so in this comment, e.g. "(PP is rejected; with PP each stage holds different keys, so groups and broadcasts would need to be per stage)". Then the PP PR that lifts the rejection finds it, rather than learning about it from a hang.
Stack from ghstack (oldest at bottom):
Stacked on #5842, the expert-parallelism PR, the chunked-loss PR and the checkpointing PR.
Summary (human-written)
Description
The checkpointing PR rejects
checkpointer.initial_load_in_hfwithparallelism.storage=FlexShardConfig(), so a FlexShard run can't startfrom a Hugging Face checkpoint, which is how fine-tuning and continued pretraining
start. Lifting the rejection alone fails the load. The state dict adapters'
to_hfandfrom_hfconvert full tensors and FSDP2's DTensors, which carry each shard's place inthe full tensor through their splits, permutations and slices, but they take each of
FlexShard's plain local shards for the whole tensor. The layouts that the checkpointing
PR declares on the state dict's tensors (DCP's
CheckpointableTensor) don't help: thenew tensors
to_hfmakes from them (a split stacked linear, a permuted query weight,one expert's slice) have none. On 2 GPUs, the Llama 3 debug model's load fails with
DCP's size mismatch, saved
[768, 256]against current[384, 256], formodel.layers.0.mlp.gate_proj.weight. As in #5842, nothing on the FlexShard pathcreates a DTensor.
The new
load_hf_into_local_shards(inflex_shard_backend.py) loads the parameters asfull tensors, a group at a time, through the adapters' conversions of full tensors, the
ones single-device runs and
convert_from_hf.pyuse, and each shard keeps its regionsof its full tensor:
takes more. One rank reads each group, in turn:
to_hfruns on new full tensors,dcp.loadwith the adapter's Hugging Face reader fills them on that rank alone(
no_dist=True), andfrom_hfconverts them back. The reader broadcasts the fulltensors, a tied weight once, and each rank copies its regions from them, by the layout
flex_shard reports.
the other keys, meta tensors of the same shapes, which hold no data. Adapters that
expect the whole state dict work unchanged: with tied weights, Llama 3's
from_hfasserts that the embedding is among its tensors.
from_hfgives back as a real tensor keeps its regions, also onethat comes from another key's Hugging Face tensors: with tied weights,
to_hfgivesno tensor for
lm_head.weight, andfrom_hfgives it back as the embedding, intok_embeddings' group. A shard that no group gives back raises.broadcasts which tensors it got back, so every rank takes part in the same broadcasts
and raises alike. A reader that fails tells the other ranks, which raise too instead
of waiting in a broadcast.
with every key, as for FSDP2, read by rank 0 and broadcast.
CheckpointManager._load_checkpointcalls the function when an entry of the modelstate dict declares a layout, which only FlexShard's do: DTensors and plain tensors
aren't
CheckpointableTensors.The checkpoint is read once, as by FSDP2, since one rank reads each group. The cost
moves to the network: every rank receives each group's full tensors, so the whole model
once. Without EP and TP, that is on the order of one training step's all-gathers. With
EP, every rank receives all experts, where a step gathers only its EP rank's, so about
eptimes that for the routed experts; the tensor-parallelism PR's TP-split weightslikewise take about
tptimes. FSDP2 reads and receives only each rank's part, exceptfor the query, key and value weights, which its adapters redistribute to
Replicate()(
_split_qkv_linear,dtensor_safe). Memory holds one group's full tensors, at most1 GiB or the largest parameter, and the copies the conversions make of them, a few times
that, much as FlexShard's initialization (
init_from_full) holds one full parameter ata time. A TODO notes what's left: sending each rank only its regions instead of the full
tensors.
Alternatives:
of this PR used (
as_fsdp2_dtensor): Add parallelism.storage to shard decoders with FlexShard #5842 removed them, so that FlexShard creates noDTensors.
to_hfrun on a tensor of row indices, which rows of each Hugging Facetensor each shard holds, and read only those, which the previous revision did. It
reads only each rank's part, but it took about 200 lines, worked only for conversions
that move rows, skipped
from_hffor the shards, and so needed an allowlist ofadapters.
convert_from_hf.pyand load the result throughinitial_load_path: an extra step, with the whole model in one process's memory.FlexShardConfig.validate_trainerallowsinitial_load_in_hfwith any state dictadapter, since the load uses each adapter's own conversions of full tensors. Validation
now rejects
initial_load_in_hf_quantizedby name, which it rejected throughinitial_load_in_hfbefore, and still rejectslast_save_in_hf.The parity test file gains
test_hf_loads_match_fsdp2, on the Llama 3 debug model andon the Llama 3 debug model with tied weights, set up as the tied Llama 3 flavors do, and
test_hf_loads_match_fsdp2_with_expert_parallelism, on the Qwen3 MoE debug model withep=2. For each model, FSDP2 trains three steps and exports a Hugging Face checkpoint(
last_save_in_hf, float32), and a fresh FlexShard model, from its own initialization,loads it with
initial_load_in_hf. Each FlexShard shard must equal its slice of FSDP2'sparameters, by the layouts flex_shard reports, and each Hugging Face tensor must be read
by one rank only (each rank's
dcp.loadcalls, gathered). The ranks gather theirmismatches before they assert, so that none waits in the next case's collectives.
Training from equal parameters is
test_matches_fsdp2's check. That covers the packedQKV split, the rotary permutation, the stacked
w13, the tied weight, and EP's split ofthe experts. The plain Llama 3 model loads in one group, the default. The tied and Qwen3
models load each parameter as a group of its own, so a conversion that needs another key
fails, as it would across the groups of a larger model (each debug model fits in one
group). With each conversion given only its group's keys, the tied case fails in Llama
3's
from_hf. With every rank reading every group, the Llama 3 test fails on the reads;with the reader's broadcasts left out, on the other rank's shards. In CI the tests run
on 4 GPUs, where
ep=2leavesedp_shard=2. They pass on 2 GB200 GPUs withworld_sizeset to 2.The CPU test
test_flex_shard_rejects_checkpointers_that_drop_shard_layoutsnowaccepts
initial_load_in_hffor the Llama 3 debug model.FSDP2's Hugging Face load runs the new check, which is false for its DTensors, and then
today's code. No other FSDP2 code changes.
Co-authored-by: Wei Feng [email protected]