Repository navigation
Stop padding-free SFT from tripping the TRL >= 1.0.0 max_length guard - #7951
Conversation
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 31254664b7
ℹ️ 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 _unsloth_columns is None and train_dataset is not None:\n" | ||
| " _unsloth_first_row = next(iter(train_dataset), None)\n" | ||
| " if isinstance(_unsloth_first_row, dict): _unsloth_columns = list(_unsloth_first_row.keys())\n" |
There was a problem hiding this comment.
Avoid consuming a sample while probing iterable datasets
When train_dataset is a single-pass iterable/stream without column_names, this new probe calls next(iter(train_dataset), None) before TRL prepares or stores the dataset. That advances the underlying iterator, so the first training example is silently dropped just to decide whether padding-free can stay enabled. For unknown schemas, prefer a non-destructive metadata check or conservatively disable padding-free instead of sampling from the dataset.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Checked this directly and no sample is lost. datasets.IterableDataset.__iter__ (and torch.utils.data.IterableDataset.__iter__) hands back a fresh iterator per call, so the probe does not advance anything shared: probe returns row0, and the full pass right after still yields row0..row4. TRL itself runs the identical probe unconditionally in the same __init__ - get_dataset_column_names does list(next(iter(dataset)).keys()) if dataset.column_names is None, plus dataset_sample = next(iter(train_dataset)) (sft_trainer.py:867 on 1.0.0, :1141 on 1.5.1, :1173 on 1.9.2) - and unsloth_zoo's sft_prepare_dataset does set(next(iter(dataset)).keys()). So this probe is neither the first nor the only reader, and conservatively disabling padding-free for an unknown schema would cost throughput for no gain.
| " except Exception:\n" | ||
| " pass\n" | ||
| " try:\n" | ||
| " _unsloth_columns = getattr(train_dataset, 'column_names', None)\n" |
There was a problem hiding this comment.
Check eval datasets before clearing max_length
When the training split is raw text but eval_dataset is already tokenized, this check leaves _unsloth_prep_truncates true because it only inspects train_dataset, then clears args.max_length. TRL prepares eval splits with the same rules as train, so a tokenized eval split skips the truncating tokenize pass and, under padding-free with max_length=None, overlength eval rows can reach evaluation unchanged; include eval split columns in this decision or disable padding-free if any unprepared split is tokenized.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Ran the exact case (raw-text train + pre-tokenized 1202-token eval split, model max 128). On TRL 1.5.1 with this branch: max_length=None, eval rows stay 1202 and collate to width 2404. The same script on TRL 0.25.1, which this diff never touches: max_length=128, eval rows stay 1202 and collate to width 2404 as well. Reason: TRL < 1.0's padding-free DataCollatorForLanguageModeling has no max_length parameter at all, so an eval cap has never been enforced under padding-free on any TRL Unsloth supports. Nothing regresses here. Folding eval into the decision would drop padding-free for the whole run - a throughput hit on every training step - to add a cap that no supported TRL applies to eval splits.
| " max_length = None\n" | ||
| " else:\n" | ||
| " print('Unsloth: Turning padding-free batching off, since your dataset is already tokenized and cannot be truncated during dataset preparation. Padding-free batching cannot enforce a `max_length` of ' + str(args.max_length) + '.')\n" | ||
| " args.padding_free = False\n" |
There was a problem hiding this comment.
Restore column pruning when disabling padding-free
When this branch disables padding-free for an already-tokenized or skip-prepare dataset, the auto/default path has already run configure_padding_free(), which forced remove_unused_columns=False. Leaving that flag false means the now-padded trainer keeps every original column; pre-tokenized datasets that still contain text or metadata columns can pass those strings into the LM/Seq2Seq collator and fail, whereas a normal non-padding-free run would prune them. Restore remove_unused_columns=True when turning padding-free off here.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Could not reproduce a failure on TRL 1.0.0, 1.5.1 or 1.9.2. A pre-tokenized dataset that keeps its text/source string columns, with padding-free auto-disabled by this branch and remove_unused_columns=False, collates fine in all three (batch keys ['attention_mask', 'input_ids', 'labels']), with and without skip_prepare_dataset. When data_collator=None TRL builds its own trl.trainer.sft_trainer.DataCollatorForLanguageModeling, which reads only the keys it needs and ignores the rest. The transformers LM/Seq2Seq collators only appear when the user passes one, and that path is blocked in unsloth/trainer.py before configure_padding_free() ever runs, so remove_unused_columns is still True there (verified: padding_free=False, remove_unused_columns=True, batch OK). Forcing it back to True would also silently override a user who set remove_unused_columns=False themselves, since the prior value is not recorded.
UNSLOTH_ALLOW_CPU=1 makes `import unsloth` skip both halves of the SFT patch on purpose, so cross-platform CI saw stock trl.SFTTrainer and every construction test failed with "SFT patch did not apply". Request the codegen swap and the __init__ wrapper explicitly, in _gpu_init's order.
|
The red The failure is in main's own rapid-submit step: That step submits, waits a fixed 100 ms, submits again, and then requires the queued-prompt control to appear. Nothing holds the first turn open, so on a fast local GGUF the first turn can finish inside that window, no queue ever forms, and the assertion times out on an application that behaved correctly. #7972 replaces the fixed delay with a held first turn, so the follow-up is provably sent while a turn is in flight. Once that lands this job stops being a coin flip here. |
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2fa2b411a9
ℹ️ 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 "seq_lengths" in names: | ||
| return _mark_capped(dataset, cap, drop_unsupervised) |
There was a problem hiding this comment.
Reject overlength late packed splits instead of marking them capped
When a dataset supplied later to evaluate(), predict(), or a dataloader builder contains seq_lengths, this branch returns it unchanged and records it as capped even if input_ids exceeds the requested cap. These late splits never pass through TRL's packing/preparation step, and the constructor may already have cleared args.max_length, so the oversized row reaches the collator/model with no cap enforcement. Either truncate while updating seq_lengths consistently or reject the overlength split rather than marking it capped.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
seq_lengths is produced only by TRL's pack_dataset, which chunks to exactly max_length, so an overlength packed late split means the caller packed at a larger cap than the trainer's. Neither alternative is better than leaving it. Truncating hits exactly what the comment above this branch describes: a stale seq_lengths makes padding-free build position ids for tokens the row no longer has. Rejecting turns a working eval into a hard error. Leaving the split alone is the same refusal the construction-time path already makes for this shape.
| kept = new.filter( | ||
| lambda e, c = tuple(supervision): any( | ||
| all((x != -100) if n == "labels" else x for n, x in zip(c, v)) | ||
| for v in zip(*[e[n] for n in c]) | ||
| ) |
There was a problem hiding this comment.
Ignore hidden supervision columns when filtering late splits
When a Hugging Face dataset uses set_format(columns=["input_ids"], output_all_columns=False) but its backing table still contains labels or a mask, _column_names includes that hidden backing column and this filter attempts to read it from each formatted example. The resulting missing-key error is caught by _cap's broad exception handler, which returns the original dataset and discards the successful input_ids truncation, allowing overlength late eval or prediction rows through unchanged. Determine supervision from columns actually yielded by the formatted split, or make this filter tolerate absent fields without abandoning the cap.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Dataset.filter and Dataset.map read the backing Arrow table, not the formatted view, so reading labels under set_format(columns=["input_ids"], output_all_columns=False) does not raise. Verified on datasets 4.4.1 and 5.0.1, in both the default and torch formats: the filter runs and keeps the right rows. There is no missing-key error here, so the input_ids truncation is never discarded.
| if (kind or getattr(dataset, "_format_type", None)) == "custom": | ||
| return None | ||
| except Exception: | ||
| return None | ||
| return getattr(dataset, "_fingerprint", None) |
There was a problem hiding this comment.
Include dataset read formats in the eval-cap cache token
For Hugging Face datasets, changing set_format(...) alters the columns and value types yielded at read time without changing the backing Arrow data or its _fingerprint. Because non-custom formats use only that fingerprint here, reevaluating the same object after changing its format reuses the capped copy created under the old format; the trainer can therefore evaluate stale columns, labels, or tensor representations rather than the dataset view the caller just selected. Include the effective format configuration in the mutation/memo token, or avoid memoizing datasets whose read format can change independently of the fingerprint.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Dataset.set_format is decorated with @fingerprint_transform, so _fingerprint does move on every format change. Measured on datasets 4.4.1 and 5.0.1: base, columns-only, torch, numpy and reset each produce a distinct fingerprint. The memo token already invalidates on a format change, so there is no stale capped copy to serve.
TRL 1.7.0 gave SFTTrainer its own `evaluate`, which prepares a split passed straight to it and packs it under `packing = args.packing if args.eval_packing is None else args.eval_packing`. The late cap assumed the opposite -- that nothing TRL owns ever runs on a late split -- so on 1.7.0 and newer it cut each row at the cap before the packer could redistribute the overflow. `_trl_prepares_late_evals` reads that off the class rather than off a version number, and `packs_late` is passed per entry point because `predict` and the two dataloader builders stay the base Trainer's on every TRL. It joins the memo key, since `evaluate` and `get_eval_dataloader` see the same object in one call and only the first may skip the cut. A split the supervision filter emptied now says so. Every TRL 1.x reads `next(iter(train_dataset))` in `__init__` to resolve `completion_only_loss` and `_is_vision_dataset`, so an emptied split came back out as a bare `StopIteration` naming nothing the caller could act on. The tests that asserted the old premise are rewritten to cover both sides of 1.7.0 with stub trainers, so they pin the wrapper's logic rather than whichever TRL is installed, and the version fact is pinned separately. Three more expected a transformed or unprobeable overlength split to construct quietly; that shape keeps `max_length` and reports the rows instead, which is the behaviour the block already had, so they now assert the report and a within-cap companion shows it is about the rows and not the transform. 147 tests pass on trl 0.24.0, 1.0.0, 1.5.1, 1.6.0, 1.7.0, 1.8.0 and 1.9.2.
Review notes, plus a real defect this round foundBefore the PR
After the PROn a TRL that carries the guard, padding-free keeps Real or theoreticalReal, and it is the default path: essentially every SFT run leaves The defect I found this roundThe 7 open items were all rejected on evidence (below), but re-running the PR's own suite against the TRL versions it is about turned up something the review had not raised. The suite was passing because CI never reaches it. The Repo tests job installs trl 0.24.0, which predates the guard, so the Two were genuine code bugs: 1. TRL 1.7.0 moved who owns a late eval split. I pulled every TRL wheel from 0.22.2 to 1.9.2 and read packing = self.args.packing if self.args.eval_packing is None else self.args.eval_packingand the 2. An emptied split left The remaining four were stale tests, rewritten rather than "fixed": the eval-packing test asserted the pre-1.7.0 premise as a hard fact, and three expected a transformed or unprobeable overlength split to construct quietly when the block deliberately keeps Verified
Both new behaviours are pinned by discriminating tests: removing the If merged, what could it breakThe new branch is reached only when Cross-platform CI on a staging repo is green on Linux, macOS and Windows (UI, API, GGUF and Mac Studio jobs). The one red job is Triage of the 7 open itemsAll seven rejected, each against something I could run rather than argue:
|
|
@codex review |
1 similar comment
|
@codex review |
|
@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: 73a3661085
ℹ️ 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".
| # see the same object in one call, but only the first may skip the cut | ||
| # under `eval_packing`, so without this the second reused the first's | ||
| # answer. | ||
| packs_late, |
There was a problem hiding this comment.
Include eval-packing state in the cap memo key
For TRL versions whose evaluate() prepares late splits, packs_late remains true whether args.eval_packing is enabled or disabled, so this key does not distinguish those two outcomes. If a caller evaluates a fingerprinted split with eval packing enabled and then disables it, the memo returns the previously untouched split instead of invoking _cap() to truncate it, allowing overlength rows through now that no packer owns them. Add the resolved _eval_packing_on(trainer.args) value to the cache identity.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The memo key already separates those two outcomes, and the suggested change is a measured no-op.
Instrumented the unmodified head through the exact sequence (evaluate with eval packing on, then again with it off, same fingerprinted split):
memo keys after both calls: [(id, True, 'keep_start', True), (id, True, 'keep_start', False)]
Two distinct entries already, because the key carries the resolved drop/keep state. The thing that actually survives between the calls is the attribute mark on the dataset, and _cap short-circuits on _cap_still_holds at rl.py:1099 before the memo is ever consulted. Applying the suggested key change literally and rerunning:
1st evaluate (eval_packing=True): collator saw 40
2nd evaluate (eval_packing=False): collator saw 40, cap = 16 -> no change
With the mark removed, which is the fix for the sibling item on this round, the second evaluation caps correctly with the key untouched.
Separately, no code path writes args.eval_packing after construction: across trl 0.22.2 through 1.9.2 and transformers 4.57.6 it is only ever read, in SFTTrainer.__init__ and SFTTrainer.evaluate.
| not hasattr(dataset, "map") | ||
| or not hasattr(dataset, "filter") |
There was a problem hiding this comment.
Fall back to the read-side wrapper for non-HF map methods
A custom map-style dataset can legitimately expose methods named map and filter without implementing the Hugging Face Dataset.map/filter API. This presence-only check routes such a split into dataset.map(_slice_row) instead of _CappedRows; an incompatible signature or return type then reaches the broad exception handler and silently returns the original overlength split. Identify actual Hugging Face datasets here, or fall back to the read-side wrapper when these calls are unsupported.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This hardens against an input the path does not receive.
Walked every dataset type that can legitimately be a Trainer eval split:
datasets.Dataset/IterableDataset/DatasetDict: HF-compatiblemap/filter, map path, correct.with_transformdatasets: caught by thetransform == "custom"arm already in the condition. TRL refuses these too.torch.utils.data.Dataset/IterableDataset, plain lists: nomap/filter, so_CappedRows/_CappedStream, correct.pandas.DataFrame, the one real type withmapandfiltermeaning something else, never reaches this branch:_column_namesiterates it to column-name strings, the probed row is not a dict,input_idsis not among the names, and_capreturns at rl.py:1102. Verified, not assumed.
The only way I could produce the described behaviour was a class written for the purpose. And the outcome there is the split returned untouched, which is the pre-PR behaviour, not wrong data reaching the model.
Adding an isinstance(dataset, datasets.Dataset) gate would also cost an import of datasets on a path that deliberately avoids one.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
|
Live evidence from a notebook run, in case it is useful here.
Same notebook, same backend, unsloth pinned to this branch: PASS, loss 1.045 -> 1.050 over 7 steps. So this is not only a unit-level fix; it is what stands between that notebook and running at all on current TRL. |
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! 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". |
Bug
SFTTrainer(...)fails to construct on every TRL >= 1.0.0:Both halves of the trip are ours:
unsloth/trainer.pyauto-enables padding-free whenever the user leavespadding_freeat itsNonedefault, which is essentially every SFT run.max_length_checkcodegen inunsloth/models/rl.pyunconditionally writesargs.max_lengthfrommax_seq_length(or the model, or 1024), somax_lengthis neverNoneby the time TRL checks.except ValueErrorrecovery inunsloth/trainer.pyonly backs off packing, so the error propagates.Passing
padding_free=Falseexplicitly trains to completion, which isolates the interaction.Reproduction
Before, on trl 1.9.2 / 1.5.1 / 1.0.0:
After:
Fix
unsloth/models/rl.py: when the TRL being compiled carries the guard, and padding-free is on with packing off, hand TRL themax_length=Noneit asks for and keep the truncation length inmax_seq_length. That is where Unsloth's own dataset prep truncates, so nothing is lost: TRL already passesmax_length=Noneto its collator under padding-free, so it was never going to enforce the value anyway. The block is emitted only when the guard text is present in the TRL source, so TRL < 1.0.0 receives exactly the sameargsas before.On an explicit user
max_length, the choice was to keep padding-free and honour the length, not to drop one of them. The length is enforced during dataset preparation at exactly the requested value (clamped to the model's own maximum), and a one-line notice is printed when it differs from the length that was otherwise resolved. Turning padding-free off instead would cost the default speedup for any user who names amax_length, and silently ignoring the value is the outcome worth avoiding; this way the user keeps both. A value equal to the config dataclass default is treated as not user-supplied.unsloth/models/rl_replacements.py: the Zoo seeds its truncation length withgetattr(args, "max_length", 0)and only falls through tomax_seq_lengthwhen that is0, so aNonewould skip the fall-through and leave the length unset. Normalised withor 0, through the existing_replace_or_fallbackanchor pattern.unsloth/trainer.py: widened the construction recovery so an auto-enabled padding-free also backs off on this error, mirroring the existing auto-packing back-off. It is a net for a TRL that words the guard differently; with the codegen fix in place it does not fire.Verified
Construction plus dataset truncation, on CPU, with each TRL installed via
--no-deps --target:max_length=128max_length=128max_length=128max_length=128max_length=128max_length=128max_length=None, truncated at 128max_length=None, truncated at 128max_length=None, truncated at 128max_length=None, truncated at 128With an explicit
max_length=64on TRL 1.x the dataset comes out truncated at 64, andtrainer.train()runs to completion on 1.9.2.packing=Trueandpadding_free=Falseruns keepmax_lengthuntouched on every version.Tests
tests/version_compat/test_trl_padding_free_max_length.pybuilds the patched SFTTrainer on CPU and branches its assertions on whether the installed TRL carries the guard, so the one file pins the new behaviour on TRL >= 1.0.0 and the untouched behaviour on TRL < 1.0.0: default construction no longer raises, an explicitmax_lengthis truncated to,padding_free=Falseandpacking=Truekeepmax_length, the codegen gate is present, and the error matcher is exact. 8 passed on each of 0.22.2, 0.25.1, 0.29.1, 1.0.0, 1.5.1 and 1.9.2.