Repository navigation
Studio: train on pre-tokenized datasets (input_ids / attention_mask / labels) - #13816
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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: |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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." | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Streams are detected and truncated lazily; per-row validation of malformed rows deep in a stream is hardening beyond what this change targets.
| if eval_dataset is not None: | ||
| eval_dataset = prepare_pretokenized_dataset( | ||
| eval_dataset, max_seq_length = max_seq, vocab_size = vocab_size |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if is_pretokenized_dataset(dataset): | ||
| return { | ||
| "requires_manual_mapping": False, | ||
| "detected_format": PRETOKENIZED_FORMAT, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if labels is not None and ( | ||
| not _is_token_list(labels) or len(labels) != len(row["input_ids"]) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| return ( | ||
| isinstance(value, (list, tuple)) | ||
| and len(value) > 0 | ||
| and all(isinstance(x, int) and not isinstance(x, bool) for x in value) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| def has_custom_labels(dataset) -> bool: | ||
| return "labels" in _column_names(dataset) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Studio loads datasets fresh from uploads or the Hub, so a persisted set_format hiding a column is not a shape Studio produces.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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"]) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…a warning [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
… 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>
…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.  --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Fixes #7139
Studio could not train on a dataset that is already tokenized (rows holding
input_ids,attention_maskand customlabels). 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 detectinput_idsand keep the user'slabels); Studio just never routed them there.What changes
input_idson every sampled row,labelsof the same length when present) and reports it aspretokenizedwith 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.labelsnoTrain on responses onlymasking (the labels are the objective; without alabelscolumn the toggle still masks prompts frominput_ids), and sequence packing is turned off (on TRL < 1.7, which Studio installs, packing keeps onlyinput_idsand silently replaces the custom labels).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.Train on responses onlyon trains full sequences there and the run shows a warning saying so (add alabelscolumn 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
Could not auto-detect format mapping.SFTTraineronunsloth/Qwen3-0.6Bwith prepared rows: the user's labels arrive unchanged in the collated batch, 5 finite losses, an over-long row cut tomax_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.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 reportsunknownand asks for a role mapping the columns cannot satisfy; after, it reportspretokenizedand the dataset is ready to train.