Skip to content

Add context parallelism support (SDPA only) - #3823

Closed
djsaunde wants to merge 3310 commits into
unslothai:mainfrom
djsaunde:cp-v4
Closed

djsaunde wants to merge 3310 commits into
unslothai:mainfrom
djsaunde:cp-v4

Conversation

@djsaunde

@djsaunde djsaunde commented Jan 2, 2026 •

Copy link
Copy Markdown
Contributor

This PR adds context parallelism support via the torch-native context_parallel API. It includes:

  • Context manager for toggling context parallelism for training / prediction steps
  • Patches for SFTConfig / SFTTrainer to allow context parallel settings to be passed to / used by the trainer
  • Loss / grad norm reduction logic to correct single-rank reporting
  • Minor unsloth-cli.py updates to allow testing of CP (e.g., disabling dataset shuffling to compare losses apples-to-apples)

Notes:

  • CP should allow context length to scale ~linearly with the number of GPUs with some comms cost
    • Although, comms can be largely overlapped with computation
  • For now, we force the SDPA attention backend when CP > 1 since we haven't implemented CP for other backends yet
  • We raise an error when CP > 1 and packing=True: torch's SDPA CP implementation doesn't support non-causal block masks 😢
    • Meanwhile, ring-flash-attention supports varlen flash attention
    • Not sure if there's a path forward for xformers; will need to check
  • We should coordinate this PR with the FSDP PR since they should share DeviceMesh creation logic / other bits and pieces!
    • We should also be able to always enable FSDP and CP together with a joint DeviceMesh across which we shared the model; gathering the model shards / doing K,V ring comms can be fully overlapped with computation. See here.

TODO:

  • Benchmark speed, memory for 1, 2, 4, 8 way context parallel
  • Test (DDP, CP) joint parallelism

Follow-ups:

danielhanchen and others added 30 commits December 7, 2025 16:40
)

* Update transformers version constraint in pyproject.toml

The latest transformers version just fixes the local training.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update transformers version constraint in pyproject.toml

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.14.7 → v0.14.8](astral-sh/ruff-pre-commit@v0.14.7...v0.14.8)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Remove reload_weights rpc call from grpo trainer

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Use regex instead of static string

* patch openenv reload_weights call

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Better handle sleep and wakeup

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reset indentation

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Remove reload_weights rpc call from grpo trainer

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Use regex instead of static string

* patch openenv reload_weights call

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Better handle sleep and wakeup

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reset indentation

* Handle multi line self.llm.chat better

* Use logger

* re-indent

* Stricter regex to replace wildcard

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
* implement (sdpa, xformers, fa2) sample packing

* attention dispatching

* ddp working OOTB with CLI

* packed SWA and softcap support

* enable batch flattening

* LGPL license headers

* mask packed sequence boundaries

* auto-enable sample packing

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Add explicit toggle for sample packing

* Add explicit toggle for sample packing

* Update __init__.py

* Update unsloth/kernels/rope_embedding.py

* Update unsloth/kernels/rope_embedding.py

* remove grad output clones; restore deleted FastLanguageModel arg

* fix

* restore rope embedding clones

* xformers mask cache

* implement (sdpa, xformers, fa2) sample packing

* attention dispatching

* ddp working OOTB with CLI

* packed SWA and softcap support

* enable batch flattening

* LGPL license headers

* mask packed sequence boundaries

* auto-enable sample packing

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Add explicit toggle for sample packing

* Add explicit toggle for sample packing

* Update __init__.py

* Update unsloth/kernels/rope_embedding.py

* Update unsloth/kernels/rope_embedding.py

* remove grad output clones; restore deleted FastLanguageModel arg

* fix

* restore rope embedding clones

* xformers mask cache

* add back accidental deletion

* Update unsloth/kernels/rope_embedding.py

Co-authored-by: Daniel Han <[email protected]>

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix merge conflicts

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Add **kwargs

* add back clobbered

* Update rope_embedding.py

* Update rope_embedding.py

* simplify trl warnings filter

* docstring

* nit

* bugfix

* Apply suggestion from @danielhanchen

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update unsloth/trainer.py

* Update unsloth/trainer.py

* Update unsloth/trainer.py

* Update unsloth/trainer.py

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
* implement (sdpa, xformers, fa2) sample packing

* attention dispatching

