Skip to content

Resolve the per layer device through a helper instead of a raw index - #11020

Merged
danielhanchen merged 20 commits into
mainfrom
pr/per-layer-device-readers
Sep 17, 2026
Merged

danielhanchen merged 20 commits into
mainfrom
pr/per-layer-device-readers

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

Summary

Sampling from inside a TrainerCallback raised ValueError: Invalid target device: None
because a decoder layer with no device index reached move_to_device. This routes all five
pipeline 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_device records where each decoder layer lives so
the fast inference paths can move activations onto it. It recorded device.index, and
torch.device("cpu").index and torch.device("meta").index are both None. Every reader then
did:

device_index = getattr(decoder_layer, "_per_layer_device_index", 0)
... = move_to_device(device_index, ...)

move_to_device takes int, str or torch.device and raises for anything else. The
getattr default never fires, because the attribute exists and is simply None.

Reported stack: SFTTrainer callback, model.generate, unsloth_fast_generate,
_CausalLM_fast_forward, LlamaModel_fast_forward_inference_custom, move_to_device.

Changes

unsloth/models/_utils.py

New per_layer_device(module, default = 0), directly above move_to_device. It probes what
is on the module instead of checking a version, and returns the device to move to plus an int
buffer index:

module carries resolution
_per_layer_device, a torch.device that device
only the index, an int or a device type string torch.device(index)
only the index, and it is None the device of the layer's own parameters
neither torch.device(default) when that device exists, else the layer's own parameters
an index torch.device() rejects torch.device(default), no raise

default is resolved through a backend probe rather than a bare torch.device(0). torch 2.6
raises "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:0 from the same call on the same host and only fail when a tensor is
moved there. A CPU only host therefore resolved a layer with no recorded device to cuda:0
and ended in "RuntimeError: No CUDA GPUs are available" on every torch newer than the one the
fallback was written against. Asking torch.<type>.is_available makes both torch versions
answer the same, and a backend that publishes no such function is taken at its word, which is
what keeps meta usable 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_weights in gemma, gemma2 and cohere, and temp_gates
plus temp_ups in llama. A torch.device cannot do that, so the index stays an index.

unsloth/models/{llama,granite,gemma,gemma2,cohere}.py

Each reader now does:

layer_device, device_index = per_layer_device(decoder_layer)
hidden_states, position_ids = move_to_device(layer_device, hidden_states, position_ids)

and each imports the helper explicitly from ._utils rather than relying on
from .llama import * to carry the name across. move_to_device is not in _utils.__all__,
so that route was never guaranteed for it either.

The companion change that publishes _per_layer_device is unslothai/unsloth-zoo#1229. This PR
does 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.

  1. An unbound name. The first version wrote layer_device, _ = per_layer_device(decoder_layer)
    in llama, discarding the index, because a grep for move_to_device does not show that
    llama.py:1302-1303 uses temp_gates[device_index] and temp_ups[device_index] further
    down the same loop body. The GPU run failed with
    NameError: name 'device_index' is not defined, which Python reports only at the first
    decode step. The symtable test below now fails immediately on this whole class of
    mistake, naming the file, the function and the symbol.
  2. 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 the
    default 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, and
    the 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 same
GPU:

revision tokens
main [128000, 791, 6864, 315, 9822, 374, 12366, 13, 578, 469, 3168, 301, 22703, 374, 7559, 304, 12366, 13, 578, 469, 3168, 301]
this PR identical
this PR, with _per_layer_device_index forced to None on every layer identical

main with the index forced to None raises the reported ValueError instead.

