Skip to content

Context parallel: compose with FSDP2 on a (dp_shard, cp) mesh - #13910

Merged
danielhanchen merged 103 commits into
mainfrom
dh/cp-fsdp2
Oct 16, 2026
Merged

danielhanchen merged 103 commits into
mainfrom
dh/cp-fsdp2

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Stacked on #13848 (Ulysses context parallel, which stacks on #4257). Depends on #13865 (FSDP2 core), which is merged into this branch; the change itself is commit 39d648e.

Context parallelism was DDP only: an FSDP2 launch with context_parallel_size > 1 was refused. This lets the two compose the way torchtitan does. The world is laid out as a (dp_shard, cp) mesh, FSDP2 shards parameters over dp_shard x cp flattened (accelerate's dp_shard_cp), and the sequence split plus the ring or Ulysses collectives stay on the cp submesh. CP peers hold different tokens of the same rows, so their gradients are reduced together with the data parallel ones, and the existing token count normalisation (pre-shard count divided by the CP size, loss scaled by the world size) stays exact because FSDP2 averages over the same D x N ranks DDP did.

Usage is unchanged: SFTConfig(context_parallel_size = N) under an FSDP2 launch (UNSLOTH_FSDP2=1 torchrun ..., or an accelerate FSDP2 config); dp_shard is world size / N.

accelerate's own ParallelismConfig(cp_size = N) is still refused. With cp_size > 1 accelerate attaches torch's context_parallel SDPA hooks in prepare(), transformers wraps each step in maybe_context_parallel and divides num_items_in_batch by the CP size, all of which Unsloth already does itself. Instead Unsloth installs a ParallelismConfig with dp_shard_size = D x N and cp_size = 1 next to its own mesh, so fsdp2_prepare_model shards over mesh["dp_shard_cp"] and the data loader gives CP peers the same batch (both read the same way since accelerate 1.10, the CP minimum).

FSDP1, DeepSpeed and a ParallelismConfig with dp_replicate, tp or sp above 1 are refused on every rank before any collective.

Tests

  • tests/test_context_parallel.py: FSDP2 accepted, mesh and config installed and restored by a later trainer, FSDP1 and extra dimensions refused.
  • tests/test_context_parallel_fsdp2_gloo.py: four gloo ranks on CPU, (dp_shard 2, cp 2). Mesh layout, accelerate's real data loader and fsdp2_prepare_model, and one patched training step through FSDP2 matching an unsharded model's gradients.
  • GPU accuracy on a tiny Llama with LoRA (3 steps, first-step gradients): (dp_shard, cp) = (1, 2) ring and Ulysses, fp32 and bf16, gradient accumulation 2, (2, 1) and (2, 2) ring and Ulysses on four GPUs all match the single GPU run (loss rel err <= 2.5e-5, min grad cosine >= 0.99988). Removing the count division moves loss and gradients by exactly 0.5, so the check can fail.

Not covered: HSDP or TP with CP, packing / FA3 / FA4 / 4-bit bases under FSDP2 + CP, multi-node, timing.

djsaunde and others added 30 commits March 12, 2026 23:10
Resolve conflicts against main (trainer patching moved to _gpu_init, CLI
_build_sft_config, packing gate, attention dispatch, CausalLM loss block).

Rework the context parallel path:
- RoPE uses the sharded global position_ids with main's fast_rope_embedding
  (drops the slice helper that raised on per-row position_ids and the
  per-layer .item() host sync); only the rope cache length scales by CP size.
- compute_loss divides the trainer's pre-shard num_items_in_batch by the CP
  size and delegates to the stock path, keeping GA-exact normalisation and
  HF's own cross-rank loss logging (replaces the custom loss all-reduce).
- Drop the custom train sampler: accelerate already gives CP ranks the same
  batch from the dp_replicate x cp mesh, and the extra DistributedSampler
  double-sharded data once dp > 1. Drop shuffle_dataset / pad_to_multiple_of
  (CP pads to 2 x size internally).
- Reset the active manager in finally; attention hook only drops the mask
  inside a CP step; reject world sizes not divisible by the CP size and
  models whose attention is not the Llama forward.
- Resolve SDPA per call so context_parallel's monkey patch is seen.
- Add tests/test_context_parallel.py.
HF find_labels treats every forward parameter containing 'label' as a
required label, so a named shift_labels made eval batches look label-less
and Unsloth's prediction_step fell into the prompt-only branch
(KeyError: 'prompt').
Without a flash kernel (T4, fp32) SDPA with enable_gqa=True falls back to
the math backend, which ring attention cannot shard (aten.add got mixed
torch.Tensor and DTensor). Expand K/V while CP is active so flash or
memory-efficient attention is used.
Training counts tokens before sharding, eval counts them after, so dividing
in compute_loss inflated eval loss by the CP size.
torch's ring attention fails in backward on sm75 (2x T4, torch 2.10, pure
torch probe without Unsloth), so fail at trainer init with a clear message.
…sses

- DeviceMesh is SPMD: build the (dp_replicate, cp) mesh on every rank and
  take its cp submesh, instead of per-group meshes that hang once
  world_size > context_parallel_size.
- Under CP, predictions come back as per-rank sequence shards; allow
  loss-only evaluation and refuse compute_metrics / predict().
- label_smoothing_factor and compute_loss_func drop labels before the
  model and recompute loss from sharded labels; refuse them under CP.
TRL chunked_nll calls the backbone directly, so it never sees the
pre-shifted labels and re-shifts the sharded ones.
…lism

