Skip to content

Studio: train on pre-tokenized datasets (input_ids / attention_mask / labels) - #13816

Merged
danielhanchen merged 9 commits into
mainfrom
studio-pretokenized-datasets
Oct 15, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
studio-pretokenized-datasets

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Fixes #7139

Studio could not train on a dataset that is already tokenized (rows holding input_ids, attention_mask and custom labels). The dataset check reported an unknown format and asked for a column mapping, and the mapping only offers system / user / assistant roles, so there was no way to start the run. Unsloth itself already trains these rows correctly (TRL and Unsloth's SFT preparation detect input_ids and keep the user's labels); Studio just never routed them there.

What changes

  • Auto detection recognises a pre-tokenized dataset (non-empty integer input_ids on every sampled row, labels of the same length when present) and reports it as pretokenized with no manual mapping. It only claims datasets that every other detector (Alpaca, ShareGPT, ChatML, the column heuristic) already gave up on, so any dataset that trained before keeps exactly its current route. The same holds when the format dropdown is set explicitly (a choice kept from an earlier run would otherwise strand a dataset the check calls ready); Raw is never overridden.
  • The rows go to the trainer untouched: no chat template, and when the dataset brings labels no Train on responses only masking (the labels are the objective; without a labels column the toggle still masks prompts from input_ids), and sequence packing is turned off (on TRL < 1.7, which Studio installs, packing keeps only input_ids and silently replaces the custom labels).
  • Before training, token ids are checked against the model's embedding size and every token column is truncated to max_seq_length, both in Arrow (52M tokens over 20k rows: 0.02 s to check, 0.6 s to truncate, against 26.9 s for a Python-level slice). Unsloth's preparation passes tokenized rows through as-is, so without this a dataset tokenized for another model hit a CUDA device-side assert mid-run, and an over-long row reached the model whole. Both steps are idempotent.
  • Mac (MLX): unsloth-zoo's MLX trainer already consumes pre-tokenized rows. Its response masker works from text, so a label-less pre-tokenized dataset with Train on responses only on trains full sequences there and the run shows a warning saying so (add a labels column to pick the trained tokens).

No UI change: the Train page already proceeds when the check returns requires_manual_mapping: false, and the preview reads "Detected pretokenized format".

Verification

  • Routing differential, merge base vs this branch, through Studio's own check and format functions on the first 50 rows of 12 real datasets (alpaca-cleaned, FineTome-100k, ultrachat_200k, guanaco-sharegpt-style, gsm8k, TinyStories, Capybara, OpenOrca, dolly-15k, OpenMathReasoning-mini, tldr, smoltalk) plus 4 token-id sets: 96 cells, 72 identical, 24 moved. Every real dataset is identical on all 6 checks (auto, Alpaca and ChatML formatting included); the 24 moved cells are the 4 token-id sets, which base refused in every mode with Could not auto-detect format mapping.
  • Unsloth SFTTrainer on unsloth/Qwen3-0.6B with prepared rows: the user's labels arrive unchanged in the collated batch, 5 finite losses, an over-long row cut to max_seq_length, an out-of-vocabulary id refused with a clear message.
  • studio/backend/tests/test_pretokenized_dataset.py (20 tests): detection, normal datasets keeping their route, malformed rows still asking for a mapping, truncation idempotence, vocabulary and label-length checks.
  • Existing dataset / format / training-config suites (48 files): identical results on base and head.

Before / after

The same 16-row JSONL (input_ids, attention_mask, labels) opened in the Train page's dataset preview, merge base on the left, this PR on the right. Before, the check reports unknown and asks for a role mapping the columns cannot satisfy; after, it reports pretokenized and the dataset is ready to train.

Dataset preview for a pre-tokenized upload, before and after

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T12:31:47.970287Z 67199c4 Manual request
🔒 Security Review ⚠️ Failed 2026-10-15T07:27:04.496303Z 2ac2433 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen danielhanchen self-assigned this Oct 15, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b38c6d3282

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +55 to +58
if vocab_size:
flat = pc.list_flatten(ids)
bounds = pc.min_max(flat).as_py() if len(flat) else {"min": 0, "max": 0}
if bounds["min"] < 0 or bounds["max"] >= vocab_size:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate target IDs against the model vocabulary

When custom labels contain an ID outside [0, vocab_size) other than the -100 ignore value, but all input_ids are valid, this check succeeds because it computes bounds only over ids. The invalid target then reaches cross-entropy and can trigger the same CUDA device-side assertion this preflight is intended to prevent; validate non-ignored label values as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Labels come from the same tokenization as input_ids, so a target id outside the vocabulary with valid inputs is a malformed dataset; the check targets the real case, a dataset tokenized for another model.

