Skip to content

Train a model the planner split across cards, instead of dying in index_select - #9995

Merged
danielhanchen merged 20 commits into
mainfrom
fix/tied-embedding-dispatch-hook
Aug 31, 2026
Merged

danielhanchen merged 20 commits into
mainfrom
fix/tied-embedding-dispatch-hook

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The problem

On a machine with two or more GPUs, FastLanguageModel.from_pretrained fails to train with a message about tensors:

RuntimeError: Expected all tensors to be on the same device, but got index is on
cuda:0, different from other tensors on cuda:1
(when checking argument in method wrapper_CUDA__index_select)

This is the default path, not an opt-in one. requested_device_map upgrades the untouched default to the "unsloth" planner, so anyone with 2 cards and no device_map gets a split without asking. Measured on 2x Tesla T4 with unsloth/Qwen3-0.6B in 4bit, the planner's map is:

model.layers.0 .. 29  -> 0        model.norm -> 0     model.rotary_emb -> 0
model.embed_tokens    -> 1        lm_head    -> 1

accelerate.dispatch_model then hooks 395 modules and not model.embed_tokens, because Qwen3-0.6B has tie_word_embeddings = True and dispatch skips tied weights: a tied parameter is reachable under more than one name. So the two modules the planner deliberately moved are the two with nothing to move their inputs after them, and llama.py's self.embed_tokens(input_ids) gets ids on cuda:0 against a weight on cuda:1.

The same model at device_map = {"": 0} trains fine, and UNSLOTH_AUTO_DEVICE_MAP=0 also trains fine because it keeps everything on one card. Neither is discoverable from the error.

The fix

_repair_tied_module_hooks re-attaches an AlignDevicesHook to any module the model's own hf_device_map names that ended up without one. It repairs only what the map already placed, skips any module that has a hook, skips cpu / disk entries (offload is a different mechanism with hooks of its own), and does nothing at all on a single-device map.

Placement is the whole fix, and the hook count does not show it

Three placements, same model, same seed, on 2x Tesla T4:

repair runs hooked trains loss
at load only (before this PR) 395 no, index_select -
after post_patch 397 yes 2.6619460582733154
after everything from_pretrained does 397 yes 2.662875493367513

The single-card loss is 2.662875493367513. The middle row trains, produces a plausible number, and is not the same training - post_patch is still too early because the QKV/MLP patching below it replaces the forwards the hook wrapped. Both working placements report 397 hooks, so a hook count cannot tell them apart. Only the loss can.

On hardware

2x Tesla T4, sm_75, torch 2.10.0+cu128, four arms per round, two Kaggle accounts in parallel.

unsloth/Qwen3-0.6B 4bit unsloth/Qwen3-4B-Base 4bit
params per card 309 / 1 242 / 156
memory per card - 1791 / 1482 MiB
loss, split 2.662875493367513 3.0040088494618735
loss, single card 2.662875493367513 3.0040088494618735
identical yes, delta 0.0 yes

So a split model now trains, and trains identically to one that fits on a single card.

What it does not change

  • DDP is untouched. The repair reads the model's own hf_device_map; each rank holds the whole model on its own device, so there is nothing to repair.
  • A single-device map returns immediately, which is the overwhelmingly common case.
  • offload_embedding is left alone. _embedding_dispatch_device reads the embedding's hook to decide where to re-send the ids after the offload pre-hook has already sent them to the CPU weight; a hook naming a card would answer that with the wrong device. The repair is behind if not offload_embedding, and a test asserts that guard from the caller's AST.
  • A failed attach warns rather than being counted. init_hook moves the module's tensors, so a map naming a device the machine lacks lands there; counting it as repaired would leave the original crash in place and hide the reason.

Tests

tests/test_tied_module_dispatch_hooks.py, 9 rules. They run the real function against stub modules rather than asserting on a hand-written dict. init_hook moves tensors to the execution device, so the far device is meta - real on every machine, so the attach is exercised on a GPU-less runner - and the integer to cuda:N conversion is checked separately against a captured hook.

Six mutations, each caught: never repairing (6 failed), re-hooking an already-hooked module (2), hooking cpu/disk (1), leaving a bare int unconverted (1), not skipping a single-device map (1), and counting a failed attach as repaired (1).

tests/test_unsloth_device_map_*.py plus the new file: 3237 passed.

A model split across cards loses its hook on any TIED weight: dispatch_model
moves the tensor but installs no AlignDevicesHook, because a tied parameter is
reachable under more than one name. On a tie_word_embeddings model the planner
puts embed_tokens and lm_head on the second card, so the two modules it
deliberately moved are the two with nothing to move their inputs after them.

Measured on 2x Tesla T4 with unsloth/Qwen3-0.6B in 4bit: 395 modules carried a
hook, embed_tokens did not, and training died at the first embedding lookup
with a message about tensor devices rather than about placement. The same run
with device_map={"": 0} trains, so the split is what breaks it, and this is
the default a 2-GPU box now gets since requested_device_map upgrades the
untouched default to the planner.

Repairs only names the model's own hf_device_map already carries, skips any
module that has a hook, and does nothing at all on a single-device map.
`_embedding_dispatch_device` reads the embedding's hook to decide where to
re-send the ids after the offload pre-hook has already sent them to the CPU
weight. Adding a hook there would answer that question with the card the map
named rather than the CPU the offload uses, so the repair now runs only when
offload_embedding is off. It stays ahead of the bnb gate, since the tied-weight
hole is not a quantization property.
The attach at load runs while the model is still the one transformers
returned. post_patch rebuilds and re-ties parts of it, and a hook on a tied
module does not survive that, so the repair has to run again once the model is
final.

Measured on 2x Tesla T4, unsloth/Qwen3-0.6B in 4bit, the planner's own map
putting embed_tokens and lm_head on the second card: after from_pretrained 395
modules carried a hook and embed_tokens did not. Calling the repair at that
point attached 2 and the same split then trained to 2.662875493367513, which is
the single-card loss to the last digit.

Idempotent, so the attach at load keeps whatever it placed.
post_patch was still too early. The QKV/MLP patching below it replaces the
forwards the hook wrapped, and on 2x Tesla T4 the same 3 steps then came out at
2.6619460582733154 against the single-card 2.662875493367513 -- trained, but
not the same training. Attaching once nothing further is rewrapped reproduces
the single-card loss exactly.

The hook count is the same either way, 397, so a count is not what distinguishes
these two placements. The loss is.
@danielhanchen
danielhanchen requested a review from Datta0 as a code owner August 30, 2026 05:08
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-08-30T20:37:54.522516Z 9046a07 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

Repo tests (CPU) went red on this PR's own file: the tests used device 0 for
the near entry, and attaching a cuda hook needs a card, which that runner does
not have. The far device is meta, which is real everywhere, and cpu now stands
in for a module the repair must leave alone.

One of them had gone vacuous in the process. The single-device map test used
entries that cannot attach on a CPU runner, so removing the early return
changed nothing and the mutation survived. It now uses entries that would
attach, and the mutation is caught again.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Single GPU and DDP, verified on hardware

Both checked against the exact commit (08a5c58613b2, installed with --no-cache-dir and pinned by SHA rather than by branch), on 2x Tesla T4, unsloth/Qwen3-0.6B in 4bit.

Single GPU is untouched.

measured
hf_device_map None
parameters cuda:0: 310
repair function present yes
modules repaired 0
loss 2.662875493367513

That is the same value four separate single-card runs produced before this change, to the last digit.

DDP is untouched, and the repair never runs there. torchrun --nproc_per_node 2, one rank per card:

fix branch main (control)
placement rank 0 cuda:0, rank 1 cuda:1, 310 params each same
modules repaired 0 on every rank n/a
trains, use_gradient_checkpointing = False yes, 2.6423681577046714 on both ranks yes, 2.6423681577046714
trains, use_gradient_checkpointing = "unsloth" no no, identically

The repair reads the model's own hf_device_map, and each DDP rank holds the whole model on one device, so there is nothing for it to do. A check on torch.cuda.device_count() or args.world_size would have behaved differently here, which is why it does not use either.

The reentrant-checkpointing failure under DDP (Expected to mark a variable ready only once ... Reused parameters in multiple reentrant backward passes) reproduces identically on unmodified main, so it is pre-existing and out of scope for this PR.

One measurement trap worth recording

An earlier run of this same check reported 2.6619460582733154 on the branch instead of the oracle, which looked like the fix changing single-GPU numerics. It was not: pip install "git+...@<branch>" resolved to an older tip, and pip also caches a built wheel keyed on the URL, which is identical for every commit on a branch. Pinning the commit SHA and passing --no-cache-dir reproduces the oracle exactly. Worth knowing for anyone verifying a branch this way, since the stale result is a plausible-looking number rather than an error.

danielhanchen and others added 2 commits August 30, 2026 08:15
Simulating this PR in a sandbox turned up three things.

The docstring's attribution was wrong. It said `dispatch_model` installs no
`AlignDevicesHook` on a tied weight. Asked directly, on accelerate 0.34.1
through 1.10.1, it hooks them: 29 of 29 modules with `tie_word_embeddings`
either way. What drops the hook is our own patching pass. `post_patch` calls
`unsloth_zoo.patching_utils.patch_model_and_tokenizer`, which builds a brand new
`torch.nn.Embedding` around the existing weight and a brand new
`torch.nn.Linear` for the lm_head and installs them through
`set_input_embeddings` / `set_output_embeddings`. The weights come across; the
`_hf_hook` belonged to the object that was replaced.

That also explains why the earlier attempts in this branch did not work, and it
means the fault is not tied-specific at all: `tie_word_embeddings = False`
loses the hook and crashes the same way. Renamed to `_repair_dispatch_hooks`,
since the old name pointed at the wrong thing.

The cpu/disk guard did not hold for a `torch.device`. `dispatch_model` takes
`Union[str, int, torch.device]` and writes back what it was given, and
`torch.device("cpu") != "cpu"`, so a map spelled that way had its offloaded
modules read as accelerator ones and hooked. Compared as text now. Reproduced on
every combination tested and fixed on all of them.

The repair at the end of the llama loader now skips `fast_inference`, which is
the test `_attach_bnb_multidevice_hooks` already opens with: under vLLM the HF
module tree this would hook is not the one that runs.

Verified, on one GPU, since `cpu` and `cuda:0` are two real devices: dispatch a
tied model with the embedding on the card and the layers on the host, rebuild
the embeddings the way `post_patch` does, and

    RuntimeError: Expected all tensors to be on the same device, but got index
    is on cpu, different from other tensors on cuda:0

appears, and the repair clears it. The new end-to-end test runs that sequence
and then checks what a loss comparison cannot see: `init_hook` calls
`set_module_tensor_to_device`, which REPLACES the Parameter, and replacing one
half of a tied pair unties it silently. It holds, because that function returns
early when the parameter is already on the target device, which it always is
here. Confirmed by backward: both halves still accumulate one shared gradient.

Skipped on a runner with no card, so the CPU job keeps the 11 stub tests.
Matrix: torch 2.6.0 and 2.9.1 against accelerate 0.34.1, 1.0.1, 1.5.2, 1.10.1
and latest, each over DEVICE_TYPE_TORCH cuda, xpu, npu and mps. Both new guards
mutation-tested.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Five review items, all of which reproduce. Three are ordering, two are the shape
of the hook itself.

The vision loader had the same bug this PR was opened for.
`_attach_bnb_multidevice_hooks` runs at vision.py:1648 and
`patch_model_and_tokenizer` at vision.py:1959, both inside
`FastBaseModel.from_pretrained`, so the rebuild that drops the hooks happens
after the repair that installs them. A VLM split across cards still met the
cross-device index_select. Repaired at the end of that function too, behind the
same fast_inference and offload_embedding guards.

`resize_token_embeddings` is later still. `loader.py:1077` and `loader.py:2129`
run it after `from_pretrained` has returned and done its own repair, and it
builds a new embedding and a new tied head without carrying `_hf_hook` across.
The file already knew this shape: the comment at loader.py:2104 disables
offload for exactly this reason. Repaired after both calls.

Two on the hook, and the second was measured rather than argued.

