Repository navigation
Conversation
) * 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>
…-config [pre-commit.ci] pre-commit autoupdate
wrong number of dimensions
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>
Support has been added for this as well. |
|
Benchmark results: Metrics are collected from running a short Here, we have 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:
|
There was a problem hiding this comment.
💡 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".
| 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." |
There was a problem hiding this comment.
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 👍 / 👎.
| 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 | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
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
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>
This PR adds context parallelism support via the torch-native
context_parallelAPI. It includes:unsloth-cli.pyupdates to allow testing of CP (e.g., disabling dataset shuffling to compare losses apples-to-apples)Notes:
packing=True: torch's SDPA CP implementation doesn't support non-causal block masks 😢ring-flash-attentionsupports varlen flash attentionxformers; will need to checkTODO:
Follow-ups:
ring-flash-attentionintegration for flash attention backend