accelerate before 1.10.0 ignores the cp mesh dim when sharding data, so CP
peers would ring-attend over different examples. The attention hook drops
the mask, which is only safe for right padding.
DoRA promotes Q/K/V to fp32, which keeps ring SDPA off the flash kernel;
reuse the flash downcast (#1013) while CP is active. Higher-rank masks
would be sharded on the wrong dim and then dropped.
accelerate's DeepSpeed data loader ignores the cp mesh dim and shards across
every rank, and FSDP2 needs a parallelism_config alongside the mesh.
accelerate's DataLoaderDispatcher (default for iterable datasets) slices by
world rank and ignores the cp dim. AcceleratorState is process-wide, so a
later non-CP trainer must not inherit the CP mesh.
# Conflicts:
#	unsloth/models/llama.py
# Conflicts:
#	unsloth/models/llama.py
…ft unset

A PEFT model is not a PreTrainedModel, so the Trainer asks DDP for find_unused_parameters,
which fails with Unsloth's reentrant gradient checkpointing (Expected to mark a variable
ready only once). An explicit user value is kept.
…d_unused on transformers 4.x too

On CUDA, autograd runs backward (and so Unsloth's reentrant checkpoint recompute) on its own
device thread, where a ContextVar set on the training thread reads as unset: the recompute then
picked flash attention / xformers over the local shard only. A module global is visible there.
transformers 4.x rebuilds the DDP handler from ddp_find_unused_parameters when it wraps the model,
so set the argument as well as the handler.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7e64a18503

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +437 to +439
has_total_train_batch_size = hasattr(trainer_cls, "get_total_train_batch_size")
if has_total_train_batch_size:
original_get_total_train_batch_size = _original("get_total_train_batch_size")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Handle batch accounting when Trainer lacks the helper

When running a supported Transformers 4.x release (the project permits transformers>=4.52.4), Trainer has no get_total_train_batch_size method, so this guard skips the correction and the older inline calculation still multiplies by all D × N ranks. Consequently, FSDP2+CP max-step runs continue to overreport num_train_samples, total batch size, and throughput by the CP factor. Fresh evidence beyond the earlier comment is that the fix only covers newer Trainer versions exposing this helper; the supported fallback path needs equivalent adjustment.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Leaving this one. On transformers 4.x the inline calculation only feeds logged numbers (num_train_samples, total batch size, throughput); the optimizer step count and the number of items each step trains on come from the dataloader and are unaffected. Patching that inline block in old Trainer source for a logging figure on FSDP2 + CP (itself a new combination) is not worth the drift risk.

Comment thread unsloth/fsdp2_launch.py
Comment on lines +70 to +71
if not unsloth_fsdp2_requested() or _env_world_size() <= 1:
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Validate ordinary Accelerate FSDP2 launches

When FSDP2 is selected through a normal accelerate launch configuration, UNSLOTH_FSDP2 is unset and this returns before _accelerate_fsdp2_support() runs. That leaves Accelerate 1.6—which is allowed by the project's accelerate>=0.34.1 dependency—on the known PEFT FULL_STATE_DICT path where rank 0 saves only its local DTensor shards; the later backport cannot install because that release lacks the state-dict option APIs. Apply the compatibility check to any detected FSDP2 launch, not only the custom torchrun opt-in, so resumable checkpoints cannot be silently corrupted.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not introduced here. A plain accelerate launch with FSDP2 on accelerate 1.6 saves the same per-rank FULL_STATE_DICT shards with or without Unsloth; that is accelerate 1.6's own behaviour, and this PR does not route that launch through any new path. The check is on the UNSLOTH_FSDP2 opt-in because that is the path where Unsloth itself sets up FSDP2 and can promise a correct checkpoint.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: f98a936647

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Base automatically changed from dh/cp-ulysses-backend to main October 16, 2026 04:15
@danielhanchen
danielhanchen changed the base branch from main to dh/fsdp2-core October 16, 2026 04:19
Base automatically changed from dh/fsdp2-core to main October 16, 2026 06:21
@danielhanchen
danielhanchen marked this pull request as ready for review October 16, 2026 08:33
@danielhanchen
danielhanchen merged commit 4ec8198 into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the dh/cp-fsdp2 branch October 16, 2026 08:33
yermakoffivan pushed a commit to yermakoffivan/unsloth that referenced this pull request Oct 16, 2026
…ormers 4.x (unslothai#14028)

Follow-up to unslothai#13910.

With FSDP2 and context parallelism enabled, `save_model` failed on
transformers 4.57.6. That version checks
`accelerator.parallelism_config` before FSDP, so with the parallelism
config Unsloth installs for CP it skipped the FSDP2 full state dict
gather. PEFT then received sharded tensors and every rank raised
`RuntimeError: Attempted to access the data pointer on an invalid python
storage.`, and no adapter file was written. Periodic checkpoints go
through `save_model` too. Transformers 5.x checks FSDP first, so it was
not affected.

Change (`unsloth/context_parallel.py`): the patched SFTTrainer also
wraps `save_model`. Only while Unsloth's own parallelism config is the
live one, it puts back the config the user had for the duration of the
call and reinstalls Unsloth's afterwards, so the save takes the same
path as FSDP2 without CP. In every other case, including CP off, it
calls the original `save_model` directly.

Tests:
- `tests/test_context_parallel_fsdp2_save_gloo.py`: two gloo ranks on
CPU through the real transformers, accelerate and PEFT save code. Rank 0
must write all 4 LoRA tensors whole and equal to the unsharded
originals, and Unsloth's config must still be installed afterwards.
Fails on main and passes here on transformers 4.57.6 with PEFT 0.18.0
and 0.20.0; passes on both on 5.17.
- `tests/test_context_parallel*.py`: 96 passed, 1 skipped.

Not covered: a real multi-GPU NCCL save and resume, and
`SHARDED_STATE_DICT` checkpoints.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants