Repository navigation
Train a model the planner split across cards, instead of dying in index_select - #9995
Conversation
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.
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. |
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.
Single GPU and DDP, verified on hardwareBoth checked against the exact commit ( Single GPU is untouched.
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.
The repair reads the model's own The reentrant-checkpointing failure under DDP ( One measurement trap worth recordingAn earlier run of this same check reported |
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.
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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if device_kind in ("cpu", "disk"): | ||
| continue # offload is a different mechanism, and has its own hooks |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
Before and after, measured on 2x Tesla T4 with an install gateThree 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.
So the issue is real and reproduces on unmodified Version compatibility, on real splits
Ceiling resolves to 5.5.0 because the package pins 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 Two measurement traps worth recordingA same-version reinstall is silently skipped. Both commits carry the same version string, so a second The tie survives the repair, and no loss comparison can show that. A fresh run of the same three arms is in flight against |
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.
|
Latest round, with the two new review items triaged and the hardware evidence re-run against the current head. Review itemsCoarse map entries (P2): accepted, fixed in f38d5b2. CPU/disk offload (P1): declined, with the measurement. Built the case directly. With no repair anywhere in the picture, the rebuild leaves a The bug, and the fix, on 2x Tesla T4Three 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 (
The map that produces it places Nothing else moves. Single GPU is byte-identical across all three arms and the repair is a no-op there ( Compatibility
The one unrelated red on staging is |
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.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! 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". |
|
CI note, since three checks are red and none of them is this change. This PR touches four files:
Backend CI passes on re-run, so The two that reproduce also reproduce on and Windows GGUF: 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 |
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.
#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.
The problem
On a machine with two or more GPUs,
FastLanguageModel.from_pretrainedfails to train with a message about tensors:This is the default path, not an opt-in one.
requested_device_mapupgrades the untouched default to the"unsloth"planner, so anyone with 2 cards and nodevice_mapgets a split without asking. Measured on 2x Tesla T4 withunsloth/Qwen3-0.6Bin 4bit, the planner's map is:accelerate.dispatch_modelthen hooks 395 modules and notmodel.embed_tokens, becauseQwen3-0.6Bhastie_word_embeddings = Trueand 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, andllama.py'sself.embed_tokens(input_ids)gets ids oncuda:0against a weight oncuda:1.The same model at
device_map = {"": 0}trains fine, andUNSLOTH_AUTO_DEVICE_MAP=0also trains fine because it keeps everything on one card. Neither is discoverable from the error.The fix
_repair_tied_module_hooksre-attaches anAlignDevicesHookto any module the model's ownhf_device_mapnames that ended up without one. It repairs only what the map already placed, skips any module that has a hook, skipscpu/diskentries (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:
index_selectpost_patchfrom_pretraineddoesThe single-card loss is 2.662875493367513. The middle row trains, produces a plausible number, and is not the same training -
post_patchis 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.6B4bitunsloth/Qwen3-4B-Base4bitSo a split model now trains, and trains identically to one that fits on a single card.
What it does not change
hf_device_map; each rank holds the whole model on its own device, so there is nothing to repair.offload_embeddingis left alone._embedding_dispatch_devicereads 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 behindif not offload_embedding, and a test asserts that guard from the caller's AST.init_hookmoves 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_hookmoves tensors to the execution device, so the far device ismeta- real on every machine, so the attach is exercised on a GPU-less runner - and the integer tocuda:Nconversion 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_*.pyplus the new file: 3237 passed.