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: size the max_steps row bound for the data-parallel world (#8958)

Daniel Han0424d9c16ed5
diff --git a/studio/backend/core/training/dataset_bounds.py b/studio/backend/core/training/dataset_bounds.py
index 13a70e4e177..d8112ade869 100644
--- a/studio/backend/core/training/dataset_bounds.py
+++ b/studio/backend/core/training/dataset_bounds.py
@@ -26,6 +26,36 @@ from typing import Any, Optional
MAX_STEPS_ROW_SLACK = 4
# Below this a subset is small enough to skew a run for no meaningful saving.
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.
+WORLD_SIZE_ENV_VARS = (
+ "WORLD_SIZE", # torchrun, accelerate launch, deepspeed
+ "LOCAL_WORLD_SIZE", # torchrun, and the only one it sets per node
+ "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",
+)
+# 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.
+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
+)
+# 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
+# truncated read fails to parse as JSON and is discarded, which is the safe answer.
+MAX_WORLD_SIZE_FILE_BYTES = 1 << 20
# Written into a run's output directory at its first start; read back on resume.
# Its absence is the signal that a checkpoint predates the bound.
ROW_BOUND_MARKER_FILE = "unsloth_row_bound.json"
@@ -54,18 +84,88 @@ def _seed_int(value: Any, default: int) -> int:
return number if number >= 0 else default
+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
+ {"hosts": [...]} object form, so the two must not disagree about how many ranks a
+ launch has.
+
+ Only a list of ranks counts, and its length is the count. Anything else -- no such
+ file, a truncated or malformed payload, some other object, an empty ring hostfile
+ (which is what mlx.launch writes for a single host) -- reads as 1, the count of
+ Studio's own launch. Never raises: a row bound must not be what fails a run.
+
+ A path must name a regular file. mlx.launch writes a temp file, and opening
+ whatever else a variable happens to name could block a run forever on a fifo.
+ """
+ source = os.environ if environ is None else environ
+ sizes = [1]
+ for name in WORLD_SIZE_ENV_FILES:
+ try:
+ value = source.get(name)
+ if not value:
+ continue
+ 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:
+ payload = json.loads(handle.read(MAX_WORLD_SIZE_FILE_BYTES))
+ else:
+ continue
+ except (OSError, UnicodeError, ValueError, TypeError, AttributeError):
+ continue
+ if isinstance(payload, dict):
+ payload = payload.get("hosts")
+ if isinstance(payload, list):
+ sizes.append(len(payload))
+ return max(sizes)
+
+
+def world_size_from_env(environ: Any = None) -> int:
+ """Data-parallel processes the launcher advertises, or 1 when none does.
+
+ The largest wins: a torchrun launch sets WORLD_SIZE and LOCAL_WORLD_SIZE, and on
+ one node they agree, while a multi-node one must be sized by the global count.
+ Anything unusable (unset, empty, a stray "auto", 0, negative) reads as 1, which
+ is the count Studio's own single-process launch has.
+
+ Some launchers advertise the count as a file rather than a number; see
+ WORLD_SIZE_ENV_FILES.
+ """
+ source = os.environ if environ is None else environ
+ numbers = max(_positive_int(source.get(name), 1) for name in WORLD_SIZE_ENV_VARS)
+ return max(numbers, world_size_from_rank_files(source))
+
+
def max_steps_dataset_rows(
- max_steps: Any, batch_size: Any, gradient_accumulation_steps: Any
+ max_steps: Any,
+ batch_size: Any,
+ gradient_accumulation_steps: Any,
+ *,
+ world_size: Any = None,
) -> Optional[int]:
"""Rows a max_steps run can reach, or None when it is unbounded.
- A step draws batch_size * gradient_accumulation_steps rows.
+ A step draws batch_size * gradient_accumulation_steps rows on every data-parallel
+ replica, so world_size times that in total: DDP hands each rank its own shard of
+ the step, and DataParallel splits the batch over the visible devices. Leaving the
+ factor out spends the whole slack on rank count alone, and from four replicas up
+ a run re-reads rows it has already trained on.
+
+ world_size is what the caller established (the CUDA worker also counts visible
+ CUDA devices, which env cannot report); anything unusable falls back to the
+ launcher env, and that falls back to 1, which is Studio's own launch.
"""
steps = _positive_int(max_steps, 0)
if steps <= 0:
return None
+ replicas = _positive_int(world_size, 0) or world_size_from_env()
per_step = _positive_int(batch_size, 1) * _positive_int(gradient_accumulation_steps, 1)
- return max(MIN_MAX_STEPS_ROWS, steps * per_step * MAX_STEPS_ROW_SLACK)
+ return max(MIN_MAX_STEPS_ROWS, steps * per_step * replicas * MAX_STEPS_ROW_SLACK)
def effective_packing(config: dict, branch_never_packs: bool = False) -> bool:
@@ -88,11 +188,20 @@ def effective_packing(config: dict, branch_never_packs: bool = False) -> bool:
return not branch_never_packs
-def max_train_rows_for_config(config: dict, branch_never_packs: bool = False) -> Optional[int]:
+def max_train_rows_for_config(
+ config: dict,
+ branch_never_packs: bool = False,
+ *,
+ world_size: Any = None,
+) -> Optional[int]:
"""The bound for a worker config, or None when the run is not bounded.
Streaming and an explicit train-split range opt out further down, in the
loaders, where those values live.
+
+ world_size is not read from the config: it belongs to the launch, not to what
+ the user configured, and a stale one carried across a spawn would size the
+ subset for the wrong machine.
"""
if effective_packing(config, branch_never_packs = branch_never_packs):
return None
@@ -100,6 +209,7 @@ def max_train_rows_for_config(config: dict, branch_never_packs: bool = False) ->
config.get("max_steps", 0) or 0,
config.get("batch_size", 2),
config.get("gradient_accumulation_steps", 4),
+ world_size = world_size,
)
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.py
index e41d86bcb82..a3f1f4a1601 100644
--- a/studio/backend/core/training/worker.py
+++ b/studio/backend/core/training/worker.py
@@ -62,6 +62,7 @@ from core.training.dataset_bounds import (
max_train_rows_for_config,
record_row_bound,
row_bound_for_resume,
+ world_size_from_env,
)
from utils.training_runs import build_default_output_dir_name
from utils.wheel_utils import (
@@ -80,6 +81,50 @@ def _output_dir_from_resume_checkpoint(resume_from_checkpoint: str | None) -> st
return str(path.parent if path.name.startswith("checkpoint-") else path)
+def _data_parallel_world_size() -> int:
+ """Replicas that each draw a full batch of rows per optimizer step.
+
+ Two things multiply row consumption and only one of them is in the env: a
+ distributed launch (torchrun, accelerate, mpirun, mlx.launch), and plain
+ DataParallel, which transformers reaches for whenever a non-distributed run
+ sees more than one CUDA device -- it sets n_gpu to the visible device count and
+ scales the train batch by it, so an extra visible GPU eats rows exactly as an
+ extra rank does. XPU and MPS stay at one device there, so only CUDA counts.
+
+ The larger of the two, never the sum: a distributed run forces n_gpu to 1, and a
+ model-parallel one (device_map="balanced", which is what Studio's own multi-GPU
+ load uses) forces it to 1 as well. Rounding up when the model turns out to be
+ sharded rather than replicated only tokenizes a larger subset of a corpus this
+ bound is orders of magnitude below anyway; rounding down means the run silently
+ re-reads rows it has already trained on.
+
+ torch is read out of sys.modules rather than imported: this also runs on the MLX
+ path, on hosts where no torch exists, and a process that never imported it has
+ no CUDA devices to count either.
+ """
+ sizes = [world_size_from_env()]
+ torch_module = sys.modules.get("torch")
+ if torch_module is not None:
+ try:
+ distributed = getattr(torch_module, "distributed", None)
+ if (
+ distributed is not None
+ and distributed.is_available()
+ and distributed.is_initialized()
+ ):
+ sizes.append(int(distributed.get_world_size()))
+ except Exception:
+ # A stubbed or half-initialised torch.distributed must not fail a run.
+ pass
+ try:
+ sizes.append(int(torch_module.cuda.device_count()))
+ except Exception:
+ # A CPU-only build answers 0, which the filter below drops; a broken or
+ # stubbed torch.cuda raises instead, and that must not fail a run either.
+ pass
+ return max([size for size in sizes if size > 0], default = 1)
+
+
def _model_local_files_only(config: dict) -> bool:
return bool(config.get("model_snapshot_path"))
@@ -2796,8 +2841,12 @@ def _run_mlx_training(event_queue, stop_queue, config):
mlx_raw_text_mode = (
training_type == "Continued Pretraining" or config.get("format_type") == "raw"
)
+ # An mlx.launch run shards the batch across its processes the same way DDP does,
+ # and it advertises the count in the env this reads.
mlx_max_train_rows = max_train_rows_for_config(
- config, branch_never_packs = is_vlm and not mlx_raw_text_mode
+ config,
+ branch_never_packs = is_vlm and not mlx_raw_text_mode,
+ world_size = _data_parallel_world_size(),
)
# MLXTrainer resumes by jumping a batch cursor into a schedule rebuilt from
# whatever dataset it is handed, so bounding a checkpoint written without one
@@ -4235,7 +4284,14 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
bool(getattr(trainer, "is_vlm", False) or getattr(trainer, "is_audio_vlm", False))
and not raw_text_mode
)
- max_train_rows = max_train_rows_for_config(config, branch_never_packs = branch_never_packs)
+ # Every replica draws its own batch per step, so the subset has to cover all of
+ # them; sized here rather than in the config because it is a property of this
+ # machine's launch. Model probing is done, so torch and the GPU mask are settled.
+ max_train_rows = max_train_rows_for_config(
+ config,
+ branch_never_packs = branch_never_packs,
+ world_size = _data_parallel_world_size(),
+ )
# A resume trains on the rows its first start chose, read back from the marker
# beside the checkpoints. No marker means the checkpoint predates the bound and
# trained on the whole dataset; since the trainer fast-forwards by batch count
@@ -4248,6 +4304,16 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
"Resuming with the row bound recorded at the original start "
f"({resumed_rows} rows) instead of {max_train_rows}\n"
)
+ if resumed_rows and max_train_rows and resumed_rows < max_train_rows:
+ # Sized for fewer replicas than this machine has: the recorded subset
+ # is what the run trained on and re-deriving it would continue on
+ # unrelated rows, so it stays, but say that the extra ranks may reach
+ # the end of it and start over.
+ logger.info(
+ "That subset was sized for a smaller data-parallel world than this "
+ "one, so the added replicas may re-read rows; start a new run "
+ "instead of resuming to size it for this machine\n"
+ )
max_train_rows = resumed_rows
# ── 4b. Load and format dataset (LLM helper may use VRAM briefly) ──
diff --git a/studio/backend/tests/test_training_preflight.py b/studio/backend/tests/test_training_preflight.py
index 3ab061e5f3a..53e29811b74 100644
--- a/studio/backend/tests/test_training_preflight.py
+++ b/studio/backend/tests/test_training_preflight.py
@@ -618,6 +618,195 @@ def test_max_steps_dataset_rows_survives_unusable_numbers():
assert max_steps_dataset_rows(10**9, 2, 4) == 10**9 * 8 * 4
+def _single_process_launch(monkeypatch):
+ """Clear every launcher variable, so a bound reads as Studio's own launch."""
+ 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)
+
+
+def test_max_steps_dataset_rows_scales_with_world_size(monkeypatch):
+ from core.training.dataset_bounds import (
+ MAX_STEPS_ROW_SLACK,
+ MIN_MAX_STEPS_ROWS,
+ max_steps_dataset_rows,
+ )
+
+ _single_process_launch(monkeypatch)
+
+ # One process is what the bound has always assumed: identical to omitting it.
+ assert max_steps_dataset_rows(2000, 8, 16, world_size = 1) == max_steps_dataset_rows(2000, 8, 16)
+ assert max_steps_dataset_rows(2000, 8, 16) == 2000 * 8 * 16 * MAX_STEPS_ROW_SLACK
+ assert max_steps_dataset_rows(30, 2, 4, world_size = 1) == MIN_MAX_STEPS_ROWS
+
+ # Every replica draws its own batch per step, so the subset grows with them.
+ for world_size in (2, 4, 8):
+ assert (
+ max_steps_dataset_rows(2000, 8, 16, world_size = world_size)
+ == 2000 * 8 * 16 * world_size * MAX_STEPS_ROW_SLACK
+ )
+ # The slack is what stops a run recycling rows, so it must survive the scaling.
+ rows = max_steps_dataset_rows(60, 2, 4, world_size = world_size)
+ assert rows >= 60 * 2 * 4 * world_size * MAX_STEPS_ROW_SLACK
+
+ # An unbounded run stays unbounded however many replicas read it.
+ assert max_steps_dataset_rows(0, 2, 4, world_size = 8) is None
+
+
+def test_max_steps_dataset_rows_survives_an_unusable_world_size(monkeypatch):
+ from core.training.dataset_bounds import MIN_MAX_STEPS_ROWS, max_steps_dataset_rows
+
+ _single_process_launch(monkeypatch)
+
+ # A launcher that reports nothing, or nonsense, must read as one process rather
+ # than raise or collapse the subset to nothing.
+ baseline = max_steps_dataset_rows(2000, 8, 16)
+ for world_size in (None, 0, -4, "", "auto", "not a number", float("inf"), object()):
+ assert max_steps_dataset_rows(2000, 8, 16, world_size = world_size) == baseline
+ assert max_steps_dataset_rows(30, 2, 4, world_size = None) == MIN_MAX_STEPS_ROWS
+
+ # A string count is what an env carries, and it still has to scale.
+ assert max_steps_dataset_rows(2000, 8, 16, world_size = "4") == baseline * 4
+
+
+def test_world_size_comes_from_the_launcher_env(monkeypatch):
+ from core.training.dataset_bounds import (
+ MAX_STEPS_ROW_SLACK,
+ max_steps_dataset_rows,
+ world_size_from_env,
+ )
+
+ _single_process_launch(monkeypatch)
+ assert world_size_from_env() == 1
+
+ # torchrun and accelerate set WORLD_SIZE; mlx.launch and mpirun set their own.
+ for name, size in (("WORLD_SIZE", 4), ("MLX_WORLD_SIZE", 2), ("OMPI_COMM_WORLD_SIZE", 8)):
+ _single_process_launch(monkeypatch)
+ monkeypatch.setenv(name, str(size))
+ assert world_size_from_env() == size
+ assert max_steps_dataset_rows(2000, 8, 16) == 2000 * 8 * 16 * size * MAX_STEPS_ROW_SLACK
+
+ # A multi-node torchrun sets both, and the global count is the one that sizes rows.
+ _single_process_launch(monkeypatch)
+ monkeypatch.setenv("WORLD_SIZE", "16")
+ monkeypatch.setenv("LOCAL_WORLD_SIZE", "8")
+ assert world_size_from_env() == 16
+
+ # Junk in the env reads as a single process, not as a crash.
+ for junk in ("", "auto", "0", "-2", "3.5"):
+ _single_process_launch(monkeypatch)
+ monkeypatch.setenv("WORLD_SIZE", junk)
+ assert world_size_from_env() == 1
+
+ # An explicit count is the caller's own detection and outranks the env, which
+ # cannot see the visible CUDA devices DataParallel would also split a batch over.
+ _single_process_launch(monkeypatch)
+ monkeypatch.setenv("WORLD_SIZE", "2")
+ assert max_steps_dataset_rows(2000, 8, 16, world_size = 8) == 2000 * 8 * 16 * 8 * (
+ MAX_STEPS_ROW_SLACK
+ )
+ # A mapping can be passed instead of the process env.
+ assert world_size_from_env({"WORLD_SIZE": "4"}) == 4
+ assert world_size_from_env({}) == 1
+
+
+def test_world_size_comes_from_an_mlx_launch_hostfile(tmp_path, monkeypatch):
+ """An Apple silicon mlx.launch advertises its ranks as a file, not a number.
+
+ Of mlx.launch's four backends only NCCL (CUDA) exports MLX_WORLD_SIZE. Ring and
+ JACCL -- everything a Mac runs -- export a path to a JSON file with one entry per
+ rank, so reading only the numeric variables sizes a four-way launch as one process
+ and the run re-reads rows it has already trained on.
+ """
+ from core.training.dataset_bounds import (
+ MAX_STEPS_ROW_SLACK,
+ max_steps_dataset_rows,
+ world_size_from_env,
+ world_size_from_rank_files,
+ )
+
+ _single_process_launch(monkeypatch)
+ assert world_size_from_rank_files() == 1
+
+ # The ring backend writes one "ip:port" list per rank; mlx.launch --hostfile ring-4.
+ ring = tmp_path / "ring.json"
+ ring.write_text(json.dumps([[f"10.0.0.{rank}:5000"] for rank in range(4)]), encoding = "utf-8")
+ _single_process_launch(monkeypatch)
+ monkeypatch.setenv("MLX_RANK", "0")
+ monkeypatch.setenv("MLX_HOSTFILE", str(ring))
+ assert world_size_from_env() == 4
+ assert max_steps_dataset_rows(60, 2, 4) == 60 * 2 * 4 * 4 * MAX_STEPS_ROW_SLACK
+
+ # The jaccl backend writes the RDMA matrix, one row per rank.
+ rdma = tmp_path / "rdma.json"
+ rdma.write_text(
+ json.dumps([[None if a == b else "mlx5_0" for b in range(3)] for a in range(3)]),
+ encoding = "utf-8",
+ )
+ _single_process_launch(monkeypatch)
+ monkeypatch.setenv("MLX_IBV_DEVICES", str(rdma))
+ assert world_size_from_env() == 3
+
+ # A single host is not a distributed launch: mlx.launch writes an empty hostfile.
+ empty = tmp_path / "empty.json"
+ empty.write_text("", encoding = "utf-8")
+ _single_process_launch(monkeypatch)
+ monkeypatch.setenv("MLX_HOSTFILE", str(empty))
+ assert world_size_from_env() == 1
+
+ # The payload can also be inline, which is how unsloth_cli/_inference.py's
+ # _json_rank_count_from_env reads these two, including the {"hosts": [...]} form.
+ for inline, expected in (
+ (json.dumps([[f"10.0.0.{rank}:5000"] for rank in range(6)]), 6),
+ (json.dumps({"hosts": ["a", "b", "c"]}), 3),
+ (" " + json.dumps([["a"], ["b"]]), 2),
+ (json.dumps([]), 1),
+ ):
+ _single_process_launch(monkeypatch)
+ monkeypatch.setenv("MLX_HOSTFILE", inline)
+ assert world_size_from_env() == expected
+
+ # Nothing about a hostfile may fail a run: unreadable, not JSON, not a list.
+ bad_json = tmp_path / "bad.json"
+ bad_json.write_text('[["10.0.0.1:5000"],', encoding = "utf-8")
+ not_a_list = tmp_path / "object.json"
+ not_a_list.write_text(json.dumps({"hosts": 4}), encoding = "utf-8")
+ a_directory = tmp_path / "adir"
+ a_directory.mkdir()
+ for value in (
+ str(tmp_path / "missing.json"),
+ str(bad_json),
+ str(not_a_list),
+ str(a_directory),
+ '[["10.0.0.1:5000"],', # inline and truncated
+ '{"hosts": 4}',
+ "[",
+ "{",
+ "",
+ " ",
+ ):
+ _single_process_launch(monkeypatch)
+ monkeypatch.setenv("MLX_HOSTFILE", value)
+ assert world_size_from_env() == 1
+
+ # A fifo would block open() forever, so only regular files are read at all.
+ fifo = tmp_path / "fifo"
+ try:
+ os.mkfifo(fifo)
+ except (AttributeError, NotImplementedError, OSError):
+ pass # Windows has no fifos, which is the point.
+ else:
+ assert world_size_from_rank_files({"MLX_HOSTFILE": str(fifo)}) == 1
+
+ # A mapping works the same way, and the largest count still wins.
+ assert world_size_from_rank_files({"MLX_HOSTFILE": str(ring)}) == 4
+ assert world_size_from_env({"MLX_HOSTFILE": str(ring), "WORLD_SIZE": "8"}) == 8
+ assert world_size_from_env({"MLX_HOSTFILE": str(ring), "WORLD_SIZE": "2"}) == 4
+ assert world_size_from_rank_files({"MLX_HOSTFILE": None}) == 1
+ assert world_size_from_rank_files({"MLX_HOSTFILE": 17}) == 1
+ assert world_size_from_rank_files({}) == 1
+
+
def test_effective_packing_decides_the_opt_out():
from core.training.dataset_bounds import effective_packing, max_train_rows_for_config
@@ -890,6 +1079,168 @@ def test_bound_leaves_enough_rows_after_the_eval_carve():
assert len(train) >= needed
+def test_bound_leaves_enough_rows_for_every_rank_after_the_eval_carve(monkeypatch):
+ from datasets import Dataset
+
+ from core.training.dataset_bounds import bound_dataset_rows, max_train_rows_for_config
+ from core.training.eval_dataset import split_dataset_for_evaluation
+
+ _single_process_launch(monkeypatch)
+
+ config = {"max_steps": 60, "batch_size": 2, "gradient_accumulation_steps": 4}
+ source = Dataset.from_dict({"text": [f"t{i}" for i in range(500_000)]})
+
+ for world_size in (1, 2, 4, 8):
+ rows = max_train_rows_for_config(config, world_size = world_size)
+ bounded = bound_dataset_rows(source, rows, 3407)
+ train, _eval = split_dataset_for_evaluation(bounded)
+
+ # Each rank draws its own batch, so the corpus a step consumes is the batch
+ # times the ranks; without the factor the eval carve alone tips ws=4 into
+ # re-reading rows it has already trained on.
+ needed = (
+ config["max_steps"]
+ * config["batch_size"]
+ * config["gradient_accumulation_steps"]
+ * world_size
+ )
+ assert len(train) >= needed
+
+ # Packing still opts out, whatever the launch looks like.
+ assert max_train_rows_for_config({**config, "packing": True}, world_size = 8) is None
+
+
+def test_row_bound_marker_round_trips_a_world_size_scaled_bound(tmp_path, monkeypatch):
+ from core.training.dataset_bounds import (
+ max_train_rows_for_config,
+ record_row_bound,
+ row_bound_for_resume,
+ )
+
+ _single_process_launch(monkeypatch)
+
+ run_dir = tmp_path / "run"
+ run_dir.mkdir()
+ checkpoint = run_dir / "checkpoint-60"
+ checkpoint.mkdir()
+
+ config = {"max_steps": 60, "batch_size": 2, "gradient_accumulation_steps": 4}
+ rows = max_train_rows_for_config(config, world_size = 4)
+ assert rows == 60 * 2 * 4 * 4 * 4
+ assert record_row_bound(str(run_dir), rows, 3407) is True
+
+ # The marker records rows, not the launch that sized them, so a resume on a
+ # differently sized machine still trains on the rows the run started with.
+ assert row_bound_for_resume(str(checkpoint), max_train_rows_for_config(config), 99) == (
+ rows,
+ 3407,
+ )
+
+ # A marker written before this change carries a single-process bound and is
+ # still read back verbatim, rather than being rescaled under the run.
+ legacy_dir = tmp_path / "legacy"
+ legacy_dir.mkdir()
+ (legacy_dir / "checkpoint-60").mkdir()
+ legacy_rows = 60 * 2 * 4 * 4
+ record_row_bound(str(legacy_dir), legacy_rows, 3407)
+ assert row_bound_for_resume(str(legacy_dir / "checkpoint-60"), rows, 3407) == (
+ legacy_rows,
+ 3407,
+ )
+
+ # And a checkpoint with no marker at all stays unbounded.
+ unmarked = tmp_path / "unmarked"
+ (unmarked / "checkpoint-60").mkdir(parents = True)
+ assert row_bound_for_resume(str(unmarked / "checkpoint-60"), rows, 3407) == (None, 3407)
+
+
+def test_both_loaders_size_the_bound_for_the_world():
+ """The factor is only worth having if both loaders actually pass it.
+
+ Read from source for the same reason as the wiring test below: neither call
+ site is reachable without a GPU or Apple hardware.
+ """
+ import ast
+ from pathlib import Path
+
+ worker_src = (Path(__file__).resolve().parents[1] / "core/training/worker.py").read_text(
+ encoding = "utf-8"
+ )
+ tree = ast.parse(worker_src)
+ calls = {}
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.FunctionDef):
+ continue
+ calls[node.name] = {
+ sub.func.id
+ for sub in ast.walk(node)
+ if isinstance(sub, ast.Call) and isinstance(sub.func, ast.Name)
+ }
+
+ for loader in ("run_training_process", "_run_mlx_training"):
+ assert "_data_parallel_world_size" in calls[loader]
+ assert worker_src.count("world_size = _data_parallel_world_size()") == 2
+ # The count is a property of this launch, so it must never be read back out of a
+ # config that was built on the parent and shipped across a spawn.
+ assert 'config.get("world_size")' not in worker_src
+
+
+def test_data_parallel_world_size_counts_ranks_and_devices(monkeypatch):
+ import types
+
+ from core.training import worker as training_worker
+
+ _single_process_launch(monkeypatch)
+
+ # No torch in sys.modules is the MLX host: the env is all there is.
+ monkeypatch.setitem(sys.modules, "torch", None)
+ assert training_worker._data_parallel_world_size() == 1
+ monkeypatch.setenv("MLX_WORLD_SIZE", "4")
+ assert training_worker._data_parallel_world_size() == 4
+
+ def _torch(devices, world_size = None):
+ distributed = types.SimpleNamespace(
+ is_available = lambda: world_size is not None,
+ is_initialized = lambda: world_size is not None,
+ get_world_size = lambda: world_size,
+ )
+ return types.SimpleNamespace(
+ cuda = types.SimpleNamespace(device_count = lambda: devices),
+ distributed = distributed,
+ )
+
+ _single_process_launch(monkeypatch)
+ # One visible GPU and no launcher is today's single-process run, unchanged.
+ monkeypatch.setitem(sys.modules, "torch", _torch(1))
+ assert training_worker._data_parallel_world_size() == 1
+
+ # transformers wraps a non-distributed multi-GPU run in DataParallel and scales
+ # the train batch by the visible device count, which no env reports.
+ monkeypatch.setitem(sys.modules, "torch", _torch(4))
+ assert training_worker._data_parallel_world_size() == 4
+
+ # A torchrun rank sees the whole node but trains on its own shard: the larger of
+ # the two, never the product, since a distributed run pins n_gpu to 1.
+ monkeypatch.setenv("WORLD_SIZE", "8")
+ monkeypatch.setitem(sys.modules, "torch", _torch(8, world_size = 8))
+ assert training_worker._data_parallel_world_size() == 8
+
+ # CPU-only and a torch whose CUDA probe raises both read as one process.
+ _single_process_launch(monkeypatch)
+ monkeypatch.setitem(sys.modules, "torch", _torch(0))
+ assert training_worker._data_parallel_world_size() == 1
+
+ def _raises():
+ raise RuntimeError("no CUDA driver")
+
+ broken = types.SimpleNamespace(
+ cuda = types.SimpleNamespace(device_count = _raises),
+ distributed = types.SimpleNamespace(is_available = _raises, is_initialized = _raises),
+ )
+ monkeypatch.setitem(sys.modules, "torch", broken)
+ assert training_worker._data_parallel_world_size() == 1
+
+
def test_both_loaders_apply_the_row_bound():
"""Guards the wiring: the helpers are useless if a loader stops calling them.
@@ -1052,9 +1403,9 @@ def test_manual_eager_slice_attests_original_hub_stream(monkeypatch, tmp_path):
monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda **kw: [tmp_path])
monkeypatch.setattr(
"core.training.trainer.load_dataset",
- lambda **kwargs: stream
- if kwargs.get("streaming")
- else pytest.fail("eager download should not run"),
+ lambda **kwargs: (
+ stream if kwargs.get("streaming") else pytest.fail("eager download should not run")
+ ),
)
result = trainer.load_and_format_dataset(