Skip to content

Support Hugging Face checkpoint loads with parallelism.storage=FlexShardConfig() - #6013

Open
anshul-si wants to merge 11 commits into
gh/anshul-si/24/basefrom
gh/anshul-si/24/head
Open

anshul-si wants to merge 11 commits into
gh/anshul-si/24/basefrom
gh/anshul-si/24/head

Conversation

@anshul-si

@anshul-si anshul-si commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

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_hf with
parallelism.storage=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 full tensors and FSDP2's DTensors, which carry each shard's place in
the 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: 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. As in #5842, nothing on the FlexShard path
creates a DTensor.

The new load_hf_into_local_shards (in flex_shard_backend.py) loads the parameters as
full tensors, a group at a time, through the adapters' conversions of full tensors, the
ones single-device runs and convert_from_hf.py use, and each shard keeps its regions
of its full tensor:

  • A group holds parameters whose full tensors take at most 1 GiB, or one parameter that
    takes more. One rank reads each group, in turn: to_hf runs on new full tensors,
    dcp.load with the adapter's Hugging Face reader fills them on that rank alone
    (no_dist=True), and from_hf converts them back. The reader broadcasts the full
    tensors, a tied weight once, and each rank copies its regions from them, by the layout
    flex_shard reports.
  • Each conversion sees every key, as in a full load: the group's full tensors and, for
    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_hf
    asserts that the embedding is among its tensors.
  • Every shard that from_hf gives back as a real tensor keeps its regions, also one
    that comes from another key's Hugging Face tensors: with tied weights, to_hf gives
    no tensor for lm_head.weight, and from_hf gives it back as the embedding, in
    tok_embeddings' group. A shard that no group gives back raises.
  • The groups and their readers depend only on the keys and full shapes, and each reader
    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.
  • Entries without a layout, such as buffers, load last, through the same conversions
    with every key, as for FSDP2, read by rank 0 and broadcast.
    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 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
ep times that for the routed experts; the tensor-parallelism PR's TP-split weights
likewise take about tp times. FSDP2 reads and receives only each rank's part, except
for 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 most
1 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 at
a time. A TODO notes what's left: sending each rank only its regions instead of the full
tensors.

Alternatives:

  • DTensor views of FlexShard's shards around the conversions, which an earlier revision
    of this PR used (as_fsdp2_dtensor): Add parallelism.storage to shard decoders with FlexShard #5842 removed them, so that FlexShard creates no
    DTensors.
  • Infer, from to_hf run on a tensor of row indices, which rows of each Hugging Face
    tensor 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_hf for the shards, and so needed an allowlist of
    adapters.
  • Load the whole model as full tensors at once: every rank holds the whole model.
  • Convert offline with convert_from_hf.py and load the result through
    initial_load_path: an extra step, with the whole model in one process's memory.

FlexShardConfig.validate_trainer allows initial_load_in_hf with any state dict
adapter, since the load uses each adapter's own conversions of full tensors. 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.

The parity test file gains test_hf_loads_match_fsdp2, on the Llama 3 debug model and
on 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 with
ep=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's
parameters, by the layouts flex_shard reports, and each Hugging Face tensor must be read
by one rank only (each rank's dcp.load calls, gathered). The ranks gather their
mismatches 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 packed
QKV split, the rotary permutation, the stacked w13, the tied weight, and EP's split of
the 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=2 leaves edp_shard=2. They pass on 2 GB200 GPUs with
world_size set to 2.

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.

Co-authored-by: Wei Feng [email protected]

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
anshul-si added a commit that referenced this pull request Nov 16, 2026
…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
[ghstack-poisoned]
@anshul-si

Copy link
Copy Markdown
Contributor Author

@claude review this pr

@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. 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's as_fsdp2_dtensor, plus a redistribute and HF loads folded into test_checkpoints_across_backends*. None of these exist at HEAD; as_fsdp2_dtensor isn't in the tree. The code instead adds the probe-based loader, an adapter allowlist, new test_hf_loads_match_fsdp2* tests and a CPU test_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.
  2. torchtitan/distributed/flex_shard_fsdp.py:262: whichever design lands, it needs a decision and a TODO with the flex_shard issue link (inline).
  3. torchtitan/distributed/flex_shard_fsdp.py:584-590: a model-specific adapter allowlist in torchtitan/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 its tp=2 case 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_tensors by hand for the Llama 3 fused QKV, the q/k permute, the w13 split and the Qwen3 per-expert split, including the case with multiple regions per shard. The view path's chunk offsets and the buffer path's index_copy_ targets look consistent. The checks for "row loaded twice", "row missing" and "last dim changed" raise ValueError.
  • The probe can't see transforms that act on values rather than indices. FlexShard keys also skip from_hf entirely. That's presumably why the allowlist exists, but the code doesn't say so.
  • from_quantized is ignored on the FlexShard branch of dcp.py. This is fine only because validation rejects initial_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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. The PR description says the load goes through as_fsdp2_state_dict / from_fsdp2_state_dict on top of Add parallelism.storage to shard decoders with FlexShard #5842's as_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.
  2. Either way, this works around flex_shard's missing DTensor view and its inverse. Per CLAUDE.md principle 3 it needs a TODO with the flex_shard issue link. The description says one exists, but the diff has none.

Comment on lines +582 to +590
# 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}")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +405 to +426
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))))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +573 to +574
@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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]
@anshul-si

Copy link
Copy Markdown
Contributor Author

@claude review this pr

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, then dcp.load on the non-meta HF tensors, then from_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

  1. 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.

  2. 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_shards needs no GPU or process group, but the module's pytestmark = pytest.mark.multi_gpu puts it in the multi-GPU job. Move it to tests/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 existing test_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: own and the group sizes depend only on keys, global shapes and dtypes. So every rank issues the same number of collective dcp.load calls.
  • A conversion that spans two titan keys fails with ValueError whenever 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=1 patch in the GPU tests guards it for those.
  • CheckpointableTensor is 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.

Comment on lines +325 to +333
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]
@anshul-si

Copy link
Copy Markdown
Contributor Author

@claude review this pr

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_hf on full tensors, with meta tensors for every other key;
  • it reads them with dcp.load(no_dist=True) and runs from_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

  1. 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 existing test_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 routed w13 in 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_dict order.
    • 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 raise RuntimeError.
    • The missing check runs on broadcast keys, so it raises on every rank alike.
  • Tied weights: Llama 3's from_hf sets hf_state_dict["lm_head.weight"] = hf_state_dict["model.embed_tokens.weight"] (llama3/state_dict_adapter.py:131). The id() alias therefore catches it.
    • In lm_head's own group, to_hf drops it, and from_hf returns a meta tensor, which is skipped.
    • The cost is an unused full new_empty for lm_head on that group's reader.
  • 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=1 cases in the tests exercise this for Llama 3 (tied) and Qwen3 MoE.
  • Quantized loads: the from_quantized reader is never built on this branch, which is safe only because validation now rejects initial_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.

Comment on lines +328 to +329
for i, group in enumerate(groups):
reader = i % world_size

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment on lines +311 to +312
# Every rank holds the same keys, and the groups depend only on the keys and
# full shapes, so every rank loads as often.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"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.

@anshul-si
anshul-si marked this pull request as ready for review November 19, 2026 05:25
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 19, 2026
@github-actions
github-actions Bot requested a review from ivy-zhou November 19, 2026 05:26
[ghstack-poisoned]
@anshul-si anshul-si changed the title Support Hugging Face checkpoint loads with parallelism.fsdp_backend=FlexShardConfig() Support Hugging Face checkpoint loads with parallelism.fsdp_backend=FlexShardBackend.Config() Nov 25, 2026
[ghstack-poisoned]
@anshul-si anshul-si changed the title Support Hugging Face checkpoint loads with parallelism.fsdp_backend=FlexShardBackend.Config() Support Hugging Face checkpoint loads with parallelism.storage=FlexShardConfig() Nov 30, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant