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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Bound dataset_num_proc by memory, and stop treating 1 as "no multiprocessing" (#7831)
Daniel Hancd3aef8a70b3
diff --git a/.github/workflows/consolidated-tests-ci.yml b/.github/workflows/consolidated-tests-ci.ymlindex cc9737fb2f0..3dfff06abb3 100644--- a/.github/workflows/consolidated-tests-ci.yml+++ b/.github/workflows/consolidated-tests-ci.yml@@ -363,6 +363,34 @@ jobs:tests/utils/test_prepare_inputs_leftpad.py \tests/utils/test_rope_scaling_drift.py+ - name: dataset_num_proc worker bounds (HARD GATE)+ # Guards for #2693: Dataset.map() dying with "One of the subprocesses+ # has abruptly died", which is the OOM killer reaping tokenizer workers+ # that nothing bounded. These assert the policy that replaced the+ # unbounded cpu_count + 4 -> 64 heuristic -- the memory clamp, the+ # 1 -> None normalisation (datasets >= 4.1 builds a Pool(1)), the+ # non-fork and macOS vetoes, and the UNSLOTH_DATASET_NUM_PROC hatch.+ #+ # Their own step rather than Bucket-A: they need no accelerator and no+ # model, they import the module standalone by path (so they cannot be+ # masked by unrelated import breakage), and their assertions are pinned+ # against simulated CPU counts and memory so the result is identical on+ # a 4-vCPU runner and a 192-core box.+ #+ # The Studio file runs here rather than in studio-backend-ci, which+ # installs studio.txt and so has no unsloth_zoo at all. Note the policy+ # module is not on unsloth_zoo main either until the companion PR lands,+ # and this job clones UNSLOTH_ZOO_REF (main by default) -- so those cases+ # reach the policy through _shared_policy, which falls back to this+ # repo's own copy. Skipping instead would leave the 14 cases that matter+ # green while the wiring they guard was inert.+ run: |+ python -m pytest -v --tb=short \+ tests/utils/test_dataset_num_proc.py \+ tests/utils/test_train_on_responses_only_num_proc.py+ PYTHONPATH=studio/backend python -m pytest -v --tb=short \+ studio/backend/tests/test_dataset_map_num_proc.py+- name: unsloth Bucket-A — CPU tests not in Repo tests (CPU)# CPU tests across 6 files under tests/saving/, tests/utils/, tests/python/# that Repo tests (CPU) --ignores. AST/protobuf/regex plus tiny CPU model@@ -2146,6 +2174,7 @@ jobs:echo "::endgroup::"echo "Consolidated job done. Coverage:"echo " - 17 unsloth Bucket-A tests under tests/saving/ + tests/utils/"+ echo " - 168 dataset_num_proc worker-bound guards (#2693)"echo " - unsloth_zoo @ ${UNSLOTH_ZOO_REF} pytest tests/ (5 GPU cases deselected)"echo " - unsloth_zoo.compiler.test_apply_fused_lm_head"diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex df3b5ed65c3..0a21158074d 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -35,7 +35,6 @@ if sys.platform in ("win32", "darwin"):import torchfrom utils.hardware import (clear_gpu_cache,- safe_num_proc,dataset_map_num_proc,get_device_map,raise_if_offloaded,@@ -3239,10 +3238,20 @@ class UnslothTrainer:"output_dir": output_dir,"report_to": _build_report_targets(training_args),"include_num_input_tokens_seen": True, # Enable token counting+ # serial_as_none = False: this is a config boundary, not a map()+ # call site. The audio paths ask for 1 to keep dataset workers+ # off a process holding audio/CUDA state, and a config `None`+ # reads as "auto-size me" downstream, which turns that request+ # into a full worker set instead.+ # None, not a count, for the ordinary case: the shared policy+ # sizes an auto request from this process's CPU affinity and+ # cgroup quota, while any integer computed here comes from the+ # host's os.cpu_count() and reads as an explicit request that+ # skips that. Studio's own caps still apply to whatever it+ # chooses."dataset_num_proc": dataset_map_num_proc(- 1- if (self.is_audio or self.is_audio_vlm or self._cuda_audio_used)- else max(1, (os.cpu_count() or 1) // 4)+ 1 if (self.is_audio or self.is_audio_vlm or self._cuda_audio_used) else None,+ serial_as_none = False,),"max_seq_length": training_args.get("max_seq_length", 2048),}diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex 169fec81eb3..6eee954f7b0 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -2631,15 +2631,9 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->)return- # ── 1c. Set fork start method so dataset.map() can multiprocess ──- # The compiled SFTTrainer disables num_proc if start method isn't "fork".- # Linux only and safe here (no CUDA context yet); macOS/Windows excluded.- if sys.platform == "linux":- import multiprocessing as _mp- try:- _mp.set_start_method("fork", force = True)- except RuntimeError:- pass # Already set+ # No start-method override: Dataset.map() imports Pool from `multiprocess`,+ # so forcing stdlib multiprocessing onto "fork" never reached it. Linux forks+ # by default, and the guard now asks multiprocess directly.# ── 1c. On Windows, check Triton availability (must be before import torch) ──if sys.platform == "win32":diff --git a/studio/backend/tests/test_dataset_map_num_proc.py b/studio/backend/tests/test_dataset_map_num_proc.pynew file mode 100644index 00000000000..2390a8c880f--- /dev/null+++ b/studio/backend/tests/test_dataset_map_num_proc.py@@ -0,0 +1,637 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Tests for ``dataset_map_num_proc()``.++``None``, not ``1``, is the disable sentinel: on ``datasets`` >= 4.1 (Studio pins+4.3.0) ``map()`` takes the pool branch for any ``num_proc >= 1``, while 3.x runs+``1`` in-process, so that split is asserted per installed release.++There is deliberately no CUDA-initialized guard; see ``dataset_map_num_proc``'s+docstring. The XPU guard is pre-existing and covered so it cannot regress.++The device probes, the platform and torch itself are substituted, so this runs+identically on a GPU box, a CPU-only Linux runner, and the macOS and Windows+legs where the function short-circuits to None.+"""++from __future__ import annotations++import sys+import types++import pytest++import utils.hardware.hardware as hw++try:+ # Import before the fixture below spoofs sys.platform: multiprocess picks its+ # contexts at import time, so a Windows runner would get POSIX fork contexts+ # and the pool would then die reaching for os.WNOHANG.+ import multiprocess # noqa: F401+except ImportError:+ pass++# The real one, read before anything can lie about it.+_HOST_PLATFORM = sys.platform++[email protected](autouse = True)+def _fork_platform(monkeypatch):+ """Pin a platform where workers are possible.++ ``dataset_map_num_proc`` returns None outright on win32 and darwin, so every+ assertion expecting a count is really about Linux. The parametrised platform+ test sets its own value after this, which wins.+ """+ monkeypatch.setattr(sys, "platform", "linux")++[email protected](autouse = True)+def _memory_headroom(monkeypatch):+ """Pin the memory ceiling the shared policy applies.++ Every count these tests assert is bounded by free RAM, so on a small runner+ ``dataset_map_num_proc(4) == 4`` quietly becomes a test of the clamp. The+ cases that are about the clamp pin their own value afterwards, which wins.+ """+ policy = hw._shared_policy()+ if policy is None:+ return+ monkeypatch.setattr(policy, "_affordable_workers", lambda: 64)+++def _require_fork(multiprocess):+ """Skip when this host cannot fork.++ The two tests below build real workers to observe whether ``datasets`` takes+ its pool branch -- a claim about the num_proc guard, not about any start+ method, and under spawn inside pytest the pool fails for unrelated reasons+ (WinError 10038, missing os.WNOHANG).+ """+ if _HOST_PLATFORM == "win32" or "fork" not in multiprocess.get_all_start_methods():+ pytest.skip("needs fork to build a real worker pool")+++def _policy_or_skip():+ """The policy module the production code will actually consult.++ Not `importorskip("unsloth_zoo.dataset_num_proc")`: that module only exists+ in the companion zoo PR, so on CI -- which clones unsloth_zoo main -- every+ case that reached the policy skipped, and the ones that stayed exercised the+ pre-PR path. `_shared_policy` finds this repo's own fallback copy, and+ returning the same object it uses is also what makes monkeypatching it bite.+ """+ policy = hw._shared_policy()+ if policy is None:+ pytest.skip("no dataset_num_proc policy on this installation")+ return policy+++def _patch_device(+ monkeypatch,+ device,+ *,+ visible_gpus: int = 1,+):+ monkeypatch.setattr(hw, "get_device", lambda: device)+ monkeypatch.setattr(hw, "get_visible_gpu_count", lambda: visible_gpus)+++def _torch_module(monkeypatch):+ """The real torch, or a stand-in when the runner has none.++ ``dataset_map_num_proc`` imports torch to read ``<device>.is_initialized()``+ and reads an ImportError as "runtime not touched yet", which on a torch-less+ runner would turn the XPU guard into a no-op.+ """+ try:+ import torch+ return torch+ except ImportError:+ stub = types.ModuleType("torch")+ monkeypatch.setitem(sys.modules, "torch", stub)+ return stub+++def _patch_runtime(monkeypatch, name, *, is_initialized):+ """Install a fake ``torch.<name>`` whose is_initialized() we control.++ ``is_initialized`` may be a bool or a callable that raises, to model a probe+ that fails rather than answering.+ """+ torch = _torch_module(monkeypatch)++ if callable(is_initialized):+ probe = is_initialized+ else:+ probe = lambda: is_initialized # noqa: E731++ monkeypatch.setattr(torch, name, types.SimpleNamespace(is_initialized = probe), raising = False)+++# ---------- CUDA: initialization must NOT disable workers ----------+++def test_dataset_map_num_proc_parallelizes_on_initialized_cuda(monkeypatch):+ """An initialized CUDA context must not disable dataset workers.++ The map child only runs the tokenizer, and 300 forced-fork map() runs on an+ initialized context produced no failures. Since detect_hardware() always+ initializes CUDA, a guard would serialize every CUDA run. Pinned so it is+ not added back without new evidence.+ """+ _patch_device(monkeypatch, hw.DeviceType.CUDA)+ _patch_runtime(monkeypatch, "cuda", is_initialized = True)+ assert hw.dataset_map_num_proc(4) == 4+++def test_dataset_map_num_proc_cuda_respects_multi_gpu_cap(monkeypatch):+ # CUDA still routes through safe_num_proc, which caps to 4 on multi-GPU.+ _patch_device(monkeypatch, hw.DeviceType.CUDA)+ _patch_runtime(monkeypatch, "cuda", is_initialized = True)+ monkeypatch.setattr(hw, "get_visible_gpu_count", lambda: 2)+ assert hw.dataset_map_num_proc(16) == 4+++# ---------- XPU (regression guard: the pre-existing behaviour must not move) ----------+++def test_dataset_map_num_proc_none_after_xpu_init(monkeypatch):+ _patch_device(monkeypatch, hw.DeviceType.XPU)+ _patch_runtime(monkeypatch, "xpu", is_initialized = True)+ assert hw.dataset_map_num_proc(4) is None+++def test_dataset_map_num_proc_parallel_before_xpu_init(monkeypatch):+ _patch_device(monkeypatch, hw.DeviceType.XPU)+ _patch_runtime(monkeypatch, "xpu", is_initialized = False)+ assert hw.dataset_map_num_proc(4) == 4+++# ---------- platform ----------++[email protected]("platform", ["win32", "darwin"])+def test_dataset_map_num_proc_none_on_spawn_platforms(monkeypatch, platform):+ # Must be None and never 1: datasets >= 4.1 builds a Pool(1) for num_proc=1.+ monkeypatch.setattr(sys, "platform", platform)+ assert hw.dataset_map_num_proc(4) is None+++def test_dataset_map_num_proc_cpu_host_parallelizes(monkeypatch):+ # No accelerator to corrupt, so preprocessing may use workers.+ _patch_device(monkeypatch, hw.DeviceType.CPU)+ assert hw.dataset_map_num_proc(4) == 4+++# ---------- the value actually reaches datasets as "no pool" ----------+++def test_none_builds_no_pool_but_a_count_does(monkeypatch):+ """The disable sentinel must actually reach ``datasets`` as "no pool".++ The property the whole module rests on, so assert it against the installed+ ``datasets`` rather than trusting the docstring.+ """+ datasets = pytest.importorskip("datasets")+ multiprocess = pytest.importorskip("multiprocess")+ _require_fork(multiprocess)++ pools_built = []+ real_pool = multiprocess.Pool++ def _spy_pool(*args, **kwargs):+ pools_built.append((args, kwargs))+ return real_pool(*args, **kwargs)++ monkeypatch.setattr(multiprocess, "Pool", _spy_pool)+ monkeypatch.setattr(datasets.arrow_dataset, "Pool", _spy_pool, raising = False)++ dataset = datasets.Dataset.from_dict({"text": [f"row {i}" for i in range(8)]})+ _count = lambda batch: {"n": [len(t) for t in batch["text"]]} # noqa: E731++ mapped = dataset.map(_count, batched = True, num_proc = None)+ assert len(mapped) == 8+ assert pools_built == [], f"Dataset.map built a worker pool: {pools_built}"++ # Control: the spy is live, so the assertion above means something.+ dataset.map(_count, batched = True, num_proc = 2)+ assert len(pools_built) == 1, "Pool spy never fired; the no-pool check is vacuous"+++def test_num_proc_one_is_not_a_disable_sentinel():+ """Pin the reason ``dataset_map_num_proc`` returns ``None`` and never ``1``.++ ``datasets`` 3.x runs ``num_proc=1`` in-process; 4.x (Studio pins 4.3.0)+ builds a ``Pool(1)``. Only ``None`` is in-process on both, so assert per+ installed version rather than hard-coding one.+ """+ datasets = pytest.importorskip("datasets")+ multiprocess = pytest.importorskip("multiprocess")+ _require_fork(multiprocess)+ from packaging.version import Version++ # Counted at the Pool class rather than at datasets.arrow_dataset.Pool:+ # 3.x and 4.x do `from multiprocess import Pool`, but 5.x calls `mp.Pool()`+ # and a spawn context instead, so the module attribute is simply absent+ # there and patching it is an AttributeError. Every one of those routes+ # constructs this class.+ import multiprocess.pool++ pools_built = []+ real_init = multiprocess.pool.Pool.__init__++ def _spy_init(self, *args, **kwargs):+ pools_built.append((args, kwargs))+ return real_init(self, *args, **kwargs)++ dataset = datasets.Dataset.from_dict({"text": [f"row {i}" for i in range(8)]})+ _count = lambda batch: {"n": [len(t) for t in batch["text"]]} # noqa: E731++ multiprocess.pool.Pool.__init__ = _spy_init+ try:+ dataset.map(_count, batched = True, num_proc = None)+ assert pools_built == [], "num_proc=None must always run in-process"++ dataset.map(_count, batched = True, num_proc = 1)+ built_for_one = len(pools_built)+ finally:+ multiprocess.pool.Pool.__init__ = real_init++ if Version(datasets.__version__) >= Version("4.1.0"):+ assert built_for_one == 1, (+ f"datasets {datasets.__version__} was expected to build a Pool(1); "+ "if that changed, dataset_map_num_proc's docstring needs updating"+ )+ else:+ assert built_for_one == 0+++# ---------- the value that reaches Dataset.map is bounded like any other ----------+++def test_a_low_memory_host_gets_no_workers(monkeypatch):+ """format_conversion.py and chat_templates.py call this directly.++ Without the shared policy a 2GB container with eight cores still handed eight+ tokenizer workers to Dataset.map, which is the OOM the policy exists to stop.+ """+ _patch_device(monkeypatch, hw.DeviceType.CPU)+ policy = _policy_or_skip()+ monkeypatch.setattr(policy, "_affordable_workers", lambda: 0)+ monkeypatch.setattr(policy, "multiprocessing_start_method", lambda: "fork")+ assert hw.dataset_map_num_proc(8) is None+++def test_the_memory_clamp_reduces_rather_than_refuses(monkeypatch):+ _patch_device(monkeypatch, hw.DeviceType.CPU)+ policy = _policy_or_skip()+ monkeypatch.setattr(policy, "_affordable_workers", lambda: 3)+ monkeypatch.setattr(policy, "multiprocessing_start_method", lambda: "fork")+ assert hw.dataset_map_num_proc(8) == 3+++def test_the_env_override_reaches_these_callers(monkeypatch):+ # The cap's log line used to advertise this on a path that never read it.+ _patch_device(monkeypatch, hw.DeviceType.CPU)+ policy = _policy_or_skip()+ monkeypatch.setattr(policy, "multiprocessing_start_method", lambda: "fork")+ policy.reset_warning_state()++ monkeypatch.setenv("UNSLOTH_DATASET_NUM_PROC", "2")+ assert hw.dataset_map_num_proc(8) == 2++ monkeypatch.setenv("UNSLOTH_DATASET_NUM_PROC", "0")+ assert hw.dataset_map_num_proc(8) is None+++def test_an_older_unsloth_zoo_keeps_the_previous_behaviour(monkeypatch):+ # The policy is a lazy, guarded import: hardware detection must not start+ # depending on the training package.+ import builtins++ real_import = builtins.__import__++ def _no_policy(name, *args, **kwargs):+ if name == "unsloth_zoo.dataset_num_proc":+ raise ImportError("older unsloth_zoo")+ return real_import(name, *args, **kwargs)++ _patch_device(monkeypatch, hw.DeviceType.CPU)+ monkeypatch.setattr(builtins, "__import__", _no_policy)+ assert hw.dataset_map_num_proc(4) == 4+++def test_the_cap_no_longer_advertises_an_override_it_cannot_honour():+ """safe_num_proc returns an int >= 1, so it cannot express in-process.++ Naming the variable there told users to set something that path never read.+ """+ import ast+ import inspect++ tree = ast.parse(inspect.getsource(hw.safe_num_proc))+ logged = [+ ast.unparse(node)+ for node in ast.walk(tree)+ if isinstance(node, ast.Call) and ast.unparse(node.func).startswith("logger.")+ ]+ assert logged, "the cap stopped logging; re-check what this is guarding"+ assert not any(+ "UNSLOTH_DATASET_NUM_PROC" in line for line in logged+ ), "safe_num_proc tells the user to set an override it never reads"+++# ---------- the config boundary spells "in-process" as 1, not None ----------+#+# trainer.py writes this value into SFTConfig.dataset_num_proc rather than+# handing it to map(). Every downstream reader treats a config None as+# "auto-size me", so a serial request stored as None comes back out as a full+# worker set: dataset_map_num_proc(1) -> None -> SFTConfig -> 8.+++def test_a_serial_request_survives_the_config_round_trip(monkeypatch):+ """The audio paths ask for 1; the config layer must still see a request for 1."""+ # The map-site half of this needs the policy: without it+ # _bounded_by_the_shared_policy returns the count unchanged by design, so a+ # runner with no unsloth_zoo reads 1 rather than None.+ _policy_or_skip()+ _patch_device(monkeypatch, hw.DeviceType.CPU)+ assert hw.dataset_map_num_proc(1, serial_as_none = False) == 1+ # The map-site default is what turns it back into "no pool" at the call.+ assert hw.dataset_map_num_proc(1) is None+++def test_the_config_value_is_still_in_process_after_the_layer_reads_it(monkeypatch):+ """End to end: what Studio stores, read back the way the SFT config layer reads it."""+ policy = _policy_or_skip()+ _patch_device(monkeypatch, hw.DeviceType.CPU)++ stored = hw.dataset_map_num_proc(1, serial_as_none = False)+ # rl.py generates serial_as_none = False for sft_trainer, then the map-site+ # rewrite converts the config value for the actual Dataset.map call.+ from_config = policy.get_dataset_num_proc(stored, serial_as_none = False)+ at_the_map_site = policy.get_dataset_num_proc(from_config)+ assert (stored, from_config, at_the_map_site) == (1, 1, None)+++def test_xpu_initialized_stays_serial_through_a_config(monkeypatch):+ """The one guard where a config None is actively dangerous.++ Unlike the spawn platforms, forking still works here, so an auto-sizer+ reading a config None would fork the corrupted Level-Zero context this+ guard exists to protect.+ """+ _patch_device(monkeypatch, hw.DeviceType.XPU)+ _patch_runtime(monkeypatch, "xpu", is_initialized = True)+ assert hw.dataset_map_num_proc(4, serial_as_none = False) == 1+ assert hw.dataset_map_num_proc(4) is None++[email protected]("platform", ["win32", "darwin"])+def test_spawn_platforms_keep_none_at_either_layer(monkeypatch, platform):+ """None is safe to store here: no reader can inflate it.++ Workers are unusable on a spawn platform, so every auto-sizer vetoes. A 1+ would be worse: only the SFT map site is rewritten, so DPO/KTO/CPO/ORPO and+ friends would hand that 1 to Dataset.map and get a Pool(1) whose child+ re-imports the user's __main__ (#3211 / #3397).+ """+ monkeypatch.setattr(sys, "platform", platform)+ assert hw.dataset_map_num_proc(4, serial_as_none = False) is None+++def test_every_other_caller_keeps_the_map_site_default(monkeypatch):+ """Only the config boundary opts in; the seven map-site callers must not."""+ _policy_or_skip()+ _patch_device(monkeypatch, hw.DeviceType.CPU)+ assert hw.dataset_map_num_proc(1) is None+ assert hw.dataset_map_num_proc(4) == 4+++def test_the_trainer_config_asks_for_the_config_sentinel():+ """The call that builds SFTConfig must pass serial_as_none = False.++ Dropping it is silent: the run still trains, just with a worker set where+ the audio paths asked for none.+ """+ import ast+ from pathlib import Path++ source = (Path(__file__).resolve().parents[1] / "core" / "training" / "trainer.py").read_text(+ encoding = "utf-8"+ )+ tree = ast.parse(source)++ config_calls = [+ value+ for node in ast.walk(tree)+ if isinstance(node, ast.Dict)+ for key, value in zip(node.keys, node.values)+ if isinstance(key, ast.Constant)+ and key.value == "dataset_num_proc"+ and isinstance(value, ast.Call)+ and ast.unparse(value.func) == "dataset_map_num_proc"+ ]+ assert config_calls, "the SFTConfig dataset_num_proc entry moved; re-check this guard"+ for call in config_calls:+ keywords = {kw.arg: ast.unparse(kw.value) for kw in call.keywords}+ assert keywords.get("serial_as_none") == "False", (+ "a config-boundary dataset_map_num_proc call lost serial_as_none = False, "+ "so a serial request will be read back as 'auto-size me': "+ f"{ast.unparse(call)}"+ )+++# ---------- the request reaches the policy as the caller wrote it ----------+++def _unexpected_auto_sizing(desired = None):+ if desired is None:+ raise AssertionError("the auto request was materialized before the policy saw it")+ return desired+++def test_an_auto_request_is_sized_by_the_policy_not_by_the_host_cpu_count(monkeypatch):+ """``safe_num_proc(None)`` reads ``os.cpu_count()``; the policy reads this process.++ Materializing the auto request before the policy saw it hid the affinity+ mask and the cgroup quota, so a 2-core container on a 64-core box asked for+ ``cpu_count // 3`` workers and was bounded only by memory.+ """+ policy = _policy_or_skip()+ _patch_device(monkeypatch, hw.DeviceType.CPU)+ monkeypatch.setattr(policy, "multiprocessing_start_method", lambda: "fork")+ monkeypatch.setattr(policy, "_usable_cpus", lambda: 2)+ monkeypatch.setattr(policy, "_affordable_workers", lambda: 64)+ monkeypatch.setattr(hw, "safe_num_proc", _unexpected_auto_sizing)++ # min(max(2 // 2, 2), cap) = 2, against os.cpu_count() // 3 on the host.+ assert hw.dataset_map_num_proc() == 2+++def test_studio_caps_still_apply_to_a_policy_chosen_count(monkeypatch):+ """The multi-GPU fork-deadlock cap is knowledge the policy does not have."""+ policy = _policy_or_skip()+ _patch_device(monkeypatch, hw.DeviceType.CUDA, visible_gpus = 2)+ monkeypatch.setattr(policy, "multiprocessing_start_method", lambda: "fork")+ monkeypatch.setattr(policy, "_usable_cpus", lambda: 64)+ monkeypatch.setattr(policy, "_affordable_workers", lambda: 64)+ assert hw.dataset_map_num_proc() == 4+++# ---------- the escape hatch ----------++[email protected]("platform", ["win32", "darwin"])+def test_the_override_is_honoured_on_spawn_platforms(monkeypatch, platform):+ """The policy calls it unvetoed, so the platform veto must not swallow it.++ A user who has read the dead-worker message and set this has accepted spawn+ workers; silently ignoring it makes the documented remedy a no-op.+ """+ policy = _policy_or_skip()+ policy.reset_warning_state()+ monkeypatch.setattr(sys, "platform", platform)+ monkeypatch.setenv("UNSLOTH_DATASET_NUM_PROC", "2")+ assert hw.dataset_map_num_proc(8) == 2++ # Unset, the veto stands.+ monkeypatch.delenv("UNSLOTH_DATASET_NUM_PROC")+ assert hw.dataset_map_num_proc(8) is None+++def test_the_override_is_not_capped_by_the_studio_heuristics(monkeypatch):+ """Uncapped by contract, including by the multi-GPU cap Studio adds after."""+ policy = _policy_or_skip()+ policy.reset_warning_state()+ _patch_device(monkeypatch, hw.DeviceType.CUDA, visible_gpus = 4)+ monkeypatch.setenv("UNSLOTH_DATASET_NUM_PROC", "16")+ assert hw.dataset_map_num_proc(2) == 16+++# ---------- the local fallback copy ----------+++def test_an_older_zoo_falls_back_to_the_unsloth_copy(monkeypatch):+ """unsloth.dataset_num_proc is the same policy; Studio should use it too.++ Only when unsloth is already imported: importing it from here would make+ hardware detection patch torch and pull in the model stack.+ """+ import builtins++ calls = []+ stub = types.ModuleType("unsloth.dataset_num_proc")+ stub.NUM_PROC_ENV_VAR = "UNSLOTH_DATASET_NUM_PROC"+ stub.get_dataset_num_proc = lambda desired = None, *, serial_as_none = True: (+ calls.append((desired, serial_as_none)) or 3+ )+ package = types.ModuleType("unsloth")+ package.dataset_num_proc = stub++ monkeypatch.setitem(sys.modules, "unsloth", package)+ monkeypatch.setitem(sys.modules, "unsloth.dataset_num_proc", stub)++ real_import = builtins.__import__++ def _no_zoo_policy(name, *args, **kwargs):+ if name == "unsloth_zoo.dataset_num_proc":+ raise ImportError("older unsloth_zoo")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", _no_zoo_policy)+ _patch_device(monkeypatch, hw.DeviceType.CPU)++ assert hw.dataset_map_num_proc(8) == 3+ assert calls == [(8, True)], calls+++def test_no_policy_anywhere_keeps_the_previous_behaviour(monkeypatch):+ """Neither module importable: the pre-policy Studio count, not a crash."""+ import builtins++ monkeypatch.delitem(sys.modules, "unsloth", raising = False)+ real_import = builtins.__import__++ def _no_policy(name, *args, **kwargs):+ if name.endswith("dataset_num_proc"):+ raise ImportError("no policy here")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", _no_policy)+ _patch_device(monkeypatch, hw.DeviceType.CPU)+ assert hw.dataset_map_num_proc(4) == 4+++def test_the_override_is_honoured_after_xpu_init(monkeypatch):+ """Same contract as the spawn platforms: the hatch is unvetoed.++ The XPU guard exists because fork corrupts the Level-Zero context, but a+ user who has read the dead-worker message and set this has accepted that.+ """+ policy = _policy_or_skip()+ policy.reset_warning_state()+ _patch_device(monkeypatch, hw.DeviceType.XPU)+ _patch_runtime(monkeypatch, "xpu", is_initialized = True)++ monkeypatch.setenv("UNSLOTH_DATASET_NUM_PROC", "2")+ assert hw.dataset_map_num_proc(8) == 2++ # Unset, the veto stands at both layers.+ monkeypatch.delenv("UNSLOTH_DATASET_NUM_PROC")+ assert hw.dataset_map_num_proc(8) is None+ assert hw.dataset_map_num_proc(8, serial_as_none = False) == 1++[email protected]("raw", ["-1", "not-a-number"])+def test_an_ignored_override_does_not_skip_the_studio_caps(monkeypatch, raw):+ """The policy warns and ignores these, so they are not the hatch.++ Treating any non-empty value as an active override let a typo skip the+ multi-GPU fork-deadlock cap while contributing nothing in its place.+ """+ policy = _policy_or_skip()+ policy.reset_warning_state()+ monkeypatch.setattr(policy, "multiprocessing_start_method", lambda: "fork")+ monkeypatch.setattr(policy, "_affordable_workers", lambda: 64)+ _patch_device(monkeypatch, hw.DeviceType.CUDA, visible_gpus = 4)++ monkeypatch.setenv("UNSLOTH_DATASET_NUM_PROC", raw)+ assert hw.dataset_map_num_proc(16) == 4+++def test_the_trainer_leaves_the_ordinary_case_to_the_policy():+ """The non-audio branch must be None, not a host-derived count.++ ``get_dataset_num_proc`` reads any integer as an explicit request and skips+ its own auto path, which is the only one that consults this process's CPU+ affinity and cgroup quota. A count computed from ``os.cpu_count()`` here+ therefore hides the container from the policy.+ """+ import ast+ from pathlib import Path++ source = (Path(__file__).resolve().parents[1] / "core" / "training" / "trainer.py").read_text(+ encoding = "utf-8"+ )++ calls = [+ value+ for node in ast.walk(ast.parse(source))+ if isinstance(node, ast.Dict)+ for key, value in zip(node.keys, node.values)+ if isinstance(key, ast.Constant)+ and key.value == "dataset_num_proc"+ and isinstance(value, ast.Call)+ and ast.unparse(value.func) == "dataset_map_num_proc"+ ]+ assert calls, "the SFTConfig dataset_num_proc entry moved; re-check this guard"+ for call in calls:+ requested = ast.unparse(call.args[0])+ assert "cpu_count" not in requested, (+ "the ordinary case is being sized from the host CPU count before the "+ f"policy can see it: {requested}"+ )+ assert requested.rstrip().endswith("None"), requesteddiff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex d511a0a7fe3..add9708ae54 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -3255,6 +3255,12 @@ def get_torch_device_str() -> str:return "cpu"+# Mirrors AUTO_NUM_PROC_CAP in unsloth_zoo.dataset_num_proc; copied rather than+# imported to keep hardware detection free of the training package. A canary in+# tests/utils/test_dataset_num_proc.py fails if the two drift.+_STUDIO_NUM_PROC_CAP = 8++def safe_num_proc(desired: Optional[int] = None) -> int:"""Return a safe ``num_proc`` for ``dataset.map()`` calls.@@ -3283,6 +3289,22 @@ def safe_num_proc(desired: Optional[int] = None) -> int:if desired is None or not isinstance(desired, int):desired = max(1, (os.cpu_count() or 1) // 3)+ # Every number reaching here is a backend heuristic (cpu_count // 3 above,+ # cpu_count // 4 from trainer.py), but downstream it looks like user intent+ # and is only clamped by free memory, so a 64-core host sends 16 workers to+ # Dataset.map -- the shape of issue #2693, and slower besides (32 workers+ # measured 14.2s against 6.3s in-process, ~1GB each).+ if desired > _STUDIO_NUM_PROC_CAP:+ # No mention of UNSLOTH_DATASET_NUM_PROC here: this function returns an+ # int >= 1 and cannot express the in-process the hatch promises. The+ # hatch is read in dataset_map_num_proc, which is the path whose value+ # reaches Dataset.map.+ logger.info(+ f"num_proc {desired} -> {_STUDIO_NUM_PROC_CAP}: tokenization stops "+ f"scaling well before this and each worker holds its own tokenizer copy."+ )+ desired = _STUDIO_NUM_PROC_CAP+visible = get_visible_gpu_count()if visible > 1:capped = max(1, min(4, desired))@@ -3315,20 +3337,51 @@ def safe_thread_num_proc(desired: Optional[int] = None) -> int:return max(1, desired)-def dataset_map_num_proc(desired: Optional[int] = None) -> Optional[int]:+def dataset_map_num_proc(+ desired: Optional[int] = None, *, serial_as_none: bool = True+) -> Optional[int]:"""Return a safe ``num_proc`` for ``Dataset.map()`` and ``Dataset.filter()``.- Returns ``None`` on spawn platforms (Windows, macOS) because ``datasets``- treats ``num_proc=1`` as multiprocessing (creates ``Pool(1)``); only- ``num_proc=None`` guarantees in-process execution.+ Returns ``None`` on spawn platforms (Windows, macOS). ``None`` -- not ``1``+ -- is the disable sentinel: ``datasets`` >= 4.1 (Studio pins 4.3.0) takes+ the pool branch for any ``num_proc >= 1``, so ``1`` still builds a+ ``Pool(1)``.Also returns ``None`` on XPU once its runtime is initialized in thisprocess: ``os.fork()`` corrupts the Level-Zero context, making Tritonkernels fail with "Pointer argument doesn't reference XPU device memory".Pre-init XPU hosts can still parallelize CPU-side preprocessing.++ There is deliberately no CUDA equivalent: the child only runs the tokenizer,+ and 300 forced-fork map() runs on an initialized CUDA context produced no+ failures. Since ``detect_hardware()`` always initializes CUDA, such a guard+ would serialize every CUDA run for nothing. The worker-count bound in+ ``unsloth_zoo.dataset_num_proc`` is what addresses issue #2693.++ ``serial_as_none`` says how to spell "run in-process" for the layer that+ reads the value back, exactly as in ``unsloth_zoo.dataset_num_proc``. Leave+ it True at a ``map()`` call site, where ``None`` is the only value that+ builds no pool. Pass **False when the result is written into a config**+ (``SFTConfig.dataset_num_proc``): a config ``None`` means "auto-size me" to+ every downstream reader, so a serial request stored as ``None`` comes back+ out as a full worker set. Only ``1`` survives that round trip, and the SFT+ map site turns it back into ``None``."""if sys.platform in ("win32", "darwin"):+ # ``UNSLOTH_DATASET_NUM_PROC`` is an unvetoed escape hatch in the shared+ # policy, so a user who has read the dead-worker message and accepted+ # spawn workers must not be overruled here without a word. Only the+ # hatch can produce a count on this platform; everything else falls+ # through to the veto below.+ if _num_proc_override_is_set():+ return _bounded_by_the_shared_policy(desired, serial_as_none)+ # ``None`` is safe at either layer here: workers are unusable on a spawn+ # platform, so every auto-sizer that reads a config ``None`` vetoes too+ # and nothing can inflate it. A ``1`` would be worse -- only the SFT map+ # site is rewritten, so DPO/KTO/CPO/ORPO/Reward/PRM would hand that 1+ # straight to Dataset.map and get a Pool(1) whose child re-imports the+ # user's __main__ (#3211 / #3397).return Noneif get_device() == DeviceType.XPU:@@ -3336,18 +3389,144 @@ def dataset_map_num_proc(desired: Optional[int] = None) -> Optional[int]:import torchexcept Exception:# No torch means no active XPU runtime, so CPU-side dataset- # parallelism is still safe.- return safe_num_proc(desired)+ # parallelism is still safe -- but it is still bounded, or a+ # torch-less container would be the one path that ignores the+ # memory ceiling and the escape hatch.+ return _bounded_by_the_shared_policy(desired, serial_as_none)xpu = getattr(torch, "xpu", None)is_initialized = getattr(xpu, "is_initialized", None)if callable(is_initialized):try:if is_initialized():- return None+ # Same reading as the spawn branch above: the hatch is+ # unvetoed by contract, so someone who has accepted the+ # risk on XPU is not overruled here without a word.+ if _num_proc_override_is_set():+ return _bounded_by_the_shared_policy(desired, serial_as_none)+ # Unlike the spawn platforms above, forking is still+ # available here, so a config ``None`` WOULD be auto-sized+ # back up and fork the corrupted Level-Zero context this+ # guard exists to protect. Encode serial for the layer.+ return None if serial_as_none else 1except Exception as e:# Treat a failing probe as "runtime not touched yet" so# pre-init CPU preprocessing can still parallelize.logger.debug("torch.xpu.is_initialized() probe failed: %s", e)- return safe_num_proc(desired)+ return _bounded_by_the_shared_policy(desired, serial_as_none)+++# sys.modules key for the copy loaded off disk below. Not "unsloth.dataset_num_proc":+# that name belongs to the package, and claiming it would make a later real import+# of unsloth return this module instead.+_LOCAL_POLICY_MODULE = "unsloth_studio_local_dataset_num_proc"+++def _shared_policy():+ """The shared num_proc policy module, or None on an installation without it.++ The Zoo owns it. ``unsloth.dataset_num_proc`` is a byte-identical fallback+ for a Zoo that predates the module. ``import unsloth.dataset_num_proc``+ would run the package __init__, which patches torch and loads the model+ stack -- unacceptable from inside hardware detection -- so that form is used+ only when the package is already imported. Otherwise the file is loaded+ straight off disk, which is safe because the module is stdlib-only by+ design: the API process reaches format conversion without importing unsloth+ at all, and leaving it with no policy there is what the 2GB container with+ eight cores used to hit.+ """+ try:+ import unsloth_zoo.dataset_num_proc as policy+ return policy+ except Exception:+ pass+ if "unsloth" in sys.modules:+ try:+ import unsloth.dataset_num_proc as policy+ return policy+ except Exception as e:+ logger.debug("local dataset_num_proc fallback unavailable: %s", e)+ return None+ # Memoised through sys.modules: the policy warns once per process about a+ # vetoed count, and re-executing the file on every map() call would reset+ # that and re-read the cgroup tree each time.+ cached = sys.modules.get(_LOCAL_POLICY_MODULE)+ if cached is not None:+ return cached+ try:+ import importlib.util++ # find_spec does not execute a top-level package, so this locates+ # unsloth/ without importing it.+ package = importlib.util.find_spec("unsloth")+ if package is None or not package.submodule_search_locations:+ return None+ path = Path(list(package.submodule_search_locations)[0]) / "dataset_num_proc.py"+ if not path.is_file():+ return None+ spec = importlib.util.spec_from_file_location(_LOCAL_POLICY_MODULE, path)+ policy = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(policy)+ sys.modules[_LOCAL_POLICY_MODULE] = policy+ return policy+ except Exception as e:+ logger.debug("local dataset_num_proc fallback unavailable: %s", e)+ return None+++def _num_proc_override_is_set() -> bool:+ """Whether the escape hatch decided the count, not merely whether it is set.++ The policy ignores an unparseable or negative value with a warning, so+ reading the variable directly would let ``UNSLOTH_DATASET_NUM_PROC=-1``+ skip the multi-GPU cap while contributing nothing.+ """+ policy = _shared_policy()+ if policy is None:+ return False+ parsed = getattr(policy, "environment_override", None)+ if parsed is None:+ # A policy that predates the public reader: presence is the best+ # available answer, and it errs toward honouring the hatch.+ return bool(os.environ.get(policy.NUM_PROC_ENV_VAR, "").strip())+ try:+ was_set, _value = parsed()+ except Exception as e:+ logger.debug("dataset_num_proc override unreadable: %s", e)+ return False+ return bool(was_set)+++def _bounded_by_the_shared_policy(+ desired: Optional[int], serial_as_none: bool = True+) -> Optional[int]:+ """Apply the training-side num_proc policy to a Studio request.++ ``format_conversion.py`` and ``chat_templates.py`` hand this straight to+ ``Dataset.map``, so without it a container with 2GB and eight cores still got+ eight tokenizer workers -- the OOM this policy exists to stop -- and+ ``UNSLOTH_DATASET_NUM_PROC`` did nothing on those paths.++ ``desired`` is passed through as the caller wrote it. Materializing an auto+ request with ``safe_num_proc`` first would hide it from the policy, whose+ auto path reads this process's CPU affinity and cgroup quota while+ ``safe_num_proc`` reads the host's ``os.cpu_count()``: a 2-core container on+ a 64-core box asked for 21 workers and got them bounded only by memory.+ Studio's own caps are then applied to whatever the policy chose, since the+ multi-GPU fork-deadlock cap is knowledge the policy does not have -- except+ over the escape hatch, which is uncapped by contract.+ """+ policy = _shared_policy()+ if policy is None:+ return safe_num_proc(desired) # the behaviour before the shared policy++ try:+ bounded = policy.get_dataset_num_proc(desired, serial_as_none = serial_as_none)+ except Exception as e:+ logger.debug("dataset_num_proc policy unavailable: %s", e)+ return safe_num_proc(desired)++ if isinstance(bounded, int) and bounded > 1 and not _num_proc_override_is_set():+ bounded = safe_num_proc(bounded)+ return boundeddiff --git a/tests/python/test_mlx_public_trainer_api.py b/tests/python/test_mlx_public_trainer_api.pyindex 89f304c76d7..6059e730b2a 100644--- a/tests/python/test_mlx_public_trainer_api.py+++ b/tests/python/test_mlx_public_trainer_api.py@@ -920,7 +920,16 @@ def test_mlx_compatibility_shims_are_installed():assert issubclass(trl.SFTConfig, unsloth.UnslothTrainingArguments)assert trainer_module.UnslothTrainer is unsloth.UnslothTrainerassert trainer_module.UnslothVisionDataCollator is unsloth.UnslothVisionDataCollator- assert chat_templates.train_on_responses_only is dataset_utils.train_on_responses_only+ # chat_templates now wraps the zoo function (issue #2693), so the re-export+ # is no longer the same object; functools.wraps records the original.+ assert (+ getattr(+ chat_templates.train_on_responses_only,+ "__wrapped__",+ chat_templates.train_on_responses_only,+ )+ is dataset_utils.train_on_responses_only+ )assert callable(unsloth.train_on_responses_only)diff --git a/tests/utils/test_dataset_num_proc.py b/tests/utils/test_dataset_num_proc.pynew file mode 100644index 00000000000..fbe407123b9--- /dev/null+++ b/tests/utils/test_dataset_num_proc.py@@ -0,0 +1,1680 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Tests for unsloth.dataset_num_proc, the fallback copy of the policy.++unsloth_zoo.dataset_num_proc owns it; this copy only runs on a zoo that predates+the module, and ``test_the_two_copies_have_not_drifted`` holds them together.++The module is stdlib-only by design and is loaded straight off disk rather than+via ``import unsloth``, so these assertions stay meaningful on a host whose+torch/unsloth_zoo pair cannot import. The ``test_rl_codegen_*`` cases tie it back+to the import path ``unsloth/models/rl.py`` generates, catching a rename.+"""++from __future__ import annotations++import ast+import importlib.util+import re+import sys+import textwrap+import types+from pathlib import Path++import pytest++try:+ # Import before the dnp fixture spoofs sys.platform: multiprocess picks its+ # contexts at import time, so a Windows runner would get POSIX fork contexts.+ import multiprocess # noqa: F401+except ImportError:+ pass+++REPO_ROOT = Path(__file__).resolve().parents[2]+MODULE_PATH = REPO_ROOT / "unsloth" / "dataset_num_proc.py"+RL_PATH = REPO_ROOT / "unsloth" / "models" / "rl.py"++# The dotted paths unsloth/models/rl.py bakes into every generated trainer: the+# zoo first, so generated source does not import back into unsloth, then this+# package as the fallback for a zoo that predates the module.+GENERATED_IMPORT_MODULE = "unsloth_zoo.dataset_num_proc"+GENERATED_FALLBACK_MODULE = "unsloth.dataset_num_proc"+GENERATED_IMPORT_NAME = "get_dataset_num_proc"+++def _load_module():+ spec = importlib.util.spec_from_file_location(+ "unsloth_dataset_num_proc_under_test", MODULE_PATH+ )+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def dnp(monkeypatch):+ module = _load_module()+ module.reset_warning_state()+ monkeypatch.delenv(module.NUM_PROC_ENV_VAR, raising = False)+ # Pin the platform: macOS is refused by policy whatever the start method says,+ # so every assertion expecting a worker count is really about a forking+ # platform. Platform tests set their own value afterwards, which wins.+ monkeypatch.setattr(module.sys, "platform", "linux")+ # Pin the memory ceiling too, at its two sources rather than at the reader,+ # so the memory tests can still patch either and win. Every count this+ # module returns is clamped by free RAM and by the cgroup budget, so on a+ # memory-limited runner a test about the start method or about an explicit+ # value silently becomes a test of the clamp instead:+ # `get_dataset_num_proc(6) == 6` returns 4 in a small container.+ try:+ import psutil+ monkeypatch.setattr(+ psutil, "virtual_memory", lambda: type("m", (), {"available": 1024 * 1024**3})()+ )+ except ImportError:+ pass+ # Point this module's cgroup reader at a path that does not exist rather than+ # stubbing the reader itself, so the tests that are about it can still+ # install a fixture tree and win.+ monkeypatch.setattr(module, "CGROUP_ROOT", "/nonexistent-cgroup-root-for-tests")+ # unsloth_zoo's readers are neutralised by name instead, and without+ # requiring the name to be there: pinning hf_xet_tuning.CGROUP_ROOT alone+ # only works on a zoo that has that global. An older zoo still exposes the+ # private dir helpers this module prefers, monkeypatch finds no attribute to+ # pin, and the policy reads the runner's real cgroup -- which in a+ # memory-limited container turns a test about the start method into a test+ # of the clamp. The tests that are about these readers install their own+ # unsloth_zoo.hf_xet_tuning in sys.modules, so they are unaffected.+ try:+ from unsloth_zoo import hf_xet_tuning+ except Exception:+ # Importing the package can fail long after it has imported this+ # submodule (__init__ pulls in hf_xet_tuning near the top and only+ # raises "Please install Unsloth" at the end), and the failure removes+ # unsloth_zoo from sys.modules while leaving unsloth_zoo.hf_xet_tuning+ # behind. The module under test reaches it through exactly that cache+ # entry, so treating the failure as absence would leave the real readers+ # live on the runner's own /sys/fs/cgroup.+ hf_xet_tuning = sys.modules.get("unsloth_zoo.hf_xet_tuning")+ if hf_xet_tuning is not None:+ for name, neutral in (+ ("CGROUP_ROOT", Path("/nonexistent-cgroup-root-for-tests")),+ ("_cgroup_v2_dirs", lambda: []),+ ("_cgroup_v1_dirs", lambda controller: []),+ ("cgroup_memory_limit", lambda: None),+ ("cgroup_cpu_limit", lambda: None),+ ):+ monkeypatch.setattr(hf_xet_tuning, name, neutral, raising = False)+ return module+++def _force_start_method(monkeypatch, dnp, method):+ monkeypatch.setattr(dnp, "multiprocessing_start_method", lambda: method)+++def _force_cpus(monkeypatch, dnp, count):+ """Pin the CPU count the auto path sizes from.++ Patching psutil alone is not enough: the count is the smallest of the host's+ CPUs, this process's affinity mask and any cgroup quota, so on a 4-vCPU runner+ a "128 CPU host" would still come out as 4.+ """+ monkeypatch.setattr(dnp, "_usable_cpus", lambda: count)+++# ---------- start-method veto ----------++[email protected]("method", ["spawn", "forkserver", None])+def test_non_fork_start_method_disables_multiprocessing(monkeypatch, dnp, method):+ # Under spawn/forkserver the child must re-import the dynamically generated+ # trainer module, which has no importable name, so workers cannot run.+ _force_start_method(monkeypatch, dnp, method)+ assert dnp.get_dataset_num_proc(8) is None+ assert dnp.get_dataset_num_proc(None) is None+++def test_non_fork_start_method_warns_once(monkeypatch, dnp, capsys):+ # Regression for eeffa4c065: an explicit value used to sail through the+ # guard. It must be vetoed, and the veto must be visible.+ _force_start_method(monkeypatch, dnp, "spawn")+ dnp.get_dataset_num_proc(8)+ dnp.get_dataset_num_proc(8)+ out = capsys.readouterr().out+ assert out.count("uses the 'spawn' start method") == 1+ assert "dataset_num_proc = 8" in out+++def test_fork_start_method_honours_explicit_value(monkeypatch, dnp):+ _force_start_method(monkeypatch, dnp, "fork")+ assert dnp.get_dataset_num_proc(6) == 6+++# ---------- the 1 -> None normalisation ----------++[email protected]("value", [1, 0, -4])+def test_non_positive_and_one_normalise_to_none(monkeypatch, dnp, value):+ # `1` is a trap: callers mean "serial", datasets >= 4.0 gives a Pool(1).+ _force_start_method(monkeypatch, dnp, "fork")+ assert dnp.get_dataset_num_proc(value) is None+++def test_serial_as_none_false_preserves_an_explicit_one(monkeypatch, dnp):+ """The config layer must not collapse 1 to None.++ unsloth_zoo.sft_prepare_dataset reads a config ``None`` as "auto-size me",+ so writing None back for a user who asked for 1 would inflate it.+ """+ _force_start_method(monkeypatch, dnp, "fork")+ assert dnp.get_dataset_num_proc(1, serial_as_none = False) == 1+ # 0 and negatives are incoherent requests but still mean "not parallel", so+ # they land on the config serial sentinel (1), not on None.+ assert dnp.get_dataset_num_proc(0, serial_as_none = False) == 1+ assert dnp.get_dataset_num_proc(-4, serial_as_none = False) == 1+++def test_config_layer_never_returns_none_while_forking_is_available(monkeypatch, dnp):+ """On a fork host no path may write None back to a config.++ None means "auto-size me" downstream, so any route to it -- memory clamp,+ explicit serial -- would re-inflate.+ """+ psutil = pytest.importorskip("psutil")+ _force_cpus(monkeypatch, dnp, 64)++ # memory clamp all the way down to serial+ _force_start_method(monkeypatch, dnp, "fork")+ monkeypatch.setattr(+ psutil, "virtual_memory", lambda: type("m", (), {"available": 1 * 1024**3})()+ )+ assert dnp.get_dataset_num_proc(16, serial_as_none = False) == 1+ assert dnp.get_dataset_num_proc(None, serial_as_none = False) == 1++[email protected]("method", ["spawn", "forkserver", None])[email protected]("desired", [None, 1, 16])+def test_config_layer_is_none_not_one_on_a_non_fork_start_method(monkeypatch, dnp, method, desired):+ """Regression: the config sentinel 1 reached unpatched TRL map() call sites.++ Only SFT gets its map site rewritten (rl_replacements.py); DPO, KTO, CPO,+ ORPO, Reward and PRM pass ``args.dataset_num_proc`` straight into+ ``Dataset.map``, where a ``1`` builds a ``Pool(1)`` whose spawned child+ re-imports the user's ``__main__`` (#3211 / #3397). None is safe here+ precisely because forking is unavailable, so every auto-sizer vetoes too.+ """+ _force_start_method(monkeypatch, dnp, method)+ assert dnp.get_dataset_num_proc(desired, serial_as_none = False) is None+++def test_config_layer_env_forced_serial_is_none_on_a_non_fork_start_method(monkeypatch, dnp):+ """UNSLOTH_DATASET_NUM_PROC=0 must not build a Pool(1) either."""+ _force_start_method(monkeypatch, dnp, "spawn")+ monkeypatch.setenv(dnp.NUM_PROC_ENV_VAR, "0")+ assert dnp.get_dataset_num_proc(None, serial_as_none = False) is None+++def test_layering_config_then_map_site_is_correct(monkeypatch, dnp):+ """Composing the two layers must land on the right value for each intent."""+ _force_start_method(monkeypatch, dnp, "fork")+ psutil = pytest.importorskip("psutil")+ _force_cpus(monkeypatch, dnp, 32)+ monkeypatch.setattr(+ psutil,+ "virtual_memory",+ lambda: type("m", (), {"available": 256 * 1024**3})(),+ )+ cfg = lambda v: dnp.get_dataset_num_proc(v, serial_as_none = False) # noqa: E731+ site = dnp.get_dataset_num_proc++ # user asked for serial -> stays serial, never auto-inflated+ assert site(cfg(1)) is None+ # user asked for a specific count -> honoured end to end+ assert site(cfg(6)) == 6+ # user asked for nothing -> capped auto, and re-applying is idempotent+ assert cfg(None) == dnp.AUTO_NUM_PROC_CAP+ assert site(cfg(None)) == dnp.AUTO_NUM_PROC_CAP+++def test_low_memory_auto_path_returns_none_not_one(monkeypatch, dnp):+ # The old heuristic returned 1 here, which still forked a Pool(1).+ _force_start_method(monkeypatch, dnp, "fork")+ psutil = pytest.importorskip("psutil")+ _force_cpus(monkeypatch, dnp, 32)+ monkeypatch.setattr(+ psutil,+ "virtual_memory",+ lambda: type("m", (), {"available": 1 * 1024**3})(),+ )+ assert dnp.get_dataset_num_proc(None) is None+++# ---------- auto sizing ----------+++def test_auto_value_is_capped(monkeypatch, dnp):+ # Was min(max(cpu_count + 4, 2), 64) -- up to 64 forked workers.+ _force_start_method(monkeypatch, dnp, "fork")+ psutil = pytest.importorskip("psutil")+ _force_cpus(monkeypatch, dnp, 128)+ monkeypatch.setattr(+ psutil,+ "virtual_memory",+ lambda: type("m", (), {"available": 512 * 1024**3})(),+ )+ assert dnp.get_dataset_num_proc(None) == dnp.AUTO_NUM_PROC_CAP+ assert dnp.AUTO_NUM_PROC_CAP < 64+++def test_auto_value_clamped_by_available_memory(monkeypatch, dnp):+ _force_start_method(monkeypatch, dnp, "fork")+ psutil = pytest.importorskip("psutil")+ _force_cpus(monkeypatch, dnp, 64)+ monkeypatch.setattr(+ psutil,+ "virtual_memory",+ lambda: type("m", (), {"available": 10 * 1024**3})(),+ )+ # 10 GB free, half of it budgeted, ~1 GB per worker -> 5.+ assert dnp.get_dataset_num_proc(None) == 5+++def test_explicit_value_is_clamped_by_memory(monkeypatch, dnp, capsys):+ """The gap that caused issue #2693.++ Studio passes an explicit ``max(1, cpu_count // 4)``, dozens of workers at+ ~680 MB each on a big-core machine, and the old heuristic bounded only the+ auto path, so that sailed through however little RAM there was.+ """+ _force_start_method(monkeypatch, dnp, "fork")+ psutil = pytest.importorskip("psutil")+ monkeypatch.setattr(+ psutil,+ "virtual_memory",+ lambda: type("m", (), {"available": 16 * 1024**3})(),+ )+ assert dnp.get_dataset_num_proc(48) == 8+ assert "reducing dataset_num_proc 48 -> 8" in capsys.readouterr().out+++def test_explicit_value_is_not_capped_by_the_auto_cap(monkeypatch, dnp):+ # AUTO_NUM_PROC_CAP bounds auto-sizing only.+ _force_start_method(monkeypatch, dnp, "fork")+ psutil = pytest.importorskip("psutil")+ monkeypatch.setattr(+ psutil,+ "virtual_memory",+ lambda: type("m", (), {"available": 512 * 1024**3})(),+ )+ assert dnp.get_dataset_num_proc(32) == 32+ assert 32 > dnp.AUTO_NUM_PROC_CAP+++def test_memory_clamp_is_skipped_without_psutil(monkeypatch, dnp):+ # No psutil means no memory reading, so honour the request.+ monkeypatch.setattr(dnp, "_affordable_workers", lambda: None)+ _force_start_method(monkeypatch, dnp, "fork")+ assert dnp.get_dataset_num_proc(32) == 32+++def test_bool_is_not_treated_as_an_int(monkeypatch, dnp):+ _force_start_method(monkeypatch, dnp, "fork")+ psutil = pytest.importorskip("psutil")+ _force_cpus(monkeypatch, dnp, 8)+ monkeypatch.setattr(+ psutil,+ "virtual_memory",+ lambda: type("m", (), {"available": 64 * 1024**3})(),+ )+ assert dnp.get_dataset_num_proc(True) == 4+++# ---------- environment escape hatch ----------+++def test_env_override_beats_start_method_veto(monkeypatch, dnp):+ # A user who knows their workload is fork-safe is never downgraded.+ _force_start_method(monkeypatch, dnp, "spawn")+ monkeypatch.setenv(dnp.NUM_PROC_ENV_VAR, "24")+ assert dnp.get_dataset_num_proc(None) == 24++[email protected]("raw", ["0", "none", "None", "false", ""])+def test_env_override_can_force_in_process(monkeypatch, dnp, raw):+ _force_start_method(monkeypatch, dnp, "fork")+ monkeypatch.setenv(dnp.NUM_PROC_ENV_VAR, raw)+ assert dnp.get_dataset_num_proc(16) is None++[email protected]("raw", ["0", "none", "None", "false", "", "1"])+def test_env_override_in_process_is_encoded_for_the_config_layer(monkeypatch, dnp, raw):+ # Regression: the env override used to return before _serial(), writing None+ # into the *config*, which unsloth_zoo.sft_prepare_dataset reads as+ # "auto-size me" -- so the hatch the dead-worker message recommends raised+ # the worker count instead of removing it. Config serial is 1, never None.+ _force_start_method(monkeypatch, dnp, "fork")+ monkeypatch.setenv(dnp.NUM_PROC_ENV_VAR, raw)+ assert dnp.get_dataset_num_proc(16, serial_as_none = False) == 1+++def test_env_override_is_uncapped(monkeypatch, dnp):+ _force_start_method(monkeypatch, dnp, "fork")+ monkeypatch.setenv(dnp.NUM_PROC_ENV_VAR, "100")+ assert dnp.get_dataset_num_proc(None) == 100+ # Above the auto cap is the easy half. The memory clamp is the one that+ # matters: the fixture leaves room for 512 workers, so without pinning it+ # this asserts nothing about the exemption. map_failure_diagnostics points+ # users at this hatch on exactly the host where the clamp would bite.+ monkeypatch.setattr(dnp, "_affordable_workers", lambda: 2)+ assert dnp.get_dataset_num_proc(None) == 100+ assert dnp.get_dataset_num_proc(4) == 100+++def test_invalid_env_override_is_ignored_with_a_warning(monkeypatch, dnp, capsys):+ _force_start_method(monkeypatch, dnp, "fork")+ monkeypatch.setenv(dnp.NUM_PROC_ENV_VAR, "banana")+ assert dnp.get_dataset_num_proc(4) == 4+ assert "is not an integer" in capsys.readouterr().out+++# ---------- start-method probing must not mutate global state ----------+++def test_start_method_probe_prefers_multiprocess_and_has_no_side_effects(dnp):+ """datasets does `from multiprocess import Pool`, so `multiprocess` -- not+ stdlib multiprocessing -- decides how map() spawns. Reading it must also not+ pin the context, which would make a later set_start_method() raise."""+ multiprocess = pytest.importorskip("multiprocess")+ import multiprocessing++ before_mp = multiprocess.get_start_method(allow_none = True)+ before_std = multiprocessing.get_start_method(allow_none = True)++ method = dnp.multiprocessing_start_method()++ # Must name a method this host offers. The private default-context chain has+ # answered "fork" on Windows, which offers only spawn; believing it would+ # read Windows as forkable and let workers through.+ assert method in multiprocess.get_all_start_methods()+ assert multiprocess.get_start_method(allow_none = True) == before_mp+ assert multiprocessing.get_start_method(allow_none = True) == before_std+++def test_start_method_probe_reports_an_explicit_setting(monkeypatch, dnp):+ import sys as _sys+ import types++ fake = types.ModuleType("multiprocess")+ fake.get_start_method = lambda allow_none = False: "forkserver"+ fake.get_all_start_methods = lambda: ["fork", "spawn", "forkserver"]+ monkeypatch.setitem(_sys.modules, "multiprocess", fake)+ assert dnp.multiprocessing_start_method() == "forkserver"+++def _fake_multiprocess(listed, default_name):+ """A multiprocess stand-in with nothing pinned yet."""+ import types++ fake = types.ModuleType("multiprocess")+ fake.get_start_method = lambda allow_none = False: None+ fake.get_all_start_methods = lambda: list(listed)+ if default_name is not None:+ context = types.ModuleType("multiprocess.context")+ context._default_context = types.SimpleNamespace(+ _default_context = types.SimpleNamespace(_name = default_name),+ _actual_context = None,+ )+ fake.context = context+ return fake+++def test_start_method_probe_prefers_the_real_default_over_list_order(monkeypatch, dnp):+ """macOS: multiprocess lists 'spawn' first but its default context is fork.++ It copies stdlib ``get_all_start_methods()`` verbatim, darwin branch+ included, while keeping ``fork`` as its ``_default_context`` on every POSIX+ platform (``#FIXME: spawn`` in multiprocess/context.py). Since ``datasets``+ pools come from ``multiprocess``, trusting the list would veto every worker+ and misreport the start method in the dead-worker diagnostics.+ """+ import sys as _sys++ darwin_order = ["spawn", "fork", "forkserver"]+ fake = _fake_multiprocess(darwin_order, "fork")+ monkeypatch.setitem(_sys.modules, "multiprocess", fake)+ assert dnp.multiprocessing_start_method() == "fork"+++def test_macos_stays_in_process_even_though_multiprocess_forks(monkeypatch, dnp, capsys):+ """The probe reports fork on macOS; policy still refuses to use it.++ ``multiprocess`` really does fork on darwin, so the diagnostics must say so,+ but CPython moved the macOS default to spawn in 3.8 (bpo-33725) because+ forking there "can lead to crashes of the subprocess as macOS system+ libraries may start threads" -- and this parent holds Torch and a threaded+ BLAS. Fixing the probe without the guard would take macOS from always-serial+ to AUTO_NUM_PROC_CAP forked workers.+ """+ _force_start_method(monkeypatch, dnp, "fork")+ # Pin memory so the contrast is about policy, not the runner's free RAM.+ monkeypatch.setattr(dnp, "_affordable_workers", lambda: 1000)+ monkeypatch.setattr(dnp.sys, "platform", "darwin")++ # Serial at a map() call site, None -- not 1 -- at the config layer, so no+ # Pool is built on datasets >= 4.1 either way.+ assert dnp.get_dataset_num_proc(8) is None+ assert dnp.get_dataset_num_proc(8, serial_as_none = False) is None+ assert dnp.get_dataset_num_proc(None) is None+ assert "macOS" in capsys.readouterr().out++ # The escape hatch still overrides it, and Linux is unaffected.+ monkeypatch.setenv(dnp.NUM_PROC_ENV_VAR, "4")+ assert dnp.get_dataset_num_proc(8) == 4+ monkeypatch.delenv(dnp.NUM_PROC_ENV_VAR)+ monkeypatch.setattr(dnp.sys, "platform", "linux")+ assert dnp.get_dataset_num_proc(8) == 8+++def test_start_method_probe_falls_back_to_list_order(monkeypatch, dnp):+ """The default context is private, so an unreadable one must not raise."""+ import sys as _sys++ fake = _fake_multiprocess(["spawn", "fork"], None)+ monkeypatch.setitem(_sys.modules, "multiprocess", fake)+ assert dnp.multiprocessing_start_method() == "spawn"+++def test_start_method_probe_matches_the_pool_multiprocess_would_build(dnp):+ """The probe must agree with multiprocess's own default on this host."""+ multiprocess = pytest.importorskip("multiprocess")+ if multiprocess.get_start_method(allow_none = True) is not None:+ pytest.skip("a start method is already pinned in this process")+ assert (+ dnp.multiprocessing_start_method()+ == multiprocess.context._default_context._default_context._name+ )+++# ---------- the generated trainer's import must match the real module ----------+++def _rl_serial_as_none(tree, source, trainer_file):+ """Evaluate rl.py's own serial_as_none rule rather than restating it.++ Restating it made every codegen case below self-fulfilling: they passed+ whatever rl.py decided, so flipping SFT to True -- losing the config+ sentinel these modules exist to protect -- was caught only by the one test+ that matches the emitted literal, which is the line a developer would edit+ in the same change.+ """+ for node in ast.walk(tree):+ if isinstance(node, ast.Assign) and getattr(node.targets[0], "id", "") == "_serial_as_none":+ # Parenthesised for the same reason as the sibling below: a+ # formatter may reflow the ternary, and the segment's continuation+ # lines are an IndentationError on their own.+ return eval( # noqa: S307+ "(" + ast.get_source_segment(source, node.value) + ")",+ {"trainer_file": trainer_file},+ )+ raise AssertionError("_serial_as_none assignment not found in unsloth/models/rl.py")+++def _rl_num_proc_snippet(trainer_file = "sft_trainer"):+ """The snippet rl.py would splice into that trainer's generated config.++ The expression is evaluated rather than literal_eval'd because it is no+ longer one literal: the serial encoding depends on the trainer being+ patched, and the point of these tests is what each one ends up with.+ """+ source = RL_PATH.read_text(encoding = "utf-8")+ tree = ast.parse(source)+ for node in ast.walk(tree):+ if isinstance(node, ast.Assign) and getattr(node.targets[0], "id", "") == "num_proc_check":+ # Parenthesised: the segment starts at the first literal, so its+ # continuation lines are an IndentationError on their own.+ expression = "(" + ast.get_source_segment(source, node.value) + ")"+ return eval( # noqa: S307+ expression, {"_serial_as_none": _rl_serial_as_none(tree, source, trainer_file)}+ )+ raise AssertionError("num_proc_check literal not found in unsloth/models/rl.py")+++def test_rl_codegen_writes_back_without_collapsing_serial():+ # SFT's config is read by an auto-sizer, so serial has to survive as 1.+ assert "serial_as_none = False" in _rl_num_proc_snippet("sft_trainer")+++ "trainer_file",+ ["dpo_trainer", "kto_trainer", "cpo_trainer", "orpo_trainer", "reward_trainer", "prm_trainer"],+)+def test_rl_codegen_keeps_serial_as_none_where_the_config_reaches_map(trainer_file):+ """Only SFT has a downstream auto-sizer to defend the sentinel against.++ These trainers hand args.dataset_num_proc straight to Dataset.map, so a+ config `1` is a Pool(1) on datasets >= 4.1 -- one worker holding its own+ tokenizer copy, on the low-memory host that just refused workers. Nothing+ inflates a None there, so None is what serial must be.+ """+ assert "serial_as_none = True" in _rl_num_proc_snippet(trainer_file)+++def test_rl_codegen_only_sft_gets_the_config_sentinel():+ # Pin the discriminator itself: a rename of the trainer file would silently+ # give every trainer the None encoding, including the one that must not have it.+ source = RL_PATH.read_text(encoding = "utf-8")+ assert '_serial_as_none = "False" if trainer_file == "sft_trainer" else "True"' in source+++# ---------- the map-site rewrite and the anchors it hangs on ----------++# The tag rl_replacements.py gives the num_proc edit; both anchors share it, so a+# rename shows up as a missing call rather than a silently unpinned anchor.+NUM_PROC_WHERE = "sft_prepare_dataset dataset_num_proc selection"++# The helpers that decide whether a source edit lands. Named here so the tests+# below fail loudly if they are renamed rather than quietly testing nothing.+ANCHOR_HELPERS = ("_require_replace", "_replace_or_fallback")++# The module-level regex the narrow fallback anchor uses.+NARROW_ANCHOR_NAME = "_ZOO_MAP_NUM_PROC_ASSIGNMENT"+++def _zoo_dataset_utils_source():+ # find_spec resolves the package path without executing its __init__, so these+ # canaries still run where torch/unsloth_zoo cannot import.+ spec = importlib.util.find_spec("unsloth_zoo")+ if spec is None or not spec.submodule_search_locations:+ pytest.skip("unsloth_zoo not installed")+ zoo_file = Path(list(spec.submodule_search_locations)[0]) / "dataset_utils.py"+ if not zoo_file.is_file():+ pytest.skip("unsloth_zoo.dataset_utils not found")+ return zoo_file.read_text(encoding = "utf-8")+++def _rl_replacements_tree():+ return ast.parse(RL_PATH.with_name("rl_replacements.py").read_text(encoding = "utf-8"))+++def _anchor_calls(where):+ return [+ node+ for node in ast.walk(_rl_replacements_tree())+ if isinstance(node, ast.Call)+ and getattr(node.func, "id", "") in ANCHOR_HELPERS+ and any(k.arg == "where" and ast.literal_eval(k.value) == where for k in node.keywords)+ ]+++def _anchor_and_count(where):+ """The (anchor, expected occurrences) of the source edit tagged ``where``."""+ found = _anchor_calls(where)+ assert len(found) == 1, f"expected exactly one anchored edit for {where!r}"+ node = found[0]+ count = next((ast.literal_eval(k.value) for k in node.keywords if k.arg == "count"), 1)+ return ast.literal_eval(node.args[1]), count+++def _keyword(where, name):+ node = _anchor_calls(where)[0]+ value = next(k.value for k in node.keywords if k.arg == name)+ return value+++def _narrow_num_proc_pattern():+ """The compiled fallback regex, read out of rl_replacements.py by name.++ Read from the module-level ``re.compile`` rather than re-typed here: a test+ holding its own copy of the pattern would keep passing after the real one+ drifted away from the Zoo.+ """+ name = _keyword(NUM_PROC_WHERE, "fallback_pattern")+ assert (+ getattr(name, "id", "") == NARROW_ANCHOR_NAME+ ), f"the num_proc fallback no longer uses {NARROW_ANCHOR_NAME}"+ for node in ast.walk(_rl_replacements_tree()):+ if (+ isinstance(node, ast.Assign)+ and any(getattr(t, "id", None) == NARROW_ANCHOR_NAME for t in node.targets)+ and isinstance(node.value, ast.Call)+ ):+ args = [ast.literal_eval(a) for a in node.value.args]+ flags = next((k for k in node.value.keywords if k.arg == "flags"), None)+ assert flags is not None and "MULTILINE" in ast.dump(+ flags.value+ ), "the narrow anchor must be MULTILINE to match a line in a block"+ return re.compile(args[0], flags = re.MULTILINE)+ raise AssertionError(f"{NARROW_ANCHOR_NAME} not found in rl_replacements.py")+++def _narrow_num_proc_replacement():+ return ast.literal_eval(_keyword(NUM_PROC_WHERE, "fallback_new"))+++def test_zoo_sft_prepare_dataset_anchor_has_not_drifted():+ """unsloth/models/rl_replacements.py rewrites unsloth_zoo's+ sft_prepare_dataset by exact string match. A Zoo release that touches those+ lines makes _require_replace raise at import time, so catch drift here."""+ source = _zoo_dataset_utils_source()++ # _require_replace raises on a missing anchor but cannot notice a count = 2+ # anchor dropping to one occurrence, so assert the counts here.+ for where in (+ NUM_PROC_WHERE,+ "sft_prepare_dataset tokenizing map() calls",+ ):+ anchor, count = _anchor_and_count(where)+ assert source.count(anchor) == count, (+ f"unsloth_zoo.dataset_utils has {source.count(anchor)} occurrences of "+ f"the {where!r} anchor, expected {count}; update rl_replacements.py"+ )+++def test_the_narrow_num_proc_anchor_still_matches_the_installed_zoo():+ """The num_proc site has a second, narrower anchor; it needs its own canary.++ The block anchor drifting is survivable precisely because this regex catches+ the assignment the block ends on. If the Zoo ever renames or restructures+ that line too, both anchors are gone and nothing rewrites the worker count --+ so pin it here, in CI, rather than discovering it from a user's Pool(1).+ """+ source = _zoo_dataset_utils_source()+ pattern = _narrow_num_proc_pattern()++ matches = pattern.findall(source)+ assert len(matches) == 1, (+ f"unsloth_zoo.dataset_utils has {len(matches)} lines matching the narrow "+ f"num_proc anchor {pattern.pattern!r}, expected 1; update rl_replacements.py"+ )++ # The block anchor and the narrow anchor have to describe the same site, or+ # the fallback would rewrite something the primary edit never touched.+ block_anchor, _ = _anchor_and_count(NUM_PROC_WHERE)+ assert pattern.search(block_anchor) is not None++ # And the fallback has to leave the file parseable at the Zoo's indentation.+ rewritten = pattern.sub(_narrow_num_proc_replacement(), source)+ assert rewritten != source+ ast.parse(rewritten)+++# ---------- what the layered anchor actually does to a drifted Zoo ----------+++def _load_anchor_helpers():+ """Exec just the anchor helpers out of rl_replacements.py.++ That module imports torch and trl at its top and this file is torch-free by+ design, so lift the definitions the anchor logic needs instead of copying+ them: a test carrying its own copy would keep passing after the real helper+ changed. Returns the namespace plus the list the fake logger warns into.+ """+ tree = _rl_replacements_tree()+ wanted = set(ANCHOR_HELPERS) | {"_warn_once", "_WARNED_MISSING_ANCHORS", NARROW_ANCHOR_NAME}+ kept = [+ node+ for node in tree.body+ if (isinstance(node, ast.FunctionDef) and node.name in wanted)+ or (+ isinstance(node, ast.Assign)+ and any(getattr(t, "id", None) in wanted for t in node.targets)+ )+ ]+ assert {node.name for node in kept if isinstance(node, ast.FunctionDef)} >= set(+ ANCHOR_HELPERS+ ), "the anchor helpers were renamed"++ warnings = []+ namespace = {+ "re": re,+ "logger": types.SimpleNamespace(warning = warnings.append),+ }+ module = ast.fix_missing_locations(ast.Module(body = kept, type_ignores = []))+ exec(compile(module, str(RL_PATH.with_name("rl_replacements.py")), "exec"), namespace) # noqa: S102+ return namespace, warnings+++def _apply_num_proc_edit(source):+ """Run the real layered edit for NUM_PROC_WHERE over ``source``."""+ namespace, warnings = _load_anchor_helpers()+ node = _anchor_calls(NUM_PROC_WHERE)[0]+ assert (+ getattr(node.func, "id", "") == "_replace_or_fallback"+ ), "the num_proc edit lost its fallback and is a plain replace again"+ result = namespace["_replace_or_fallback"](+ source,+ ast.literal_eval(node.args[1]),+ ast.literal_eval(node.args[2]),+ fallback_pattern = namespace[NARROW_ANCHOR_NAME],+ fallback_new = _narrow_num_proc_replacement(),+ where = NUM_PROC_WHERE,+ )+ return result, warnings+++def test_the_block_anchor_is_used_when_the_zoo_has_not_moved():+ source = _zoo_dataset_utils_source()+ result, warnings = _apply_num_proc_edit(source)+ assert "_unsloth_get_dataset_num_proc" in result+ assert 'map_kwargs["num_proc"] = dataset_num_proc' not in result+ # The block replacement takes the Zoo's own sizing with it; the fallback,+ # which only rewrites the assignment, leaves it standing.+ block_anchor, _ = _anchor_and_count(NUM_PROC_WHERE)+ assert block_anchor not in result+ assert warnings == [], f"a matching anchor must not warn: {warnings}"+ ast.parse(result)+++def test_the_narrow_anchor_takes_over_when_the_block_drifts():+ """A Zoo that rewrites the block but keeps the assignment must still be fixed.++ This is the case `required = False` used to swallow: the edit no-ops, the Zoo+ reads the config `1` the config layer writes for "serial", and datasets >= 4.1+ turns that into a Pool(1) on the host that asked for no workers.+ """+ source = _zoo_dataset_utils_source()+ # Drift the block without touching the line the fallback keys on.+ drifted = source.replace(+ " import multiprocessing as _mp\n",+ " import multiprocessing as _mp # zoo refactor\n",+ 1,+ )+ assert drifted != source+ assert _narrow_num_proc_pattern().findall(drifted)++ result, warnings = _apply_num_proc_edit(drifted)+ assert "_unsloth_get_dataset_num_proc" in result, "the fallback anchor did not apply"+ assert 'map_kwargs["num_proc"] = dataset_num_proc' not in result+ # Only the assignment was rewritten, so the Zoo's own sizing is still there,+ # computing a value nothing reads. That is the price of the narrow anchor.+ assert "if _mp.get_start_method() != 'fork':" in result+ assert len(warnings) == 1 and "moved in this unsloth_zoo" in warnings[0]+ ast.parse(result)+++def test_neither_anchor_matching_only_warns():+ """The remaining escape hatch stays a warning, not a raise.++ Hard-failing here would break every SFT run on a Zoo whose text merely moved,+ which is a far bigger blast radius than the one worker at stake.+ """+ source = (+ _zoo_dataset_utils_source()+ .replace(+ ' map_kwargs["num_proc"] = dataset_num_proc\n',+ ' map_kwargs.update({"num_proc": dataset_num_proc})\n',+ 1,+ )+ .replace(+ " import multiprocessing as _mp\n",+ " import multiprocessing as _mp # zoo refactor\n",+ 1,+ )+ )+ assert not _narrow_num_proc_pattern().findall(source)++ result, warnings = _apply_num_proc_edit(source)+ assert result == source, "nothing should be rewritten when both anchors miss"+ assert len(warnings) == 1 and "anchor not found" in warnings[0]+++def test_the_narrow_anchor_keeps_indentation_and_yields_none(monkeypatch):+ """The injected fallback has to run, at the Zoo's indentation, and give None.++ Indentation comes from the match, so a Zoo that nests the assignment deeper+ still gets valid source; and the value it computes for a config `1` -- what+ the config layer writes for "serial" -- has to be None, never 1.+ """+ module = _load_module()+ module.reset_warning_state()+ monkeypatch.delenv(module.NUM_PROC_ENV_VAR, raising = False)+ # The injected snippet imports the zoo copy first; point that name at the+ # copy under test so this stays a torch-free, offline assertion.+ if "unsloth_zoo" not in sys.modules:+ monkeypatch.setitem(sys.modules, "unsloth_zoo", types.ModuleType("unsloth_zoo"))+ monkeypatch.setitem(sys.modules, "unsloth_zoo.dataset_num_proc", module)++ pattern = _narrow_num_proc_pattern()+ replacement = _narrow_num_proc_replacement()++ for indent in (" ", " "):+ snippet = pattern.sub(replacement, f'{indent}map_kwargs["num_proc"] = dataset_num_proc')+ for line in snippet.split("\n"):+ assert line.startswith(indent), f"lost the {len(indent)}-space indent: {line!r}"++ namespace = {+ "map_kwargs": {},+ "args": types.SimpleNamespace(dataset_num_proc = 1),+ }+ exec(compile(textwrap.dedent(snippet), "<fallback>", "exec"), namespace) # noqa: S102+ assert (+ namespace["map_kwargs"]["num_proc"] is None+ ), "a config 1 has to become None at the map site; 1 is a Pool(1) on datasets >= 4.1"+++def test_rl_codegen_imports_the_module_that_exists():+ # The snippet is spliced into generated source as text, so a rename would+ # otherwise surface only at trainer-construction time in production.+ snippet = _rl_num_proc_snippet()+ assert f"from {GENERATED_IMPORT_MODULE} import {GENERATED_IMPORT_NAME}" in snippet+ assert f"from {GENERATED_FALLBACK_MODULE} import {GENERATED_IMPORT_NAME}" in snippet+ assert snippet.index(GENERATED_IMPORT_MODULE) < snippet.index(+ GENERATED_FALLBACK_MODULE+ ), "the zoo has to be tried first; the unsloth copy is only the fallback"+ assert MODULE_PATH.is_file()+ module = _load_module()+ assert callable(getattr(module, GENERATED_IMPORT_NAME))+++def test_generated_source_reaches_for_the_zoo_before_unsloth():+ """Generated trainer source must not import back into unsloth.++ unsloth/__init__.py generates that source, so a `from unsloth...` there is an+ import of the package mid-flight, and it drags unsloth/utils/__init__.py ->+ packing -> attention_dispatch -> models._utils (torch and the model stack)+ into a module needing none of it. Both call sites must try the zoo first.+ """+ tree = _rl_replacements_tree()+ injected = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call) or getattr(node.func, "id", "") not in ANCHOR_HELPERS:+ continue+ if len(node.args) >= 3 and isinstance(node.args[2], ast.Constant):+ injected.append(ast.literal_eval(node.args[2]))+ # The narrow fallback injects source too, as an re.sub template.+ injected += [+ ast.literal_eval(k.value)+ for k in node.keywords+ if k.arg == "fallback_new" and isinstance(k.value, ast.Constant)+ ]+ reaching = [text for text in injected if "dataset_num_proc" in text]+ assert (+ len(reaching) == 3+ ), "expected the num_proc selection, its narrow fallback and the map() wrapper"+ for text in reaching:+ assert f"from {GENERATED_IMPORT_MODULE} import" in text+ assert text.index(GENERATED_IMPORT_MODULE) < text.index(+ GENERATED_FALLBACK_MODULE+ ), f"this injection imports unsloth before the zoo:\n{text}"+++def test_the_two_copies_have_not_drifted():+ """The zoo owns the policy; this package keeps a fallback copy.++ Two copies can disagree, and the failure would be silent: whichever import+ wins decides the worker count. Compare them with docstrings stripped, so+ prose may differ per repo but no branch, constant or message may.+ """+ spec = importlib.util.find_spec("unsloth_zoo")+ if spec is None or not spec.submodule_search_locations:+ pytest.skip("unsloth_zoo not installed")+ zoo_file = Path(list(spec.submodule_search_locations)[0]) / "dataset_num_proc.py"+ if not zoo_file.is_file():+ pytest.skip("this unsloth_zoo predates dataset_num_proc")++ def _shape(path):+ tree = ast.parse(path.read_text(encoding = "utf-8"))+ for node in ast.walk(tree):+ if not isinstance(+ node, (ast.Module, ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)+ ):+ continue+ body = node.body+ if (+ body+ and isinstance(body[0], ast.Expr)+ and isinstance(body[0].value, ast.Constant)+ and isinstance(body[0].value.value, str)+ ):+ node.body = body[1:] or [ast.Pass()]+ return ast.dump(ast.parse(ast.unparse(tree)))++ assert _shape(MODULE_PATH) == _shape(zoo_file), (+ "unsloth/dataset_num_proc.py and unsloth_zoo/dataset_num_proc.py "+ "have diverged; the zoo copy is the source of truth"+ )+++def test_rl_codegen_snippet_is_valid_python_at_method_indent():+ # rl.py re-indents extra_args to 8 spaces and drops it into __init__.+ snippet = _rl_num_proc_snippet()+ body = "\n".join(" " * 8 + line for line in snippet.split("\n"))+ source = (+ "class C:\n def __init__(self, dataset_num_proc = None):\n" + body + "\n pass\n"+ )+ ast.parse(source)+++def test_rl_codegen_snippet_survives_an_unimportable_helper():+ # A generated file can outlive an unsloth downgrade: constructing a config+ # must still work, just leaving the caller's value alone.+ snippet = _rl_num_proc_snippet()+ namespace = {"dataset_num_proc": 7}+ import builtins++ real_import = builtins.__import__++ def _blocked(name, *args, **kwargs):+ if name.startswith("unsloth"):+ raise ImportError("simulated downgrade")+ return real_import(name, *args, **kwargs)++ builtins.__import__ = _blocked+ try:+ exec(snippet, namespace)+ finally:+ builtins.__import__ = real_import+ assert namespace["dataset_num_proc"] == 7+++# ---------- worker-death diagnostics ----------+++_DATASETS_MESSAGE = (+ "One of the subprocesses has abruptly died during map operation."+ "To debug the error, disable multiprocessing."+)+++def test_worker_death_is_reraised_with_context(dnp):+ # datasets discards the child's exit status, so the original message cannot+ # distinguish an OOM kill from anything else.+ with pytest.raises(RuntimeError) as caught:+ with dnp.map_failure_diagnostics(8):+ raise RuntimeError(_DATASETS_MESSAGE)++ message = str(caught.value)+ assert "dataset_num_proc = 8" in message+ assert "8 workers" in message+ assert "8GB" in message, "should estimate what those workers cost"+ assert dnp.NUM_PROC_ENV_VAR in message, "must name the escape hatch"+ assert "out-of-memory" in message+ # The child's traceback must survive for anyone who wants it.+ assert isinstance(caught.value.__cause__, RuntimeError)+ assert _DATASETS_MESSAGE in str(caught.value.__cause__)+++def test_worker_death_diagnostics_handles_in_process_runs(dnp):+ # num_proc=None still reaches the wrapper; it must not divide by a None.+ with pytest.raises(RuntimeError) as caught:+ with dnp.map_failure_diagnostics(None):+ raise RuntimeError(_DATASETS_MESSAGE)+ assert "dataset_num_proc = None" in str(caught.value)+ assert "1 worker," in str(caught.value)+++def test_unrelated_errors_pass_through_untouched(dnp):+ # Only the dead-worker message is rewritten, and non-RuntimeError types are+ # not caught at all.+ original = RuntimeError("CUDA out of memory")+ with pytest.raises(RuntimeError) as caught:+ with dnp.map_failure_diagnostics(4):+ raise original+ assert caught.value is original++ key = KeyError("text")+ with pytest.raises(KeyError) as caught_key:+ with dnp.map_failure_diagnostics(4):+ raise key+ assert caught_key.value is key++ # The identity assertions above hold under `except Exception` as well, since+ # the guard re-raises the same object. This one does not: it carries the+ # dead-worker text, so a widened clause would rewrite it into a RuntimeError.+ lookalike = ValueError("One of the subprocesses has abruptly died during map operation.")+ with pytest.raises(ValueError) as caught_other:+ with dnp.map_failure_diagnostics(4):+ raise lookalike+ assert caught_other.value is lookalike+++def test_successful_map_is_not_disturbed(dnp):+ with dnp.map_failure_diagnostics(4):+ result = "tokenized"+ assert result == "tokenized"+++def test_studio_num_proc_cap_has_not_drifted(dnp):+ """Studio duplicates AUTO_NUM_PROC_CAP; the two must stay equal.++ hardware.py cannot import this module without pulling unsloth's whole+ __init__ into hardware detection, so it carries its own copy. Read it out of+ the source, since importing studio needs a backend environment this lacks.+ """+ hardware = REPO_ROOT / "studio" / "backend" / "utils" / "hardware" / "hardware.py"+ if not hardware.is_file():+ pytest.skip("studio backend not present")++ tree = ast.parse(hardware.read_text(encoding = "utf-8"))+ found = [+ node.value.value+ for node in ast.walk(tree)+ if isinstance(node, ast.Assign)+ and any(getattr(t, "id", "") == "_STUDIO_NUM_PROC_CAP" for t in node.targets)+ and isinstance(node.value, ast.Constant)+ ]+ assert len(found) == 1, "expected exactly one _STUDIO_NUM_PROC_CAP assignment"+ assert found[0] == dnp.AUTO_NUM_PROC_CAP, (+ f"studio caps dataset workers at {found[0]} while this module caps the "+ f"auto path at {dnp.AUTO_NUM_PROC_CAP}; they must agree"+ )+++def test_studio_bounds_its_own_computed_worker_count(dnp):+ """A backend heuristic must not outrank the cap.++ trainer.py asks for cpu_count // 4 and safe_num_proc's auto path is+ cpu_count // 3, so a 64-core host produced 16 workers and a 192-core one 48.+ Those arrive downstream as explicit ints, only clamped by free memory, so a+ roomy machine kept all 48.+ """+ hardware = REPO_ROOT / "studio" / "backend" / "utils" / "hardware" / "hardware.py"+ if not hardware.is_file():+ pytest.skip("studio backend not present")+ source = hardware.read_text(encoding = "utf-8")++ tree = ast.parse(source)+ safe = next(+ (n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == "safe_num_proc"),+ None,+ )+ assert safe is not None, "safe_num_proc is where every studio map() count is decided"+ body = ast.dump(safe)+ assert "_STUDIO_NUM_PROC_CAP" in body, (+ "safe_num_proc no longer bounds its result; studio would send "+ "cpu_count // 3 workers straight to Dataset.map"+ )+++def test_the_recovery_advice_does_not_promise_more_than_it_delivers(dnp):+ """UNSLOTH_DATASET_NUM_PROC=0 is not in-process on every installation.++ The dead-worker message is the one place a user is told what to do next, so+ it has to be true. On fork, train_on_responses_only over the Zoo's threshold+ gets ``1`` -- a bare None would read as "size it for me". The Zoo release+ that ships with this reads that ``1`` as in-process, but an older one turns+ it into a Pool(1), and generated code runs against whichever Zoo is+ installed. Saying "tokenize in-process" flatly was wrong for exactly the+ large-dataset runs that die.+ """+ with pytest.raises(RuntimeError) as excinfo:+ with dnp.map_failure_diagnostics(8):+ raise RuntimeError("One of the subprocesses has abruptly died during map operation.")+ message = str(excinfo.value)+ assert f"{dnp.NUM_PROC_ENV_VAR}=0" in message+ assert "single worker" in message, "the exception to in-process has to be stated"+ assert "train_on_responses_only" in message, "and which path it applies to"+ assert f"{dnp.ZOO_MIN_ROWS_FOR_MULTIPROC:,}" in message, "and above which size"+++def test_the_advice_matches_what_the_resolver_actually_returns(dnp, monkeypatch):+ """Executed, not just read: drive both branches of the claim above.++ A message asserting a behaviour the resolver does not have would be worse+ than the vague one it replaced.+ """++ class _Split:+ def __init__(self, n):+ self.n = n++ def __len__(self):+ return self.n++ class _Trainer:+ def __init__(self, split):+ self.train_dataset = split+ self.eval_dataset = None++ monkeypatch.setattr(dnp, "multiprocessing_start_method", lambda: "fork")+ monkeypatch.setattr(dnp, "_affordable_workers", lambda: 1000)+ monkeypatch.setattr(dnp.sys, "platform", "linux")+ monkeypatch.setenv(dnp.NUM_PROC_ENV_VAR, "0")++ over = dnp.resolve_responses_only_num_proc(+ _Trainer(_Split(dnp.ZOO_MIN_ROWS_FOR_MULTIPROC + 1)), None+ )+ under = dnp.resolve_responses_only_num_proc(+ _Trainer(_Split(dnp.ZOO_MIN_ROWS_FOR_MULTIPROC - 1)), None+ )+ assert over == 1, "over the threshold the best expressible request is one worker"+ assert under is None, "under it the Zoo's own guard already goes in-process"+++def test_probe_rejects_a_start_method_the_host_does_not_offer(monkeypatch, dnp):+ """The private default-context chain is not trustworthy on its own.++ On a Windows runner it answered "fork" while get_all_start_methods() was+ ["spawn"]. Believing it reads Windows as forkable, so+ _workers_unusable_reason() returns None and workers get through -- the spawn+ re-import loop of #3211 / #3397.+ """+ import sys as _sys+ import types++ fake = types.ModuleType("multiprocess")+ fake.get_start_method = lambda allow_none = False: None+ fake.get_all_start_methods = lambda: ["spawn"]+ context = types.ModuleType("multiprocess.context")+ context._default_context = types.SimpleNamespace(+ _default_context = types.SimpleNamespace(_name = "fork"),+ )+ fake.context = context+ monkeypatch.setitem(_sys.modules, "multiprocess", fake)++ assert dnp.multiprocessing_start_method() == "spawn"++ monkeypatch.setattr(dnp.sys, "platform", "win32")+ assert dnp.get_dataset_num_proc(8) is None+ assert dnp.get_dataset_num_proc(8, serial_as_none = False) is None+++class _Split:+ """Minimal sized stand-in for a datasets.Dataset."""++ def __init__(self, n):+ self.n = n++ def __len__(self):+ return self.n+++# ---------- containers: the host is not what this process may use ----------+++def test_memory_budget_follows_the_cgroup_not_the_host(monkeypatch, dnp):+ """psutil reports the HOST inside a container.++ A 2GB pod on a 512GB box read as having room for the full worker set and got+ OOM-killed, which is the failure the memory ceiling exists to prevent.+ """+ psutil = pytest.importorskip("psutil")+ _force_start_method(monkeypatch, dnp, "fork")+ _force_cpus(monkeypatch, dnp, 64)+ monkeypatch.setattr(+ psutil, "virtual_memory", lambda: type("m", (), {"available": 512 * 1024**3})()+ )+ monkeypatch.setattr(dnp, "_cgroup_free_bytes", lambda: None)+ assert dnp.get_dataset_num_proc(None) == dnp.AUTO_NUM_PROC_CAP++ monkeypatch.setattr(dnp, "_cgroup_free_bytes", lambda: 2 * 1024**3)+ assert dnp.get_dataset_num_proc(None) is None, "a 2GB container has no room for workers"++ monkeypatch.setattr(dnp, "_cgroup_free_bytes", lambda: 8 * 1024**3)+ assert dnp.get_dataset_num_proc(None) == 4+++def test_memory_already_spent_in_the_container_is_not_counted_as_free(monkeypatch, dnp):+ # Otherwise a container that has already spent most of its limit still reads+ # as having the whole thing available.+ psutil = pytest.importorskip("psutil")+ _force_start_method(monkeypatch, dnp, "fork")+ _force_cpus(monkeypatch, dnp, 64)+ monkeypatch.setattr(+ psutil, "virtual_memory", lambda: type("m", (), {"available": 512 * 1024**3})()+ )+ monkeypatch.setattr(dnp, "_cgroup_free_bytes", lambda: 32 * 1024**3)+ assert dnp.get_dataset_num_proc(None) == dnp.AUTO_NUM_PROC_CAP++ # 30 of the 32GB already spent leaves 2, which is not enough for workers.+ monkeypatch.setattr(dnp, "_cgroup_free_bytes", lambda: 2 * 1024**3)+ assert dnp.get_dataset_num_proc(None) is None+++def test_cpu_count_follows_the_affinity_mask(monkeypatch, dnp):+ # Under taskset or Slurm pinning the host count is not what this process can+ # run on, and workers would only contend for the cores it does have.+ psutil = pytest.importorskip("psutil")+ monkeypatch.setattr(psutil, "cpu_count", lambda *a, **k: 128)+ monkeypatch.setattr(dnp, "_cgroup_cpu_quota", lambda: None)+ monkeypatch.setattr(dnp.os, "sched_getaffinity", lambda pid: set(range(4)), raising = False)+ assert dnp._usable_cpus() == 4+++def test_cpu_count_follows_a_fractional_cgroup_quota(monkeypatch, dnp):+ # Kubernetes "cpu: 500m" is cpu.max "50000 100000" = 0.5 cores. Requiring a+ # whole core would fall back to the host count, so a half-core pod would size+ # workers from every core on the machine.+ psutil = pytest.importorskip("psutil")+ monkeypatch.setattr(psutil, "cpu_count", lambda *a, **k: 128)+ monkeypatch.setattr(dnp.os, "sched_getaffinity", lambda pid: set(range(128)), raising = False)+ monkeypatch.setattr(dnp, "_cgroup_cpu_quota", lambda: 0.5)+ assert dnp._usable_cpus() == 1+++def test_a_single_usable_cpu_tokenizes_in_process(monkeypatch, dnp):+ _force_start_method(monkeypatch, dnp, "fork")+ _force_cpus(monkeypatch, dnp, 1)+ assert dnp.get_dataset_num_proc(None) is None+++def test_the_cgroup_readers_never_raise(dnp):+ # They run on every auto-sizing call, on hosts with no cgroup at all.+ free = dnp._cgroup_free_bytes()+ assert free is None or (isinstance(free, int) and free >= 0)+ quota = dnp._cgroup_cpu_quota()+ assert quota is None or isinstance(quota, float)+++# ---------- the zoo reads the other module ----------+++def _force_stdlib_start_method(monkeypatch, dnp, method):+ real = dnp._module_start_method+ monkeypatch.setattr(+ dnp,+ "_module_start_method",+ lambda name: method if name == "multiprocessing" else real(name),+ )+++def test_serial_is_one_when_the_two_modules_disagree(monkeypatch, dnp, capsys):+ """A None handed to train_on_responses_only is "size it for me" to it.++ Its auto path asks stdlib multiprocessing. Where that says fork while+ multiprocess says spawn, None is not serial: it picks cpu_count + 4 workers,+ and datasets then builds that pool on the spawn context -- the #3211 / #3397+ re-import loop, multiplied.+ """+ _force_start_method(monkeypatch, dnp, "spawn")+ _force_stdlib_start_method(monkeypatch, dnp, "fork")++ trainer = type("t", (), {"train_dataset": _Split(dnp.ZOO_MIN_ROWS_FOR_MULTIPROC * 2)})()+ assert dnp.resolve_responses_only_num_proc(trainer, None) == 1+ assert dnp.resolve_responses_only_num_proc(trainer, 16) == 1+ assert "disagree about the start method" in capsys.readouterr().out+++def test_serial_stays_none_when_the_zoo_would_refuse_workers_too(monkeypatch, dnp):+ # macOS: multiprocess forks, stdlib spawns. Its own veto fires, so None is+ # genuinely in-process there and 1 would be a pool it did not need.+ _force_start_method(monkeypatch, dnp, "fork")+ monkeypatch.setattr(dnp.sys, "platform", "darwin")+ _force_stdlib_start_method(monkeypatch, dnp, "spawn")++ trainer = type("t", (), {"train_dataset": _Split(dnp.ZOO_MIN_ROWS_FOR_MULTIPROC * 2)})()+ assert dnp.resolve_responses_only_num_proc(trainer, None) is None+ assert dnp.resolve_responses_only_num_proc(trainer, 16) is None+++def test_agreeing_modules_are_left_alone(monkeypatch, dnp):+ _force_start_method(monkeypatch, dnp, "fork")+ _force_stdlib_start_method(monkeypatch, dnp, "fork")+ _force_cpus(monkeypatch, dnp, 32)+ psutil = pytest.importorskip("psutil")+ monkeypatch.setattr(+ psutil, "virtual_memory", lambda: type("m", (), {"available": 256 * 1024**3})()+ )+ monkeypatch.setattr(dnp, "_cgroup_free_bytes", lambda: None)++ trainer = type("t", (), {"train_dataset": _Split(dnp.ZOO_MIN_ROWS_FOR_MULTIPROC * 2)})()+ assert dnp.resolve_responses_only_num_proc(trainer, None) == dnp.AUTO_NUM_PROC_CAP+ assert dnp.resolve_responses_only_num_proc(trainer, 1) == 1+++def _fake_cgroup_module(+ monkeypatch,+ v2_dirs = (),+ v1_dirs = (),+):+ import types++ def _read_first_line(path):+ return path.read_text() if path.is_file() else None++ def _parse_limit(raw):+ if not raw or raw.strip() == "max":+ return None+ try:+ return int(raw.strip())+ except ValueError:+ return None++ fake = types.ModuleType("unsloth_zoo.hf_xet_tuning")+ fake._cgroup_v2_dirs = lambda: list(v2_dirs)+ fake._cgroup_v1_dirs = lambda controller: list(v1_dirs)+ fake._read_first_line = _read_first_line+ fake._parse_limit = _parse_limit+ fake.cgroup_memory_limit = lambda: None+ fake.cgroup_cpu_limit = lambda: None+ monkeypatch.setitem(sys.modules, "unsloth_zoo.hf_xet_tuning", fake)+ return fake+++def test_free_memory_pairs_each_limit_with_its_own_usage(monkeypatch, dnp, tmp_path):+ """The binding limit is often an ancestor's, and so is the usage that fills it.++ A leaf's usage against a slice's limit reports memory that siblings have+ already spent as free. The other direction is worse: the root+ memory.current is the whole machine, and against a unit's own MemoryMax it+ leaves every run with nothing.+ """+ slice_dir = tmp_path / "user.slice"+ leaf = slice_dir / "session.scope"+ leaf.mkdir(parents = True)++ # The slice caps 32GB and 30 of them are spent, mostly by a sibling; this+ # leaf has a 16GB cap of its own and has spent 1.+ (slice_dir / "memory.max").write_text("34359738368\n")+ (slice_dir / "memory.current").write_text("32212254720\n")+ (leaf / "memory.max").write_text("17179869184\n")+ (leaf / "memory.current").write_text("1073741824\n")++ _fake_cgroup_module(monkeypatch, v2_dirs = [leaf, slice_dir])+ # 34 - 32 = 2GB from the slice, 16 - 1 = 15GB from the leaf. The slice binds.+ assert dnp._cgroup_free_bytes() == 2 * 1024**3+++def test_free_memory_is_never_negative(monkeypatch, dnp, tmp_path):+ # An over-committed cgroup reports more usage than its limit under pressure.+ leaf = tmp_path / "scope"+ leaf.mkdir()+ (leaf / "memory.max").write_text("1073741824\n")+ (leaf / "memory.current").write_text("2147483648\n")+ _fake_cgroup_module(monkeypatch, v2_dirs = [leaf])+ assert dnp._cgroup_free_bytes() == 0+++def test_an_unlimited_cgroup_is_not_a_ceiling(monkeypatch, dnp, tmp_path):+ leaf = tmp_path / "scope"+ leaf.mkdir()+ (leaf / "memory.max").write_text("max\n")+ (leaf / "memory.current").write_text("1073741824\n")+ _fake_cgroup_module(monkeypatch, v2_dirs = [leaf])+ assert dnp._cgroup_free_bytes() is None+++def test_a_readable_limit_with_no_readable_usage_still_binds(monkeypatch, dnp, tmp_path):+ leaf = tmp_path / "scope"+ leaf.mkdir()+ (leaf / "memory.max").write_text("2147483648\n")+ _fake_cgroup_module(monkeypatch, v2_dirs = [leaf])+ assert dnp._cgroup_free_bytes() == 2 * 1024**3+++def _old_zoo(monkeypatch, memory_limit = None):+ """An unsloth_zoo predating the private cgroup helpers, with only the public reader."""+ import types++ fake = types.ModuleType("unsloth_zoo.hf_xet_tuning")+ fake.cgroup_memory_limit = lambda: memory_limit+ fake.cgroup_cpu_limit = lambda: None+ monkeypatch.setitem(sys.modules, "unsloth_zoo.hf_xet_tuning", fake)+ return fake+++def test_the_unaided_reader_subtracts_usage_too(monkeypatch, dnp, tmp_path):+ """An older unsloth_zoo must not turn the ceiling back into the raw limit.++ cgroup_memory_limit() alone reports an 8GB cgroup holding 6GB as 8GB free,+ which is the one case the ceiling exists for: sizing workers off memory that+ is already spent is how #2693's map() children get OOM-killed.+ """+ _old_zoo(monkeypatch, memory_limit = 8 * 1024**3)+ leaf = tmp_path / "kubepods" / "podabc"+ leaf.mkdir(parents = True)+ (leaf / "memory.max").write_text("8589934592\n")+ (leaf / "memory.current").write_text("6442450944\n")++ monkeypatch.setattr(dnp, "CGROUP_ROOT", str(tmp_path))+ monkeypatch.setattr(dnp, "_proc_self_cgroup", lambda: ["0::/kubepods/podabc"])+ assert dnp._cgroup_free_bytes() == 2 * 1024**3+++def test_the_unaided_reader_walks_to_the_binding_ancestor(monkeypatch, dnp, tmp_path):+ """Same pairing rule as the helper-backed path: the slice's limit binds, with the slice's usage."""+ _old_zoo(monkeypatch)+ slice_dir = tmp_path / "user.slice"+ leaf = slice_dir / "session.scope"+ leaf.mkdir(parents = True)+ (slice_dir / "memory.max").write_text("34359738368\n")+ (slice_dir / "memory.current").write_text("32212254720\n")+ (leaf / "memory.max").write_text("17179869184\n")+ (leaf / "memory.current").write_text("1073741824\n")++ monkeypatch.setattr(dnp, "CGROUP_ROOT", str(tmp_path))+ monkeypatch.setattr(dnp, "_proc_self_cgroup", lambda: ["0::/user.slice/session.scope"])+ assert dnp._cgroup_free_bytes() == 2 * 1024**3+++def test_the_unaided_reader_handles_cgroup_v1(monkeypatch, dnp, tmp_path):+ _old_zoo(monkeypatch)+ leaf = tmp_path / "memory" / "slurm" / "job_1"+ leaf.mkdir(parents = True)+ (leaf / "memory.limit_in_bytes").write_text("4294967296\n")+ (leaf / "memory.usage_in_bytes").write_text("3221225472\n")++ monkeypatch.setattr(dnp, "CGROUP_ROOT", str(tmp_path))+ monkeypatch.setattr(+ dnp,+ "_proc_self_cgroup",+ lambda: ["7:memory,blkio:/slurm/job_1"],+ )+ assert dnp._cgroup_free_bytes() == 1024**3+++def test_the_unaided_reader_ignores_the_unlimited_sentinels(monkeypatch, dnp, tmp_path):+ _old_zoo(monkeypatch)+ v2 = tmp_path / "scope"+ v2.mkdir()+ (v2 / "memory.max").write_text("max\n")+ (v2 / "memory.current").write_text("1073741824\n")+ v1 = tmp_path / "memory"+ v1.mkdir()+ # v1's "unlimited": a near-2^63 sentinel, not a 8-exabyte ceiling.+ (v1 / "memory.limit_in_bytes").write_text("9223372036854771712\n")+ (v1 / "memory.usage_in_bytes").write_text("1073741824\n")++ monkeypatch.setattr(dnp, "CGROUP_ROOT", str(tmp_path))+ monkeypatch.setattr(dnp, "_proc_self_cgroup", lambda: ["0::/scope", "7:memory:/"])+ assert dnp._cgroup_free_bytes() is None+++def test_the_unaided_reader_is_never_negative(monkeypatch, dnp, tmp_path):+ _old_zoo(monkeypatch)+ leaf = tmp_path / "scope"+ leaf.mkdir()+ (leaf / "memory.max").write_text("1073741824\n")+ (leaf / "memory.current").write_text("2147483648\n")+ monkeypatch.setattr(dnp, "CGROUP_ROOT", str(tmp_path))+ monkeypatch.setattr(dnp, "_proc_self_cgroup", lambda: ["0::/scope"])+ assert dnp._cgroup_free_bytes() == 0+++def test_the_unaided_reader_keeps_the_public_limit_as_a_last_resort(monkeypatch, dnp, tmp_path):+ """No readable cgroup tree here, but an older zoo may still find one its own way.++ A limit with no usage beside it is still a ceiling, and is a tighter one than+ psutil's host-wide view inside a container.+ """+ _old_zoo(monkeypatch, memory_limit = 4 * 1024**3)+ monkeypatch.setattr(dnp, "CGROUP_ROOT", str(tmp_path / "absent"))+ monkeypatch.setattr(dnp, "_proc_self_cgroup", lambda: [])+ assert dnp._cgroup_free_bytes() == 4 * 1024**3+++def test_the_unaided_reader_never_raises(monkeypatch, dnp):+ """It runs on every auto-sizing call under an older zoo, on hosts with no cgroup at all."""+ _old_zoo(monkeypatch)+ free = dnp._cgroup_free_bytes_unaided()+ assert free is None or (isinstance(free, int) and free >= 0)+++def _no_hf_xet_tuning(monkeypatch):+ """Neither the private helpers nor the public readers: no unsloth_zoo at all."""+ import builtins++ real_import = builtins.__import__++ def _blocked(name, *args, **kwargs):+ if name == "unsloth_zoo.hf_xet_tuning":+ raise ImportError("older unsloth_zoo")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", _blocked)+++def test_no_unsloth_zoo_and_no_cgroup_is_not_a_ceiling(monkeypatch, dnp, tmp_path):+ # The cgroup tree is pointed away from the host's on purpose: the unaided+ # reader needs no unsloth_zoo, so leaving it on the real /sys/fs/cgroup would+ # make the assertion depend on whether the runner is itself in a limited+ # container, which is how this test would fail on CI and pass on a laptop.+ _no_hf_xet_tuning(monkeypatch)+ monkeypatch.setattr(dnp, "CGROUP_ROOT", str(tmp_path / "absent"))+ monkeypatch.setattr(dnp, "_proc_self_cgroup", lambda: [])+ assert dnp._cgroup_free_bytes() is None+ assert dnp._cgroup_cpu_quota() is None+++def test_no_unsloth_zoo_still_reads_the_cgroup(monkeypatch, dnp, tmp_path):+ """The point of the unaided reader: the ceiling survives having no zoo to ask."""+ _no_hf_xet_tuning(monkeypatch)+ leaf = tmp_path / "scope"+ leaf.mkdir()+ (leaf / "memory.max").write_text("8589934592\n")+ (leaf / "memory.current").write_text("6442450944\n")+ monkeypatch.setattr(dnp, "CGROUP_ROOT", str(tmp_path))+ monkeypatch.setattr(dnp, "_proc_self_cgroup", lambda: ["0::/scope"])+ assert dnp._cgroup_free_bytes() == 2 * 1024**3+ # The CPU quota reader has no unaided path, so it stays silent.+ assert dnp._cgroup_cpu_quota() is None+++def test_env_forced_serial_is_in_process_on_a_small_split(monkeypatch, dnp):+ """The documented recovery has to actually recover.++ UNSLOTH_DATASET_NUM_PROC=0 with the config sentinel 1 arriving as an explicit+ count used to return 1, which bypasses the small-split guard and builds a+ Pool(1) on datasets >= 4.1. Under the threshold the guard is in-process, so+ None is what expresses the request exactly.+ """+ _force_start_method(monkeypatch, dnp, "fork")+ _force_stdlib_start_method(monkeypatch, dnp, "fork")+ monkeypatch.setenv(dnp.NUM_PROC_ENV_VAR, "0")++ small = type("t", (), {"train_dataset": _Split(100)})()+ assert dnp.resolve_responses_only_num_proc(small, 1) is None+ assert dnp.resolve_responses_only_num_proc(small, None) is None++ # Over the threshold the guard is gone, and 1 is the least it can be given.+ big = type("t", (), {"train_dataset": _Split(dnp.ZOO_MIN_ROWS_FOR_MULTIPROC * 2)})()+ assert dnp.resolve_responses_only_num_proc(big, 1) == 1+++def test_a_memory_starved_explicit_count_is_in_process_on_a_small_split(monkeypatch, dnp):+ # Same shape without the env var: the memory clamp resolves to serial, and+ # under the threshold that has an exact encoding.+ _force_start_method(monkeypatch, dnp, "fork")+ _force_stdlib_start_method(monkeypatch, dnp, "fork")+ monkeypatch.setattr(dnp, "_affordable_workers", lambda: 0)++ small = type("t", (), {"train_dataset": _Split(100)})()+ assert dnp.resolve_responses_only_num_proc(small, 16) is None+++def test_an_explicit_count_the_host_can_afford_is_untouched_by_the_row_guard(monkeypatch, dnp):+ _force_start_method(monkeypatch, dnp, "fork")+ _force_stdlib_start_method(monkeypatch, dnp, "fork")+ monkeypatch.setattr(dnp, "_affordable_workers", lambda: 1000)++ small = type("t", (), {"train_dataset": _Split(100)})()+ assert dnp.resolve_responses_only_num_proc(small, 4) == 4+++def test_the_fallback_does_not_sit_behind_a_torch_import():+ """MLX hosts have no torch, and reach this module through chat_templates.++ unsloth/utils/__init__.py imports .packing, which imports torch, and+ .attention_dispatch, which imports unsloth.models._utils on top. A fallback+ under that package would raise on the torch-free host it exists to serve, so+ it lives at the top level and every reference to it has to stay there.+ """+ assert (+ MODULE_PATH.parent.name == "unsloth"+ ), "the fallback moved back under a package whose __init__ imports torch"++ utils_init = REPO_ROOT / "unsloth" / "utils" / "__init__.py"+ reached = {+ node.module.split(".")[0]+ if isinstance(node, ast.ImportFrom) and node.level == 0+ else (node.module or "").lstrip(".")+ for node in ast.parse(utils_init.read_text(encoding = "utf-8")).body+ if isinstance(node, ast.ImportFrom)+ }+ assert reached, "unsloth/utils/__init__.py stopped importing anything; re-check the premise"++ for path in (+ REPO_ROOT / "unsloth" / "chat_templates.py",+ REPO_ROOT / "unsloth" / "models" / "rl.py",+ REPO_ROOT / "unsloth" / "models" / "rl_replacements.py",+ ):+ source = path.read_text(encoding = "utf-8")+ assert (+ "unsloth.utils.dataset_num_proc" not in source+ ), f"{path.name} reaches it via unsloth.utils"+ assert ".utils.dataset_num_proc" not in source, f"{path.name} reaches it via unsloth.utils"+++def test_the_fixture_really_neutralises_the_zoo_readers(dnp):+ """The fixture's patching must survive a package __init__ that raises.++ unsloth_zoo/__init__ imports hf_xet_tuning near the top and can raise at the+ end, which drops the package from sys.modules but leaves the submodule+ cached -- and that cache entry is what the policy imports. Patching only on+ a clean `from unsloth_zoo import hf_xet_tuning` leaves the real readers live+ on the runner's own /sys/fs/cgroup, so every sizing assertion silently+ becomes a test of the container's memory limit.+ """+ module = sys.modules.get("unsloth_zoo.hf_xet_tuning")+ if module is None:+ pytest.skip("unsloth_zoo.hf_xet_tuning is not reachable here")+ assert str(module.CGROUP_ROOT).startswith("/nonexistent"), module.CGROUP_ROOT+ assert module._cgroup_v2_dirs() == []+ assert module._cgroup_v1_dirs("memory") == []+++def test_the_unaided_reader_picks_its_own_v1_line_too(monkeypatch, dnp, tmp_path):+ """The other half of the scan: a v1 line that is not the first line.++ The hybrid case above puts the memory controller first, so taking line 0+ would still land on it. Here a pids line comes first and the memory+ controller sits at a different path, which is what a Slurm step looks like:+ reading line 0 walks a directory that does not exist and loses the ceiling+ the step was given.+ """+ _no_hf_xet_tuning(monkeypatch)+ v2_leaf = tmp_path / "user.slice" / "app.scope"+ v2_leaf.mkdir(parents = True)+ (v2_leaf / "memory.max").write_text("8589934592\n")+ (v2_leaf / "memory.current").write_text("6442450944\n")+ # 4GB capped, 3 spent: 1GB free, which is less than the v2 side's 2GB.+ v1_leaf = tmp_path / "memory" / "slurm" / "job_1"+ v1_leaf.mkdir(parents = True)+ (v1_leaf / "memory.limit_in_bytes").write_text("4294967296\n")+ (v1_leaf / "memory.usage_in_bytes").write_text("3221225472\n")++ monkeypatch.setattr(dnp, "CGROUP_ROOT", str(tmp_path))+ monkeypatch.setattr(+ dnp,+ "_proc_self_cgroup",+ lambda: [+ "11:pids:/user.slice/user-1000.slice/session-3.scope",+ "10:memory:/slurm/job_1",+ "0::/user.slice/app.scope",+ ],+ )+ assert dnp._cgroup_free_bytes() == 1024**3+++def test_the_hatch_wins_on_a_small_split_too(monkeypatch, dnp):+ """A split under the threshold is where the resolver would otherwise stand+ down, and standing down there would silently discard the count a user set+ by hand to get workers on a small dataset."""+ _force_start_method(monkeypatch, dnp, "fork")+ _force_stdlib_start_method(monkeypatch, dnp, "fork")+ monkeypatch.setenv(dnp.NUM_PROC_ENV_VAR, "16")++ small = type("t", (), {"train_dataset": _Split(100)})()+ assert dnp.resolve_responses_only_num_proc(small, None) == 16diff --git a/tests/utils/test_train_on_responses_only_num_proc.py b/tests/utils/test_train_on_responses_only_num_proc.pynew file mode 100644index 00000000000..c1a4ae413da--- /dev/null+++ b/tests/utils/test_train_on_responses_only_num_proc.py@@ -0,0 +1,317 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The worker-count bound applied to unsloth_zoo's train_on_responses_only.++The zoo sizes its own dataset.map() workers with the uncapped heuristic issue+#2693 is about, so unsloth.chat_templates wraps it. These tests pin the two+things that make the wrapper non-obvious: None means "auto" to the zoo, not+"in-process", and an explicit count switches off its small-split guard.+"""++import importlib.util+import re+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[2]+++def _load_helper():+ spec = importlib.util.spec_from_file_location(+ "_unsloth_dnp", REPO_ROOT / "unsloth" / "dataset_num_proc.py"+ )+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++dnp = _load_helper()+++class _Split:+ """Minimal sized stand-in for a datasets.Dataset."""++ def __init__(self, rows):+ self._rows = rows++ def __len__(self):+ return self._rows+++class _Unsized:+ """Stands in for an IterableDataset, whose length the zoo cannot read."""++ def __len__(self):+ raise TypeError("unsized")+++class _Trainer:+ def __init__(+ self,+ train_dataset = None,+ eval_dataset = None,+ ):+ self.train_dataset = train_dataset+ self.eval_dataset = eval_dataset+++BIG = dnp.ZOO_MIN_ROWS_FOR_MULTIPROC+SMALL = dnp.ZOO_MIN_ROWS_FOR_MULTIPROC - 1++[email protected](autouse = True)+def _reset(monkeypatch):+ dnp.reset_warning_state()+ monkeypatch.delenv(dnp.NUM_PROC_ENV_VAR, raising = False)+ # Pin CPUs, memory and both start methods so the assertions are about the+ # wrapper, not this machine. Auto is min(max(cpus // 2, AUTO_NUM_PROC_CAP)),+ # so reaching the cap needs >= 2 * AUTO_NUM_PROC_CAP usable CPUs -- and+ # "usable" is the smallest of the host, the affinity mask and any cgroup+ # quota, so patching psutil alone would still read a 4-vCPU runner as 4.+ pytest.importorskip("psutil")+ monkeypatch.setattr(dnp, "_usable_cpus", lambda: 64)+ monkeypatch.setattr(dnp, "_affordable_workers", lambda: 1000)+ monkeypatch.setattr(dnp, "multiprocessing_start_method", lambda: "fork")+ # The zoo's own auto path reads stdlib multiprocessing; agreeing here keeps+ # these cases about the row thresholds. The disagreement is covered in+ # test_dataset_num_proc.py.+ monkeypatch.setattr(dnp, "_zoo_auto_sizer_forks", lambda: True)+ yield+ dnp.reset_warning_state()+++# ── The zoo's threshold, duplicated in ZOO_MIN_ROWS_FOR_MULTIPROC ──+++def _zoo_source():+ """Read unsloth_zoo's dataset_utils source without importing it.++ Importing the package pulls torch, which is not always loadable here, and+ these two checks only need the text. find_spec on the submodule would import+ unsloth_zoo, so locate the top level package and read the file off disk.+ """+ spec = importlib.util.find_spec("unsloth_zoo")+ locations = list(getattr(spec, "submodule_search_locations", None) or [])+ if spec is None or not locations:+ pytest.skip("unsloth_zoo is not installed")+ source = Path(locations[0]) / "dataset_utils.py"+ if not source.is_file():+ pytest.skip("unsloth_zoo.dataset_utils not found on disk")+ return source.read_text()+++def test_zoo_threshold_constant_has_not_drifted():+ """ZOO_MIN_ROWS_FOR_MULTIPROC mirrors a local inside the zoo function.++ It cannot be imported, so this canary is the only thing between a zoo change+ and silently removing its small-split guard.+ """+ match = re.search(r"_MIN_ROWS_FOR_MULTIPROC\s*=\s*([0-9_]+)", _zoo_source())+ assert match is not None, (+ "unsloth_zoo no longer defines _MIN_ROWS_FOR_MULTIPROC; "+ "resolve_responses_only_num_proc assumes it exists to decide when "+ "substituting a worker count is safe"+ )+ assert int(match.group(1).replace("_", "")) == dnp.ZOO_MIN_ROWS_FOR_MULTIPROC+++def test_zoo_still_treats_none_as_auto_not_serial():+ """The reason None cannot be forwarded to the zoo as an in-process request."""+ assert "_num_proc_was_auto = num_proc is None or type(num_proc) is not int" in _zoo_source()+++# ── Explicit counts ──+++def test_explicit_count_is_bounded(monkeypatch):+ monkeypatch.setattr(dnp, "_affordable_workers", lambda: 4)+ assert dnp.resolve_responses_only_num_proc(_Trainer(_Split(BIG)), 64) == 4+++def test_explicit_count_survives_when_memory_allows():+ assert dnp.resolve_responses_only_num_proc(_Trainer(_Split(BIG)), 6) == 6+++def test_explicit_one_stays_one_and_never_becomes_none():+ """None would read as 'auto' to the zoo and inflate to the auto count."""+ assert dnp.resolve_responses_only_num_proc(_Trainer(_Split(BIG)), 1) == 1+++def test_explicit_count_serialised_by_memory_becomes_one_not_none(monkeypatch):+ monkeypatch.setattr(dnp, "_affordable_workers", lambda: 0)+ assert dnp.resolve_responses_only_num_proc(_Trainer(_Split(BIG)), 32) == 1+++def test_explicit_count_ignores_split_size():+ """The zoo already skips its guard for explicit counts, so we take nothing."""+ assert dnp.resolve_responses_only_num_proc(_Trainer(_Split(SMALL)), 6) == 6+++# ── Auto counts: the zoo's small-split guard must survive ──+++def test_auto_small_split_passes_none_through():+ assert dnp.resolve_responses_only_num_proc(_Trainer(_Split(SMALL)), None) is None+++def test_auto_large_split_gets_the_bounded_count():+ resolved = dnp.resolve_responses_only_num_proc(_Trainer(_Split(BIG)), None)+ assert resolved == dnp.AUTO_NUM_PROC_CAP+++def test_auto_uses_the_largest_split_not_the_smallest():+ """A big train split must still be bounded when eval is small."""+ trainer = _Trainer(train_dataset = _Split(BIG), eval_dataset = _Split(10))+ assert dnp.resolve_responses_only_num_proc(trainer, None) == dnp.AUTO_NUM_PROC_CAP+++def test_auto_unsized_split_passes_none_through():+ trainer = _Trainer(train_dataset = _Unsized())+ assert dnp.resolve_responses_only_num_proc(trainer, None) is None+++ "trainer",+ [+ _Trainer(train_dataset = _Split(BIG), eval_dataset = _Unsized()),+ _Trainer(train_dataset = _Unsized(), eval_dataset = _Split(BIG)),+ _Trainer(train_dataset = _Split(BIG), eval_dataset = {"a": _Unsized()}),+ ],+ ids = ["unsized-eval", "unsized-train", "unsized-eval-dict"],+)+def test_an_unsized_split_does_not_hide_a_large_sized_one(trainer):+ """Regression: one unsized split disabled the bound for every other split.++ An unsized split used to abandon the measurement and return None, which the+ zoo reads as "auto", not "in-process", so it sized the *sized* split with its+ own uncapped min(max(cpu_count + 4, 2), 64). The unsized one can never use+ workers anyway (the zoo's IterableDataset branch passes no num_proc).+ """+ assert dnp.resolve_responses_only_num_proc(trainer, None) == dnp.AUTO_NUM_PROC_CAP+++def test_auto_dict_eval_dataset_is_unpacked():+ trainer = _Trainer(train_dataset = _Split(10), eval_dataset = {"a": _Split(BIG)})+ assert dnp.resolve_responses_only_num_proc(trainer, None) == dnp.AUTO_NUM_PROC_CAP+++def test_no_trainer_passes_none_through():+ assert dnp.resolve_responses_only_num_proc(None, None) is None+++def test_trainer_without_datasets_passes_none_through():+ assert dnp.resolve_responses_only_num_proc(_Trainer(), None) is None+++def test_bool_is_treated_as_auto_like_the_zoo_does():+ """type(True) is not int by the zoo's test, so it counts as auto."""+ assert dnp.resolve_responses_only_num_proc(_Trainer(_Split(SMALL)), True) is True+++def test_env_override_still_wins_for_explicit_values(monkeypatch):+ monkeypatch.setenv(dnp.NUM_PROC_ENV_VAR, "16")+ monkeypatch.setattr(dnp, "_affordable_workers", lambda: 2)+ assert dnp.resolve_responses_only_num_proc(_Trainer(_Split(BIG)), 4) == 16+++ "trainer",+ [+ _Trainer(train_dataset = _Split(SMALL)),+ _Trainer(train_dataset = _Unsized()),+ _Trainer(),+ ],+ ids = ["small-split", "unsized-split", "no-splits"],+)+def test_env_override_wins_on_the_split_size_shortcut(monkeypatch, trainer):+ """The escape hatch must win everywhere, including the early return.++ The shortcut for splits the zoo would not have parallelized used to return+ before UNSLOTH_DATASET_NUM_PROC was read, dropping a count set by a user who+ had just been told to set it.+ """+ monkeypatch.setenv(dnp.NUM_PROC_ENV_VAR, "3")+ assert dnp.resolve_responses_only_num_proc(trainer, None) == 3+++# ── Serial is encoded for the zoo, which reads None as "auto" ──+++def _spawn(monkeypatch):+ # Both modules on spawn, the ordinary Windows host. The interesting case is+ # when they disagree, which is what _split below covers.+ monkeypatch.setattr(dnp, "multiprocessing_start_method", lambda: "spawn")+ monkeypatch.setattr(dnp, "_zoo_auto_sizer_forks", lambda: False)+++def _split(monkeypatch):+ # multiprocess on spawn, stdlib still on fork: a None here is "size it for+ # me" to the zoo, and datasets then builds that pool on the spawn context.+ monkeypatch.setattr(dnp, "multiprocessing_start_method", lambda: "spawn")+ monkeypatch.setattr(dnp, "_zoo_auto_sizer_forks", lambda: True)+++ "requested",+ [None, 32, 1],+ ids = ["auto", "explicit-count", "explicit-one"],+)+def test_serial_is_none_not_one_on_spawn(_spawn, requested):+ """On spawn the zoo must be left to veto, not handed a Pool(1).++ ``1`` is not in-process on ``datasets`` >= 4.1, and under spawn each of those+ children re-imports the user's ``__main__`` (#3211 / #3397). ``None`` is safe+ precisely because it is *not* serial to the zoo: its auto path runs its own+ non-fork veto and lands in-process. That holds only while the zoo's check+ agrees, which is why _spawn pins both modules.+ """+ assert dnp.resolve_responses_only_num_proc(_Trainer(_Split(BIG)), requested) is None+++ "requested",+ [None, 32, 1],+ ids = ["auto", "explicit-count", "explicit-one"],+)+def test_one_worker_when_only_multiprocess_is_on_spawn(_split, requested):+ """The zoo's veto reads stdlib multiprocessing, so it would not fire here.++ A None would be auto-sized to cpu_count + 4 and datasets would build that+ pool on the spawn context. One worker is the smallest request the zoo honours+ verbatim: still a Pool(1), but not dozens of them.+ """+ assert dnp.resolve_responses_only_num_proc(_Trainer(_Split(BIG)), requested) == 1+++def test_env_forced_serial_on_a_large_split_is_one_on_fork(monkeypatch):+ """The fork side of the same branch, where 1 is the best available value.++ The zoo's row guard cannot help on a large split and None would be read as+ "auto" and inflated, so one forked worker is the floor this wrapper can+ express. Pinned so the spawn tests above cannot be "fixed" by making every+ start method return None.+ """+ monkeypatch.setenv(dnp.NUM_PROC_ENV_VAR, "0")+ assert dnp.resolve_responses_only_num_proc(_Trainer(_Split(BIG)), None) == 1+++def test_env_explicit_count_is_not_downgraded_on_spawn(_spawn, monkeypatch):+ """The escape hatch is deliberate, so it keeps bypassing the veto."""+ monkeypatch.setenv(dnp.NUM_PROC_ENV_VAR, "3")+ assert dnp.resolve_responses_only_num_proc(_Trainer(_Split(BIG)), None) == 3++[email protected]("raw", ["0", "none", "false"])+def test_env_forced_in_process_leaves_the_zoo_guard_in_charge(monkeypatch, raw):+ """UNSLOTH_DATASET_NUM_PROC=0 must not turn into a Pool(1) on a small split.++ The zoo's guard already yields None under its threshold, and None -- not the+ 1 this function can express -- is the only value datasets runs in-process on+ every release, so honour the hatch by leaving the value alone.+ """+ monkeypatch.setenv(dnp.NUM_PROC_ENV_VAR, raw)+ assert dnp.resolve_responses_only_num_proc(_Trainer(_Split(SMALL)), None) is Nonediff --git a/unsloth/__init__.py b/unsloth/__init__.pyindex 659637dd92e..58057025b69 100644--- a/unsloth/__init__.py+++ b/unsloth/__init__.py@@ -1314,7 +1314,15 @@ if _IS_MLX:def train_on_responses_only(*args, **kwargs):"""Mask non-response tokens through the shared zoo dataset helper."""- from unsloth_zoo.dataset_utils import train_on_responses_only as _train_on_responses_only+ # Prefer the chat_templates export, which bounds the zoo's dataset.map()+ # worker count (issue #2693). It is None on a torch-free host; fall back+ # so the zoo raises its own ImportError, not "NoneType is not callable".+ from .chat_templates import train_on_responses_only as _train_on_responses_only++ if _train_on_responses_only is None:+ from unsloth_zoo.dataset_utils import (+ train_on_responses_only as _train_on_responses_only,+ )return _train_on_responses_only(*args, **kwargs)def _safe_mlx_trl_star_exports(_trl):diff --git a/unsloth/chat_templates.py b/unsloth/chat_templates.pyindex 9d3a9f0be9d..eee361d2c4a 100644--- a/unsloth/chat_templates.py+++ b/unsloth/chat_templates.py@@ -39,13 +39,53 @@ import refrom .ollama_template_mappers import OLLAMA_TEMPLATEStry:from unsloth_zoo.dataset_utils import (- train_on_responses_only,+ train_on_responses_only as _zoo_train_on_responses_only,standardize_data_formats,)except ImportError:# dataset_utils pulls torch; keep chat_templates importable on torch-free# (MLX) hosts, which expose these via the backend-specific wrappers instead.- train_on_responses_only = standardize_data_formats = None+ _zoo_train_on_responses_only = standardize_data_formats = None++if _zoo_train_on_responses_only is None:+ train_on_responses_only = None+else:+ import functools as _functools+ import inspect as _inspect++ _ZOO_RESPONSES_ONLY_SIGNATURE = _inspect.signature(_zoo_train_on_responses_only)++ @_functools.wraps(_zoo_train_on_responses_only)+ def train_on_responses_only(*args, **kwargs):+ # The zoo still auto-sizes its dataset.map() workers with the uncapped+ # min(max(cpu_count + 4, 2), 64) heuristic (issue #2693) and is a+ # separate package, so bound the count on the way in. See+ # resolve_responses_only_num_proc; the local copy is only the fallback+ # for a zoo predating it. Top level, not under unsloth.utils, whose+ # __init__ imports torch: this path has to stay MLX-safe.+ try:+ from unsloth_zoo.dataset_num_proc import resolve_responses_only_num_proc+ except ImportError:+ from .dataset_num_proc import resolve_responses_only_num_proc++ try:+ bound = _ZOO_RESPONSES_ONLY_SIGNATURE.bind_partial(*args, **kwargs)+ except TypeError:+ # Signature drift, or a bad call. Let the zoo raise its own error.+ return _zoo_train_on_responses_only(*args, **kwargs)++ # The zoo returns the masking closure before reading num_proc.+ if bound.arguments.get("return_function", False):+ return _zoo_train_on_responses_only(*args, **kwargs)++ arguments = dict(bound.arguments)+ arguments["num_proc"] = resolve_responses_only_num_proc(+ arguments.get("trainer"),+ arguments.get("num_proc"),+ )+ trainer = arguments.pop("trainer", None)+ return _zoo_train_on_responses_only(trainer, **arguments)+standardize_sharegpt = standardize_data_formatsCHAT_TEMPLATES = {}DEFAULT_SYSTEM_MESSAGE = {}diff --git a/unsloth/dataset_num_proc.py b/unsloth/dataset_num_proc.pynew file mode 100644index 00000000000..1c732d498ab--- /dev/null+++ b/unsloth/dataset_num_proc.py@@ -0,0 +1,730 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++"""Fallback copy of the ``dataset_num_proc`` policy for ``Dataset.map()``.++``unsloth_zoo.dataset_num_proc`` is the source of truth, since generated trainer+source must not import back into the package that generated it. Every caller+tries the zoo first, so this copy exists only so that upgrading unsloth alone+still fixes the bug; ``test_the_two_copies_have_not_drifted`` keeps the two in+step, and this file can go once the zoo floor guarantees the module.++It replaces four drifted copies of the heuristic (generated source in+``unsloth/models/rl.py``, plus ``unsloth_zoo.dataset_utils``), two of them wrong+in ways that produced https://github.com/unslothai/unsloth/issues/2693:++1. They asked ``multiprocessing.get_start_method()`` about forking, but+ ``Dataset.map`` imports ``Pool`` from ``multiprocess`` (the dill fork), which+ keeps its own default context. The two read different settings.++2. They used ``1`` as the "disable multiprocessing" sentinel, but ``datasets``+ >= 4.1 (Studio pins 4.3.0) pools for any ``num_proc >= 1``, so only ``None``+ is in-process on every supported version.+"""++from __future__ import annotations++import contextlib+import os+import sys+from typing import Iterator, Optional++__all__ = [+ "AUTO_NUM_PROC_CAP",+ "MEMORY_BUDGET_FRACTION",+ "NUM_PROC_ENV_VAR",+ "WORKER_MEMORY_BUDGET_GB",+ "ZOO_MIN_ROWS_FOR_MULTIPROC",+ "environment_override",+ "get_dataset_num_proc",+ "map_failure_diagnostics",+ "multiprocessing_start_method",+ "reset_warning_state",+ "resolve_responses_only_num_proc",+]++# Escape hatch: a positive integer forces that count verbatim (no cap, no+# start-method veto), "0"/"none" forces in-process tokenization.+NUM_PROC_ENV_VAR = "UNSLOTH_DATASET_NUM_PROC"++# Upper bound for the *auto* count only; raise it via NUM_PROC_ENV_VAR. The old+# min(max(cpu_count + 4, 2), 64) forked up to 64 workers, each handed its own+# dill-pickled tokenizer closure and an Arrow shard over a pipe. Measured on+# 8000 rows, Qwen2.5 fast tokenizer, 3 reps: None 6.3s, 1 9.5s, 8 8.1s,+# 32 14.2s, 64 21.7s -- more workers were slower than none at every size.+AUTO_NUM_PROC_CAP = 8++# ~680 MB peak RSS per worker on that run, flat across counts; 1 GB for headroom.+WORKER_MEMORY_BUDGET_GB = 1.0++# Share of *available* RAM tokenization may spend; the rest belongs to the run+# that follows. This is what bounds issue #2693, where OOM-killed workers+# surface only as "One of the subprocesses has abruptly died during map+# operation", the real cause discarded.+MEMORY_BUDGET_FRACTION = 0.5++# Mirrors _MIN_ROWS_FOR_MULTIPROC, a local inside+# dataset_utils.train_on_responses_only (hence not importable): below it that+# helper maps a split in-process, unless handed an explicit count.+# resolve_responses_only_num_proc needs the threshold to keep that guard; a+# canary in tests/test_dataset_num_proc.py catches drift.+ZOO_MIN_ROWS_FOR_MULTIPROC = 5_000++# Warn at most once per process per distinct reason.+_WARNED: set = set()+++def reset_warning_state() -> None:+ """Clear the once-per-process warning memo. Intended for tests."""+ _WARNED.clear()+++def _warn_once(key: str, message: str) -> None:+ if key in _WARNED:+ return+ _WARNED.add(key)+ print(f"Unsloth: {message}")+++def _unpinned_default_start_method(module) -> Optional[str]:+ """The default start method of a module that has not pinned one yet.++ ``get_all_start_methods()[0]`` is the documented default, but ``multiprocess``+ copies that function verbatim -- darwin branch listing ``spawn`` first --+ without copying the darwin default that goes with it, keeping ``fork`` as its+ ``_default_context`` (``#FIXME: spawn`` in its ``context.py``). So its list+ says ``spawn`` while its ``Pool`` forks, and ``datasets`` builds from+ ``multiprocess``. Read the default context's own name instead; unlike+ ``get_context()`` it does not assign ``_actual_context``, keeping the probe+ side-effect free. Private attributes, hence the fallback.+ """+ try:+ methods = module.get_all_start_methods()+ except Exception:+ methods = []++ try:+ name = module.context._default_context._default_context._name+ # Only if the platform actually offers it: a Windows runner answered+ # 'fork' while get_all_start_methods() was ['spawn'], which would read+ # Windows as forkable -- the spawn re-import loop of #3211 / #3397.+ if isinstance(name, str) and name and (not methods or name in methods):+ return name+ except Exception:+ pass+ return methods[0] if methods else None+++def _module_start_method(module_name: str) -> Optional[str]:+ """One module's start method. Raises if the module cannot be read at all.++ Observing must not mutate: ``get_start_method(allow_none = False)`` pins+ ``_actual_context``, which would make a later ``set_start_method()`` raise.+ """+ module = __import__(module_name)+ method = module.get_start_method(allow_none = True)+ if method is None:+ method = _unpinned_default_start_method(module)+ return method+++def multiprocessing_start_method() -> Optional[str]:+ """Return the start method ``datasets`` will actually use, or None.++ ``datasets.arrow_dataset`` does ``from multiprocess import Pool``, so+ ``multiprocess`` -- not stdlib ``multiprocessing`` -- decides how+ ``Dataset.map(num_proc = ...)`` spawns workers. Falls back to the stdlib+ module, then to None (the caller then treats forking as unavailable).+ """+ for module_name in ("multiprocess", "multiprocessing"):+ try:+ return _module_start_method(module_name)+ except Exception:+ continue+ return None+++def _workers_unusable_reason() -> Optional[str]:+ """Why ``datasets`` workers cannot be used here, or None when they can.++ * **Not ``fork``.** The child must re-import the dynamically generated+ trainer module, which has no importable name, so it cannot come up at all.++ * **macOS, whatever the start method says.** CPython moved the macOS default+ to ``spawn`` in 3.8 (bpo-33725) because forking there "can lead to crashes+ of the subprocess as macOS system libraries may start threads".+ ``multiprocess`` never copied that, so ``datasets`` genuinely forks on+ macOS out of a parent holding Torch and a threaded BLAS. Reporting that+ truthfully is right; acting on it is not, so macOS stays in-process as a+ stated policy rather than as a side effect of the probe.+ """+ start_method = multiprocessing_start_method()+ if start_method != "fork":+ return f"this process uses the {start_method!r} start method"+ if sys.platform == "darwin":+ return "'multiprocess' forks on macOS, which CPython documents as unsafe there (bpo-33725)"+ return None+++def _cgroup_cpu_quota() -> Optional[float]:+ """This process's cgroup CPU ceiling in cores, or None outside one.++ Reuses the reader in ``hf_xet_tuning`` rather than parsing ``/sys/fs/cgroup``+ again: it already handles v1 against v2, the ``/proc/self/cgroup`` path walk+ and the "unlimited" sentinels. Imported lazily, so this module still loads on+ its own.+ """+ try:+ from unsloth_zoo.hf_xet_tuning import cgroup_cpu_limit+ return cgroup_cpu_limit()+ except Exception:+ return None+++# Module constant so tests can point the unaided reader at a fixture tree.+CGROUP_ROOT = "/sys/fs/cgroup"+++def _cgroup_first_line(path: str) -> Optional[str]:+ try:+ # encoding named explicitly: these are ASCII kernel files, but a+ # locale-dependent read crashes or produces mojibake on a Windows+ # console codepage, and CI polices every read/write for it.+ with open(path, "r", encoding = "utf-8") as f:+ return f.readline().strip()+ except OSError:+ return None+++def _cgroup_int(raw: Optional[str]) -> Optional[int]:+ if raw is None:+ return None+ try:+ return int(raw)+ except ValueError:+ return None+++def _cgroup_limit(raw: Optional[str]) -> Optional[int]:+ """``"max"`` (or an unparseable value) means unlimited."""+ value = _cgroup_int(raw)+ if value is None:+ return None+ # cgroup v1 spells "unlimited" as a near-2^63 sentinel.+ return value if 0 < value < (1 << 62) else None+++def _cgroup_dirs(root: str, rel: Optional[str]) -> list:+ """``root/rel`` and every ancestor up to *root*, innermost first.++ A parent slice's limit binds this process just as its own does.+ """+ dirs = []+ if rel and rel != "/":+ current = os.path.normpath(os.path.join(root, rel.lstrip("/")))+ while current.startswith(root + os.sep):+ dirs.append(current)+ current = os.path.dirname(current)+ dirs.append(root)+ return dirs+++def _proc_self_cgroup() -> list:+ try:+ with open("/proc/self/cgroup", "r", encoding = "utf-8") as f:+ return [line.strip() for line in f if line.strip()]+ except OSError:+ return [] # not Linux, or procfs is hidden+++def _cgroup_free_bytes_unaided() -> Optional[int]:+ """``_cgroup_free_bytes`` without unsloth_zoo's private cgroup helpers.++ Only reached on an older unsloth_zoo, and only ever a fallback: the pairing+ rule, the "unlimited" sentinels and the innermost-first walk are the ones+ documented on ``_cgroup_free_bytes``. Reading the public ``cgroup_memory_limit``+ alone is the last resort, since a limit is still a ceiling even unpaired.+ """+ lines = _proc_self_cgroup()+ free = []++ if os.path.isdir(CGROUP_ROOT):+ rel = None+ # The v2 line is "0::<path>"; under systemd hybrid mode v1 lines share+ # the file, so scan rather than taking the first.+ for line in lines:+ if line.startswith("0::"):+ rel = line[3:].strip()+ break+ for directory in _cgroup_dirs(CGROUP_ROOT, rel):+ used = _cgroup_int(_cgroup_first_line(os.path.join(directory, "memory.current")))+ for name in ("memory.max", "memory.high"):+ limit = _cgroup_limit(_cgroup_first_line(os.path.join(directory, name)))+ if limit is not None:+ free.append(limit if used is None else limit - used)++ v1_root = os.path.join(CGROUP_ROOT, "memory")+ if os.path.isdir(v1_root):+ rel = None+ for line in lines:+ # "<id>:<controllers>:<path>"; mounts are often combined.+ parts = line.split(":", 2)+ if len(parts) == 3 and "memory" in parts[1].split(","):+ rel = parts[2]+ break+ for directory in _cgroup_dirs(v1_root, rel):+ used = _cgroup_int(_cgroup_first_line(os.path.join(directory, "memory.usage_in_bytes")))+ limit = _cgroup_limit(+ _cgroup_first_line(os.path.join(directory, "memory.limit_in_bytes"))+ )+ if limit is not None:+ free.append(limit if used is None else limit - used)++ if free:+ return max(min(free), 0)++ try:+ from unsloth_zoo.hf_xet_tuning import cgroup_memory_limit+ return cgroup_memory_limit()+ except Exception:+ return None+++def _cgroup_free_bytes() -> Optional[int]:+ """Bytes free under the binding cgroup memory limit, or None outside one.++ Each limit is paired with the usage of the directory that set it. The binding+ limit is often an ancestor's -- a systemd slice, a Slurm job step -- and that+ ancestor's usage counts siblings this process cannot see from its own leaf,+ so pairing a leaf's usage with an ancestor's limit would report memory that+ is already spent as free. The reverse pairing is worse still: the root+ ``memory.current`` is the whole machine, and subtracting it from a unit's own+ MemoryMax leaves every run with nothing.+ """+ try:+ from unsloth_zoo.hf_xet_tuning import (+ _cgroup_v1_dirs,+ _cgroup_v2_dirs,+ _parse_limit,+ _read_first_line,+ )+ except Exception:+ # An older unsloth_zoo has no such private helpers. Do the same pairing+ # here rather than reading the public limit alone: an 8GB cgroup with 6GB+ # already resident would otherwise report 8GB free, and memory pressure+ # is the one condition this ceiling exists for.+ return _cgroup_free_bytes_unaided()++ def _used(path):+ raw = _read_first_line(path)+ if not raw:+ return None+ try:+ return int(raw.strip())+ except ValueError:+ return None++ free = []+ for directory in _cgroup_v2_dirs():+ used = _used(directory / "memory.current")+ for name in ("memory.max", "memory.high"):+ limit = _parse_limit(_read_first_line(directory / name))+ if limit is not None:+ free.append(limit if used is None else limit - used)+ for directory in _cgroup_v1_dirs("memory"):+ used = _used(directory / "memory.usage_in_bytes")+ limit = _parse_limit(_read_first_line(directory / "memory.limit_in_bytes"))+ if limit is not None:+ free.append(limit if used is None else limit - used)++ return max(min(free), 0) if free else None+++def _available_memory_gb() -> Optional[float]:+ """Free RAM this process may actually use, or None when it cannot be read.++ ``psutil.virtual_memory().available`` reports the HOST inside a container, so+ a 2GB pod on a 512GB box read as having room for the full worker set and got+ OOM-killed -- the exact failure the memory ceiling exists to prevent.+ """+ try:+ import psutil+ available_gb = psutil.virtual_memory().available / (1024**3)+ except Exception:+ return None++ free = _cgroup_free_bytes()+ if free is not None:+ available_gb = min(available_gb, free / (1024**3))+ return available_gb+++def _usable_cpus() -> Optional[int]:+ """CPUs this process may actually run on, or None when that cannot be read.++ ``cpu_count()`` is the host's, so under ``taskset``, Slurm pinning or a+ Kubernetes CPU quota a one-core job would auto-size workers that then contend+ for that one core, making tokenization slower than doing it in-process.+ """+ try:+ import psutil+ cpus = psutil.cpu_count()+ except Exception:+ cpus = os.cpu_count()+ if not cpus:+ return None++ try:+ cpus = min(cpus, len(os.sched_getaffinity(0)))+ except (AttributeError, OSError):+ pass # not Linux, or the call is unavailable: the host count stands++ quota = _cgroup_cpu_quota()+ if quota is not None and quota > 0:+ # A fractional quota still binds: Kubernetes "cpu: 500m" is 0.5 cores.+ cpus = min(cpus, max(1, int(quota)))+ return cpus+++def _affordable_workers() -> Optional[int]:+ """How many workers free RAM can cover, or None when it cannot be read."""+ available_gb = _available_memory_gb()+ if available_gb is None:+ return None+ budget_gb = available_gb * MEMORY_BUDGET_FRACTION+ return int(budget_gb / WORKER_MEMORY_BUDGET_GB)+++def _clamp_by_memory(num_proc: int) -> Optional[int]:+ """Bound a worker count by RAM. None means "do not use workers at all".++ Applies to explicit counts too: the old heuristic capped only the auto path,+ so a caller passing a number (Studio passes ``max(1, cpu_count // 4)``) could+ ask for dozens of workers on a machine with no room. That is what OOMs.+ """+ affordable = _affordable_workers()+ if affordable is None:+ # No memory reading, so honour the request rather than serialising a+ # machine that may be perfectly capable.+ return num_proc++ if affordable < 2:+ _warn_once(+ "memory_serial",+ "not enough free memory for dataset tokenization workers "+ f"(~{WORKER_MEMORY_BUDGET_GB:g}GB each); tokenizing in-process.",+ )+ return None++ if affordable < num_proc:+ _warn_once(+ "memory_clamp",+ f"reducing dataset_num_proc {num_proc} -> {affordable} to fit free "+ f"memory (~{WORKER_MEMORY_BUDGET_GB:g}GB per worker). Set "+ f"{NUM_PROC_ENV_VAR} to override.",+ )+ return affordable++ return num_proc+++def _auto_num_proc() -> Optional[int]:+ """Worker count to use when the caller did not ask for a specific one."""+ try:+ import psutil # noqa: F401 the memory clamp below needs it to mean anything+ except Exception:+ # No psutil means no memory reading; stay conservative.+ return None++ cpus = _usable_cpus()+ if cpus is None:+ return None+ if cpus <= 1:+ # Workers would only contend for the single core they are pinned to.+ return None++ return _clamp_by_memory(min(max(cpus // 2, 2), AUTO_NUM_PROC_CAP))+++def _serial(serial_as_none: bool) -> Optional[int]:+ """The value meaning "run in-process", encoded for the calling layer.++ At a ``map()`` call site that is ``None``, the only value ``datasets`` runs+ in-process on every supported release. At the *config* layer it is ``1``,+ because a config ``None`` is read downstream as "auto-size me" and would+ inflate a serial request; the call site turns that ``1`` back into ``None``.++ That only holds while workers are usable, hence the veto check. Where they+ are not, nothing can inflate a config ``None`` -- every auto-sizer that reads+ it vetoes too -- while ``1`` is unsafe, since only the SFT map site is+ rewritten by ``rl_replacements.py``: TRL's DPO, KTO, CPO, ORPO, Reward and+ PRM trainers hand ``args.dataset_num_proc`` straight to ``Dataset.map``,+ whose ``Pool(1)`` child re-imports the user's ``__main__`` (#3211 / #3397).+ """+ if serial_as_none:+ return None+ return None if _workers_unusable_reason() is not None else 1+++def _from_environment() -> "tuple[bool, Optional[int]]":+ """Read NUM_PROC_ENV_VAR. Returns (was_set_and_valid, value)."""+ raw = os.environ.get(NUM_PROC_ENV_VAR)+ if raw is None:+ return False, None++ text = raw.strip()+ if text.lower() in ("", "0", "none", "null", "false"):+ return True, None++ try:+ value = int(text)+ except ValueError:+ _warn_once(+ "env_invalid",+ f"{NUM_PROC_ENV_VAR}={raw!r} is not an integer, ignoring it.",+ )+ return False, None++ if value < 0:+ _warn_once(+ "env_negative",+ f"{NUM_PROC_ENV_VAR}={raw!r} is negative, ignoring it.",+ )+ return False, None+ if value <= 1:+ return True, None+ return True, value+++def environment_override() -> "tuple[bool, Optional[int]]":+ """Whether NUM_PROC_ENV_VAR decided the count, and what it asked for.++ ``(was_set_and_valid, value)``, with ``value = None`` meaning "in-process".+ Public because a caller that layers its own caps on top of this module needs+ to know whether the hatch chose the answer: the hatch is uncapped by+ contract, and an unparseable or negative value is *not* the hatch, it is+ ignored with a warning. Reading the variable directly cannot tell those+ apart.+ """+ return _from_environment()+++def get_dataset_num_proc(+ desired: Optional[int] = None, *, serial_as_none: bool = True+) -> Optional[int]:+ """Return a safe ``num_proc`` for ``Dataset.map()`` / ``Dataset.filter()``.++ ``None`` means "run in-process" -- the only value that builds no worker pool+ on every supported ``datasets`` release, since 4.x pools for any+ ``num_proc >= 1``. Everything returned is bounded by free memory, explicit+ counts included; only ``NUM_PROC_ENV_VAR`` is exempt.++ Args:+ desired: The worker count the caller asked for, or None to auto-size.+ serial_as_none: How to encode "run in-process". True at a ``map()`` call+ site, yielding ``None``. **False when writing back to a config**,+ yielding ``1``, because downstream readers+ (``dataset_utils.sft_prepare_dataset``) treat a config ``None`` as+ "auto-size me" and would inflate a user's ``1``.++ Returns:+ A worker count >= 2, or this layer's in-process sentinel (``None`` at a+ call site, ``1`` at the config layer).+ """+ # 1. The environment override wins over everything, uncapped and unvetoed,+ # so a user who knows their workload is fork-safe is never downgraded.+ env_set, env_value = _from_environment()+ if env_set:+ # In-process still has to be encoded for this layer, or+ # UNSLOTH_DATASET_NUM_PROC=0 -- the hatch the dead-worker message+ # recommends -- would inflate a config instead of removing workers.+ return _serial(serial_as_none) if env_value is None else env_value++ # 2. Workers are unusable whatever was requested; see+ # `_workers_unusable_reason` for the two refusals.+ unusable = _workers_unusable_reason()+ if unusable is not None:+ if isinstance(desired, int) and not isinstance(desired, bool) and desired > 1:+ _warn_once(+ "start_method",+ f"dataset_num_proc = {desired} cannot be used because "+ f"{unusable}. Falling back to single-process tokenization. "+ f"Set {NUM_PROC_ENV_VAR} to override.",+ )+ return _serial(serial_as_none)++ # 3. Normalise "no multiprocessing" requests. `1` is the trap: callers pass+ # it meaning "serial" and datasets >= 4.1 hands them a Pool(1).+ if isinstance(desired, int) and not isinstance(desired, bool) and desired <= 1:+ return _serial(serial_as_none)++ # 4. Auto-size when no usable request was made, then bound by memory. A+ # non-int, or a bool (an int subclass), is not a request.+ if desired is None or not isinstance(desired, int) or isinstance(desired, bool):+ num_proc = _auto_num_proc()+ else:+ num_proc = _clamp_by_memory(desired)++ if num_proc is None:+ return _serial(serial_as_none)+ return num_proc+++# The message datasets raises when a pool worker dies. It never reads the child's+# exit status, so an OOM kill, a segfault and a genuine exception all arrive as+# this one string -- which is why #2693 looks untraceable.+_WORKER_DIED = "subprocesses has abruptly died"+++def map_failure_diagnostics(num_proc: Optional[int]) -> "Iterator[None]":+ """Re-raise a dead-worker error from ``Dataset.map`` with usable context.++ Names the start method, the worker count and roughly what they cost, none of+ which survives the original message. The cause is chained.+ """+ try:+ yield+ except RuntimeError as exception:+ if _WORKER_DIED not in str(exception):+ raise++ workers = num_proc if isinstance(num_proc, int) else 1+ estimated_gb = workers * WORKER_MEMORY_BUDGET_GB+ raise RuntimeError(+ f"Unsloth: tokenization failed because a dataset worker died.\n"+ f" dataset_num_proc = {num_proc!r} "+ f"({workers} worker{'' if workers == 1 else 's'}, "+ f"start method {multiprocessing_start_method()!r})\n"+ f" Each worker holds its own copy of the tokenizer and its dataset "+ f"shard, so this run needed roughly {estimated_gb:g}GB on top of the "+ f"model. The most common cause is the out-of-memory killer.\n"+ f" Retry with {NUM_PROC_ENV_VAR}=0 for the fewest workers this path "+ f"can use, or {NUM_PROC_ENV_VAR}=<n> to choose a count. That is "+ f"in-process everywhere, though on an unsloth_zoo older than the one "+ f"that reads 1 as in-process, train_on_responses_only still forks a "+ f"single worker on a split over {ZOO_MIN_ROWS_FOR_MULTIPROC:,} rows: "+ f"a bare None there reads as 'size it for me'.\n"+ f" Original error: {exception}"+ ) from exception+++def _largest_split_rows(trainer) -> Optional[int]:+ """Rows in the biggest *sized* split ``train_on_responses_only`` will map over.++ None only when no split has a readable length at all. Unsized splits are+ skipped rather than abandoning the measurement, since sizing is per split and+ an unsized one can never use workers anyway; letting one hide a large sized+ sibling left that sibling on the uncapped auto count. ``eval_dataset`` may be+ a dict of named splits, so unpack that too.+ """+ if trainer is None:+ return None++ largest = 0+ measured = False+ for attribute in ("train_dataset", "eval_dataset"):+ dataset = getattr(trainer, attribute, None)+ if dataset is None:+ continue+ splits = list(dataset.values()) if isinstance(dataset, dict) else [dataset]+ for split in splits:+ if split is None:+ continue+ try:+ rows = len(split)+ except Exception:+ # Skip rather than let it mask a sized sibling.+ continue+ measured = True+ largest = max(largest, rows)+ return largest if measured else None+++def _zoo_auto_sizer_forks() -> bool:+ """Whether ``train_on_responses_only`` would pick workers for a bare ``None``.++ Its auto path asks stdlib ``multiprocessing``, not ``multiprocess`` -- the+ split this whole module is about. Where the two disagree, ``None`` is not+ "serial" to it, it is "size it for me", and ``datasets`` then builds that pool+ on the non-fork ``multiprocess`` context.+ """+ try:+ return _module_start_method("multiprocessing") == "fork"+ except Exception:+ return False+++def _serial_for_the_zoo(value: Optional[int]) -> Optional[int]:+ """Re-encode a serial ``None`` for a reader that decides on the other module.++ ``None`` only means "no workers" to ``train_on_responses_only`` while its own+ check refuses them too. When it would not, ``1`` is the smallest request it+ honours verbatim, and that helper now reads ``1`` as in-process; on a release+ that predates this it is a ``Pool(1)``, still one child rather than the+ ``cpu_count + 4`` its auto path would have chosen.+ """+ if value is not None or not _zoo_auto_sizer_forks():+ return value+ _warn_once(+ "start_method_split",+ "'multiprocess' and 'multiprocessing' disagree about the start method "+ f"({multiprocessing_start_method()!r} against 'fork'), so "+ "train_on_responses_only is being held to one worker rather than left to "+ f"size itself. Set {NUM_PROC_ENV_VAR} to override.",+ )+ return 1+++def resolve_responses_only_num_proc(trainer, num_proc):+ """Bound the worker count ``train_on_responses_only`` hands to ``map()``.++ ``dataset_utils.train_on_responses_only`` still auto-sizes with the uncapped+ ``min(max(cpu_count + 4, 2), 64)`` heuristic this module replaces everywhere+ else -- the shape behind issue #2693. Until that copy is wired onto this+ module the bound is applied from outside, and two properties of its API+ constrain what can be expressed:++ * **Serial is the config-layer sentinel, not the call-site one.** That helper+ reads ``None`` as "size it for me", so on ``fork`` handing it ``None``+ would *inflate* the count rather than remove it; ``1`` is the closest+ expressible request, and it is in-process on any release that reads it as+ such. Under spawn the trade flips -- each ``Pool(1)`` child re-imports+ the user's ``__main__`` (#3211 / #3397), while ``None`` is safe because its+ auto path vetoes non-fork itself. That is exactly what+ ``serial_as_none = False`` encodes, so defer to it -- then re-check with+ ``_serial_for_the_zoo``, since that veto reads the other module.+ * **An explicit count disables its per-split small-split guard.** A small+ eval split alongside a large train split then picks up workers it would not+ have had: worth it only when a split is big enough to have been+ parallelized at all, which is what the row check below establishes.+ """+ # Mirror that helper's own test, so "explicit" means the same on both sides+ # (it treats bools as auto, since type(True) is not int).+ was_auto = num_proc is None or type(num_proc) is not int+ rows = _largest_split_rows(trainer)+ small = rows is None or rows < ZOO_MIN_ROWS_FOR_MULTIPROC++ if not was_auto:+ resolved = get_dataset_num_proc(num_proc, serial_as_none = False)+ if resolved == 1 and small:+ # Serial, and every split is under the threshold, so the helper's own+ # guard runs each of them in-process, which an older unsloth_zoo+ # would not do for the 1 expressible here: reaching this with+ # UNSLOTH_DATASET_NUM_PROC=0 and a config sentinel of 1 was the+ # escape hatch still building a Pool(1) there.+ return None+ return _serial_for_the_zoo(resolved)++ if small:+ # The escape hatch must win here too.+ env_set, env_value = _from_environment()+ if env_set and env_value is not None:+ return env_value+ # Otherwise it would have gone in-process anyway, and its guard yields+ # None, which is more in-process than the 1 expressible here. Safe whatever+ # the start method: every split here is under the threshold, so its own+ # per-split guard serialises them all.+ return num_proc++ return _serial_for_the_zoo(get_dataset_num_proc(None, serial_as_none = False))diff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex a256d8545fb..af96c2f87b7 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -1436,18 +1436,34 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):extra_args += saving_check# Edit dataset_num_proc+ # The policy lives in unsloth_zoo.dataset_num_proc: it had drifted into four+ # inline copies, two wrong (stdlib `multiprocessing` asked about a start+ # method `datasets` takes from `multiprocess`, and `1` used as the serial+ # sentinel when datasets >= 4.1 builds a Pool(1) for it). The zoo rather than+ # unsloth, so generated source never imports back into its generator;+ # unsloth.dataset_num_proc is the fallback for an older zoo, and the+ # ladder is guarded so a stale generated file degrades to the caller's value.+ # serial_as_none depends on who reads the value back. Only SFT has a+ # downstream auto-sizer: unsloth_zoo.sft_prepare_dataset reads a config+ # `None` as "auto-size me", so serial has to be written as `1` there and the+ # map() call site (rl_replacements.py) turns it back into None. DPO, KTO,+ # CPO, ORPO, Reward and PRM hand args.dataset_num_proc straight to+ # Dataset.map, where nothing can inflate a None but a `1` is a Pool(1) on+ # datasets >= 4.1 -- one worker with its own tokenizer copy, on a host the+ # memory clamp had just declared too small for workers.if "dataset_num_proc" in call_args:+ _serial_as_none = "False" if trainer_file == "sft_trainer" else "True"num_proc_check = (- "import multiprocessing as _mp\n"- "if dataset_num_proc is None:\n"- " if _mp.get_start_method() != 'fork':\n"- " dataset_num_proc = None\n"- " else:\n"- " import psutil\n"- " dataset_num_proc = min(max((psutil.cpu_count() or 1)+4, 2), 64)\n"- " memory_gb_left = psutil.virtual_memory().available / (1024**3)\n"- " if memory_gb_left <= 2: dataset_num_proc = 1\n"- " else: dataset_num_proc = min(dataset_num_proc, int(memory_gb_left))\n"+ "try:\n"+ " from unsloth_zoo.dataset_num_proc import get_dataset_num_proc as _unsloth_get_dataset_num_proc\n"+ "except Exception:\n"+ " try:\n"+ " from unsloth.dataset_num_proc import get_dataset_num_proc as _unsloth_get_dataset_num_proc\n"+ " except Exception:\n"+ " _unsloth_get_dataset_num_proc = None\n"+ "if _unsloth_get_dataset_num_proc is not None:\n"+ " dataset_num_proc = _unsloth_get_dataset_num_proc("+ f"dataset_num_proc, serial_as_none = {_serial_as_none})\n")extra_args += num_proc_checkdiff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex 4ef3af6adde..1309bf2a33a 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -452,6 +452,13 @@ _WRAPPED_PACKING_SETUP = (_WARNED_MISSING_ANCHORS = set()+def _warn_once(where, message):+ if where in _WARNED_MISSING_ANCHORS:+ return+ _WARNED_MISSING_ANCHORS.add(where)+ logger.warning(message)++def _require_replace(function,old,@@ -476,13 +483,72 @@ def _require_replace(f"Unsloth: source anchor not found{detail}; the patched function is out ""of sync with this TRL / unsloth_zoo version. Please file a bug report.")- if where not in _WARNED_MISSING_ANCHORS:- _WARNED_MISSING_ANCHORS.add(where)- logger.warning(f"Unsloth: skipped an optional source edit{detail} (anchor not found).")+ _warn_once(+ where,+ f"Unsloth: skipped an optional source edit{detail} (anchor not found).",+ )return functionreturn function.replace(old, new, count)+# The one line every unsloth_zoo revision of sft_prepare_dataset ends its worker+# count on, as a regex so a renamed right-hand side still matches and the+# indentation is carried into the replacement. `git log -S` on the Zoo says this+# line last changed in Aug 2025 (#257) and has survived 24 later commits to+# dataset_utils.py, while the block around it was rewritten three times in 2026+# alone (#473, #553, #733) -- which is why it is the fallback rather than the+# primary anchor.+_ZOO_MAP_NUM_PROC_ASSIGNMENT = re.compile(+ r"^(?P<indent>[ \t]*)map_kwargs\[\"num_proc\"\][ \t]*=[ \t]*[^\n]+$",+ flags = re.MULTILINE,+)+++def _replace_or_fallback(+ function,+ old,+ new,+ *,+ fallback_pattern,+ fallback_new,+ where = "",+):+ """str.replace over a wide anchor, with a narrower anchor to fall back on.++ One literal anchor is all-or-nothing, and neither outcome is acceptable here.+ `required = True` hard-fails every SFT run on a Zoo whose text merely moved.+ `required = False` leaves the un-rewritten Zoo logic in place, and for the+ worker count that is not the no-op it looks like: the config layer writes+ "run in-process" as `args.dataset_num_proc = 1` (a config `None` means+ "auto-size me" to the Zoo), the Zoo reads that `1` as an explicit count, and+ `datasets` >= 4.1 builds a `Pool(1)` for it -- forking a tokenizer worker on+ exactly the host, or the `UNSLOTH_DATASET_NUM_PROC=0`, that asked for none.++ So: try the wide anchor, then a narrow one that survives more drift, and warn+ only when both miss. `fallback_new` is an `re.sub` template, so it can carry+ the matched indentation over with `\\g<indent>`.+ """+ if old in function:+ return function.replace(old, new, 1)++ function, applied = fallback_pattern.subn(fallback_new, function)+ if applied:+ _warn_once(+ where,+ f"Unsloth: the source block for {where} moved in this unsloth_zoo; "+ "applied the narrower anchor instead. Please file a bug report.",+ )+ return function++ _warn_once(+ where,+ f"Unsloth: skipped an optional source edit ({where}) (anchor not found); "+ "dataset tokenization may fork a worker process this host asked it not "+ "to. Please file a bug report.",+ )+ return function++# Fix tokenizer double BOSdef sft_trainer_prepare_dataset(function_name, function):if function_name != "_prepare_non_packed_dataloader" and function_name != "_prepare_dataset":@@ -552,6 +618,85 @@ def sft_trainer_prepare_dataset(function_name, function):)""",where = "sft_prepare_dataset pack_dataset call",)+ # why: the map() call site -- not the config -- is where the worker+ # count must be made safe. The Zoo copy asks stdlib `multiprocessing`+ # for a start method datasets takes from `multiprocess`, and its+ # low-memory branch yields 1, which still builds a Pool(1) on+ # datasets >= 4.1. The shared helper caps a config None instead of+ # the Zoo's uncapped `cpu_count + 4 -> 64`. Imported from the Zoo so+ # generated source never imports back into its generator;+ # unsloth.dataset_num_proc is only the fallback for an older Zoo.+ function = _replace_or_fallback(+ function,+ """if not isinstance(dataset, IterableDataset):+ import multiprocessing as _mp+ dataset_num_proc = getattr(args, "dataset_num_proc", None)+ if dataset_num_proc is None:+ if _mp.get_start_method() != 'fork':+ dataset_num_proc = None+ else:+ import psutil+ dataset_num_proc = min(max((psutil.cpu_count() or 1)+4, 2), 64)+ memory_gb_left = psutil.virtual_memory().available / (1024**3)+ if memory_gb_left <= 2:+ dataset_num_proc = 1+ else:+ dataset_num_proc = min(dataset_num_proc, int(memory_gb_left))+ map_kwargs["num_proc"] = dataset_num_proc""",+ """if not isinstance(dataset, IterableDataset):+ try:+ from unsloth_zoo.dataset_num_proc import get_dataset_num_proc as _unsloth_get_dataset_num_proc+ except ImportError:+ from unsloth.dataset_num_proc import get_dataset_num_proc as _unsloth_get_dataset_num_proc+ map_kwargs["num_proc"] = _unsloth_get_dataset_num_proc(+ getattr(args, "dataset_num_proc", None)+ )""",+ # This block is the likeliest anchor in the file to drift -- the+ # Zoo rewrote it three times in 2026 -- but its absence is not+ # harmless, so it cannot simply be optional: the config layer+ # encodes serial as `1` for this site to turn back into None, and+ # an un-rewritten Zoo hands that `1` to Dataset.map. The fallback+ # keys on the assignment the block ends with, which has not+ # changed since Aug 2025, and reads args rather than the Zoo's+ # own local so it is the same computation the block anchor above+ # installs; the Zoo's now-dead sizing runs and is discarded.+ # Hard-failing instead would break every install on a newer Zoo,+ # which is a far larger blast radius than one worker.+ fallback_pattern = _ZOO_MAP_NUM_PROC_ASSIGNMENT,+ fallback_new = r"""\g<indent>try:+\g<indent> from unsloth_zoo.dataset_num_proc import get_dataset_num_proc as _unsloth_get_dataset_num_proc+\g<indent>except ImportError:+\g<indent> from unsloth.dataset_num_proc import get_dataset_num_proc as _unsloth_get_dataset_num_proc+\g<indent>map_kwargs["num_proc"] = _unsloth_get_dataset_num_proc(+\g<indent> getattr(args, "dataset_num_proc", None)+\g<indent>)""",+ where = "sft_prepare_dataset dataset_num_proc selection",+ )+ # why: datasets never reads the child's exit status, so every worker+ # death -- OOM kill, segfault, real exception -- flattens into "One+ # of the subprocesses has abruptly died during map operation". Wrap+ # both tokenizing map() calls (count = 2: the prompt-completion and+ # plain-text branches) so the user gets the worker count, start+ # method and implied memory instead.+ function = _require_replace(+ function,+ """ with _w.catch_warnings():+ _w.filterwarnings("ignore", message=".*couldn't be hashed properly.*")""",+ """ try:+ from unsloth_zoo.dataset_num_proc import map_failure_diagnostics as _unsloth_map_diagnostics+ except ImportError:+ from unsloth.dataset_num_proc import map_failure_diagnostics as _unsloth_map_diagnostics+ with _w.catch_warnings(), _unsloth_map_diagnostics(map_kwargs.get("num_proc")):+ _w.filterwarnings("ignore", message=".*couldn't be hashed properly.*")""",+ count = 2,+ where = "sft_prepare_dataset tokenizing map() calls",+ # required = False, like the selection above: this only improves the+ # message a dead worker produces, and a diagnostic must not be able+ # to fail a training run because a Zoo release moved the line it+ # anchors on. test_zoo_sft_prepare_dataset_anchor_has_not_drifted is+ # what notices, in CI rather than in someone's run.+ required = False,+ )function = function.split("\n")function = "\n".join(" " * 4 + x for x in function)function = function.replace("def sft_prepare_dataset", "def _prepare_dataset")