`skip_keys` was dropped. dispatch_model passes the model's
`_skip_keys_device_placement`, which is `["past_key_values"]` on every decoder
checked, and those are the keys accelerate deliberately does not move with the
inputs.

`io_same_device` was True on every repaired module, where dispatch_model sets it
only on the root. On a submodule it copies the whole result back to the incoming
card and the next hook copies it over again, so a run of rebuilt blocks
round-trips the hidden states at every layer. Measured on the split repro: False
gives byte-identical logits and the output still reaches the caller, because the
root's own hook survives the rebuild and does that. It is now True only when the
root has no hook, where nothing else would.

Also read the cpu/disk guard through `.type` rather than `str()`. The earlier fix
caught `torch.device("cpu")` and still missed `torch.device("cpu", 0)`, which
stringifies to "cpu:0" and matches neither entry.

Five new tests, each mutation-tested by restoring the bug it covers. The
simulation harness needed a fix of its own first: it executes the function
lifted out by AST in a hand-built namespace, and `torch.device` was not in it,
so every run failed with a NameError that read like a product fault. It now
checks the free names up front and names the missing one.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 30, 2026

@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: ac41452076

ℹ️ 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/vision.py
Comment on lines +252 to +253
if device_kind in ("cpu", "disk"):
continue # offload is a different mechanism, and has its own hooks

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 Restore hooks for rebuilt CPU/disk-offloaded modules

When hf_device_map places a rebuilt embedding or output head on cpu or disk, the original Accelerate offload hook is attached to the module that patch_model_and_tokenizer or resize_token_embeddings discards. Skipping the replacement here therefore does not leave the offload machinery intact: the new module has no hook and may retain a CPU or meta weight, so its first GPU input fails with a device mismatch or meta-tensor error. Preserve or reconstruct the offload hook and its weight state for these mapped replacements instead of unconditionally skipping them.

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.

The observation is right that the rebuilt module is unusable. The conclusion that this PR should restore its hook is not, and the measurement says why.

Built the case directly: a model dispatched with the embedding offloaded to CPU, then the same module rebuild the patching pass does, with no repair anywhere in the picture.

accelerate offloaded the embedding      weight device meta, hook True
after the rebuild                       weight device meta, hook False
forward                                 NotImplementedError: Cannot copy out of
                                        meta tensor; no data!

Two things follow.

It is pre-existing. That sequence contains no repair at all, so it is the state main is in today. This PR neither introduces the breakage nor worsens it, and the cpu/disk branch skipping the module leaves it exactly as it found it.

It is not reconstructable here. An offloaded module's weight is on meta; the data lives in the hook's weights_map, which belonged to the module object that was just discarded. AlignDevicesHook(execution_device="cpu") has no weights_map, no offload_dir and no offload_index, so attaching one would not make the module work. It would replace a clear Cannot copy out of meta tensor with a hook that silently reads nothing, which is worse than the current failure.

So this stays out of scope for this PR. It is a real defect and worth its own fix, in patch_model_and_tokenizer where the rebuild happens and the outgoing module's offload state is still in hand, rather than in a function that only sees the map afterwards.

The behaviour is pinned by a test either way, so the skip cannot be quietly widened later.

@danielhanchen

Copy link
Copy Markdown
Member Author

Before and after, measured on 2x Tesla T4 with an install gate

Three arms in one Kaggle session, each verified to be the commit it claims by asking the installed tree which symbol it carries. Neither arm stood down.

main parent 08a5c5861 head 726a23e30
single GPU trains, 2.662875493367513 trains, 2.662875493367513 trains, 2.662875493367513
split across 2 cards fails trains, 2.662875493367513 trains, 2.662875493367513
DDP, checkpointing off trains, 2.6423681577046714 both ranks same same
DDP, use_gradient_checkpointing="unsloth" fails fails identically fails identically

main on the split path:

RuntimeError: Expected all tensors to be on the same device, but got index is on
cuda:0, different from other tensors on cuda:1
(when checking argument in method wrapper_CUDA__index_select)