A layer carrying neither attribute, which is every model that never went through
verify_and_set_device, resolves to torch.device(0), which is what the previous
getattr(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:

corner python torch transformers TRL PEFT tests GPU generate
mA 3.10 2.6.0 4.57.6 0.22.2 0.18.0 pass not run, cu124 wheels have no sm_100 SASS on this card
mB 3.13 2.8.0 5.0.0 0.27.2 0.19.1 pass pass
mC 3.13 2.11.0 5.5.0 1.0.0 0.20.0 pass pass
mD 3.13 2.14.0 5.17.0 1.13.0 0.20.0 pass pass
mX1 3.13 2.14.0 5.17.0 1.13.0 0.18.0 pass pass
mX1b 3.13 2.14.0 5.17.0 1.13.0 0.18.0 pass pass
mX2 3.13 2.11.0 4.57.6 1.13.0 0.19.1 pass pass

The torch 2.6.0 corner earned its place: torch.device(0) raises
RuntimeError: Cannot access accelerator device when none is available there when no
accelerator is visible, which is how a CPU-only CI runner looks. Every conversion in the
helper goes through _as_torch_device for that reason, so resolving a layer's device is
never itself the thing that fails.

Tests

tests/test_per_layer_device_readers.py, 37 tests, CPU only apart from one GPU assertion.

  • per_layer_device over all five attribute shapes, including a garbage index.
  • The real move_to_device accepts whatever the helper returns, in every shape, and the
    buffer index subscripts a per accelerator tuple.
  • The verbatim failure, driven through move_to_device, plus the assertion that a literal
    None is still rejected loudly.
  • A round trip through unsloth_zoo.patching_utils.verify_and_set_device, so writer and
    reader are checked against each other rather than against a comment.
  • Per reader file: the raw attribute read is gone, the helper is called, the resolved device
    is what reaches move_to_device, and the helper is imported explicitly.
  • Per reader file: symtable locates the reader from its own call site and fails if that
    scope 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] and temp_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.
  • On a real GPU: the layer's own cuda device and torch.cuda.current_device().
  • The accelerator probe: cpu and meta are usable, an unknown backend is taken at its
    word, cuda follows torch.cuda.is_available, and with the probe spoofed off a layer with
    no 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 main and pass here. The one that passes there is the per accelerator
tuple check for granite, which has no such tuple and is vacuous in that file.

Alongside them: tests/test_import_fixes_drift.py 26 passed and 10 skipped, the collection
drift gate 275 collected, and 577 passed with 11 skipped across every test file that imports
models._utils or one of the five model modules. pytest --collect-only tests/ collects
23969 against 23942 on main, the difference being exactly these tests, with the same 9
pre existing Studio collection errors on both.

Evidence

Logs live in the logs/ directory of the environment that produced them; the repro script
tees one per mode, and the matrix harness names its own.

what result in the log
main, greedy generate on cuda the 22 token id sequence in the table above
main, _per_layer_device_index forced to None on every layer the reported ValueError: Invalid target device: None
this PR, the same two modes RESULT_3538_cuda PASS and RESULT_3538_none PASS, identical ids in both
this PR, attributes published the way the companion change does, no accelerator RESULT_3538_cpu PASS resolved=cpu buffer_index=0
the new test file, the drift gate, the collection gate, and every suite importing the touched modules 33 passed and 1 skipped, 26 passed and 10 skipped, 275 collected, 577 passed and 11 skipped
version matrix one log per corner, matrix_mA_per-layer-device.log through matrix_mX2_per-layer-device.log

The single skip in the new file is the GPU assertion, which is skipped when
CUDA_VISIBLE_DEVICES is 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_device records 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 a max_memory forced 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, raises ValueError: Invalid target device: None on main and generates normally on this branch. The case that needs two cards: with max_memory = {0: "700MiB", 1: "700MiB", "cpu": "16GiB"} accelerate offloads whole decoder layers off the accelerators, and their parameters sit on the meta device, whose .index is None exactly as the CPU's is. On main those layers are recorded as recorded=['1', None]; on this branch as recorded=['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 main and on this branch, while the recorded device attribute goes from absent to device(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, raises ValueError: Invalid target device: None on main and generates normally on this branch. The resolver is exercised directly as well: with the attributes a CPU resident layer now carries, the branch resolves to cpu with buffer index 0, while on main the 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 in hf_device_map but left their parameters on the meta device, 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

  • mA's GPU cell was not run: that corner's cu124 wheels carry no SASS for this card, so the
    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.
  • A decoder layer that is genuinely off the accelerators still cannot generate. On two real
    T4s with max_memory = {0: "700MiB", 1: "700MiB", "cpu": "16GiB"} the offloaded layers are
    now recorded as meta instead of None, so the reader resolves them, but generation then
    dies with CUDA error: an illegal memory access was encountered on both main and this
    branch, 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.
  • Five readers exist and all five are changed. There is no sixth, and Studio does not read
    either attribute, but the four sibling readers are covered by the source level and
    symtable tests rather than by a GPU run of their own, since only the llama path has a
    repro 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.

case base this PR, zoo on main this PR + zoo#1229
index forced to None on every layer FAIL ValueError: Invalid target device: None PASS PASS
resolver asked for a CPU layer n/a, no per_layer_device in this tree PASS, resolves to cpu PASS
decoder layers offloaded off every accelerator, 2 / 4 / 8 devices FAIL, records ['1','None'] / ['1','2','3','None'] / ['1'..'7','None'] FAIL, same PASS, records ['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-None row goes FAIL to PASS with
unsloth_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 encountered on the B200, the same on
the 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) on
every 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 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. That is strictly worse than the ValueError
this reader replaces.

per_layer_device now refuses meta on every route, asks accelerate's
_hf_hook.execution_device first (which is where AlignDevicesHook.pre_forward sends the
layer's own inputs) and falls back to default otherwise. 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 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 d6b57d25 had won. It now sits behind buffer_index is None: an
indexed accelerator device can never be meta, and .index is read once either way, so only a
layer already off an indexed device pays the .type read (~147 ns).

B200, 200,000 iterations, 15 repeats, median, same process:

layer shape before the meta guard with it, checked up front with it, behind .index
device and index published 166.57 ns 335.09 ns 166.48 ns
index only, every existing install 653.45 ns 785.93 ns 650.39 ns
neither attribute 1758.00 ns 1798.53 ns 1737.37 ns

The 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 wrapping move_to_device, which is used at exactly
those five places and nowhere else:

  • a LoRA training step calls it 0 times, over 61 steps, every arm, one and two GPUs
  • greedy decode calls it 16 times per token, one per layer

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:

case metric main this branch delta
1 GPU train steps/sec 2.4338 2.3034 -5.36%
1 GPU train peak memory 1546.21 MiB 1546.21 MiB bit-identical
1 GPU decode tok/s 63.414 61.799 -2.55%
1 GPU decode, main against main 63.414 61.776 -2.58%
2 GPU train steps/sec 2.1671 1.9405 -10.45%
2 GPU train peak memory 1618.42 MiB 1618.42 MiB bit-identical
2 GPU decode tok/s 57.291 57.141 -0.26%
2 GPU decode, main against main 57.291 58.222 +1.62%

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_index really taking both values and activations crossing devices at every
layer 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-case
numbers.

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/unsloth main is itself red on Repo 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.

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
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 15, 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-09-17T09:55:43.184884Z 9f5ecac Manual request
ℹ️ 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 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: 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".

Comment thread unsloth/models/_utils.py
Comment on lines +2600 to +2602
if device is None:
if index is None:
device = _device_of_parameters(module)

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

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.

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.

pre-commit-ci Bot and others added 3 commits September 15, 2026 15:06
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.
@danielhanchen

Copy link
Copy Markdown
Member Author

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.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 16, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 16, 2026
danielhanchen and others added 5 commits September 16, 2026 04:56
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.
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 524adf3439

ℹ️ 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 self-assigned this Sep 16, 2026
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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 8bce7338f5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

Performance on 1 GPU and on 2 GPUs

Measured, with a negative control, on 8x NVIDIA B200, torch 2.14.0+cu130, transformers 4.57.6,
TRL 0.24.0. Arms are separate worktrees selected by PYTHONPATH, nothing edited in place:

  • main (merge base) 12865908
  • PR head 524adf34
  • negative control: a second independent checkout of 12865908

The installed unsloth_zoo publishes only _per_layer_device_index (patching_utils.py:320), which
is the shape the new reader is slowest on, so this is the worst case rather than the best.

Where the changed code runs, counted rather than assumed

All five changed call sites are inside *_fast_forward_inference. Counting move_to_device, which
is used at exactly those five sites and nowhere else, in a real run:

path calls
LoRA training step 0 per step (61 steps, 0 total, every arm, 1 and 2 GPU)
greedy decode 16 per decoded token, which is n_layers, so 4080 per 256 tokens

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

layer device measurement main this PR delta
cuda:0 reader only 37.2 ns 629.1 ns +591.9 ns (16.9x)
cuda:0 reader plus move_to_device 591.0 ns 1140.0 ns +549.0 ns (1.93x)
cuda:1 reader only 38.6 ns 667.1 ns +628.5 ns
cuda:1 reader plus move_to_device 562.3 ns 1118.3 ns +556.0 ns

Predicted end to end cost: 549 ns x 16 calls per token = 8.8 us per decoded token, against a
measured 15,800 us per token. That is 0.056% of decode and 0.000% of training.

End to end, 61 steps, bs2 x ga3, seq 2048, seed 3407, Llama-3.2-1B-Instruct 4bit, 3 reps per arm

1 GPU:

metric main this PR delta inside noise
train steps/sec 2.4338 2.3034 -5.36% yes, base 95% CI +/-6.5%, neg control +0.71%
train wall s 25.0755 26.7833 +6.81% yes
train peak mem MiB 1546.21 1546.21 0.00% bit identical

2 GPU pipeline parallel, GPUs 2 and 3, layers 0-7 on cuda:0 and 8-15 on cuda:1, so
_per_layer_device_index really takes both values:

metric main this PR delta inside noise
train steps/sec 2.1671 1.9405 -10.45% yes, base 95% CI +/-13.7%, neg control -4.3%
train wall s 28.2067 32.0771 +13.72% yes
train peak mem MiB 1618.42 1618.42 0.00% bit identical
decode tok/sec 57.611 58.094 +0.84% yes

Rotated decode only run, arm order permuted every rep so run order drift cannot alias onto one arm,
6 processes per arm, median of 21 generations of 256 tokens:

layout main this PR head minus base same-code negative control
1 GPU 63.414 tok/s (sd 1.684, 95% CI +/-2.79%) 61.799 tok/s -2.55% -2.58%
2 GPU 57.291 tok/s (sd 2.182, 95% CI +/-4.00%) 57.141 tok/s -0.26% +1.62%

The negative control reproduces the entire 1 GPU decode delta from two identical checkouts of main.
The harness resolution floor is about 2.6 to 4% for decode and 7 to 14% for training wall time; the
predicted effect is 0.056%, three orders of magnitude below that floor.

Correctness

check 1 GPU 2 GPU
loss curve max abs difference over 61 logged steps 0.0028 (control 0.0032) 0.0037 (control 0.0030)
final loss main 1.2536, 1.2531, 1.2530 1.2535, 1.2547, 1.2533
final loss this PR 1.2529, 1.2537, 1.2531 1.2534, 1.2529, 1.2533
greedy decode output byte identical yes yes
peak memory bit identical bit identical

Agreement between the arms is at or below main's agreement with itself, so the tolerance is the
harness determinism floor, roughly 4e-3 on a logged loss, not a drift.

Verdict

1 GPU: performance identical. The changed reader is called zero times per training step, and the
decode path cost is 8.8 us/token against a 15.8 ms/token budget.

2 GPU: no regression. Pipeline parallel decode -0.26% against a +1.62% same code control, with loss
curves and greedy outputs identical.

The 16.9x per call figure for the reader in isolation is real, and it is 592 ns on a 15,800,000 ns
per token path.

…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.
@danielhanchen

Copy link
Copy Markdown
Member Author

Correction to the microbenchmark above, and a 1 GPU improvement

The reader-only figures in my previous comment (37.2 ns against 629.1 ns, 16.9x) were taken on
565c849, the commit BEFORE the memoised fast path landed in 8bce733. Re-running the identical
harness against 565c849 reproduces them exactly, 633.7 ns reader-only and 1173.0 ns reader plus
move_to_device, which is what identifies the mistake. They are not the cost of this PR as it
stands. The end-to-end numbers in that comment are unaffected, since the changed reader is called
zero times per training step either way.

Does the memo actually hit

Counted, not assumed. A branch-for-branch counting twin of the live head source, over a real greedy
decode of 256 tokens, Llama-3.2-1B-Instruct 4bit, 16 layers:

counter calls share
total 4080 100.00%
fast-path hit 4064 99.61%
miss, no memo yet 16 0.39%
memo written, published-index route 16 0.39%

4080 is 255 decode steps times 16 layers; prefill does not go through this loop. The 16 misses are
exactly one cold miss per layer on the first decode step, and no slow route is ever re-entered.
Neither suspect fires: all five call sites pass default = 0, and LlamaDecoderLayer has a normal
__dict__.

The real current cost, and the improvement

200k iterations by 15 repeats, one process, arm order rotated, negative control 0.6 to 11.2 ns.
Reader-only medians in nanoseconds:

published shape merge base head e0feb19 head plus this change delta
index, which is what unsloth_zoo actually writes 26.9 90.4 70.1 -20.3
device 438.2 89.3 77.3 -12.0
neither name published 432.4 2104.5 127.6 -1976.9

Reader plus move_to_device: 574.0 to 537.9, 573.1 to 548.3, and 2654.0 to 593.8.

Two things came out of the search. Reading the memo as an attribute rather than through
module.__dict__[key] is worth about 20 ns, because one specialised LOAD_ATTR beats the __dict__
descriptor plus a dict lookup, and the memo lives in the instance dict either way. More importantly,
a layer that publishes NEITHER name was never memoised at all and cost 2104 ns per layer per token
in three failed nn.Module.__getattr__ scans, each of which walks _parameters, _buffers and
_modules before raising. That shape is memoisable, because the answer comes from default and
nothing on the module.

Three alternatives were measured and rejected: two separate memo attributes (55.9 ns on an
index-published layer but 647.7 ns on a device-published one, a failed attribute lookup every call),
dropping the per-layer memo entirely (128.7 ns), and three plain attributes (68.5 ns, worse than the
tuple).

What the new route gives up, stated rather than glossed

The absent-shape route validates with "_per_layer_device_index" not in __dict__ and "_per_layer_device" not in __dict__. That catches instance-level publication, which is how
verify_and_set_device writes, and it would not catch either name being monkeypatched onto the
layer's CLASS between forwards. It is guarded on from_default, so a device read off the layer's own
parameters, which moves when the layer moves, is still never memoised. A test asserts that.

Pushed as 9d79c19c5fd0d5d42734372f883e658e0cdd2c6e, two files, +133 / -22.
tests/test_per_layer_device_readers.py 57 passed, 53 existing plus 4 covering the new route and its
invalidation. The wider set, the five model files plus device helpers, stopping criteria, import-fix
drift, fast-generate guard, gemma cache selection and dispatch hook repair: 240 passed, 6 skipped.
The real 256-token decode on the new code holds the same 99.61% hit rate.

Not claimed

No tokens per second delta. 20 ns times 16 layers is 0.3 us per token against a decode step of about
10 ms, which is far below run-to-run noise, so the gain is real per call and invisible in aggregate
on this shape. The publish = neither gain, 2 us times 16 layers, would be visible, but that shape
was never observed in a real run: unsloth_zoo 2026.9.3 publishes _per_layer_device_index on every
layer. One GPU only; the device-published and non-zero-index shapes were benchmarked on synthetic
layers. The four non-llama call sites are covered by source-level and unit tests, not by a real
decode.

@danielhanchen

Copy link
Copy Markdown
Member Author

What this PR is for, in plain terms

Unsloth can split one model across several GPUs, so layer 1 might live on GPU 0 and layer 20 on
GPU 1, and layers can be pushed onto the CPU when GPU memory runs short. Before running each layer,
Unsloth has to move the text being generated onto whatever device that layer is on.

It used to do that by reading a plain number off the layer saying which GPU it was. A layer sitting
on the CPU has no such number, so the value read back was empty, and the move then stopped with

Invalid target device: None

in the middle of generating (#3538). The user was not doing anything exotic: they were running a
model that did not quite fit, which is the case the CPU offload exists for.

This PR replaces those five copy-pasted lookups with one shared helper that works out the real
answer and returns two things: the actual device, and a number that is always safe to use as an
array subscript. Both halves are needed, because gemma, gemma2 and cohere index a per-device tuple
with that number, which a device object cannot do.

It is probed rather than version-gated, because the shape published by unsloth_zoo has changed over
time: an older zoo publishes only the index, and that index is None on an accelerator layer it named
without one, which is exactly the failure above. meta is excluded from every route, because moving
an activation there destroys it silently.

What it does NOT fix, stated so nobody expects it to: a layer genuinely on the CPU while
temp_gates or out_weights sit on an accelerator still ends in a loud cross-device RuntimeError.
That is a different bug and it is meant to be loud.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 9f5ecac231

ℹ️ 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 merged commit 2a28379 into main Sep 17, 2026
44 of 53 checks passed
@danielhanchen
danielhanchen deleted the pr/per-layer-device-readers branch September 17, 2026 10:31
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 17, 2026
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.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants