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: trim masked padding from pre-tokenized rows and range-check labels (#14818)
Daniel Han41db865d22c3
diff --git a/studio/backend/core/training/token_preview_worker.py b/studio/backend/core/training/token_preview_worker.pyindex 4cccf33b81e..c73e1bf4b4b 100644--- a/studio/backend/core/training/token_preview_worker.py+++ b/studio/backend/core/training/token_preview_worker.py@@ -195,7 +195,8 @@ def _pretokenized(tokenizer, model_name: str, rows: list, max_length: int, requefrom datasets import Datasetfrom utils.datasets.pretokenized import has_custom_labels, prepare_pretokenized_dataset- dataset = Dataset.from_list(rows)+ # Lengths after masked padding is trimmed, so only a real max_seq_length cut reads as truncation.+ dataset = prepare_pretokenized_dataset(Dataset.from_list(rows), max_seq_length = None)full_lengths = [len(ids) for ids in dataset["input_ids"]]dataset = prepare_pretokenized_dataset(dataset, max_seq_length = max_length)input_ids = [list(ids) for ids in dataset["input_ids"]]diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex 3c2f83a6f45..a68fb5415c3 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -3955,6 +3955,11 @@ class UnslothTrainer:if eval_info.get("dropped_rows_warning"):self._record_warning(f"Eval dataset: {eval_info['dropped_rows_warning']}")eval_dataset = eval_info["dataset"]+ # Formatted on its own, so it can resolve to another format than the training split (a split carved+ # out of train has no entry and shares the training format).+ dataset_info["eval_final_format"] = str(+ eval_info.get("final_format", "") or ""+ ).lower()logger.info("Eval dataset formatted successfully\n")elif eval_enabled and not has_separate_eval_source and not dataset_streaming:formatted_dataset = dataset_info["dataset"]@@ -4629,6 +4634,11 @@ class UnslothTrainer:)raw_text_mode = dataset_final_format == "raw_text"pretokenized_mode = dataset_final_format == PRETOKENIZED_FORMAT+ eval_final_format = (+ str(dataset.get("eval_final_format", dataset_final_format) or "").lower()+ if isinstance(dataset, dict)+ else ""+ )# Without a labels column, "Train on responses only" can still mask prompts from input_ids.user_labels = pretokenized_mode and has_custom_labels(dataset["dataset"])self.tokenizer = get_training_chat_template(@@ -4946,11 +4956,10 @@ class UnslothTrainer:# Packed rows share one bidirectional attention window, so documents would see each other.config_args["packing"] = Falselogger.info("Text-diffusion model: sequence packing turned off\n")- if pretokenized_mode:- # Packing on TRL < 1.7 keeps only input_ids, silently replacing the user's labels.- if config_args.get("packing"):- logger.info("Pre-tokenized dataset: sequence packing turned off\n")- config_args["packing"] = False+ eval_pretokenized = (+ eval_dataset is not None and eval_final_format == PRETOKENIZED_FORMAT+ )+ if pretokenized_mode or eval_pretokenized:try:vocab_size = int(self.model.get_input_embeddings().num_embeddings)except Exception:@@ -4961,19 +4970,31 @@ class UnslothTrainer:completion_only = resolve_completion_only_loss(dataset["dataset"], config_args.get("completion_only_loss"))+ # Each split goes by its own format: a separately supplied eval split can be pre-tokenized while the+ # training split is text, and the reverse.+ if pretokenized_mode:+ # Packing on TRL < 1.7 keeps only input_ids, silently replacing the user's labels.+ if config_args.get("packing"):+ logger.info("Pre-tokenized dataset: sequence packing turned off\n")+ config_args["packing"] = Falsedataset["dataset"] = prepare_pretokenized_dataset(dataset["dataset"],max_seq_length = max_seq,vocab_size = vocab_size,completion_only_loss = completion_only,)- if eval_dataset is not None:- eval_dataset = prepare_pretokenized_dataset(- eval_dataset,- max_seq_length = max_seq,- vocab_size = vocab_size,- completion_only_loss = completion_only,- )+ if eval_pretokenized:+ # TRL packs eval by `packing` unless eval_packing says otherwise, and packing keeps only input_ids,+ # so a pre-tokenized eval split beside a packed text train split would lose its labels.+ if config_args.get("packing"):+ logger.info("Pre-tokenized eval dataset: eval sequence packing turned off\n")+ config_args["eval_packing"] = False+ eval_dataset = prepare_pretokenized_dataset(+ eval_dataset,+ max_seq_length = max_seq,+ vocab_size = vocab_size,+ completion_only_loss = completion_only,+ )# Plain-text single-pass runs tokenize in the DataLoader workers instead of a blocking .map(); everything# else stays eager.diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex dcd054a1cca..50d9d5a1969 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -2453,6 +2453,35 @@ def _activate_transformers_version_or_warn(model_name: str, hf_token: str | None)+def _mlx_vocab_size(model):+ """Rows of the MLX model's input embedding table (the CUDA path reads get_input_embeddings().num_embeddings), so+ a pre-tokenized id or label past it is refused before the loss indexes it. None when it cannot be found, which+ skips only the range check."""+ for owner in (model, getattr(model, "language_model", None)):+ if owner is None:+ continue+ for embed in (+ getattr(getattr(owner, "model", None), "embed_tokens", None),+ getattr(owner, "embed_tokens", None),+ ):+ # A LoRA-wrapped embedding keeps the table on its inner module.+ for layer in (+ embed,+ getattr(embed, "embedding", None),+ getattr(embed, "base_layer", None),+ ):+ if layer is None:+ continue+ # QuantizedEmbedding packs its weight, so its row count is the stored num_embeddings.+ rows = getattr(layer, "num_embeddings", None)+ shape = getattr(getattr(layer, "weight", None), "shape", None)+ if rows is None and shape:+ rows = shape[0]+ if isinstance(rows, int) and not isinstance(rows, bool) and rows > 0:+ return rows+ return None++def _carry_mlx_chat_template_to_processor(model, tokenizer) -> bool:"""MLXTrainer saves the loader's processor when it has one, so a text run on a multimodal base checkpoint (Qwen3.5Base) saved no template and Chat failed with "chat_template is not set". Give it the template the rows used."""@@ -3465,6 +3494,7 @@ def _run_mlx_training(event_queue, stop_queue, config):format_type = config.get("format_type", "")custom_format_mapping = config.get("custom_format_mapping")dataset_final_format = ""+ eval_final_format = ""try:from utils.datasets import format_and_template_datasetdef _fmt_progress(status_message = "", **_kw):@@ -3538,6 +3568,7 @@ def _run_mlx_training(event_queue, stop_queue, config):for message in info.get("run_warnings", []):_send("warning", message = message)dataset_final_format = str(info.get("final_format", "") or "").lower()+ eval_final_format = dataset_final_formatif eval_dataset is not None:ev = format_and_template_dataset(eval_dataset,@@ -3552,6 +3583,8 @@ def _run_mlx_training(event_queue, stop_queue, config):)if ev.get("success", True):eval_dataset = ev.get("dataset", eval_dataset)+ # A separately supplied eval split is detected on its own and may not be pre-tokenized.+ eval_final_format = str(ev.get("final_format", "") or "").lower()if hasattr(eval_dataset, "__len__") and len(eval_dataset) == 0:_send("warning",@@ -3597,6 +3630,21 @@ def _run_mlx_training(event_queue, stop_queue, config):)else:dataset, eval_dataset = split_result+ eval_final_format = dataset_final_format++ # zoo's MLX batcher reads input_ids / labels and ignores attention_mask, so masked padding is trimmed here as on+ # CUDA. MLX truncates to max_seq_length itself. Each split goes by its own format: a separately supplied eval+ # split can be pre-tokenized while the training split is text, and the reverse.+ if dataset_final_format == "pretokenized":+ from utils.datasets.pretokenized import prepare_pretokenized_dataset+ dataset = prepare_pretokenized_dataset(+ dataset, max_seq_length = None, vocab_size = _mlx_vocab_size(model), mlx = True+ )+ if eval_dataset is not None and eval_final_format == "pretokenized":+ from utils.datasets.pretokenized import prepare_pretokenized_dataset+ eval_dataset = prepare_pretokenized_dataset(+ eval_dataset, max_seq_length = None, vocab_size = _mlx_vocab_size(model), mlx = True+ )requested_max_steps = config.get("max_steps", 0) or 0num_epochs = config.get("num_epochs", 3)diff --git a/studio/backend/tests/test_mlx_vocab_size_apple.py b/studio/backend/tests/test_mlx_vocab_size_apple.pynew file mode 100644index 00000000000..32e08286127--- /dev/null+++ b/studio/backend/tests/test_mlx_vocab_size_apple.py@@ -0,0 +1,54 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""_mlx_vocab_size on real mlx-lm modules (random init, no download), on Apple Silicon only."""++from __future__ import annotations++import platform+import sys++import pytest++pytestmark = pytest.mark.skipif(+ sys.platform != "darwin" or platform.machine() != "arm64",+ reason = "MLX runs on Apple Silicon only",+)++_VOCAB = 320+++def _tiny_llama():+ pytest.importorskip("mlx_lm")+ from mlx_lm.models import llama++ args = llama.ModelArgs(+ model_type = "llama",+ hidden_size = 64,+ num_hidden_layers = 1,+ intermediate_size = 128,+ num_attention_heads = 4,+ rms_norm_eps = 1e-5,+ vocab_size = _VOCAB,+ num_key_value_heads = 4,+ )+ return llama.Model(args)+++def test_dense_quantized_and_lora_embeddings_report_the_vocab_size():+ import mlx.nn as nn+ from core.training.worker import _mlx_vocab_size++ model = _tiny_llama()+ assert _mlx_vocab_size(model) == _VOCAB++ # The packed weight has fewer columns, never fewer rows than the vocabulary.+ nn.quantize(model, group_size = 64, bits = 4)+ assert isinstance(model.model.embed_tokens, nn.QuantizedEmbedding)+ assert _mlx_vocab_size(model) == _VOCAB++ from mlx_lm.tuner.lora import LoRAEmbedding++ model = _tiny_llama()+ model.model.embed_tokens = LoRAEmbedding.from_base(model.model.embed_tokens, r = 4)+ assert _mlx_vocab_size(model) == _VOCABdiff --git a/studio/backend/tests/test_pretokenized_dataset.py b/studio/backend/tests/test_pretokenized_dataset.pyindex fab620ca036..c3e52d96dae 100644--- a/studio/backend/tests/test_pretokenized_dataset.py+++ b/studio/backend/tests/test_pretokenized_dataset.py@@ -3,6 +3,7 @@"""Pre-tokenized datasets (input_ids / attention_mask / labels) route to training as-is (#7139), and nothing else moves."""+import importlib.utilimport inspectimport sysfrom pathlib import Path@@ -343,7 +344,16 @@ def test_prepare_rejects_non_list_masks_with_the_mask_error(mask):prepare_pretokenized_dataset(ds, max_seq_length = 2048, vocab_size = 100)[email protected]("fmt", [None, "numpy", "torch"])+# The torch formatter needs torch, which the CPU-only CI legs do not install.+_TORCH_FMT = pytest.param(+ "torch",+ marks = pytest.mark.skipif(+ importlib.util.find_spec("torch") is None, reason = "torch is not installed"+ ),+)++[email protected]("fmt", [None, "numpy", _TORCH_FMT])@pytest.mark.parametrize("mask", [0, 1.0, True])def test_prepare_rejects_streamed_scalar_masks_with_the_mask_error(mask, fmt, monkeypatch):# Streamed rows skip the Arrow type check: a scalar mask must not surface as len()'s TypeError.@@ -360,7 +370,7 @@ def test_prepare_rejects_streamed_scalar_masks_with_the_mask_error(mask, fmt, molist(out)[email protected]("fmt", ["numpy", "torch"])[email protected]("fmt", ["numpy", _TORCH_FMT])def test_prepare_truncates_streamed_array_masks(fmt, monkeypatch):monkeypatch.setattr("datasets.config.TORCHVISION_AVAILABLE", False)ds = (@@ -392,3 +402,496 @@ def test_positional_custom_format_mapping_still_binds():assert format_dataset(_pretokenized(), *defaults, None)["final_format"] == "pretokenized"mapped = format_dataset(_pretokenized(), *defaults, {"input_ids": "user"})assert mapped["final_format"] != "pretokenized"+++# Padded rows: TRL's collator rebuilds attention_mask as all ones, so masked padding is trimmed at preparation.+_PADDED = {+ "left": ([0, 0, 4, 5], [0, 0, 1, 1], [-100, -100, 4, 5], [4, 5], [4, 5]),+ "right": ([2, 3, 5, 0, 0], [1, 1, 1, 0, 0], [2, 3, 5, -100, -100], [2, 3, 5], [2, 3, 5]),+ "both": ([0, 2, 3, 0], [0, 1, 1, 0], [-100, -100, 3, -100], [2, 3], [-100, 3]),+}++[email protected]("streaming", [False, True])[email protected]("with_labels", [True, False])[email protected]("side", sorted(_PADDED))+def test_prepare_trims_masked_padding(side, with_labels, streaming):+ ids, mask, labels, want_ids, want_labels = _PADDED[side]+ rows = {"input_ids": [ids, [2, 3]], "attention_mask": [mask, [1, 1]]}+ if with_labels:+ rows["labels"] = [labels, [2, 3]]+ ds = Dataset.from_dict(rows)+ if streaming:+ ds = ds.to_iterable_dataset()+ out = list(prepare_pretokenized_dataset(ds, max_seq_length = 2048, vocab_size = 100))+ assert out[0]["input_ids"] == want_ids+ assert out[0]["attention_mask"] == [1] * len(want_ids)+ if with_labels:+ assert out[0]["labels"] == want_labels+ assert out[1] == {k: v[1] for k, v in rows.items()}+++def test_prepare_trims_then_truncates_and_is_idempotent():+ ds = Dataset.from_dict({"input_ids": [[0, 0, 4, 5, 6]], "attention_mask": [[0, 0, 1, 1, 1]]})+ once = prepare_pretokenized_dataset(ds, max_seq_length = 2, vocab_size = 100)+ assert once.to_dict() == {"input_ids": [[4, 5]], "attention_mask": [[1, 1]]}+ assert (+ prepare_pretokenized_dataset(once, max_seq_length = 2, vocab_size = 100).to_dict()+ == once.to_dict()+ )++[email protected]("streaming", [False, True])+ "mask, match",+ [+ ([1, 0, 1, 1], "row 1 has 'attention_mask' zeros between attended tokens"),+ ([0, 0, 0, 0], "row 1 has an all-zero 'attention_mask'"),+ ([0, 2, 1, 1], "row 1 has 'attention_mask' values other than 0 and 1"),+ # A negative minimum or no zero at all must not skip the value check.+ ([-1, 0, 1, 1], "row 1 has 'attention_mask' values other than 0 and 1"),+ ([1, 2, 1, 1], "row 1 has 'attention_mask' values other than 0 and 1"),+ # Fractional values sit inside [0, 1], so only an exact {0, 1} check catches them.+ ([0.5, 1.0, 1.0, 1.0], "row 1 has 'attention_mask' values other than 0 and 1"),+ ([0.0, 0.5, 1.0, 1.0], "row 1 has 'attention_mask' values other than 0 and 1"),+ ],+)+def test_prepare_refuses_masks_it_cannot_trim(mask, match, streaming):+ ds = Dataset.from_dict(+ {"input_ids": [[1, 2, 3, 4]] * 2, "attention_mask": [[1, 1, 1, 1], mask]}+ )+ if streaming:+ ds = ds.to_iterable_dataset()+ with pytest.raises(ValueError, match = match):+ list(prepare_pretokenized_dataset(ds, max_seq_length = 2048, vocab_size = 100))++[email protected]("streaming", [False, True])+ "rows, column",+ [+ ({"input_ids": [[1, 2, 3]], "attention_mask": [[0, 1]]}, "attention_mask"),+ ({"input_ids": [[1, 2, 3]], "labels": [[1, 2]]}, "labels"),+ (+ {+ "input_ids": [[0, 2, 3]],+ "attention_mask": [[0, 1, 1]],+ "assistant_masks": [[0, 1, 1, 1]],+ },+ "assistant_masks",+ ),+ ],+)+def test_prepare_refuses_a_padded_mask_of_another_length(rows, column, streaming):+ ds = Dataset.from_dict(rows)+ if streaming:+ ds = ds.to_iterable_dataset()+ with pytest.raises(ValueError, match = f"'{column}' must have the same length"):+ list(prepare_pretokenized_dataset(ds, max_seq_length = 2048, vocab_size = 100))++[email protected]("streaming", [False, True])[email protected]("column", ["completion_mask", "assistant_masks", "token_type_ids"])[email protected]("with_mask", [True, False])+def test_prepare_refuses_an_unpadded_token_column_of_another_length(column, with_mask, streaming):+ # No zero in the mask (or no mask) means nothing is trimmed, but TRL still reads these columns per position.+ rows = {"input_ids": [[1, 2, 3], [4, 5]], column: [[0, 1, 1], [0, 1, 1]]}+ if with_mask:+ rows["attention_mask"] = [[1, 1, 1], [1, 1]]+ ds = Dataset.from_dict(rows)+ if streaming:+ ds = ds.to_iterable_dataset()+ with pytest.raises(ValueError, match = f"'{column}' must have the same length"):+ # completion_mask is applied only under completion_only_loss.+ list(+ prepare_pretokenized_dataset(+ ds, max_seq_length = 2048, vocab_size = 100, completion_only_loss = True+ )+ )++[email protected]("streaming", [False, True])+def test_prepare_trims_and_truncates_trl_supervision_masks_with_input_ids(streaming):+ rows = {+ "input_ids": [[0, 0, 4, 5, 6], [2, 3]],+ "attention_mask": [[0, 0, 1, 1, 1], [1, 1]],+ "completion_mask": [[0, 0, 0, 1, 1], [0, 1]],+ "assistant_masks": [[0, 0, 0, 1, 1], [0, 1]],+ }+ ds = Dataset.from_dict(rows)+ if streaming:+ ds = ds.to_iterable_dataset()+ out = list(+ prepare_pretokenized_dataset(+ ds, max_seq_length = 2, vocab_size = 100, completion_only_loss = True+ )+ )+ assert out[0] == {+ "input_ids": [4, 5],+ "attention_mask": [1, 1],+ "completion_mask": [0, 1],+ "assistant_masks": [0, 1],+ }+ assert out[1] == {k: v[1] for k, v in rows.items()}+++def test_preview_does_not_report_trimmed_padding_as_truncation():+ from core.training import token_preview_worker++ rows = [+ {"input_ids": [0, 0, 4, 5], "attention_mask": [0, 0, 1, 1]},+ {"input_ids": [0, 4, 5, 6, 7], "attention_mask": [0, 1, 1, 1, 1]},+ ]+ ids, _, full_lengths, _ = token_preview_worker._pretokenized(None, "m", rows, 3, {})+ assert ids == [[4, 5], [4, 5, 6]]+ # Row 0 only lost padding; row 1 lost padding and one real token to max_seq_length.+ assert full_lengths == [2, 4]+++def test_mlx_training_prepares_pretokenized_train_and_eval_rows():+ # zoo's MLX batcher ignores attention_mask, so the worker must trim padding before MLXTrainer sees the rows.+ import ast++ source = (Path(__file__).resolve().parents[1] / "core" / "training" / "worker.py").read_text(+ encoding = "utf-8"+ )+ fn = next(+ node+ for node in ast.walk(ast.parse(source))+ if isinstance(node, ast.FunctionDef) and node.name == "_run_mlx_training"+ )+ prepared = {+ node.args[0].id: node.lineno+ for node in ast.walk(fn)+ if isinstance(node, ast.Call)+ and getattr(node.func, "id", None) == "prepare_pretokenized_dataset"+ }+ trainer_line = next(+ node.lineno+ for node in ast.walk(fn)+ if isinstance(node, ast.Call) and getattr(node.func, "id", None) == "MLXTrainer"+ )+ assert set(prepared) == {"dataset", "eval_dataset"}+ assert max(prepared.values()) < trainer_line+++def test_mlx_training_prepares_eval_only_when_it_is_pretokenized():+ # A separately supplied eval split is formatted on its own and may resolve to text, with no input_ids to prepare.+ import ast++ source = (Path(__file__).resolve().parents[1] / "core" / "training" / "worker.py").read_text(+ encoding = "utf-8"+ )+ fn = next(+ node+ for node in ast.walk(ast.parse(source))+ if isinstance(node, ast.FunctionDef) and node.name == "_run_mlx_training"+ )+ parents = {child: node for node in ast.walk(fn) for child in ast.iter_child_nodes(node)}+ call = next(+ node+ for node in ast.walk(fn)+ if isinstance(node, ast.Call)+ and getattr(node.func, "id", None) == "prepare_pretokenized_dataset"+ and node.args[0].id == "eval_dataset"+ )+ guard = parents[call]+ while not isinstance(guard, ast.If):+ guard = parents[guard]+ assert "eval_final_format" in {n.id for n in ast.walk(guard.test) if isinstance(n, ast.Name)}+ # Set from the eval formatter's own result, not copied from the training split.+ assigned = [+ node+ for node in ast.walk(fn)+ if isinstance(node, ast.Assign)+ and any(getattr(t, "id", None) == "eval_final_format" for t in node.targets)+ ]+ assert any(+ "ev" in {n.id for n in ast.walk(a.value) if isinstance(n, ast.Name)} for a in assigned+ )+++def test_mlx_training_prepares_a_pretokenized_eval_split_whatever_the_train_format():+ # A text training split with a pre-tokenized eval split must still trim the eval rows' masked padding.+ import ast++ source = (Path(__file__).resolve().parents[1] / "core" / "training" / "worker.py").read_text(+ encoding = "utf-8"+ )+ fn = next(+ node+ for node in ast.walk(ast.parse(source))+ if isinstance(node, ast.FunctionDef) and node.name == "_run_mlx_training"+ )+ parents = {child: node for node in ast.walk(fn) for child in ast.iter_child_nodes(node)}+ call = next(+ node+ for node in ast.walk(fn)+ if isinstance(node, ast.Call)+ and getattr(node.func, "id", None) == "prepare_pretokenized_dataset"+ and node.args[0].id == "eval_dataset"+ )+ node = call+ while node is not fn:+ node = parents[node]+ if isinstance(node, ast.If):+ names = {n.id for n in ast.walk(node.test) if isinstance(n, ast.Name)}+ assert "dataset_final_format" not in names+++def test_cuda_training_prepares_each_split_by_its_own_format():+ # A text train split with a pre-tokenized eval split still trims the eval padding, and a text eval split beside a+ # pre-tokenized train split is left alone (it has no input_ids to prepare).+ import ast++ tree = ast.parse(+ (Path(__file__).resolve().parents[1] / "core" / "training" / "trainer.py").read_text(+ encoding = "utf-8"+ )+ )+ parents = {child: node for node in ast.walk(tree) for child in ast.iter_child_nodes(node)}+ call = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and getattr(node.func, "id", None) == "prepare_pretokenized_dataset"+ and getattr(node.args[0], "id", None) == "eval_dataset"+ )+ guards, node = set(), call+ while node in parents:+ node = parents[node]+ if isinstance(node, ast.If):+ guards |= {n.id for n in ast.walk(node.test) if isinstance(n, ast.Name)}+ assert "eval_pretokenized" in guards+ assert not guards & {"pretokenized_mode", "dataset_final_format"}+ fn = node = call+ while not isinstance(fn, ast.FunctionDef):+ fn = parents[fn]+ flag = next(+ a+ for a in ast.walk(fn)+ if isinstance(a, ast.Assign) and getattr(a.targets[0], "id", None) == "eval_pretokenized"+ )+ assert "eval_final_format" in {n.id for n in ast.walk(flag.value) if isinstance(n, ast.Name)}+ # The separately formatted eval split records its own resolved format for the training step to read.+ recorded = [+ a+ for a in ast.walk(tree)+ if isinstance(a, ast.Assign)+ and isinstance(a.targets[0], ast.Subscript)+ and getattr(a.targets[0].slice, "value", None) == "eval_final_format"+ ]+ assert any(+ "eval_info" in {n.id for n in ast.walk(a.value) if isinstance(n, ast.Name)}+ for a in recorded+ )++[email protected]("streaming", [False, True])+def test_prepare_trims_boolean_masks_like_integer_masks(streaming):+ rows = {+ "input_ids": [[0, 2, 3, 0], [4, 5]],+ "attention_mask": [[False, True, True, False], [True, True]],+ "labels": [[-100, 2, 3, -100], [4, 5]],+ }+ ds = Dataset.from_dict(rows)+ if streaming:+ ds = ds.to_iterable_dataset()+ out = list(prepare_pretokenized_dataset(ds, max_seq_length = 2048, vocab_size = 100))+ assert out[0]["input_ids"] == [2, 3]+ assert out[0]["labels"] == [2, 3]+ assert out[0]["attention_mask"] == [True, True]+ assert out[1] == {k: v[1] for k, v in rows.items()}++[email protected]("streaming", [False, True])+def test_prepare_refuses_interior_false_in_a_boolean_mask(streaming):+ ds = Dataset.from_dict({"input_ids": [[1, 2, 3]], "attention_mask": [[True, False, True]]})+ if streaming:+ ds = ds.to_iterable_dataset()+ with pytest.raises(ValueError, match = "zeros between attended tokens"):+ list(prepare_pretokenized_dataset(ds, max_seq_length = 2048, vocab_size = 100))+++def test_prepare_leaves_an_all_true_boolean_mask_byte_identical():+ rows = {"input_ids": [[1, 2, 3]], "attention_mask": [[True, True, True]]}+ ds = Dataset.from_dict(rows)+ out = prepare_pretokenized_dataset(ds, max_seq_length = 2048, vocab_size = 100)+ assert out is ds+ assert out.data.table.equals(Dataset.from_dict(rows).data.table)++[email protected]("streaming", [False, True])[email protected]("bad", [100, 250, -1, -5])+def test_prepare_rejects_labels_outside_the_vocabulary(bad, streaming):+ ds = Dataset.from_dict({"input_ids": [[1, 2, 3]], "labels": [[-100, 2, bad]]})+ if streaming:+ ds = ds.to_iterable_dataset()+ with pytest.raises(ValueError, match = f"label {bad} is invalid"):+ list(prepare_pretokenized_dataset(ds, max_seq_length = 2048, vocab_size = 100))++[email protected]("with_mask", [True, False])+def test_prepare_leaves_unpadded_rows_byte_identical(with_mask):+ rows = {"input_ids": [[1, 2, 3], [4, 5]], "labels": [[-100, 2, 3], [-100, -100]]}+ if with_mask:+ rows["attention_mask"] = [[1, 1, 1], [1, 1]]+ ds = Dataset.from_dict(rows)+ out = prepare_pretokenized_dataset(ds, max_seq_length = 2048, vocab_size = 100)+ assert out is ds+ assert out.data.table.equals(Dataset.from_dict(rows).data.table)+++def test_trl_collator_never_attends_or_trains_masked_padding():+ collator_cls = pytest.importorskip("trl.trainer.sft_trainer").DataCollatorForLanguageModeling+ ids = [[0, 0, 4, 5], [2, 3, 5, 0], [0, 4, 2, 5]]+ masks = [[0, 0, 1, 1], [1, 1, 1, 0], [0, 1, 1, 1]]+ ds = prepare_pretokenized_dataset(+ Dataset.from_dict({"input_ids": ids, "attention_mask": masks}),+ max_seq_length = 8,+ vocab_size = 6,+ )+ batch = collator_cls(pad_token_id = 0)([ds[i] for i in range(len(ds))])+ for r, (row, mask) in enumerate(zip(ids, masks)):+ real = [t for t, m in zip(row, mask) if m]+ attended = [+ t+ for t, m in zip(batch["input_ids"][r].tolist(), batch["attention_mask"][r].tolist())+ if m+ ]+ assert attended == real+ assert [x for x in batch["labels"][r].tolist() if x != -100] == real++[email protected]("streaming", [False, True])+ "rows, column",+ [+ ({"input_ids": [[1, 2], [3, 4]], "attention_mask": [[1, 1], [None, 1]]}, "attention_mask"),+ ({"input_ids": [[1, 2], [3, 4]], "labels": [[-100, 2], [None, 4]]}, "labels"),+ ],+)+def test_prepare_refuses_null_values_in_token_columns(rows, column, streaming):+ # Arrow's any / min_max skip nulls, so [None, 1] used to pass as an all-ones mask and TRL attended the hole.+ ds = Dataset.from_dict(rows)+ if streaming:+ ds = ds.to_iterable_dataset()+ with pytest.raises(ValueError, match = rf"row 1 .*null.*'{column}'"):+ list(prepare_pretokenized_dataset(ds, max_seq_length = 8))+++def test_mlx_vocab_size_reads_the_input_embedding_table():+ from types import SimpleNamespace as NS++ from core.training.worker import _mlx_vocab_size++ weight = NS(shape = (32, 8))+ assert _mlx_vocab_size(NS(model = NS(embed_tokens = NS(weight = weight)))) == 32+ # QuantizedEmbedding packs its weight, so the stored row count wins over the packed shape.+ quant = NS(num_embeddings = 64, weight = NS(shape = (64, 1)))+ assert _mlx_vocab_size(NS(model = NS(embed_tokens = quant))) == 64+ vlm = NS(language_model = NS(model = NS(embed_tokens = NS(weight = weight))))+ assert _mlx_vocab_size(vlm) == 32+ lora = NS(embedding = NS(weight = weight))+ assert _mlx_vocab_size(NS(model = NS(embed_tokens = lora))) == 32+ assert _mlx_vocab_size(NS()) is None+++def test_mlx_training_passes_the_model_vocab_size_to_both_splits():+ # Without it an out-of-range label reaches the MLX loss, where indexing the vocabulary fails mid-run.+ import ast++ source = (Path(__file__).resolve().parents[1] / "core" / "training" / "worker.py").read_text(+ encoding = "utf-8"+ )+ fn = next(+ node+ for node in ast.walk(ast.parse(source))+ if isinstance(node, ast.FunctionDef) and node.name == "_run_mlx_training"+ )+ calls = [+ node+ for node in ast.walk(fn)+ if isinstance(node, ast.Call)+ and getattr(node.func, "id", None) == "prepare_pretokenized_dataset"+ ]+ assert len(calls) == 2+ for call in calls:+ vocab = next(k.value for k in call.keywords if k.arg == "vocab_size")+ assert isinstance(vocab, ast.Call) and vocab.func.id == "_mlx_vocab_size"+ assert [a.id for a in vocab.args] == ["model"]+ # zoo's MLX reader applies masks by its own policy, not the installed TRL's.+ assert any(k.arg == "mlx" and k.value.value is True for k in call.keywords)+++def test_cuda_training_turns_eval_packing_off_for_a_pretokenized_eval_split():+ # TRL packs eval by `packing` unless eval_packing overrides it, and packing drops the eval split's labels.+ import ast++ tree = ast.parse(+ (Path(__file__).resolve().parents[1] / "core" / "training" / "trainer.py").read_text(+ encoding = "utf-8"+ )+ )+ guard = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.If)+ and isinstance(node.test, ast.Name)+ and node.test.id == "eval_pretokenized"+ )+ assigned = [+ a+ for a in ast.walk(guard)+ if isinstance(a, ast.Assign)+ and isinstance(a.targets[0], ast.Subscript)+ and getattr(a.targets[0].value, "id", None) == "config_args"+ and getattr(a.targets[0].slice, "value", None) == "eval_packing"+ ]+ assert assigned and all(a.value.value is False for a in assigned)+++def test_eval_packing_is_a_field_on_every_supported_trl():+ # eval_packing exists from TRL 0.22.2 (the floor) on, so setting it never breaks SFTConfig construction.+ SFTConfig = pytest.importorskip("trl").SFTConfig+ assert "eval_packing" in SFTConfig.__dataclass_fields__++[email protected]("fmt", ["numpy", _TORCH_FMT])[email protected]("with_labels", [False, True])+def test_prepare_trims_formatted_streams(fmt, with_labels):+ # A formatted stream hands the mapper arrays, not lists.+ rows = {"input_ids": [[0, 2, 3], [4, 5, 6]], "attention_mask": [[0, 1, 1], [1, 1, 1]]}+ if with_labels:+ rows["labels"] = [[-100, 2, 3], [4, 5, 6]]+ ds = Dataset.from_dict(rows).to_iterable_dataset().with_format(fmt)+ out = list(prepare_pretokenized_dataset(ds, max_seq_length = 2, vocab_size = 100))+ assert [[int(x) for x in r["input_ids"]] for r in out] == [[2, 3], [4, 5]]+ assert [[int(x) for x in r["attention_mask"]] for r in out] == [[1, 1], [1, 1]]+ if with_labels:+ assert [[int(x) for x in r["labels"]] for r in out] == [[2, 3], [4, 5]]++[email protected]("streaming", [False, True])+def test_mlx_trims_assistant_masks_beside_labels_whatever_the_trl(streaming, monkeypatch):+ # zoo's MLX reader applies assistant_masks beside labels and refuses a length mismatch, even+ # where TRL >= 1.7's collator would ignore them.+ import utils.datasets.pretokenized as pretokenized++ monkeypatch.setattr(pretokenized, "_collator_masks_user_labels", lambda: False)+ rows = {+ "input_ids": [[0, 0, 4, 5]],+ "attention_mask": [[0, 0, 1, 1]],+ "labels": [[-100, -100, 4, 5]],+ "assistant_masks": [[0, 0, 1, 1]],+ "completion_mask": [[0, 0, 1]],+ }+ ds = Dataset.from_dict(rows)+ if streaming:+ ds = ds.to_iterable_dataset()+ out = list(prepare_pretokenized_dataset(ds, max_seq_length = None, vocab_size = 100, mlx = True))+ assert out[0]["input_ids"] == [4, 5]+ assert out[0]["labels"] == [4, 5]+ assert out[0]["assistant_masks"] == [1, 1]+ # completion_mask applies on MLX only for an explicit completion_only_loss=True: left as is.+ assert out[0]["completion_mask"] == [0, 0, 1]diff --git a/studio/backend/utils/datasets/pretokenized.py b/studio/backend/utils/datasets/pretokenized.pyindex 7bc79729983..7306ab0be16 100644--- a/studio/backend/utils/datasets/pretokenized.py+++ b/studio/backend/utils/datasets/pretokenized.py@@ -27,13 +27,25 @@ def _collator_masks_user_labels() -> bool:return True-def _checked_masks(columns, completion_only_loss = None) -> tuple:+def _checked_masks(+ columns,+ completion_only_loss = None,+ mlx = False,+) -> tuple:"""Masks the trainer will apply, the only ones checked and truncated.TRL applies `assistant_masks` on presence but `completion_mask` only under`completion_only_loss`, which, left unset, it resolves from the dataset shape (prompt pluscompletion columns). Beside user labels the masks are applied only by TRL < 1.7's collator.+ zoo's MLX reader applies `assistant_masks` on presence, labels or not, and `completion_mask`+ only for an explicit `completion_only_loss=True`."""+ if mlx:+ return tuple(+ c+ for c in _MASK_COLUMNS+ if c in columns and (completion_only_loss is True or c != "completion_mask")+ )if "labels" in columns and not _collator_masks_user_labels():return ()if completion_only_loss is None:@@ -106,23 +118,54 @@ def has_custom_labels(dataset) -> bool:return "labels" in _column_names(dataset)+def _check_labels_range(flat_labels, vocab_size) -> None:+ import pyarrow.compute as pc++ flat = pc.filter(flat_labels, pc.not_equal(flat_labels, -100))+ if not len(flat):+ return+ bounds = pc.min_max(flat).as_py()+ if bounds["min"] is None:+ return+ if bounds["min"] < 0 or (vocab_size and bounds["max"] >= vocab_size):+ bad = bounds["min"] if bounds["min"] < 0 else bounds["max"]+ _raise_bad_label(bad, vocab_size)+++def _raise_bad_label(bad, vocab_size):+ limit = f"in [0, {vocab_size})" if vocab_size else "non-negative"+ raise ValueError(+ f"Pre-tokenized dataset: label {bad} is invalid. Labels must be -100 (ignored) or a token id "+ f"{limit}. The dataset was likely tokenized for a different model or uses another ignore index."+ )+++def _raise_bad_mask_values(row_index):+ raise ValueError(+ f"Pre-tokenized dataset: row {row_index} has 'attention_mask' values other than 0 and 1."+ )+++def _raise_null_values(column, row_index):+ raise ValueError(+ f"Pre-tokenized dataset: row {row_index} has a missing (null) value inside '{column}'. "+ "Every position must hold an integer."+ )++def _check_arrow_table(table,max_seq_length,vocab_size,masks = (),labels = True,-) -> bool:+) -> tuple[bool, bool]:+ """Returns (needs_truncation, needs_trimming)."""import pyarrow as paimport pyarrow.compute as pcids = table.column("input_ids")lengths = pc.list_value_length(ids)- if labels and "labels" in table.column_names:- if not pc.all(pc.equal(lengths, pc.list_value_length(table.column("labels")))).as_py():- raise ValueError(- "Pre-tokenized dataset: 'labels' must have the same length as 'input_ids' in every row."- )for name in masks:# An all-null or scalar column has no list kernel: reject it with the same error.kind = table.column(name).type@@ -136,6 +179,33 @@ def _check_arrow_table(# A row without the mask compares as null: that row fails too.if pc.all(same, skip_nulls = False).as_py() is not True:raise _mask_error(name)+ others = [c for c in ("attention_mask", "token_type_ids") if c in table.column_names]+ if labels and "labels" in table.column_names:+ others.append("labels")+ # Arrow reductions (any, all, min_max) skip nulls, so a mask such as [None, 1] or a label hole would pass every+ # check below and reach the trainer; refuse null elements first.+ for column in ["input_ids", *masks, *others]:+ if pc.list_flatten(table.column(column)).null_count:+ values = table.column(column).combine_chunks()+ holes = pc.is_null(pc.list_flatten(values))+ _raise_null_values(column, pc.filter(pc.list_parent_indices(values), holes)[0].as_py())+ # Trimming slices every token column at the mask's boundaries, so each must line up with input_ids.+ for column in others:+ if not pc.all(pc.equal(lengths, pc.list_value_length(table.column(column)))).as_py():+ raise _mask_error(column)+ needs_trimming = False+ if "attention_mask" in table.column_names:+ mask = table.column("attention_mask").combine_chunks()+ flat_mask = pc.list_flatten(mask)+ if pa.types.is_boolean(flat_mask.type):+ # Arrow has no bool-vs-int comparison kernel; True/False are exactly 1/0, so compare them as integers.+ flat_mask = pc.cast(flat_mask, pa.int8())+ # Exact membership, not a range: a float mask such as [0.5, 1.0] sits inside [0, 1] yet is neither value.+ bad = pc.and_(pc.not_equal(flat_mask, 0), pc.not_equal(flat_mask, 1))+ if pc.any(bad).as_py():+ _raise_bad_mask_values(pc.filter(pc.list_parent_indices(mask), bad)[0].as_py())+ # Only a mask with zeros changes what trains (TRL rebuilds all-one masks); an all-ones mask is left as is.+ needs_trimming = pc.min_max(flat_mask).as_py()["min"] == 0if vocab_size:flat = pc.list_flatten(ids)bounds = pc.min_max(flat).as_py() if len(flat) else {"min": 0, "max": 0}@@ -146,8 +216,62 @@ def _check_arrow_table(f"(size {vocab_size}). The dataset was likely ""tokenized for a different model; re-tokenize it with this model's tokenizer.")+ if "labels" in others:+ _check_labels_range(pc.list_flatten(table.column("labels")), vocab_size)longest = pc.max(lengths).as_py() or 0- return longest > max_seq_length+ return bool(max_seq_length) and longest > max_seq_length, needs_trimming+++def _trim_row(+ row_index,+ columns,+ values,+ masks = (),+):+ """Drops the leading/trailing attention_mask==0 positions of one row from every token column. TRL's collators+ rebuild the mask as all ones (padding-free ones drop it), so trimming is the only way a pad stays unattended."""+ width = len(values[columns.index("input_ids")])+ for column, value in zip(columns, values):+ # A mask the trainer applies must be present; a scalar (None, int, numpy 0-d) has no len().+ if value is None and column not in masks:+ continue+ try:+ bad = len(value) != width+ except TypeError:+ bad = True+ if bad:+ raise _mask_error(column)+ mask = values[columns.index("attention_mask")] if "attention_mask" in columns else None+ if mask is None:+ return values+ if mask.count(0) + mask.count(1) != len(mask):+ _raise_bad_mask_values(row_index)+ if 0 not in mask:+ return values+ if 1 not in mask:+ raise ValueError(+ f"Pre-tokenized dataset: row {row_index} has an all-zero 'attention_mask', so it has no tokens "+ "to train on. Remove the row."+ )+ start = mask.index(1)+ stop = len(mask) - mask[::-1].index(1)+ if 0 in mask[start:stop]:+ raise ValueError(+ f"Pre-tokenized dataset: row {row_index} has 'attention_mask' zeros between attended tokens. "+ "Only leading or trailing padding can be masked; Studio's trainer attends every kept token, "+ "so remove the masked tokens from input_ids (and labels) instead."+ )+ return [v[start:stop] if v is not None else v for v in values]+++def _restore_format(out, fmt):+ # The whole format: the column selection too, so hidden columns stay hidden.+ return out.with_format(+ fmt["type"],+ columns = fmt["columns"],+ output_all_columns = fmt["output_all_columns"],+ **(fmt["format_kwargs"] or {}),+ )def prepare_pretokenized_dataset(@@ -156,44 +280,75 @@ def prepare_pretokenized_dataset(max_seq_length,vocab_size = None,completion_only_loss = None,+ mlx = False,):- """Unsloth's SFT preparation passes tokenized rows through untouched: an over-long row would reach the model whole and an id past the embedding table is a device-side assert mid-run. Idempotent."""+ """Unsloth's SFT preparation passes tokenized rows through untouched: an over-long row would reach the model whole and an id past the embedding table is a device-side assert mid-run. Rows whose attention_mask zeros are leading/trailing padding lose those positions (the trainer would attend and train on them); zeros between attended tokens are refused. A falsy max_seq_length skips truncation. Idempotent."""names = _column_names(dataset)- completion_only_loss = resolve_completion_only_loss(dataset, completion_only_loss)+ if not mlx:+ completion_only_loss = resolve_completion_only_loss(dataset, completion_only_loss)# Masks are checked even when set_format hides them: TRL 0.22-0.26 re-exposes every column through# with_transform, and 1.7+ reads dataset.column_names and builds labels with map(), which sees them all.- masks = _checked_masks(getattr(dataset, "column_names", None) or names, completion_only_loss)+ masks = _checked_masks(+ getattr(dataset, "column_names", None) or names, completion_only_loss, mlx = mlx+ )# A mask the trainer will not apply is left as it is (it may not even be a list).columns = [c for c in _TOKEN_COLUMNS if (c in names and c not in _MASK_COLUMNS) or c in masks]table = getattr(dataset, "data", None)- needs_truncation = True- if table is not None and hasattr(table, "column"):- # Covers the whole backing table, rows a select() hid included: a bad id there is still a bad dataset.- needs_truncation = _check_arrow_table(- table, max_seq_length, vocab_size, masks, labels = "labels" in names++ if table is None or not hasattr(table, "column"):+ # Streaming: nothing to scan up front, so rows are checked, trimmed and truncated as they are read.+ def _prepare(batch, indices):+ # A formatted stream (numpy, torch) hands over arrays: work on plain lists.+ out = {+ c: [v.tolist() if hasattr(v, "tolist") else v for v in batch[c]] for c in columns+ }+ for i, row_index in enumerate(indices):+ for c in columns:+ if isinstance(out[c][i], (list, tuple)) and None in out[c][i]:+ _raise_null_values(c, row_index)+ labels = out["labels"][i] if "labels" in out else None+ if labels is not None and len(labels) != len(out["input_ids"][i]):+ raise _mask_error("labels")+ if labels:+ high, low = max(labels), min((x for x in labels if x != -100), default = 0)+ if low < 0 or (vocab_size and high >= vocab_size):+ _raise_bad_label(low if low < 0 else high, vocab_size)+ values = _trim_row(row_index, columns, [out[c][i] for c in columns], masks)+ if max_seq_length:+ values = [v[:max_seq_length] if v is not None else v for v in values]+ for c, v in zip(columns, values):+ out[c][i] = v+ return out++ return dataset.map(_prepare, batched = True, with_indices = True)++ # Covers the whole backing table, rows a select() hid included: a bad id there is still a bad dataset.+ needs_truncation, needs_trimming = _check_arrow_table(+ table, max_seq_length, vocab_size, masks, labels = "labels" in names+ )+ if needs_trimming:++ def _trim(batch, indices):+ out = {c: list(batch[c]) for c in columns}+ for i, row_index in enumerate(indices):+ trimmed = _trim_row(row_index, columns, [out[c][i] for c in columns], masks)+ for c, v in zip(columns, trimmed):+ out[c][i] = v+ return out++ fmt = dataset.format+ dataset = _restore_format(+ dataset.with_format(None).map(+ _trim,+ batched = True,+ with_indices = True,+ desc = "Trimming masked padding from pre-tokenized rows",+ ),+ fmt,)if not needs_truncation or not max_seq_length:return dataset- if table is None:-- def _truncate(batch):- # Streamed rows never reach _check_arrow_table: check the masks before slicing.- for name in masks:- for ids, mask in zip(batch["input_ids"], batch[name]):- # A scalar (None, int, numpy 0-d) has no len(): the mask error, as on the Arrow path.- try:- bad = ids is None or len(mask) != len(ids)- except TypeError:- bad = True- if bad:- raise _mask_error(name)- return {- c: [v[:max_seq_length] if v is not None else v for v in batch[c]] for c in columns- }-- return dataset.map(_truncate, batched = True)-import pyarrow.compute as pcdef _truncate_arrow(batch):@@ -207,11 +362,4 @@ def prepare_pretokenized_dataset(out = dataset.with_format("arrow").map(_truncate_arrow, batched = True, desc = "Truncating pre-tokenized rows")- # Restore the whole format: the column selection too, so hidden columns stay hidden.- fmt = dataset.format- return out.with_format(- fmt["type"],- columns = fmt["columns"],- output_all_columns = fmt["output_all_columns"],- **(fmt["format_kwargs"] or {}),- )+ return _restore_format(out, dataset.format)