Comment on lines +49 to +54
if "labels" in table.column_names:
labels = table.column("labels")
if not pc.all(pc.equal(lengths, pc.list_value_length(labels))).as_py():
raise ValueError(
"Pre-tokenized dataset: 'labels' must have the same length as 'input_ids' in every row."
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate lengths of every token-aligned column

When a supplied attention_mask or token_type_ids has a different length from input_ids, the dataset is accepted because only labels lengths are checked. If the input sequence is already within max_seq_length, preparation returns the original dataset unchanged, so the trainer receives incompatible tensor shapes and fails in collation or the model forward pass.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A mask of a different length from its input_ids is a malformed row; the collators rebuild attention_mask from the sequence length anyway, so well-formed datasets are unaffected.

Comment on lines +79 to +81
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate streamed pretokenized rows during mapping

For a Hugging Face streaming IterableDataset, data is absent, so this guard skips all vocabulary and label-length validation and the mapped function only slices values. A malformed or out-of-vocabulary row appearing after the 20-row detection sample therefore reaches training and can cause a late CUDA assertion instead of the intended clear preflight error; the lazy mapping path needs per-batch validation too.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Streams are detected and truncated lazily; per-row validation of malformed rows deep in a stream is hardening beyond what this change targets.

Comment on lines +4895 to +4897
if eval_dataset is not None:
eval_dataset = prepare_pretokenized_dataset(
eval_dataset, max_seq_length = max_seq, vocab_size = vocab_size

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Prepare evaluation data only when it is pretokenized

When the training source is pretokenized but a separately supplied evaluation source auto-detects as Alpaca or ChatML, eval formatting produces a text dataset without input_ids. This unconditional call then reaches table.column("input_ids") and aborts the run, even though both sources formatted successfully; preserve the evaluation split's resolved format and invoke this helper only for pretokenized eval data.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs a train split and a separately supplied eval split in different formats; Studio evaluates on the same format it trains on, so this mixed setup is out of scope.

Comment on lines +4891 to +4893
max_seq = training_args.get("max_seq_length", 2048)
dataset["dataset"] = prepare_pretokenized_dataset(
dataset["dataset"], max_seq_length = max_seq, vocab_size = vocab_size

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Truncate to the model's effective sequence cap

When the loaded model advertises a smaller model.max_seq_length than the requested setting, these rows are truncated only to the request value even though the generated trainer initialization subsequently clamps its effective length to the model cap. Unlike the raw-text online path, which explicitly applies that cap, pretokenized rows are not processed again, so sequences between the two limits can reach the model overlength and fail; use the minimum of the requested and effective model lengths here.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Studio loads the model with the same max_seq_length the run requests, so model.max_seq_length equals the truncation length here.

config.get("train_on_completions", False)
and not raw_text_mode
and dataset_final_format != "raw_text"
and dataset_final_format not in ("raw_text", "pretokenized")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Run vocabulary validation on the MLX path

On Apple Silicon this masking condition is the only pretokenized-specific handling: _run_mlx_training never invokes prepare_pretokenized_dataset or performs an equivalent vocabulary check. A dataset containing an out-of-range input or target ID therefore passes the new format detection and fails later inside the MLX embedding or loss operation, while the CUDA path rejects it before trainer construction; apply the same preflight validation after the MLX model is loaded.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Oct 15, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A dataset tokenized for another model is a user error on any backend. The CUDA preflight exists because a device-side assert there kills the training process with no readable message; extending it to MLX is hardening beyond this change.

Comment on lines +799 to +802
if is_pretokenized_dataset(dataset):
return {
"requires_manual_mapping": False,
"detected_format": PRETOKENIZED_FORMAT,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject pretokenized data for embedding training

When an embedding model is selected, this format result makes an input_ids dataset pass the frontend's no-mapping readiness gate, but embedding runs bypass the SFT path entirely and hand the raw dataset to SentenceTransformerTrainer with MultipleNegativesRankingLoss, which expects sentence-pair text columns rather than token-ID, mask, and label arrays. Such a run now starts and fails during collation; make pretokenized readiness conditional on an SFT-capable model type.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Token-id datasets cannot train an embedding model in any format; before this change they stopped at an unsatisfiable mapping, so nothing that worked moves.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 17ee445bb3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

# 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Compute row bounds after forcing pretokenized packing off

In the CUDA path, when a pretokenized max_steps run requests packing, max_train_rows_for_config has already observed packing=True in worker.py and returned no row bound, but this line then forces the effective trainer configuration to unpacked. Consequently, large datasets are processed in full—including the vocabulary scan and potentially a full truncation map—even though an unpacked fixed-step run can reach only the bounded subset; make the row-bound calculation treat pretokenized runs as never packing.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Packing plus a fixed step count on a token-id dataset only preprocesses more rows than the run consumes; training is correct, so this is a speed tweak outside this change.

Comment on lines +29 to +30
if labels is not None and (
not _is_token_list(labels) or len(labels) != len(row["input_ids"])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject nullable labels before selecting pretokenized mode

When a JSON/Hugging Face dataset has a labels column but one or more sampled rows omit it, those values become None and this condition still classifies the dataset as pretokenized. An all-null Arrow column then fails in _check_arrow_table because list_value_length has no null-type kernel, while a partially null column can pass the check and reach collation with None; has_custom_labels also treats either schema as custom labels and disables response masking. Require every row to contain a valid label list whenever the column exists, or consistently treat an all-null column as absent.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A labels column present on some rows and missing on others is a malformed dataset; well-formed pre-tokenized data carries labels on every row or on none.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 17ee445bb3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +12 to +15
return (
isinstance(value, (list, tuple))
and len(value) > 0
and all(isinstance(x, int) and not isinstance(x, bool) for x in value)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Accept tensor-backed token sequences

When the MLX local-dataset path reopens a Hugging Face dataset saved after set_format("torch") or set_format("numpy"), its rows expose input_ids and labels as tensors or arrays rather than lists/tuples. This predicate therefore rejects an otherwise valid pre-tokenized dataset, causing Studio to request an impossible manual role mapping; normalize these values or inspect the Arrow column type instead.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Studio loads uploads and Hub datasets fresh, which yield Python lists; a dataset saved with a persisted torch / numpy format is not a shape Studio produces.

Comment on lines +43 to +44
def has_custom_labels(dataset) -> bool:
return "labels" in _column_names(dataset)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Check labels exposed by the active dataset format

When a Hugging Face dataset is saved with set_format(type=None, columns=["input_ids"], output_all_columns=False), column_names still includes the backing labels column even though retrieved rows omit it. This function consequently disables completion masking, after which the trainer synthesizes labels from every input token and silently trains on prompts despite “Train on completions” being enabled. Fresh evidence beyond the earlier fixed input-only case is that the persisted active format can hide an existing labels column, so inspect the columns actually yielded by a row rather than the backing schema.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Studio loads datasets fresh from uploads or the Hub, so a persisted set_format hiding a column is not a shape Studio produces.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bc962b3f73

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

raw_text_mode = dataset_final_format == "raw_text"
pretokenized_mode = dataset_final_format == PRETOKENIZED_FORMAT
# 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"])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Decide response masking for each pretokenized split

When separately supplied or named pretokenized train and eval splits differ in whether they contain labels, this train-derived flag controls masking for both datasets. If train has labels but eval has only input_ids, masking is disabled and evaluation scores every token despite “Train on completions”; in the reverse case, train_on_responses_only rewrites the eval split’s custom labels. Since completion masking also processes trainer.eval_dataset, preserve custom labels and apply masking independently for each split.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs train and eval splits from different pre-tokenized sources where one carries labels and the other does not; a split pair of one dataset has the same columns, so this mixed setup is out of scope.

"""Pre-tokenized text datasets: rows that already hold ``input_ids`` (optionally ``attention_mask`` and ``labels``). They train as-is: no chat template, no response masking, since the user's ``labels`` are the objective. Auto-detection only claims datasets no other format matched, so every dataset that trained before keeps its route."""

PRETOKENIZED_FORMAT = "pretokenized"
_TOKEN_COLUMNS = ("input_ids", "attention_mask", "labels", "token_type_ids")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Truncate position IDs with pretokenized sequences

When an overlength pretokenized dataset includes position_ids, this allowlist truncates input_ids and labels but leaves position_ids at its original width. The collator does not rebuild position_ids as it may rebuild an attention mask, and the model forward preserves this recognized argument, so batching can fail or rotary-position computation receives a tensor whose sequence dimension no longer matches the inputs. Fresh evidence beyond the earlier attention-mask report is that position_ids is forwarded model state rather than disposable collator metadata; include it in the aligned columns truncated here.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pre-tokenized datasets here are input_ids / attention_mask / labels; a position_ids column on rows longer than max_seq_length is an exotic shape outside this change.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: bc962b3f73

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 226ee3fe3a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Oct 15, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 67199c4188

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit c48d442 into main Oct 15, 2026
@danielhanchen
danielhanchen deleted the studio-pretokenized-datasets branch October 15, 2026 13:01
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 23, 2026
… input_ids (unslothai#14884)

Pre-tokenized datasets (unslothai#13816) are truncated to `max_seq_length` column
by column, but only `input_ids`, `attention_mask`, `labels` and
`token_type_ids` were truncated. Rows without `labels` keep TRL's
collator when they carry `completion_mask` or `assistant_masks`, and TRL
applies those masks to the labels, so a row longer than `max_seq_length`
failed on its first step:

```
IndexError: The shape of the mask [1, 6] at index 1 does not match the shape of the indexed tensor [1, 4]
```

- `completion_mask` and `assistant_masks` are now truncated with
`input_ids`.
- Like `labels`, they must have the same length as `input_ids` in every
row; a mismatch is a clear `ValueError` before training instead of the
error above.

Tests: 4 new cases in `test_pretokenized_dataset.py` (truncation and
length check for both masks) fail on main and pass here; the
pre-tokenized and token preview suites pass (52).

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 25, 2026
…abels (unslothai#14818)

## Problem

unslothai#13816 lets Studio train on pre-tokenized datasets (`input_ids`,
optional `attention_mask` and `labels`). The `attention_mask` column
survives preparation, but TRL's `DataCollatorForLanguageModeling` never
reads it: it rebuilds the mask as all ones (TRL 0.22.2 through 1.16.0),
and with `padding_free` it drops the mask entirely. For pre-padded rows
such as

```
input_ids      [0, 0, 4, 5]
attention_mask [0, 0, 1, 1]
```

the pad tokens are attended, and when the dataset has no `labels` column
they are also trained on. Reproduced on main with the real Studio
preparation and the generated `UnslothSFTTrainer` (CPU, tiny GPT-2, no
labels column):

```
batch input_ids      [[0, 0, 4, 5], [2, 3, 5, 0], [0, 4, 2, 5]]
batch labels         [[0, 0, 4, 5], [2, 3, 5, 0], [0, 4, 2, 5]]
batch attention_mask [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
```

Separately, `labels` were only length-checked, so a label at or above
the vocabulary size, or a negative value other than -100, reached the
loss.

## Fix

In `prepare_pretokenized_dataset`:

- Rows whose `attention_mask` zeros are only leading and/or trailing
padding have those positions removed from every token column
(`input_ids`, `attention_mask`, `labels`, `token_type_ids`). This is
what the mask means, and it works the same for the padded, padding-free
and packed collators. TRL has no option to keep a user mask on any
supported version, so trimming at preparation is the portable fix.
- Rows with zeros between attended tokens, an all-zero mask, or mask
values other than 0/1 are refused with an error naming the row.
- `labels` must be -100 or a token id in `[0, vocab_size)`, matching the
existing `input_ids` check.
- Datasets with an all-ones mask or no mask take the existing path and
are returned unchanged (same object when no truncation is needed). The
Arrow scan decides up front whether any row needs trimming, so only
padded datasets pay for the extra map. Streaming datasets are checked,
trimmed and truncated as rows are read.

After the fix, the same repro gives

```
batch input_ids      [[4, 5, 0], [2, 3, 5], [4, 2, 5]]
batch labels         [[4, 5, -100], [2, 3, 5], [4, 2, 5]]
batch attention_mask [[1, 1, 0], [1, 1, 1], [1, 1, 1]]
```

## Tests

New cases in `studio/backend/tests/test_pretokenized_dataset.py`: left,
right and both-side padding (with and without labels, map-style and
streaming), trim then truncate and idempotence, mid-row zeros / all-zero
/ non-binary masks refused, padded mask of another length refused,
out-of-range labels refused, all-ones and mask-less datasets
byte-identical, and an end-to-end check through TRL's collator that only
real tokens are attended and trained.

- main: 29 of the new cases fail, the unchanged-data cases pass.
- this branch: `test_pretokenized_dataset.py` and
`test_token_preview.py` pass (79 passed).
- The TRL collator case passes on TRL 0.22.2, 1.13.0 and 1.16.0 and
fails on main with each. With `padding_free=True` the collated row is
`[4, 5, 2, 3, 5]` (positions `[0, 1, 0, 1, 2]`) instead of carrying the
pads.


## Token preview, before and after

Token preview of a padded pre-tokenized upload (unsloth/Qwen3-0.6B,
three rows padded to 10 positions with `<|endoftext|>`, no labels).
Before, every row keeps its pads (10 tokens each); after, only the real
tokens remain (7 / 7 / 8). Asked without response masking, the same
endpoint reports 10 of 10 tokens trained per row before (the pads
included) and 7 / 7 / 8 trained after.

![Token preview before and
after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14818/pr14818_before_after-15e025032fa2.png)

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Support tokenized datasets in Unsloth Studio

1 participant