Skip to content

Context parallelism: generic Ulysses on any Hugging Face attention model, per-instance trainer wrappers - #16558

Merged
danielhanchen merged 8 commits into
mainfrom
dh/par-generic-ulysses
Nov 4, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
dh/par-generic-ulysses

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

A follow-up to the one-flag parallel work now on main: context parallelism on models beyond Unsloth's fast Llama forward, and no more patching of trainer classes.

What

  • Generic Ulysses. Ulysses now runs the model's own attention function after the all-to-all (ALL_ATTENTION_FUNCTIONS[impl], or the modeling module's eager_attention_forward for eager). scaling, softcap and sliding_window go through unchanged, attention sinks are sliced to the local heads, and for eager / sdpa the whole-sequence mask (causal, window, packed documents) is rebuilt. When unsloth_zoo has replaced a class forward (Gemma3), the stashed Hugging Face forward runs while a Ulysses manager is active. _supports_context_parallel and attach_attention_hooks accept any model whose attention calls the registry. Sliding window and softcap are refused only for ring, and the registry row cp x attention now covers ring only. Bidirectional (non-causal) attention is refused under Ulysses instead of being trained with a causal mask.
  • Per-instance trainer wrappers. SFTTrainer and the generated DPO / GRPO trainers keep only __init__ patched on the class. A trainer that asks for context parallelism gets its CP wrappers bound on itself before the original __init__ runs, and loses them again if it ends up without CP or __init__ raises. Trainers without CP, whether built before or after a CP trainer in the same process, run the class's own methods. The CP mesh and parallelism config sit on the shared AcceleratorState only while a CP entry point is running.
  • FSDP2 keeps adamw_8bit. The generated SFT / GRPO configs no longer switch adamw_8bit to adamw_torch_fused on accelerate's FSDP2 path. Once _prepare_fsdp2 maps the optimizer onto the DTensor parameters, a bitsandbytes Adam / AdamW steps each rank's local shard, as native FSDP2 already does. Any other bitsandbytes optimizer, UNSLOTH_FSDP2_BNB_LOCAL=0, or CPU shards are refused at that point, with alternatives.
  • Clearer refusals. UNSLOTH_CP_SIZE on a trainer that has no CP wrapper now gives the actual cause: the CPU backend, a trainer outside SFT / DPO / GRPO, UNSLOTH_ALLOW_CPU=1, or a failed patched-trainer build (with the recorded error).
  • Block compile stays clean with PEFT parametrizations. PEFT's ParamWrapper registers a torch parametrization on every forward (here on the Qwen3-MoE router), and torch builds a new Parametrized<Class> subclass each time. Under block compile each module now reuses one such class, keyed weakly by instance and never shared between modules.

Why

Before this, Ulysses only worked through Unsloth's fast Llama attention. On CPU ranks the test harness had to force the support check open and install the attention wrapper by hand. It also dropped the model's own scaling, softcap, window and sinks. Patching trainer classes leaked CP behaviour into every later trainer in the same process.

The parametrization change fixes a recompile that the generic path exposed. Dynamo guards a module's type id, so the router forward and PEFT's get_base_layer recompiled every time the fresh class landed at an address Dynamo had not seen yet. That count depends on the allocator. The qwen3_moe cp 2 LoRA block compile cell came out at 28 recompiles against 26 for one process, failing the "no more than one process" check. With one class per module, both sides come out at 6 recompiles and 6 graph breaks (one router class per layer), against 26 / 12 in one process before.

Tests

All on CPU with gloo ranks and tiny models, with no GPU visible.

Failing first: these branch test files fail when run on the one-flag head (now main).

file one-flag head this branch
test_context_parallel.py 17 failed, 86 passed 103 passed
test_context_parallel_fsdp2_gloo.py 1 failed 1 passed
test_context_parallel_fsdp2_save_gloo.py 2 failed, 2 skipped 2 passed, 2 skipped
test_context_parallel_rl.py 1 failed, 37 passed 38 passed
test_cp_instance_overrides_gloo.py 1 failed 1 passed
test_cp_trainer_refusal.py 4 failed 4 passed
test_fsdp2_bnb_optim_kept.py 2 failed 2 passed
test_parallel_env.py 5 failed, 106 passed 132 passed (current main's tests included)
test_cp_ulysses_generic_gloo.py 12 failed, 1 passed 13 passed
test_ulysses_hybrid.py 1 failed, 18 passed 19 passed
test_fsdp2_default_optim.py 7 skipped 7 skipped (CUDA only)
  • test_parallel_cp_compose_gloo.py: 26 passed. Before the parametrization fix, test_moe_block_compile_under_cp_is_compile_clean[lora] failed with 28 recompiles against 26.
  • test_block_compile.py: 48 passed, 6 skipped. The new test_parametrized_class_is_reused_per_module passes. One failure, test_sm_count_is_read_outside_the_trace, needs a CUDA device and fails the same way on main.
  • The generic Ulysses tests compare tiny Gemma3 / Gemma2 / Qwen3 / gpt-oss on 2 ranks against one process (loss and every parameter gradient, plain rows and packed), with negative controls for window, softcap and sinks.

Not covered

  • No GPU runs here: NCCL ranks, flash attention backends under generic Ulysses, and real-size models were not exercised. test_fsdp2_default_optim.py only runs on CUDA.
  • The class reuse only applies under Unsloth's block compile. The unsloth_zoo compiled-module path still sees one fresh parametrized class per forward.
  • Ring attention still refuses sliding window, softcap and chunked attention. DPO / GRPO keep the Llama-style support rule.
  • macOS, Windows and AMD were not run.

…del, per-instance trainer wrappers

- Ulysses runs the model's own attention function after the all-to-all (scaling, softcap, window and sinks kept; eager / sdpa masks rebuilt over the whole sequence).
- SFT / DPO / GRPO trainers bind their CP wrappers on the instance, not the class.
- FSDP2 keeps optim = 'adamw_8bit' (bitsandbytes Adam steps each rank's local shard).
- Refusals name the real reason a trainer has no CP wrapper.
- Block compile reuses one Parametrized class per module, so PEFT's per-forward parametrization stops recompiling.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-03T23:02:31.974693Z b35da88 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 787e1ba84d

ℹ️ 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 +326 to +328
)
return (
window if isinstance(window, int) and not isinstance(window, bool) and window > 0 else None

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 Preserve non-causal attention when rebuilding the mask

For newly accepted Hugging Face models configured with non-causal attention, such as Gemma3 with use_bidirectional_attention=True, the eager path always calls _whole_sequence_mask, which unconditionally masks every key after the query. The windowed SDPA path does the same. Consequently, enabling Ulysses silently changes bidirectional attention into causal attention and produces different outputs and gradients from the unsharded model. Respect the module's is_causal setting (and any explicit override) when rebuilding the mask, or reject these configurations before training.

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.

Fixed in 6206452. Ulysses now refuses non-causal attention: once when the wrapper is installed (module.is_causal False, for example Gemma3 with use_bidirectional_attention) and again on a per-call is_causal=False override. Supporting it properly would need each model's bidirectional window rule (Gemma3 uses distance < window, the generic overlay uses <=), so refusing is safer for now. New test: test_bidirectional_attention_is_refused.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 62064527b1

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

@LeoBorcherding

Copy link
Copy Markdown
Collaborator

I cancelled the CI runs on this PR for now, since Codex hasn't converged at the current head yet: the latest push hasn't been reviewed by Codex yet. CI here runs on the team's shared runner pool, and it's backed up right now (380+ runs queued), so runs on code that's still changing push everyone else's back.

Once Codex says "Didn't find any major issues" on the head commit, one push or a re-run brings CI back. A small ask going forward: hold the push until Codex is clean, and batch follow-up fixes into a single push. Thanks!

…s it

test_u*.py belongs to rest-2 and *gloo*.py to gloo, so test_ulysses_generic_gloo.py ran in both and
test_ci_repo_cpu_shards failed. test_cp_* matches the gloo shard only.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: b35da88155

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

@MegaGimen

Copy link
Copy Markdown
Contributor

For reference: the Gemma 4 sliding-window / scale handling under Ulysses here overlaps with #15883, opened on 2026-10-29, five days before this PR (commits were pushed onto that branch on 2026-10-30). #15883 is part of a series (#15880-#15883) that is still open. It is not mentioned here.

danielhanchen added a commit to MegaGimen/unsloth that referenced this pull request Nov 7, 2026
Resolved toward main's generic Ulysses (unslothai#16558): Hugging Face attention, Kimi-Linear MLA included,
runs through _ulysses_hf_attention with its own scale and value width, so the MLA value padding is
dropped. The Kimi delta attention mixer path, the every-expert MoE grads and the gate shim are kept
on top of main's attention declarations, registry gates and decoder mask hook.

Co-authored-by: Immanuel Sun <[email protected]>
danielhanchen added a commit to MegaGimen/unsloth that referenced this pull request Nov 7, 2026
Main dropped the module's weakref import in unslothai#16558 once its own last use moved out;
install_idle_expert_grad_hook still holds the MoE blocks by weak reference, so every
Kimi-Linear MoE training step under context parallelism raised NameError.

Co-authored-by: Immanuel Sun <[email protected]>
danielhanchen added a commit to MegaGimen/unsloth that referenced this pull request Nov 7, 2026
Kimi-Linear's MLA layers call ALL_ATTENTION_FUNCTIONS, so main's generic Ulysses (unslothai#16558)
already runs them with their own scale and narrower value heads. Drop the KimiMLAAttention
class list: the hybrid check accepts the Gated DeltaNet attention classes or any registry
attention next to the Ulysses mixers, and the hooks install the generic wrapper as for
plain attention models. Equivalence: the hub KimiMLAAttention / KimiDecoderLayer under CP2
gloo match one process on main and on this branch (sdpa fp64 with a custom and the default
scale, eager fp32), every parameter gradient, and fail when the CP arm loses the scale.

Co-authored-by: Immanuel Sun <[email protected]>
danielhanchen added a commit that referenced this pull request Nov 11, 2026
… times it (#17049)

Under context parallelism, `trainer.evaluate()` reports `eval_loss`
multiplied by the cp size.

`patched_prediction_step` (#16558) puts the sequence's target count in
`inputs["num_items_in_batch"]`, calls `self.compute_loss(model, inputs)`
on each rank's shard, and sums the results over the cp group. TRL's
`SFTTrainer.compute_loss` only reads its `num_items_in_batch`
**argument** (here None); the fused forward accepts the inputs key and
does nothing with it. So each rank returns its own shard's token mean,
and the `all_reduce` adds cp_size of them.

Real `SFTTrainer` on the CPU backend (tiny Llama, same data and weights;
the agent-written repro is the audit's `e2e.py`):

| | eval_loss |
|---|---|
| one process | 10.336449 |
| cp = 2, main | 20.673664 on both ranks |
| dp2 x cp2, main | 20.673664 on all 4 |
| cp = 2, this PR | 10.336451 on both ranks |

Training is unaffected (`training_step` passes the count as an
argument). What breaks is `eval_loss` and everything that reads it:
early stopping, `load_best_model_at_end`, and logged curves. The
existing unit test missed it because its stand-in `compute_loss` read
`inputs["num_items_in_batch"]`.

Fix: weight each shard's mean by its share of the sequence's targets
(`local / count`) before the sum, and stop relying on how `compute_loss`
normalises. An empty shard still contributes 0.

Tests: the stand-in `compute_loss` now takes `num_items_in_batch` as an
argument the way TRL does. New
`test_eval_loss_is_not_multiplied_by_the_cp_size`: two ranks with 2 of 4
targets each should sum to 1. It gets 2.0 on main and passes here. 104
passed in `tests/test_context_parallel.py`, including the existing
empty-shard test.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
danielhanchen added a commit that referenced this pull request Nov 11, 2026
…#17051)

On the generic Hugging Face Ulysses path (#16558), the model's
`rotary_emb(hidden, position_ids)` runs on each rank's **shard** of
`position_ids`. transformers' `@dynamic_rope_update` picks frequencies
from `max(position_ids) + 1`:
- **longrope** (Phi-3 / 3.5 / 4-mini long context) uses the short
factors at or below `original_max_position_embeddings` and the long
factors above it;
- **dynamic** NTK recomputes `inv_freq` past `max_position_embeddings`.

So ranks rotate with different frequencies than a single process would,
and keys from different frequency sets are attended together after the
all-to-all. Long sequences are exactly where CP gets used. Unsloth's
fast Llama path is not affected (it sets `rope_seq_len = kv_seq_len *
cp_manager.size`).

Parity against one process (loss and all-reduced per-parameter grads,
gloo CPU):

| case | main | this PR |
|---|---|---|
| Phi-3 longrope, orig 10, seq 16, cp 2 | max grad diff 1.2e-3, dloss
1.8e-5 | 1.5e-8, dloss 0 |
| Phi-3 longrope, orig 20, seq 32, cp 4 | 6.5e-4 | 2.2e-8 |
| Llama dynamic NTK | 5.1e-5 (~3000x the plain-RoPE baseline) | 1.9e-8 |
| control: orig >= seq | 3.0e-8 | 3.0e-8 |

At a realistic size (orig 4096, seq 16384, cp 4), rank 0's longrope cos
is off by up to 2.4, and dynamic NTK ranks 0–2 are off by about 2.0.

Fix:
- `_ulysses_shard` keeps the unsharded `position_ids` on the manager for
the duration of the step.
- `attach_attention_hooks` (Ulysses, generic path only) wraps rotary
modules whose `rope_type` is `dynamic` or `longrope`, including
per-layer-type dicts. The wrapper computes cos / sin over the whole
sequence's positions and returns this rank's contiguous slice.
- No collective is added. Outside a CP step, or when the shapes do not
match a contiguous shard, the original forward runs unchanged.

Test:
`test_ulysses_seq_len_rope_uses_the_whole_sequence[dynamic|longrope]`
builds a tiny Llama (dynamic) or Phi-3 (longrope) where rank 0's shard
stays within the original length while the whole sequence exceeds it.
Both cases fail on main and pass here; `tests/test_context_parallel.py`
has 105 passed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
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.

3 participants