Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

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

Daniel Han2a283793b531
diff --git a/studio/backend/tests/test_diffusers_prewarm.py b/studio/backend/tests/test_diffusers_prewarm.py
index 77359f29a36..31dc70e5651 100644
--- a/studio/backend/tests/test_diffusers_prewarm.py
+++ b/studio/backend/tests/test_diffusers_prewarm.py
@@ -3,22 +3,12 @@
"""Pre-importing diffusers off the first image load.
-The first diffusion load in a fresh process pays about 5.3s of pure import before it touches a
-weight (``diffusers`` 1.6s, ``diffusers.hooks`` 2.4s, the pipeline classes 1.3s). None of it
-depends on which model was picked, so it can be paid earlier on a thread nobody waits on.
-Measured end to end, the load path's own import work drops from 4.47s to 0.60s, at the same
-peak RSS: the memory is paid either way, just earlier.
-
-The tests below pin the properties that make that safe to ship rather than the speedup itself:
-
- 1. A chat-only or training-only install pays NOTHING. The gate must not import diffusers when
- there is no local image or video model, which is the whole reason the gate exists.
- 2. Every failure mode degrades to "skip", never to an exception: the post-warm worker also
- carries MLX repair and linked-folder sync.
- 3. It runs from the POST-warm worker, after the coordinated warm, so it cannot delay a warm
- stage or the socket bind.
- 4. The tqdm quieting that diffusers forces at import is applied here too, or the prewarm would
- write progress bars onto the structlog stream.
+These tests pin the properties that make paying that import early safe, not the speedup:
+
+ 1. A chat-only or training-only install pays NOTHING.
+ 2. Every failure mode degrades to "skip": the post-warm worker also carries MLX repair.
+ 3. It runs from the POST-warm worker, so it cannot delay a warm stage or the socket bind.
+ 4. The tqdm quieting diffusers forces at import is applied here too.
None of these import the real diffusers, which is the point of stubbing it.
"""
@@ -41,10 +31,7 @@ _BACKEND = Path(__file__).resolve().parent.parent
def restore_diffusers_modules():
"""Put back every ``diffusers*`` entry this test disturbs.
- The purge tests call the real ``purge_partial_import``, which evicts whatever ``diffusers``
- submodules the session had already imported. monkeypatch cannot undo that: it only restores
- keys it set itself, so the eviction leaks into later tests, which then rebuild a partial
- diffusers and fail for reasons that have nothing to do with them.
+ monkeypatch only restores keys it set itself, so the real purge leaks into later tests.
"""
saved = {name: mod for name, mod in sys.modules.items() if name.split(".")[0] == "diffusers"}
try:
@@ -74,9 +61,7 @@ def _stub_gate(
):
"""Stand in for the media index and the engine router.
- ``engine`` is what a load of these models would select. It is not decoration: a CPU or MPS
- host routes a supported GGUF to sd.cpp, which imports no diffusers, so "a model exists" and
- "diffusers would be used" are different questions and only the second one may prewarm.
+ ``engine`` is not decoration: a CPU or MPS host routes a supported GGUF to sd.cpp.
"""
idx = types.ModuleType("core.inference.media_model_index")
@@ -163,11 +148,8 @@ def test_a_video_only_install_also_prewarms(warm, monkeypatch):
def test_a_video_only_install_of_an_h3_gguf_pays_nothing(warm, monkeypatch):
"""MiniMax H3 as a GGUF is the one video combination that never imports diffusers.
- ``VideoBackend.load_pipeline`` asks ``is_h3_native(fam, kind)`` and returns through
- ``_run_load_h3_native`` before its own ``import diffusers``. The image resolver cannot see
- this: ``detected_image_family`` has no answer for a ``VideoFamily``, so the "unknown family"
- branch would call it diffusers and charge an H3-only install 316 MB it never uses. Uses the
- real family detector and the real predicate, so a rename on either side fails here.
+ ``VideoBackend.load_pipeline`` returns through ``_run_load_h3_native`` before its own
+ ``import diffusers``, and ``detected_image_family`` cannot place a ``VideoFamily``.
"""
_stub_gate(monkeypatch, {"text-to-image": [], "text-to-video": ["unsloth/MiniMax-H3-GGUF"]})
seen = _stub_diffusers(monkeypatch)
@@ -179,13 +161,7 @@ def test_a_video_only_install_of_an_h3_gguf_pays_nothing(warm, monkeypatch):
def test_an_h3_gguf_named_only_by_its_filename_pays_nothing(warm, monkeypatch):
- """The supported layout the repo id alone cannot answer for.
-
- A local directory or a generically named repo often carries the family token only in the
- checkpoint filename, which is why video.py's own ``_detect_load_family`` tries the repo id
- and then ``f"{repo_id}/{gguf_filename}"``. Looking at the id alone leaves this install
- prewarming 316 MB for a load that returns through ``_run_load_h3_native``.
- """
+ """The family token can live only in the checkpoint filename, so video.py tries both."""
_stub_gate(monkeypatch, {"text-to-image": [], "text-to-video": ["custom-video"]})
sys.modules["core.inference.media_model_index"].resolve_local_media_model = (
lambda model_id, task: types.SimpleNamespace(
@@ -202,12 +178,7 @@ def test_an_h3_gguf_named_only_by_its_filename_pays_nothing(warm, monkeypatch):
def test_a_video_family_we_cannot_identify_still_prewarms(warm, monkeypatch):
- """The H3 skip is an exception carved out of the default, not a new default.
-
- Every other video load reaches video.py's ``import diffusers``, so anything the detector
- cannot place must keep prewarming. Getting this backwards would silently drop the feature
- for every video user whose repo id is not in the family table.
- """
+ """The H3 skip is an exception: every other video load reaches `import diffusers`."""
_stub_gate(monkeypatch, {"text-to-image": [], "text-to-video": ["someone/private-repack"]})
_stub_diffusers(monkeypatch)
@@ -215,10 +186,7 @@ def test_a_video_family_we_cannot_identify_still_prewarms(warm, monkeypatch):
def test_the_torch_warm_opt_out_also_disables_the_prewarm(warm, monkeypatch):
- """UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1 means no unsolicited torch import, and importing
- diffusers imports torch. start_background_warm() declines under that variable, but
- join_background_warm() reports True when no worker ever ran, so the post-warm thread reaches
- the prewarm anyway. Without this check the opt-out would be defeated by the new code."""
+ """join_background_warm() reports True when no worker ran, so this needs its own check."""
monkeypatch.setenv(warm.DISABLE_ENV_VAR, "1")
_stub_gate(monkeypatch, {"text-to-image": ["unsloth/Z-Image-GGUF"]})
monkeypatch.delitem(sys.modules, "diffusers", raising = False)
@@ -277,10 +245,7 @@ def test_a_diffusers_that_cannot_import_means_skip_not_crash(warm, monkeypatch):
def test_the_windows_rocm_stubs_are_installed_before_the_import(warm, monkeypatch):
- """core/inference/diffusion.py installs these three at module scope, above its own lazy
- `import diffusers`, because on Windows ROCm diffusers imports xformers on sight and its
- quantizers torchao, and both land on an absent distributed backend. This prewarm can be the
- first importer in the process, so it owes the same three installs, in front of the import."""
+ """On Windows ROCm, diffusers imports xformers and torchao onto an absent backend."""
from core import _torchao_stub
from core.inference import diffusion_torchao_patches
@@ -322,10 +287,7 @@ def test_a_failed_prewarm_leaves_no_half_imported_diffusers(
"""The failure this prewarm adds that the loader did not have.
When ``diffusers/__init__.py`` raises, CPython evicts only the parent and keeps every
- submodule it already executed. The prewarm swallows that failure, so the next importer is a
- user's image load, and it would re-run ``__init__`` with each ``from .x import y`` served
- from that cache and attributes never rebound: diffusers imports "successfully" while missing
- pieces. Hand the load path a clean slate instead.
+ submodule it executed, so the next importer rebuilds an incomplete package from them.
"""
_stub_gate(monkeypatch, {"text-to-image": ["m"]})
monkeypatch.delitem(sys.modules, "diffusers", raising = False)
@@ -359,12 +321,8 @@ def test_the_diffusers_import_lock_is_held_across_the_failure_cleanup(
):
"""Releasing between the failed import and the purge is the whole bug.
- CPython drops the ``diffusers`` module lock the moment ``__init__`` raises. A request already
- blocked on that lock would wake up in the gap, re-import against the submodules the failed
- import left behind, and republish the malformed parent, at which point
- ``purge_partial_import`` deliberately declines because those leftovers now belong to a live
- importer. The bare warm stages already hold the lock across import and cleanup
- (``_held_import_lock``); this asserts the prewarm does the same.
+ CPython drops the module lock the moment ``__init__`` raises, and a request waiting in
+ that gap republishes the malformed parent, which the purge then declines.
"""
from importlib._bootstrap import _get_module_lock
@@ -409,14 +367,7 @@ def test_the_diffusers_import_lock_is_held_across_the_failure_cleanup(
def test_a_hooks_failure_after_a_good_parent_still_purges_the_hook_subtree(
warm, monkeypatch, restore_diffusers_modules
):
- """The half of the failure the parent purge cannot reach.
-
- ``import diffusers`` and ``import diffusers.hooks`` are two imports and either can fail. When
- the parent succeeded and the subpackage did not, purging "diffusers" is a no-op by design (it
- is in sys.modules and belongs to nobody), so the hook submodules that already executed stay
- cached and the load path's own ``from diffusers.hooks import ...`` rebuilds an incomplete
- package from them. That is the #7580 shape, one level down.
- """
+ """The #7580 shape one level down: with the parent good, purging it is a no-op."""
_stub_gate(monkeypatch, {"text-to-image": ["m"]})
parent = types.ModuleType("diffusers")
monkeypatch.setitem(sys.modules, "diffusers", parent)
@@ -472,12 +423,8 @@ def test_the_parent_and_child_import_locks_are_never_held_together(
):
"""Holding both would invert CPython's own lock order and deadlock a concurrent import.
- ``import diffusers.hooks`` makes CPython take the CHILD lock first and import the parent from
- inside it (``_find_and_load`` -> ``_ModuleLockManager(name)`` -> ``_find_and_load_unlocked``
- -> import parent). A prewarm holding parent-then-child inverts that against any concurrent
- ``from diffusers.hooks import ...``, and the resulting cycle surfaces as the ``_DeadlockError``
- that ``_lock_unlock_module`` swallows, which is the partially initialised module this whole
- change exists to prevent.
+ ``import diffusers.hooks`` makes CPython take the CHILD lock first, so parent-then-child
+ inverts that and cycles, as the ``_DeadlockError`` importlib swallows.
"""
from importlib._bootstrap import _get_module_lock
@@ -512,12 +459,7 @@ def test_the_parent_and_child_import_locks_are_never_held_together(
def test_a_concurrent_submodule_import_does_not_deadlock_the_prewarm(
warm, monkeypatch, restore_diffusers_modules
):
- """The failure mode from the other side, with two real threads and the real locks.
-
- One thread takes the hooks lock and then reaches for the parent, which is the order CPython
- uses for ``from diffusers.hooks import ...``. The prewarm runs concurrently. With sequential
- scopes both finish; with the locks nested this is the cycle.
- """
+ """The same inversion from the other side, with two real threads and the real locks."""
from importlib._bootstrap import _ModuleLockManager as LM
_stub_gate(monkeypatch, {"text-to-image": ["m"]})
@@ -566,12 +508,8 @@ def test_the_lock_is_never_released_between_a_failed_import_and_its_purge(
):
"""Held CONTINUOUSLY, not merely held again by the time the purge runs.
- Writing the try around the ``with`` instead of inside it releases the lock when the scope
- exits on the exception and reacquires it in the handler. A request already waiting wakes up
- in that gap, re-imports against the submodules the failed import left behind, and republishes
- the malformed package, at which point ``purge_partial_import`` declines because the leftovers
- now belong to a live importer. Asserting the purge ran under the lock does not catch this,
- because the handler has reacquired by then; only the timeline does.
+ The try around the ``with`` releases the lock on the exception and reacquires it in the
+ handler, which asserting that the purge ran under the lock would not catch.
"""
_stub_gate(monkeypatch, {"text-to-image": ["m"]})
monkeypatch.delitem(sys.modules, "diffusers", raising = False)
@@ -637,10 +575,8 @@ def test_the_lock_is_never_released_between_a_failed_import_and_its_purge(
def test_a_host_that_routes_to_sd_cpp_pays_nothing(warm, monkeypatch):
- """The case presence alone gets wrong. A CPU or MPS host with a runnable native binary, or
- UNSLOTH_DIFFUSION_ENGINE=sd_cpp, serves a supported GGUF through sd.cpp and imports no
- diffusers, so prewarming would add ~316 MB to a low-memory install that never reclaims it
- with a load."""
+ """What presence alone gets wrong: a native binary or UNSLOTH_DIFFUSION_ENGINE=sd_cpp
+ serves a supported GGUF through sd.cpp, importing no diffusers."""
_stub_gate(monkeypatch, {"text-to-image": ["unsloth/Z-Image-GGUF"]}, engine = "sd_cpp")
monkeypatch.delitem(sys.modules, "diffusers", raising = False)
@@ -670,10 +606,7 @@ def test_a_non_gguf_model_still_prewarms_on_a_native_host(warm, monkeypatch):
def test_a_gguf_whose_family_is_only_in_its_filename_is_still_recognised():
- """The layout `detect_family` cannot see: an opaque directory whose family keyword lives
- only in the .gguf filename. Treating it as unknown would prewarm on exactly the sd.cpp host
- this gate exists to spare, so the gate must use the same pick-aware resolver the listing and
- the loader use. Driven through the REAL resolver, since a stub of it could not show this."""
+ """The layout `detect_family` cannot see: the family keyword is only in the filename."""
from core.inference.media_locality import detected_image_family
opaque = types.SimpleNamespace(
@@ -711,9 +644,7 @@ def test_the_gate_uses_the_routers_own_prediction():
def test_the_gate_asks_for_the_catalogs_real_task_identifiers():
"""``_build_index`` matches ``_local_model_task(info) == task`` exactly, so a friendly
- ``"image"``/``"video"`` builds a permanently EMPTY index and the gate refuses forever: the
- prewarm would be dead code that every stubbed test still passes. Pinned against the
- catalog's own set so a rename there fails here instead of silently disabling the prewarm."""
+ ``"image"``/``"video"`` builds an EMPTY index while every stubbed test still passes."""
from hub.services.models.catalog_classification import _LOADABLE_MEDIA_GGUF_TASKS
from utils import torch_warmup
@@ -721,12 +652,7 @@ def test_the_gate_asks_for_the_catalogs_real_task_identifiers():
def test_the_real_index_answers_our_task_strings_and_not_the_friendly_ones(monkeypatch):
- """The same check driven through the REAL index rather than a stub of it.
-
- This is the one a stub cannot make: feed the catalog one text-to-image model and confirm
- ``available_media_model_ids`` finds it under the identifier the gate passes, and finds
- nothing under ``"image"``. Without it, keying the stub on the gate's own strings makes a
- wrong identifier look correct, which is exactly how this shipped the first time."""
+ """Through the REAL index: a stub keyed on the gate's own strings cannot catch this."""
from core.inference import media_model_index as idx
from utils import torch_warmup
@@ -775,9 +701,7 @@ def _post_warm_source() -> str:
def test_it_runs_from_the_post_warm_worker_and_last():
- """POST-warm, so it cannot delay a coordinated warm stage or the socket bind. And last
- within that worker, because it is the only item there that is latency work rather than
- correctness: MLX repair and linked-folder sync keep their place in the queue."""
+ """POST-warm, so it cannot delay a stage or the bind, and last: it is latency work."""
src = _post_warm_source()
assert (
"prewarm_diffusers_if_image_models_exist" in src
@@ -790,9 +714,7 @@ def test_it_runs_from_the_post_warm_worker_and_last():
def test_the_coordinated_warm_stages_do_not_import_diffusers():
- """The four warm stages are on the path to a usable backend. Pulling diffusers into one of
- them would delay every boot, including chat-only ones, which is what the post-warm worker
- exists to avoid."""
+ """The warm stages gate a usable backend, so diffusers there delays every boot."""
from utils import torch_warmup
import inspect
diff --git a/studio/backend/utils/torch_warmup.py b/studio/backend/utils/torch_warmup.py
index f3bf090faed..faa92ffebe5 100644
--- a/studio/backend/utils/torch_warmup.py
+++ b/studio/backend/utils/torch_warmup.py
@@ -3,11 +3,9 @@
"""Import the ML stack on a background thread while the backend finishes booting.
-torch (plus the sympy/scipy/pandas it drags in) used to be imported by `import main`, so the port could not bind until it finished; deferring it alone would only move the cost to the first request, so this module pays it concurrently. Started from the last line of main.py's lifespan, since everything above is on the critical path to binding the socket and would contend for the GIL, and uvicorn binds as soon as the lifespan returns, so the warm overlaps serving rather than boot.
+Started from the LAST line of main.py's lifespan: everything above is on the critical path to binding the socket and would contend for the GIL, and uvicorn binds as soon as the lifespan returns, so the warm overlaps serving rather than boot. Idempotent, never fatal (a failed stage is logged, left cold and retried by whoever needs it), and never half-initialised, since stages delegate to the module owning the cache.
-Contract: idempotent (one thread per process); never fatal (a failed stage is logged, left cold and retried by whoever needs it); no half-initialised state, since stages delegate to the module owning the cache (utils.hardware, model_config) which caches under a lock and only on success; optional GPU consumers stay cold, with Hub downloads loading the Xet/Unsloth Zoo integration and RAG its embedding backend on demand.
-
-This does NOT make torch-dependent endpoints cheap while it runs: anything reaching get_device() blocks until the hardware stage finishes, so `async def` handlers on that path must use asyncio.to_thread (see main.py's /api/health).
+This does NOT make torch-dependent endpoints cheap while it runs: anything reaching get_device() blocks until the hardware stage finishes, so `async def` handlers there must use asyncio.to_thread.
"""
from __future__ import annotations
@@ -92,11 +90,11 @@ def _synchronize_with_imports(fn):
def purge_partial_import(package: str) -> list:
"""Drop the submodules a failed package import left behind in sys.modules.
- When ``package/__init__.py`` raises, CPython evicts only the parent and keeps every submodule it already executed, so the next import re-runs ``__init__`` with each ``from .x import y`` served from that cache and attributes never rebound: the package imports "successfully" while missing pieces (the bitsandbytes case fixed in #7580). The warm makes this reachable, importing on a thread and swallowing the failure so the retry is somebody else's request.
+ When ``package/__init__.py`` raises, CPython evicts only the parent and keeps every submodule it executed, so the next import re-runs ``__init__`` with each ``from .x import y`` served from that cache: the package imports "successfully" while missing pieces (#7580).
Acts only on that exact signature (parent gone, submodules present), so a concurrent still-running import is left alone; returns what it removed.
- Declines when any submodule is a loaded C extension: evicting one re-runs its module init, and pybind11 answers a duplicate type registration with std::terminate. A torch missing attributes is bad, SIGABRT mid-serve is worse. Known native registries populated by pure-Python modules are reset only after every stale module has been removed and no importer has republished the parent.
+ Declines when any submodule is a loaded C extension: evicting one re-runs its module init, and pybind11 answers a duplicate type registration with std::terminate. Known native registries populated by pure-Python modules are reset only after every stale module has been removed and no importer has republished the parent.
"""
if package in sys.modules:
return []
@@ -153,7 +151,8 @@ _STAGE_PACKAGE = {
"datasets": "datasets",
}
-# Hold the import lock across a bare import AND its failure cleanup: locking only the purge leaves a window where a queued importer reuses stale submodules.
+# Hold the import lock across the import AND its cleanup, or a queued importer sees stale
+# submodules in between.
_BARE_IMPORT_STAGES = frozenset({"datasets"})
@@ -204,16 +203,11 @@ def _warm_datasets() -> None:
# Keep metadata and framework registries ready without importing optional GPU consumers.
# Unsloth Zoo is loaded by utils.hf_xet_fallback only when a Hub operation needs it.
def _warm_inference_backend() -> None:
- # Its constructor reaches hw.get_device(), so whoever builds it first pays for detection, which lazily is some request, and sync helpers call the getter inline from async handlers. Building it here makes the getter a dict read. After hardware, to reuse it.
from core.inference import get_inference_backend
get_inference_backend()
- # Before _prime_nvlink_topology, which is the first thread this module starts: once that
- # exists, "the first torch._dynamo import is single-threaded" stops being true. Folded into
- # this stage rather than added as a fifth one on purpose -- _STAGES carries a purge-on-
- # failure contract (_STAGE_PACKAGE) whose only sensible entry here would be torch, and
- # purging torch is never right. ensure_dynamo_imported never raises, so this stage's
- # failure semantics are unchanged.
+ # Must precede _prime_nvlink_topology: once that thread exists, the first dynamo import
+ # is no longer single-threaded (#10350).
ensure_dynamo_imported()
_prime_nvlink_topology()
@@ -222,12 +216,8 @@ def _prime_nvlink_topology() -> Optional[threading.Thread]:
"""Build the P2P gate's interconnect matrix off the load path. Returns the thread,
for tests to join.
- Fire and forget on its own thread: the probe can spend its NVML bound plus the
- shell-out timeout, and a warm stage blocking that long delays every stage behind
- it. Nothing here is critical-path, so a prime that never finishes costs one load
- its head start. prime_nvlink_topology stays NVML-only and success-only: a
- subprocess running its full timeout perturbs the process, and a miss cached this
- early would keep P2P off for the life of it (#10613)."""
+ Fire and forget, or its timeouts delay every stage behind it. Success-only: a miss cached
+ this early keeps P2P off for the life of the process (#10613)."""
def _probe() -> None:
try:
@@ -260,29 +250,11 @@ _dynamo_done = False
def ensure_dynamo_imported() -> bool:
"""Finish ``import torch._dynamo`` on ONE thread. True iff dynamo is importable.
- ``torch/__init__.py`` makes ``_dynamo`` a LAZY submodule, so any ``torch._dynamo.X``
- calls ``importlib.import_module``, which hands back whatever is in ``sys.modules`` -- a
- still-initialising module included, since ``_lock_unlock_module`` swallows ``_DeadlockError``
- to avoid deadlocking. The import takes ~0.6-3.9s and binds ``.config`` at ~0.007s but
- ``.utils`` only at ~0.284s, so for most of it the module is present and ``.utils`` is not.
- Anything reading it in that window raises ``partially initialized module 'torch._dynamo'
- has no attribute 'utils'`` (#10350, #10963).
-
- The window is opened by ordinary loads, not by torch.compile: ``diffusers.hooks``
- evaluates ``@torch.compiler.disable()`` at class-body time and ``torch/compiler/__init__.py``
- is ``import torch._dynamo``, so the CPU-offload step of any diffusion load opens it well
- outside every compile gate. Accelerate hit the same thing and wrapped it lazily; diffusers
- does not.
-
- Doing the first import once, early and single-threaded is what closes it: measured on torch
- 2.10.0 (the version both reports carry), 4-8 threads entering the dynamo/inductor cycle
- together failed 19/20 runs without this and 0/20 with it.
-
- Honest limit: this makes the first import single-threaded IN PRACTICE by getting there
- first. It cannot make a genuinely concurrent first import safe -- CPython's per-module lock
- is the thing being contended, and third-party code reaches dynamo without passing through
- here. Never fatal: a host with no torch, or a dynamo that legitimately fails to import,
- reports False and leaves callers on their existing eager fallbacks."""
+ ``_dynamo`` is a LAZY submodule, so ``torch._dynamo.X`` hands back a still-initialising
+ module: ``.config`` binds early and ``.utils`` late, and a read in between raises
+ ``partially initialized module ... has no attribute 'utils'`` (#10350, #10963). Ordinary
+ loads open that window, not torch.compile: ``diffusers.hooks`` evaluates
+ ``@torch.compiler.disable()`` at class-body time. Wins only by getting there first."""
global _dynamo_done
if _dynamo_done:
return True
@@ -309,16 +281,9 @@ def ensure_dynamo_imported() -> bool:
def close_dynamo_import_window(log) -> bool:
"""``ensure_dynamo_imported()`` plus the breadcrumb, for a caller about to import diffusers.
- Every media load path reaches diffusers, and `import diffusers` is itself a dynamo importer,
- so each one owes this call in front of its first such import. The warning is deliberately not
- a retry: measured on torch 2.10, a process that has lost this race does not recover (0 of 14
- retries resolved), and evicting the half-built package to re-import is the C-extension purge
- that ``purge_partial_import`` already refuses. What is useful is a breadcrumb, so that if
- anything below dies on dynamo the log already says the condition predates the load.
-
- Call sites still wrap the IMPORT of this module as well as the call: this file reaches
- ``importlib._bootstrap._ModuleLockManager``, a private CPython name, and a build lacking it
- must not take a load down. Best-effort throughout, never a new failure."""
+ `import diffusers` is itself a dynamo importer, so every media load path owes this call in
+ front of its first one. A warning, not a retry: a process that lost the race does not
+ recover. Wrap the IMPORT of this module too, since it reaches a private CPython name."""
if ensure_dynamo_imported():
return True
log.warning(
@@ -340,17 +305,18 @@ def _warm(epoch: Optional[int] = None) -> None:
started = time.perf_counter()
if epoch is None:
epoch = _detection_epoch()
- # The boundary checks below only catch a shutdown between stages. Inside one, the orchestrator constructor reaches get_device(), which takes no epoch; the scope binds it to this pass so a mid-stage shutdown discards it instead of republishing DEVICE.
+ # These checks catch only a shutdown BETWEEN stages; the scope binds the epoch so a
+ # mid-stage shutdown discards this pass rather than republishing DEVICE.
with _owning_epoch(epoch):
for name, fn in _STAGES:
if epoch is not None and _detection_epoch() != epoch:
- # Checked before the first stage too: start_background_warm() reads the epoch before start(), so a shutdown in that gap retires this thread while it is still scheduled, with nothing yet run.
+ # Before the first stage too: a shutdown between the epoch read and start().
logger.info("torch warm stopped before %s: its lifespan ended", name)
return
# Only the real stage takes the epoch; a patched _STAGES entry is called bare.
_run_stage(name, partial(fn, epoch) if fn is _warm_hardware else fn)
if epoch is not None and _detection_epoch() != epoch:
- # Shutdown retired this lifespan's detection. Later stages build the orchestrator, which reaches get_device() and would start a fresh detection, republishing DEVICE after teardown cleared it.
+ # Later stages reach get_device(), republishing DEVICE after teardown.
logger.info("torch warm stopped after %s: its lifespan ended", name)
return
_status["finished"] = True
@@ -389,22 +355,22 @@ def _warm_after(previous: threading.Thread, epoch: Optional[int]) -> None:
def start_background_warm() -> bool:
"""Start the warm thread once. Returns True iff this call started it.
- Runs on every host, torch or not: stage one is hardware detection, which must not wait for a request (it feeds /api/health's chat_only). A finished thread from an earlier lifespan does not count as one already running, because reset_background_warm() declines mid-warm, so a shutdown leaves the object in place and treating that as "already started" would skip the warm over hardware state the same shutdown just cleared.
+ Runs on every host, torch or not: stage one is hardware detection, which feeds /api/health's chat_only. A FINISHED thread from an earlier lifespan does not count as one already running: reset_background_warm() declines mid-warm, so a shutdown leaves the object in place and treating that as "already started" skips the warm over hardware state the same shutdown cleared.
"""
global _thread
if os.environ.get(DISABLE_ENV_VAR) == "1":
return False
global _thread_epoch
- # Epoch read before start(): the child may not run for a while, and a shutdown in that gap retires this lifespan. Reading it in the thread would adopt the post-shutdown one.
+ # Epoch read before start(): reading it in the child would adopt the post-shutdown one.
epoch = _detection_epoch()
with _start_lock:
target, args = _warm, (epoch,)
if _thread is not None:
- # A warm holds the latch while its own lifespan is current, so repeat calls are no-ops. Once shutdown retires that epoch the next lifespan warms again.
if _thread_epoch is not None and epoch == _thread_epoch:
return False
if _thread.is_alive():
- # Stale but mid-stage: it stops at the next boundary and nothing retries, so this lifespan would serve cold. Hand off; the successor joins it first, so only one thread imports.
+ # Stale but mid-stage: nothing retries it, so hand off to a successor that
+ # joins it first, keeping one importer.
target, args = _warm_after, (_thread, epoch)
else:
_clear_finished_warm_locked()
@@ -423,9 +389,9 @@ def start_background_warm() -> bool:
def reset_background_warm() -> bool:
"""Let a later lifespan in this process start a fresh warm. True iff reset.
- The same app can start twice (repeated ASGI lifespans, an embedded restart) and shutdown clears the hardware state the first warm produced, so leaving the finished thread in place would make the second lifespan skip the warm and hand detection back to the first request, the stall this module removes.
+ The same app can start twice, and shutdown clears the hardware state the first warm produced, so leaving the finished thread in place hands detection back to the first request, which is the stall this module removes.
- Declines while the previous warm runs, so two warms never share the same imports. Detection self-heals then: shutdown clears DETECTION_COMPLETE and /api/health kicks start_background_detection().
+ Declines while the previous warm runs, so two warms never share the same imports; detection self-heals then, because /api/health kicks start_background_detection().
"""
with _start_lock:
thread = _thread
@@ -461,20 +427,10 @@ _diffusers_prewarmed = False
def _a_local_model_would_load_through_diffusers() -> bool:
"""Whether any indexed media model would actually load through DIFFUSERS on this host.
- Presence alone is the wrong question. A CPU or MPS host with a runnable native binary, or
- any host with ``UNSLOTH_DIFFUSION_ENGINE=sd_cpp``, routes a supported GGUF to sd.cpp, which
- imports no diffusers at all -- so prewarming there would add ~316 MB to exactly the
- low-memory installs that can least afford it, and it would never be reclaimed by a load.
-
- ``predict_engine`` is the same predicate selection and the download planner use, and it is
- documented to activate nothing and install nothing, so asking it here cannot perturb a
- resident model. A non-GGUF pick short-circuits it: only a GGUF can go native.
-
- The family comes from ``detected_image_family``, the resolver the listing and locality
- routes already share, rather than ``detect_family`` on the id: a local GGUF can carry its
- family only in the FILENAME (``/models/custom/model.gguf`` holding ``z-image``), which
- ``detect_family`` cannot see, and treating that as unknown would prewarm on exactly the
- sd.cpp host this gate exists to spare."""
+ Presence alone is the wrong question: a CPU or MPS host with a native binary, or
+ ``UNSLOTH_DIFFUSION_ENGINE=sd_cpp``, routes a supported GGUF to sd.cpp and imports no
+ diffusers. Family detection is pick-aware because a local GGUF can name it only in the
+ FILENAME."""
from core.inference.diffusion_engine_router import ( # noqa: PLC0415
ENGINE_DIFFUSERS,
predict_engine,
@@ -485,12 +441,8 @@ def _a_local_model_would_load_through_diffusers() -> bool:
resolve_local_media_model,
)
- # Scope limit, deliberate: the media index is keyed on current_account_id(), and this runs on
- # a boot thread with no bound account, so it answers for the owner. On a multi-user install
- # where only a non-owner has an image model, the gate says no and that user's first load
- # still pays the import. Not worth fixing here: building an index per configured account
- # means a filesystem scan per account on the boot thread, which is the cost this gate exists
- # to avoid, and the failure mode is only the absence of a speedup, exactly as today.
+ # Deliberate scope limit: the media index is keyed on current_account_id() and this boot
+ # thread has none, so it answers for the owner; the failure mode is only no speedup.
for task in _MEDIA_PREWARM_TASKS:
for model_id in available_media_model_ids(task):
pick = resolve_local_media_model(model_id, task = task)
@@ -500,10 +452,7 @@ def _a_local_model_would_load_through_diffusers() -> bool:
if kind != "gguf":
return True # only a GGUF can go native, by either backend
if task == _VIDEO_TASK:
- # The video backend has its own native path and its own family type, so the
- # image resolver and the image router cannot answer for it: an H3 GGUF returns
- # from _run_load_h3_native before video.py's own `import diffusers`, while every
- # other video load reaches it.
+ # The image resolver cannot answer for video; see _is_native_video_pick.
if _is_native_video_pick(pick):
continue
return True
@@ -518,9 +467,8 @@ def _a_local_model_would_load_through_diffusers() -> bool:
def _is_native_video_pick(pick) -> bool:
"""Whether *pick* is the one video combination that never imports diffusers.
- ``VideoBackend.load_pipeline`` asks ``is_h3_native(fam, kind)`` and returns through
- ``_run_load_h3_native`` before its own ``import diffusers``; everything else falls through
- to it. Asking the video backend's own predicate keeps this from drifting away from it."""
+ ``VideoBackend.load_pipeline`` returns through ``_run_load_h3_native`` before its own
+ ``import diffusers``; every other video load reaches that import."""
from core.inference.video_families import detect_video_family # noqa: PLC0415
from core.inference.video_minimax_h3 import is_h3_native # noqa: PLC0415
@@ -541,31 +489,19 @@ def _is_native_video_pick(pick) -> bool:
if family is not None:
return bool(is_h3_native(family, "gguf"))
# Not covered on purpose: _detect_load_family also reads general.architecture out of a
- # renamed GGUF's header. That is file IO on a boot thread to save memory, and guessing wrong
- # in this direction only costs the prewarm, so an unidentifiable GGUF falls through to the
- # safe default and prewarms.
+ # renamed GGUF's header, which is file IO on a boot thread.
return False
def prewarm_diffusers_if_image_models_exist() -> bool:
"""Import diffusers off the first image load. True iff this call did the import.
- Measured on this stack, the first diffusion load pays roughly 5.3s of pure import before it
- touches a weight: ``diffusers`` 1.6s, ``diffusers.hooks`` 2.4s and the pipeline classes 1.3s,
- for about 316 MB. None of it depends on which model was picked, so it is the same cost every
- first load in a fresh process, and all of it can be paid earlier by a thread nobody is
- waiting on.
-
- Gated on the install actually having a local image or video model, which is the whole point:
- a chat-only or training-only user never pays the 316 MB. The gate itself is stdlib only (it
- does not import torch or diffusers) and its index is cached and needed by the Images page
- anyway, so building it here is work moved earlier rather than work added.
+ Gated on the install having a local image or video model, so a chat-only or a
+ training-only user never pays it. The gate itself is stdlib only.
- Called from the POST-warm worker, after ``join_background_warm()``, so it cannot delay any
- coordinated warm stage or the socket bind. Concurrency was measured rather than assumed: 4 to
- 8 threads importing diffusers submodules together failed 0 of 16 trials, with and without
- dynamo already imported, because these are ordinary package imports that CPython's per module
- lock serialises, unlike the dynamo/inductor cycle in #10350.
+ Called from the POST-warm worker, after ``join_background_warm()``, so it cannot delay a
+ warm stage or the socket bind. Concurrent submodule imports are safe here, unlike the
+ dynamo cycle in #10350: CPython's per-module lock serialises ordinary imports.
Never fatal, and opt out with ``UNSLOTH_STUDIO_DISABLE_DIFFUSERS_PREWARM=1``."""
global _diffusers_prewarmed
@@ -573,11 +509,8 @@ def prewarm_diffusers_if_image_models_exist() -> bool:
return False
if os.environ.get(DIFFUSERS_PREWARM_DISABLE_ENV_VAR) == "1":
return False
- # The torch opt-out covers this too. start_background_warm() declines under DISABLE_ENV_VAR,
- # but join_background_warm() reports True when no worker ever ran, so the post-warm thread
- # arrives here regardless; importing diffusers imports torch, which is precisely what that
- # variable exists to prevent. Checked here rather than at the call site so every caller gets
- # it, and so the warm-window tests that assert no unsolicited torch import keep holding.
+ # join_background_warm() reports True when no worker ran, so the post-warm thread arrives
+ # here even under DISABLE_ENV_VAR, and diffusers imports torch.
if os.environ.get(DISABLE_ENV_VAR) == "1":
return False
with _diffusers_prewarm_lock:
@@ -585,8 +518,7 @@ def prewarm_diffusers_if_image_models_exist() -> bool:
return False
try:
if not _a_local_model_would_load_through_diffusers():
- # Nothing diffusers would serve, so the import is pure cost. Not latched: a
- # model downloaded later should let the next lifespan reconsider.
+ # Not latched: a model downloaded later lets the next lifespan reconsider.
logger.debug("diffusers prewarm skipped: no local model routes to diffusers")
return False
except Exception as exc: # noqa: BLE001 -- a gate that cannot answer means skip, not crash
@@ -594,10 +526,8 @@ def prewarm_diffusers_if_image_models_exist() -> bool:
return False
try:
- # core.inference.diffusion installs these at module scope, above its own lazy
- # `import diffusers`, because on Windows ROCm diffusers reaches xformers and torchao
- # and both land on an absent distributed backend. This prewarm can be the first
- # importer in the process, so it owes the same three installs; they are idempotent.
+ # On Windows ROCm diffusers reaches xformers and torchao, both landing on an
+ # absent distributed backend, so any first importer owes these stubs.
from core._torchao_stub import ( # noqa: PLC0415
install_torchao_windows_rocm_stub,
install_xformers_windows_rocm_stub,
@@ -614,29 +544,8 @@ def prewarm_diffusers_if_image_models_exist() -> bool:
return False
started = time.perf_counter()
- # One lock at a time, never both. Each scope holds that package's own lock across its
- # import AND its cleanup, the way _held_import_lock does for the bare warm stages,
- # because releasing between the two is the bug: CPython drops the lock the moment the
- # import raises, so a request already waiting on it wakes up, re-imports against the
- # submodules that import left behind, and republishes the malformed package -- at which
- # point purge_partial_import declines, since those leftovers now belong to a live
- # importer. Reentrant per thread, so the nested acquire inside the purge is free.
- #
- # NOT nested, which is the part that is easy to get backwards. `import diffusers.hooks`
- # makes CPython take the CHILD lock first and import the parent from inside it
- # (_find_and_load -> _ModuleLockManager(name) -> _find_and_load_unlocked -> import
- # parent). Holding parent-then-child here would invert that against any concurrent
- # `from diffusers.hooks import ...` and produce a lock cycle, which surfaces as the
- # _DeadlockError that _lock_unlock_module swallows -- i.e. exactly the partially
- # initialised module this whole change exists to prevent. Sequential scopes have no
- # cycle: by the time the hooks scope runs, the parent is published, so importing the
- # child acquires nothing else.
- # The try INSIDE each with, not around it: exiting the scope on the exception would
- # release the lock and the handler would reacquire it, and that gap is the whole bug.
- # A request already waiting on the lock wakes up in it, re-imports against the submodules
- # the failed import left behind, and republishes the malformed package -- at which point
- # purge_partial_import declines, because those leftovers now belong to a live importer.
- # Reentrant per thread, so the nested acquire inside the purge is free.
+ # The try goes INSIDE each `with`: leaving the scope first frees the lock for a waiter
+ # to republish the malformed package before the purge runs.
with _ModuleLockManager("diffusers"):
try:
import diffusers # noqa: F401, PLC0415
@@ -645,31 +554,21 @@ def prewarm_diffusers_if_image_models_exist() -> bool:
purge_partial_import("diffusers")
return False
- # A separate scope, never nested inside the one above. `import diffusers.hooks` makes
- # CPython take the CHILD lock first and import the parent from inside it (_find_and_load
- # -> _ModuleLockManager(name) -> _find_and_load_unlocked -> import parent). Holding
- # parent-then-child here would invert that against a concurrent `from diffusers.hooks
- # import ...` and produce a lock cycle, which surfaces as the _DeadlockError that
- # _lock_unlock_module swallows: exactly the partially initialised module this change
- # exists to prevent. Sequentially there is no cycle, because the parent is already
- # published by the time this runs, so importing the child acquires nothing else.
+ # A separate scope, NEVER nested in the one above: CPython takes the CHILD lock first
+ # here, so parent-then-child would invert that against a concurrent importer.
with _ModuleLockManager("diffusers.hooks"):
try:
import diffusers.hooks # noqa: F401, PLC0415
except Exception as exc: # noqa: BLE001 -- the load path imports it again and reports
logger.debug("diffusers prewarm skipped: %r", exc)
- # The parent stays: it imported cleanly, and purging it would be a no-op anyway
- # since it is in sys.modules and belongs to nobody. What has to go is the hook
- # submodules that did execute, or the load path's own `from diffusers.hooks
- # import ...` rebuilds an incomplete package from them (#7580, one level down).
+ # The parent stays; the hook submodules that ran must go, or a later
+ # `from diffusers.hooks import ...` rebuilds from them (#7580).
purge_partial_import("diffusers.hooks")
return False
# Outside both locks: it imports nothing under diffusers. diffusers hard-codes
- # _tqdm_active = True at import and honours no env var, so a prewarm that skipped this
- # would let "Loading pipeline components..." draw straight onto the structlog stream,
- # mid-record. Not fatal to the prewarm: the imports above already succeeded, which is the
- # work this exists to do, and the load path calls the same idempotent helper anyway.
+ # diffusers hard-codes _tqdm_active = True and honours no env var, so without this
+ # its bars draw onto the structlog stream mid-record.
try:
from loggers.config import quiet_third_party_progress_bars # noqa: PLC0415
quiet_third_party_progress_bars()
diff --git a/tests/test_per_layer_device_readers.py b/tests/test_per_layer_device_readers.py
new file mode 100644
index 00000000000..edbb490b931
--- /dev/null
+++ b/tests/test_per_layer_device_readers.py
@@ -0,0 +1,645 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""`verify_and_set_device` recorded `device.index` verbatim and `torch.device("cpu").index` is
+None, so an offloaded layer ended `move_to_device` with "Invalid target device: None" (#3538)."""
+
+from __future__ import annotations
+
+import functools
+import pathlib
+import re
+
+import pytest
+from real_accelerator import (
+ has_real_cuda,
+) # tests/_shared, on sys.path via tests/conftest.py
+import torch
+
+
+# Keep in step with a grep for `_per_layer_device` across the repository (#3538).
+READERS = {
+ # llama's reader is nested, which is why the scope is located from the call site.
+ "unsloth/models/llama.py": ("temp_gates", "temp_ups"),
+ "unsloth/models/granite.py": (),
+ "unsloth/models/gemma.py": ("out_weights",),
+ "unsloth/models/gemma2.py": ("out_weights",),
+ "unsloth/models/cohere.py": ("out_weights",),
+}
+
+REPOSITORY_ROOT = pathlib.Path(__file__).resolve().parents[1]
+
+
+def _device_or_none(value):
+ try:
+ return torch.device(value)
+ except (RuntimeError, TypeError, ValueError):
+ return None
+
+
[email protected]_cache(maxsize = 1)
+def default_device_is_usable() -> bool:
+ """Measured, not asked: torch 2.6 raises here, torch 2.11 returns `cuda:0` and fails later."""
+ try:
+ torch.zeros(1, device = torch.device(0))
+ return True
+ except Exception:
+ return False
+
+
+class _Layer(torch.nn.Module):
+ def __init__(
+ self,
+ device = None,
+ index = "absent",
+ parameter_device = "cpu",
+ ):
+ super().__init__()
+ self.weight = torch.nn.Parameter(
+ torch.zeros(2, device = torch.device(parameter_device)),
+ requires_grad = False,
+ )
+ if device is not None:
+ self._per_layer_device = device
+ if index != "absent":
+ self._per_layer_device_index = index
+
+
+def test_current_unsloth_zoo_device_wins():
+ from unsloth.models._utils import per_layer_device
+
+ layer = _Layer(device = torch.device("cuda:2"), index = 2)
+ device, buffer_index = per_layer_device(layer)
+ assert device == torch.device("cuda:2")
+ assert buffer_index == 2
+
+
+def test_cpu_offloaded_layer_resolves_to_cpu_not_cuda_zero():
+ from unsloth.models._utils import per_layer_device
+
+ layer = _Layer(device = torch.device("cpu"), index = "cpu")
+ device, buffer_index = per_layer_device(layer)
+ assert device == torch.device("cpu")
+ assert isinstance(
+ buffer_index, int
+ ), "gemma, gemma2 and cohere subscript a per-device tuple with this"
+
+
+def test_older_unsloth_zoo_integer_index_is_unchanged():
+ from unsloth.models._utils import per_layer_device
+
+ layer = _Layer(index = 1, parameter_device = "cpu")
+ device, buffer_index = per_layer_device(layer)
+ if default_device_is_usable():
+ assert device == torch.device(1)
+ else:
+ assert device == torch.device("cpu")
+ assert buffer_index == 1, "the buffer subscript must survive either way"
+
+
[email protected](not has_real_cuda(), reason = "needs two orderable accelerator ordinals")
+def test_a_boolean_index_is_not_an_accelerator_ordinal():
+ """`False` hashes equal to 0, so as an ordinal it would key the memo for another value."""
+ from unsloth.models._utils import per_layer_device
+
+ layer = _Layer(index = False, parameter_device = "cpu")
+ device, buffer_index = per_layer_device(layer, default = 1)
+ assert device == torch.device(1), "a bool index resolved as the ordinal 0"
+ assert buffer_index == 1
+
+
+def test_a_boolean_index_does_not_poison_the_memo_for_zero():
+ """Bool first, then 0: reversed, a shared memo entry is masked by the correct value."""
+ from unsloth.models._utils import per_layer_device
+
+ per_layer_device(_Layer(index = False, parameter_device = "cpu"))
+ device, buffer_index = per_layer_device(_Layer(index = 0, parameter_device = "cpu"))
+ if default_device_is_usable():
+ assert device == torch.device(0)
+ else:
+ assert device == torch.device("cpu")
+ assert buffer_index == 0
+
+
+def test_a_re_placed_layer_is_not_answered_from_the_memo():
+ """unsloth_zoo re-running `verify_and_set_device` must invalidate it with no explicit clear."""
+ from unsloth.models._utils import per_layer_device
+
+ layer = _Layer(index = 0, parameter_device = "cpu")
+ per_layer_device(layer)
+ layer._per_layer_device_index = "cpu"
+ device, buffer_index = per_layer_device(layer)
+ assert device == torch.device("cpu"), "the memo survived the index it was derived from"
+ assert buffer_index == 0
+
+
+def test_a_published_device_is_memoised_too():
+ from unsloth.models._utils import per_layer_device
+
+ published = torch.device("cpu")
+ layer = _Layer(device = published, index = 0, parameter_device = "cpu")
+ first = per_layer_device(layer)
+ second = per_layer_device(layer)
+ assert first == second == (published, 0)
+ layer._per_layer_device = torch.device("meta")
+ third_device, _ = per_layer_device(layer)
+ assert third_device != torch.device("meta"), (
+ "the memo answered for a device that is no longer published, and meta destroys an "
+ "activation moved to it"
+ )
+
+
+def test_a_hook_derived_answer_is_never_memoised():
+ """accelerate moves an offloaded layer between runs without touching `_per_layer_device`."""
+ from unsloth.models._utils import per_layer_device
+
+ class _Hook:
+ def __init__(self, execution_device):
+ self.execution_device = execution_device
+
+ layer = _Layer(device = torch.device("meta"), index = 0, parameter_device = "meta")
+ layer._hf_hook = _Hook(torch.device("cpu"))
+ first, _ = per_layer_device(layer)
+ assert first == torch.device("cpu")
+
+ layer._hf_hook.execution_device = (
+ torch.device("cpu") if not has_real_cuda() else torch.device(0)
+ )
+ second, _ = per_layer_device(layer)
+ assert (
+ second == layer._hf_hook.execution_device
+ ), "the memo answered with the device accelerate has already moved this layer off"
+
+
+def test_the_memo_is_keyed_on_the_default_as_well_as_the_index():
+ """Keyed on the index alone, a per-device tuple is read at the wrong offset."""
+ from unsloth.models._utils import per_layer_device
+
+ layer = _Layer(index = "cpu", parameter_device = "cpu")
+ first_device, first_index = per_layer_device(layer, default = 0)
+ second_device, second_index = per_layer_device(layer, default = 1)
+ assert first_device == torch.device("cpu")
+ assert second_device == torch.device("cpu")
+ assert first_index == 0
+ assert second_index == 1, "the memo returned the subscript for a different default"
+
+
+def test_two_layers_on_different_devices_do_not_share_a_memo_entry():
+ from unsloth.models._utils import per_layer_device
+
+ first, _ = per_layer_device(_Layer(index = 0, parameter_device = "cpu"))
+ second, second_index = per_layer_device(_Layer(index = 1, parameter_device = "cpu"))
+ if default_device_is_usable():
+ assert first == torch.device(0)
+ assert second == torch.device(1)
+ assert second_index == 1
+
+
+def test_older_unsloth_zoo_none_index_reads_the_layer_instead():
+ from unsloth.models._utils import per_layer_device
+
+ layer = _Layer(index = None, parameter_device = "cpu")
+ device, buffer_index = per_layer_device(layer)
+ assert device == torch.device("cpu"), (
+ "a None index must not resolve to cuda:0, which would move a CPU layer's "
+ "activations off the layer"
+ )
+ assert isinstance(buffer_index, int)
+
+
+def test_a_layer_with_no_attributes_keeps_the_historical_default():
+ from unsloth.models._utils import per_layer_device
+
+ layer = _Layer()
+ device, buffer_index = per_layer_device(layer)
+ if default_device_is_usable():
+ assert device == torch.device(0)
+ else:
+ assert device == torch.device("cpu")
+ assert buffer_index == 0
+
+
+def test_an_unavailable_accelerator_is_not_a_usable_device():
+ from unsloth.models import _utils
+
+ assert _utils._device_type_is_usable("cpu")
+ assert _utils._device_type_is_usable(
+ "meta"
+ ), "meta has no is_available to ask, and an offloaded layer sits on it"
+ assert _utils._device_type_is_usable(
+ "not-a-backend"
+ ), "an unknown backend must be taken at its word, not refused"
+ assert _utils._device_type_is_usable("cuda") == torch.cuda.is_available()
+
+
+def test_a_default_pointing_at_a_missing_accelerator_reads_the_layer(monkeypatch):
+ from unsloth.models import _utils
+
+ monkeypatch.setattr(_utils, "_device_type_is_usable", lambda device_type: device_type == "cpu")
+ assert _utils._as_torch_device(0) is None
+ assert _utils._as_torch_device("cpu") == torch.device("cpu")
+
+ layer = _Layer(parameter_device = "cpu")
+ device, buffer_index = _utils.per_layer_device(layer)
+ assert device == torch.device(
+ "cpu"
+ ), "with no accelerator the layer's own parameters are the only real answer"
+ assert buffer_index == 0, "the historical subscript must survive the fallback"
+
+
+def test_an_available_accelerator_still_wins_the_default(monkeypatch):
+ from unsloth.models import _utils
+
+ monkeypatch.setattr(_utils, "_device_type_is_usable", lambda device_type: True)
+ layer = _Layer(parameter_device = "cpu")
+ device, buffer_index = _utils.per_layer_device(layer)
+ expected = _device_or_none(0)
+ if expected is not None:
+ assert device == expected
+ assert buffer_index == 0
+
+
+def test_a_garbage_index_falls_back_rather_than_raising():
+ from unsloth.models._utils import per_layer_device
+
+ layer = _Layer(index = "not a device")
+ device, buffer_index = per_layer_device(layer)
+ assert isinstance(device, torch.device)
+ if default_device_is_usable():
+ assert device == torch.device(0)
+ else:
+ assert device == torch.device("cpu")
+ assert buffer_index == 0
+
+
+ "device,index",
+ [
+ (torch.device("cpu"), "cpu"),
+ (torch.device("cuda:0"), 0),
+ (None, None),
+ (None, 3),
+ (None, "absent"),
+ ],
+)
+def test_move_to_device_accepts_every_resolution(device, index):
+ """The contract that broke: move_to_device only takes int, str or torch.device."""
+ from unsloth.models._utils import move_to_device, per_layer_device
+
+ layer = _Layer(device = device, index = index)
+ resolved, buffer_index = per_layer_device(layer)
+ assert isinstance(resolved, torch.device)
+
+ per_device_buffers = tuple(range(8))
+ assert per_device_buffers[buffer_index] == buffer_index
+
+ # The move is only performed where it cannot need hardware.
+ if resolved.type == "cpu":
+ moved = move_to_device(resolved, torch.zeros(2))
+ assert moved.device == torch.device("cpu")
+
+
+def test_cpu_offloaded_layer_no_longer_raises_invalid_target_device():
+ from unsloth.models._utils import move_to_device, per_layer_device
+
+ layer = _Layer(device = torch.device("cpu"), index = "cpu")
+ resolved, _ = per_layer_device(layer)
+ hidden_states = torch.zeros(1, 2, 4)
+ position_ids = torch.zeros(1, 2, dtype = torch.long)
+ hidden_states, position_ids = move_to_device(resolved, hidden_states, position_ids)
+ assert hidden_states.device == torch.device("cpu")
+ assert position_ids.device == torch.device("cpu")
+
+ with pytest.raises(ValueError, match = "Invalid target device"):
+ move_to_device(None, hidden_states)
+
+
+def test_unsloth_zoo_setter_and_reader_agree():
+ from unsloth.models._utils import per_layer_device
+
+ try:
+ from unsloth_zoo.patching_utils import verify_and_set_device
+ except Exception as exception: # pragma: no cover
+ pytest.skip(f"unsloth_zoo not importable: {exception}")
+
+ layer = torch.nn.Linear(4, 4)
+ verify_and_set_device(layer)
+ device, buffer_index = per_layer_device(layer)
+ assert device == torch.device("cpu")
+ assert isinstance(buffer_index, int)
+
+
[email protected]("path", sorted(READERS))
+def test_every_reader_goes_through_the_helper(path):
+ source = (REPOSITORY_ROOT / path).read_text(encoding = "utf-8")
+ assert (
+ 'getattr(decoder_layer, "_per_layer_device_index"' not in source
+ ), f"{path} reads the raw index again; a None there is #3538"
+ assert (
+ "per_layer_device(decoder_layer)" in source
+ ), f"{path} no longer resolves the layer device through per_layer_device"
+ assert re.search(
+ r"move_to_device\(\s*layer_device", source
+ ), f"{path} does not hand the resolved device to move_to_device"
+
+
[email protected]("path", sorted(READERS))
+def test_every_reader_imports_the_helper_explicitly(path):
+ """Do not rely on `from .llama import *` to carry the name across."""
+ source = (REPOSITORY_ROOT / path).read_text(encoding = "utf-8")
+ assert re.search(
+ r"^from \._utils import .*per_layer_device", source, re.MULTILINE
+ ), f"{path} must import per_layer_device from ._utils explicitly"
+
+
+def _reader_scopes(source: str, path: str):
+ import ast
+
+ tree = ast.parse(source)
+ functions = [
+ node for node in ast.walk(tree) if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ ]
+ found = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ if getattr(node.func, "id", None) != "per_layer_device":
+ continue
+ enclosing = [
+ function
+ for function in functions
+ if function.lineno <= node.lineno <= (function.end_lineno or function.lineno)
+ ]
+ assert enclosing, f"{path}: per_layer_device call at module level?"
+ innermost = max(enclosing, key = lambda function: function.lineno)
+ found.append((innermost.name, innermost.lineno))
+ return found
+
+
[email protected]("path", sorted(READERS))
+def test_no_reader_reads_a_name_it_never_binds(path):
+ """Dropping the index leaves the subscripts on a name Python only reports at the first
+ decode step; symtable calls it an implicit global, so this catches it statically."""
+ import builtins
+ import importlib
+ import symtable
+
+ module = importlib.import_module("unsloth.models." + pathlib.Path(path).stem)
+ source = (REPOSITORY_ROOT / path).read_text(encoding = "utf-8")
+ wanted = _reader_scopes(source, path)
+ assert wanted, f"{path}: no per_layer_device call found"
+
+ def scopes(table):
+ yield table
+ for child in table.get_children():
+ yield from scopes(child)
+
+ checked = []
+ unbound = []
+ for scope in scopes(symtable.symtable(source, path, "exec")):
+ if scope.get_type() != "function":
+ continue
+ if (scope.get_name(), scope.get_lineno()) not in wanted:
+ continue
+ checked.append(scope.get_name())
+ for symbol in scope.get_symbols():
+ name = symbol.get_name()
+ if not symbol.is_global():
+ continue
+ if hasattr(module, name) or hasattr(builtins, name):
+ continue
+ unbound.append(name)
+
+ assert len(checked) == len(
+ wanted
+ ), f"{path}: located {wanted} from the call sites but symtable matched {checked}"
+ assert not unbound, (
+ f"{path}:{checked} reads {sorted(set(unbound))} without binding it and "
+ f"without {module.__name__} defining it, so generation raises NameError"
+ )
+
+
[email protected]("path", sorted(READERS))
+def test_per_accelerator_tuples_are_still_subscripted_by_an_int(path):
+ source = (REPOSITORY_ROOT / path).read_text(encoding = "utf-8")
+ for tuple_name in READERS[path]:
+ assert f"{tuple_name}[device_index]" in source, (
+ f"{path} subscripts {tuple_name} with something other than the "
+ "buffer index per_layer_device returns"
+ )
+ assert "layer_device, device_index = per_layer_device(decoder_layer)" in source
+
+
[email protected](not has_real_cuda(), reason = "needs a real GPU")
+def test_cuda_layer_path_is_unchanged():
+ from unsloth.models._utils import move_to_device, per_layer_device
+
+ try:
+ from unsloth_zoo.patching_utils import verify_and_set_device
+ except Exception as exception: # pragma: no cover
+ pytest.skip(f"unsloth_zoo not importable: {exception}")
+
+ layer = torch.nn.Linear(4, 4).cuda()
+ verify_and_set_device(layer)
+ device, buffer_index = per_layer_device(layer)
+
+ assert device.type == "cuda"
+ assert buffer_index == torch.cuda.current_device()
+ moved = move_to_device(device, torch.zeros(2))
+ assert moved.device == next(layer.parameters()).device
+
+
+def test_the_backend_probe_is_asked_once_per_device_type():
+ from unsloth.models import _utils
+
+ assert hasattr(
+ _utils._device_type_is_usable, "cache_clear"
+ ), "_device_type_is_usable must stay memoised; it is on the per-token path"
+
+ _utils._device_type_is_usable.cache_clear()
+ calls = []
+ real = torch.cuda.is_available
+
+ def counted():
+ calls.append(1)
+ return real()
+
+ try:
+ torch.cuda.is_available = counted
+ first = _utils._device_type_is_usable("cuda")
+ for _ in range(50):
+ assert _utils._device_type_is_usable("cuda") == first
+ finally:
+ torch.cuda.is_available = real
+ _utils._device_type_is_usable.cache_clear()
+
+ assert len(calls) <= 1, (
+ f"the backend was probed {len(calls)} times for one device type; "
+ "that is a per-layer per-token cost"
+ )
+
+
+def test_the_published_attributes_are_read_without_a_failed_getattr():
+ """`nn.Module.__getattr__` scans _parameters, _buffers and _modules before raising."""
+ from unsloth.models._utils import per_layer_device
+
+ class _Counting(_Layer):
+ misses = 0
+
+ def __getattr__(self, name):
+ if name in ("_per_layer_device", "_per_layer_device_index"):
+ type(self).misses += 1
+ return super().__getattr__(name)
+
+ layer = _Counting(device = torch.device("cpu"), index = "cpu")
+ _Counting.misses = 0
+ per_layer_device(layer)
+ assert _Counting.misses == 0
+
+ # unsloth_zoo from before the device attribute existed: the index alone.
+ layer = _Counting(index = 0)
+ _Counting.misses = 0
+ per_layer_device(layer)
+ assert _Counting.misses == 0, (
+ "the missing device attribute must not be discovered through "
+ "nn.Module.__getattr__ on every layer of every token"
+ )
+
+
+def test_a_class_level_attribute_is_still_honoured():
+ from unsloth.models._utils import per_layer_device
+
+ class _ClassAttribute(_Layer):
+ _per_layer_device = torch.device("cpu")
+ _per_layer_device_index = "cpu"
+
+ device, buffer_index = per_layer_device(_ClassAttribute())
+ assert device == torch.device("cpu")
+ assert buffer_index == 0
+
+ class _Property(_Layer):
+ @property
+ def _per_layer_device_index(self):
+ return "cpu"
+
+ device, buffer_index = per_layer_device(_Property())
+ assert device == torch.device("cpu")
+ assert buffer_index == 0
+
+
+def test_moving_an_activation_to_meta_destroys_it_silently():
+ """meta propagates through matmul instead of raising: the decode returns nothing."""
+ activation = torch.ones(2, 4)
+ moved = activation.to("meta")
+ assert moved.device.type == "meta"
+ assert torch.matmul(moved, torch.ones(4, 4)).device.type == "meta"
+
+
+def test_a_meta_layer_never_resolves_to_meta():
+ from unsloth.models._utils import per_layer_device
+ for layer in (
+ _Layer(parameter_device = "meta", index = None),
+ _Layer(device = torch.device("meta"), index = "meta"),
+ _Layer(parameter_device = "meta", index = "meta"),
+ ):
+ device, buffer_index = per_layer_device(layer)
+ assert device.type != "meta", device
+ assert isinstance(buffer_index, int), buffer_index
+
+
+def test_a_meta_layer_uses_the_accelerate_hook_execution_device():
+ from types import SimpleNamespace
+
+ from unsloth.models._utils import per_layer_device
+
+ layer = _Layer(parameter_device = "meta", index = None)
+ layer._hf_hook = SimpleNamespace(execution_device = "cpu")
+ device, _buffer_index = per_layer_device(layer)
+ assert device == torch.device("cpu")
+
+
+def test_a_hook_that_itself_says_meta_is_not_believed():
+ """accelerate sets execution_device to meta while a model is still being built."""
+ from types import SimpleNamespace
+
+ from unsloth.models._utils import per_layer_device
+
+ for execution_device in (None, "meta", torch.device("meta")):
+ layer = _Layer(parameter_device = "meta", index = None)
+ layer._hf_hook = SimpleNamespace(execution_device = execution_device)
+ device, _buffer_index = per_layer_device(layer)
+ assert device.type != "meta", (execution_device, device)
+
+
+def test_a_non_meta_layer_is_unchanged_by_the_meta_guard():
+ from unsloth.models._utils import per_layer_device
+
+ device, buffer_index = per_layer_device(_Layer(parameter_device = "cpu", index = None))
+ assert device == torch.device("cpu")
+ assert buffer_index == 0
+
+ device, buffer_index = per_layer_device(_Layer(device = torch.device("cuda:1"), index = 1))
+ assert device == torch.device("cuda:1")
+ assert buffer_index == 1
+
+
+def test_the_fast_path_spells_the_memo_name_the_constant_holds():
+ """Read as a literal, written through the constant: a rename is a silent miss."""
+ from unsloth.models import _utils
+
+ source = (REPOSITORY_ROOT / "unsloth/models/_utils.py").read_text(encoding = "utf-8")
+ fast_path = source.split("def per_layer_device(")[1].split("\n published =")[0]
+ assert f"module.{_utils._PER_LAYER_DEVICE_MEMO}" in fast_path, (
+ "the fast path does not read the attribute _PER_LAYER_DEVICE_MEMO names, so the "
+ "memo is written and never read"
+ )
+
+
+def test_a_layer_that_publishes_nothing_is_memoised_from_the_default():
+ from unsloth.models import _utils
+
+ layer = _Layer(parameter_device = "cpu")
+ first = _utils.per_layer_device(layer)
+ memo = layer.__dict__.get(_utils._PER_LAYER_DEVICE_MEMO)
+ if not default_device_is_usable():
+ assert memo is None, (
+ "with no usable default the answer came off the layer's own parameters, which "
+ "move with the layer, and memoising that sends activations to a dead device"
+ )
+ return
+ assert memo is not None, "the unpublished shape was left unmemoised"
+ assert memo[2] == _utils._MEMO_FROM_DEFAULT
+ assert _utils.per_layer_device(layer) == first
+
+
[email protected]("name", ["_per_layer_device_index", "_per_layer_device"])
+def test_the_default_memo_yields_the_moment_the_layer_publishes_a_name(name):
+ """unsloth_zoo running `verify_and_set_device` late must be followed, not memo-answered."""
+ from unsloth.models import _utils
+
+ if not default_device_is_usable():
+ pytest.skip("no usable default device, so this shape is never memoised")
+
+ layer = _Layer(parameter_device = "cpu")
+ _utils.per_layer_device(layer)
+ _utils.per_layer_device(layer)
+ assert layer.__dict__[_utils._PER_LAYER_DEVICE_MEMO][2] == _utils._MEMO_FROM_DEFAULT
+
+ setattr(layer, name, torch.device("cpu") if name == "_per_layer_device" else "cpu")
+ device, buffer_index = _utils.per_layer_device(layer)
+ assert device == torch.device("cpu"), f"the memo survived {name} being published on the layer"
+ assert buffer_index == 0
+
+
+def test_a_parameter_derived_answer_is_never_memoised(monkeypatch):
+ """With no usable default the answer comes off the layer's parameters, which move."""
+ from unsloth.models import _utils
+
+ monkeypatch.setattr(_utils, "_device_type_is_usable", lambda device_type: device_type == "cpu")
+ layer = _Layer(parameter_device = "cpu")
+ device, _ = _utils.per_layer_device(layer)
+ assert device == torch.device("cpu")
+ assert _utils._PER_LAYER_DEVICE_MEMO not in layer.__dict__, (
+ "a parameter-derived answer was memoised; the layer can move without any published "
+ "value changing, so the next token would go to the device it left"
+ )
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index d8884c7f808..b2cfc09d79f 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -2539,6 +2539,183 @@ if DEVICE_COUNT == 1 and int(os.environ.get("WORLD_SIZE", "1")) <= 1:
accelerate.accelerator.Accelerator.distributed_type = property(lambda self: DistributedType.NO)
+_PER_LAYER_DEVICE_MISSING = object()
+
+# A single object, because the checks below test it by identity to mean "no instance dict".
+_NO_INSTANCE_DICT = {}
+
+# Not spelled `_per_layer_device*`: that prefix is what unsloth_zoo publishes and the readers
+# grep for. The fast path spells this one out, so a rename must change both (asserted).
+_PER_LAYER_DEVICE_MEMO = "_unsloth_resolved_layer_device"
+
+# Memo slot 3: what the answer came from, hence what the fast path re-checks by identity.
+_MEMO_FROM_DEVICE = 0
+_MEMO_FROM_INDEX = 1
+_MEMO_FROM_DEFAULT = 2
+
+
[email protected]_cache(maxsize = None)
+def _device_type_is_usable(device_type: str) -> bool:
+ """No `torch.<type>.is_available` (`meta` included) means taken at its word."""
+ if device_type == "cpu":
+ return True
+ is_available = getattr(getattr(torch, device_type, None), "is_available", None)
+ if is_available is None:
+ return True
+ try:
+ return bool(is_available())
+ except Exception:
+ return False
+
+
+def _as_torch_device(value):
+ """A bare `torch.device(0)` is WRONG: with no accelerator torch 2.6 raises and torch 2.11
+ returns `cuda:0`. Probing the backend makes both return None here."""
+ try:
+ device = torch.device(value)
+ except (RuntimeError, TypeError, ValueError):
+ return None
+ if not _device_type_is_usable(device.type):
+ return None
+ return device
+
+
[email protected]_cache(maxsize = None)
+def _resolved_published_index(index, default):
+ """None means "needs the module": the caller falls through to the unmemoised routes."""
+ if index.__class__ is bool or not isinstance(index, (int, str)):
+ return None
+ device = _as_torch_device(index)
+ if device is None:
+ return None
+ buffer_index = device.index
+ if buffer_index is None:
+ if device.type == "meta":
+ return None
+ # Unindexed device: keep the callers' per-device tuple subscript in range.
+ buffer_index = index if index.__class__ is int else default
+ return device, buffer_index
+
+
+def _device_of_parameters(module):
+ for parameter in module.parameters():
+ return parameter.device
+ return None
+
+
+def _non_meta_device_of_parameters(module):
+ device = _device_of_parameters(module)
+ if device is not None and device.type == "meta":
+ return None
+ return device
+
+
+def _accelerate_execution_device(module):
+ """`AlignDevicesHook.pre_forward` sends args to `execution_device`, so for an offloaded or
+ meta layer that field, not its parameters, says where it runs."""
+ execution_device = getattr(getattr(module, "_hf_hook", None), "execution_device", None)
+ if execution_device is None:
+ return None
+ device = _as_torch_device(execution_device)
+ if device is None or device.type == "meta":
+ return None
+ return device
+
+
+def per_layer_device(module, default = 0):
+ """Where this decoder layer lives, as (device, buffer_index); gemma, gemma2 and cohere
+ still need the index, to subscript a per-device tuple. Probed, not version-gated: an older
+ unsloth_zoo publishes only the index and leaves it None on an accelerator layer, the
+ "Invalid target device: None" of unslothai/unsloth#3538. meta is excluded everywhere,
+ since moving an activation there destroys it silently. A layer genuinely on CPU with
+ accelerator-resident buffers is NOT fixed here and still raises."""
+ try:
+ source, resolved, derived_from = module._unsloth_resolved_layer_device
+ if default == 0:
+ if derived_from == _MEMO_FROM_INDEX:
+ if source is module._per_layer_device_index:
+ return resolved
+ elif derived_from == _MEMO_FROM_DEVICE:
+ if source is module._per_layer_device:
+ return resolved
+ # _MEMO_FROM_DEFAULT: derived from `default` alone, so only publishing one of the
+ # two names can stale it.
+ elif (
+ "_per_layer_device_index" not in module.__dict__
+ and "_per_layer_device" not in module.__dict__
+ ):
+ return resolved
+ except (AttributeError, TypeError, ValueError):
+ pass
+
+ # Instance dictionary, not getattr: `nn.Module.__getattr__` scans _parameters, _buffers
+ # and _modules before raising. The getattr fallback keeps class attributes working.
+ published = getattr(module, "__dict__", _NO_INSTANCE_DICT)
+ device = published.get("_per_layer_device")
+ index = published.get("_per_layer_device_index", _PER_LAYER_DEVICE_MISSING)
+ if device is None and index is _PER_LAYER_DEVICE_MISSING:
+ device = getattr(module, "_per_layer_device", None)
+ index = getattr(module, "_per_layer_device_index", _PER_LAYER_DEVICE_MISSING)
+
+ if device is None and (index.__class__ is int or index.__class__ is str):
+ # Exact class, not isinstance: bool must not key the memo (False hashes equal to 0),
+ # and an unhashable value must fall through rather than raise.
+ resolved = _resolved_published_index(index, default)
+ if resolved is not None:
+ if default == 0 and published is not _NO_INSTANCE_DICT:
+ # Memoisable because it depends on the published value alone, so the fast
+ # path's identity check is a complete invalidation.
+ published[_PER_LAYER_DEVICE_MEMO] = (index, resolved, _MEMO_FROM_INDEX)
+ return resolved
+
+ # Recorded before the fallbacks below overwrite what it is asking about.
+ published_nothing = device is None and index is _PER_LAYER_DEVICE_MISSING
+ if not isinstance(device, torch.device):
+ device = None
+ if device is None:
+ if index is None:
+ device = _device_of_parameters(module)
+ elif isinstance(index, (int, str)) and not isinstance(index, bool):
+ device = _as_torch_device(index)
+ from_default = False
+ if device is None:
+ # `torch.device(default)` may not be constructible, and a device is still owed.
+ device = _as_torch_device(default)
+ if device is None:
+ device = _non_meta_device_of_parameters(module) or torch.device("cpu")
+ else:
+ from_default = True
+
+ buffer_index = device.index
+ if buffer_index is None and device.type == "meta":
+ device = (
+ _accelerate_execution_device(module) or _as_torch_device(default) or torch.device("cpu")
+ )
+ # Module-derived however it was spelled, so it must not be memoised.
+ from_default = False
+ buffer_index = device.index
+ if buffer_index is None:
+ buffer_index = index if isinstance(index, int) and not isinstance(index, bool) else default
+ if default == 0 and published is not _NO_INSTANCE_DICT:
+ # Only when the answer IS the published object: a parameter- or hook-derived device
+ # moves without it changing, and memoising that sends activations to a dead device.
+ published_device = published.get("_per_layer_device")
+ if published_device is not None and published_device is device:
+ published[_PER_LAYER_DEVICE_MEMO] = (
+ published_device,
+ (device, buffer_index),
+ _MEMO_FROM_DEVICE,
+ )
+ elif published_nothing and from_default:
+ # `from_default` is the whole condition, for the same reason.
+ published[_PER_LAYER_DEVICE_MEMO] = (
+ None,
+ (device, buffer_index),
+ _MEMO_FROM_DEFAULT,
+ )
+ return device, buffer_index
+
+
def move_to_device(target_device, *tensors):
"""Move tensors to target_device (returns same objects if already there)."""
if isinstance(target_device, int):
diff --git a/unsloth/models/cohere.py b/unsloth/models/cohere.py
index 4051a7a9d14..fce9af39ef9 100644
--- a/unsloth/models/cohere.py
+++ b/unsloth/models/cohere.py
@@ -15,6 +15,7 @@ from .llama import (
original_apply_o,
)
from ._utils import __version__
+from ._utils import move_to_device, per_layer_device
from unsloth_zoo.hf_utils import dtype_from_config
from unsloth_zoo.utils import _get_dtype, Version
from ..utils.packing import get_packed_info_from_kwargs
@@ -445,8 +446,8 @@ def CohereModel_fast_forward_inference(
next_decoder_cache = []
for idx, decoder_layer in enumerate(self.model.layers):
- device_index = getattr(decoder_layer, "_per_layer_device_index", 0)
- hidden_states, position_ids = move_to_device(device_index, hidden_states, position_ids)
+ layer_device, device_index = per_layer_device(decoder_layer)
+ hidden_states, position_ids = move_to_device(layer_device, hidden_states, position_ids)
residual = hidden_states
hidden_states = fast_layernorm_inference(
decoder_layer.input_layernorm, hidden_states, out_weights[device_index]
diff --git a/unsloth/models/gemma.py b/unsloth/models/gemma.py
index 9dfadd1c0bb..ef3f2a8a80f 100644
--- a/unsloth/models/gemma.py
+++ b/unsloth/models/gemma.py
@@ -12,6 +12,7 @@
from .llama import *
from .llama import _get_rope_theta
from ._utils import __version__
+from ._utils import move_to_device, per_layer_device
from unsloth_zoo.utils import _get_dtype, Version
from unsloth_zoo.hf_utils import dtype_from_config
from ..utils.packing import (
@@ -189,8 +190,8 @@ def GemmaModel_fast_forward_inference(
next_decoder_cache = []
for idx, decoder_layer in enumerate(self.model.layers):
- device_index = getattr(decoder_layer, "_per_layer_device_index", 0)
- hidden_states, position_ids = move_to_device(device_index, hidden_states, position_ids)
+ layer_device, device_index = per_layer_device(decoder_layer)
+ hidden_states, position_ids = move_to_device(layer_device, hidden_states, position_ids)
residual = hidden_states
hidden_states = fast_rms_layernorm_inference_gemma(
diff --git a/unsloth/models/gemma2.py b/unsloth/models/gemma2.py
index 1b4af1ebbdc..91b3f893973 100644
--- a/unsloth/models/gemma2.py
+++ b/unsloth/models/gemma2.py
@@ -15,6 +15,7 @@ from .llama import (
original_apply_o,
)
from ._utils import __version__
+from ._utils import move_to_device, per_layer_device
from unsloth_zoo.utils import _get_dtype, Version
from unsloth_zoo.hf_utils import dtype_from_config
from ..utils.packing import get_packed_info_from_kwargs
@@ -485,8 +486,8 @@ def Gemma2Model_fast_forward_inference(
next_decoder_cache = []
for idx, decoder_layer in enumerate(self.model.layers):
# For pipeline parallelism every tensor must be on the same device; this movement happens once per GPU in PP.
- device_index = getattr(decoder_layer, "_per_layer_device_index", 0)
- hidden_states, position_ids = move_to_device(device_index, hidden_states, position_ids)
+ layer_device, device_index = per_layer_device(decoder_layer)
+ hidden_states, position_ids = move_to_device(layer_device, hidden_states, position_ids)
use_sliding_window = idx % 2 == 0
diff --git a/unsloth/models/granite.py b/unsloth/models/granite.py
index 5410a8bd41c..ff190178f9b 100644
--- a/unsloth/models/granite.py
+++ b/unsloth/models/granite.py
@@ -12,6 +12,7 @@
from .llama import *
import os
from ._utils import __version__
+from ._utils import move_to_device, per_layer_device
from unsloth_zoo.utils import _get_dtype, Version
from unsloth_zoo.hf_utils import dtype_from_config
from ..utils.packing import get_packed_info_from_kwargs
@@ -451,8 +452,8 @@ def GraniteModel_fast_forward_inference(
next_decoder_cache = []
for idx, decoder_layer in enumerate(self.model.layers):
- device_index = getattr(decoder_layer, "_per_layer_device_index", 0)
- hidden_states, position_ids = move_to_device(device_index, hidden_states, position_ids)
+ layer_device, _ = per_layer_device(decoder_layer)
+ hidden_states, position_ids = move_to_device(layer_device, hidden_states, position_ids)
residual = hidden_states
hidden_states = fast_rms_layernorm_inference(decoder_layer.input_layernorm, hidden_states)
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index 69d0248930b..62cc0093f9b 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -22,6 +22,7 @@ from ._utils import *
from ._utils import apply_unsloth_gradient_checkpointing
from ._utils import __version__, importlib_version
from ._utils import move_to_device
+from ._utils import per_layer_device
from ._utils import (
_get_inference_mode_context_manager,
_prepare_model_for_qat,
@@ -1266,8 +1267,8 @@ def _LlamaModel_fast_forward_inference(
next_decoder_cache = []
for idx, decoder_layer in enumerate(self.model.layers):
- device_index = getattr(decoder_layer, "_per_layer_device_index", 0)
- X, residual, position_ids = move_to_device(device_index, X, residual, position_ids)
+ layer_device, device_index = per_layer_device(decoder_layer)
+ X, residual, position_ids = move_to_device(layer_device, X, residual, position_ids)
residual.copy_(X)
X = fast_rms_layernorm_inference(
decoder_layer.input_layernorm,