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
Studio: tokenize the dataset online for plain-text single-pass runs (#8960)
Daniel Han7b13a787cf72
diff --git a/scripts/online_tokenization_ab.py b/scripts/online_tokenization_ab.pynew file mode 100644index 00000000000..215276bbd06--- /dev/null+++ b/scripts/online_tokenization_ab.py@@ -0,0 +1,251 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Eager vs online preparation, measured through Studio's real training path.++Drives ``UnslothTrainer.load_model`` -> ``prepare_model_for_training`` ->+``load_and_format_dataset`` -> ``start_training``, so the integrated gating is+what gets measured. The arms differ only by ``UNSLOTH_STUDIO_ONLINE_TOKENIZATION``:++ python scripts/online_tokenization_ab.py --arm eager --dataset <split> --out ab_eager.json+ python scripts/online_tokenization_ab.py --arm online --dataset <split> --out ab_online.json++Same seed, rows and order, so per-step losses must match; a mismatch means the+lazy transform is not producing the rows the eager map produced.+"""++from __future__ import annotations++import argparse+import json+import os+import sys+import tempfile+import time+from pathlib import Path++REPO = Path(__file__).resolve().parents[1]+# Scratch root for the per-arm `datasets` cache; no machine-specific layout.+WORKSPACE = Path(os.environ.get("UNSLOTH_WORKSPACE") or tempfile.gettempdir())++os.environ.setdefault("CUDA_VISIBLE_DEVICES", "0")+os.environ.setdefault("UNSLOTH_DISABLE_STATISTICS", "1")++sys.path.insert(0, str(REPO / "studio" / "backend"))+sys.path.insert(0, str(REPO))+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--arm", choices = ("eager", "online"), required = True)+ # No default path: it would only exist on one machine.+ parser.add_argument(+ "--dataset",+ required = True,+ help = "Parquet/JSONL split, or a Hugging Face dataset id, carrying a text column",+ )+ parser.add_argument("--model", default = "unsloth/Qwen3-0.6B", help = "Model id or local path")+ parser.add_argument("--max-steps", type = int, default = 30)+ parser.add_argument("--batch-size", type = int, default = 2)+ parser.add_argument("--grad-accum", type = int, default = 4)+ parser.add_argument("--max-seq-length", type = int, default = 2048)+ parser.add_argument("--out", required = True)+ parser.add_argument("--fresh-cache", action = "store_true", default = True)+ parser.add_argument("--no-fresh-cache", dest = "fresh_cache", action = "store_false")+ args = parser.parse_args()++ # Fresh cache per run, else the eager arm just reads the other arm's+ # tokenize map out of Arrow and measures a cache hit real users never get.+ if args.fresh_cache:+ cache = WORKSPACE / "unsloth_ab_cache" / f"{args.arm}_{int(time.time())}"+ cache.mkdir(parents = True, exist_ok = True)+ os.environ["HF_DATASETS_CACHE"] = str(cache)++ # Set before anything imports the gate.+ if args.arm == "eager":+ os.environ["UNSLOTH_STUDIO_ONLINE_TOKENIZATION"] = "0"+ else:+ os.environ.pop("UNSLOTH_STUDIO_ONLINE_TOKENIZATION", None)++ import unsloth # noqa: F401 - must precede transformers/trl+ from transformers import TrainerCallback++ from core.training.trainer import UnslothTrainer++ start = time.perf_counter()+ marks: dict = {}++ def mark(name: str) -> None:+ marks[name] = round(time.perf_counter() - start, 4)+ print(f"[phase] {name} @ {marks[name]}s", flush = True)++ trainer = UnslothTrainer()+ if not trainer.load_model(+ model_name = args.model,+ max_seq_length = args.max_seq_length,+ load_in_4bit = True,+ ):+ print("model load failed", file = sys.stderr)+ return 1+ if not trainer.prepare_model_for_training(+ use_lora = True,+ lora_r = 16,+ lora_alpha = 16,+ lora_dropout = 0.0,+ target_modules = [+ "q_proj",+ "k_proj",+ "v_proj",+ "o_proj",+ "gate_proj",+ "up_proj",+ "down_proj",+ ],+ use_gradient_checkpointing = "unsloth",+ ):+ print("model prepare failed", file = sys.stderr)+ return 1+ mark("model_ready")++ # `local_datasets` resolves its entries to files and rejects anything without a+ # supported extension, so a Hub id has to go through `dataset_source` instead.+ local_split = os.path.exists(args.dataset) or Path(args.dataset).suffix.lower() in (+ ".json",+ ".jsonl",+ ".csv",+ ".parquet",+ )+ result = trainer.load_and_format_dataset(+ dataset_source = None if local_split else args.dataset,+ format_type = "auto",+ local_datasets = [args.dataset] if local_split else None,+ )+ if result is None:+ print("dataset load failed", file = sys.stderr)+ return 1+ dataset, eval_dataset = result+ mark("dataset_formatted")++ class _Probe(TrainerCallback):+ """Wall clock at train() and at every step, plus the loss stream."""++ def __init__(self):+ self.losses: list = []+ self.step_times: list = []++ def on_train_begin(self, targs, state, control, **kwargs):+ mark("train_begin")++ def on_step_end(self, targs, state, control, **kwargs):+ self.step_times.append(round(time.perf_counter() - start, 4))+ if len(self.step_times) == 1:+ mark("first_step_end")++ def on_log(+ self,+ targs,+ state,+ control,+ logs = None,+ **kwargs,+ ):+ if logs and "loss" in logs:+ self.losses.append(logs["loss"])++ probe = _Probe()++ # The trainer only exists inside the worker thread, so attach on appearance.+ original_preflight = trainer._preflight_first_batch++ def _preflight_with_probe():+ mark("trainer_built")+ trainer.trainer.add_callback(probe)+ error = original_preflight()+ mark("prewarm_done")+ return error++ trainer._preflight_first_batch = _preflight_with_probe++ started = trainer.start_training(+ dataset = dataset,+ eval_dataset = eval_dataset,+ output_dir = f"ab_{args.arm}", # resolved under Studio's outputs root+ num_epochs = 1,+ max_steps = args.max_steps,+ batch_size = args.batch_size,+ gradient_accumulation_steps = args.grad_accum,+ learning_rate = 2e-4,+ weight_decay = 0.01,+ random_seed = 3407,+ max_seq_length = args.max_seq_length,+ packing = False,+ train_on_completions = False,+ )+ if not started:+ print("training failed to start", file = sys.stderr)+ return 1++ while trainer.training_thread and trainer.training_thread.is_alive():+ time.sleep(1)+ trainer.training_thread.join()+ mark("train_done")++ progress = trainer.get_training_progress()+ error = getattr(progress, "error", None)++ decision = getattr(trainer, "_online_prewarm_batches", 0)+ # What the trainer actually got configured with, read off the object.+ observed = {}+ sft = getattr(trainer, "trainer", None)+ if sft is not None:+ targs = getattr(sft, "args", None)+ split = getattr(sft, "train_dataset", None)+ fmt = getattr(split, "format", None)+ observed = {+ "dataloader_num_workers": getattr(targs, "dataloader_num_workers", None),+ "dataloader_persistent_workers": getattr(targs, "dataloader_persistent_workers", None),+ "dataloader_prefetch_factor": getattr(targs, "dataloader_prefetch_factor", None),+ "dataset_kwargs": getattr(targs, "dataset_kwargs", None),+ "remove_unused_columns": getattr(targs, "remove_unused_columns", None),+ "padding_free": getattr(targs, "padding_free", None),+ "packing": getattr(targs, "packing", None),+ "dataset_num_proc": getattr(targs, "dataset_num_proc", None),+ "train_split_format": fmt.get("type") if isinstance(fmt, dict) else None,+ "train_split_columns": list(getattr(split, "column_names", None) or []),+ "train_split_rows": len(split) if split is not None else None,+ }+ payload = {+ "arm": args.arm,+ "error": error,+ "phases": marks,+ "losses": probe.losses,+ "step_times": probe.step_times,+ "prewarm_batches": decision,+ "observed": observed,+ # Studio's chat-template render, which BOTH arms do eagerly.+ "format_seconds": round(+ marks.get("dataset_formatted", 0.0) - marks.get("model_ready", 0.0), 4+ ),+ # Trainer construction: TRL's tokenizing map on the eager arm, nothing online.+ "prep_seconds": round(+ marks.get("trainer_built", 0.0) - marks.get("dataset_formatted", 0.0), 4+ ),+ "time_to_first_step": marks.get("first_step_end"),+ "steady_state_seconds": (+ round(probe.step_times[-1] - probe.step_times[0], 4)+ if len(probe.step_times) > 1+ else None+ ),+ }+ if probe.losses:+ payload["mean_loss"] = round(sum(probe.losses) / len(probe.losses), 6)++ out = Path(args.out)+ out.parent.mkdir(parents = True, exist_ok = True)+ out.write_text(json.dumps(payload, indent = 2), encoding = "utf-8")+ print(json.dumps({k: v for k, v in payload.items() if k != "step_times"}, indent = 2))+ return 1 if error else 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex 225dad8a984..32d79206d47 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -3439,13 +3439,208 @@ class UnslothTrainer:except Exception:return False+ def _configure_online_tokenization(+ self,+ *,+ config_args: dict,+ dataset,+ eval_dataset,+ training_args: dict,+ data_collator,+ raw_text_mode: bool,+ is_deepseek_ocr: bool,+ ):+ """Switch the plain-text path to lazy, worker-side tokenization.++ Mutates ``config_args`` and the ``dataset`` wrapper in place when the run+ qualifies, and leaves both untouched otherwise.+ ``self._online_eval_dataset`` returns the transformed eval split, and+ ``self._online_prewarm_batches`` tells ``_preflight_first_batch`` how deep+ to prime. Never raises: any failure degrades to the eager path.+ """+ from utils.datasets.online_tokenization import (+ OnlineTokenizationDecision,+ attach_online_tokenization,+ decide_online_tokenization,+ first_sample_text,+ online_config_args,+ quiet_tokenizer_fork_warning,+ resolve_add_special_tokens,+ )++ self._online_eval_dataset = eval_dataset+ train_dataset = dataset["dataset"] if isinstance(dataset, dict) else dataset++ # A step-capped run says nothing about passes, but Studio knows the rows+ # and microbatch size, so resolve it here. World size scales rows consumed+ # per step; omitting it would understate the passes.+ resolved_epochs = None+ max_steps = int(config_args.get("max_steps") or 0)+ if max_steps > 0:+ try:+ rows = len(train_dataset)+ world_size = max(1, int(os.environ.get("WORLD_SIZE", "1")))+ per_step = (+ int(config_args.get("per_device_train_batch_size", 1))+ * int(config_args.get("gradient_accumulation_steps", 1))+ * world_size+ )+ resolved_epochs = (max_steps * per_step) / rows if rows else None+ except Exception: # noqa: BLE001 - unresolvable stays unresolved+ resolved_epochs = None++ try:+ decision = decide_online_tokenization(+ dataset = train_dataset,+ eval_dataset = eval_dataset,+ processing_class = self.tokenizer,+ model = self.model,+ text_field = config_args.get("dataset_text_field", "text") or "text",+ packing = bool(config_args.get("packing", False)),+ is_vlm = bool(self.is_vlm),+ is_audio = bool(self.is_audio or self._cuda_audio_used),+ is_audio_vlm = bool(self.is_audio_vlm),+ is_deepseek_ocr = bool(is_deepseek_ocr),+ is_cpt = bool(training_args.get("is_cpt", False)),+ raw_text_mode = bool(raw_text_mode),+ has_custom_collator = data_collator is not None,+ train_on_completions = bool(training_args.get("train_on_completions", False)),+ dataset_streaming = bool(+ training_args.get("dataset_streaming", False)+ or detect_streaming_dataset(train_dataset)+ ),+ num_train_epochs = config_args.get("num_train_epochs"),+ max_steps = config_args.get("max_steps"),+ grad_accum = config_args.get("gradient_accumulation_steps", 1),+ resolved_max_steps_epochs = resolved_epochs,+ )+ except Exception as exc: # noqa: BLE001 - a gating failure must not fail a run+ logger.warning(f"Online tokenization gating failed, using eager path: {exc}")+ return OnlineTokenizationDecision(enabled = False, reason = f"gating error: {exc}")++ logger.info(f"{decision.as_log_line()}\n")+ if not decision.enabled:+ return decision++ try:+ text_field = config_args.get("dataset_text_field", "text") or "text"+ max_length = int(config_args.get("max_seq_length") or 2048)+ # The generated `__init__` clamps `max_seq_length` to the model's cap+ # and derives `max_length` from it, but runs after this. Apply the same+ # cap here or the transform truncates wider than the eager map it+ # replaces, and the attestation claims a width nothing enforced.+ model_cap = getattr(self.model, "max_seq_length", None)+ try:+ if model_cap is not None and 0 < int(model_cap) < max_length:+ logger.info(+ f"Online tokenization: max_length {max_length} exceeds the "+ f"model's {int(model_cap)}, using the model's\n"+ )+ max_length = int(model_cap)+ except (TypeError, ValueError):+ pass+ add_special_tokens = resolve_add_special_tokens(+ self.tokenizer, first_sample_text(train_dataset, text_field)+ )+ quiet_tokenizer_fork_warning()++ view = attach_online_tokenization(+ train_dataset,+ tokenizer = self.tokenizer,+ text_field = text_field,+ max_length = max_length,+ add_special_tokens = add_special_tokens,+ )+ if isinstance(dataset, dict):+ dataset["dataset"] = view+ if eval_dataset is not None:+ # Probe the eval split's own first row: TRL calls _prepare_dataset+ # once per split, so reusing the train answer would tokenize eval+ # differently whenever the splits disagree about a leading BOS.+ eval_add_special_tokens = resolve_add_special_tokens(+ self.tokenizer, first_sample_text(eval_dataset, text_field)+ )+ self._online_eval_dataset = attach_online_tokenization(+ eval_dataset,+ tokenizer = self.tokenizer,+ text_field = text_field,+ max_length = max_length,+ add_special_tokens = eval_add_special_tokens,+ )+ config_args.update(online_config_args(decision))+ self._online_prewarm_batches = decision.prewarm_batches+ logger.info(+ f"Online tokenization attached: max_length={max_length}, "+ f"add_special_tokens={add_special_tokens}\n"+ )+ return decision+ except Exception as exc: # noqa: BLE001+ logger.warning(f"Online tokenization setup failed, using eager path: {exc}")+ if isinstance(dataset, dict):+ dataset["dataset"] = train_dataset+ self._online_eval_dataset = eval_dataset+ self._online_prewarm_batches = 0+ return OnlineTokenizationDecision(enabled = False, reason = f"setup error: {exc}")++ def _release_online_dataloader(self) -> None:+ """Shut down the online path's persistent DataLoader workers.++ Persistence is what carries the prewarm barrier's workers into train();+ nothing else drops them, so they would stay resident through merging,+ quantization and GGUF export -- the most memory-hungry part of a run --+ each a fork of a process that had already initialised CUDA. Called from a+ finally (so it covers preflight errors and a raising train()), and+ idempotent because those paths reach it twice.+ """+ if not getattr(self, "_online_prewarm_batches", 0):+ return+ trainer = getattr(self, "trainer", None)+ if trainer is None:+ return+ try:+ from utils.datasets.online_tokenization import release_train_dataloader+ released = release_train_dataloader(trainer)+ except Exception as exc: # noqa: BLE001 - cleanup must never fail a finished run+ logger.warning(f"Online tokenization worker shutdown failed: {exc}")+ return+ # `_online_prewarm_batches` is left alone: it records how the run was+ # configured and the A/B harness reads it back. A second call is a no-op.+ if released:+ logger.info(f"Online tokenization: shut down {released} DataLoader workers\n")+def _preflight_first_batch(self) -> Optional[str]:"""Validate the first real batch before train(). A base model whose chattemplate renders empty yields empty float32 input_ids that crash the- embedding on step 1; catch it here. Returns None for a valid batch."""+ embedding on step 1; catch it here. Returns None for a valid batch.++ On the online path this doubles as the prewarm barrier: enough+ microbatches for the first optimizer step and the DataLoader's in-flight+ depth are pulled through here, so step 1 never waits on a cold worker.++ The workers survive, not the batches: ``train()`` calls ``iter()`` again+ and torch answers with ``_iterator._reset(...)``, restarting the sampler+ at row 0, so these batches are tokenized twice. No rows are lost, and what+ it buys is forked workers past their first import and tokenizer touch plus+ a warm page cache."""+ prewarm = int(getattr(self, "_online_prewarm_batches", 0) or 0)+ if prewarm:+ from utils.datasets.online_tokenization import memoize_train_dataloader++ # Hold the loader this barrier fills, or train() forks fresh workers+ # and everything drained here is wasted.+ memoize_train_dataloader(self.trainer)try:loader = self.trainer.get_train_dataloader()- batch = next(iter(loader))+ iterator = iter(loader)+ batch = next(iterator)+ for _ in range(max(0, prewarm - 1)):+ try:+ next(iterator)+ except StopIteration:+ break # a short split simply prewarms fewer+ # Drop the local names: on the eager path that tears the loader down;+ # on the online path the memo still holds it, so the workers survive.+ del iterator, loaderexcept StopIteration:return ("Cannot start training: the dataset produced no training rows. "@@ -3932,6 +4127,22 @@ class UnslothTrainer:config_args["packing"] = Falselogger.info("Applied DAC overrides: packing=False\n")+ # ========== ONLINE (OVERLAPPED) TOKENIZATION ==========+ # Plain-text single-pass runs tokenize in the DataLoader workers+ # instead of a blocking .map(); everything else stays eager.+ self._online_prewarm_batches = 0+ online_decision = self._configure_online_tokenization(+ config_args = config_args,+ dataset = dataset,+ eval_dataset = eval_dataset,+ training_args = training_args,+ data_collator = data_collator,+ raw_text_mode = raw_text_mode,+ is_deepseek_ocr = is_deepseek_ocr,+ )+ if online_decision.enabled:+ eval_dataset = self._online_eval_dataset+logger.info(f"The configuration is: {config_args}")logger.info("Training configuration prepared\n")@@ -4185,7 +4396,15 @@ class UnslothTrainer:self._update_progress(total_steps = total_steps, status_message = "Starting training...")logger.info("Starting training...\n")- self.trainer.train(resume_from_checkpoint = training_args.get("resume_from_checkpoint"))+ try:+ self.trainer.train(+ resume_from_checkpoint = training_args.get("resume_from_checkpoint")+ )+ finally:+ # Before _finalize_training, not after: merging and exporting are+ # where the memory goes, and the workers still hold a fork of this+ # process.+ self._release_online_dataloader()# ========== SAVE MODEL ==========self._finalize_training(output_dir)@@ -4198,6 +4417,9 @@ class UnslothTrainer:self._update_progress(is_training = False, error = str(e))finally:+ # Backstop for returns that never reach train(), notably a preflight+ # error: that path has already forked the workers.+ self._release_online_dataloader()self.is_training = Falsedef _patch_adapter_config(self, output_dir: str) -> None:diff --git a/studio/backend/tests/test_online_tokenization.py b/studio/backend/tests/test_online_tokenization.pynew file mode 100644index 00000000000..50502d18766--- /dev/null+++ b/studio/backend/tests/test_online_tokenization.py@@ -0,0 +1,542 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Which configurations may tokenize online, and what the lazy view produces.++No GPU and no model: the gate is a pure function of the run's shape, and the+transform runs against a real tokenizer on a real ``datasets.Dataset``. Every+"degrades to the old path" claim is a test here, since a wrong answer is either a+crash (VLM, pre-tokenized) or a run that trains on different rows.+"""++import sys+from types import SimpleNamespace++import pytest++sys.path.insert(0, "studio/backend")++from utils.datasets.online_tokenization import ( # noqa: E402+ ENV_FLAG,+ MIN_ROWS_FOR_ONLINE,+ TRUNCATION_ATTESTATION_ATTR,+ OnlineTokenizationDecision,+ attach_online_tokenization,+ build_tokenizing_transform,+ dataset_column_names,+ dataset_supports_with_transform,+ decide_online_tokenization,+ env_override,+ is_processor,+ online_config_args,+ prewarm_batch_count,+ resolve_add_special_tokens,+ text_column_defect,+ trl_supports_skip_prepare_dataset,+)++datasets = pytest.importorskip("datasets")+++ROWS = MIN_ROWS_FOR_ONLINE + 5+++def _text_dataset(n = ROWS, extra_columns = None):+ data = {+ "text": [f"row {i}" for i in range(n)],+ "conversations": [[{"role": "user", "content": str(i)}] for i in range(n)],+ }+ data.update(extra_columns or {})+ return datasets.Dataset.from_dict(data)+++class _Tokenizer:+ """The narrowest thing the online path needs: callable, no ``.tokenizer``."""++ bos_token = "<s>"+ chat_template = "{{ messages }}"++ def __call__(+ self,+ texts,+ truncation = True,+ max_length = 8,+ add_special_tokens = True,+ ):+ if isinstance(texts, str):+ texts = [texts]+ ids = [[len(t)] * min(len(t), max_length if truncation else len(t)) for t in texts]+ return {"input_ids": ids}+++class _Processor(_Tokenizer):+ tokenizer = _Tokenizer()+++def _base_kwargs(**overrides):+ kwargs = dict(+ dataset = _text_dataset(),+ eval_dataset = None,+ processing_class = _Tokenizer(),+ model = SimpleNamespace(),+ text_field = "text",+ packing = False,+ num_train_epochs = 1,+ max_steps = 0,+ grad_accum = 4,+ workers = 4,+ )+ kwargs.update(overrides)+ return kwargs++[email protected](autouse = True)+def _no_env_override(monkeypatch):+ monkeypatch.delenv(ENV_FLAG, raising = False)+ # The gate refuses on spawn platforms; these tests describe Linux behaviour+ # and simulate the other platforms explicitly where that is the point.+ monkeypatch.setattr(sys, "platform", "linux")+ # Same for the TRL hook: the CPU test job installs no TRL, so leaving it+ # ambient makes every gate below report "no skip_prepare_dataset hook".+ # The detector itself is covered separately below.+ monkeypatch.setattr(+ "utils.datasets.online_tokenization.trl_supports_skip_prepare_dataset",+ lambda: True,+ )+++# ---------------------------------------------------------------- the happy path+++def test_plain_text_single_epoch_run_goes_online():+ decision = decide_online_tokenization(**_base_kwargs())+ assert decision.enabled, decision.reason+ assert decision.workers == 4+ assert decision.prewarm_batches == max(4, 4 * decision.prefetch_factor)+++def test_online_config_args_are_the_four_keys_the_mechanism_needs():+ decision = decide_online_tokenization(**_base_kwargs())+ args = online_config_args(decision)+ assert args["dataset_kwargs"] == {"skip_prepare_dataset": True}+ # `Trainer._remove_unused_columns` reads `column_names`, which a transformed+ # split answers from its BACKING table -- it would strip the text column the+ # transform reads.+ assert args["remove_unused_columns"] is False+ assert args["dataloader_num_workers"] == 4+ assert args["dataloader_prefetch_factor"] > 0+ assert args["dataloader_persistent_workers"] is True+++# ------------------------------------------------------- degradation, one per gate++[email protected]("platform", ["win32", "darwin"])+def test_spawn_platforms_keep_the_eager_path(monkeypatch, platform):+ """Studio already forces `dataloader_num_workers = 0` there, because a+ modified `sys.path` does not survive the spawn. Never a crash: just off."""+ monkeypatch.setattr(sys, "platform", platform)+ decision = decide_online_tokenization(**_base_kwargs())+ assert not decision.enabled+ assert platform in decision.reason+++ "flag, reason_fragment",+ [+ ({"is_vlm": True}, "multimodal"),+ ({"is_audio_vlm": True}, "multimodal"),+ ({"is_deepseek_ocr": True}, "multimodal"),+ ({"is_audio": True}, "audio"),+ ({"is_cpt": True}, "continued pretraining"),+ ({"raw_text_mode": True}, "raw-text"),+ ({"has_custom_collator": True}, "custom data collator"),+ ({"packing": True}, "packing"),+ ({"train_on_completions": True}, "train on completions"),+ ({"dataset_streaming": True}, "streaming"),+ ],+)+def test_each_excluded_shape_takes_the_old_path(flag, reason_fragment):+ decision = decide_online_tokenization(**_base_kwargs(**flag))+ assert not decision.enabled+ assert reason_fragment in decision.reason+++def test_streaming_dataset_object_is_refused_even_without_the_flag():+ """`IterableDataset` also has `with_transform` in recent `datasets`, so the+ check is an isinstance and not a `hasattr`."""+ stream = datasets.Dataset.from_dict({"text": ["a", "b"]}).to_iterable_dataset()+ decision = decide_online_tokenization(**_base_kwargs(dataset = stream))+ assert not decision.enabled+ assert "map-style" in decision.reason+++def test_a_plain_list_dataset_is_refused():+ decision = decide_online_tokenization(**_base_kwargs(dataset = [{"text": "a"}] * ROWS))+ assert not decision.enabled+ assert "map-style" in decision.reason++[email protected]("column", ["input_ids", "labels", "prompt", "completion"])+def test_an_already_tokenized_dataset_is_refused(column):+ dataset = _text_dataset(extra_columns = {column: [[1, 2, 3]] * ROWS})+ decision = decide_online_tokenization(**_base_kwargs(dataset = dataset))+ assert not decision.enabled+ assert column in decision.reason+++def test_a_processor_is_refused():+ decision = decide_online_tokenization(**_base_kwargs(processing_class = _Processor()))+ assert not decision.enabled+ assert "processor" in decision.reason+++def test_a_model_needing_token_type_ids_is_refused(monkeypatch):+ """Gemma-family modules build their causal mask from `token_type_ids`, and+ the zoo's tokenize asks for them. Rather than reproduce that column lazily,+ those models keep the eager path."""+ module = SimpleNamespace(**{"create_" + "causal_mask_mapping": lambda: None})+ monkeypatch.setitem(sys.modules, "fake_gemma_modelling", module)++ class _GemmaLike:+ pass++ _GemmaLike.__module__ = "fake_gemma_modelling"+ decision = decide_online_tokenization(**_base_kwargs(model = _GemmaLike()))+ assert not decision.enabled+ assert "token_type_ids" in decision.reason+++def test_missing_text_column_is_refused():+ dataset = datasets.Dataset.from_dict({"conversations": [[]] * ROWS})+ decision = decide_online_tokenization(**_base_kwargs(dataset = dataset))+ assert not decision.enabled+ assert "text" in decision.reason+++def test_a_null_text_row_is_refused():+ """The reproduction that motivated this gate: the eager map dies on one None+ inside the constructor, while the lazy view trained past step 20 and would+ have died hours in, at whatever step drew row 137."""+ texts = [f"row {i}" for i in range(ROWS)]+ texts[137] = None+ dataset = datasets.Dataset.from_dict({"text": texts})+ decision = decide_online_tokenization(**_base_kwargs(dataset = dataset))+ assert not decision.enabled+ assert "null" in decision.reason+++ "column",+ [+ [7] * ROWS,+ [[f"row {i}"] for i in range(ROWS)],+ [{"content": "x"}] * ROWS,+ ],+ ids = ["ints", "lists", "structs"],+)+def test_a_text_column_that_is_not_strings_is_refused(column):+ dataset = datasets.Dataset.from_dict({"text": column})+ decision = decide_online_tokenization(**_base_kwargs(dataset = dataset))+ assert not decision.enabled+ assert "not strings" in decision.reason+++def test_a_null_text_row_in_the_eval_split_is_refused():+ texts = [f"row {i}" for i in range(64)]+ texts[7] = None+ eval_dataset = datasets.Dataset.from_dict({"text": texts})+ decision = decide_online_tokenization(**_base_kwargs(eval_dataset = eval_dataset))+ assert not decision.enabled+ assert "eval split" in decision.reason and "null" in decision.reason+++def test_the_text_column_check_reads_metadata_and_never_a_row():+ """Both halves come off the schema and Arrow's per-chunk null count, so the+ gate must reach its answer on a split whose rows refuse to be read at all --+ otherwise it is the eager pass it exists to avoid, in miniature."""++ class _Unreadable(type(_text_dataset(16))):+ def __getitem__(self, key):+ raise AssertionError("the gate read a row")++ dataset = _text_dataset()+ unreadable = _Unreadable(dataset.data, info = dataset.info)+ assert text_column_defect(unreadable, "text") is None+++def test_a_spawn_start_method_keeps_the_eager_path_on_linux(monkeypatch):+ """The gate is named for Windows and macOS, but the hazard it describes is+ `spawn` re-importing the entry point against a `sys.path` Studio modified in+ process. A Linux host set to spawn is the same hazard."""+ import multiprocessing++ monkeypatch.setattr(multiprocessing, "get_start_method", lambda allow_none = False: "spawn")+ decision = decide_online_tokenization(**_base_kwargs())+ assert not decision.enabled+ assert "spawn" in decision.reason and "fork" in decision.reason+++def test_an_unset_start_method_falls_back_to_the_platform_default(monkeypatch):+ """`get_start_method()` with no argument pins the context and makes a later+ `set_start_method()` raise, so the default is read off the method list."""+ import multiprocessing++ monkeypatch.setattr(multiprocessing, "get_start_method", lambda allow_none = False: None)+ monkeypatch.setattr(multiprocessing, "get_all_start_methods", lambda: ["fork", "spawn"])+ assert decide_online_tokenization(**_base_kwargs()).enabled++ monkeypatch.setattr(multiprocessing, "get_all_start_methods", lambda: ["forkserver"])+ assert not decide_online_tokenization(**_base_kwargs()).enabled+++def test_a_trl_without_the_hook_keeps_the_eager_path(monkeypatch):+ """The veto the autouse fixture pins away, exercised on its own: without+ `skip_prepare_dataset` TRL would run its own tokenizing map over the lazy+ view, which is the whole pass the online path exists to avoid."""+ monkeypatch.setattr(+ "utils.datasets.online_tokenization.trl_supports_skip_prepare_dataset",+ lambda: False,+ )+ decision = decide_online_tokenization(**_base_kwargs())+ assert not decision.enabled+ assert "skip_prepare_dataset" in decision.reason+++def test_the_hook_detector_reads_the_installed_trl(monkeypatch):+ """No TRL means no SFT run, so the detector says no rather than raising; a+ `SFTConfig` without `dataset_kwargs` says no too, since the key would be+ dropped and TRL would tokenize the view."""+ import builtins++ real_import = builtins.__import__++ def no_trl(name, *args, **kwargs):+ if name == "trl" or name.startswith("trl."):+ raise ImportError("No module named 'trl'")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", no_trl)+ assert trl_supports_skip_prepare_dataset() is False+++def test_too_few_workers_is_refused():+ decision = decide_online_tokenization(**_base_kwargs(workers = 1))+ assert not decision.enabled+ assert "workers" in decision.reason+++def test_a_small_dataset_keeps_the_eager_path():+ decision = decide_online_tokenization(**_base_kwargs(dataset = _text_dataset(100)))+ assert not decision.enabled+ assert "smaller than" in decision.reason+++def test_multi_epoch_runs_keep_the_eager_path():+ """The lazy view re-tokenizes on every pass; the eager one reads Arrow.+ Measured at +2.9% of steady-state training time over 2.4 epochs, against a+ saving that is paid once, so anything past a single pass stays eager."""+ decision = decide_online_tokenization(**_base_kwargs(num_train_epochs = 3))+ assert not decision.enabled+ assert "one pass" in decision.reason+++def test_a_step_capped_run_of_unknown_length_keeps_the_eager_path():+ decision = decide_online_tokenization(**_base_kwargs(max_steps = 500))+ assert not decision.enabled+ assert "unknown length" in decision.reason+++def test_a_resolved_sub_epoch_step_cap_may_go_online():+ """`max_steps` alone says nothing about passes, but a caller that has+ resolved it to a fraction of an epoch has answered the question."""+ decision = decide_online_tokenization(+ **_base_kwargs(max_steps = 60, resolved_max_steps_epochs = 0.02)+ )+ assert decision.enabled, decision.reason+++# ---------------------------------------------------------------- the eval split+++def test_a_raw_eval_split_is_transformed_alongside_the_train_split():+ decision = decide_online_tokenization(**_base_kwargs(eval_dataset = _text_dataset(64)))+ assert decision.enabled, decision.reason+++def test_an_eval_split_the_transform_cannot_serve_disables_the_feature():+ """`skip_prepare_dataset` skips the EVAL prep too, so an eval split the+ online path cannot tokenize would reach the model as raw text."""+ bad_eval = datasets.Dataset.from_dict({"something_else": ["x"] * 8})+ decision = decide_online_tokenization(**_base_kwargs(eval_dataset = bad_eval))+ assert not decision.enabled+ assert "eval" in decision.reason+++def test_an_already_tokenized_eval_split_disables_the_feature():+ tokenized_eval = datasets.Dataset.from_dict({"text": ["x"] * 8, "input_ids": [[1, 2]] * 8})+ decision = decide_online_tokenization(**_base_kwargs(eval_dataset = tokenized_eval))+ assert not decision.enabled+ assert "eval" in decision.reason+++# ------------------------------------------------------------------ escape hatch+++def test_env_flag_zero_forces_the_eager_path(monkeypatch):+ monkeypatch.setenv(ENV_FLAG, "0")+ assert env_override() is False+ decision = decide_online_tokenization(**_base_kwargs())+ assert not decision.enabled+ assert ENV_FLAG in decision.reason+++def test_env_flag_one_overrides_the_cost_gates_only(monkeypatch):+ monkeypatch.setenv(ENV_FLAG, "1")+ forced = decide_online_tokenization(+ **_base_kwargs(dataset = _text_dataset(10), num_train_epochs = 5)+ )+ assert forced.enabled, forced.reason+ # ...but never a correctness gate: a VLM stays eager however hard it is asked.+ assert not decide_online_tokenization(**_base_kwargs(is_vlm = True)).enabled+++def test_an_unrecognised_env_value_is_not_an_override(monkeypatch):+ monkeypatch.setenv(ENV_FLAG, "maybe")+ assert env_override() is None+ assert decide_online_tokenization(**_base_kwargs()).enabled+++# ------------------------------------------------------------------- the transform+++def test_the_transform_returns_input_ids_for_the_whole_batch():+ transform = build_tokenizing_transform(_Tokenizer(), "text", 8, True)+ out = transform({"text": ["abc", "de"]})+ assert "input_ids" in out+ assert len(out["input_ids"]) == 2+++def test_the_transform_passes_the_whole_tokenizer_output_through():+ """The eager map keeps `attention_mask` too (`remove_columns` drops only the+ ORIGINAL columns), and both the collator and the attention dispatcher branch+ on which keys are present."""++ class _WithMask(_Tokenizer):+ def __call__(self, texts, **kwargs):+ out = super().__call__(texts, **kwargs)+ out["attention_mask"] = [[1] * len(ids) for ids in out["input_ids"]]+ return out++ transform = build_tokenizing_transform(_WithMask(), "text", 8, True)+ out = transform({"text": ["abc", "de"]})+ assert sorted(out) == ["attention_mask", "input_ids"]+++def test_the_view_is_immutable_and_leaves_the_original_alone():+ """`with_transform`, never `set_transform`: the caller's object is also held+ by the preview and the row-count checks."""+ dataset = _text_dataset(32)+ view = attach_online_tokenization(+ dataset,+ tokenizer = _Tokenizer(),+ text_field = "text",+ max_length = 8,+ add_special_tokens = True,+ )+ assert view is not dataset+ assert "input_ids" in view[0]+ assert "input_ids" not in dataset[0]+ assert dataset[0]["text"] == "row 0"+++def test_the_view_yields_the_same_row_count_and_order():+ dataset = _text_dataset(32)+ view = attach_online_tokenization(+ dataset,+ tokenizer = _Tokenizer(),+ text_field = "text",+ max_length = 8,+ add_special_tokens = True,+ )+ assert len(view) == len(dataset)+ assert view[5]["input_ids"] == _Tokenizer()(["row 5"], max_length = 8)["input_ids"][0]+++def test_the_view_attests_its_truncation_width():+ """unsloth's `max_length` enforcement reads this instead of scanning every+ row -- and scanning a lazy split is the eager tokenize pass all over again."""+ view = attach_online_tokenization(+ _text_dataset(32),+ tokenizer = _Tokenizer(),+ text_field = "text",+ max_length = 1234,+ add_special_tokens = True,+ )+ assert view.__dict__[TRUNCATION_ATTESTATION_ATTR] == 1234+++def test_the_transformed_view_still_reports_its_backing_columns():+ """Pinned because two consumers depend on it: `Trainer._remove_unused_columns`+ (hence `remove_unused_columns = False`) and unsloth's tokenized-split probe,+ which is why that probe reads a row rather than the metadata."""+ view = attach_online_tokenization(+ _text_dataset(32),+ tokenizer = _Tokenizer(),+ text_field = "text",+ max_length = 8,+ add_special_tokens = True,+ )+ assert "text" in dataset_column_names(view)+ assert "input_ids" not in dataset_column_names(view)+++# ------------------------------------------------------- the double-BOS rule+++def test_add_special_tokens_is_off_when_the_template_emits_a_bos():+ tokenizer = SimpleNamespace(bos_token = "<s>", chat_template = "<s>{{ x }}")+ assert resolve_add_special_tokens(tokenizer, "hello") is False+++def test_add_special_tokens_is_off_when_the_text_already_starts_with_bos():+ tokenizer = SimpleNamespace(bos_token = "<s>", chat_template = "{{ x }}")+ assert resolve_add_special_tokens(tokenizer, "<s>hello") is False+++def test_add_special_tokens_stays_on_otherwise():+ tokenizer = SimpleNamespace(bos_token = "<s>", chat_template = "{{ x }}")+ assert resolve_add_special_tokens(tokenizer, "hello") is True+++def test_no_bos_token_means_add_special_tokens_stays_on():+ tokenizer = SimpleNamespace(bos_token = None, chat_template = "")+ assert resolve_add_special_tokens(tokenizer, "hello") is True+++# ----------------------------------------------------------------- small helpers+++ "grad_accum, workers, prefetch, expected",+ [(4, 4, 4, 16), (32, 2, 2, 32), (1, 0, 0, 1), (0, 0, 0, 1)],+)+def test_prewarm_depth_covers_the_first_step_and_the_queue(grad_accum, workers, prefetch, expected):+ assert prewarm_batch_count(grad_accum, workers, prefetch) == expected+++def test_is_processor_spots_a_wrapped_tokenizer():+ assert is_processor(_Processor()) is True+ assert is_processor(_Tokenizer()) is False+++def test_dataset_supports_with_transform_rejects_none_and_streams():+ assert dataset_supports_with_transform(None) is False+ assert dataset_supports_with_transform(_text_dataset(4)) is True+++def test_a_disabled_decision_never_carries_worker_settings():+ decision = OnlineTokenizationDecision(enabled = False, reason = "test")+ assert decision.workers == 0+ assert decision.prewarm_batches == 0+ assert "off" in decision.as_log_line()diff --git a/studio/backend/tests/test_online_tokenization_runtime.py b/studio/backend/tests/test_online_tokenization_runtime.pynew file mode 100644index 00000000000..33ecdd5393e--- /dev/null+++ b/studio/backend/tests/test_online_tokenization_runtime.py@@ -0,0 +1,283 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""What the mechanism does once it is running, not what the gate decided.++Three claims a gate test cannot reach, each a property of real DataLoader worker+processes pulling real rows through the lazy view:++1. the prewarm barrier does not consume rows training then never sees,+2. the loader the barrier filled is the one ``train()`` uses,+3. those workers are gone once training is over.++Asserted against a real ``DataLoader`` with forked workers over a real+``datasets.Dataset``. No model, no GPU, and a stand-in tokenizer: none of these+claims is about tokenization.+"""++import multiprocessing+import sys++import pytest++sys.path.insert(0, "studio/backend")++from utils.datasets.online_tokenization import ( # noqa: E402+ attach_online_tokenization,+ memoize_train_dataloader,+ release_train_dataloader,+)++datasets = pytest.importorskip("datasets")+torch = pytest.importorskip("torch")++from torch.utils.data import DataLoader, RandomSampler # noqa: E402++WORKERS = 2+PREFETCH = 2+PREWARM = WORKERS * PREFETCH+BATCH = 4+ROWS = 400+++class _Tokenizer:+ """Deterministic and module-level, so a forked worker inherits it intact."""++ bos_token = None+ chat_template = ""++ def __call__(+ self,+ texts,+ truncation = True,+ max_length = 8,+ add_special_tokens = True,+ ):+ if isinstance(texts, str):+ texts = [texts]+ return {"input_ids": [[len(t)] * min(len(t), max_length) for t in texts]}+++def _collate(rows):+ """Keep the rows as they arrive: the assertions are about WHICH rows."""+ return [tuple(row["input_ids"]) for row in rows]+++def _view():+ dataset = datasets.Dataset.from_dict({"text": [f"row {i}" for i in range(ROWS)]})+ return attach_online_tokenization(+ dataset,+ tokenizer = _Tokenizer(),+ text_field = "text",+ max_length = 8,+ add_special_tokens = True,+ )+++class _FakeTrainer:+ """Only the surface the mechanism touches: one loader factory, counted.++ Each call builds a new loader, as ``Trainer.get_train_dataloader`` does:+ transformers rebuilds the train loader every time, which is why+ ``memoize_train_dataloader`` exists.+ """++ def __init__(+ self,+ dataset,+ shuffle = False,+ ):+ self.dataset = dataset+ self.shuffle = shuffle+ self.calls = 0++ def get_train_dataloader(self):+ self.calls += 1+ return DataLoader(+ self.dataset,+ batch_size = BATCH,+ sampler = RandomSampler(self.dataset) if self.shuffle else None,+ shuffle = False,+ num_workers = WORKERS,+ prefetch_factor = PREFETCH,+ persistent_workers = True,+ collate_fn = _collate,+ )+++def _prewarm(trainer, batches):+ """The barrier from ``UnslothTrainer._preflight_first_batch``, verbatim:+ memoize, pull ``batches`` microbatches, drop the local names. The memo keeps+ the filled workers alive past this function."""+ memoize_train_dataloader(trainer)+ loader = trainer.get_train_dataloader()+ iterator = iter(loader)+ next(iterator)+ for _ in range(max(0, batches - 1)):+ try:+ next(iterator)+ except StopIteration:+ break+ del iterator, loader+++def _expected_rows():+ """Every row the view yields, in backing order, as `_collate` renders them."""+ return [tuple([len(f"row {i}")] * min(len(f"row {i}"), 8)) for i in range(ROWS)]+++def _take(loader, count):+ taken = []+ for batch in loader:+ taken.append(batch)+ if len(taken) == count:+ break+ return taken++[email protected](autouse = True)+def _no_leaked_workers():+ """A failing assertion must not leave worker processes behind for the next test."""+ before = set(multiprocessing.active_children())+ yield+ for child in set(multiprocessing.active_children()) - before:+ child.terminate()+ child.join(timeout = 5)+++def test_the_prewarm_re_iterates_from_the_start_rather_than_continuing():+ """The barrier pulls microbatches; training must not begin where it stopped.++ A sequential sampler makes it exact: had the prewarm left the iterator where+ it finished, training would start at row 16 and come up ``PREWARM * BATCH``+ rows short.+ """+ trainer = _FakeTrainer(_view())+ _prewarm(trainer, PREWARM)++ pass_batches = list(trainer.get_train_dataloader())+ rows = [row for batch in pass_batches for row in batch]++ assert rows == _expected_rows(), "training did not start from the first row"+ assert len(rows) == ROWS, f"the prewarm swallowed {ROWS - len(rows)} rows"+ release_train_dataloader(trainer)+++def test_a_shuffled_pass_after_prewarming_still_covers_every_row():+ """Same claim with the sampler a real run uses: nothing is missing, and+ nothing is served twice to make up the count."""+ torch.manual_seed(0)+ trainer = _FakeTrainer(_view(), shuffle = True)+ _prewarm(trainer, PREWARM)++ rows = [row for batch in trainer.get_train_dataloader() for row in batch]++ assert len(rows) == ROWS+ assert sorted(rows) == sorted(_expected_rows())+ release_train_dataloader(trainer)+++def test_train_uses_the_loader_the_barrier_filled():+ """Without the memo the barrier forks workers, fills them, and train()+ throws them away and forks a second set."""+ trainer = _FakeTrainer(_view())+ memoize_train_dataloader(trainer)+ first = trainer.get_train_dataloader()+ _take(first, 1)+ second = trainer.get_train_dataloader()++ assert second is first+ assert trainer.calls == 1, "the underlying factory ran more than once"+ release_train_dataloader(trainer)+++def test_the_workers_are_gone_once_training_is_over():+ """Persistent workers survive train() by design, so something has to end+ them; otherwise Studio merges, quantizes and exports alongside them."""+ before = len(multiprocessing.active_children())+ trainer = _FakeTrainer(_view())+ _prewarm(trainer, PREWARM)+ _take(trainer.get_train_dataloader(), 3)++ during = len(multiprocessing.active_children())+ assert during == before + WORKERS, "the barrier did not fork the workers"++ released = release_train_dataloader(trainer)++ assert released == WORKERS+ assert len(multiprocessing.active_children()) == before+++def test_releasing_puts_the_real_getter_back_and_is_idempotent():+ """It is called from a finally that two paths reach twice, and a trainer+ reused afterwards must rebuild rather than be handed a dead loader."""+ trainer = _FakeTrainer(_view())+ _prewarm(trainer, PREWARM)++ assert release_train_dataloader(trainer) == WORKERS+ assert release_train_dataloader(trainer) == 0+ assert "get_train_dataloader" not in trainer.__dict__+ assert trainer._unsloth_online_memoized is False++ rebuilt = trainer.get_train_dataloader()+ assert trainer.calls == 2+ del rebuilt+++def test_a_wrapped_loader_reports_its_workers_once():+ """`accelerator.prepare` returns a wrapper that shares the inner loader's+ iterator, so a walk over both sees one worker set twice. Observed on a real+ run as a count of 8 for 2 workers."""++ class _Wrapper:+ def __init__(self, inner):+ self.base_dataloader = inner+ self._iterator = None++ trainer = _FakeTrainer(_view())+ memoize_train_dataloader(trainer)+ inner = trainer.get_train_dataloader()+ _take(inner, 1)+ wrapper = _Wrapper(inner)+ wrapper._iterator = inner._iterator+ trainer._unsloth_online_loader_cache["loader"] = wrapper++ assert release_train_dataloader(trainer) == WORKERS+ assert inner._iterator is None and wrapper._iterator is None+++def test_the_memoized_eval_workers_are_released_too():+ """`dataloader_num_workers` is a TrainingArguments setting, so the eval loader+ forks the same workers and transformers parks it in `_eval_dataloaders`; torch+ keeps its `_iterator` alive after the eval loop drains it, so those workers+ outlive train() just as the train ones do."""+ before = len(multiprocessing.active_children())+ trainer = _FakeTrainer(_view())+ _prewarm(trainer, PREWARM)++ eval_loader = DataLoader(+ _view(),+ batch_size = BATCH,+ num_workers = WORKERS,+ prefetch_factor = PREFETCH,+ persistent_workers = True,+ collate_fn = _collate,+ )+ list(eval_loader) # the eval loop drains it; torch retains the iterator+ trainer._eval_dataloaders = {"eval": eval_loader}++ assert eval_loader._iterator is not None, "torch dropped the persistent iterator"+ assert len(multiprocessing.active_children()) == before + 2 * WORKERS++ released = release_train_dataloader(trainer)++ assert released == 2 * WORKERS, "the eval loader's workers were left running"+ assert eval_loader._iterator is None+ assert trainer._eval_dataloaders == {}, "the dead loader is still memoized"+ assert len(multiprocessing.active_children()) == before+++def test_releasing_a_trainer_that_never_went_online_does_nothing():+ trainer = _FakeTrainer(_view())+ assert release_train_dataloader(trainer) == 0+ assert trainer.calls == 0diff --git a/studio/backend/tests/test_online_tokenization_wiring.py b/studio/backend/tests/test_online_tokenization_wiring.pynew file mode 100644index 00000000000..d119d4228e5--- /dev/null+++ b/studio/backend/tests/test_online_tokenization_wiring.py@@ -0,0 +1,492 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""`UnslothTrainer._configure_online_tokenization`: what it changes, and when.++The gate itself is covered by ``test_online_tokenization.py``; this is the+wiring. The method must apply all four parts of the mechanism or leave+``config_args`` and the dataset wrapper exactly as it found them: half-applied is+the dangerous state, since ``skip_prepare_dataset`` without the lazy transform+trains on raw strings. Every degradation path gets a case, driven through the+real method, because "silently takes the old path" is a claim about side effects.+"""++import contextlib+import sys+from types import SimpleNamespace++import pytest++sys.path.insert(0, "studio/backend")++datasets = pytest.importorskip("datasets")+# Importing the trainer imports torch; a runner without it skips the module+# rather than failing collection.+pytest.importorskip("torch")++from utils.datasets.online_tokenization import MIN_ROWS_FOR_ONLINE # noqa: E402+++_STUBBED: list = []+++def _stub_if_missing(name, attrs):+ """Stand in for a dep the CPU-only test job does not install.++ The real one wins whenever it imports, same rule and same ``__spec__ = None``+ (which quiets the trainer's namespace-shadow guard) as+ ``test_training_preflight.py``.+ """+ if name in sys.modules:+ return+ import importlib+ import types+ from unittest.mock import MagicMock++ try:+ importlib.import_module(name)+ return+ except Exception: # noqa: BLE001+ pass+ module = types.ModuleType(name)+ module.__spec__ = None+ for attr in attrs:+ setattr(module, attr, MagicMock())+ sys.modules[name] = module+ _STUBBED.append(name)+++def _stubbed():+ for name, attrs in (+ ("unsloth", ("FastLanguageModel", "FastVisionModel", "is_bfloat16_supported")),+ ("unsloth.chat_templates", ("get_chat_template",)),+ ("trl", ("SFTTrainer", "SFTConfig")),+ ):+ _stub_if_missing(name, attrs)+ try:+ yield+ finally:+ while _STUBBED:+ sys.modules.pop(_STUBBED.pop(), None)+++with _stubbed():+ from core.training.trainer import UnslothTrainer # noqa: E402++_configure = UnslothTrainer._configure_online_tokenization+++ROWS = MIN_ROWS_FOR_ONLINE + 5+++class _Tokenizer:+ bos_token = "<s>"+ chat_template = "{{ messages }}"++ def __call__(+ self,+ texts,+ truncation = True,+ max_length = 8,+ add_special_tokens = True,+ ):+ if isinstance(texts, str):+ texts = [texts]+ return {"input_ids": [[7] * min(len(t), max_length) for t in texts]}+++def _dataset(n = ROWS, columns = None):+ data = {"text": [f"row {i}" for i in range(n)]}+ data.update(columns or {})+ return datasets.Dataset.from_dict(data)+++def _fake_self(**overrides):+ trainer = SimpleNamespace(+ tokenizer = _Tokenizer(),+ model = SimpleNamespace(),+ is_vlm = False,+ is_audio = False,+ is_audio_vlm = False,+ _cuda_audio_used = False,+ _online_prewarm_batches = 0,+ _online_eval_dataset = None,+ )+ for key, value in overrides.items():+ setattr(trainer, key, value)+ trainer._configure_online_tokenization = _configure.__get__(trainer)+ return trainer+++def _config_args(**overrides):+ args = {+ "dataset_text_field": "text",+ "max_seq_length": 2048,+ "packing": False,+ "num_train_epochs": 1,+ "per_device_train_batch_size": 2,+ "gradient_accumulation_steps": 4,+ "dataset_num_proc": 8,+ }+ args.update(overrides)+ return args+++def _run(+ monkeypatch,+ *,+ self_overrides = None,+ config_overrides = None,+ wrapper = None,+ eval_dataset = None,+ **call_overrides,+):+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.delenv("UNSLOTH_STUDIO_ONLINE_TOKENIZATION", raising = False)+ # Pin the TRL hook: these cover the wiring, not the runner's TRL version.+ monkeypatch.setattr(+ "utils.datasets.online_tokenization.trl_supports_skip_prepare_dataset",+ lambda: True,+ )+ trainer = _fake_self(**(self_overrides or {}))+ config_args = _config_args(**(config_overrides or {}))+ wrapper = {"dataset": _dataset()} if wrapper is None else wrapper+ kwargs = dict(+ config_args = config_args,+ dataset = wrapper,+ eval_dataset = eval_dataset,+ training_args = {},+ data_collator = None,+ raw_text_mode = False,+ is_deepseek_ocr = False,+ )+ kwargs.update(call_overrides)+ decision = trainer._configure_online_tokenization(**kwargs)+ return decision, config_args, wrapper, trainer+++# ------------------------------------------------------------------ applied fully+++def test_a_qualifying_run_gets_all_four_parts_of_the_mechanism(monkeypatch):+ decision, config_args, wrapper, trainer = _run(monkeypatch)+ assert decision.enabled, decision.reason+ # 1. lazy view in place of the eager split+ assert wrapper["dataset"].format["type"] == "custom"+ assert "input_ids" in wrapper["dataset"][0]+ # 2. TRL told not to run its own tokenizing map+ assert config_args["dataset_kwargs"] == {"skip_prepare_dataset": True}+ # 3. workers, overlapped with the GPU+ assert config_args["dataloader_num_workers"] >= 2+ assert config_args["dataloader_persistent_workers"] is True+ assert config_args["dataloader_prefetch_factor"] > 0+ # 4. a prewarm depth for _preflight_first_batch to drain+ assert trainer._online_prewarm_batches == decision.prewarm_batches+++def test_the_lazy_view_yields_what_the_eager_map_would_have(monkeypatch):+ """Same tokenizer, same truncation, same `add_special_tokens`: the rows the+ collator sees must be identical, or the loss moves."""+ _, config_args, wrapper, trainer = _run(monkeypatch)+ expected = _Tokenizer()(["row 3"], max_length = 2048)["input_ids"][0]+ assert wrapper["dataset"][3]["input_ids"] == expected+++def test_an_eval_split_is_transformed_with_the_same_settings(monkeypatch):+ """`skip_prepare_dataset` skips TRL's EVAL preparation too, so an untouched+ eval split would reach the model as raw strings."""+ eval_split = _dataset(64)+ decision, _, _, trainer = _run(monkeypatch, eval_dataset = eval_split)+ assert decision.enabled, decision.reason+ assert trainer._online_eval_dataset is not eval_split+ assert "input_ids" in trainer._online_eval_dataset[0]+++def test_the_eval_split_gets_its_own_double_bos_probe(monkeypatch):+ """TRL runs `_prepare_dataset` once per split, so `add_special_tokens` comes+ from each split's own first row; reusing the train answer would shift every+ eval sequence by a token whenever the splits disagree about a leading BOS."""++ class _Recording(_Tokenizer):+ def __init__(self):+ self.seen = []++ def __call__(+ self,+ texts,+ truncation = True,+ max_length = 8,+ add_special_tokens = True,+ ):+ self.seen.append(add_special_tokens)+ return super().__call__(+ texts,+ truncation = truncation,+ max_length = max_length,+ add_special_tokens = add_special_tokens,+ )++ # train rows are plain; the eval split already carries the BOS token.+ eval_split = datasets.Dataset.from_dict(+ {"text": [f"{_Tokenizer.bos_token}row {i}" for i in range(64)]}+ )+ tokenizer = _Recording()+ decision, _, wrapper, trainer = _run(+ monkeypatch,+ self_overrides = {"tokenizer": tokenizer},+ eval_dataset = eval_split,+ )+ assert decision.enabled, decision.reason++ tokenizer.seen.clear()+ wrapper["dataset"][0]+ assert tokenizer.seen == [True], "plain train rows keep the tokenizer's specials"++ tokenizer.seen.clear()+ trainer._online_eval_dataset[0]+ assert tokenizer.seen == [False], "an eval split that already has BOS must not get a second"+++# ---------------------------------------------------- degradation: nothing touched+++def _assert_untouched(config_args, wrapper, trainer, original):+ assert wrapper["dataset"] is original+ for key in (+ "dataset_kwargs",+ "remove_unused_columns",+ "dataloader_num_workers",+ "dataloader_prefetch_factor",+ "dataloader_persistent_workers",+ ):+ assert key not in config_args, f"{key} leaked onto the eager path"+ assert trainer._online_prewarm_batches == 0+++def test_packing_on_takes_the_old_path(monkeypatch):+ original = _dataset()+ decision, config_args, wrapper, trainer = _run(+ monkeypatch, wrapper = {"dataset": original}, config_overrides = {"packing": True}+ )+ assert not decision.enabled and "packing" in decision.reason+ _assert_untouched(config_args, wrapper, trainer, original)+++def test_a_streaming_split_takes_the_old_path(monkeypatch):+ stream = _dataset(64).to_iterable_dataset()+ decision, config_args, wrapper, trainer = _run(monkeypatch, wrapper = {"dataset": stream})+ assert not decision.enabled+ _assert_untouched(config_args, wrapper, trainer, stream)+++def test_a_vlm_takes_the_old_path(monkeypatch):+ original = _dataset()+ decision, config_args, wrapper, trainer = _run(+ monkeypatch, wrapper = {"dataset": original}, self_overrides = {"is_vlm": True}+ )+ assert not decision.enabled and "multimodal" in decision.reason+ _assert_untouched(config_args, wrapper, trainer, original)+++def test_an_already_tokenized_split_takes_the_old_path(monkeypatch):+ original = _dataset(columns = {"input_ids": [[1, 2]] * ROWS})+ decision, config_args, wrapper, trainer = _run(monkeypatch, wrapper = {"dataset": original})+ assert not decision.enabled and "input_ids" in decision.reason+ _assert_untouched(config_args, wrapper, trainer, original)++[email protected]("platform", ["win32", "darwin"])+def test_windows_and_macos_take_the_old_path(monkeypatch, platform):+ original = _dataset()+ monkeypatch.setattr(sys, "platform", platform)+ monkeypatch.delenv("UNSLOTH_STUDIO_ONLINE_TOKENIZATION", raising = False)+ trainer = _fake_self()+ config_args = _config_args()+ wrapper = {"dataset": original}+ decision = trainer._configure_online_tokenization(+ config_args = config_args,+ dataset = wrapper,+ eval_dataset = None,+ training_args = {},+ data_collator = None,+ raw_text_mode = False,+ is_deepseek_ocr = False,+ )+ assert not decision.enabled and platform in decision.reason+ _assert_untouched(config_args, wrapper, trainer, original)+++def test_a_custom_collator_takes_the_old_path(monkeypatch):+ original = _dataset()+ decision, config_args, wrapper, trainer = _run(+ monkeypatch, wrapper = {"dataset": original}, data_collator = object()+ )+ assert not decision.enabled and "collator" in decision.reason+ _assert_untouched(config_args, wrapper, trainer, original)+++def test_completion_masking_takes_the_old_path(monkeypatch):+ """`train_on_responses_only` maps and filters the trainer's split, which on+ a lazy view would materialise the whole thing and can drop rows."""+ original = _dataset()+ decision, config_args, wrapper, trainer = _run(+ monkeypatch,+ wrapper = {"dataset": original},+ training_args = {"train_on_completions": True},+ )+ assert not decision.enabled and "completions" in decision.reason+ _assert_untouched(config_args, wrapper, trainer, original)+++def test_raw_text_and_cpt_take_the_old_path(monkeypatch):+ original = _dataset()+ decision, *_ = _run(monkeypatch, wrapper = {"dataset": original}, raw_text_mode = True)+ assert not decision.enabled and "raw-text" in decision.reason++ original = _dataset()+ decision, config_args, wrapper, trainer = _run(+ monkeypatch, wrapper = {"dataset": original}, training_args = {"is_cpt": True}+ )+ assert not decision.enabled and "pretraining" in decision.reason+ _assert_untouched(config_args, wrapper, trainer, original)+++def test_a_broken_gate_degrades_instead_of_failing_the_run(monkeypatch):+ """The feature is an optimisation. Any unexpected failure in it must cost+ the user speed, never the run."""+ original = _dataset()++ def _explode(**kwargs):+ raise RuntimeError("boom")++ monkeypatch.setattr("utils.datasets.online_tokenization.decide_online_tokenization", _explode)+ decision, config_args, wrapper, trainer = _run(monkeypatch, wrapper = {"dataset": original})+ assert not decision.enabled and "boom" in decision.reason+ _assert_untouched(config_args, wrapper, trainer, original)+++def test_a_failure_while_attaching_rolls_the_dataset_back(monkeypatch):+ original = _dataset()++ def _explode(dataset, **kwargs):+ raise RuntimeError("attach failed")++ monkeypatch.setattr("utils.datasets.online_tokenization.attach_online_tokenization", _explode)+ decision, config_args, wrapper, trainer = _run(monkeypatch, wrapper = {"dataset": original})+ assert not decision.enabled and "attach failed" in decision.reason+ _assert_untouched(config_args, wrapper, trainer, original)+++# ---------------------------------------------------------------- step-capped runs+++def test_a_step_cap_is_resolved_into_passes_rather_than_guessed(monkeypatch):+ """`max_steps` alone reads as "unknown length" in the gate; Studio knows the+ row count and the microbatch size, so it answers the question here."""+ decision, _, _, _ = _run(monkeypatch, config_overrides = {"max_steps": 30, "num_train_epochs": 1})+ assert decision.enabled, decision.reason+++def test_a_step_cap_that_exceeds_one_pass_takes_the_old_path(monkeypatch):+ original = _dataset()+ # 100_000 steps x 2 x 4 = 800k rows over a 10_005-row split: 80 passes.+ decision, config_args, wrapper, trainer = _run(+ monkeypatch,+ wrapper = {"dataset": original},+ config_overrides = {"max_steps": 100_000},+ )+ assert not decision.enabled and "one pass" in decision.reason+ _assert_untouched(config_args, wrapper, trainer, original)+++def test_world_size_scales_the_rows_a_step_consumes(monkeypatch):+ """DDP consumes `batch x accum x world_size` rows per step, so ignoring the+ rank count would call a multi-pass run single-pass."""+ monkeypatch.setenv("WORLD_SIZE", "8")+ original = _dataset()+ decision, config_args, wrapper, trainer = _run(+ monkeypatch,+ wrapper = {"dataset": original},+ config_overrides = {"max_steps": 200},+ )+ assert not decision.enabled and "one pass" in decision.reason+ _assert_untouched(config_args, wrapper, trainer, original)+++# ------------------------------------------------------------- the prewarm barrier+++def _preflight_self(loader_calls, batches):+ from utils.datasets.online_tokenization import memoize_train_dataloader # noqa: F401++ class _Loader:+ def __init__(self):+ self.iterations = 0++ def __iter__(self):+ self.iterations += 1+ return iter(batches)++ class _Inner:+ def __init__(self):+ self.loader = _Loader()++ def get_train_dataloader(self):+ loader_calls.append(1)+ return self.loader++ trainer = SimpleNamespace(+ trainer = _Inner(),+ model_name = "org/model",+ tokenizer = None,+ _online_prewarm_batches = 0,+ )+ trainer._preflight_first_batch = UnslothTrainer._preflight_first_batch.__get__(trainer)+ trainer._chat_template_renders_empty = UnslothTrainer._chat_template_renders_empty.__get__(+ trainer+ )+ return trainer+++def test_the_eager_path_still_pulls_exactly_one_batch():+ """No prewarm depth means today's behaviour, unchanged."""+ import torch++ batch = {"input_ids": torch.ones(1, 4, dtype = torch.long)}+ calls: list = []+ trainer = _preflight_self(calls, [batch, batch, batch])+ assert trainer._preflight_first_batch() is None+ assert len(calls) == 1+ assert not getattr(trainer.trainer, "_unsloth_online_memoized", False)+++def test_the_prewarm_drains_the_requested_depth_and_keeps_the_loader():+ import torch++ batch = {"input_ids": torch.ones(1, 4, dtype = torch.long)}+ calls: list = []+ trainer = _preflight_self(calls, [batch] * 32)+ trainer._online_prewarm_batches = 16+ assert trainer._preflight_first_batch() is None+ # The memo is what makes the barrier mean anything: transformers rebuilds the+ # train loader every call, so without it train() forks a second worker set.+ assert trainer.trainer._unsloth_online_memoized is True+ assert trainer.trainer.get_train_dataloader() is trainer.trainer.loader+ assert len(calls) == 1+++def test_a_short_split_prewarms_fewer_batches_rather_than_failing():+ import torch++ batch = {"input_ids": torch.ones(1, 4, dtype = torch.long)}+ trainer = _preflight_self([], [batch, batch])+ trainer._online_prewarm_batches = 16+ assert trainer._preflight_first_batch() is None+++def test_an_empty_split_still_reports_the_no_rows_error():+ trainer = _preflight_self([], [])+ trainer._online_prewarm_batches = 16+ error = trainer._preflight_first_batch()+ assert error and "no training rows" in errordiff --git a/studio/backend/utils/datasets/online_tokenization.py b/studio/backend/utils/datasets/online_tokenization.pynew file mode 100644index 00000000000..10cb551a8a0--- /dev/null+++ b/studio/backend/utils/datasets/online_tokenization.py@@ -0,0 +1,741 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Online (overlapped) dataset tokenization for the plain-text SFT path.++TRL's ``_prepare_dataset`` maps over every row before ``train()`` may begin: the+largest fixed startup cost (97s of 106s of preparation on 100k rows of+OpenMathReasoning at ``dataset_num_proc = 8``), and all of it overlappable with+the GPU. This module moves it into the DataLoader workers. Four pieces, all+needed together:++1. ``datasets.Dataset.with_transform`` attaches a per-batch tokenizer that runs+ on ``__getitem__``. It returns an immutable *view*; ``set_transform`` would+ mutate the caller's object, which the preview/eval code also holds.+2. TRL gets ``dataset_kwargs = {"skip_prepare_dataset": True}`` so it does not+ map over the view, materialising the pass we are avoiding. Studio already+ uses that hook for the VLM branch.+3. ``dataloader_num_workers`` > 0 with prefetch and persistent workers, so the+ tokenizer runs overlapped with the GPU.+4. A prewarm barrier pulls ``max(grad_accum, workers * prefetch)`` microbatches+ before ``train()``: plain prefetch does not promise the first ``__next__``.++The transform reproduces ``unsloth_zoo.dataset_utils.sft_prepare_dataset``'s+tokenize step exactly (truncation, ``max_length``, double-BOS rule), so rows are+byte-identical to the eager path. Anything where that is not provable stays+eager; see :func:`decide_online_tokenization`.++Two costs worth stating. The pass gate counts TRAIN passes only: a lazy eval+split is re-tokenized on every evaluation where the eager map tokenized once,+which scales with ``eval_steps``. And the workers are persistent by design (the+barrier's workers must survive into ``train()``), so they need explicit shutdown+at the end; see :func:`release_train_dataloader`.+"""++from __future__ import annotations++import os+import sys+from dataclasses import dataclass, field+from typing import Any, Optional++from loggers import get_logger++logger = get_logger(__name__)+++# Below this the eager map costs seconds and does not pay for four workers. 10k+# is the smallest size the A/B measured a win at (first step 23.1s -> 12.1s).+MIN_ROWS_FOR_ONLINE = 10_000++# Measured: four workers stayed ahead of a B200 on a 0.6B model; more only costs.+MAX_ONLINE_WORKERS = 4++# Fewer than this and the tokenizer falls behind the GPU: slower steps, not a+# faster start.+MIN_ONLINE_WORKERS = 2++DEFAULT_PREFETCH_FACTOR = 4++ENV_FLAG = "UNSLOTH_STUDIO_ONLINE_TOKENIZATION"++# Presence means already tokenized, or a prompt/completion split the zoo+# tokenizes with a different function.+_PRETOKENIZED_COLUMNS = ("input_ids", "labels", "prompt", "completion")++# Stamped on the view by :func:`attach_online_tokenization`; unsloth's+# `max_length` scan reads it as proof every row is already truncated to that+# width, instead of reading every row of a lazy split -- the eager pass again.+TRUNCATION_ATTESTATION_ATTR = "_unsloth_truncated_to"+++@dataclass(frozen = True)+class OnlineTokenizationDecision:+ """Whether this run takes the online path, and with what settings.++ ``enabled`` False means behave exactly as before; ``reason`` names the gate+ that decided it, for the training log.+ """++ enabled: bool+ reason: str+ workers: int = 0+ prefetch_factor: int = 0+ prewarm_batches: int = 0+ checks: tuple = field(default = ())++ def as_log_line(self) -> str:+ if not self.enabled:+ return f"Online tokenization: off ({self.reason})"+ return (+ f"Online tokenization: on ({self.reason}); "+ f"workers={self.workers}, prefetch={self.prefetch_factor}, "+ f"prewarm={self.prewarm_batches} microbatches"+ )+++def env_override() -> Optional[bool]:+ """``UNSLOTH_STUDIO_ONLINE_TOKENIZATION``: 0/false forces off, 1/true forces on.++ Unset returns None and the gates decide. Forcing on only drops the heuristic+ gates (row count, epoch count); correctness gates always stand, since the+ lazy path on a VLM or pre-tokenized split does not train differently, it fails.+ """+ raw = os.environ.get(ENV_FLAG)+ if raw is None:+ return None+ raw = raw.strip().lower()+ if raw in ("0", "false", "no", "off"):+ return False+ if raw in ("1", "true", "yes", "on"):+ return True+ return None+++def dataloader_worker_start_method() -> Optional[str]:+ """How DataLoader workers will actually start, read without fixing it.++ ``get_start_method()`` with no argument RESOLVES and pins the default, after+ which ``set_start_method()`` raises. So: the explicitly set method if any,+ else the platform default, which is ``get_all_start_methods()[0]`` and costs+ nothing to read.+ """+ try:+ import multiprocessing++ explicit = multiprocessing.get_start_method(allow_none = True)+ if explicit:+ return explicit+ methods = multiprocessing.get_all_start_methods()+ return methods[0] if methods else None+ except Exception: # noqa: BLE001 - unreadable reads as "not fork"+ return None+++def platform_supports_dataloader_workers() -> bool:+ """Fork, and only fork.++ The hazard is ``spawn``, not the OS: a spawned worker re-imports the entry+ point against a fresh ``sys.path``, and Studio's is modified in-process, so+ the import fails (why ``trainer.py`` already forces 0 workers on Windows and+ macOS, which default to spawn). A Linux process set to ``spawn`` or+ ``forkserver`` is the same hazard, and a platform check cannot see it.+ """+ if sys.platform in ("win32", "darwin"):+ return False+ return dataloader_worker_start_method() == "fork"+++def trl_supports_skip_prepare_dataset() -> bool:+ """Feature-detect the ``skip_prepare_dataset`` hook.++ ``SFTConfig`` must carry ``dataset_kwargs`` and ``SFTTrainer.__init__`` must+ read the key. If the source is unreadable (compiled or patched build) the+ field alone decides: Studio's VLM branch has relied on this hook across every+ supported TRL, so a missing source is not evidence of a missing hook.+ """+ try:+ import dataclasses++ from trl import SFTConfig, SFTTrainer+ except Exception: # noqa: BLE001 - no TRL means no SFT run at all+ return False++ try:+ names = {f.name for f in dataclasses.fields(SFTConfig)}+ except Exception: # noqa: BLE001+ names = set(getattr(SFTConfig, "__annotations__", {}) or {})+ if "dataset_kwargs" not in names:+ return False++ try:+ import inspect+ source = inspect.getsource(SFTTrainer.__init__)+ except Exception: # noqa: BLE001+ return True+ return "skip_prepare_dataset" in source+++def dataset_supports_with_transform(dataset: Any) -> bool:+ """A map-style ``datasets.Dataset`` with the lazy-view API.++ Not a ``hasattr`` check: recent ``IterableDataset`` also has+ ``with_transform``, and a stream is exactly what must not be touched.+ """+ try:+ from datasets import Dataset as HfDataset+ from datasets import IterableDataset as HfIterableDataset+ except Exception: # noqa: BLE001+ return False+ if isinstance(dataset, HfIterableDataset):+ return False+ if not isinstance(dataset, HfDataset):+ return False+ return callable(getattr(dataset, "with_transform", None))+++def is_processor(processing_class: Any) -> bool:+ """True for a multimodal processor rather than a plain tokenizer.++ ``ProcessorMixin`` first, then the ``hasattr(x, "tokenizer")`` test+ ``sft_prepare_dataset`` itself uses.+ """+ try:+ from transformers import ProcessorMixin+ if isinstance(processing_class, ProcessorMixin):+ return True+ except Exception: # noqa: BLE001+ pass+ return hasattr(processing_class, "tokenizer")+++def model_needs_token_type_ids(model: Any, processing_class: Any) -> bool:+ """Mirror of the zoo's ``_needs_token_type_ids`` probe.++ Gemma-family modules build their causal mask from ``token_type_ids``, so the+ zoo asks for them. Rather than reproduce that column lazily, decline those+ models and leave them eager.+ """+ marker = "create_" + "causal_mask_mapping"+ try:+ candidates = [model, getattr(model, "model", None)]+ for candidate in candidates:+ if candidate is None:+ continue+ module = sys.modules.get(type(candidate).__module__)+ if module is not None and hasattr(module, marker):+ return True+ except Exception: # noqa: BLE001+ return True # unprobeable reads as "needs them", i.e. stay eager++ try:+ for base in type(processing_class).__mro__:+ base_module = getattr(base, "__module__", "") or ""+ if "transformers.models." not in base_module:+ continue+ modelling = base_module.replace(".processing_", ".modeling_")+ module = sys.modules.get(modelling)+ if module is not None and hasattr(module, marker):+ return True+ except Exception: # noqa: BLE001+ return True+ return False+++def dataset_column_names(dataset: Any) -> tuple:+ """Backing column names, or () when the split cannot answer."""+ names = getattr(dataset, "column_names", None)+ if isinstance(names, dict):+ return tuple({c for value in names.values() for c in (value or [])})+ if names is None:+ return ()+ return tuple(names)+++def text_column_defect(dataset: Any, text_field: str) -> Optional[str]:+ """Why ``text_field`` cannot be tokenized lazily, or None when it can.++ The eager map fails on a null or non-string row inside the constructor, in+ seconds. The lazy view fails only when the sampler draws that row, possibly+ hours in with checkpoints behind it -- the one way this feature makes a+ failing run worse rather than slower, so those shapes are refused up front.++ Both checks are metadata, not rows: dtype off the schema, and Arrow's+ per-chunk ``null_count``. A ``select``ed split keeps the full backing table,+ so its null count over-reports, vetoing a split that might have been fine and+ never the other way round.+ """+ try:+ from datasets import Value+ features = getattr(dataset, "features", None) or {}+ feature = features.get(text_field)+ except Exception: # noqa: BLE001 - unreadable schema stays eager+ return f"the type of '{text_field}' could not be read"++ if not isinstance(feature, Value) or feature.dtype not in ("string", "large_string"):+ described = getattr(feature, "dtype", None) or type(feature).__name__+ return f"'{text_field}' holds {described}, not strings"++ try:+ nulls = int(dataset.data.column(text_field).null_count)+ except Exception: # noqa: BLE001+ return f"'{text_field}' could not be checked for null rows"+ if nulls > 0:+ return f"'{text_field}' has {nulls:,} null row{'' if nulls == 1 else 's'}"+ return None+++def resolve_worker_count(desired: Optional[int] = None) -> int:+ """How many DataLoader workers this host can spare, 0 for "do not".++ Sized by the same policy as ``dataset_num_proc`` (CPU affinity and cgroup+ quota, not raw ``os.cpu_count()``), capped at :data:`MAX_ONLINE_WORKERS`.+ """+ if not platform_supports_dataloader_workers():+ return 0+ try:+ from utils.hardware import dataset_map_num_proc+ available = dataset_map_num_proc(desired, serial_as_none = True)+ except Exception: # noqa: BLE001+ available = None+ if not available or available < MIN_ONLINE_WORKERS:+ return 0+ return int(min(available, MAX_ONLINE_WORKERS))+++def prewarm_batch_count(grad_accum: int, workers: int, prefetch_factor: int) -> int:+ """Microbatches to pull before ``train()``.++ ``grad_accum`` because step 1 needs that many, and ``workers *+ prefetch_factor`` because that is the in-flight depth to fill.+ """+ return max(1, int(grad_accum or 1), int(workers or 0) * int(prefetch_factor or 0))+++def _epoch_count(num_train_epochs: Optional[float], max_steps: Optional[int]) -> float:+ """Epochs this run will actually perform.++ ``max_steps > 0`` wins over ``num_train_epochs``, and a step-capped run is+ not assumed to be one epoch: unknown (``inf``) unless the caller resolved it.+ """+ if max_steps and int(max_steps) > 0:+ return float("inf")+ try:+ return float(num_train_epochs if num_train_epochs is not None else 1.0)+ except (TypeError, ValueError):+ return float("inf")+++def decide_online_tokenization(+ *,+ dataset: Any,+ eval_dataset: Any = None,+ processing_class: Any = None,+ model: Any = None,+ text_field: str = "text",+ packing: bool = False,+ is_vlm: bool = False,+ is_audio: bool = False,+ is_audio_vlm: bool = False,+ is_deepseek_ocr: bool = False,+ is_cpt: bool = False,+ raw_text_mode: bool = False,+ has_custom_collator: bool = False,+ train_on_completions: bool = False,+ dataset_streaming: bool = False,+ num_train_epochs: Optional[float] = 1.0,+ max_steps: Optional[int] = 0,+ grad_accum: int = 1,+ row_count: Optional[int] = None,+ workers: Optional[int] = None,+ prefetch_factor: int = DEFAULT_PREFETCH_FACTOR,+ resolved_max_steps_epochs: Optional[float] = None,+) -> OnlineTokenizationDecision:+ """Decide whether this run may tokenize online. Pure, GPU-free, testable.++ Every gate is a veto, correctness before cost, so the log reads "off (VLM)"+ rather than "off (dataset too small)" when both are true.+ """+ checks: list = []++ def veto(reason: str) -> OnlineTokenizationDecision:+ checks.append((reason, False))+ return OnlineTokenizationDecision(enabled = False, reason = reason, checks = tuple(checks))++ override = env_override()+ if override is False:+ return veto(f"{ENV_FLAG}=0")++ # ---- correctness gates: never overridable ----+ if not platform_supports_dataloader_workers():+ if sys.platform in ("win32", "darwin"):+ return veto(f"{sys.platform} spawns DataLoader workers")+ return veto(+ f"DataLoader workers would start by "+ f"{dataloader_worker_start_method() or 'an unknown method'}, not fork"+ )+ if not trl_supports_skip_prepare_dataset():+ return veto("this TRL has no skip_prepare_dataset hook")+ if is_vlm or is_audio_vlm or is_deepseek_ocr:+ return veto("multimodal model")+ if is_audio:+ return veto("audio model")+ if is_cpt:+ return veto("continued pretraining")+ if raw_text_mode:+ return veto("raw-text mode")+ if has_custom_collator:+ return veto("custom data collator")+ if packing:+ return veto("packing enabled")+ if train_on_completions:+ return veto("train on completions")+ if dataset_streaming:+ return veto("streaming dataset")+ if not dataset_supports_with_transform(dataset):+ return veto("dataset is not a map-style datasets.Dataset")+ if processing_class is None or is_processor(processing_class):+ return veto("processor rather than a plain tokenizer")+ if not callable(processing_class):+ return veto("tokenizer is not callable")+ if model_needs_token_type_ids(model, processing_class):+ return veto("model needs token_type_ids")++ columns = dataset_column_names(dataset)+ if text_field not in columns:+ return veto(f"no '{text_field}' column to tokenize")+ already = [c for c in _PRETOKENIZED_COLUMNS if c in columns]+ if already:+ return veto(f"dataset already carries {already[0]}")+ defect = text_column_defect(dataset, text_field)+ if defect is not None:+ return veto(defect)++ if eval_dataset is not None:+ if not dataset_supports_with_transform(eval_dataset):+ return veto("eval split is not a map-style datasets.Dataset")+ eval_columns = dataset_column_names(eval_dataset)+ if text_field not in eval_columns:+ return veto(f"eval split has no '{text_field}' column")+ if any(c in eval_columns for c in _PRETOKENIZED_COLUMNS):+ return veto("eval split is already tokenized")+ eval_defect = text_column_defect(eval_dataset, text_field)+ if eval_defect is not None:+ return veto(f"eval split: {eval_defect}")++ resolved_workers = resolve_worker_count() if workers is None else int(workers)+ if resolved_workers < MIN_ONLINE_WORKERS:+ return veto("not enough CPU workers to stay ahead of the GPU")+ checks.append(("correctness gates", True))++ # ---- cost gates: the escape hatch may override these ----+ forced = override is True++ if row_count is None:+ try:+ row_count = len(dataset)+ except Exception: # noqa: BLE001+ row_count = None+ if not forced and (row_count is None or row_count < MIN_ROWS_FOR_ONLINE):+ return veto(f"dataset smaller than {MIN_ROWS_FOR_ONLINE:,} rows")++ epochs = (+ float(resolved_max_steps_epochs)+ if resolved_max_steps_epochs is not None+ else _epoch_count(num_train_epochs, max_steps)+ )+ # The lazy view re-tokenizes every pass: +2.9% of steady-state time measured+ # over 2.4 epochs (237.2s eager vs 244.1s online, identical loss). One pass+ # pays that once against a 97s map; each extra epoch pays again while the+ # saving stays fixed, so anything past a single pass keeps the Arrow cache.+ if not forced and epochs > 1.0:+ detail = (+ "step-capped run of unknown length"+ if epochs == float("inf")+ else (f"{epochs:g} epochs")+ )+ return veto(f"more than one pass over the data ({detail})")++ checks.append(("cost gates", True))+ prewarm = prewarm_batch_count(grad_accum, resolved_workers, prefetch_factor)+ reason = "forced by " + ENV_FLAG if forced else "plain-text single-pass SFT run"+ return OnlineTokenizationDecision(+ enabled = True,+ reason = reason,+ workers = resolved_workers,+ prefetch_factor = int(prefetch_factor),+ prewarm_batches = prewarm,+ checks = tuple(checks),+ )+++def resolve_add_special_tokens(processing_class: Any, sample_text: Optional[str]) -> bool:+ """The zoo's double-BOS rule, copied rather than re-derived (getting it wrong+ shifts every row by a token).++ ``sft_prepare_dataset`` turns ``add_special_tokens`` off when the rendered+ text already starts with BOS, or when the chat template emits one.+ """+ tokenizer = getattr(processing_class, "tokenizer", None)+ chat_template = getattr(processing_class, "chat_template", "") or ""+ if not chat_template and tokenizer is not None:+ chat_template = getattr(tokenizer, "chat_template", "") or ""++ bos_token = getattr(processing_class, "bos_token", None) or getattr(+ tokenizer, "bos_token", None+ )+ if bos_token is None:+ return True+ if isinstance(sample_text, (list, tuple)):+ sample_text = sample_text[0] if sample_text else None+ if sample_text is not None and str(sample_text).startswith(bos_token):+ return False+ if bos_token in chat_template:+ return False+ return True+++def build_tokenizing_transform(+ tokenizer: Any, text_field: str, max_length: int, add_special_tokens: bool+):+ """A batched ``with_transform`` callable equivalent to the zoo's ``_tokenize``.++ ``with_transform`` passes a dict of column lists and wants the same row count+ back, so the batch is encoded in one call, as the eager map does.++ The tokenizer's whole output is passed through, not just ``input_ids``: the+ eager map keeps it too (``remove_columns`` drops only original columns), and+ the collator and attention dispatcher branch on which keys are present.+ """++ def transform(batch: dict) -> dict:+ texts = batch[text_field]+ encoded = tokenizer(+ texts,+ truncation = True,+ max_length = max_length,+ add_special_tokens = add_special_tokens,+ )+ return dict(encoded)++ return transform+++def attach_online_tokenization(+ dataset: Any, *, tokenizer: Any, text_field: str, max_length: int, add_special_tokens: bool+):+ """Return an immutable lazily-tokenizing view of ``dataset``.++ ``with_transform``, not ``set_transform``: the caller's object is also held by+ the dataset preview and row-count checks, and mutating it in place would+ silently change what those see.++ ``columns = [text_field]`` avoids materialising large unused columns on every+ ``__getitem__``.++ The view is stamped with :data:`TRUNCATION_ATTESTATION_ATTR` so unsloth's+ ``max_length`` enforcement trusts the cap instead of reading every row, which+ on a lazy split is the eager tokenize pass again.+ """+ transform = build_tokenizing_transform(tokenizer, text_field, max_length, add_special_tokens)+ try:+ view = dataset.with_transform(transform, columns = [text_field])+ except TypeError:+ # `datasets` without the `columns` kwarg: only the narrow read is lost.+ view = dataset.with_transform(transform)+ try:+ setattr(view, TRUNCATION_ATTESTATION_ATTR, int(max_length))+ except Exception: # noqa: BLE001 - a split that refuses attributes just gets scanned+ pass+ return view+++def first_sample_text(dataset: Any, text_field: str) -> Optional[str]:+ """The first row's rendered text, for the double-BOS probe. Never raises."""+ try:+ row = dataset[0]+ except Exception: # noqa: BLE001+ try:+ row = next(iter(dataset))+ except Exception: # noqa: BLE001+ return None+ if not isinstance(row, dict):+ return None+ value = row.get(text_field)+ if isinstance(value, (list, tuple)):+ value = value[0] if value else None+ return value if isinstance(value, str) else None+++def online_config_args(decision: OnlineTokenizationDecision) -> dict:+ """The ``SFTConfig`` keys the online path needs, and nothing else.++ ``remove_unused_columns`` must be False: ``_remove_unused_columns`` reads+ ``column_names``, which on a transformed split reports the backing table, so+ it would strip the column the transform reads.+ """+ return {+ "dataset_kwargs": {"skip_prepare_dataset": True},+ "remove_unused_columns": False,+ "dataloader_num_workers": decision.workers,+ "dataloader_prefetch_factor": decision.prefetch_factor,+ "dataloader_persistent_workers": True,+ }+++def memoize_train_dataloader(trainer: Any) -> bool:+ """Make the prewarmed train DataLoader the one ``train()`` actually uses.++ transformers memoizes only the EVAL loaders (``_eval_dataloaders``); the train+ loader is rebuilt every call, so without this ``train()`` discards the+ barrier's warmed workers and forks four more.++ ``_inner_training_loop`` calls ``get_train_dataloader()`` once, so a one-shot+ memo changes no semantics and avoids preparing the dataset twice. The cache+ lives on the trainer, not only in the closure, so+ :func:`release_train_dataloader` can reach the loader and shut it down.+ Returns whether the memo was installed.+ """+ getter = getattr(trainer, "get_train_dataloader", None)+ if getter is None or getattr(trainer, "_unsloth_online_memoized", False):+ return False++ cache: dict = {}++ def _memoized():+ if "loader" not in cache:+ cache["loader"] = getter()+ return cache["loader"]++ try:+ trainer.get_train_dataloader = _memoized+ trainer._unsloth_online_loader_cache = cache+ trainer._unsloth_online_memoized = True+ except Exception: # noqa: BLE001 - a trainer that refuses attributes keeps today's behaviour+ return False+ return True+++def _nested_loaders(loader: Any):+ """``loader`` and whatever it wraps, outermost first.++ ``accelerator.prepare`` returns a ``DataLoaderShard`` or a wrapper holding+ ``base_dataloader`` depending on version; the workers belong to whichever+ object owns ``_iterator``.+ """+ seen: list = []+ current = loader+ for _ in range(4): # a wrapper chain, not a graph: bounded on purpose+ if current is None or any(current is item for item in seen):+ break+ seen.append(current)+ current = getattr(current, "base_dataloader", None) or getattr(current, "dataloader", None)+ return seen+++def _shutdown_loader_workers(loader: Any, shut: list) -> int:+ """Shut down every worker set ``loader`` (or a wrapper of it) still holds.++ ``shut`` carries iterators already stopped: a wrapper and its inner loader+ share one iterator, so count it once but clear the reference at every level.+ """+ released = 0+ for candidate in _nested_loaders(loader):+ iterator = getattr(candidate, "_iterator", None)+ shutdown = getattr(iterator, "_shutdown_workers", None)+ if not callable(shutdown):+ continue+ try:+ if not any(iterator is seen for seen in shut):+ shut.append(iterator)+ released += len(getattr(iterator, "_workers", ()) or ())+ shutdown()+ candidate._iterator = None+ except Exception as exc: # noqa: BLE001 - a wedged worker must not fail the run+ logger.warning(f"Online tokenization worker shutdown failed: {exc}")+ return released+++def release_train_dataloader(trainer: Any) -> int:+ """Shut down the online run's persistent DataLoader workers. Returns how many.++ Covers the prewarmed train loader and the eval loaders transformers memoized+ in ``_eval_dataloaders``; both were built with the same worker settings.++ ``dataloader_persistent_workers = True`` lets the barrier's workers survive+ into ``train()``, and equally keeps them alive after it returns: memo holds+ loader holds iterator holds the processes, so nothing drops the last+ reference. Studio then merges, quantizes and exports -- the most+ memory-hungry part of a run -- with four forked children still resident, each+ holding the parent's CUDA file descriptors.++ Idempotent and never raises: called from a ``finally``, including where+ training never started.+ """+ released = 0+ cache = getattr(trainer, "_unsloth_online_loader_cache", None)+ loader = cache.pop("loader", None) if isinstance(cache, dict) else None++ # Restore the real bound method, so a reused trainer rebuilds instead of+ # handing out a loader whose workers just went away.+ try:+ trainer.__dict__.pop("get_train_dataloader", None)+ trainer._unsloth_online_memoized = False+ trainer._unsloth_online_loader_cache = None+ except Exception: # noqa: BLE001+ pass++ shut: list = []+ released += _shutdown_loader_workers(loader, shut)++ # Worker count is a TrainingArguments setting, so the EVAL loader gets the+ # same workers and `persistent_workers = True`; transformers keeps it in+ # `_eval_dataloaders` (unchanged 4.51.3 through 5.5.0) and torch keeps its+ # `_iterator` alive once iterated, so eval workers outlive train() just as+ # the train ones do. Drop the memo too, so a later eval rebuilds.+ memo = getattr(trainer, "_eval_dataloaders", None)+ if isinstance(memo, dict):+ for key in list(memo.keys()):+ released += _shutdown_loader_workers(memo.pop(key, None), shut)+ return released+++def quiet_tokenizer_fork_warning() -> None:+ """Silence the fast tokenizer's post-fork parallelism notice.++ The Rust tokenizer has already run in parallel by the time workers fork, so+ ``tokenizers`` warns and disables its threads in the child anyway. Doing it+ explicitly is the same outcome without the noise in the training log.+ """+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")+++__all__ = [+ "ENV_FLAG",+ "MAX_ONLINE_WORKERS",+ "MIN_ONLINE_WORKERS",+ "MIN_ROWS_FOR_ONLINE",+ "DEFAULT_PREFETCH_FACTOR",+ "TRUNCATION_ATTESTATION_ATTR",+ "OnlineTokenizationDecision",+ "attach_online_tokenization",+ "build_tokenizing_transform",+ "dataloader_worker_start_method",+ "dataset_column_names",+ "dataset_supports_with_transform",+ "decide_online_tokenization",+ "env_override",+ "first_sample_text",+ "is_processor",+ "memoize_train_dataloader",+ "model_needs_token_type_ids",+ "online_config_args",+ "platform_supports_dataloader_workers",+ "prewarm_batch_count",+ "quiet_tokenizer_fork_warning",+ "release_train_dataloader",+ "resolve_add_special_tokens",+ "resolve_worker_count",+ "text_column_defect",+ "trl_supports_skip_prepare_dataset",+]diff --git a/tests/utils/test_truncation_attestation.py b/tests/utils/test_truncation_attestation.pynew file mode 100644index 00000000000..50981eafc48--- /dev/null+++ b/tests/utils/test_truncation_attestation.py@@ -0,0 +1,253 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""A split that truncates its own rows may say so instead of being scanned.++`pretokenized_within_cap` checks `max_length` by reading every row. On a+lazily-tokenizing `with_transform` view -- what Studio's online tokenization+produces -- reading a row is tokenizing it, so the scan runs the whole eager pass+the view exists to avoid, inside `__init__` where nothing overlaps it.++`_unsloth_truncated_to = N` is the escape: every row is already cut at N. Both+copies of the scan (this module's and the one `rl.py` inlines into every+generated trainer) must agree, so both run here; the inlined one is extracted+from the codegen string and executed, the only way to test source that only+exists as a string.+"""++from __future__ import annotations++import re+import sys+import textwrap+import types+from pathlib import Path++import pytest+++REPO_ROOT = Path(__file__).resolve().parents[2]+RL_PATH = REPO_ROOT / "unsloth" / "models" / "rl.py"+++def _load_rl_module():+ """`unsloth.models.rl` without importing unsloth: only the pure, stdlib-only+ helpers are needed."""+ import ast++ source = RL_PATH.read_text(encoding = "utf-8")+ tree = ast.parse(source)+ wanted = {+ "_attested_within_cap",+ "pretokenized_within_cap",+ "splits_within_cap",+ "_SCAN_ROWS",+ "_TRUNCATION_ATTESTATION_ATTR",+ }+ kept = [+ node+ for node in tree.body+ if (isinstance(node, (ast.FunctionDef, ast.ClassDef)) and node.name in wanted)+ or (+ isinstance(node, ast.Assign)+ and any(isinstance(t, ast.Name) and t.id in wanted for t in node.targets)+ )+ ]+ module = types.ModuleType("rl_helpers_under_test")+ exec(compile(ast.Module(body = kept, type_ignores = []), str(RL_PATH), "exec"), module.__dict__)+ return module+++rl = _load_rl_module()+++class _Lazy:+ """A split that rebuilds its rows on read and counts the reads: stands in for+ `with_transform` without the `datasets` dependency, and can prove the scan+ did not happen."""++ def __init__(+ self,+ n,+ width,+ attest = None,+ ):+ self.n = n+ self.width = width+ self.reads = 0+ if attest is not None:+ self._unsloth_truncated_to = attest++ def __len__(self):+ return self.n++ def __getitem__(self, i):+ self.reads += 1+ return {"input_ids": [1] * self.width}++ def __iter__(self):+ for i in range(self.n):+ yield self[i]+++def test_an_attesting_split_is_believed_without_a_single_read():+ split = _Lazy(100_000, width = 2048, attest = 2048)+ assert rl.pretokenized_within_cap(split, 2048) is True+ assert split.reads == 0, "the attestation was ignored and the split was scanned"+++def test_a_split_attesting_a_wider_cap_is_refused():+ """Truncated to 4096 proves nothing about a 2048 cap, and the refusal must+ not silently fall through to a scan that would find the same answer."""+ split = _Lazy(8, width = 4096, attest = 4096)+ assert rl.pretokenized_within_cap(split, 2048) is False+ assert split.reads == 0+++def test_a_split_attesting_a_narrower_cap_is_accepted():+ split = _Lazy(8, width = 512, attest = 512)+ assert rl.pretokenized_within_cap(split, 2048) is True+++def test_a_split_with_no_attestation_is_still_scanned():+ split = _Lazy(4, width = 8)+ assert rl.pretokenized_within_cap(split, 2048) is True+ assert split.reads == 4+++def test_an_overlength_unattested_split_is_still_caught():+ split = _Lazy(4, width = 9000)+ assert rl.pretokenized_within_cap(split, 2048) is False++[email protected]("claim", [True, False, "2048", 2048.0, None, object()])+def test_a_non_int_claim_is_not_an_attestation(claim):+ """`True` is an `int` in Python and would read as a cap of 1. Anything that+ is not a plain integer falls through to the scan."""+ split = _Lazy(4, width = 9000)+ if claim is not None:+ split._unsloth_truncated_to = claim+ assert rl.pretokenized_within_cap(split, 2048) is False+++def test_the_claim_is_read_from_the_split_itself_not_through_a_wrapper():+ """`_CappedBase.__getattr__` forwards unknown names to the split inside, so+ a plain `getattr` would let an inner split's guarantee answer for a wrapper+ that carries none."""++ class _Forwarding:+ def __init__(self, inner):+ self._inner = inner++ def __getattr__(self, name):+ return getattr(self._inner, name)++ def __len__(self):+ return len(self._inner)++ def __iter__(self):+ for row in self._inner:+ yield {"input_ids": row["input_ids"] * 8}++ wrapper = _Forwarding(_Lazy(4, width = 4096, attest = 4096))+ assert rl._attested_within_cap(wrapper, 40960) is None+++def test_splits_within_cap_honours_the_attestation_per_split():+ good = _Lazy(4, width = 2048, attest = 2048)+ bad = _Lazy(4, width = 4096, attest = 4096)+ assert rl.splits_within_cap({"a": good}, 2048) is True+ assert rl.splits_within_cap({"a": good, "b": bad}, 2048) is False+++# ------------------------------------------------- the copy rl.py inlines+++def _inlined_within_cap(cap):+ """Build `_unsloth_within_cap` out of the codegen string and return it.++ The generated trainer cannot import from `rl.py`, so the scan exists twice;+ extracting and executing the literals is the only way to hold both copies to+ the same verdict.+ """+ source = RL_PATH.read_text(encoding = "utf-8")+ start = source.index('" def _unsloth_within_cap(_ds):\\n"')+ end = source.index('" def _unsloth_splits_within_cap(_ev):\\n"')+ body = "".join(re.findall(r'^\s*"((?:[^"\\]|\\.)*)"\s*$', source[start:end], re.MULTILINE))+ # Strip the indentation the literals carry for the generated `__init__`.+ body = textwrap.dedent(body.encode().decode("unicode_escape"))+ namespace = {"_unsloth_cap": cap}+ exec(body, namespace)+ return namespace["_unsloth_within_cap"]+++ "attest, width, cap, expected, expected_reads",+ [+ (2048, 2048, 2048, True, 0),+ (512, 512, 2048, True, 0),+ (4096, 4096, 2048, False, 0),+ (None, 8, 2048, True, 4),+ (None, 9000, 2048, False, 1),+ ],+)+def test_the_inlined_copy_gives_the_same_verdict(attest, width, cap, expected, expected_reads):+ inlined = _inlined_within_cap(cap)+ split = _Lazy(4, width = width, attest = attest)+ assert inlined(split) is expected+ assert split.reads == expected_reads++ module_level = _Lazy(4, width = width, attest = attest)+ assert rl.pretokenized_within_cap(module_level, cap) is expected+++def test_the_codegen_and_the_module_agree_on_the_attribute_name():+ """A rename on one side and not the other is a silent no-op, not a failure:+ the scan would simply never see an attestation again."""+ source = RL_PATH.read_text(encoding = "utf-8")+ assert rl._TRUNCATION_ATTESTATION_ATTR == "_unsloth_truncated_to"+ assert (+ source.count("'_unsloth_truncated_to'") >= 2+ ), "the codegen no longer reads the attribute the module writes"+++def test_studio_stamps_the_attribute_this_scan_reads():+ """The producer and the consumer live in different packages; nothing but a+ test ties the string they share together."""+ studio = REPO_ROOT / "studio" / "backend" / "utils" / "datasets" / "online_tokenization.py"+ if not studio.exists():+ pytest.skip("studio backend not present in this checkout")+ text = studio.read_text(encoding = "utf-8")+ assert f'TRUNCATION_ATTESTATION_ATTR = "{rl._TRUNCATION_ATTESTATION_ATTR}"' in text+++if __name__ == "__main__":+ sys.exit(pytest.main([__file__, "-q"]))+++# ------------------------------------------- the generated block must still parse+++def test_the_generated_max_length_block_is_valid_python():+ """The block only exists as string literals, so a stray indent or unclosed+ bracket stays invisible until a user gets a `SyntaxError` from a generated+ trainer. Assemble and parse it, reading the literals off the source rather+ than running the generator, which needs a TRL this install may not have.+ """+ import ast++ source = RL_PATH.read_text(encoding = "utf-8")+ start = source.index(" max_length_check = (")+ end = source.index(" extra_args += max_length_check")+ literals = re.findall(r'^\s*"((?:[^"\\]|\\.)*)"\s*$', source[start:end], re.MULTILINE)+ block = "".join(literals).encode().decode("unicode_escape")+ # The generator emits this at one indent level inside the trainer's __init__.+ ast.parse(textwrap.dedent(block))+++def test_the_attestation_branch_is_present_in_the_generated_block():+ """Pinned by name: without it a `with_transform` split loses padding-free and+ is scanned row by row, which is the eager tokenize pass it exists to avoid."""+ source = RL_PATH.read_text(encoding = "utf-8")+ assert "_unsloth_attests" in source+ assert "not _unsloth_prep_truncates and not _unsloth_eval_packing" in sourcediff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex ad01d486c98..ac790ece7e0 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -918,6 +918,27 @@ def _is_stream(dataset):_SCAN_ROWS = 1024+# A producer that truncates every row itself can say so and be believed without a+# scan: scanning a lazily-tokenizing split (`with_transform`) would tokenize every+# row in `__init__`, the exact eager pass it exists to avoid. Only a cap at or+# below the enforced one counts.+_TRUNCATION_ATTESTATION_ATTR = "_unsloth_truncated_to"+++def _attested_within_cap(dataset, cap):+ """The split's own truncation-width claim, or None if it makes none.++ Read from `__dict__`, not `getattr`: `_CappedBase.__getattr__` forwards to the+ inner split, so a wrapper would inherit a guarantee it does not carry.+ """+ own = getattr(dataset, "__dict__", None)+ if not isinstance(own, dict):+ return None+ claimed = own.get(_TRUNCATION_ATTESTATION_ATTR)+ if not isinstance(claimed, int) or isinstance(claimed, bool):+ return None+ return claimed <= cap+def pretokenized_within_cap(dataset, cap):"""Whether every pre-tokenized row in `dataset` already fits `cap`.@@ -936,6 +957,9 @@ def pretokenized_within_cap(dataset, cap):"""if dataset is None:return True+ attested = _attested_within_cap(dataset, cap)+ if attested is not None:+ return attestedtry:try:n = len(dataset)@@ -2716,6 +2740,15 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):" _UNSLOTH_SCAN_ROWS = 1024\n"" def _unsloth_within_cap(_ds):\n"" if _ds is None: return True\n"+ # Believe a producer's own truncation claim: scanning a+ # `with_transform` split would tokenize every row in `__init__`,+ # the eager pass it exists to avoid. Read from `__dict__` so a+ # wrapper does not inherit the inner split's claim.+ " _unsloth_own = getattr(_ds, '__dict__', None)\n"+ " if isinstance(_unsloth_own, dict):\n"+ " _unsloth_claim = _unsloth_own.get('_unsloth_truncated_to')\n"+ " if isinstance(_unsloth_claim, int) and not isinstance(_unsloth_claim, bool):\n"+ " return _unsloth_claim <= _unsloth_cap\n"" try:\n"" try: _n = len(_ds)\n"" except Exception: _n = None\n"@@ -3042,6 +3075,25 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):# as a bare `StopIteration` naming nothing at all." if _unsloth_emptied:\n"" raise ValueError('Unsloth: truncating to `max_length = ' + str(args.max_length) + '` left every row with no supervised token, so there is nothing to train on. The supervised part of your rows starts past that length: raise `max_length`, or set `truncation_mode = \"keep_end\"` if the completion sits at the end of each row.')\n"+ # A producer that truncates every row enforces the cap just as+ # `truncate_dataset` would, so keep padding-free rather than pay the+ # fallback for a guarantee already held. Studio's online tokenization+ # is this shape: a `with_transform` view capped on read, invisible+ # without reading -- and reading it all is the eager pass it avoids.+ # Not under `eval_packing`: that split is meant to be overlength and+ # the packer needs the `max_length` this branch clears.+ " if not _unsloth_prep_truncates and not _unsloth_eval_packing:\n"+ " def _unsloth_attests(_ds):\n"+ " if _ds is None: return True\n"+ " _own = getattr(_ds, '__dict__', None)\n"+ " if not isinstance(_own, dict): return False\n"+ " _claim = _own.get('_unsloth_truncated_to')\n"+ " if not isinstance(_claim, int) or isinstance(_claim, bool): return False\n"+ " return _claim <= _unsloth_cap\n"+ " _unsloth_attest_eval = eval_dataset if 'eval_dataset' in locals() else None\n"+ " _unsloth_attest_splits = list(_unsloth_attest_eval.values()) if isinstance(_unsloth_attest_eval, dict) else [_unsloth_attest_eval]\n"+ " if _unsloth_attests(train_dataset) and all(_unsloth_attests(_s) for _s in _unsloth_attest_splits):\n"+ " _unsloth_prep_truncates = True\n"" if _unsloth_prep_truncates:\n"" args.max_seq_length = args.max_length\n"" args.max_length = None\n"