* ddp working OOTB with CLI

* packed SWA and softcap support

* enable batch flattening

* LGPL license headers

* mask packed sequence boundaries

* auto-enable sample packing

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Add explicit toggle for sample packing

* Add explicit toggle for sample packing

* Update __init__.py

* Update unsloth/kernels/rope_embedding.py

* Update unsloth/kernels/rope_embedding.py

* remove grad output clones; restore deleted FastLanguageModel arg

* fix

* restore rope embedding clones

* xformers mask cache

* implement (sdpa, xformers, fa2) sample packing

* attention dispatching

* ddp working OOTB with CLI

* packed SWA and softcap support

* enable batch flattening

* LGPL license headers

* mask packed sequence boundaries

* auto-enable sample packing

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Add explicit toggle for sample packing

* Add explicit toggle for sample packing

* Update __init__.py

* Update unsloth/kernels/rope_embedding.py

* Update unsloth/kernels/rope_embedding.py

* remove grad output clones; restore deleted FastLanguageModel arg

* fix

* restore rope embedding clones

* xformers mask cache

* add back accidental deletion

* Update unsloth/kernels/rope_embedding.py

Co-authored-by: Daniel Han <[email protected]>

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix merge conflicts

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Add **kwargs

* add back clobbered

* Update rope_embedding.py

* Update rope_embedding.py

* simplify trl warnings filter

* docstring

* nit

* bugfix

* add padding-free seqlen metadata

* auto-enable padding free

* gemma2 disable

* Apply suggestion from @danielhanchen

* Update trainer.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update trainer.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
* fbgemm version check

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* safer version check

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Add check for torchvision-torch compatibility

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* refactor package check logic

* Remove logs and enforce torch

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
* Update _utils.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shimmyshimmer and others added 10 commits January 14, 2026 03:45
Disable gradient checkpointing when explicitly off for vision
[trl] use non lora model as base for RL
…_chunked_loss

Chunk Across Batch and Context length for logprob calculations for grpo
…nslothai#3859)

* add int8 weight-only QAT scheme, add test, fix tests for current torchao version

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* change quantization to PerAxis

* lambda =/

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* add torchao messages, remove group_size from int8

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* raise exception on missing torchao

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* touch up the torchao imports

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
@djsaunde

Copy link
Copy Markdown
Contributor Author

Btw on a high level, the whole context parallel, is it supported for our auto compiled models (aka those not in models/ folder)?

Support has been added for this as well.

@djsaunde djsaunde changed the title Add context parallelism support Add context parallelism support (SDPA only) Jan 16, 2026
@djsaunde

djsaunde commented Jan 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Benchmark results:

Metrics are collected from running a short unsloth-cli.py runs with this gist.

Here, we have unsloth/Meta-Llama-3.1-8B using H100s (up to 8), varying context length, chunked cross-entropy loss disabled (i.e., UNSLOTH_CE_LOSS_N_CHUNKS=1):

================================================================================
                                    name status model  seq_len  cp  ga  bsz tokens/sec peak_mem_gb step_time_ms final_loss
  Meta-Llama-3.1-8B_test-2k_cp1_ga1_bsz1     OK           2048   1   1    1    8043.08       16.59       254.64       4.54
  Meta-Llama-3.1-8B_test-2k_cp2_ga1_bsz1     OK           2048   2   1    1    6952.85       16.20       294.61       4.54
  Meta-Llama-3.1-8B_test-2k_cp4_ga1_bsz1     OK           2048   4   1    1    6041.08       15.95       342.66       4.54
  Meta-Llama-3.1-8B_test-2k_cp8_ga1_bsz1     OK           2048   8   1    1    5355.07       15.88       382.46       4.54
  Meta-Llama-3.1-8B_test-4k_cp1_ga1_bsz1     OK           4096   1   1    1    8364.64       17.68       489.68       4.59
  Meta-Llama-3.1-8B_test-4k_cp2_ga1_bsz1     OK           4096   2   1    1   10611.38       16.74       386.01       4.59
  Meta-Llama-3.1-8B_test-4k_cp4_ga1_bsz1     OK           4096   4   1    1   12980.96       16.20       315.56       4.59
  Meta-Llama-3.1-8B_test-4k_cp8_ga1_bsz1     OK           4096   8   1    1   10789.90       15.95       379.66       4.59
  Meta-Llama-3.1-8B_test-8k_cp1_ga1_bsz1     OK           8192   1   1    1    7816.00       19.83      1048.11       4.62
  Meta-Llama-3.1-8B_test-8k_cp2_ga1_bsz1     OK           8192   2   1    1   11236.50       17.86       729.05       4.62
  Meta-Llama-3.1-8B_test-8k_cp4_ga1_bsz1     OK           8192   4   1    1   17898.05       16.74       457.86       4.62
  Meta-Llama-3.1-8B_test-8k_cp8_ga1_bsz1     OK           8192   8   1    1   20613.81       16.20       397.45       4.62
 Meta-Llama-3.1-8B_test-16k_cp1_ga1_bsz1     OK          16384   1   1    1    6381.21       24.15      2567.54       4.62
 Meta-Llama-3.1-8B_test-16k_cp2_ga1_bsz1     OK          16384   2   1    1   10225.86       20.05      1602.22       4.62
 Meta-Llama-3.1-8B_test-16k_cp4_ga1_bsz1     OK          16384   4   1    1   17690.31       17.86       926.16       4.62
 Meta-Llama-3.1-8B_test-16k_cp8_ga1_bsz1     OK          16384   8   1    1   27336.72       16.74       599.34       4.62
 Meta-Llama-3.1-8B_test-32k_cp1_ga1_bsz1     OK          32768   1   1    1    4634.72       32.76      7070.12       4.63
 Meta-Llama-3.1-8B_test-32k_cp2_ga1_bsz1     OK          32768   2   1    1    7880.20       24.43      4158.31       4.63
 Meta-Llama-3.1-8B_test-32k_cp4_ga1_bsz1     OK          32768   4   1    1   14667.56       20.05      2234.06       4.63
 Meta-Llama-3.1-8B_test-32k_cp8_ga1_bsz1     OK          32768   8   1    1   24923.11       17.87      1314.77       4.63
 Meta-Llama-3.1-8B_test-64k_cp1_ga1_bsz1     OK          65536   1   1    1    3025.10       50.03     21664.13       4.63
 Meta-Llama-3.1-8B_test-64k_cp2_ga1_bsz1     OK          65536   2   1    1    5436.25       33.17     12055.43       4.63
 Meta-Llama-3.1-8B_test-64k_cp4_ga1_bsz1     OK          65536   4   1    1   10272.81       24.43      6379.58       4.63
 Meta-Llama-3.1-8B_test-64k_cp8_ga1_bsz1     OK          65536   8   1    1   18788.06       20.05      3488.18       4.63
Meta-Llama-3.1-8B_test-128k_cp1_ga1_bsz1    OOM         131072   1   1    1        N/A         N/A          N/A        N/A
Meta-Llama-3.1-8B_test-128k_cp2_ga1_bsz1     OK         131072   2   1    1    3339.92       50.68     39244.23       4.63
Meta-Llama-3.1-8B_test-128k_cp4_ga1_bsz1     OK         131072   4   1    1    6438.30       33.18     20358.19       4.63
Meta-Llama-3.1-8B_test-128k_cp8_ga1_bsz1     OK         131072   8   1    1   12182.10       24.43     10759.41       4.63
Meta-Llama-3.1-8B_test-256k_cp1_ga1_bsz1    OOM         262144   1   1    1        N/A         N/A          N/A        N/A
Meta-Llama-3.1-8B_test-256k_cp2_ga1_bsz1    OOM         262144   2   1    1        N/A         N/A          N/A        N/A
Meta-Llama-3.1-8B_test-256k_cp4_ga1_bsz1     OK         262144   4   1    1    3683.61       50.75     71165.19       4.62
Meta-Llama-3.1-8B_test-256k_cp8_ga1_bsz1     OK         262144   8   1    1    7104.28       33.25     36899.48       4.62
Meta-Llama-3.1-8B_test-512k_cp1_ga1_bsz1    OOM         524288   1   1    1        N/A         N/A          N/A        N/A
Meta-Llama-3.1-8B_test-512k_cp2_ga1_bsz1    OOM         524288   2   1    1        N/A         N/A          N/A        N/A
Meta-Llama-3.1-8B_test-512k_cp4_ga1_bsz1    OOM         524288   4   1    1        N/A         N/A          N/A        N/A
Meta-Llama-3.1-8B_test-512k_cp8_ga1_bsz1     OK         524288   8   1    1    3894.89       50.90    134609.51       4.62
================================================================================

