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.

CPU backend: context parallelism engages (or refuses) instead of silently running DDP; CP modules import (#16802)

Daniel Hana215ec7eee29
diff --git a/tests/test_cpu_route_context_parallel.py b/tests/test_cpu_route_context_parallel.py
new file mode 100644
index 00000000000..16d0e0cfe83
--- /dev/null
+++ b/tests/test_cpu_route_context_parallel.py
@@ -0,0 +1,227 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+"""CPU backend: a trainer asking for CP gets it or an error before __init__, never plain DDP.
+Fresh interpreters since the backend is chosen at import; 2-rank cells are gloo on a tiny Qwen3."""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+import pytest
+
+_ROOT = Path(__file__).resolve().parents[1]
+_REPO = "trl-internal-testing/tiny-Qwen3ForCausalLM"
+
+
+def _env(extra = None):
+ env = {
+ k: v
+ for k, v in os.environ.items()
+ if k not in ("UNSLOTH_ALLOW_CPU", "UNSLOTH_FORCE_CPU", "UNSLOTH_DISABLE_CPU_FALLBACK")
+ and not k.startswith("UNSLOTH_CP_")
+ and k != "UNSLOTH_PARALLEL"
+ }
+ env["CUDA_VISIBLE_DEVICES"] = ""
+ env["UNSLOTH_FORCE_CPU"] = "1"
+ env["OMP_NUM_THREADS"] = "2"
+ env["TOKENIZERS_PARALLELISM"] = "false"
+ env["PYTHONPATH"] = os.pathsep.join(filter(None, [str(_ROOT), env.get("PYTHONPATH")]))
+ env.update(extra or {})
+ return env
+
+
+def _run(
+ code,
+ extra = None,
+ timeout = 900,
+):
+ return subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output = True,
+ text = True,
+ env = _env(extra),
+ timeout = timeout,
+ cwd = tempfile.gettempdir(),
+ )
+
+
+def _result(out):
+ for line in out.stdout.splitlines():
+ if line.startswith("RESULT "):
+ return json.loads(line[7:])
+ pytest.fail(f"no RESULT line\nstdout:\n{out.stdout[-3000:]}\nstderr:\n{out.stderr[-5000:]}")
+
+
+_ROUTE = "import unsloth\nassert unsloth.DEVICE_TYPE == 'cpu', unsloth.DEVICE_TYPE\n"
+
+
+ "statement",
+ [
+ "from unsloth.utils import attention_dispatch",
+ "import unsloth.context_parallel",
+ "import unsloth.utils.packing",
+ "from unsloth.utils import ulysses_hybrid",
+ ],
+)
+def test_cpu_route_imports_cp_and_attention_modules(statement):
+ code = (
+ _ROUTE
+ + statement
+ + (
+ "\nfrom unsloth.utils import attention_dispatch as ad\n"
+ "from unsloth import context_parallel as cp\n"
+ "assert ad.get_cp_manager is cp.get_cp_manager and cp.get_cp_manager() is None\n"
+ "print('RESULT ' + __import__('json').dumps({'ok': True}))\n"
+ )
+ )
+ out = _run(code)
+ assert out.returncode == 0, out.stderr[-5000:]
+ assert _result(out)["ok"]
+
+
+def test_cpu_route_plain_trainer_skips_gpu_stack():
+ # No CP asked for: the gate must not load the GPU model stack.
+ code = _ROUTE + (
+ "import sys, json, trl\n"
+ "from unsloth import FastLanguageModel\n"
+ f"model, tok = FastLanguageModel.from_pretrained({_REPO!r}, max_seq_length = 32, load_in_4bit = False)\n"
+ "from datasets import Dataset\n"
+ "ds = Dataset.from_dict({'text': ['hello world'] * 4})\n"
+ "cfg = trl.SFTConfig(output_dir = 'o_plain', max_steps = 1, report_to = 'none', dataset_num_proc = 1)\n"
+ "trainer = trl.SFTTrainer(model = model, args = cfg, train_dataset = ds, processing_class = tok)\n"
+ "print('RESULT ' + json.dumps({'models': 'unsloth.models' in sys.modules,\n"
+ " 'cp': 'unsloth.context_parallel' in sys.modules}))\n"
+ )
+ out = _run(code)
+ assert out.returncode == 0, out.stderr[-5000:]
+ assert _result(out) == {"models": False, "cp": False}
+
+
[email protected]("forwarded", [1, None])
+def test_cpu_route_forwarded_cp_size_of_one_opts_out(forwarded):
+ # SFTTrainer(args = config with cp 2, context_parallel_size = 1 / None): the keyword wins, so no CP and no error.
+ code = _ROUTE + (
+ "import sys, json, trl\n"
+ "from unsloth import FastLanguageModel\n"
+ f"model, tok = FastLanguageModel.from_pretrained({_REPO!r}, max_seq_length = 32, load_in_4bit = False)\n"
+ "from datasets import Dataset\n"
+ "ds = Dataset.from_dict({'text': ['hello world'] * 4})\n"
+ "cfg = trl.SFTConfig(output_dir = 'o_opt_out', max_steps = 1, report_to = 'none', dataset_num_proc = 1)\n"
+ "cfg.context_parallel_size = 2\n"
+ "trainer = trl.SFTTrainer(model = model, args = cfg, train_dataset = ds, processing_class = tok,\n"
+ f" context_parallel_size = {forwarded!r})\n"
+ "print('RESULT ' + json.dumps({'cp': 'unsloth.context_parallel' in sys.modules,\n"
+ " 'manager': getattr(trainer, '_context_parallel_manager', None) is not None}))\n"
+ )
+ out = _run(code)
+ assert out.returncode == 0, out.stderr[-5000:]
+ assert _result(out) == {"cp": False, "manager": False}
+
+
+def test_cpu_route_cp_refused_before_init_when_unavailable():
+ # The CP machinery cannot load (simulated): the trainer must raise before the TRL __init__ runs.
+ code = _ROUTE + (
+ "import sys, json, types, trl\n"
+ "sys.modules['unsloth.context_parallel'] = None\n"
+ "calls = []\n"
+ "base = trl.SFTTrainer.__mro__[1]\n"
+ "real = base.__init__\n"
+ "base.__init__ = lambda self, *a, **k: calls.append(1)\n"
+ "cfg = types.SimpleNamespace(context_parallel_size = 2)\n"
+ "try:\n"
+ " trl.SFTTrainer(model = None, args = cfg)\n"
+ " err = None\n"
+ "except Exception as e:\n"
+ " err = f'{type(e).__name__}: {e}'\n"
+ "print('RESULT ' + json.dumps({'error': err, 'init_ran': bool(calls)}))\n"
+ )
+ out = _run(code)
+ res = _result(out)
+ assert res["error"] is not None and "context parallelism" in res["error"], res
+ assert res["init_ran"] is False, res
+
+
+_WORKER = r"""
+import json, os, sys
+import unsloth
+assert unsloth.DEVICE_TYPE == "cpu", unsloth.DEVICE_TYPE
+import torch, trl
+from datasets import Dataset
+from unsloth import FastLanguageModel
+
+torch.manual_seed(0)
+model, tok = FastLanguageModel.from_pretrained(REPO, max_seq_length = 32, load_in_4bit = False)
+if tok.pad_token is None:
+ tok.pad_token = tok.eos_token
+ds = Dataset.from_dict({"text": ["the quick brown fox jumps over the lazy dog " * 3] * 8})
+cfg = trl.SFTConfig(
+ output_dir = OUT, max_steps = 2, per_device_train_batch_size = 2, learning_rate = 1e-3,
+ report_to = "none", logging_steps = 1, save_strategy = "no", dataset_num_proc = 1,
+ max_length = 32, padding_free = False, ddp_find_unused_parameters = False,
+)
+if MODE == "config":
+ cfg.context_parallel_size = 2
+ cfg.context_parallel_backend = "ulysses"
+trainer = trl.SFTTrainer(model = model, args = cfg, train_dataset = ds, processing_class = tok)
+manager = getattr(trainer, "_context_parallel_manager", None)
+trainer.train()
+losses = [h["loss"] for h in trainer.state.log_history if "loss" in h]
+print("RESULT " + json.dumps({
+ "rank": int(os.environ["RANK"]),
+ "manager": None if manager is None else {"size": manager.size, "backend": str(manager.backend)},
+ "losses": losses,
+}), flush = True)
+"""
+
+
+def _free_port():
+ from tests._rendezvous_port import free_port
+ return free_port()
+
+
[email protected]("mode", ["config", "env"])
+def test_cpu_route_two_rank_cp_engages(mode, tmp_path):
+ pytest.importorskip("trl")
+ port = _free_port()
+ code = f"REPO = {_REPO!r}\nOUT = {str(tmp_path / 'out')!r}\nMODE = {mode!r}\n" + _WORKER
+ extra = {"MASTER_ADDR": "127.0.0.1", "MASTER_PORT": str(port), "WORLD_SIZE": "2"}
+ if mode == "env":
+ extra["UNSLOTH_CP_SIZE"] = "2"
+ extra["UNSLOTH_CP_BACKEND"] = "ulysses"
+ procs = [
+ subprocess.Popen(
+ [sys.executable, "-c", code],
+ stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE,
+ text = True,
+ env = _env({**extra, "RANK": str(r), "LOCAL_RANK": str(r)}),
+ cwd = str(tmp_path),
+ )
+ for r in range(2)
+ ]
+ outs = []
+ for p in procs:
+ try:
+ stdout, stderr = p.communicate(timeout = 900)
+ except subprocess.TimeoutExpired:
+ for q in procs:
+ q.kill()
+ raise
+ outs.append(subprocess.CompletedProcess(p.args, p.returncode, stdout, stderr))
+ for out in outs:
+ assert out.returncode == 0, out.stderr[-6000:]
+ results = [_result(out) for out in outs]
+ for res in results:
+ assert res["manager"] is not None, f"CP silently fell back to DDP: {res}"
+ assert res["manager"]["size"] == 2, res
+ assert "ulysses" in res["manager"]["backend"], res
+ # CP ranks train one sequence split across them: the same loss on both.
+ assert results[0]["losses"] and results[0]["losses"] == pytest.approx(
+ results[1]["losses"], rel = 1e-5
+ )
diff --git a/unsloth/_cpu_init.py b/unsloth/_cpu_init.py
index ab0231e6498..e55162fb4ee 100644
--- a/unsloth/_cpu_init.py
+++ b/unsloth/_cpu_init.py
@@ -211,6 +211,89 @@ _install_cpu_trainer_module()
del _install_cpu_trainer_module
+def _cpu_cp_requested(args, kwargs) -> bool:
+ from .parallel_env import env_cp_size
+
+ config = kwargs["args"] if "args" in kwargs else (args[1] if len(args) > 1 else None)
+ size = getattr(config, "context_parallel_size", None)
+ if "context_parallel_size" in kwargs:
+ # The keyword wins over the config, and None opts out like 1 (context_parallel.patch_sft_trainer).
+ size = kwargs["context_parallel_size"]
+ if isinstance(size, int) and not isinstance(size, bool) and size > 1:
+ return True
+ return env_cp_size() > 1
+
+
+def _install_cpu_context_parallel():
+ # context_parallel loads the GPU model stack, so load it lazily on the first trainer requesting CP;
+ # that trainer gets CP or an error before __init__, never silent plain DDP.
+ import functools
+
+ trainer_cls = _SFTTrainer
+ if not isinstance(trainer_cls, type) or trainer_cls is _SFTConfig:
+ return # TRL missing: the stub already raises
+ original_init = trainer_cls.__init__
+ cp_keys = (
+ "context_parallel_size",
+ "context_parallel_backend",
+ "context_parallel_rotate_method",
+ )
+ state = {}
+
+ @functools.wraps(original_init)
+ def cp_fields_into_config(self, *args, **kwargs):
+ # Stock TRL rejects CP kwargs (the GPU route's SFTConfig declares them), so move them onto the config.
+ cp = {key: kwargs.pop(key) for key in cp_keys if key in kwargs}
+ config = kwargs["args"] if "args" in kwargs else (args[1] if len(args) > 1 else None)
+ if config is not None:
+ for key, value in cp.items():
+ setattr(config, key, value)
+ return original_init(self, *args, **kwargs)
+
+ @functools.wraps(original_init)
+ def __init__(self, *args, **kwargs):
+ requested = _cpu_cp_requested(args, kwargs)
+ if requested and "init" not in state:
+ current = trainer_cls.__init__
+ trainer_cls.__init__ = (
+ cp_fields_into_config # patch_sft_trainer wraps the class's __init__
+ )
+ try:
+ from .context_parallel import patch_sft_trainer
+ patch_sft_trainer()
+ state["init"] = trainer_cls.__init__
+ except Exception as error:
+ raise RuntimeError(
+ "Unsloth: context parallelism was requested (context_parallel_size > 1 or "
+ "UNSLOTH_CP_SIZE / UNSLOTH_PARALLEL cp), but it could not be set up on the CPU backend: "
+ f"{type(error).__name__}: {error}. Unset it to train without context parallelism."
+ ) from error
+ finally:
+ trainer_cls.__init__ = current
+ init = state.get("init")
+ if init is None:
+ # context_parallel_size = 1 / None opts out, but stock TRL still rejects the keyword.
+ init = cp_fields_into_config if any(key in kwargs for key in cp_keys) else original_init
+ init(self, *args, **kwargs)
+ # A config TRL rebuilt from to_dict() loses CP attributes set on it.
+ if (
+ requested
+ and init
+ is not cp_fields_into_config # else an outer, hand-installed patch owns the check
+ and getattr(self, "_context_parallel_manager", None) is None
+ ):
+ raise RuntimeError(
+ "Unsloth: context parallelism was requested but the trainer did not set it up on the CPU "
+ "backend (pass a trl.SFTConfig as args); refusing to train without it."
+ )
+
+ trainer_cls.__init__ = __init__
+
+
+_install_cpu_context_parallel()
+del _install_cpu_context_parallel
+
+
def _load_dataprep(name: str):
# By file: dataprep/__init__ also imports synthetic.py, which needs a GPU device type.
import sys
diff --git a/unsloth/context_parallel.py b/unsloth/context_parallel.py
index bedb78d1f7d..5839b66455c 100644
--- a/unsloth/context_parallel.py
+++ b/unsloth/context_parallel.py
@@ -196,6 +196,15 @@ def _unregister_cp_sharding_rules() -> None:
unregister_cp_sharding_rules(clear_the_cache = False)
+# A module global, not a ContextVar: CUDA runs backward (and checkpoint recompute) on another thread.
+_ACTIVE_MANAGER: Optional["ContextParallelManager"] = None
+
+
+# Before the imports below: on the CPU route they bind this from the partially initialised module.
+def get_cp_manager() -> Optional["ContextParallelManager"]:
+ return _ACTIVE_MANAGER
+
+
from .device_type import DEVICE_TYPE_TORCH
from .utils.ulysses import _document_positions, ulysses_head_plan
from .utils.ulysses_hybrid import (
@@ -207,9 +216,6 @@ from .utils.ulysses_hybrid import (
wrap_gated_delta_forward,
)
-# A module global, not a ContextVar: CUDA runs backward (and checkpoint recompute) on another thread.
-_ACTIVE_MANAGER: Optional["ContextParallelManager"] = None
-
# shift_labels is built before sharding so each shard's last token keeps its next-token target.
_BUFFER_NAMES = ("input_ids", "attention_mask", "labels", "position_ids", "shift_labels")
_PAD_VALUES = {"labels": -100, "shift_labels": -100, "attention_mask": 0, "input_ids": 0}
@@ -235,10 +241,6 @@ _INSTALLED_MESH = []
_INSTALLED_PARALLELISM_CONFIG = []
-def get_cp_manager() -> Optional["ContextParallelManager"]:
- return _ACTIVE_MANAGER
-
-
def _stateful_mixers(model) -> list:
from .utils.packing import _iter_stateful_mixers
return _iter_stateful_mixers(model) if isinstance(model, torch.nn.Module) else []
diff --git a/unsloth/utils/__init__.py b/unsloth/utils/__init__.py
index 7834bc43e58..2fecf9e64f9 100644
--- a/unsloth/utils/__init__.py
+++ b/unsloth/utils/__init__.py
@@ -10,6 +10,10 @@
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
+import importlib
+
+# Import models first, else the CPU route sees attention_dispatch half initialised (import cycle via llama.py).
+importlib.import_module("..models", __name__)
from .packing import (
configure_padding_free,
configure_sample_packing,