Repository navigation
Tensor parallel: generate, adapter / tokenizer saves, merged and GGUF exports, and reload cells under UNSLOTH_TP_SIZE - #15368
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.
|
Codex Review: Didn't find any major issues. 👍 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". |
…ory or host writes its own copy [skip ci]
|
Follow-up in d16def8: a tokenizer / processor world save now records rank 0's (host, directory). A rank whose own target differs (per-rank folders, node-local disks on another host, or a save rank 0 made alone) writes its own copy as without tensor parallel, instead of returning without a file. New @codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d16def8d7d
ℹ️ 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".
| if where is not None and (not rest or rest[0] != where): | ||
| return call() |
There was a problem hiding this comment.
Guard nested saves during the nonzero-rank fallback
When a processor saves to per-rank directories or node-local storage on another host, this fallback invokes its original save without setting _ACTIVE. The processor's nested tokenizer is also marked by mark_world_save, so its save_pretrained enters another tp_world_save and waits for the next world key. Rank 0 skips that nested rendezvous because its _ACTIVE guard is set, so it never publishes that key for this save. The nonzero rank consequently hangs until the save timeout (seven days by default), rather than writing its local processor/tokenizer copy. Run the local fallback under the same nested-save guard used by rank 0.
Useful? React with 👍 / 👎.
| status, value, *rest = _wait(key) | ||
| if where is not None and (not rest or rest[0] != where): | ||
| return call() | ||
| if status != "ok": | ||
| raise RuntimeError(f"Unsloth: tensor parallel `{what}` failed on rank 0: {value}") | ||
| return value |
There was a problem hiding this comment.
Match world-save generations after rank-zero-only saves
If rank 0 saves a tokenizer alone and every rank subsequently saves that tokenizer to the same directory, their world counters are offset: rank 0 publishes the second save under key 2, while another rank reads the already-completed key 1. Because the host and directory match, that rank immediately returns the previous save's result without waiting for the current write. A reload can therefore read stale tokenizer state or files while rank 0 rewrites them. The new directory comparison only handles this counter mismatch when the target changes; repeated saves to the same target also need a way to distinguish the current save generation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 143dbc9 by removing the rendezvous for these saves instead of patching the counter. Tokenizer / processor world saves now need no cross-rank agreement: every rank writes into a private temporary directory next to the target and moves each file in with os.replace (atomic per file, same bytes on every rank), then returns once its own files are in place. A save rank 0 made alone cannot offset a later one, and no rank can return an earlier save's result. Uploads (push_to_hub, save_pretrained(push_to_hub = True)) go out from global rank 0 only, also without a rendezvous. test_tp_world_save_dirs_gloo.py now covers a shared directory, per-rank directories, and a rank-0-only save followed by a world save of changed tokenizer state to the same directory: the previous head returned the old state on rank 1 (model_max_length 111 instead of 222), this head passes. TP / PP / export suite: 184 passed, 1 skipped; transformers 4.57.6 + TRL 0.22.2 subset: 75 passed, 1 skipped.
…te copy and moves it in with os.replace; uploads on rank 0 only [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 143dbc9c80
ℹ️ 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".
| save_pretrained.__name__ = "unsloth_tp_world_save_pretrained" | ||
| d["save_pretrained"] = save_pretrained |
There was a problem hiding this comment.
Preserve processor picklability when wrapping saves
When a tensor-parallel run uses a processor with a spawn-based DataLoader, assigning this local closure to the processor makes the processor—and any data collator holding it—unpicklable. Worker startup then fails with AttributeError: Can't get local object 'mark_world_save.<locals>.save_pretrained', before training begins. This also affects unwrapped tokenizers passed through this branch. Use a picklable wrapper, following the existing _TokenizerBoundMethod approach in unsloth/save.py, rather than storing a nested function on the instance.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 0158da2. mark_world_save now stores _TokenizerBoundMethod(unsloth_tp_world_save_pretrained, obj, "save_pretrained") (the same picklable bound wrapper unsloth/save.py uses for tokenizer saves) instead of a nested function; the wrapper calls the object's own save (an instance-level one kept as _unsloth_tp_inner_save, else the class method). A pickled processor or collator unpickles with the plain class save_pretrained, so spawn workers need nothing from the wrapper. New test_marked_processor_stays_picklable fails on the previous head with AttributeError: Can't get local object 'mark_world_save.<locals>.save_pretrained' and passes now; test_tp_world_save_dirs_gloo.py + test_tp_replica_gloo.py: 17 passed.
…picklable bound method, not a closure [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0158da2037
ℹ️ 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".
| f"Unsloth: tensor parallel `{what}`: the whole model ({_gib(kept)}) does not fit " | ||
| f"{device} ({_gib(free)} free); gathering it to the CPU instead." | ||
| ) | ||
| return items, torch.device("cpu") |
There was a problem hiding this comment.
Use a CPU-capable merge writer for CPU replicas
On a CUDA run with a double-quantized NF4 model, if rank 0 has enough GPU memory for gather workspace but not the retained replica, this fallback moves the packed weights and quantization state to CPU. However, the newly enabled unsloth_save_model(..., save_method="merged_16bit") path still calls _merge_lora (unsloth/save.py:1759), which calls fast_dequantize. Its CUDA implementation invokes Triton kernels and then falls back to _fast_dequantize_ctypes, which requests a CUDA stream using the CPU tensor's device index. Consequently, this export fails despite passing the fallback memory check. Select a CPU-capable dequantizer for this writer, or stage each projection onto the GPU before merging it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 495d4d9. A CPU-staged 4-bit export replica now tags each rebuilt weight with the GPU it came from, and _merge_lora moves only that projection (packed weight, quant state, LoRA A/B) to that GPU, dequantizes and merges there with the same kernels as the GPU replica path, then returns the merged weight on the CPU. The CPU fallback's memory check now also budgets one projection's merge on the GPU. Untagged weights (every non tensor parallel merge and the GPU replica path) are unchanged.
New test tests/test_tp_replica_cpu_stage_cuda.py asserts every dequantize the merge runs gets CUDA tensors and that the result is bitwise equal to the same merge done on the GPU replica: 4/4 fail on the previous head, 4/4 pass now.
…e GPU it came from, back to the CPU [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. 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". |
…s own c10d store [skip ci]
[skip ci]
|
@codex review |
`Repo tests (CPU, studio)` fails on main in `tests/python/test_accelerator_skip_guards.py`, which keeps tests from reading a probe that `tests/_zoo_aggressive_cuda_spoof.py` patches to True for the whole session: - `test_no_skip_guard_reads_a_spoofable_accelerator_probe`: `test_fsdp2_bnb_optim_sync.py:95: torch.cuda.is_available()` (from #15384). The skip guard now uses `has_real_cuda()` from `tests/_shared/real_accelerator.py`, like the other root tests. - `test_no_test_lets_a_loader_infer_the_device_from_a_spoofed_probe`: `test_tp_replica_gloo.py:257: PeftModel.from_pretrained() with no torch_device=` (from #15368). This is a gloo CPU test, so the reload passes `torch_device = "cpu"`. Test-only change. | check | main | this PR | |---|---|---| | `tests/python/test_accelerator_skip_guards.py` | 2 failed | passed | | `test_accelerator_skip_guards.py` + `test_fsdp2_bnb_optim_sync.py` + `test_tp_replica_gloo.py` (CPU) | | 44 passed, 1 skipped |
…#15493) ## Problem `Repo tests (CPU, rest)` fails on main since #15368, so every PR based on it inherits 8 failures (#15474, #15475, #15479, #15480, #15481 and others): ``` tests/test_for_training_generation_flag.py::test_for_training_deletes_a_generation_flag_delegated_by_a_peft_wrapper[llama.py-FastLlamaModel] unsloth/models/llama.py:5526: in for_training _tensor_parallel_for_training(model) E TypeError: 'NoneType' object is not callable ``` All 8 parametrizations fail the same way, for `llama.py` and `vision.py`. ## Product or test The test. It lifts `for_training` out of `llama.py` / `vision.py` with `ast` and runs it in a namespace where any name it did not lift resolves to `None`. From `_utils.py` it lifted a hardcoded list of ten helpers. #15368 made `for_training` call a new `_utils` helper, `_tensor_parallel_for_training`, which is not on that list, so the lifted code called `None`. `for_training` itself is fine: the helper only restores the sharded parameters on a tensor-parallel model and does nothing otherwise. ## Fix The hardcoded list stays as roots. On top of it, the test now lifts every `_utils.py` function that `for_training` or those helpers reach by name, transitively, with the same walk it already used for helpers in the model file (factored into `_closure`). A helper added later is lifted the same way instead of turning into `None`. ## Verification - `tests/test_for_training_generation_flag.py`: 8 passed (8 failed on main). - Sabotage: - With `del m._flag_for_generation` replaced by `pass` in `llama.py` (the behaviour this test guards), 2 fail, so the guard still bites. - With `_tensor_parallel_for_training` made to raise, 6 fail. The lifted helper is the real one and actually runs, not a stand-in. - ruff format and check are clean.
…harness (#15498) `tests/test_for_training_generation_flag.py` fails on main, in the `Repo tests (CPU, rest)` job (all 8 cases): ``` unsloth/models/llama.py:5526: in for_training _tensor_parallel_for_training(model) E TypeError: 'NoneType' object is not callable ``` Since #15368, `for_training` calls `_tensor_parallel_for_training(model)` first. The test compiles `for_training` out of `llama.py` with a fixed set of `_utils.py` helpers into its own namespace, and that helper is not one of them. These tests have no tensor parallel world, so the namespace now gets a no-op for it. Test-only change. | | main | this PR | |---|---|---| | torch 2.13 / transformers 5.17 | 8 failed | 8 passed | | torch 2.6 / transformers 4.57.6 | | 8 passed |
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(...)andTextStreamerwere refused.model.save_pretrained("lora_model"),push_to_huband the merged / GGUF / torchao / OpenVINO exports were refused by TP / PP: every causal LM architecture trains like one process or is refused up front #15230's_model_parallel_refuses_save.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:
QuantState.apply_tensor_parallelnow 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.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:
for_training(the Unsloth trainer calls it attrain());for_inferencebefore it);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):
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_TIMEOUTdefaults 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 theUNSLOTH_TP_SIZEloader and byapply_tensor_parallel(the tokenizer Unsloth keeps on the model). The tensor parallelTrainer.save_modelnow makes that tokenizer call on every rank.Merged / GGUF / torchao / OpenVINO exports.
_model_parallel_refuses_savenow 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, wherestate_dict()cannot detach the frozen DTensor shards.Reload cell. Under
UNSLOTH_TP_SIZE, loading a LoRA adapter (a local directory withadapter_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 withtp_full_state_dictafter 2 tp training steps).for_trainingputs the same parameter objects back, and the loss is bitwise unchanged;for_inferencereleases it, then trains the DTensor parameters.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.for_inferenceis still refused.UNSLOTH_TP_SIZEreload 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:for_inference/generateto gather on every wrapper level;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 liftedfor_inferenceguard is checked with PP.Results on CPU (gloo):
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 2run 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_scriptsfiles, shortened to 3 steps on a 300-row slice. Three edits were made:if True;Every other cell, including
TextStreamergeneration at the notebook's own sampling settings, ran unmodified.In both scripts,
adapter_model.safetensorshas the same keys, dtypes and shapes as the one-GPU file. Its values differ by the trainings' rounding.adapter_config.jsonhas the same size but a different hash. PEFT writestarget_modulesfrom 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_inferenceand greedy generate;save_pretrained;save_pretrained_merged("merged_16bit");save_pretrained_gguf("q8_0");One GPU then loads the adapter TP 2 wrote and runs the same generate and exports.
Not covered here, and known differences
Qwen3 script, saved padding side. Under TP 2 this script's
tokenizer_config.jsonrecordspadding_side"right"; on one GPU it records "left".for_inference. Under TP 2 the model is still in training mode when its save cell runs (the probe printstraining True); on one GPU it is in inference mode.trainer.train(). The cause on the Tensor parallel from UNSLOTH_TP_SIZE for unmodified training scripts, with Trainer checkpoints and 8-bit AdamW #15326 training path is not identified yet.Not run on a GPU:
UNSLOTH_TP_SIZETrainer 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 adapter and merged paths that
push_to_huband the CPU fallback reuse are covered on CPU gloo.Out of scope or unchanged:
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.