Repository navigation
Resolve the per layer device through a helper instead of a raw index - #11020
Conversation
The five pipeline-parallel inference readers each did
device_index = getattr(decoder_layer, "_per_layer_device_index", 0)
... = move_to_device(device_index, ...)
and unsloth_zoo recorded that attribute as device.index, which is None for a
CPU-offloaded or not-yet-materialised layer. move_to_device rejects None, so a
sampling callback inside a trainer ended with "ValueError: Invalid target device:
None".
Add per_layer_device in models/_utils.py and route all five readers through it.
It prefers the torch.device unsloth_zoo now publishes on _per_layer_device, falls
back to the index, and when the index is None reads the placement off the layer's
own parameters rather than defaulting to cuda:0, which would move a CPU layer's
activations off the layer. A layer carrying neither attribute keeps the
historical default of 0, so nothing that worked before changes.
It returns the device and, separately, an int buffer index, because four of the
readers also use the old value to subscript a tuple with one entry per
accelerator: out_weights in gemma, gemma2 and cohere, temp_gates and temp_ups in
llama. A torch.device cannot do that, which is why the index stays an index.
Every reader imports the helper explicitly rather than relying on
`from .llama import *`.
Every conversion goes through _as_torch_device rather than a bare torch.device
call: on torch 2.6 the integer form raises "Cannot access accelerator device when
none is available" on a host with no accelerator visible, which is how a CPU-only
runner looks, and resolving a device must not be the thing that fails.
The new test locates each reader from its own call site and fails when it reads a
name it never binds, which is the shape that would otherwise only surface as a
NameError at the first decode step.
Refs #3538
Pairs with unslothai/unsloth-zoo#1229
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bca18eb10b
ℹ️ 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 is None: | ||
| if index is None: | ||
| device = _device_of_parameters(module) |
There was a problem hiding this comment.
Keep CPU layers out of the accelerator-only inference path
When _per_layer_device_index is None for a CPU-offloaded layer—the exact scenario this change targets—this resolves the activation device to CPU, but the five callers still use accelerator-resident state. For example, llama.py:1232-1245 allocates XX, variance, and MLP buffers on DEVICE_TYPE_TORCH:0 and passes them alongside the now-CPU X at lines 1273-1278; Gemma likewise creates out_weights on accelerator devices at lines 160-166 and combines one with CPU hidden states at lines 197-198. Generation therefore merely changes from Invalid target device: None to a cross-device operation failure. CPU/meta placement needs a compatible fallback inference path, or every scratch/cache tensor must follow layer_device.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Half genuine and fixed in 8f0efc5, half out of scope for this PR.
The meta half is real and worse than described: tensor.to("meta") succeeds and discards the data, and torch.matmul(meta, cuda) returns a meta tensor rather than raising, so a decode would run to completion and produce nothing. per_layer_device now refuses meta on every route, asks accelerate's _hf_hook.execution_device first, and falls through to default otherwise. Measured on 8 B200s: with layer 0's published device parked on meta the pre-fix reader fails layer 0 resolved to meta, and the fixed one generates the same token ids as the 1, 2, 3, 4 and 8 device runs.
The CPU half I am not taking. A layer genuinely resident on CPU while llama's temp_gates and gemma's out_weights are allocated per accelerator still ends in a loud cross-device RuntimeError, which is not a regression and not silent. A CPU-offloaded inference path is a separate piece of work; the docstring no longer implies this PR provides one.
torch 2.6 raises from the bare torch.device(0) on a host with no visible accelerator, which is what the fallback in per_layer_device was written against. From torch 2.11 the same call on the same host returns cuda:0 and only fails when a tensor is moved there, so a CPU only host resolved a layer with no recorded device to cuda:0 and ended in RuntimeError: No CUDA GPUs are available instead of falling back to the layer's own parameters. Probe the backend so every torch version answers the same.
|
Confirmed this against main, where all five readers still pass the raw _per_layer_device_index into move_to_device and unsloth_zoo records device.index, which is None for a cpu or meta layer, so this looks like the linked crash. Will get this reviewed. |
per_layer_device runs once per decoder layer per generated token inside the five pipeline parallel inference readers, and two things in it were far more expensive than the single getattr it replaced. nn.Module.__getattr__ costs about 470ns to report a missing attribute, because it searches _parameters, _buffers and _modules and only then raises for getattr to swallow. Any install whose unsloth_zoo publishes only the index leaves _per_layer_device missing on every layer, so that cost was paid on every layer of every token. verify_and_set_device assigns both names a plain non tensor value, which nn.Module keeps in the instance dictionary, so read it there and fall back to getattr only when neither name is present, which keeps a class attribute or a property resolving exactly as before. _device_type_is_usable calls torch.cuda.is_available(), about 700ns on torch 2.14, and the set of usable device types cannot change inside a process, so it is memoised. Measured on a B200 with torch 2.14, five interleaved samples per variant, each shape compared against the reader this PR replaces running on that same shape: layer shape old reader before after device and index published 26ns 150ns 162ns index only, older zoo 26ns 2259ns 613ns neither attribute 435ns 2867ns 1776ns The index only shape is what every existing install has until the matching unsloth_zoo ships. At 32 layers it went from 71us of added time per generated token to 19us, and it drops to 4us once both attributes are published. Three tests. Two of them fail without this change.
Running the full default test selection on the merge base and on this branch and diffing the failure sets turned up two gates this file trips, both of which are about the file itself rather than about the fix. tests/python/test_accelerator_skip_guards.py: the GPU-only test gated on torch.cuda.is_available(). tests/_zoo_aggressive_cuda_spoof.py patches that probe to True process wide and does not undo it, and every module under tests/version_compat and tests/vllm_compat applies it at import, so on a CPU only box this test un-skipped whenever it shared a session with one of them and died inside torch with "Cannot access accelerator device when none is available". Gate on has_real_cuda() from tests/_shared/real_accelerator.py, which records the answer before anything can spoof it, as the other GPU tests in tests/ already do. tests/test_source_read_encoding.py: four reads of checked-in source used the platform default encoding, which breaks on Windows the moment one of those files gains a non-ASCII byte. Pass encoding = "utf-8". Both gates now pass, and so does the file itself: 80 passed across the three.
|
@codex review |
|
@codex security review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
Delete-first pass: collapse multi-line rationale to one line, drop measured numbers, duplicated paragraphs and restatements of the code. Comments, docstrings and whitespace only, AST gated; no behaviour change.
torch.device(...) plus the .type probe behind it is about 330 ns of the reader's cost, and the reader runs once per decoder layer per generated token. The mapping from a published value to its device cannot change in-process, for the same reason _device_type_is_usable is already memoised, so each distinct value is resolved once. Index only, the shape every published unsloth_zoo writes, goes from 650.4 ns to 147.9 ns. The no-attribute shape goes from 1737.4 ns to 782.1 ns. Nothing else moves. The memo keys on the default as well as the index, since an unindexed device takes its buffer subscript from it, and refuses bool because False hashes equal to 0.
The resolved answer is memoised on the layer and validated by identity against the published value it came from, so unsloth_zoo re-running verify_and_set_device invalidates it with no explicit clear. Two dict subscripts inside a try, rather than .get, because a hit is the whole point and .get costs about 25 ns more per lookup. Every shape a released or current unsloth_zoo publishes now costs about 74 ns against main's 40 ns, down from 650 ns: device and index published 166.5 -> 74.9 ns index only 650.4 -> 75.0 ns unindexed device published 650.4 -> 74.0 ns Only the two routes that depend on the published value alone are memoised. A device read from the layer's parameters or from AlignDevicesHook.execution_device can move without the published value changing, so memoising it would keep sending activations to a device accelerate has already left.
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Performance on 1 GPU and on 2 GPUsMeasured, with a negative control, on 8x NVIDIA B200, torch 2.14.0+cu130, transformers 4.57.6,
The installed unsloth_zoo publishes only Where the changed code runs, counted rather than assumedAll five changed call sites are inside
So this PR is not on the training path at all. Its only hot path is single token decode. Microbenchmark, same process, timeit, 200k iterations x 15 repeats, median per call
Predicted end to end cost: 549 ns x 16 calls per token = 8.8 us per decoded token, against a End to end, 61 steps, bs2 x ga3, seq 2048, seed 3407, Llama-3.2-1B-Instruct 4bit, 3 reps per arm1 GPU:
2 GPU pipeline parallel, GPUs 2 and 3, layers 0-7 on cuda:0 and 8-15 on cuda:1, so
Rotated decode only run, arm order permuted every rep so run order drift cannot alias onto one arm,
The negative control reproduces the entire 1 GPU decode delta from two identical checkouts of main. Correctness
Agreement between the arms is at or below main's agreement with itself, so the tolerance is the Verdict1 GPU: performance identical. The changed reader is called zero times per training step, and the 2 GPU: no regression. Pipeline parallel decode -0.26% against a +1.62% same code control, with loss The 16.9x per call figure for the reader in isolation is real, and it is 592 ns on a 15,800,000 ns |
…se the unpublished shape
Two changes to the memo, both measured on a B200, torch 2.14.0, python 3.13,
200k iterations by 15 repeats, arm order rotated, base against base through the
identical harness as a negative control (0.6 to 11.2 ns).
1. The fast path reads the memo as an attribute instead of subscripting
`module.__dict__`. The memo still lives in the instance dictionary, so
nothing else about it changes, but one specialised LOAD_ATTR is cheaper than
the `__dict__` descriptor plus a dict lookup.
2. A layer that publishes neither name is memoised too. That shape had no memo
at all and paid three failed `nn.Module.__getattr__` scans per layer per
token, about 2 us. It is memoisable because the answer comes from `default`
and nothing on the module, so the fast path validates it by confirming that
the layer still publishes neither name. `from_default` is the whole
condition: a device read off the layer's own parameters moves when the layer
does, and memoising that is how a reader ends up sending activations to a
device the layer left, so it stays unmemoised.
Reader only, median ns, against the previous head:
published shape before after delta
index (what unsloth_zoo writes)
90.4 70.1 -20.3
device 89.3 77.3 -12.0
neither 2104.5 127.6 -1976.9
Reader plus move_to_device: 574.0 to 537.9, 573.1 to 548.3, 2654.0 to 593.8.
A real greedy decode, Llama-3.2-1B-Instruct 4bit, 256 tokens, 16 layers, keeps
the same 99.61 percent hit rate: 4064 of 4080 calls answered from the memo, the
16 misses being one cold miss per layer on the first token.
Tests: the four added here cover the new route and the invalidation it has to
keep, including that a parameter-derived answer is still never memoised and that
the memo yields the moment either name is published on the layer.
Correction to the microbenchmark above, and a 1 GPU improvementThe reader-only figures in my previous comment (37.2 ns against 629.1 ns, 16.9x) were taken on Does the memo actually hitCounted, not assumed. A branch-for-branch counting twin of the live head source, over a real greedy
4080 is 255 decode steps times 16 layers; prefill does not go through this loop. The 16 misses are The real current cost, and the improvement200k iterations by 15 repeats, one process, arm order rotated, negative control 0.6 to 11.2 ns.
Reader plus Two things came out of the search. Reading the memo as an attribute rather than through Three alternatives were measured and rejected: two separate memo attributes (55.9 ns on an What the new route gives up, stated rather than glossedThe absent-shape route validates with Pushed as Not claimedNo tokens per second delta. 20 ns times 16 layers is 0.3 us per token against a decode step of about |
What this PR is for, in plain termsUnsloth can split one model across several GPUs, so layer 1 might live on GPU 0 and layer 20 on It used to do that by reading a plain number off the layer saying which GPU it was. A layer sitting in the middle of generating (#3538). The user was not doing anything exotic: they were running a This PR replaces those five copy-pasted lookups with one shared helper that works out the real It is probed rather than version-gated, because the shape published by unsloth_zoo has changed over What it does NOT fix, stated so nobody expects it to: a layer genuinely on the CPU while |
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
The only conflicts were in studio/backend/utils/torch_warmup.py and studio/backend/tests/test_diffusers_prewarm.py, both of which this branch touched only through a comment trim and neither of which belongs to the context and attention plan fix. unslothai#11020 carried its own reduction pass over the same two files into main, so both are resolved by taking main verbatim: they are now byte identical to main and out of this PR's diff.
…nslothai#11020) * Resolve the per layer device through a helper instead of a raw index The five pipeline-parallel inference readers each did device_index = getattr(decoder_layer, "_per_layer_device_index", 0) ... = move_to_device(device_index, ...) and unsloth_zoo recorded that attribute as device.index, which is None for a CPU-offloaded or not-yet-materialised layer. move_to_device rejects None, so a sampling callback inside a trainer ended with "ValueError: Invalid target device: None". Add per_layer_device in models/_utils.py and route all five readers through it. It prefers the torch.device unsloth_zoo now publishes on _per_layer_device, falls back to the index, and when the index is None reads the placement off the layer's own parameters rather than defaulting to cuda:0, which would move a CPU layer's activations off the layer. A layer carrying neither attribute keeps the historical default of 0, so nothing that worked before changes. It returns the device and, separately, an int buffer index, because four of the readers also use the old value to subscript a tuple with one entry per accelerator: out_weights in gemma, gemma2 and cohere, temp_gates and temp_ups in llama. A torch.device cannot do that, which is why the index stays an index. Every reader imports the helper explicitly rather than relying on `from .llama import *`. Every conversion goes through _as_torch_device rather than a bare torch.device call: on torch 2.6 the integer form raises "Cannot access accelerator device when none is available" on a host with no accelerator visible, which is how a CPU-only runner looks, and resolving a device must not be the thing that fails. The new test locates each reader from its own call site and fails when it reads a name it never binds, which is the shape that would otherwise only surface as a NameError at the first decode step. Refs unslothai#3538 Pairs with unslothai/unsloth-zoo#1229 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Treat an unavailable accelerator as no device when resolving a layer torch 2.6 raises from the bare torch.device(0) on a host with no visible accelerator, which is what the fallback in per_layer_device was written against. From torch 2.11 the same call on the same host returns cuda:0 and only fails when a tensor is moved there, so a CPU only host resolved a layer with no recorded device to cuda:0 and ended in RuntimeError: No CUDA GPUs are available instead of falling back to the layer's own parameters. Probe the backend so every torch version answers the same. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Keep the per layer device reader off the per token slow paths per_layer_device runs once per decoder layer per generated token inside the five pipeline parallel inference readers, and two things in it were far more expensive than the single getattr it replaced. nn.Module.__getattr__ costs about 470ns to report a missing attribute, because it searches _parameters, _buffers and _modules and only then raises for getattr to swallow. Any install whose unsloth_zoo publishes only the index leaves _per_layer_device missing on every layer, so that cost was paid on every layer of every token. verify_and_set_device assigns both names a plain non tensor value, which nn.Module keeps in the instance dictionary, so read it there and fall back to getattr only when neither name is present, which keeps a class attribute or a property resolving exactly as before. _device_type_is_usable calls torch.cuda.is_available(), about 700ns on torch 2.14, and the set of usable device types cannot change inside a process, so it is memoised. Measured on a B200 with torch 2.14, five interleaved samples per variant, each shape compared against the reader this PR replaces running on that same shape: layer shape old reader before after device and index published 26ns 150ns 162ns index only, older zoo 26ns 2259ns 613ns neither attribute 435ns 2867ns 1776ns The index only shape is what every existing install has until the matching unsloth_zoo ships. At 32 layers it went from 71us of added time per generated token to 19us, and it drops to 4us once both attributes are published. Three tests. Two of them fail without this change. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Make the reader tests obey the repository's own two drift gates Running the full default test selection on the merge base and on this branch and diffing the failure sets turned up two gates this file trips, both of which are about the file itself rather than about the fix. tests/python/test_accelerator_skip_guards.py: the GPU-only test gated on torch.cuda.is_available(). tests/_zoo_aggressive_cuda_spoof.py patches that probe to True process wide and does not undo it, and every module under tests/version_compat and tests/vllm_compat applies it at import, so on a CPU only box this test un-skipped whenever it shared a session with one of them and died inside torch with "Cannot access accelerator device when none is available". Gate on has_real_cuda() from tests/_shared/real_accelerator.py, which records the answer before anything can spoof it, as the other GPU tests in tests/ already do. tests/test_source_read_encoding.py: four reads of checked-in source used the platform default encoding, which breaks on Windows the moment one of those files gains a non-ASCII byte. Pass encoding = "utf-8". Both gates now pass, and so does the file itself: 80 passed across the three. * Never resolve a decoder layer's activation device to meta * Declare the AGPL-3.0 SPDX identifier on the new test file * Keep the meta guard off the per token fast path * Trim the comments in the files this PR touches Delete-first pass: collapse multi-line rationale to one line, drop measured numbers, duplicated paragraphs and restatements of the code. Comments, docstrings and whitespace only, AST gated; no behaviour change. * Cut the remaining comments to the facts the code does not state * Memoise the published-index half of the per layer device read torch.device(...) plus the .type probe behind it is about 330 ns of the reader's cost, and the reader runs once per decoder layer per generated token. The mapping from a published value to its device cannot change in-process, for the same reason _device_type_is_usable is already memoised, so each distinct value is resolved once. Index only, the shape every published unsloth_zoo writes, goes from 650.4 ns to 147.9 ns. The no-attribute shape goes from 1737.4 ns to 782.1 ns. Nothing else moves. The memo keys on the default as well as the index, since an unindexed device takes its buffer subscript from it, and refuses bool because False hashes equal to 0. * Answer the per layer device read from the layer itself The resolved answer is memoised on the layer and validated by identity against the published value it came from, so unsloth_zoo re-running verify_and_set_device invalidates it with no explicit clear. Two dict subscripts inside a try, rather than .get, because a hit is the whole point and .get costs about 25 ns more per lookup. Every shape a released or current unsloth_zoo publishes now costs about 74 ns against main's 40 ns, down from 650 ns: device and index published 166.5 -> 74.9 ns index only 650.4 -> 75.0 ns unindexed device published 650.4 -> 74.0 ns Only the two routes that depend on the published value alone are memoised. A device read from the layer's parameters or from AlignDevicesHook.execution_device can move without the published value changing, so memoising it would keep sending activations to a device accelerate has already left. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Answer the per layer device read with one attribute lookup, and memoise the unpublished shape Two changes to the memo, both measured on a B200, torch 2.14.0, python 3.13, 200k iterations by 15 repeats, arm order rotated, base against base through the identical harness as a negative control (0.6 to 11.2 ns). 1. The fast path reads the memo as an attribute instead of subscripting `module.__dict__`. The memo still lives in the instance dictionary, so nothing else about it changes, but one specialised LOAD_ATTR is cheaper than the `__dict__` descriptor plus a dict lookup. 2. A layer that publishes neither name is memoised too. That shape had no memo at all and paid three failed `nn.Module.__getattr__` scans per layer per token, about 2 us. It is memoisable because the answer comes from `default` and nothing on the module, so the fast path validates it by confirming that the layer still publishes neither name. `from_default` is the whole condition: a device read off the layer's own parameters moves when the layer does, and memoising that is how a reader ends up sending activations to a device the layer left, so it stays unmemoised. Reader only, median ns, against the previous head: published shape before after delta index (what unsloth_zoo writes) 90.4 70.1 -20.3 device 89.3 77.3 -12.0 neither 2104.5 127.6 -1976.9 Reader plus move_to_device: 574.0 to 537.9, 573.1 to 548.3, 2654.0 to 593.8. A real greedy decode, Llama-3.2-1B-Instruct 4bit, 256 tokens, 16 layers, keeps the same 99.61 percent hit rate: 4064 of 4080 calls answered from the memo, the 16 misses being one cold miss per layer on the first token. Tests: the four added here cover the new route and the invalidation it has to keep, including that a parameter-derived answer is still never memoised and that the memo yields the moment either name is published on the layer. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Cut the comments in this PR back to the facts the code cannot state --------- Co-authored-by: danielhanchen <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Summary
Sampling from inside a
TrainerCallbackraisedValueError: Invalid target device: Nonebecause a decoder layer with no device index reached
move_to_device. This routes all fivepipeline parallel inference readers through one helper that resolves the layer's device
properly, and adds the test that catches the whole family of mistakes around it.
The CUDA path is unchanged token for token on a real generate.
Root cause
unsloth_zoo.patching_utils.verify_and_set_devicerecords where each decoder layer lives sothe fast inference paths can move activations onto it. It recorded
device.index, andtorch.device("cpu").indexandtorch.device("meta").indexare both None. Every reader thendid:
move_to_devicetakesint,strortorch.deviceand raises for anything else. Thegetattrdefault never fires, because the attribute exists and is simply None.Reported stack:
SFTTrainercallback,model.generate,unsloth_fast_generate,_CausalLM_fast_forward,LlamaModel_fast_forward_inference_custom,move_to_device.Changes
unsloth/models/_utils.pyNew
per_layer_device(module, default = 0), directly abovemove_to_device. It probes whatis on the module instead of checking a version, and returns the device to move to plus an int
buffer index:
_per_layer_device, atorch.devicetorch.device(index)torch.device(default)when that device exists, else the layer's own parameterstorch.device()rejectstorch.device(default), no raisedefaultis resolved through a backend probe rather than a baretorch.device(0). torch 2.6raises "RuntimeError: Cannot access accelerator device when none is available" from that call
on a host with nothing visible, which is what the fallback was written against, but torch 2.11
and later return
cuda:0from the same call on the same host and only fail when a tensor ismoved there. A CPU only host therefore resolved a layer with no recorded device to
cuda:0and ended in "RuntimeError: No CUDA GPUs are available" on every torch newer than the one the
fallback was written against. Asking
torch.<type>.is_availablemakes both torch versionsanswer the same, and a backend that publishes no such function is taken at its word, which is
what keeps
metausable for an offloaded layer.The pair matters because four of the five readers also use the old value to subscript a tuple
with one entry per accelerator:
out_weightsin gemma, gemma2 and cohere, andtemp_gatesplus
temp_upsin llama. Atorch.devicecannot do that, so the index stays an index.unsloth/models/{llama,granite,gemma,gemma2,cohere}.pyEach reader now does:
and each imports the helper explicitly from
._utilsrather than relying onfrom .llama import *to carry the name across.move_to_deviceis not in_utils.__all__,so that route was never guaranteed for it either.
The companion change that publishes
_per_layer_deviceis unslothai/unsloth-zoo#1229. This PRdoes not depend on it: an older unsloth_zoo that still writes a None index is handled by the
third row of the table above.
Two mistakes the runs caught
Both were found by actually running this, not by review, and both now have a test.
layer_device, _ = per_layer_device(decoder_layer)in llama, discarding the index, because a grep for
move_to_devicedoes not show thatllama.py:1302-1303usestemp_gates[device_index]andtemp_ups[device_index]furtherdown the same loop body. The GPU run failed with
NameError: name 'device_index' is not defined, which Python reports only at the firstdecode step. The
symtabletest below now fails immediately on this whole class ofmistake, naming the file, the function and the symbol.
torch.device(0)is not always constructible. On torch 2.6.0 with no accelerator visible,which is how a CPU only runner looks, the bare integer form raises
RuntimeError: Cannot access accelerator device when none is available. That was thedefault path in the first version. Every conversion in the helper now goes through
_as_torch_device, so resolving a layer's device is never itself the thing that fails, andthe test computes its expectation from whether the bare integer form is constructible at
all rather than hardcoding one torch version's answer.
Compatibility
Nothing about the CUDA path moves.
Llama-3.2-1B-Instruct, greedy, 16 new tokens, on the sameGPU:
main[128000, 791, 6864, 315, 9822, 374, 12366, 13, 578, 469, 3168, 301, 22703, 374, 7559, 304, 12366, 13, 578, 469, 3168, 301]_per_layer_device_indexforced to None on every layermainwith the index forced to None raises the reportedValueErrorinstead.A layer carrying neither attribute, which is every model that never went through
verify_and_set_device, resolves totorch.device(0), which is what the previousgetattr(layer, "_per_layer_device_index", 0)produced. There is no behaviour change for it.Environment: python 3.13, torch 2.14.0+cu130, transformers 5.17.0, TRL 1.13.0, PEFT 0.20.0,
Linux, one NVIDIA B200.
Version matrix, seven corners, run through the fix pass harness:
The torch 2.6.0 corner earned its place:
torch.device(0)raisesRuntimeError: Cannot access accelerator device when none is availablethere when noaccelerator is visible, which is how a CPU-only CI runner looks. Every conversion in the
helper goes through
_as_torch_devicefor that reason, so resolving a layer's device isnever itself the thing that fails.
Tests
tests/test_per_layer_device_readers.py, 37 tests, CPU only apart from one GPU assertion.per_layer_deviceover all five attribute shapes, including a garbage index.move_to_deviceaccepts whatever the helper returns, in every shape, and thebuffer index subscripts a per accelerator tuple.
move_to_device, plus the assertion that a literalNone is still rejected loudly.
unsloth_zoo.patching_utils.verify_and_set_device, so writer andreader are checked against each other rather than against a comment.
is what reaches
move_to_device, and the helper is imported explicitly.symtablelocates the reader from its own call site and fails if thatscope reads a name it never binds. This is not theoretical. Binding only the device in
llama and discarding the index leaves
temp_gates[device_index]andtemp_ups[device_index]reading a name that no longer exists, which Python only reports at the first decode step;
the test fails immediately and names the file, the function and the symbol.
torch.cuda.current_device().cpuandmetaare usable, an unknown backend is taken at itsword,
cudafollowstorch.cuda.is_available, and with the probe spoofed off a layer withno recorded device resolves to its own parameters rather than to an accelerator the host
does not have. The control, with the probe spoofed on, keeps the historical default.
36 of the 37 fail on
mainand pass here. The one that passes there is the per acceleratortuple check for granite, which has no such tuple and is vacuous in that file.
Alongside them:
tests/test_import_fixes_drift.py26 passed and 10 skipped, the collectiondrift gate 275 collected, and 577 passed with 11 skipped across every test file that imports
models._utilsor one of the five model modules.pytest --collect-only tests/collects23969 against 23942 on
main, the difference being exactly these tests, with the same 9pre existing Studio collection errors on both.
Evidence
Logs live in the
logs/directory of the environment that produced them; the repro scripttees one per mode, and the matrix harness names its own.
main, greedy generate on cudamain,_per_layer_device_indexforced to None on every layerValueError: Invalid target device: NoneRESULT_3538_cuda PASSandRESULT_3538_none PASS, identical ids in bothRESULT_3538_cpu PASS resolved=cpu buffer_index=0matrix_mA_per-layer-device.logthroughmatrix_mX2_per-layer-device.logThe single skip in the new file is the GPU assertion, which is skipped when
CUDA_VISIBLE_DEVICESis empty.Kaggle T4x2
The readers here and the companion change that publishes the attribute were run together on real hardware, on two accelerators, which is the configuration issue 3538 describes.
The per layer device change was run on two real accelerators, which is the configuration issue 3538 describes: a Kaggle kernel with two Tesla T4s. With unsloth's own planner the 1B model spreads across both cards and
verify_and_set_devicerecords indices 0 and 1; generation produces byte identical token ids on main and on this branch (md5 5e316fcdb6fa), on one card, on the default two card placement, and on amax_memoryforced split, on both ends of the version matrix. Forcing the index to None, which is what an older unsloth_zoo writes for a layer with no index, raisesValueError: Invalid target device: Noneon main and generates normally on this branch. The case that needs two cards: withmax_memory = {0: "700MiB", 1: "700MiB", "cpu": "16GiB"}accelerate offloads whole decoder layers off the accelerators, and their parameters sit on the meta device, whose.indexis None exactly as the CPU's is. On main those layers are recorded asrecorded=['1', None]; on this branch asrecorded=['meta', 1], which is what the change publishes. Generation with such a layer still fails on both sides, now with an illegal memory access rather than the None ValueError, because the float32 layernorm and MLP scratch buffers are still allocated one per accelerator; that limitation is unchanged by this PR and is stated as such. The new tests go from 33 failed, 1 passed on main to 34 passed on the branch in unsloth, and from 8 failed, 4 passed to 12 passed in unsloth-zoo.Colab L4
The same pair of trees was run on a rented Colab L4, one NVIDIA L4, compute capability 8.9, with torch 2.14.0, transformers 5.17.0, TRL 1.13.0 and PEFT 0.20.0 in a venv built on the VM, so the single card behaviour is answered on the most common paid Colab tier as well. The ordinary CUDA path does not move, generating the same 24 token ids on
mainand on this branch, while the recorded device attribute goes from absent todevice(type='cuda', index=0), which is the publication half of the change. Forcing the index to None on every decoder layer, which is what an older unsloth_zoo writes for a layer with no device index, raisesValueError: Invalid target device: Noneonmainand generates normally on this branch. The resolver is exercised directly as well: with the attributes a CPU resident layer now carries, the branch resolves tocpuwith buffer index 0, while onmainthe helper does not exist. The new tests move from 33 failed and 1 passed to 34 passed here, and from 8 failed and 4 passed to 12 passed in unsloth-zoo. One case is not answerable on this hardware and is reported rather than claimed: with a 700 MiB budget on a single 24 GB card, accelerate routed the decoder layers to the CPU inhf_device_mapbut left their parameters on themetadevice, so no layer was CPU resident when the reader ran and the probe reported not applicable on both phases. The genuine placement variants need more than one accelerator and belong to the two card run above.Known limitations
probe skips rather than reporting a false pass. Its CPU cell passes, and it is the corner
that found the
torch.device(0)bug above.T4s with
max_memory = {0: "700MiB", 1: "700MiB", "cpu": "16GiB"}the offloaded layers arenow recorded as
metainstead of None, so the reader resolves them, but generation thendies with
CUDA error: an illegal memory access was encounteredon bothmainand thisbranch, because the float32 layernorm and MLP scratch buffers are still allocated one per
accelerator and a layer that is not on one has no buffer of its own. This PR removes the
None, it does not make that configuration work.
either attribute, but the four sibling readers are covered by the source level and
symtabletests rather than by a GPU run of their own, since only the llama path has arepro here.
Refs #3538
Pairs with unslothai/unsloth-zoo#1229
What this PR fixes on its own, and what needs unsloth-zoo#1229
Measured at 1, 2, 4 and 8 B200s and on a 2xT4 Kaggle session, with three trees: the merge base,
this head with unsloth_zoo on main (the layout every existing install has), and this head
paired with unsloth-zoo#1229.
Noneon every layerValueError: Invalid target device: Noneper_layer_devicein this treecpu['1','None']/['1','2','3','None']/['1'..'7','None']['0','1']/['0'..'3']/['0'..'7']So this PR alone does not fix the offloaded-layer case. What it fixes on its own is that the
reader no longer crashes when handed a
None: the forced-Nonerow goes FAIL to PASS withunsloth_zoo untouched. The attribute that carries a real device for an offloaded layer is written
by unsloth-zoo#1229, so the offload row needs that PR alongside this one.
Merge order: either order is fine and neither breaks the other; the offload behaviour only
appears once both are in. This PR is safe to merge first and is a strict improvement on its own
(a crash becomes a correct resolution); unsloth-zoo#1229 is safe to merge first and is inert
without a reader that uses the device it publishes.
Generation with a layer genuinely off the accelerators still fails identically on all three trees
(
AcceleratorError: CUDA error: an illegal memory access was encounteredon the B200, the same onthe T4). That is the pre-existing limitation this PR does not address: the float32 layernorm and
MLP scratch buffers are allocated one per accelerator. The docstring says so now rather than
implying otherwise.
The generated token ids are byte-identical to the single-device run (
ids_md5 59c4e9318565) onevery tree at every device count, which is the "an ordinary user sees no difference" half.
Review round: meta is never an activation target
Codex raised that a CPU or meta placement leaves the accelerator-only inference path
inconsistent. The meta half is real and worse than it reads:
tensor.to("meta")SUCCEEDS anddiscards the data, and
torch.matmul(meta, cuda)returns a meta tensor rather than raising, so adecode would run to completion and produce nothing. That is strictly worse than the ValueError
this reader replaces.
per_layer_devicenow refuses meta on every route, asks accelerate's_hf_hook.execution_devicefirst (which is whereAlignDevicesHook.pre_forwardsends thelayer's own inputs) and falls back to
defaultotherwise. On 8 B200s with layer 0's publisheddevice parked on meta, the pre-fix reader fails
layer 0 resolved to metaand the fixed onegenerates the same token ids as the 1, 2, 3, 4 and 8 device runs. The zoo half of the same defect
is unsloth-zoo#1229.
The CPU half is not taken here, for the reason in the table above: it is a loud cross-device
RuntimeError, not a silent wrong answer, and a CPU-offloaded inference path is separate work.
Per-token cost, re-measured
This reader runs once per decoder layer per generated token, so the meta guard was measured
rather than assumed. Checked up front it cost +132 ns on every call on every shape, undoing a
third of the reduction commit
d6b57d25had won. It now sits behindbuffer_index is None: anindexed accelerator device can never be meta, and
.indexis read once either way, so only alayer already off an indexed device pays the
.typeread (~147 ns).B200, 200,000 iterations, 15 repeats, median, same process:
.indexThe same regression and its earlier fix reproduce on a Tesla T4: index-only shape 64.1 ns on
main, 3563.3 ns as opened (55.5x), 1079.0 ns at the current head (16.8x). So it is a property of
the code, not of sm_100.
What that per-call figure costs a real run
The ratio is real in isolation and it is worth stating what it is not. All five changed call
sites are inside
*_fast_forward_inference(llama.py:1270,gemma.py:193,gemma2.py:485,cohere.py:445,granite.py:453). Counted by wrappingmove_to_device, which is used at exactlythose five places and nowhere else:
So this reader is not on the training path at all, and its only hot path is single-token decode:
549 ns per call times 16 calls is 8.8 us against a measured 15,800 us per token, 0.056%.
End to end, 61 steps, batch 2 x accumulation 3, sequence 2048, seed 3407,
Llama-3.2-1B-Instruct 4bit, three repetitions per arm, decode rotated over six processes per arm
and taken as the median of 21 generations of 256 tokens:
Read the control rows before the head rows. Two independent checkouts of the same commit, through
the identical harness, differ by -2.58% on one-GPU decode, which is the whole of the -2.55%
attributed to the branch. The harness floor is roughly 2.6 to 4% for decode and 7 to 14% for
training wall time, against a predicted effect of 0.056%. The claim here is not that the branch is
2.55% slower; it is that no harness on this host can resolve an effect this small, and the
arithmetic bounds it three orders of magnitude below the floor.
The two-GPU arm is genuinely pipeline-parallel, layers 0 to 7 on cuda:0 and 8 to 15 on cuda:1,
with
_per_layer_device_indexreally taking both values and activations crossing devices at everylayer boundary. A first attempt was discarded as void because Unsloth placed all 16 layers on
cuda:0 and therefore measured nothing. The installed unsloth_zoo publishes only
_per_layer_device_index, which is the shape this reader is slowest on, so these are worst-casenumbers.
Correctness over the same runs: maximum loss deviation across 61 logged steps is 0.0028 on one GPU
and 0.0037 on two, against main-against-main controls of 0.0032 and 0.0030, so the two arms agree
at least as closely as main agrees with itself. Greedy decode output is byte-identical in both
layouts.
This bounds a 16-layer model. On a 100-layer model the per-token cost scales with the layer count,
but so does per-token compute, so the ratio does not worsen. That was not measured directly.
Pre-existing CI failures, named rather than fixed here
unslothai/unslothmainis itself red onRepo tests (CPU, studio)and(Python 3.13, rest)(run 35060623218). The same two jobs fail on this PR and on several unrelated ones in the same
batch, with the same tests:
tests/multi_account/test_chat_shared_resident.py(3 tests,{"detail":"Failed to get status"})and
tests/studio/test_chat_preset_load_config.py::test_preset_sheet_reacts_to_a_reasoning_budget_change.Neither touches anything this PR changes, so they are recorded here and left to their owner
rather than fixed inside an unrelated PR.