Note that CP=1 OOMs at 128k context length, CP=2 at 256K, CP=4 at 512k, and CP=4 would have OOMed at 1024k. This is in line with the expected ~linear savings in VRAM with increasing context length. It's also interesting to note the tokens/s throughput increase, which depends on both context length and CP size: generally, higher CP gives higher throughput, except at short context length.

Enabling CCE loss and / or tiled MLP will allow even longer context lengths, but comes at the expense of training wall clock time (it starts to take quite a while), so I decided to omit those experiments here. But, for example, I was able to hit 1M context length just by enabling CCE loss and with CP size 4.

Some notes:

  • For full release, I recommend adding support for the flash attention backend via ring-flash-attention. I started work on this on this branch, but it needs some bugfixes:
    • The flash attention "dense" (sample packing disabled) backend appears to work and matches loss with the CP=1 case, but gradient norms are ~2-5x too large. This might just be a reported loss issue (i.e., the number that gets logged on the command line / in wandb is wrong, but I think the internal grad norms are correct since the CP=1 vs. CP=2 losses match).
    • The flash attention "varlen" (sample packing enabled) backend gives NaN grad norms from the first training step. I suspect something is wrong with the backwards pass.
  • I disabled auto-padding free for these runs. If enabled, it results in worse VRAM scaling (with and without context parallelism). I think we should revisit this as a default.
  • Some models don't exhibit the same ~linear VRAM savings; e.g., when testing a "compiled" model (via the Unsloth compiler), specifically OLMo2 7B, I saw sublinear savings (just comparing CP=1 vs. CP=2): results. Not sure why this is. It might be related to their use of vanilla MHA instead of GQA?
  • Logs are duplicated across processes: this can be fixed with a simple utility to prevent logs from being emitted on non-main processes.
  • Combining with DDP (e.g., 4 GPUs, CP=2) currently causes training to hang during the first model forward pass. This needs to be debugged. I'm guessing we need to do device mesh creation differently in the joint CP / DDP setting. Might be worth checking if torch context_parallel even supports this.

@djsaunde
djsaunde marked this pull request as ready for review January 16, 2026 21:40

@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: cb5e10bd5c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread unsloth/models/llama.py
Comment on lines +674 to +678
if flat_ids.shape[0] > 1:
all_equal = torch.all(flat_ids == flat_ids[0]).item()
if not all_equal:
raise RuntimeError(
"fast_rope_embedding requires identical position_ids across the batch."

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 Allow per-sample position_ids in Llama RoPE path

The new check hard-errors when position_ids are not identical across the batch. In padding-free or packed training (where TRL supplies per-sample position_ids), the IDs typically differ, so this now raises at runtime even when context parallelism is disabled. Previously, Llama passed rope_position_ids into fast_rope_embedding, which supports per-token indices, so this is a regression that breaks sample packing/padding-free flows. Consider keeping the per-token path for non-CP (or for any case where position_ids are per-sample) instead of rejecting them.

Useful? React with 👍 / 👎.

Comment on lines +131 to +135
def _build_device_mesh(self) -> DeviceMesh:
self._dp_world_size = self._world_size // self.settings.size
mesh = torch.arange(self._world_size, dtype = torch.int64).reshape(
self._dp_world_size, self.settings.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 Validate world_size divisibility for context parallel mesh

The device mesh is built via integer division and reshape without checking that world_size is divisible by context_parallel_size. For configurations like world_size=6, cp_size=4, this will raise a reshape error and silently produce a wrong dp_world_size value. Add an explicit world_size % cp_size == 0 check (and a clear error) before constructing the mesh to avoid hard-to-diagnose failures.

Useful? React with 👍 / 👎.

mmathew23 added a commit to mmathew23/unsloth that referenced this pull request Mar 4, 2026
Resolved conflicts in llama.py and attention_dispatch.py:
- llama.py: kept both loader_utils import and F import, used required_seq_len with dtype casting
- attention_dispatch.py: kept main's batched masked inference fix with scaled_dot_product_attention
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Oct 16, 2026
Replacement for unslothai#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).

---------

Co-authored-by: Dan Saunders <[email protected]>
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.