Repository navigation
Context parallelism: generic Ulysses on any Hugging Face attention model, per-instance trainer wrappers - #16558
Conversation
…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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
There was a problem hiding this comment.
💡 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".
| ) | ||
| return ( | ||
| window if isinstance(window, int) and not isinstance(window, bool) and window > 0 else None |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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]>
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]>
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]>
… 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]>
…#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]>
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
ALL_ATTENTION_FUNCTIONS[impl], or the modeling module'seager_attention_forwardfor eager).scaling,softcapandsliding_windowgo 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_parallelandattach_attention_hooksaccept any model whose attention calls the registry. Sliding window and softcap are refused only for ring, and the registry rowcp x attentionnow covers ring only. Bidirectional (non-causal) attention is refused under Ulysses instead of being trained with a causal mask.__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 sharedAcceleratorStateonly while a CP entry point is running.adamw_8bit. The generated SFT / GRPO configs no longer switchadamw_8bittoadamw_torch_fusedon accelerate's FSDP2 path. Once_prepare_fsdp2maps 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.UNSLOTH_CP_SIZEon 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).ParamWrapperregisters a torch parametrization on every forward (here on the Qwen3-MoE router), and torch builds a newParametrized<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_layerrecompiled 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).
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 newtest_parametrized_class_is_reused_per_modulepasses. One failure,test_sm_count_is_read_outside_the_trace, needs a CUDA device and fails the same way on main.Not covered
test_fsdp2_default_optim.pyonly runs on CUDA.