Repository navigation
Studio: trim masked padding from pre-tokenized rows and range-check labels - #14818
Conversation
…abels TRL's language-modeling collator rebuilds attention_mask as all ones (and the padding-free path drops it), so pre-padded token-ID rows had their pad tokens attended, and trained on when the dataset has no labels column. Preparation now drops leading/trailing attention_mask==0 positions from every token column and refuses rows with zeros between attended tokens or an all-zero mask. Labels must be -100 or a token id inside the vocabulary, like input_ids. All-ones and mask-less datasets are returned unchanged.
|
@codex review |
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dd14b9c388
ℹ️ 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 not pc.all(pc.equal(lengths, pc.list_value_length(labels))).as_py(): | ||
| if "attention_mask" in table.column_names: | ||
| # 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(pc.list_flatten(table.column("attention_mask"))).as_py() == 0 |
There was a problem hiding this comment.
Validate mask values before deciding not to trim
For a map-style dataset whose mask contains a negative value alongside padding, such as [-1, 0, 1], the minimum is -1, so needs_trimming is false and neither the binary-value validation nor trimming runs. The row then reaches TRL unchanged, where the zero-masked token is attended and potentially trained on—the exact corruption this change is intended to prevent. Validate that all mask values are 0 or 1 independently of the trimming decision.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, fixed in 3655faa8b8. The map-style path now checks the mask's min and max before deciding whether to trim, so a negative value or a value above 1 is refused with the offending row even when the mask has no zeros (for example [-1, 0, 1, 1] or [1, 2, 1, 1]). The streaming path does the same check before its "no zeros, leave it" early return. All-ones masks still pass through untouched. Both cases are now in test_prepare_refuses_masks_it_cannot_trim for map-style and streaming.
| if "attention_mask" in out: | ||
| values = _trim_row(row_index, out["attention_mask"][i], values) |
There was a problem hiding this comment.
Check streaming mask lengths before slicing rows
For streaming datasets, the mask length is never compared with input_ids before _trim_row uses its boundaries to slice every token column. A row with input_ids=[1,2,3] and attention_mask=[0,1], for example, is silently converted to input_ids=[2], dropping the unrepresented final token; the equivalent map-style dataset is correctly rejected. Since format detection does not validate masks, perform the same per-row length check on this streaming path before trimming.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3655faa8b8. Streaming rows now check that labels matches input_ids in every row, and before any trimming, that every per-token column (attention_mask, labels, token_type_ids, completion_mask, assistant_masks) lines up with input_ids. So input_ids=[1, 2, 3] with attention_mask=[0, 1] is now refused with the same message as the map-style path, instead of becoming [2]. test_prepare_refuses_a_padded_mask_of_another_length now covers both paths.
| vocab_size = None, | ||
| ): | ||
| """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. Idempotent.""" |
There was a problem hiding this comment.
Invoke padding preparation on the MLX training path
On Apple Silicon, _run_mlx_training sends the formatted dataset directly to MLXTrainer without calling this helper; the MLX pre-tokenized batching path consumes input_ids and labels but does not apply the row's attention_mask. Consequently, masked padding is still attended and, when labels are absent, trained on for Mac runs, while the token preview does call this helper and misleadingly shows the padding removed. Wire the same preparation into the MLX train and eval paths.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. _run_mlx_training handed pre-tokenized rows straight to MLXTrainer, and zoo's pre-tokenized MLX path reads input_ids, labels, completion_mask and assistant_masks but never applies attention_mask. Fixed in 3655faa8b8: once the eval split is settled, the worker runs prepare_pretokenized_dataset on both the train and eval datasets whenever the final format is pretokenized. On MLX it only trims and validates (max_seq_length=None), because MLX already truncates to max_seq_length itself. A test checks that both datasets are prepared before MLXTrainer is built.
…ows on MLX Mask values must be 0 or 1 even when no trimming is needed. Streaming rows check label and mask lengths before slicing. completion_mask and assistant_masks are trimmed and truncated with input_ids. The MLX worker trims masked padding before MLXTrainer, and token preview no longer reports trimmed padding as truncation. [skip ci]
|
@codex review |
|
@codex security review |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3655faaf2d
ℹ️ 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 bounds["min"] is not None and (bounds["min"] < 0 or bounds["max"] > 1): | ||
| mask = table.column("attention_mask").combine_chunks() | ||
| flat = pc.list_flatten(mask) | ||
| bad = pc.or_(pc.less(flat, 0), pc.greater(flat, 1)) | ||
| _raise_bad_mask_values(pc.filter(pc.list_parent_indices(mask), bad)[0].as_py()) |
There was a problem hiding this comment.
Reject fractional values in Arrow attention masks
For a map-style dataset with an attention_mask such as [0.5, 1.0], both values fall within the min/max bounds, so validation passes and needs_trimming remains false. The row is returned unchanged even though the helper promises to reject every value other than 0 or 1; TRL then rebuilds an all-one mask and attends the malformed position. Check each flattened value for exact membership in {0, 1} rather than only checking its range.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, fixed in 95e8b3dc14. The Arrow path only compared the min/max against [0, 1], so a float mask like [0.5, 1.0] slipped through with no zero and was returned untouched. It now checks exact membership (every value equal to 0 or 1) and reports the first offending row; the streaming path already did this per row. Added [0.5, 1.0, 1.0, 1.0] and [0.0, 0.5, 1.0, 1.0] cases to test_prepare_refuses_masks_it_cannot_trim for both map-style and streaming; the map-style fractional case failed before the change. Integer and float all-ones masks still pass and come back unchanged.
| # Only a mask with zeros changes what trains (TRL rebuilds all-one masks); an all-ones mask is left as is. | ||
| needs_trimming = bounds["min"] == 0 | ||
| # Trimming slices every token column at the mask's boundaries, so each must line up with input_ids. | ||
| for column in _TOKEN_COLUMNS[1:] if needs_trimming else ("labels",): |
There was a problem hiding this comment.
Validate supervision masks even when no trimming is needed
For an unpadded map-style row whose completion_mask or assistant_masks length differs from input_ids, needs_trimming is false and this loop validates only labels, leaving the malformed supervision mask to reach TRL and cause a shape mismatch when it is applied position by position. Although padded rows are now handled, the current conditional is fresh evidence that these columns are still skipped whenever the attention mask has no zeros; validate every present per-token column independently of trimming.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, fixed in 95e8b3dc14. The length check now covers every present per-token column (attention_mask, labels, token_type_ids, completion_mask, assistant_masks) on every row, whether or not the row gets trimmed and whether or not there is an attention mask at all, in both the Arrow and streaming paths. New test test_prepare_refuses_an_unpadded_token_column_of_another_length covers each column with an all-ones mask and with no mask; all 12 cases failed before. Validation only raises, so well-formed all-ones and mask-less datasets are still returned as the same object (the byte-identical test still passes).
| if eval_dataset is not None: | ||
| eval_dataset = prepare_pretokenized_dataset(eval_dataset, max_seq_length = None) |
There was a problem hiding this comment.
Prepare the MLX eval split only when it is pre-tokenized
When a Mac run uses pre-tokenized training data but a separately supplied eval dataset that auto-formats to text, dataset_final_format describes only the training split, yet this call unconditionally sends the eval split to prepare_pretokenized_dataset. The eval formatter above runs independently, so such an eval dataset has no input_ids; preparation then fails at table.column("input_ids") before MLXTrainer starts. Track the eval split's resolved format and prepare it only when that split is also pre-tokenized.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 95e8b3dc14. The MLX worker now tracks the eval split's own resolved format (eval_final_format, taken from the eval formatter's result, or the training format when eval is carved out of train) and only runs prepare_pretokenized_dataset on the eval split when that is pretokenized. A separately supplied text eval set goes to MLXTrainer the same way it did before this PR. Added test_mlx_training_prepares_eval_only_when_it_is_pretokenized, which failed before.
…n, prepare MLX eval only when pre-tokenized [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 95e8b3de69
ℹ️ 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 "attention_mask" in table.column_names: | ||
| flat_mask = pc.list_flatten(table.column("attention_mask")) | ||
| # Exact membership, not a range: a float mask such as [0.5, 1.0] sits inside [0, 1] yet is neither value. | ||
| if pc.any(pc.and_(pc.not_equal(flat_mask, 0), pc.not_equal(flat_mask, 1))).as_py(): |
There was a problem hiding this comment.
Handle boolean Arrow masks before integer comparisons
For a map-style dataset whose attention_mask is stored as Arrow bool—for example Dataset.from_dict({"input_ids": [[1, 2]], "attention_mask": [[True, False]]})—these comparisons invoke not_equal(bool, int64), for which PyArrow has no kernel, so preparation raises ArrowNotImplementedError instead of trimming an otherwise valid binary mask. Normalize boolean masks or compare with type-compatible scalars before performing the exact-membership check.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, fixed. A bool attention_mask is now cast to int8 before the 0/1 membership check and min/max scan, so not_equal(bool, int64) is never reached. True and False are exactly 1 and 0, so a boolean mask is trimmed the same way as an integer one, and the kept rows keep their bool values. An all-True boolean mask still means no trimming, so the dataset comes back as the same object with the table unchanged. Added tests for map-style and streaming: padding is trimmed, an interior False is refused, and an all-True mask comes back unchanged.
…eval split on its own format
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a88f6fc0da
ℹ️ 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".
| eval_final_format = ( | ||
| str(dataset.get("eval_final_format", dataset_final_format) or "").lower() | ||
| if isinstance(dataset, dict) | ||
| else "" |
There was a problem hiding this comment.
Apply response masking independently to each split
When the training and separately supplied eval datasets resolve to different formats, masking is still controlled solely by user_labels from the training split. For example, a pre-tokenized train split with custom labels and a text eval split now passes preparation, but user_labels=True disables train_on_completions for both, so eval loss includes prompt tokens; in the reverse combination, masking can overwrite the pre-tokenized eval split's custom objective. Apply response masking per split rather than using the training format for both.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Leaving this one out of this PR. Choosing train_on_completions from the training split, and applying that one decision to a separately supplied eval split, is how main already works: user_labels is computed from dataset["dataset"] only, and train_on_responses_only masks both trainer.train_dataset and trainer.eval_dataset in one call. Separately formatted eval splits that resolve to a different format than train were possible before this PR as well. This PR only trims masked padding and validates pre-tokenized rows; it does not change which split decides masking. Masking each split on its own means splitting the apply_completion_masking / train_on_responses_only call per dataset, which is a separate change, so I would rather do it in its own PR than fold it in here.
There was a problem hiding this comment.
Not changed here: response masking by the train split's labels predates this PR (main behaves the same for mixed-format train/eval pairs) and only moves the reported eval loss; out of scope for this padding fix.
| # Exact membership, not a range: a float mask such as [0.5, 1.0] sits inside [0, 1] yet is neither value. | ||
| if pc.any(pc.and_(pc.not_equal(flat_mask, 0), pc.not_equal(flat_mask, 1))).as_py(): |
There was a problem hiding this comment.
Reject null values in Arrow attention masks
For a map-style dataset with a mask such as [None, 1], the comparisons produce a null result and pc.any skips it, while min_max also ignores it. The row is therefore accepted unchanged and TRL rebuilds an all-one mask, attending and potentially training on the malformed position. Check for null list elements before this reduction so every accepted value is actually 0 or 1.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, fixed in 6d94106. Arrow's any / min_max skip nulls, so a mask like [None, 1] passed as all ones. _check_arrow_table now refuses a null element in any token column (input_ids, attention_mask, labels, token_type_ids, completion_mask, assistant_masks) before the other checks and names the first bad row. The streaming path does the same check per row, so labels with a hole get a clear error too instead of a TypeError from max(). Datasets with no nulls take the same path as before and come out unchanged. Tests: test_prepare_refuses_null_values_in_token_columns (mask and labels, map style and streaming).
| if dataset_final_format == "pretokenized": | ||
| from utils.datasets.pretokenized import prepare_pretokenized_dataset | ||
|
|
||
| dataset = prepare_pretokenized_dataset(dataset, max_seq_length = None) |
There was a problem hiding this comment.
Pass the model vocabulary size on the MLX path
For Apple Silicon runs, both new preparation calls omit vocab_size, so a pre-tokenized row with an otherwise valid input_ids sequence but an out-of-range positive label is accepted and reaches the MLX loss, where indexing the vocabulary can fail mid-run. The CUDA path derives the embedding vocabulary size before preparation; derive the corresponding MLX model/tokenizer size and pass it here as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6d94106. The MLX path now gives both preparation calls vocab_size = _mlx_vocab_size(model), which reads the row count of the input embedding table. It looks under model.model.embed_tokens, the language_model wrapper for VLMs, and a LoRA-wrapped embedding's inner module, and it uses num_embeddings for QuantizedEmbedding because that weight is packed. If no table can be found it returns None, which skips only the range check, the same as before. Tests: test_mlx_vocab_size_reads_the_input_embedding_table and test_mlx_training_passes_the_model_vocab_size_to_both_splits.
…-tokenized eval split unpacked
|
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". |
Drops the earlier auto-format of unrelated unsloth/ and tests/ files (AST-equal) so the PR only touches Studio. [skip ci]
…m embeddings [skip ci]
…kip torch-format tests without torch [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
Problem
#13816 lets Studio train on pre-tokenized datasets (
input_ids, optionalattention_maskandlabels). Theattention_maskcolumn survives preparation, but TRL'sDataCollatorForLanguageModelingnever reads it: it rebuilds the mask as all ones (TRL 0.22.2 through 1.16.0), and withpadding_freeit drops the mask entirely. For pre-padded rows such asthe pad tokens are attended, and when the dataset has no
labelscolumn they are also trained on. Reproduced on main with the real Studio preparation and the generatedUnslothSFTTrainer(CPU, tiny GPT-2, no labels column):Separately,
labelswere 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:attention_maskzeros 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.labelsmust be -100 or a token id in[0, vocab_size), matching the existinginput_idscheck.After the fix, the same repro gives
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.test_pretokenized_dataset.pyandtest_token_preview.pypass (79 passed).padding_free=Truethe 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.