So the issue is real and reproduces on unmodified main, and single GPU is unchanged to the last digit across all three arms. Under DDP the repair reports [0, 0] on every rank and each rank holds one device, which is the case a check on torch.cuda.device_count() rather than on the model's own hf_device_map would have broken. The checkpointing failure is Expected to mark a variable ready only once and it is identical on main, so it is pre-existing and not this change.

Version compatibility, on real splits

transformers / trl split trains
floor 4.57.6 / 0.22.2 cuda:0 + cuda:1 2.6619460582733154
ceiling 5.5.0 / 0.24.0 cuda:0 + cuda:1 2.662875493367513

Ceiling resolves to 5.5.0 because the package pins transformers<=5.5.0. In both, embedding_device is cuda:1, param_device_counts is {"cuda:1": 1, "cuda:0": 309} and 397 modules carry a hook.

Away from GPUs, the repair was exercised against torch 2.6.0 and 2.9.1 with accelerate 0.34.1, 1.0.1, 1.5.2, 1.10.1 and latest, over DEVICE_TYPE_TORCH of cuda, xpu, npu and mps. The function has no filesystem, path or platform constructs, so Linux, macOS, Windows and WSL differ in nothing it touches.

Two measurement traps worth recording

A same-version reinstall is silently skipped. Both commits carry the same version string, so a second pip install "unsloth @ git+...@<sha>" in one session reports success in half the time and leaves the first commit in place. --no-cache-dir does not prevent this; only --force-reinstall does. An earlier round reported the arms identical for exactly that reason, and the numbers looked entirely plausible. The gate above exists because of it.

The tie survives the repair, and no loss comparison can show that. AlignDevicesHook.init_hook calls set_module_tensor_to_device, which replaces the Parameter object, and replacing one half of a tied pair unties it without changing any forward output. It holds because that function returns early when the parameter is already on the target device, which it always is here. Confirmed by running a backward and checking both halves still accumulate one shared gradient.

A fresh run of the same three arms is in flight against ac4145207, which carries the five fixes from this round.

danielhanchen and others added 2 commits August 30, 2026 11:33
A device map does not have to NAME the modules the patching pass replaces.
Every map this loader builds itself is leaf-granular and lists both, but a
hand-written coarse map such as {"model": 0, "lm_head": 1} covers
model.embed_tokens through an ancestor. dispatch_model hooks it regardless,
because it walks the subtree an entry covers: measured, a {"": 0,
"model.layers.1": "cpu"} map leaves lm_head hooked without lm_head being a
key. Iterating map keys alone repaired 0 there and left exactly the crash this
function exists for, arriving through the shape of the map rather than the
shape of the model.

Only the two modules the pass actually replaces are resolved this way, under
the longest entry covering them, and an entry the map names still wins. Four
tests, two mutations caught.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Latest round, with the two new review items triaged and the hardware evidence re-run against the current head.

Review items

Coarse map entries (P2): accepted, fixed in f38d5b2. dispatch_model hooks a module the map never names, because it walks the subtree an entry covers. Measured on a {"": 0, "model.layers.1": "cpu"} map: lm_head comes back hooked without being a key, and the key-only iteration repaired 0. The rebuilt embedding and head are now resolved against the longest entry covering them; an entry the map names still wins over a covering ancestor. Four tests, two mutations caught.

CPU/disk offload (P1): declined, with the measurement. Built the case directly. With no repair anywhere in the picture, the rebuild leaves a meta weight and no hook, and the forward raises NotImplementedError: Cannot copy out of meta tensor; no data!. That is the state main is in, so this PR neither introduces nor worsens it. It is also not reconstructable from the map: the data lives in the discarded hook's weights_map, and a bare AlignDevicesHook(execution_device="cpu") would replace a clear error with a hook that silently reads nothing. Detail in the thread.

The bug, and the fix, on 2x Tesla T4

Three arms in one session, each install-gated on the SHA and on the symbol it should carry, so no arm can silently run another's code (main has neither repair symbol, the parent has the old name, the head has the new one).

arm split model single GPU DDP, checkpointing off
main RuntimeError 2.662875493367513 2.6423680782318115
parent 2.6619460582733154 2.662875493367513 2.6423680782318115
head 2.6619460582733154 2.662875493367513 2.6423680782318115

