Skip to content

Add context parallelism support (SDPA only) - #4257

Merged
danielhanchen merged 53 commits into
mainfrom
dh/recover-3823-context-parallel
Oct 16, 2026
Merged

danielhanchen merged 53 commits into
mainfrom
dh/recover-3823-context-parallel

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Mar 12, 2026 •

Copy link
Copy Markdown
Member

Replacement for #3823 due to Studio rebasing.

Adds context parallelism (CP) for SFT through PyTorch's context_parallel (SDPA ring attention). Each rank holds 1 / context_parallel_size of every sequence, so the context that fits grows roughly linearly with the number of GPUs.

Usage: SFTConfig(context_parallel_size = N) under torchrun / accelerate launch with a world size divisible by N (unsloth-cli.py --context_parallel_size N). Optional context_parallel_rotate_method = "allgather" (default, torch's default) or "alltoall".

How it works:

  • unsloth/context_parallel.py: per step, builds position_ids and pre-shifted shift_labels on the full sequence, pads to a multiple of 2 * N (torch's load balancer), then shards input_ids, labels, shift_labels, position_ids, attention_mask along the sequence. Forward and backward both run inside the context, so gradient checkpointing recomputes with ring attention. The rotate method is set inside each step and restored after.
  • Mesh (dp_replicate, cp) is handed to accelerate, which gives every CP rank the same batch and shards data only across dp_replicate.
  • Loss: training counts target tokens before sharding, so the world-summed num_items_in_batch counts each sequence N times and is divided by N once (the same divisor HF uses for its own parallelism_config). A missing count with labels present raises instead of falling back to a local mean. Eval counts after sharding, all-reduces the loss over the CP group and reports a per-replica token mean. Gradient accumulation micro-steps use no_sync as usual.
  • Attention: SDPA is pinned to the ring-capable kernels (flash, efficient, cuDNN where torch registers it) for the CP region; GQA stays native (enable_gqa, so the ring moves n_kv_heads, not n_heads; UNSLOTH_CP_GQA=0 expands K/V instead); fp32 Q/K/V are downcast for the kernel. RoPE uses the sharded global position_ids; the CausalLM loss accepts pre-shifted shift_labels.
  • Packing / padding-free are turned off under CP (ring attention has no varlen support); the Ulysses follow-up lifts this.

Guards (all ranks fail at trainer init, before any collective): no process group, world size not divisible by N, torch < 2.7, accelerate < 1.10, models whose loss does not accept num_items_in_batch, attention other than the Llama forward (Llama, Qwen2, Gemma), sliding window / chunked attention / logit softcapping / non-full layer_types, GPUs below compute capability 8.0 (torch's ring attention fails in backward on 2x T4, reproduced with a pure torch probe), use_legacy_prediction_loop, iterable datasets in predict().

GPU parity (2 x B200, tiny random Llama / Qwen2 with LoRA r16, 3 steps, uneven rows 300-1100 tokens with masked regions, one row leaving rank 1 with no targets). Reference is CP=1 on the same rows; gates are loss relative error <= 5e-3 and per-parameter gradient cosine >= 0.999; the CP=1 rerun (A/A) sets the noise floor.

arm dtype GA loss rel err min grad cos max grad rel L2
CP=1 rerun (A/A noise floor) bf16 1 2.6e-5 0.99997 8.1e-3
ring allgather, MHA bf16 1 2.6e-5 0.99984 1.8e-2
ring alltoall, MHA bf16 1 3.1e-5 0.99984 1.8e-2
ring allgather, GQA (kv 2), no_sync on the first micro-step fp32 2 1.9e-5 0.99990 1.4e-2
ring, MQA (kv 1) bf16 1 8.2e-5 0.99985 1.8e-2
ring, Qwen2 GQA bf16 1 1.7e-5 0.99986 1.7e-2
ring, gradient checkpointing off bf16 1 3.3e-5 0.99984 1.8e-2
control: no division by N bf16 1 5.0e-1 (FAIL, expected) 0.99984 5.0e-1
control: shard-local SDPA instead of ring bf16 1 3.2e-3 0.812 (FAIL, expected) 6.3e-1

The first four rows are on this branch's head; the rest are on the earlier head with the same ring path. Ring arms sit at about 2x the A/A spread (fp32 Q/K/V are downcast for the ring kernel), well inside the gates; both controls trip them. On 2 x T4 the trainer refuses CP at init as intended.

FA3 / FA4: on sm100 the ring's default SDPA picks cuDNN or efficient, so the FA4 override is not reached unless flash is forced; FA4 itself could not be validated on torch 2.13 here (flash-attn-4 b19+ changed the return arity torch expects, b18's backward hangs), so it is untested under CP.

No change when context_parallel_size is 1 (default): switchboard base vs head reports sft, vision_sft, audio_sft, inference_smoke NO_REGRESSION and regression_smoke with 0 regressions.

Follow-ups:

  • Ulysses backend (stacked PR) for packing, padding-free and varlen kernels under CP.
  • DDP x CP and FSDP2 x CP joint meshes on real GPUs (the loss algebra for dp x cp is covered by the CPU tests).

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen
danielhanchen force-pushed the dh/recover-3823-context-parallel branch from f155c0e to 9c816f3 Compare March 12, 2026 23:10
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 29, 2026
@unslothai unslothai deleted a comment from gemini-code-assist Bot Sep 29, 2026
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').
…kernels

- context_parallel_backend (ring) and context_parallel_rotate_method
  (allgather or alltoall) on SFTConfig, UnslothTrainingArguments and the CLI;
  bad sizes and choices fail before the trainer builds its datasets.
- Enforce PyTorch >= 2.7 by version, not only by import.
- Ring refuses sliding, chunked and softcapped attention, including
  layer_types and nested text configs.
- Refuse models that do not take loss kwargs, and raise in training_step
  when labels arrive without num_items_in_batch instead of training on a
  per-shard mean.
- Pin SDPA to the kernels the CP dispatcher rings (flash, efficient, and
  cuDNN where handled) so the math kernel cannot attend over one shard.
- Scope FA3 / FA4 to train() for CP trainers even though packing is off.
2-GPU parity with GA=2 matches with sync_each_batch on or off (ring, allgather and alltoall), and on
transformers 4.57 the Trainer calls no_sync directly so the flag was never read.

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 6786ecacdc

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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 000a860b55

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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 38506840c2

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

@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

# Conflicts:
#	tests/utils/test_packing.py

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 0e74295fa9

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

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: a7d76f5dff

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

@danielhanchen
danielhanchen merged commit 493ac4d into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the dh/recover-3823-context-parallel branch October 16, 2026 03:18
danielhanchen referenced this pull request in danielhanchen/unsloth-staging-2 Oct 16, 2026
…nslothai#13848)

Stacked on #4257 (base is its branch; retarget to `main` once it
merges).

Adds a Ulysses backend for context parallelism:
`SFTConfig(context_parallel_size = N, context_parallel_backend =
"ulysses")`. Ring attention (#4257) shards the sequence inside SDPA, so
it cannot run varlen kernels and turns packing / padding-free off.
Ulysses instead exchanges sequence shards for head shards around
attention, so attention sees the whole sequence for `H / N` heads and
the normal dispatcher runs unchanged: packing, padding-free, flash
varlen, torch varlen, SDPA packed segments and xformers all keep
working, and FA4 / FA3 engage wherever they engage without CP (torch's
flash path).

How it works:
- `unsloth/utils/ulysses.py`: an autograd all-to-all (`[B, H, T/N, D] ->
[B, H/N, T, D]` and back for the output; backward is the inverse
exchange, no scaling). When `N > n_kv_heads`, K/V heads are repeated so
every rank gets whole groups; autograd sums the copies' gradients back.
Needs `n_heads % N == 0` and `n_kv_heads` and `N` dividing one another,
checked on every rank at trainer init.
- `run_attention` routes through the exchange when a Ulysses manager is
active, rebuilding `AttentionConfig` / `AttentionContext` for the local
heads and global length, so the existing backends and guards
(`flash_impl_allows`, varlen int32 guard, padded tail segment) apply as
is.
- `ContextParallelManager` (Ulysses): builds `shift_labels` on the full
sequence after masking packed document starts, keeps (or builds
per-document) `position_ids`, pads to a multiple of `N`, and keeps this
rank's contiguous slice. `packed_seq_lengths` stays global, since
attention sees the whole sequence; the CP pad tail becomes its own
segment.
- Ring-only restrictions stay ring-only: SDPA forcing and the varlen
refusal in `select_attention_backend`, the fp32 downcast,
`UNSLOTH_CP_GQA`, the trainer's packing / padding-free / `eval_packing`
block, `sync_each_batch`, and the sm80 requirement.
- Loss is the same contract as #4257: the pre-shard target count summed
over the world, divided by `N` once.

Tests:
- `tests/test_ulysses.py` (CPU, gloo, 2 and 4 ranks): exchange order and
round trip; forward and Q/K/V gradients against full-sequence attention
for MHA, GQA, MQA with 2x and 4x KV replication, fp32 and fp64, odd
lengths padded; packed documents crossing every shard seam; the real
`run_attention` SDPA path for dense and packed rows.
- `tests/test_context_parallel.py`: contiguous sharding after the global
shift, packed lengths kept global with per-document positions and masked
document starts, ring refusing packed batches, routing through the
exchange, head-count and sm80 checks at init.

GPU parity (tiny random Llama / Qwen2 with LoRA r16, 3 steps, uneven
rows with masked regions, one row leaving the second contiguous shard
with no targets). Reference is CP=1 on the same rows; gates are loss
relative error <= 5e-3 and per-parameter gradient cosine >= 0.999; the
CP=1 rerun (A/A) sets the noise floor.

2 x Tesla T4 (sm75, fp32, torch 2.14.1), where ring CP is refused:

| arm | GA | loss rel err | min grad cos | max grad rel L2 | all-to-alls
(rank 0) |
|---|---|---|---|---|---|
| CP=1 rerun (A/A) | 1 | 0 | 1.000000 | 7.8e-7 | 0 |
| Ulysses, GQA (kv 2) | 1 | 0 | 1.000000 | 2.3e-6 | 144 |
| Ulysses, MHA (kv 8), `no_sync` on the first micro-step | 2 | 9e-8 |
1.000000 | 2.2e-6 | 288 |
| Ulysses, MQA (kv 1, K/V repeated 2x) | 2 | 9e-8 | 1.000000 | 2.0e-6 |
288 |
| Ulysses, packing + padding-free on | 1 | 9e-8 | 1.000000 | 3.1e-6 |
144 |
| control: no division by `N` | 1 | 5.0e-1 (FAIL, expected) | 1.000000 |
5.0e-1 | 144 |
| ring | 1 | refused at init (needs compute capability >= 8.0) | | | |

2 x B200 (bf16 and fp32, torch 2.13; fp32 Q/K/V are downcast for the
flash kernels here, so the spread is larger):

| arm | dtype | GA | loss rel err | min grad cos | max grad rel L2 |
|---|---|---|---|---|---|
| CP=1 rerun (A/A) | bf16 | 1 | 1.1e-5 | 0.99997 | 8.1e-3 |
| Ulysses, MHA / GQA / MQA | bf16 | 1 | <= 2.1e-5 | >= 0.99992 | <=
1.2e-2 |
| Ulysses, Qwen2 GQA | bf16 | 1 | 2.6e-5 | 0.99993 | 1.2e-2 |
| Ulysses, GQA | fp32 | 2 | 4.4e-6 | 0.99998 | 7.1e-3 |
| Ulysses packed (3/3 micro-batches packed, a document crossing the
shard seam in each) vs CP=1 packed | bf16 | 1 | <= 1.5e-5 | 0.99995 |
9.5e-3 |
| ring on this branch, GQA | fp32 | 2 | 9.3e-6 | 0.99990 | 1.4e-2 |
| ring with `packing = True` | bf16 | 1 | 1.4e-5 | 0.99984 | 1.8e-2
(packing switched off at init) |
| control: no division by `N` | bf16 | 1 | 5.0e-1 (FAIL, expected) |
0.99993 | 5.0e-1 |

Not covered here: model families other than the Llama forward (Llama,
Qwen2, Gemma), more than 2 GPUs, DP x CP on GPU (CPU gloo covers the 2 x
2 loss algebra), FA3 on Hopper, and FA4 (could not be validated on torch
2.13 here: flash-attn-4 b19+ changed the return arity torch expects and
b18's backward hangs).

---------

Co-authored-by: Dan Saunders <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
bestoffersdirect-fork-sync Bot pushed a commit to BestOffersDirect/unsloth that referenced this pull request Oct 16, 2026
…hai#13910)

Stacked on unslothai#13848 (Ulysses context parallel, which stacks on unslothai#4257).
Depends on unslothai#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.

---------

Co-authored-by: Dan Saunders <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
oobabooga pushed a commit to oobabooga/unsloth that referenced this pull request Oct 19, 2026
… (torch 2.10 step time) (unslothai#14152)

## Summary

`patch_sft_trainer()` (context parallelism, unslothai#4257) runs at `import
unsloth` and replaces `train`, `training_step`, `prediction_step`,
`evaluate`, `predict`, `evaluation_loop`, `save_model` and
`get_total_train_batch_size` on `trl.SFTTrainer` with wrappers that pass
straight through when `context_parallel_size = 1`. Even as pass-throughs
they made LoRA training steps much slower on torch 2.10 with sm80+ GPUs
(L4 / A100): gemma-4-E2B steady step went from ~300 ms to ~425 ms. Torch
2.14, T4 and torch 2.11 to 2.13 were not affected.

Bisecting on Colab L4 / A100 with torch 2.10:

- Reverting only the `patch_sft_trainer()` call restores base speed.
- Keeping any single wrapper (`__init__`, `train`, `training_step`,
`prediction_step`, `evaluation_loop`, or the four evaluation wrappers
together) is as fast as base.
- Only the full set is slow. The profile shows the extra time as CPU
self time in AOTAutograd's `CompiledFunction` (413 ms vs 110 ms over 4
steps, same call count).

This change keeps the `__init__` wrapper, which runs the CP option
checks and installs the accelerator state. It now installs the other
wrappers on the class only once a trainer actually enables context
parallelism (`context_parallel_size > 1`, after every gate passes).
Trainers with CP off run the original methods. CP behaviour is
unchanged: the wrappers are the same functions, installed before
`train()` can run. `patch_sft_trainer(install_cp_methods = True)`
installs them up front, which the unit tests that call the wrappers
directly use.

## Results (Colab L4, LoRA SFT, 15 steps, steady step ms)

| arm | gemma-4-E2B torch 2.10 | Qwen3-0.6B torch 2.10 | gemma-4-E2B
torch 2.14 | Qwen3-0.6B torch 2.14 |
|---|---|---|---|---|
| base (before unslothai#4257) | 297.0 | 304.2 | 254.8 | 285.3 |
| main | 428.5 | 310.2 | 257.7 | 285.7 |
| this PR | 303.2 | 304.5 | 255.2 | 285.5 |
| this PR (repeat, last arm) | 305.2 | 302.0 | 259.6 | 292.4 |
| main (repeat, last arm) | 421.6 | 313.8 | 255.2 | 287.5 |

Peak memory is the same in every arm. The losses for the 6 logged steps
match base exactly (torch 2.14: one identical loss trace across all
arms), and there are 0 graph breaks in all arms.

## Tests

- `tests/test_context_parallel.py`, `tests/test_ulysses.py`,
`tests/test_ulysses_hybrid.py`,
`tests/test_context_parallel_fsdp2_gloo.py`,
`tests/test_context_parallel_fsdp2_save_gloo.py` pass on CPU / gloo. One
test fails on this CPU-only host,
`test_unsloth_training_arguments_keep_the_cp_options` (no bf16 on CPU),
and it fails identically on main.
- New `test_cp_methods_are_wrapped_only_once_a_trainer_enables_cp`: with
CP off only `__init__` is wrapped, even after constructing a trainer. A
trainer that enables CP installs the wrappers around the original
methods.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants