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
SFT: answer the pre-tokenized cap check from Arrow lengths when they prove it (#16293)
Daniel Han44290aa41091
diff --git a/tests/utils/test_cap_scan_arrow.py b/tests/utils/test_cap_scan_arrow.pynew file mode 100644index 00000000000..d751758b744--- /dev/null+++ b/tests/utils/test_cap_scan_arrow.py@@ -0,0 +1,183 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The pre-tokenized cap scan answers from Arrow lengths when it can, and its verdict+never differs from the row-by-row pass it short-circuits."""++from __future__ import annotations++import ast+import re+import textwrap+import types+from pathlib import Path++import pytest++datasets = pytest.importorskip("datasets")+pa = pytest.importorskip("pyarrow")+from datasets import Dataset, Features, Image, LargeList, Sequence, Value # noqa: E402++REPO_ROOT = Path(__file__).resolve().parents[2]+RL_PATH = REPO_ROOT / "unsloth" / "models" / "rl.py"+CAP = 3+++def _load_helpers():+ source = RL_PATH.read_text(encoding = "utf-8")+ wanted = {+ "_attested_within_cap",+ "_arrow_within_cap",+ "pretokenized_within_cap",+ "_SCAN_ROWS",+ "_TRUNCATION_ATTESTATION_ATTR",+ }+ kept = [+ node+ for node in ast.parse(source).body+ if (isinstance(node, ast.FunctionDef) 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_cap_helpers")+ exec(compile(ast.Module(body = kept, type_ignores = []), str(RL_PATH), "exec"), module.__dict__)+ return module, source+++rl, _SOURCE = _load_helpers()+++def _inlined():+ 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))+ namespace = {"_unsloth_cap": CAP, "_UNSLOTH_SCAN_ROWS": 1024}+ exec(textwrap.dedent(body.encode().decode("unicode_escape")), namespace)+ return namespace["_unsloth_within_cap"]+++def _row_pass(ds, cap = CAP):+ """The row loop as it was before the Arrow short-circuit."""+ if ds is None:+ return True+ try:+ try:+ n = len(ds)+ except Exception:+ n = None+ rows = iter(ds)+ if rows is iter(ds):+ return False+ seen = 0+ for row in rows:+ if "input_ids" not in row:+ return True+ if len(row["input_ids"]) > cap:+ return False+ seen += 1+ if n is None and seen >= 1024:+ return False+ except Exception:+ return False+ return True+++def _shapes():+ fits = Dataset.from_dict(+ {"input_ids": [[1, 2], [3, 4, 5], []], "labels": [[1, 2], [3, 4, 5], []]}+ )+ over = Dataset.from_dict({"input_ids": [[1, 2], [3, 4, 5, 6]]})+ none_first = Dataset.from_dict({"input_ids": [None, [1, 2]]})+ none_late = Dataset.from_dict({"input_ids": [[1], [1, 2], None]})+ big = Dataset.from_dict({"input_ids": [[1] * (i % 4) for i in range(5000)]})+ big_over = Dataset.from_dict(+ {"input_ids": [[1] * (3 if i != 4321 else 4) for i in range(5000)]}+ )+ large = Dataset.from_dict(+ {"input_ids": [[1, 2], [3]]}, features = Features({"input_ids": LargeList(Value("int32"))})+ )+ fixed = Dataset.from_dict(+ {"input_ids": [[1, 2], [3, 4]]},+ features = Features({"input_ids": Sequence(Value("int32"), length = 2)}),+ )+ fixed_over = Dataset.from_dict(+ {"input_ids": [[1, 2, 3, 4]]},+ features = Features({"input_ids": Sequence(Value("int32"), length = 4)}),+ )+ nested = Dataset.from_dict({"input_ids": [[[1, 2, 3, 4]], [[1], [2], [3]]]})+ as_text = Dataset.from_dict({"input_ids": ["abcdef", "ab"]})+ as_int = Dataset.from_dict({"input_ids": [1, 2]})+ raw = Dataset.from_dict({"text": ["a", "b"]})+ empty = Dataset.from_dict({"input_ids": [[1, 2, 3, 4]]}).select([])+ hidden_long = over.select([0])+ shown_long = over.select([1, 0])+ filtered = big_over.filter(lambda e: len(e["input_ids"]) < 4)+ shuffled = big_over.shuffle(seed = 0)+ numpy_fmt = over.with_format("numpy")+ cols_hidden = over.with_format(None, columns = [])+ with_image = Dataset.from_dict(+ {"input_ids": [[1, 2]], "image": [None]},+ features = Features({"input_ids": Sequence(Value("int32")), "image": Image()}),+ )+ transformed = fits.with_transform(lambda b: {"input_ids": [[1] * 9 for _ in b["input_ids"]]})+ attested = Dataset.from_dict({"input_ids": [[1] * 9]})+ attested._unsloth_truncated_to = CAP+ return {+ "fits": fits,+ "over": over,+ "none_first": none_first,+ "none_late": none_late,+ "big": big,+ "big_over": big_over,+ "large": large,+ "fixed": fixed,+ "fixed_over": fixed_over,+ "nested": nested,+ "as_text": as_text,+ "as_int": as_int,+ "raw": raw,+ "empty": empty,+ "hidden_long": hidden_long,+ "shown_long": shown_long,+ "filtered": filtered,+ "shuffled": shuffled,+ "numpy_fmt": numpy_fmt,+ "cols_hidden": cols_hidden,+ "with_image": with_image,+ "transformed": transformed,+ "attested": attested,+ "none": None,+ }+++SHAPES = _shapes()++[email protected]("name", sorted(SHAPES))+def test_both_copies_match_the_row_pass(name):+ ds = SHAPES[name]+ expected = True if name == "attested" else _row_pass(ds)+ assert rl.pretokenized_within_cap(ds, CAP) is expected+ assert _inlined()(ds) is expected+++def test_arrow_never_claims_what_the_rows_deny():+ for name, ds in SHAPES.items():+ if rl._arrow_within_cap(ds, CAP) is True:+ assert _row_pass(ds) is True, name+++def test_a_plain_split_is_answered_without_reading_a_row(monkeypatch):+ ds = Dataset.from_dict({"input_ids": [[1] * (i % 4) for i in range(2000)]}).filter(+ lambda e: len(e["input_ids"]) > 0+ )++ def refuse(self, *a, **k):+ raise AssertionError("rows were read")++ monkeypatch.setattr(Dataset, "__iter__", refuse)+ monkeypatch.setattr(Dataset, "__getitem__", refuse)+ assert rl.pretokenized_within_cap(ds, CAP) is True+ assert _inlined()(ds) is Truediff --git a/tests/utils/test_truncation_attestation.py b/tests/utils/test_truncation_attestation.pyindex 5a9c0c22964..c107df58f22 100644--- a/tests/utils/test_truncation_attestation.py+++ b/tests/utils/test_truncation_attestation.py@@ -27,6 +27,7 @@ def _load_rl_module():tree = ast.parse(source)wanted = {"_attested_within_cap",+ "_arrow_within_cap","pretokenized_within_cap","splits_within_cap","_SCAN_ROWS",diff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex be286707cb6..284f2c12cc0 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -1252,6 +1252,37 @@ def _attested_within_cap(dataset, cap):return claimed <= cap+def _arrow_within_cap(dataset, cap):+ """True when Arrow list lengths prove every ``input_ids`` fits ``cap``, else None (the row scan decides). Only plain python-format splits with nothing to decode, where a row's ``input_ids`` is its stored list."""+ try:+ import datasets+ import pyarrow+ import pyarrow.compute as pc+ from datasets.features.features import require_decoding++ if type(dataset) is not datasets.Dataset or dataset._format_type is not None:+ return None+ if any(require_decoding(feature) for feature in dataset.features.values()):+ return None+ column = dataset.data.column("input_ids")+ kind = column.type+ if not (+ pyarrow.types.is_list(kind)+ or pyarrow.types.is_large_list(kind)+ or pyarrow.types.is_fixed_size_list(kind)+ ):+ return None+ lengths = pc.list_value_length(column)+ if dataset._indices is not None:+ lengths = lengths.take(dataset._indices.column(0))+ if lengths.null_count:+ return None+ longest = pc.max(lengths).as_py()+ return True if longest is None or longest <= cap else None+ except Exception:+ return None++def pretokenized_within_cap(dataset, cap):"""Whether every pre-tokenized row in ``dataset`` already fits ``cap``. The generated ``__init__`` carries an inlined copy (that module is standalone and cannot import from here); this one serves callers reached when the generated block was never inserted, and a test pins the two to the same verdict. Unverifiable reads FALSE, never true: a single-pass stream cannot be scanned without consuming it, an unexhausted one proves only its prefix, and a split that raises mid-scan has said nothing, and in each case guessing yes is the silently-uncapped run."""if dataset is None:@@ -1259,6 +1290,8 @@ def pretokenized_within_cap(dataset, cap):attested = _attested_within_cap(dataset, cap)if attested is not None:return attested+ if _arrow_within_cap(dataset, cap):+ return Truetry:try:n = len(dataset)@@ -2961,6 +2994,21 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):" _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"+ # Inline copy of _arrow_within_cap: anything it cannot prove falls through to the row loop.+ " try:\n"+ " import datasets as _unsloth_hfds, pyarrow as _unsloth_pa, pyarrow.compute as _unsloth_pc\n"+ " from datasets.features.features import require_decoding as _unsloth_decodes\n"+ " if type(_ds) is _unsloth_hfds.Dataset and _ds._format_type is None and not any(_unsloth_decodes(_f) for _f in _ds.features.values()):\n"+ " _unsloth_col = _ds.data.column('input_ids')\n"+ " _unsloth_t = _unsloth_col.type\n"+ " if _unsloth_pa.types.is_list(_unsloth_t) or _unsloth_pa.types.is_large_list(_unsloth_t) or _unsloth_pa.types.is_fixed_size_list(_unsloth_t):\n"+ " _unsloth_lens = _unsloth_pc.list_value_length(_unsloth_col)\n"+ " if _ds._indices is not None: _unsloth_lens = _unsloth_lens.take(_ds._indices.column(0))\n"+ " if not _unsloth_lens.null_count:\n"+ " _unsloth_longest = _unsloth_pc.max(_unsloth_lens).as_py()\n"+ " if _unsloth_longest is None or _unsloth_longest <= _unsloth_cap: return True\n"+ " except Exception:\n"+ " pass\n"" try:\n"" try: _n = len(_ds)\n"" except Exception: _n = None\n"