Repository navigation
TP / PP: every causal LM architecture trains like one process or is refused up front - #15230
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
|
@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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0016cecaec
ℹ️ 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".
| for p in params: | ||
| g = p.grad | ||
| local = g.to_local() if _is_dtensor(g) else g | ||
| local.mul_(coef.to(device = local.device, dtype = local.dtype)) |
There was a problem hiding this comment.
Keep the clipping coefficient in FP32
For FP16 gradients, casting the clipping coefficient to local.dtype before multiplication can underflow it to zero and silently erase all gradients. For example, one million finite FP16 gradient entries of 60000 have a norm of approximately 6e7; with max_norm=1, the coefficient is approximately 1.67e-8, which rounds to zero in FP16, although the correctly clipped entries (approximately 0.001) are representable. This affects both TP clipping paths using this helper. Move the coefficient to the gradient's device without narrowing its dtype, preserving the previous scaling accuracy while avoiding host synchronization.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the latest push: the coefficient stays fp32, and fp16 / bf16 gradients are scaled in fp32 and copied back (a device tensor multiplied into an fp16 gradient is cast to fp16 first, so keeping the coefficient fp32 alone does not help on CUDA). Still no host sync. Your example is a new test: 60000 fp16 gradients with a total norm of 6e7 and max_norm = 1 now clip to 1e-3 instead of 0; a coefficient of 1 still leaves gradients bitwise unchanged.
…annot round to zero [skip ci]
|
@codex review |
…/unsloth into dh/s6-parallel-general [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
# Conflicts: # unsloth/models/tp_native.py [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
…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.
… 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>
Follow-up to #15174 (tensor parallelism v2) and #15175 (pipeline parallelism v1). It runs TP and PP over every causal LM architecture transformers 5.17 knows (178 in
MODEL_FOR_CAUSAL_LM_MAPPING). The goal: every architecture either trains like one process or is refused before the model is touched, never a crash halfway through, silently wrong numbers or a partly mutated model.Sweep result
Tiny random-weight copies of each architecture's default config, CPU gloo, 2 ranks, fp32, LoRA r=4, compared against one process (rtol 1e-4). A refusal only counts as clean if parameters, buffers, module tree, hooks, markers and
requires_gradare unchanged.20 model types had no buildable tiny model. Four deliberately broken variants of the code (no all-reduce, mutate-then-refuse for TP and PP, a 1% PP loss scale) were all caught.
Fixes
self.embed_dimor with the width read fromhidden_states.size(). Both patterns are now refused up front.num_items_in_batch, so the summed micro-batch loss was n_microbatches times too large. A forward that neither namesnum_items_in_batchnor passes**kwargstoloss_functionis refused.qkv_projwould have been split as [q, k, v] blocks; a structuralqkv_projmust now be sliced bynum_key_value_heads * head_dimin its forward.save_tp_adapter/pp.save_adapterand a single-process export.tp_clip_grad_norm_usedfloat(total)and a Python branch, one host sync per clip. It now scales with a tensor clamp (astorch.nn.utils.clip_grad_norm_does) and returns a tensor; a coefficient of 1 leaves gradients bitwise unchanged.Newly supported
fc_in/fc_out,dense_h_to_4h/dense_4h_to_h), HunYuan dense and LFM2 (per-head q / k layernorms), Apertus (scalar xIELU parameters replicated).Still refused (and what support would need)
MoE (expert sharding or expert parallelism, plus the router aux loss across PP stages), MLA (shard
q_b_proj/kv_b_projby heads), hybrid linear-attention stacks under PP (mixed layer classes; TP already passes with those layers replicated), fused-qkv layouts such as Bloom / Falcon / MPT / GPT-2c_attn(layout rules from the forward's view shape, ALiBi slopes per local head), full-width q / k norms such as OLMo2 / 3 (a distributed RMSNorm).Tests
New
tests/test_parallel_general_gloo.py, 26 tests, parametrised over the swept architectures (about 20 s). All fail on main and pass here. Existing suites:test_tp_native_gloo.py+test_tp_native_oracle.py86 passed, 1 skipped;test_pp_native_gloo.py22 passed. The PP checkpointing tests also pass on transformers 4.57.6 / PEFT 0.18 / torch 2.10.Not covered: GPU (NCCL, bf16 / fp16, 4-bit QLoRA sharding, Unsloth's fast forwards and fused kernels, torch.compile), sizes beyond tp=2 / pp=2, multi-node. The export refusal is exercised on CPU with HF + PEFT models; GGUF / torchao / OpenVINO are covered by a check that every entry point carries the guard.