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.

Skip the per-layer RoPE stream sync unless the model spans several devices (#13609)

Daniel Han1c0b34e54812
diff --git a/tests/test_rope_sync_single_device.py b/tests/test_rope_sync_single_device.py
new file mode 100644
index 00000000000..893767eba8c
--- /dev/null
+++ b/tests/test_rope_sync_single_device.py
@@ -0,0 +1,231 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+"""RoPE drains the stream only for a model split over several devices, not on every multi-GPU host."""
+
+import gc
+import weakref
+
+import pytest
+import torch
+
+import unsloth.kernels.rope_embedding as RE
+from real_accelerator import has_real_cuda
+
+
+class _FakeQ:
+ def __init__(self, index):
+ self.index = index
+ self.device = torch.device("cuda", index)
+
+ def get_device(self):
+ return self.index
+
+
+class _Model:
+ def __init__(self, device_map):
+ self.hf_device_map = device_map
+
+
+def current(monkeypatch):
+ device = [0]
+ monkeypatch.setattr(RE, "_current_device", lambda: device[0], raising = False)
+ return device
+
+
+def synced(monkeypatch, current):
+ calls = []
+
+ class _Stream:
+ def __init__(self, device):
+ self.device = device
+
+ def synchronize(self):
+ calls.append(self.device.index)
+
+ monkeypatch.setattr(RE, "torch_device_stream", _Stream)
+ monkeypatch.setattr(RE, "_SPLIT_MODELS", weakref.WeakSet(), raising = False)
+ monkeypatch.setattr(RE, "_UNREGISTERED_SPLIT_SEEN", False, raising = False)
+ monkeypatch.setattr(RE.Fast_RoPE_Embedding_QK, "apply", lambda Q, K, *a: (Q, K))
+ monkeypatch.setattr(RE.Slow_RoPE_Embedding, "apply", lambda Q, *a: Q)
+ return calls
+
+
+def _rope(index):
+ Q = _FakeQ(index)
+ RE._fast_rope_embedding_eager(Q, Q, None, None, rope_embedding_indices = object())
+
+
[email protected]("index", [0, 3])
+def test_single_device_on_multi_gpu_host_never_syncs(monkeypatch, synced, current, index):
+ monkeypatch.setattr(RE, "DEVICE_COUNT", 8)
+ current[0] = index
+ assert not RE.register_split_model(_Model({"": index}))
+ for _ in range(64):
+ _rope(index)
+ assert synced == []
+
+
+def test_inplace_rope_single_device_never_syncs(monkeypatch, synced):
+ monkeypatch.setattr(RE, "DEVICE_COUNT", 2)
+ for _ in range(8):
+ Q = _FakeQ(0)
+ RE.inplace_rope_embedding(Q, Q, None, None, None)
+ assert synced == []
+
+
+def test_one_visible_device_never_syncs(monkeypatch, synced):
+ monkeypatch.setattr(RE, "DEVICE_COUNT", 1)
+ assert not RE.register_split_model(_Model({"model.layers.0": 0, "model.layers.1": 1}))
+ for _ in range(8):
+ _rope(0)
+ Q = _FakeQ(0)
+ RE.inplace_rope_embedding(Q, Q, None, None, None)
+ assert synced == []
+
+
+def test_split_model_syncs_from_the_first_call(monkeypatch, synced):
+ monkeypatch.setattr(RE, "DEVICE_COUNT", 2)
+ model = _Model(
+ {
+ "model.embed_tokens": 0,
+ "model.layers.0": "cuda:0",
+ "model.layers.1": "1",
+ "lm_head": "cpu",
+ }
+ )
+ assert RE.register_split_model(model)
+ layers = [0, 0, 1, 1]
+ for _ in range(3):
+ for index in layers:
+ _rope(index)
+ assert synced == layers * 3
+ Q = _FakeQ(0)
+ RE.inplace_rope_embedding(Q, Q, None, None, None)
+ assert synced[-1] == 0
+
+
+def test_independent_single_device_models_stay_unsynced(monkeypatch, synced, current):
+ monkeypatch.setattr(RE, "DEVICE_COUNT", 2)
+ a, b = _Model({"": 0}), _Model({"": "cuda:1"})
+ assert not RE.register_split_model(a) and not RE.register_split_model(b)
+ for _ in range(4):
+ for index in (0, 1):
+ current[0] = index
+ _rope(index)
+ assert synced == []
+
+
+def test_freed_split_model_stops_syncing(monkeypatch, synced):
+ monkeypatch.setattr(RE, "DEVICE_COUNT", 2)
+ model = _Model({"model.layers.0": 0, "model.layers.1": 1})
+ assert RE.register_split_model(model)
+ _rope(0)
+ assert synced == [0]
+ del model
+ gc.collect()
+ _rope(0)
+ assert synced == [0]
+
+
+def test_unregistered_split_syncs_once_seen(monkeypatch, synced):
+ monkeypatch.setattr(RE, "DEVICE_COUNT", 2)
+ for _ in range(2):
+ for index in [0, 0, 1, 1]:
+ _rope(index)
+ assert synced == [1, 1, 0, 0, 1, 1]
+
+
+def test_index_less_entries_mean_the_current_device(monkeypatch, synced, current):
+ monkeypatch.setattr(RE, "DEVICE_COUNT", 2)
+ current[0] = 1
+ assert not RE.register_split_model(
+ _Model({"model.layers.0": "cuda", "model.layers.1": "cuda:1"})
+ )
+ assert RE.register_split_model(_Model({"model.layers.0": "cuda", "model.layers.1": "cuda:0"}))
+
+
+def test_unhashable_split_model_drains_instead_of_raising(monkeypatch, synced):
+ monkeypatch.setattr(RE, "DEVICE_COUNT", 2)
+
+ class _Unhashable(_Model):
+ def __eq__(self, other):
+ return self is other
+
+ assert RE.register_split_model(_Unhashable({"model.layers.0": 0, "model.layers.1": 1}))
+ for index in [0, 0, 1, 1]:
+ _rope(index)
+ assert synced == [0, 0, 1, 1]
+
+
+def test_hand_dispatched_split_syncs_from_the_first_call(monkeypatch, synced):
+ import importlib
+ import sys
+
+ monkeypatch.setattr(RE, "DEVICE_COUNT", 2)
+ calls = []
+
+ def stub(model, device_map, **kwargs):
+ calls.append(device_map)
+
+ names = [
+ "accelerate",
+ "accelerate.big_modeling",
+ "transformers.modeling_utils",
+ "transformers.integrations.accelerate",
+ "transformers.integrations.peft",
+ ]
+ bound = []
+ importlib.import_module("accelerate.big_modeling")
+ for name in names:
+ module = sys.modules.get(name)
+ if module is not None and hasattr(module, "dispatch_model"):
+ monkeypatch.setattr(module, "dispatch_model", stub)
+ bound.append(module)
+ RE._register_splits_on_dispatch()
+ assert all(module.dispatch_model is not stub for module in bound)
+ RE._register_splits_on_dispatch()
+ assert not getattr(stub, "_unsloth_registers_split", False)
+
+ import accelerate
+
+ single, split = _Model({}), _Model({})
+ accelerate.dispatch_model(single, device_map = {"": 1})
+ accelerate.dispatch_model(split, {"model.layers.0": 0, "model.layers.1": "cuda:1"})
+ assert len(calls) == 2 and len(RE._SPLIT_MODELS) == 1 and split in RE._SPLIT_MODELS
+ for index in [0, 0, 1, 1]:
+ _rope(index)
+ assert synced == [0, 0, 1, 1]
+
+
[email protected](not has_real_cuda(), reason = "Triton RoPE kernel needs CUDA")
[email protected]("use_indices", [False, True])
+def test_real_kernel_single_device_no_sync_same_result(monkeypatch, use_indices):
+ monkeypatch.setattr(RE, "_SPLIT_MODELS", weakref.WeakSet(), raising = False)
+ monkeypatch.setattr(RE, "_UNREGISTERED_SPLIT_SEEN", False, raising = False)
+ monkeypatch.setattr(RE, "_current_device", torch.cuda.current_device)
+ count = [0]
+ real = torch.cuda.Stream.synchronize
+
+ def counting(self):
+ count[0] += 1
+ return real(self)
+
+ monkeypatch.setattr(torch.cuda.Stream, "synchronize", counting)
+ torch.manual_seed(0)
+ b, h, s, d = 2, 4, 32, 64
+ inv = 1.0 / (10000 ** (torch.arange(0, d, 2, device = "cuda").float() / d))
+ emb = torch.cat([torch.outer(torch.arange(s, device = "cuda").float(), inv)] * 2, -1)
+ cos, sin = emb.cos(), emb.sin()
+ idx = torch.arange(s, device = "cuda").expand(b, s).contiguous() if use_indices else None
+ x = torch.randn(b, h, s, d, device = "cuda")
+
+ monkeypatch.setattr(RE, "DEVICE_COUNT", 1)
+ ref_q, ref_k = RE.fast_rope_embedding(x.clone(), x.clone(), cos, sin, idx)
+ monkeypatch.setattr(RE, "DEVICE_COUNT", 2)
+ q, k = RE.fast_rope_embedding(x.clone(), x.clone(), cos, sin, idx)
+ torch.cuda.synchronize()
+ assert count[0] == 0
+ assert torch.equal(q, ref_q) and torch.equal(k, ref_k)
diff --git a/unsloth/kernels/rope_embedding.py b/unsloth/kernels/rope_embedding.py
index 7069254dd62..9dfe2a5d05c 100644
--- a/unsloth/kernels/rope_embedding.py
+++ b/unsloth/kernels/rope_embedding.py
@@ -11,10 +11,11 @@
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import functools
+import weakref
import triton
import triton.language as tl
import torch
-from ..device_type import DEVICE_COUNT
+from ..device_type import DEVICE_COUNT, DEVICE_TYPE_TORCH
from typing import Tuple
from .utils import calculate_settings, long_indexing, torch_gpu_device, torch_device_stream
from .rms_layernorm import (
@@ -396,14 +397,113 @@ if _TRACEABLE:
_tag_compile_cache(__file__)
+# The RoPE stream drain exists only for models split over devices (#3049, #3061); single-device skips it.
+_SPLIT_MODELS = weakref.WeakSet()
+
+# Unregistered or untrackable split seen: drain every call from then on.
+_UNREGISTERED_SPLIT_SEEN = False
+
+if DEVICE_COUNT > 1:
+ _current_device = getattr(torch, DEVICE_TYPE_TORCH).current_device
+else:
+ _current_device = None
+
+
+def _accelerator_indices(device_map):
+ # Index-less "cuda" means the current device, not device 0.
+ current = _current_device() if _current_device is not None else 0
+ indices = set()
+ for value in device_map.values():
+ if isinstance(value, bool):
+ continue
+ if isinstance(value, int):
+ indices.add(value)
+ continue
+ text = str(value)
+ if text.isdigit():
+ indices.add(int(text))
+ continue
+ if text in ("cpu", "disk", "meta"):
+ continue
+ try:
+ device = torch.device(text)
+ except Exception:
+ continue
+ if device.type in ("cpu", "meta"):
+ continue
+ indices.add(current if device.index is None else device.index)
+ return indices
+
+
+def register_split_model(model, device_map = None):
+ """Never raises: a split that cannot be tracked (an unhashable model) drains every call instead."""
+ global _UNREGISTERED_SPLIT_SEEN
+ if DEVICE_COUNT <= 1:
+ return False
+ try:
+ if device_map is None:
+ device_map = getattr(model, "hf_device_map", None)
+ if not isinstance(device_map, dict) or len(_accelerator_indices(device_map)) < 2:
+ return False
+ _SPLIT_MODELS.add(model)
+ except Exception:
+ _UNREGISTERED_SPLIT_SEEN = True
+ return True
+
+
+def _register_splits_on_dispatch():
+ import sys
+
+ try:
+ import accelerate.big_modeling as big_modeling
+ except Exception:
+ return
+ original = big_modeling.dispatch_model
+ if getattr(original, "_unsloth_registers_split", False):
+ return
+
+ @functools.wraps(original)
+ def dispatch_model(model, device_map, *args, **kwargs):
+ out = original(model, device_map, *args, **kwargs)
+ register_split_model(model, device_map)
+ return out
+
+ dispatch_model._unsloth_registers_split = True
+ # transformers binds it by name at import.
+ for name in (
+ "accelerate",
+ "accelerate.big_modeling",
+ "transformers.modeling_utils",
+ "transformers.integrations.accelerate",
+ "transformers.integrations.peft",
+ ):
+ module = sys.modules.get(name)
+ if module is not None and getattr(module, "dispatch_model", None) is original:
+ module.dispatch_model = dispatch_model
+
+
+if DEVICE_COUNT > 1:
+ _register_splits_on_dispatch()
+
+
+def _sync_if_split(Q):
+ global _UNREGISTERED_SPLIT_SEEN
+ if DEVICE_COUNT <= 1:
+ return
+ if not (_SPLIT_MODELS or _UNREGISTERED_SPLIT_SEEN):
+ if Q.get_device() == _current_device():
+ return
+ _UNREGISTERED_SPLIT_SEEN = True
+ torch_device_stream(Q.device).synchronize()
+
+
def _fast_rope_embedding_eager(Q, K, cos, sin, rope_embedding_indices):
if rope_embedding_indices is not None:
Q_out, K_out = Fast_RoPE_Embedding_QK.apply(Q, K, cos, sin, rope_embedding_indices)
else:
Q_out = Fast_RoPE_Embedding.apply(Q.transpose(1, 2).contiguous(), cos, sin).transpose(1, 2)
K_out = Fast_RoPE_Embedding.apply(K.transpose(1, 2).contiguous(), cos, sin).transpose(1, 2)
- if DEVICE_COUNT > 1:
- torch_device_stream(Q.device).synchronize()
+ _sync_if_split(Q)
return Q_out, K_out
@@ -467,5 +567,5 @@ class Slow_RoPE_Embedding(torch.autograd.Function):
def inplace_rope_embedding(Q, K, cos, sin, position_ids):
Q = Slow_RoPE_Embedding.apply(Q, cos, sin, position_ids)
K = Slow_RoPE_Embedding.apply(K, cos, sin, position_ids)
- torch_device_stream(Q.device).synchronize()
+ _sync_if_split(Q)
return Q, K
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index f669b1703f4..901e2c53be7 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -100,6 +100,7 @@ from ..kernels import (
post_patch_loss_function,
)
from ..kernels.bnb_override import install_bnb_nf4_override as _install_bnb_nf4_override
+from ..kernels.rope_embedding import register_split_model
from ._utils import (
__version__,
importlib_version,
@@ -303,6 +304,7 @@ def _infer_device_map_from_loaded_model(model, skip = ()):
def _repair_dispatch_hooks(model):
"""Give a dispatched module its hook back after the load replaced it. `dispatch_model` hooks every map entry; what drops the hook is our own `post_patch` -> `patch_model_and_tokenizer`, which installs a NEW Embedding and Linear over the same weights, so `_hf_hook` dies with the old module. Not tied-specific: `tie_word_embeddings = False` fails identically. Unrepaired, a split model raises `index is on cuda:0, different from other tensors on cuda:1` at the first embedding lookup."""
+ register_split_model(model)
device_map = getattr(model, "hf_device_map", None)
if not device_map or len(set(device_map.values())) < 2:
return 0