main on the split:

RuntimeError: Expected all tensors to be on the same device, but got index is on
cuda:0, different from other tensors on cuda:1
(when checking argument in method wrapper_CUDA__index_select)

The map that produces it places lm_head and model.embed_tokens on cuda:1 and everything else on cuda:0. main carries 395 hooked modules with the embedding unhooked; the head carries 397 with it hooked. So the failure is real, and the fix is what removes it.

Nothing else moves. Single GPU is byte-identical across all three arms and the repair is a no-op there (repair_count 0). DDP with checkpointing off is identical across all three. DDP with gradient_checkpointing="unsloth" fails identically on all three arms including main with Expected to mark a variable ready only once, so that is pre-existing and not this PR's.

Compatibility

  • Version floor and ceiling, both on a real split: transformers 4.57.6 / trl 0.22.2 trains, and transformers 5.5.0 / trl 0.24.0 trains, both with embedding_device cuda:1 and 397 modules hooked.
  • Sandbox matrix, 10 of 10 green: torch 2.6.0 and 2.9.1 against accelerate 0.34.1, 1.0.1, 1.5.2, 1.10.1 and latest, across cuda / xpu / npu / mps device kinds.
  • Cross-platform staging: ubuntu-latest, macos-14 and windows-latest all green.
  • Tie preservation and the shared full-finetune gradient are asserted directly, since loss parity alone cannot see them.

The one unrelated red on staging is Unsloth GGUF CI, on a multi-turn sampling determinism assertion in llama.cpp inference. This PR touches no inference path.

danielhanchen and others added 4 commits August 30, 2026 12:09
An AlignDevicesHook wraps the module's OWN forward, so it moves the input
inside base_layer(x). lora.Linear.forward then reaches for the caller's x again
for the adapter branch, where it casts dtype and not device, and feeds it to
lora_A, whose weights PEFT put on the base layer's device via
_move_adapter_to_device_of_base_layer. On a split model those are different
cards, so the adapter branch raises where the base call did not.

Isolated against peft 0.20.0: the base layer alone copes, the wrapper raises
'Expected all tensors to be on the same device, but got mat2 is on cuda:0,
different from other tensors on cpu', and hooking the wrapper fixes it.

Reachable rather than hypothetical: the continued pretraining recipe targets
embed_tokens and lm_head by name, which are exactly the two modules the load
rebuilt. Wired into both get_peft_model paths and both adapter-loading paths.

Only the endpoints are considered, since every other adapter wraps a module
accelerate hooked itself. Six tests, two mutations caught.
A 2xT4 run corrected the previous commit's scope. Naming embed_tokens and
lm_head in target_modules does NOT produce a LoRA layer: unsloth routes them to
modules_to_save, so the wrapper is a ModulesToSaveWrapper with no base_layer at
all, and the LoRA lift could never have rescued this recipe.

ModulesToSaveWrapper._setup has two branches. The untied one deepcopies the
original module, and the copy CARRIES _hf_hook, which peft then rebuilds: that
works, but only because this file put a hook on the original first. The tied one
builds a fresh nn.Linear sharing the tied weight, so there is no hook to inherit
and peft's own hasattr guard finds nothing.

Measured on peft 0.20.0: untied active module hooked, tied active module not.
The lift now hooks the tied branch's copy at the original's execution device and
leaves peft's own alone. Three tests, one mutation caught, and the whole thing
is idempotent.
Two tests carried the same name, so the later definition won silently and the
repair's version tested nothing. Caught by the source lint duplicate-definition
check, not by the suite, which reported 29 passing while one of them was dead
code. 30 now, and the recovered guard is mutation-tested: dropping the repair's
defensive accessor fails it.
Re-running the recipe on 2xT4 against the fixed head shows the trainable copy
coming back WITH a hook at cuda:1 and its weight on cuda:0, still failing with
'index is on cuda:1, different from other tensors on cuda:0'. The same error
appears on the head before this branch existed, so it neither caused nor cured
it.

The cause is not a missing hook. _offload_frozen_module_for_training
(llama.py:199) moves the trainable copy to a bare DEVICE_TYPE_TORCH, which is
'cuda' and therefore cuda:0, whatever device the map assigned the original. No
hook can reconcile a weight the loader deliberately placed elsewhere, and one
pointing at cuda:1 disagrees with it. That is a separate defect, present on main
and independent of dispatch hooks, so it is not this PR's to fix here.

The LoRA branch stays: it is a different wrapper shape, and it is measured
against real peft rather than inferred. sim_09 keeps the modules_to_save
measurement without asserting a fix.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 96383803f7

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

danielhanchen commented Aug 30, 2026 •

Copy link
Copy Markdown
Member Author

CI note, since three checks are red and none of them is this change.

This PR touches four files: unsloth/models/vision.py, llama.py, loader.py and its own test file. All three failures are in suites that exercise llama.cpp serving and SSE batching, which none of that code reaches. Rather than assert that, here is each one re-run and compared against main.

job attempt 1 attempt 2 same job on main
Backend CI (Python 3.13) fail pass fail at 10:54, 10:36, 10:10, 08:22
Windows Unsloth GGUF CI fail fail fail at 13:00 and 11:43; pass at 10:54, 10:36, 10:10
Mac UI + API + Update + Inference fail fail fail at 11:43, 10:54, 10:36, 10:10, 08:22

Backend CI passes on re-run, so test_event_batch_flushes_while_upstream_is_idle is a flake. It was 1 failure out of 35168 tests.

The two that reproduce also reproduce on main, on the identical assertion. Mac, byte for byte on both:

assert answer in first[1], (
AssertionError: openai: turn 2 must carry turn 1's answer '95', so history reached
the model. Got "You haven't provided the previous question. \n"

and Windows GGUF:

AssertionError: openai non-deterministic at turn 2 with temperature=0.0

Both are model-behaviour assertions against a local GGUF server: one that greedy decoding reproduces itself, one that conversation history reaches the model. They are worth fixing, and they are not this PR's.

For the record on what this PR IS verified against: 27 tests, 6 sandbox simulations, a torch 2.6.0/2.9.1 x accelerate 0.34.1/1.0.1/1.5.2/1.10.1/latest matrix across cuda/xpu/npu/mps, cross-platform staging green on ubuntu-latest, macos-14 and windows-latest, and a 2xT4 run where main fails the split with the cross-device index_select error while both fixed arms train to 2.6619460582733154.

danielhanchen and others added 2 commits August 30, 2026 20:32
Delete-first, per unslothai/scripts#230. Per file:

  vision.py  128 -> 38
  llama.py    18 ->  3
  loader.py   18 ->  6
  tests       174 -> 36
  TOTAL       338 -> 83   (75.4%)

Deleted rather than shortened: restatements of the code, the measured loss
numbers and module counts (they are in the PR description), narration about
which attach point was tried first, and every test docstring whose function
name already says the same thing. What survives is limited to invariants the
code does not state and the WRONG-alternative warnings: torch.device('cpu', 0)
is not == 'cpu'; dispatch sets io_same_device on the root only; a coarse map
covers an endpoint through an ancestor; _embedding_dispatch_device READS the
hook, so adding one under offload answers its question wrongly.

comment_tools.py check --strip-docstrings passes vision, llama and loader, and
FAILS the test file: _strip_docstrings blanks a docstring rather than removing
the node, so a DELETED docstring reads as a code change. Verified independently
instead by stripping docstrings and comments from both versions and comparing
the ASTs: 4/4 identical, zero code tokens changed.
@danielhanchen
danielhanchen merged commit 3d531a8 into main Aug 31, 2026
49 of 52 checks passed
@danielhanchen
danielhanchen deleted the fix/tied-embedding-dispatch-hook branch August 31, 2026 02:55
danielhanchen pushed a commit that referenced this pull request Aug 31, 2026
#9995 landed and now calls _repair_dispatch_hooks at the top of
_attach_bnb_multidevice_hooks, so the test harness namespace no longer had
every name the function reads and 9 tests died on NameError. Exec the real
function rather than stubbing it, so these tests fail if the two changes ever
stop composing.
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