Skip to content

Tensor parallel: generate, adapter / tokenizer saves, merged and GGUF exports, and reload cells under UNSLOTH_TP_SIZE - #15368

Merged
danielhanchen merged 55 commits into
mainfrom
dh/s7-tp-post-training
Oct 26, 2026
Merged

danielhanchen merged 55 commits into
mainfrom
dh/s7-tp-post-training

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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:

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".

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.

danielhanchen and others added 30 commits October 24, 2026 15:19
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.
…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
# 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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 6735a2995c

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member Author

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 tests/test_tp_world_save_dirs_gloo.py fails on the previous head and passes now; test_tp_replica_gloo.py still passes (16 passed together).

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth/models/tp_replica.py Outdated
Comment on lines +616 to +617
if where is not None and (not rest or rest[0] != where):
return call()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment thread unsloth/models/tp_replica.py Outdated
Comment on lines +615 to +620
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth/models/tp_replica.py Outdated
Comment on lines +667 to +668
save_pretrained.__name__ = "unsloth_tp_world_save_pretrained"
d["save_pretrained"] = save_pretrained

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 495d4d9c02

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen
danielhanchen merged commit 78b2f82 into main Oct 26, 2026
18 of 38 checks passed
@danielhanchen
danielhanchen deleted the dh/s7-tp-post-training branch October 26, 2026 22:54
danielhanchen added a commit that referenced this pull request Oct 27, 2026
`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 |
danielhanchen added a commit that referenced this pull request Oct 27, 2026
…#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.
danielhanchen added a commit that referenced this pull request Oct 27, 2026
…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 |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant