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.

Context parallel: patch DPO / GRPO even when context_parallel is imported before the models (#17185)

Daniel Handcb1eb1ec75c
diff --git a/tests/test_cp_rl_patch_import_order.py b/tests/test_cp_rl_patch_import_order.py
new file mode 100644
index 00000000000..fe00415eea8
--- /dev/null
+++ b/tests/test_cp_rl_patch_import_order.py
@@ -0,0 +1,48 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""DPO / GRPO keep their context parallel patch when unsloth.context_parallel is imported before the models."""
+
+import os
+import subprocess
+import sys
+
+import pytest
+
+_REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+_PROBE = """
+import sys
+__import__(sys.argv[1])
+import unsloth.models # noqa: F401 (models/llama.py patches the TRL trainers)
+from trl import DPOTrainer, GRPOTrainer
+print("CP_FLAGS", [bool(getattr(t, "__unsloth_context_parallel__", False)) for t in (DPOTrainer, GRPOTrainer)])
+"""
+
+
[email protected]("first", ["unsloth", "unsloth.context_parallel"])
+def test_rl_trainers_get_context_parallel_patch(first, tmp_path):
+ # GPU-less CPU fallback, where unsloth's own import does not load the models before context_parallel.
+ env = {
+ k: v
+ for k, v in os.environ.items()
+ if k not in ("UNSLOTH_ALLOW_CPU", "UNSLOTH_FORCE_CPU", "UNSLOTH_DISABLE_CPU_FALLBACK")
+ }
+ env.update(
+ CUDA_VISIBLE_DEVICES = "",
+ OMP_NUM_THREADS = "2",
+ TOKENIZERS_PARALLELISM = "false",
+ PYTHONPATH = os.pathsep.join(filter(None, [_REPO, env.get("PYTHONPATH")])),
+ UNSLOTH_COMPILE_LOCATION = str(tmp_path / "ucc"),
+ )
+ out = subprocess.run(
+ [sys.executable, "-c", _PROBE, first],
+ cwd = str(tmp_path),
+ env = env,
+ capture_output = True,
+ text = True,
+ timeout = 900,
+ )
+ assert out.returncode == 0, out.stderr[-4000:]
+ flags = [line for line in out.stdout.splitlines() if line.startswith("CP_FLAGS")]
+ assert flags == ["CP_FLAGS [True, True]"], (out.stdout[-2000:], out.stderr[-2000:])
+ assert "Could not add context parallelism" not in out.stdout + out.stderr
diff --git a/unsloth/context_parallel.py b/unsloth/context_parallel.py
index 3a6e5337f0a..569fefbf5d9 100644
--- a/unsloth/context_parallel.py
+++ b/unsloth/context_parallel.py
@@ -2662,3 +2662,8 @@ def patch_rl_trainer(trainer_cls, kind: str) -> None:
trainer_cls._unsloth_cp_methods = cp_methods
trainer_cls.__init__ = patched_init
trainer_cls.__unsloth_context_parallel__ = True
+
+
+# RL trainers patched while this module was still importing (see models/rl.py).
+for _trainer_cls, _kind in globals().pop("_DEFERRED_RL_TRAINERS", ()):
+ patch_rl_trainer(_trainer_cls, _kind)
diff --git a/unsloth/models/rl.py b/unsloth/models/rl.py
index f46cfacbfd1..c4cd3b1c51d 100644
--- a/unsloth/models/rl.py
+++ b/unsloth/models/rl.py
@@ -4137,8 +4137,16 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):
logger.info(f"Unsloth: Could not wrap GRPO DDP gradient sync for {RLTrainer_name}: {e}")
if trainer_file in ("dpo_trainer", "grpo_trainer"):
try:
- from ..context_parallel import patch_rl_trainer
- patch_rl_trainer(getattr(created_module, f"Unsloth{RLTrainer_name}"), trainer_file)
+ trainer_cls = getattr(created_module, f"Unsloth{RLTrainer_name}")
+ cp_module = sys.modules.get(__name__.rsplit(".", 2)[0] + ".context_parallel")
+ if cp_module is not None and not hasattr(cp_module, "patch_rl_trainer"):
+ # context_parallel is mid-import (its unsloth.utils import loaded us); it patches these at its end.
+ cp_module.__dict__.setdefault("_DEFERRED_RL_TRAINERS", []).append(
+ (trainer_cls, trainer_file)
+ )
+ else:
+ from ..context_parallel import patch_rl_trainer
+ patch_rl_trainer(trainer_cls, trainer_file)
except Exception as e:
logger.warning(f"Unsloth: Could not add context parallelism to {RLTrainer_name}: {e}")
if trainer_file == "ppo_trainer":