Skip to content

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

Studio: read every launcher world size when resolving a step-capped run's passes (#9000)

Daniel Handef58ea63582
diff --git a/studio/backend/core/training/dataset_bounds.py b/studio/backend/core/training/dataset_bounds.py
index d8112ade869..649a43b89e4 100644
--- a/studio/backend/core/training/dataset_bounds.py
+++ b/studio/backend/core/training/dataset_bounds.py
@@ -29,28 +29,28 @@ MIN_MAX_STEPS_ROWS = 1024
# Launchers that advertise a data-parallel process count. Read as env because this
# module is torch-free and the bound is computed before any process group exists, so
# torch.distributed cannot be asked: at bound time it is almost never initialised.
-# MLX_WORLD_SIZE and the MPI pairs mirror the set routes/inference.py already trusts
-# to detect an mlx.launch, so both loaders learn their rank count the same way.
+# The MPI names routes/inference.py reads, plus the torchrun ones it does not, and a
+# looser test: it pairs each size with its rank partner because it refuses requests;
+# sizing a row bound only needs a bare size. Annotated per variable, several of which
+# are widely miscited.
WORLD_SIZE_ENV_VARS = (
- "WORLD_SIZE", # torchrun, accelerate launch, deepspeed
- "LOCAL_WORLD_SIZE", # torchrun, and the only one it sets per node
+ "WORLD_SIZE", # torchrun, accelerate launch, deepspeed. NOT set by any MPI
+ "LOCAL_WORLD_SIZE", # torchrun's --nproc-per-node; it sets WORLD_SIZE too
"MLX_WORLD_SIZE", # only mlx.launch's NCCL backend, which is CUDA-only
- "OMPI_COMM_WORLD_SIZE",
- "PMI_SIZE",
- "PMIX_SIZE",
- "MPI_WORLD_SIZE",
- "MV2_COMM_WORLD_SIZE",
+ "OMPI_COMM_WORLD_SIZE", # Open MPI / prterun, alongside OMPI_COMM_WORLD_RANK
+ "PMI_SIZE", # MPICH and Intel MPI via Hydra; srun only under --mpi=pmi2
+ "PMIX_SIZE", # nothing sets this: PMIx answers job size through PMIx_Get
+ "MPI_WORLD_SIZE", # likewise undocumented in every MPI checked
+ "MV2_COMM_WORLD_SIZE", # MVAPICH2, and only under its mpirun_rsh launcher
)
-# The count an mlx.launch on Apple silicon advertises, which is not a number in the
-# env: of its four backends only NCCL (CUDA) exports MLX_WORLD_SIZE. Ring and JACCL
-# export a path to a JSON file with one entry per rank instead, and MLX documents the
-# world size as exactly the length of that list. Without these two an mlx.launch reads
-# as one process and the MLX loader under-counts, which is the direction that recycles
-# rows, so the Apple path -- the only one MLX training actually runs on -- would keep
-# the bug this module's world size exists to fix.
+# An mlx.launch world size that is not a number in the env: of its five backends only
+# NCCL (CUDA) exports MLX_WORLD_SIZE; ring and JACCL export a path to a JSON file whose
+# outer list has one entry per rank, and that length is the world size. Without these
+# two an mlx.launch reads as one process, and under-counting recycles rows -- so the
+# Apple path, the only one MLX training runs on, would keep the bug this fixes.
WORLD_SIZE_ENV_FILES = (
- "MLX_HOSTFILE", # ring backend: one "ip:port" list per rank
- "MLX_IBV_DEVICES", # jaccl backend: the RDMA matrix, one row per rank
+ "MLX_HOSTFILE", # ring backend: a path to [["ip:port", ...], ...], one per rank
+ "MLX_IBV_DEVICES", # jaccl backend: a path to the N x N RDMA matrix, one row per rank
)
# A hostfile is a few hundred bytes per rank. Read a bounded prefix so a wrong path
# (an env var pointed at something enormous) cannot pull a file into memory; a
@@ -87,7 +87,6 @@ def _seed_int(value: Any, default: int) -> int:
def world_size_from_rank_files(environ: Any = None) -> int:
"""Ranks an mlx.launch listed in a hostfile, or 1 when there is no readable one.
- Only a list counts, and its length is the count. Anything else -- no such file, a
Either representation the rest of the repo accepts: the payload inline in the
variable, or a path to a file holding it. `unsloth_cli/_inference.py`'s
`_json_rank_count_from_env` reads the same two variables the same way, down to the
@@ -112,7 +111,11 @@ def world_size_from_rank_files(environ: Any = None) -> int:
if value.lstrip()[:1] in ("[", "{"):
payload = json.loads(value[:MAX_WORLD_SIZE_FILE_BYTES])
elif os.path.isfile(value):
- with open(value, encoding = "utf-8") as handle:
+ # Binary, so the cap really is bytes: a text read() counts
+ # CHARACTERS, so 4-byte codepoints would pull 4x the cap off disk.
+ # json.loads takes bytes; non-UTF-8 raises UnicodeDecodeError (a
+ # ValueError), caught below.
+ with open(value, "rb") as handle:
payload = json.loads(handle.read(MAX_WORLD_SIZE_FILE_BYTES))
else:
continue
@@ -141,6 +144,28 @@ def world_size_from_env(environ: Any = None) -> int:
return max(numbers, world_size_from_rank_files(source))
+def world_size_env_report(environ: Any = None) -> str:
+ """The launcher variables that are set, for a log line. Never raises.
+
+ Which variable claimed the rank count is the only thing a user can act on when
+ a run on one machine is told it makes several passes. mpirun, srun and some
+ container images leave a size variable behind, and a stale one reads as a
+ multi-rank launch here exactly as it does in the row bound.
+
+ Values are truncated: MLX_HOSTFILE legitimately carries a whole JSON payload.
+ """
+ source = os.environ if environ is None else environ
+ parts = []
+ for name in WORLD_SIZE_ENV_VARS + WORLD_SIZE_ENV_FILES:
+ try:
+ value = source.get(name)
+ except Exception: # noqa: BLE001 - a log line must not be what fails a run
+ continue
+ if value:
+ parts.append(f"{name}={str(value)[:64]}")
+ return ", ".join(parts) or "no launcher variable set"
+
+
def max_steps_dataset_rows(
max_steps: Any,
batch_size: Any,
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.py
index 32d79206d47..73b2af3eea9 100644
--- a/studio/backend/core/training/trainer.py
+++ b/studio/backend/core/training/trainer.py
@@ -89,7 +89,7 @@ from .training import (
should_use_mlx_training_backend,
)
-from .dataset_bounds import bound_dataset_rows
+from .dataset_bounds import bound_dataset_rows, world_size_env_report, world_size_from_env
logger = get_logger(__name__)
@@ -3479,7 +3479,32 @@ class UnslothTrainer:
if max_steps > 0:
try:
rows = len(train_dataset)
- world_size = max(1, int(os.environ.get("WORLD_SIZE", "1")))
+ # Every launcher variable, not WORLD_SIZE alone: no MPI sets it (Open
+ # MPI uses OMPI_COMM_WORLD_SIZE, Hydra/Intel MPI PMI_SIZE, mlx.launch's
+ # CUDA-only NCCL backend MLX_WORLD_SIZE), LOCAL_WORLD_SIZE is defensive
+ # since torchrun sets both and the max prefers the global count. Reading
+ # one variable calls an mpirun launch single-process and engages a view
+ # that re-tokenizes every extra pass; it also raises on junk like
+ # int("auto"), leaving resolved_epochs None so the gate reads inf and
+ # kills the feature. Env-only, deliberately NOT worker.py's
+ # _data_parallel_world_size, which also counts visible CUDA devices:
+ # that bounds a row subset where over-counting is free, this feeds a
+ # veto where both directions are wrong. Studio's multi-GPU load is
+ # device_map="balanced", model-parallel to transformers with _n_gpu = 1,
+ # so a balanced 4-GPU run draws one GPU's rows per step and counting
+ # devices would report 4x the passes, vetoing a qualifying run.
+ world_size = world_size_from_env()
+ if world_size > 1:
+ # Say which variable said so: a stale size from an earlier mpirun
+ # or an HPC container image reads as a multi-rank launch on a
+ # one-process machine, and the only symptom is this run being told
+ # it makes several passes. The row bound already trusts the same
+ # variables; what was missing was a way to see them.
+ logger.info(
+ f"Launcher environment reports {world_size} data-parallel "
+ f"processes ({world_size_env_report()}); a step-capped run "
+ f"consumes that many times the rows per step\n"
+ )
per_step = (
int(config_args.get("per_device_train_batch_size", 1))
* int(config_args.get("gradient_accumulation_steps", 1))
diff --git a/studio/backend/tests/test_online_tokenization_wiring.py b/studio/backend/tests/test_online_tokenization_wiring.py
index d119d4228e5..721a334c638 100644
--- a/studio/backend/tests/test_online_tokenization_wiring.py
+++ b/studio/backend/tests/test_online_tokenization_wiring.py
@@ -12,6 +12,7 @@ real method, because "silently takes the old path" is a claim about side effects
"""
import contextlib
+import json
import sys
from types import SimpleNamespace
@@ -80,6 +81,31 @@ _configure = UnslothTrainer._configure_online_tokenization
ROWS = MIN_ROWS_FOR_ONLINE + 5
+def _single_process_launch(monkeypatch):
+ """Clear every launcher variable, so a run reads as Studio's own launch.
+
+ Same helper and same constant tuples as ``test_training_preflight.py``: the
+ two must not disagree about what counts as a launcher, or one file starts
+ passing on a set of variables the other never clears.
+ """
+ from core.training.dataset_bounds import WORLD_SIZE_ENV_FILES, WORLD_SIZE_ENV_VARS
+ for name in WORLD_SIZE_ENV_VARS + WORLD_SIZE_ENV_FILES:
+ monkeypatch.delenv(name, raising = False)
+
+
[email protected](autouse = True)
+def _no_ambient_launcher(monkeypatch):
+ """Every case in this file starts from a single-process launch.
+
+ The pass count is read out of the environment, so without this a case's
+ result depends on whatever the runner's shell happens to export, and on
+ whichever earlier test last set one of these. Both were live here: the file
+ already sets ``WORLD_SIZE`` in one test, and pytest's monkeypatch undo only
+ covers variables a test itself touched.
+ """
+ _single_process_launch(monkeypatch)
+
+
class _Tokenizer:
bos_token = "<s>"
chat_template = "{{ messages }}"
@@ -149,6 +175,15 @@ def _run(
"utils.datasets.online_tokenization.trl_supports_skip_prepare_dataset",
lambda: True,
)
+ # Pin the worker count for the same reason: resolve_worker_count sizes itself from
+ # CPU affinity and the cgroup quota and returns 0 below MIN_ONLINE_WORKERS, vetoing
+ # before the pass count is compared. On a two-core runner every case here asserted
+ # about the runner, on the wrong veto reason. The worker gate is covered by
+ # test_online_tokenization.py.
+ monkeypatch.setattr(
+ "utils.datasets.online_tokenization.resolve_worker_count",
+ lambda desired = None: 4,
+ )
trainer = _fake_self(**(self_overrides or {}))
config_args = _config_args(**(config_overrides or {}))
wrapper = {"dataset": _dataset()} if wrapper is None else wrapper
@@ -414,6 +449,161 @@ def test_world_size_scales_the_rows_a_step_consumes(monkeypatch):
_assert_untouched(config_args, wrapper, trainer, original)
+# 200 steps x 2 x 4 = 1600 rows per replica over a 10_005-row split: 0.16 passes on
+# one process, 1.28 on eight. Every launcher below advertises the same eight, so these
+# cases differ from the control at the bottom only in whether the variable is read.
+_EIGHT_RANK_STEPS = 200
+
+
+def _eight_ranks(
+ monkeypatch,
+ expect_enabled = False,
+ **env,
+):
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+ original = _dataset()
+ decision, config_args, wrapper, trainer = _run(
+ monkeypatch,
+ wrapper = {"dataset": original},
+ config_overrides = {"max_steps": _EIGHT_RANK_STEPS},
+ )
+ if expect_enabled:
+ assert decision.enabled, decision.reason
+ return decision
+ assert not decision.enabled and "one pass" in decision.reason, decision.reason
+ _assert_untouched(config_args, wrapper, trainer, original)
+ return decision
+
+
+def test_an_mpirun_launch_scales_the_rows_a_step_consumes(monkeypatch):
+ """mpirun never sets WORLD_SIZE. Reading that one variable alone calls an
+ eight-rank run single-process and engages a view that re-tokenizes on every
+ extra pass."""
+ _eight_ranks(monkeypatch, OMPI_COMM_WORLD_SIZE = "8")
+
+
+def test_a_per_node_torchrun_scales_the_rows_a_step_consumes(monkeypatch):
+ """torchrun sets WORLD_SIZE and LOCAL_WORLD_SIZE both, so this is the defensive
+ case: an environment that kept the per-node count and lost the global one still
+ has to be counted rather than read as a single process."""
+ _eight_ranks(monkeypatch, LOCAL_WORLD_SIZE = "8")
+
+
+def test_an_mlx_hostfile_scales_the_rows_a_step_consumes(monkeypatch, tmp_path):
+ """mlx.launch's ring backend advertises its ranks as a JSON file rather than a
+ number; its NCCL backend is CUDA-only, so this path is reachable.
+
+ Written in the shape the ring backend really uses: the outer list has one entry
+ per rank, and each entry is that rank's own list of addresses, because a pair of
+ peers may hold several connections."""
+ hostfile = tmp_path / "hosts.json"
+ hostfile.write_text(
+ json.dumps([[f"10.0.0.{i}:9000", f"10.0.0.{i}:9001"] for i in range(8)]),
+ encoding = "utf-8",
+ )
+ _eight_ranks(monkeypatch, MLX_HOSTFILE = str(hostfile))
+
+
+def test_an_inline_hosts_payload_scales_the_rows_a_step_consumes(monkeypatch):
+ """The same variable also carries the payload inline, in the {"hosts": [...]}
+ object form `unsloth_cli/_inference.py` accepts."""
+ payload = json.dumps({"hosts": [f"10.0.0.{i}:9000" for i in range(8)]})
+ _eight_ranks(monkeypatch, MLX_HOSTFILE = payload)
+
+
+# Only values that RAISE: the old max(1, int(...)) already answered 1 for "0" and
+# "-4", so those would pass against the bug and belong in dataset_bounds' own tests.
[email protected]("junk", ["auto", "", "eight"])
+def test_a_junk_world_size_no_longer_disables_online_tokenization(monkeypatch, junk):
+ """The direction this used to fail in was not the obvious one.
+
+ `int("auto")` raises, the enclosing `except` leaves the pass count unresolved,
+ and an unresolved step-capped run reads as infinite passes, so a launcher that
+ exported a non-numeric WORLD_SIZE silently turned the feature OFF on a run that
+ qualifies. Unusable values are a single process, which is what this host is.
+ """
+ monkeypatch.setenv("WORLD_SIZE", junk)
+ original = _dataset()
+ decision, config_args, wrapper, trainer = _run(
+ monkeypatch,
+ wrapper = {"dataset": original},
+ config_overrides = {"max_steps": 30},
+ )
+ assert decision.enabled, decision.reason
+ assert wrapper["dataset"] is not original
+ assert config_args["dataset_kwargs"] == {"skip_prepare_dataset": True}
+
+
+def test_the_resolved_pass_count_handed_to_the_gate_is_the_arithmetic(monkeypatch):
+ """The veto only sees a number, so assert the number rather than its verdict:
+ a wrong world size that still lands on the same side of 1.0 is a bug that has
+ not surfaced yet."""
+ monkeypatch.setenv("OMPI_COMM_WORLD_SIZE", "8")
+ seen: dict = {}
+ import utils.datasets.online_tokenization as online_mod
+
+ real = online_mod.decide_online_tokenization
+
+ def _record(**kwargs):
+ seen.update(kwargs)
+ return real(**kwargs)
+
+ monkeypatch.setattr(online_mod, "decide_online_tokenization", _record)
+ _run(
+ monkeypatch,
+ config_overrides = {"max_steps": _EIGHT_RANK_STEPS},
+ )
+ expected = (_EIGHT_RANK_STEPS * 2 * 4 * 8) / ROWS
+ assert seen["resolved_max_steps_epochs"] == pytest.approx(expected)
+ assert seen["resolved_max_steps_epochs"] > 1.0
+
+
+def _captured_logger(monkeypatch):
+ """Record what the trainer logs, without depending on the logging config."""
+ lines: list = []
+
+ class _Recorder:
+ def info(self, message, *args, **kwargs):
+ lines.append(str(message))
+
+ warning = error = debug = info
+
+ import core.training.trainer as trainer_mod
+
+ monkeypatch.setattr(trainer_mod, "logger", _Recorder())
+ return lines
+
+
+def test_a_multi_rank_launch_names_the_variable_that_claimed_the_ranks(monkeypatch):
+ """A size variable left behind by an earlier mpirun, or inherited from an
+ interactive srun, reads here as a multi-rank launch on a machine running one
+ process, and its whole visible effect is this run being told it makes several
+ passes. Name the variable so that verdict is not silent. The merged row bound
+ reads the same variables, so the environment is trusted either way."""
+ lines = _captured_logger(monkeypatch)
+ _eight_ranks(monkeypatch, OMPI_COMM_WORLD_SIZE = "8")
+ reported = [line for line in lines if "data-parallel processes" in line]
+ assert len(reported) == 1, lines
+ assert "8 data-parallel processes" in reported[0]
+ assert "OMPI_COMM_WORLD_SIZE=8" in reported[0]
+
+
+def test_a_single_process_launch_says_nothing_about_launchers(monkeypatch):
+ """The report is for the surprising case only; a normal run must not grow a
+ line about a world size of one."""
+ lines = _captured_logger(monkeypatch)
+ _eight_ranks(monkeypatch, expect_enabled = True)
+ assert not [line for line in lines if "data-parallel processes" in line], lines
+
+
+def test_a_single_process_launch_still_qualifies(monkeypatch):
+ """The control for every case above: same steps, same split, no launcher
+ variable at all. Counting a rank that is not there would veto this run."""
+ decision = _eight_ranks(monkeypatch, expect_enabled = True)
+ assert decision.prewarm_batches > 0
+
+
# ------------------------------------------------------------- the prewarm barrier
diff --git a/studio/backend/tests/test_training_preflight.py b/studio/backend/tests/test_training_preflight.py
index 53e29811b74..bb229954343 100644
--- a/studio/backend/tests/test_training_preflight.py
+++ b/studio/backend/tests/test_training_preflight.py
@@ -807,6 +807,65 @@ def test_world_size_comes_from_an_mlx_launch_hostfile(tmp_path, monkeypatch):
assert world_size_from_rank_files({}) == 1
+def test_a_rank_file_read_is_capped_in_bytes_not_characters(tmp_path):
+ """The cap has to bound what comes off the disk, whatever the file holds.
+
+ A text-mode ``read(n)`` counts CHARACTERS, so a file of 4-byte codepoints
+ would pull four times ``MAX_WORLD_SIZE_FILE_BYTES`` into memory on a variable
+ that names an arbitrary path. Read in binary and the constant means what it
+ says; ``json.loads`` takes bytes, and non-UTF-8 raises ``UnicodeDecodeError``,
+ which is a ``ValueError`` and already discarded.
+ """
+ from core.training.dataset_bounds import (
+ MAX_WORLD_SIZE_FILE_BYTES,
+ world_size_from_rank_files,
+ )
+
+ # Sized so the readings disagree: under the cap in characters, over it in bytes.
+ # A text handle reads it whole and answers 8; binary truncates to one process,
+ # the safe direction, and reading the whole file is what the cap forbids.
+ wide = tmp_path / "wide.json"
+ filler = "\U0001f600" * (MAX_WORLD_SIZE_FILE_BYTES // 3) # 4 bytes per character
+ hosts = [filler] + [f"10.0.0.{rank}:5000" for rank in range(7)]
+ # ensure_ascii would escape the codepoints back to ASCII and make the two
+ # readings agree, which is what this test needs them not to do.
+ wide.write_text(json.dumps(hosts, ensure_ascii = False), encoding = "utf-8")
+ assert len(wide.read_text(encoding = "utf-8")) < MAX_WORLD_SIZE_FILE_BYTES
+ assert wide.stat().st_size > MAX_WORLD_SIZE_FILE_BYTES
+ assert world_size_from_rank_files({"MLX_HOSTFILE": str(wide)}) == 1
+
+ # Non-UTF-8 bytes must be discarded, not raised.
+ invalid = tmp_path / "invalid.bin"
+ invalid.write_bytes(b'["\xff\xfe10.0.0.1:5000"]')
+ assert world_size_from_rank_files({"MLX_HOSTFILE": str(invalid)}) == 1
+
+
+def test_the_launcher_env_report_names_the_variable_that_claimed_the_ranks():
+ """A stale size variable is otherwise invisible.
+
+ The report exists so a user whose single-machine run is told it makes several
+ passes can see which variable said so. It must never raise and never grow
+ without bound: MLX_HOSTFILE legitimately carries a whole JSON payload.
+ """
+ from core.training.dataset_bounds import world_size_env_report
+
+ assert world_size_env_report({}) == "no launcher variable set"
+ assert world_size_env_report({"WORLD_SIZE": ""}) == "no launcher variable set"
+ assert world_size_env_report({"NOT_A_LAUNCHER": "8"}) == "no launcher variable set"
+
+ report = world_size_env_report({"OMPI_COMM_WORLD_SIZE": "8", "WORLD_SIZE": "2"})
+ assert "OMPI_COMM_WORLD_SIZE=8" in report and "WORLD_SIZE=2" in report
+
+ long_payload = world_size_env_report({"MLX_HOSTFILE": json.dumps(["h"] * 500)})
+ assert len(long_payload) < 200
+
+ class _Hostile:
+ def get(self, name):
+ raise RuntimeError("environment lookup exploded")
+
+ assert world_size_env_report(_Hostile()) == "no launcher variable set"
+
+
def test_effective_packing_decides_the_opt_out():
from core.training.dataset_bounds import effective_packing, max_train_rows_for_config
diff --git a/unsloth/utils/packing.py b/unsloth/utils/packing.py
index 26963f991d6..1e1d8155b4a 100644
--- a/unsloth/utils/packing.py
+++ b/unsloth/utils/packing.py
@@ -169,10 +169,14 @@ def enable_sample_packing(
if isinstance(ids, Iterable):
seq_lengths.append(len(ids))
if seq_lengths:
- # Boundary labels are NOT masked here: unsloth_zoo's
+ # Boundary labels are NOT masked here. unsloth_zoo's
# _unsloth_get_batch_samples counts num_items_in_batch off this batch and
- # already subtracts the N-1 boundary targets, so masking here would deduct
- # twice on TRL < 0.24 (no pre-masking). The guard runs in the forward.
+ # discounts the N-1 boundary targets itself, idempotently: it zeroes those
+ # slots rather than subtracting a constant, so the count is unaffected by
+ # upstream masking (TRL >= 0.24's labels[position_ids == 0] = -100,
+ # completion-only masking, assistant_masks). Masking here would be harmless
+ # to the count; labels are left alone because the guard that needs these
+ # positions runs in the forward, off packed_seq_lengths.
batch["packed_seq_lengths"] = torch.tensor(seq_lengths, dtype = torch.int32)
if "attention_mask" in batch:
batch.pop("attention_mask")
@@ -216,7 +220,8 @@ def enable_padding_free_metadata(model, trainer):
batch = original_torch_call(examples)
if seq_lengths:
# Labels left alone for the same reason as enable_sample_packing:
- # num_items_in_batch is counted off this batch.
+ # num_items_in_batch is counted off this batch, and the zoo's discount of the
+ # boundary targets is idempotent, so masked slots do not change the count.
batch["packed_seq_lengths"] = torch.tensor(
seq_lengths,
dtype = torch.int32,