Repository navigation
Tensor parallel from UNSLOTH_TP_SIZE for unmodified training scripts, with Trainer checkpoints and 8-bit AdamW - #15326
Conversation
sharded_loading(tp_mesh) / load_tensor_parallel(...) make from_pretrained build the model on meta and stream the safetensors checkpoint: replicated tensors whole, attention / MLP projections as this rank's slices (per-part slices for fused qkv and packed gate_up). The slices stay plain tensors tagged with their full shape, so get_peft_model creates full-size LoRA factors with the same init as one GPU; apply_tensor_parallel then wraps them into the DTensors v1 builds. A forward before apply_tensor_parallel is refused. 16-bit safetensors checkpoints only; quantized loads are refused.
shard_model(model, FSDP2Config(mesh = mesh['dp'])) now accepts a model sharded by apply_tensor_parallel(model, mesh['tp']) when the two meshes are the dimensions of one (dp, tp) mesh covering the world. The frozen tp shards stay replicated over dp (fully_shard(ignored_params), torch 2.7+); FSDP2 shards the trainable LoRA DTensors over dp and reduces their tp Partial gradients itself. Refused: no mesh / a mesh that is not the dp dimension, shard_frozen, cpu_offload, torch < 2.7, and trainable per-head norms (their tp sum is a Parameter hook, and FSDP2 replaces the Parameters). - The trainable-weight agreement compares and broadcasts the local tensors of DTensor parameters. - Fused / packed layouts are also recorded on the owning module, so adapter saving and gathered grads keep the 1-GPU order after FSDP2 replaces the Parameter objects. - tp_clip_grad_norm_ handles 2-D gradients (each element counted once over its replicas). - native_clip_grad_norm_ counts FSDP2's _StridedShard as a shard dimension: newer torch does not report it as is_shard(), so those norms were not reduced over dp. - save_tp_adapter accepts a tp mesh smaller than the world when the dp dimension covers the rest.
The Trainer no longer refuses a model sharded by apply_tensor_parallel (tp only, or dp x tp after shard_model over mesh['dp']). tp_native.tp_trainer_setup runs around Trainer.__init__: - accelerate does not wrap the tp ranks in DDP (prepare_model keeps only the autocast wrap; native FSDP2 prepares a dp x tp model itself), - the dataloader is sharded over dp only, so the tp ranks of a replica read the same batches, - clip_grad_norm_ uses tp_clip_grad_norm_, and float16 gets a ShardedGradScaler (one inf decision for all ranks, initial scale divided by dp), - trainer.save_model() writes the standard 1-GPU adapter (collective), - the generated TRL trainers skip their trailing model.for_inference() (it would route the decoder layers onto decode paths outside the tensor parallel regions). The loss needs no change: the token count gathered over the world counts each replica's tokens tp times and the Trainer's loss scale multiplies by dp * tp, which FSDP2's mean over dp turns into the token mean over the dp replicas. Refused with a reason: Trainer checkpoints / resume, evaluation, bitsandbytes / paged / GaLore optimizers, DeepSpeed, accelerate FSDP / ParallelismConfig, iterable datasets, model_init, and a tp mesh that does not cover the world without shard_model over the dp dimension.
…A init on sharded_loading slices [skip ci]
…cheduler [skip ci]
…allel setup [skip ci]
…ral rules Found by sweeping every MODEL_FOR_CAUSAL_LM architecture (2 gloo ranks vs one process): - Gemma 3n MLP activation sparsity takes mean / std over the intermediate features: sharded, every rank used its own 1 / tp statistics (silent wrong loss and grads). MLP forwards (and the class helpers they call) that reduce over features or read the global intermediate size are now refused. - XGLM / MVP reshape the attention output with self.embed_dim and TrOCR with the input width read from hidden_states.size(): they crashed in the first forward after the model was sharded. Both reads are refused up front. - A decoder block shared by several layers (Zamba2 / ALBERT style) was sharded twice and crashed half way through the mutation. Shared regions are now sharded once; a weight shared by two projections is refused. - A structural qkv_proj is only taken as [q, k, v] blocks when the forward slices it by the key / value head count (Phi3); CodeGen's mp_num layout would otherwise be split wrongly once its MLP names are known. Generalisation: fc_in / fc_out / dense_h_to_4h / dense_4h_to_h / c_proj MLP names (GPT-J), q_layernorm / k_layernorm / query_layernorm / key_layernorm per-head norms checked by weight size (HunYuan, LFM2), scalar-parameter elementwise activations kept replicated with summed grads (Apertus xIELU), and decoder_layers as the layer count of decoder-only encoder-decoder configs.
… allow position tables - A block reused by layers on two stages (Zamba2 / ALBERT style) trained its LoRA as two independent copies (silent wrong grads). Trainable parameters shared across stages are now refused before the split. - Micro-batch losses are summed with num_items_in_batch over the whole batch; a causal LM forward that ignores it (BART / Whisper / TrOCR / MVP decoders: CrossEntropyLoss mean) would give n_microbatches times the loss. Forwards that neither name num_items_in_batch nor pass **kwargs to self.loss_function are refused. - Learned position / token-type tables before the layers (GPT-2 wpe, OPT / BART / Whisper embed_positions) are input-side parts like the embedding norm: their pre-layer output is replaced on later stages anyway. A wrapper holding only the decoder (OPTModel, BartDecoderWrapper) is no longer taken for an extra tower, and decoder_layers counts the layers of decoder-only encoder-decoder configs.
Two spawned 2-rank worlds (one per mode) cover GPT-J, HunYuan dense, LFM2 (conv layers replicated), Apertus and a shared decoder block training like one process under TP; Gemma 3n activation sparsity, XGLM, TrOCR and CodeGen refused with the model untouched; GPT-2 and OPT training like one process under PP; BART (per-call mean loss) and a block shared across stages refused with the model untouched. Every case fails on the parent branch.
… models before writing After apply_tensor_parallel each rank holds 1 / tp of the attention / MLP weights; after apply_pipeline_parallel the other stages' layers, embeddings and lm_head are zero-stride placeholders. unsloth_save_model wrote a shard-sized (TP) or all-zero (PP) checkpoint, and the generic merged path raised half way after writing files. Every export patch_saving_functions binds, and every writer behind them, now raises on every rank before anything is written and points to save_tp_adapter / PipelineParallel .save_adapter, then exporting on one GPU, as generate and for_inference already do.
tp_clip_grad_norm_ and _clip_over_world read float(total) and branched on it, one device to host sync per clip. They now scale every gradient (its local shard for DTensors) by clamp(max_norm / (total + eps), max = 1) like torch's clip_grad_norm_, and return the norm as a tensor. A coefficient of 1 leaves the gradients bitwise unchanged.
…ormers 4.x - TP and PP models: unsloth_save_model (merged_16bit, lora), save_pretrained_merged and the generic merged writer raise on every rank and write nothing (before: shard-sized or all-zero checkpoints, or a mid-way error after writing). A static check that every export bound by patch_saving_functions, and every writer behind them, is guarded first. - tp_clip_grad_norm_ / _clip_over_world under a guard that fails on any tensor float() / item() / bool(): a tensor norm, grads clipped to max_norm, unchanged when not clipping. - test_pp_native_gloo: reentrant checkpointing needs enable_input_require_grads with frozen embeddings; transformers 4.57's gradient_checkpointing_enable does not call it for a PEFT model, so both checkpointing parity tests failed in the one-process reference.
# Conflicts: # unsloth/models/_utils.py # unsloth/models/tp_native.py
…annot round to zero [skip ci]
…/unsloth into dh/s6-parallel-general [skip ci]
# Conflicts: # unsloth/models/tp_native.py [skip ci]
…er checkpoints and 8-bit AdamW UNSLOTH_TP_SIZE=k torchrun --nproc-per-node N script.py: the layout is read once (k divides the world, UNSLOTH_PP_SIZE > 1 refused), FastLanguageModel / FastModel.from_pretrained load 16-bit checkpoints through sharded_loading, get_peft_model applies apply_tensor_parallel over mesh['tp'], and Trainer.__init__ shards the dp dimension with native FSDP2 (UNSLOTH_FSDP2=1) or averages gradients over mesh['dp']. The Trainer on a tensor parallel model now writes per-rank checkpoints (local shards of the trainable weights and optimizer state) and resumes them on the same layout, and bitsandbytes Adam / AdamW step the local shards as under native FSDP2.
… 5.x mixed-grad clip, accelerate FSDP refusal - dp averaging agrees on which trainables have a gradient and zero-fills the missing ones, so every dp replica reduces the same buckets (an unrouted expert no longer desyncs the all-reduce). - transformers 5.x clips mixed DTensor / plain gradients in _mixed_mesh_grad_norm, bypassing the tensor parallel clip and the dp average: keep them on Accelerator.clip_grad_norm_. - UNSLOTH_TP_SIZE with UNSLOTH_FSDP2=1 that resolves to accelerate's FSDP is refused (the dp dimension would be neither sharded nor averaged). - broadcast of non-contiguous local shards goes through a dense copy.
|
@codex review |
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 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: Didn't find any major issues. You're on a roll. 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". |
|
Two separate things on this PR's latest CI:
|
…evice index as CUDA in the YaRN load check (#15351) ## Problem Two tests in the `Repo tests (CPU, rest)` shard fail on main itself, so every PR based on it inherits them (seen on #15326 and #15339). Both are test bugs; the product code they guard is fine. **1. `tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding`** ``` Pass encoding = "utf-8": ['tests/test_parallel_general_gloo.py:732: open()'] ``` #15230 added `test_every_whole_model_export_is_guarded`, which reads `unsloth/save.py` with a bare `open(...).read()`. That uses the locale encoding, which on Windows is the ANSI codepage. The read now names `encoding = "utf-8"` and closes the file. **2. `tests/test_yarn_rope_parameters_load.py::test_yarn_reaches_the_model[lang-*]`** ``` RuntimeError: Cannot access accelerator device when none is available. ``` #15214 added this subprocess check. It runs FastLanguageModel on a spoofed CUDA box and sends CUDA tensor allocations to the CPU through an `_is_cuda(device)` helper. The rotary embedding allocates with `device = get_current_device()`, which is a bare index (`0`). The helper called `torch.device(0)`, and on CPU-only torch 2.10 that resolves the index through the accelerator and raises before the YaRN assertion is reached. The `model` cases passed only because that path does not allocate with a bare index. A bare int is now treated as a CUDA ordinal without asking torch, and strings and `torch.device` values go through `torch.device(...)` as before. ## Verification - On main: `test_source_read_encoding.py` 1 failed and `test_yarn_rope_parameters_load.py` 2 failed. The yarn test also fails at #15214's own merge commit (801ba6d), and #15214 never ran a `rest` shard. - With this change: - `test_source_read_encoding.py`: 16 passed - `test_yarn_rope_parameters_load.py`: 5 passed - `test_parallel_general_gloo.py::test_every_whole_model_export_is_guarded`: passed - Sabotage: with FastLanguageModel's `_fold_rope_parameters` call replaced by `rope_scaling = None`, both `lang` cases now fail on the YaRN assertion itself (`{'type': 'linear', 'factor': 4.0, ...}`). Before this change they crashed first, so they could not catch a dropped YaRN.
# Conflicts: # unsloth/models/_utils.py # unsloth/models/loader.py [skip ci]
|
Merged main (conflicts with #15324 and #15225). Both sides kept: the DDP @codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
…oise is not amplified (#15381) ## Problem `Repo tests (CPU, gloo)` is red on main since #15326. Three tests fail locally and in CI (for example #15284): - `test_env_tp2_trainer_matches_one_process[sharded_16bit]` - `test_env_tp2_trainer_matches_one_process[full_load]` - `test_env_tp2_with_fsdp2_flag_and_no_dp_dimension` They fail like this: ``` comparison failed. Mismatched elements: 1 / 3: Max relative difference: 1.24e-05 Index | Obtained | Expected 2 | 0.3388126790523529 | 0.33881688117980957 +- 3.4e-06 ``` ## Product or test The test. I measured both arms (`tp = 2` against one process) step by step on main: | | step 1 | step 2 | step 3 | |---|---|---|---| | loss, relative gap | 0 | 0 | 0 | | grad norm, relative gap | 3.2e-7 | 1.6e-6 | 1.2e-5 | The worst LoRA tensor after the run (`layers.1.mlp.gate_proj.lora_B`) is 1.35e-4 off, while the rest sit near 2e-6. The losses match exactly and the first-step gap is fp32 reduction-order noise. The gap then grows about 10x per step, which is what `m / (sqrt(v) + eps)` does to near-zero LoRA gradients at the Trainer's default `adam_epsilon = 1e-8`. Changing only eps on both arms: | `adam_epsilon` | step-3 grad-norm gap | worst tensor | |---|---|---| | 1e-8 (default) | 1.24e-5 | 1.35e-4 | | 1e-5 | 5.3e-6 | 5.9e-6 | | 1e-4 | 9.4e-7 | 4.4e-7 | | 1e-3 | 1.2e-6 | 1.4e-7 | A tensor-parallel bug would not shrink with eps. This is the same effect #15264 fixed for the hand-written TP x FSDP2 loop. The new UNSLOTH_TP_SIZE Trainer tests share `_trainer_args`, which still used the default eps. ## Fix `_trainer_args` in `tests/test_tp_native_gloo.py`, used by both the native and the env-driven Trainer tests, now passes `adam_epsilon = _TRAINER_ADAM_EPS` (1e-4). A comment records the measurement. The tolerances (`rel = 1e-5` on grad norms, `rtol = 1e-4, atol = 1e-6` on the adapter state) are unchanged. ## Verification - `tests/test_tp_env_gloo.py` and `tests/test_tp_native_gloo.py` in full: 52 passed. On main, the three tests above fail. - Sabotage: with the backward all-reduce of the column-parallel input removed in `tp_native.py` (`return grad, None`), a real TP bug that leaves earlier layers with partial gradients, all three tests fail at `Max relative difference: 3.5e-4`, 35x over the tolerance. The looser eps does not hide a real TP error.
… exports, and reload cells under UNSLOTH_TP_SIZE (#15368) ## Summary Follows #15326 (merged). With `UNSLOTH_TP_SIZE=2 torchrun --nproc-per-node 2 script.py`, an unmodified notebook script trained, then stopped at its first post-training cell: - `FastLanguageModel.for_inference(model)`, `model.generate(...)` and `TextStreamer` were refused. - `model.save_pretrained("lora_model")`, `push_to_hub` and the merged / GGUF / torchao / OpenVINO exports were refused by #15230's `_model_parallel_refuses_save`. - The reload cell `FastLanguageModel.from_pretrained("lora_model")` had nothing to load. This PR makes those cells run under tensor parallel, for both the environment launch and the Python API (`apply_tensor_parallel`). Every rank still runs every cell, as in a one-process script. Pipeline parallel stays refused. Tensor parallel x native FSDP2 keeps its current behavior: its adapter save goes through the FSDP2 path, and generate / exports are refused with a message. Nothing changes for models that are not tensor parallel; every new branch starts with the existing dict-lookup marker check. ## How it works (new `unsloth/models/tp_replica.py`) **for_inference / generate.** Every rank gathers a whole single-GPU replica in place: - Sharded DTensor weights and LoRA factors are all-gathered back to full tensors, in the 1-GPU part order. - 4-bit weights get their packed codes all-gathered and are rebuilt with the 1-GPU `QuantState`. `apply_tensor_parallel` now keeps that state on the CPU, one byte per 64 weights, about 56 MB for Qwen3-4B. The replica is therefore bitwise the 1-GPU weight, double quantized absmax included. - The module state tensor parallel changed is switched back for as long as the replica is in: local head counts, per-module config copies, projection forwards, region hooks and the cached-forward guard. Unsloth's normal fast generate path then runs unchanged. Before each generate, tp rank 0's CPU and CUDA RNG states are copied to its tp group, so sampled text agrees across tp ranks. With DDP-style dp > 1, each tp group copies its own rank 0's state. The sharded parameters (the ones the optimizer holds) are kept and put back: - by `for_training` (the Unsloth trainer calls it at `train()`); - when a generate that gathered the replica itself returns (no `for_inference` before it); - before any forward that records gradients. The replica is gathered only when every rank has room for it. The check is the gathered bytes plus max(512 MiB, 10%) of headroom against free GPU memory. Otherwise every rank raises before anything changes, naming the rank without room and its numbers (format, numbers illustrative): ``` Unsloth: tensor parallel `for_inference` gathers a whole single-GPU replica of the model, but rank 1 needs 2.41 GiB more for it (+ 0.50 GiB headroom) and has 1.20 GiB free on its GPU. Free memory (e.g. del trainer; gc.collect(); torch.cuda.empty_cache()), or save the adapter with model.save_pretrained(...) and run this on one GPU. ``` **save_pretrained / push_to_hub (adapter).** The LoRA tensors are gathered to global rank 0, which runs the unchanged one-process save or upload. The other ranks wait on the rendezvous store, then return rank 0's return value, or raise rank 0's error. Using the store rather than an NCCL barrier means a long export or upload cannot trip the collective timeout or the NCCL watchdog. `UNSLOTH_TP_SAVE_TIMEOUT` defaults to 7 days. A tokenizer of a tensor parallel run is written the same way, by rank 0 while the others wait, so a reload cell never reads a half-written `tokenizer.json`. These tokenizers are marked by the `UNSLOTH_TP_SIZE` loader and by `apply_tensor_parallel` (the tokenizer Unsloth keeps on the model). The tensor parallel `Trainer.save_model` now makes that tokenizer call on every rank. **Merged / GGUF / torchao / OpenVINO exports.** `_model_parallel_refuses_save` now gathers the whole model to rank 0 for a tensor parallel model, then runs the existing single-process export there. The nested save calls inside the export write directly. The other ranks wait on the store, as above. The replica goes to rank 0's GPU when it fits there, otherwise to its CPU when it fits host RAM. If neither fits, the refusal with numbers is kept. LoRA-only writers gather the whole model too, because they run under `inference_mode`, where `state_dict()` cannot detach the frozen DTensor shards. **Reload cell.** Under `UNSLOTH_TP_SIZE`, loading a LoRA adapter (a local directory with `adapter_config.json`, or a Hub repo with one) loads in full on every rank instead of a sharded 16-bit load. 4-bit loads already did. After rank 0's save and the wait, every rank reads complete files. ## Tests New file `tests/test_tp_replica_gloo.py`: CPU gloo, tiny models, fp32, compared with one process holding the same weights (gathered with `tp_full_state_dict` after 2 tp training steps). - **Generate on the replica** (llama, llama with biases, qwen3, phi3 fused qkv, gemma2): - logits equal bitwise; - greedy tokens equal, batch of one and of two; - sampled tokens equal to one process seeded like tp rank 0, with each rank seeded differently first; - `for_training` puts the same parameter objects back, and the loss is bitwise unchanged; - a bare generate releases its replica; - a gradient forward after `for_inference` releases it, then trains the DTensor parameters. - **dp 2 x tp 2 (4 ranks).** Each tp group gathers its own replica and copies its own tp rank 0's RNG state. Groups sample differently from each other, and ranks agree within a group. - **QLoRA, nested and plain absmax.** The gathered weight has the 1-GPU codes bitwise and the 1-GPU QuantState (nested flag included). Its dequantized weight is bitwise equal, and greedy tokens are equal. After release, the logits equal the sharded run's bitwise. - **Adapter and tokenizer save.** Rank 0 sleeps 1.5 s before writing, and the other rank only returns once the files exist. Every file is byte-identical to a one-process `save_pretrained` (adapter, config, README, tokenizer files). The return value is the same on all ranks, and rank 0's error reaches every rank. Reloading the files with PEFT gives bitwise the trained logits. - **save_pretrained_merged (merged_16bit).** Every tensor is bitwise equal to a one-process merge. The model stays sharded afterwards. - **Refusals.** A replica that does not fit one rank's memory is refused on every rank, with the GiB numbers, and the model is left untouched. Pipeline parallel `for_inference` is still refused. - **Reload detection.** `UNSLOTH_TP_SIZE` reload detection for an adapter directory versus a base checkpoint. A/B on the RNG copy: with it disabled, rank 1's sampled tokens diverge from rank 0's after 5 tokens and the test fails. Updated tests, where the old asserts expected the removed refusals: - `test_tp_native_gloo.py`: - the guards test now expects `for_inference` / `generate` to gather on every wrapper level; - the parity cases call generate before training, so the parity asserts also cover the release; - `test_tp_env_gloo.py`: generate under the env launch now returns tokens; - `test_parallel_general_gloo.py`: tensor parallel exports now run on rank 0 only. Rank 1 writes nothing and shares rank 0's outcome. PP exports are still refused before writing; - `test_return_logits_survives_for_training.py`: the lifted `for_inference` guard is checked with PP. Results on CPU (gloo): | suite | torch 2.13 / tf 5.17 | torch 2.10 / tf 5.17 | torch 2.13 / tf 4.57.6 + TRL 0.22.2 | |---|---|---|---| | test_tp_replica_gloo, test_tp_native_gloo, test_tp_env_gloo, test_parallel_general_gloo, test_pp_native_gloo, test_return_logits_survives_for_training, test_fsdp2_save_coverage, test_tp_native_oracle | 181 passed, 1 skipped | 72 passed (subset) | 71 passed, 1 skipped (subset; the skip is the transformers 4.x StableLM refusal) | The torch 2.10 and 4.57.6 columns ran test_tp_replica_gloo, test_tp_env_gloo, test_parallel_general_gloo, test_return_logits_survives_for_training, and the guards / parity / QLoRA tests of test_tp_native_gloo. ## GPU (Kaggle T4 x2, torch 2.9.0, transformers 4.57.6, TRL 0.22.2) All runs ended with exit code 0. Each `UNSLOTH_TP_SIZE=2 torchrun --nproc-per-node 2` run was compared with the same script on one GPU, in the same kernel. The tables are from the commit before the last one, which only rewords the out-of-memory refusal and gathers each rank's free memory for it. At this PR's head, the Llama3.2 script and the same-adapter script were rerun, with the same results: greedy and sampled tokens equal to one GPU and across ranks, 146 merged tensors bitwise equal, the same GGUF sha256. **Notebook scripts.** These are `python_scripts` files, shortened to 3 steps on a 300-row slice. Three edits were made: - the reload cell switched to `if True`; - a probe before the save cell (64 greedy tokens, then 32 sampled tokens with a different seed on every rank); - the same probe at the end, on the reloaded model. Every other cell, including `TextStreamer` generation at the notebook's own sampling settings, ran unmodified. | | Qwen3_(4B)-Instruct (4-bit) | Llama3.2_(1B_and_3B)-Conversational (3B 4-bit) | |---|---|---| | losses, one GPU | 1.1559 / 1.3027 / 1.2466 | 0.6978 / 0.7962 / 0.9112 | | losses, TP 2 | 1.1561 / 1.3027 / 1.2473 | 0.6978 / 0.7963 / 0.9112 | | greedy (64 tokens) on the trained TP model vs the reloaded adapter | equal | equal | | greedy, rank 0 vs rank 1 | equal | equal | | greedy, TP 2 vs one GPU (each trained on its own) | first 29 tokens equal (the two trainings differ in the 4th loss digit) | equal | | seeded sampling, TP rank 0 vs rank 1 | equal; the reloaded model, which is not tensor parallel and samples with each rank's own seed, diverges between the ranks at token 29 | equal | | adapter directory vs one GPU | same 10 files and sizes, except tokenizer_config.json (see below) | same 7 files; every file but the weights and adapter_config.json byte-identical | In both scripts, `adapter_model.safetensors` has the same keys, dtypes and shapes as the one-GPU file. Its values differ by the trainings' rounding. `adapter_config.json` has the same size but a different hash. PEFT writes `target_modules` from a set, so the order changes between any two processes; three one-process saves on CPU give three orders. An earlier run of the same scripts, at the first commit of this PR, matched one GPU for all 64 Qwen3 greedy tokens. **Same adapter, TP 2 vs one GPU.** A small script with Llama-3.2-1B-Instruct 4-bit and adamw_8bit trains 3 SFT steps under TP 2, then calls: - `for_inference` and greedy generate; - `save_pretrained`; - `save_pretrained_merged("merged_16bit")`; - `save_pretrained_gguf("q8_0")`; - the reload cell. One GPU then loads the adapter TP 2 wrote and runs the same generate and exports. | check | result | |---|---| | greedy (64 tokens): TP 2 replica, TP 2 reload, one GPU | all three equal | | merged_16bit safetensors | 146 tensors bitwise equal | | GGUF q8_0 | same file sha256 (1,321,082,784 bytes, 147 tensors equal) | | rank 1 during rank 0's GGUF export | waited 78.7 s on the store, no NCCL timeout | ## Not covered here, and known differences **Qwen3 script, saved padding side.** Under TP 2 this script's `tokenizer_config.json` records `padding_side` "right"; on one GPU it records "left". - The script never calls `for_inference`. Under TP 2 the model is still in training mode when its save cell runs (the probe prints `training True`); on one GPU it is in inference mode. - That state is decided before any code from this PR runs. Unsloth's train wrapper restores the training flag the model had before `trainer.train()`. The cause on the #15326 training path is not identified yet. **Not run on a GPU:** - 16-bit (sharded loading) generate / exports (on CPU gloo, the `UNSLOTH_TP_SIZE` Trainer test on a sharded 16-bit load now runs generate, without a token comparison); - `FastModel` / vision models (Gemma 3); - `push_to_hub` (no Hub writes from tests); - the CPU fallback of an export replica (the GPU replica fit everywhere here). The adapter and merged paths that `push_to_hub` and the CPU fallback reuse are covered on CPU gloo. **Out of scope or unchanged:** - 4 and 8 GPU layouts ran on CPU gloo only (dp 2 x tp 2), since Kaggle has 2 GPUs. - Tensor parallel x native FSDP2: generate / exports are refused, and the adapter save is unchanged. - Pipeline parallel post-training cells and vLLM / GRPO under tensor parallel are separate work. **Every rank must make the collective calls.** A save called on rank 0 only, inside `if rank == 0:`, waits for the other ranks' part of the gather. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Summary
Tensor parallelism (TP v2) was Python API only:
apply_tensor_parallel,load_tensor_parallel/sharded_loading,tp_trainer_setup. This PR lets an unmodified training script use it from the environment, the same way native FSDP2 is used today:It also closes the Trainer gaps that the notebook scripts hit by default:
optim = "adamw_8bit"is used in 137 of 170 scripts.save_strategyis left at the HF default"steps"in 155 of 170.How the environment is applied
The layout is read once, in the new
unsloth/models/tp_env.py.Validation happens before any model is touched:
UNSLOTH_TP_SIZEmust be an integer of at least 1 that dividesWORLD_SIZE.UNSLOTH_PP_SIZE > 1is refused. The message says pipeline parallelism needs the Python API until Trainer support lands.UNSLOTH_TP_SIZEunset or 1 makes every hook a no-op.Mesh: with dp = 1 the mesh is 1-D
("tp",). Otherwise it isinit_device_mesh(dev, (dp, tp), ("dp", "tp")), checked withpp_native.check_mesh_composition. If torchrun has not created the process group yet, this creates it (nccl afterset_device(LOCAL_RANK)on CUDA, gloo on CPU), and accelerate reuses it.Hooks, in this order: split, then tp, then FSDP2.
FastLanguageModel.from_pretrained/FastModel.from_pretrained(decorator):sharded_loading(mesh["tp"]), so each rank reads only its slices of the attention / MLP projections.get_peft_model.UNSLOTH_TP_SHARDED_LOAD=0forces full loads.get_peft_model(both loaders):apply_tensor_parallel(model, mesh["tp"])runs once LoRA is attached, so LoRA is full size with the 1-GPU init. Its refusals are re-raised namingUNSLOTH_TP_SIZE.Trainer.__init__: tensor parallel is applied ifget_peft_modeldid not do it. For dp > 1:UNSLOTH_FSDP2=1, native FSDP2 shards overmesh["dp"](FSDP2Config.mesh) instead of refusing the tp model.mesh["dp"]before clipping, or at the optimizer step when there is no clipping. Trainables are broadcast from dp rank 0 first. torch DDP itself cannot wrap DTensor parameters._tensor_parallel_trainer_premoved after the native FSDP2 pre-shard, because its world-size check needs the dp mesh.Trainer on a tensor parallel model
These changes apply to the Python API path too.
Checkpoints. Each rank writes
checkpoint-N/unsloth_tp/rankNNNNN.pt. It holds:The scheduler, scaler, RNG and trainer state are written by the Trainer as before.
save_modelstill writes the 1-GPU adapter.Resume restores the same layout exactly. A different world size, tp size or dp mode is refused before anything is loaded. These overrides are set per Trainer instance, so they win over native FSDP2's class-level hooks; the full-state gathers in those hooks do not restore the packed tp part order.
bitsandbytes Adam / AdamW (
adamw_8bit,paged_adamw_8bit,adamw_bnb_8bit,paged_adamw_32bit) step each DTensor's local shard with the existingfsdp2_bnb_optimlocal-shard optimizer, as under native FSDP2. WithUNSLOTH_FSDP2_BNB_LOCAL=0, they switch to torch AdamW instead. Other bitsandbytes optimizers either switch to their torch equivalent or are refused.dp averaging follows DDP:
None.transformers 5.x clipping fix: 5.x clips mixed DTensor / plain gradients itself in
_mixed_mesh_grad_norm, for examplemodules_to_savenext to the LoRA DTensors. That path bypasses the tensor parallel clip and the dp average, so those gradients now stay onAccelerator.clip_grad_norm_.Kept refusals (their messages now name
UNSLOTH_TP_SIZEunder an env launch):evaluate/predictload_best_model_at_end,push_to_hubUNSLOTH_FSDP2=1that resolves to accelerate's FSDP (refused: the dp dimension would be neither sharded nor averaged)Generation,
for_inferenceand merged / GGUF exports under TP are unchanged and still refused.Tests
tests/test_tp_env_gloo.py: CPU gloo with a tiny Llama, fp32, compared with one process.UNSLOTH_FSDP2=1with tp = world: FSDP2 is skipped, and the result matches one process.tests/test_tp_native_gloo.py:modules_to_saveTrainer test now also asserts grad-norm parity, which failed on transformers 5.x before the clip fix.Versions: torch 2.10 / 2.13 / 2.14 with transformers 5.17, and torch 2.13 with transformers 4.57.6 + TRL 0.22.2.
Results on CPU (gloo):
(1) The failures and their reruns:
test_tp2_matches_one_process[stablelm]hit the gloo 120 s receive timeout once, on a heavily loaded host. It passes when rerun alone, and this PR does not touch that path.test_trainer_splits_mixed_optimizer_groups_for_tp_onlyfailed its new grad-norm assert at rel 1e-5, which is tighter than the one-process reference's fp32 norm (about 2e-4 off, as noted for clip_grad_norm_ elsewhere in that file). At rel 1e-3 it passes on torch 2.13 with transformers 5.17 and with 4.57.6.The transformers 5.x clip fix was checked differentially. Without it, the mixed-group test's grad norms are 2-3% off the one-process run (0.9096 / 0.7698 / 0.8810 vs 0.8903 / 0.7725 / 0.9082). With it, they agree within 2e-4 (the fp32 reference band).
GPU (Kaggle T4 x2, torch 2.9.0, transformers 4.57.6, TRL 0.22.2)
All runs use unmodified notebook
python_scriptsshortened to 3 steps over a 300-row slice. The Qwen3 4-bit and resume runs used this PR's head. The 16-bit Qwen3, Llama and Gemma runs used its first commit; the later commits change only the dp > 1 averaging, the transformers 5.x clip route and the accelerate FSDP refusal, none of which these tp-only runs on 4.57.6 reach. The comparisons areUNSLOTH_TP_SIZE=2 torchrun --nproc-per-node 2against the same script on one GPU, in the same kernel.load_in_4bit = False(16-bit, sharded load)Per-script notes:
adamw_8bitstayed bitsandbytes AdamW, stepping the local shards; there was no switch to torch AdamW.output_dir. Its end-of-training checkpoint (save_strategy"steps", the HF default) was written under TP 2. The others leaveoutput_dirunset, and Unsloth then setssave_strategy = "no".load_in_4bit = Falsechanged. No unmodified notebook runs plain Qwen3 4B SFT in 16-bit. The QAT notebook passesqat_schemetoget_peft_model, where tensor parallelism refuses QAT fake-quantized projections; that path was not run here, and that script fails on T4 even on one GPU.model.generate/FastLanguageModel.for_inference). That is the existing tensor parallel refusal; generation under TP is a follow-up.GPU checkpoint resume: a notebook-style SFT with Llama 3.2 1B 4-bit, LoRA and adamw_8bit, saving every step, then a fresh model resumed from checkpoint-1.
unsloth_tp/rank00000.ptandrank00001.pt.Not covered here
for_inference, adaptersave_pretrained/ merged / GGUF exports under TP.