Skip to content

Stop padding-free SFT from tripping the TRL >= 1.0.0 max_length guard - #7951

Merged
danielhanchen merged 74 commits into
unslothai:mainfrom
danielhanchen:fix-padding-free-max-length
Aug 9, 2026
Merged

danielhanchen merged 74 commits into
unslothai:mainfrom
danielhanchen:fix-padding-free-max-length

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Bug

SFTTrainer(...) fails to construct on every TRL >= 1.0.0:

File ".../unsloth_compiled_cache/UnslothSFTTrainer.py", line 1310, in __init__
    raise ValueError(...)
ValueError: When `padding_free=True` without packing, `max_length` is not enforced. Either enable
packing (e.g., `packing=True, packing_strategy='bfd'`), provide already truncated inputs, or set
`max_length=None`.

Both halves of the trip are ours:

  • unsloth/trainer.py auto-enables padding-free whenever the user leaves padding_free at its None default, which is essentially every SFT run.
  • The max_length_check codegen in unsloth/models/rl.py unconditionally writes args.max_length from max_seq_length (or the model, or 1024), so max_length is never None by the time TRL checks.
  • TRL added that guard in 1.0.0; it is absent in 0.25.1 and 0.29.1. The existing except ValueError recovery in unsloth/trainer.py only backs off packing, so the error propagates.

Passing padding_free=False explicitly trains to completion, which isolates the interaction.

Reproduction

import unsloth
from trl import SFTConfig, SFTTrainer
from transformers import AutoModelForCausalLM, AutoTokenizer
from datasets import Dataset

m = "hf-internal-testing/tiny-random-LlamaForCausalLM"
tok = AutoTokenizer.from_pretrained(m); tok.pad_token = tok.pad_token or tok.eos_token
model = AutoModelForCausalLM.from_pretrained(m); model.max_seq_length = 128
ds = Dataset.from_dict({"text": ["hello world " * 200] * 8})

args = SFTConfig(output_dir="out", max_steps=1, per_device_train_batch_size=2, use_cpu=True)
SFTTrainer(model=model, args=args, train_dataset=ds, processing_class=tok)   # ValueError

Before, on trl 1.9.2 / 1.5.1 / 1.0.0:

RESULT: FAIL ValueError When `padding_free=True` without packing, `max_length` is not enforced. ...

After:

RESULT: OK padding_free=True packing=False max_length=None max_seq_length=128 longest_input_ids=128

Fix

unsloth/models/rl.py: when the TRL being compiled carries the guard, and padding-free is on with packing off, hand TRL the max_length=None it asks for and keep the truncation length in max_seq_length. That is where Unsloth's own dataset prep truncates, so nothing is lost: TRL already passes max_length=None to 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 same args as 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 a max_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 with getattr(args, "max_length", 0) and only falls through to max_seq_length when that is 0, so a None would skip the fall-through and leave the length unset. Normalised with or 0, through the existing _replace_or_fallback anchor 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:

trl transformers before after
0.22.2 4.57.6 ok, max_length=128 unchanged, max_length=128
0.25.1 4.57.6 ok, max_length=128 unchanged, max_length=128
0.29.1 5.14.1 ok, max_length=128 unchanged, max_length=128
1.0.0 5.14.1 ValueError ok, max_length=None, truncated at 128
1.5.1 5.14.1 ValueError ok, max_length=None, truncated at 128
1.9.2 4.57.6 ValueError ok, max_length=None, truncated at 128
1.9.2 5.14.1 ValueError ok, max_length=None, truncated at 128

With an explicit max_length=64 on TRL 1.x the dataset comes out truncated at 64, and trainer.train() runs to completion on 1.9.2. packing=True and padding_free=False runs keep max_length untouched on every version.

Tests

tests/version_compat/test_trl_padding_free_max_length.py builds 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 explicit max_length is truncated to, padding_free=False and packing=True keep max_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.

@danielhanchen
danielhanchen requested a review from Datta0 as a code owner August 5, 2026 17:05
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 5, 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: 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".

Comment thread unsloth/models/rl.py Outdated
Comment on lines +1223 to +1225
" 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"

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 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 👍 / 👎.

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.

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.

Comment thread unsloth/models/rl.py Outdated
" except Exception:\n"
" pass\n"
" try:\n"
" _unsloth_columns = getattr(train_dataset, 'column_names', None)\n"

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 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 👍 / 👎.

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.

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.

Comment thread unsloth/models/rl.py
" 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"

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 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 👍 / 👎.

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.

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.

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 6, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 6, 2026
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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

The red Chat UI Tests job here is not this PR. This PR changes unsloth/models/rl.py, rl_replacements.py, unsloth/trainer.py and one version-compat test; it touches nothing under studio/ or tests/studio/.

The failure is in main's own rapid-submit step:

[ui] STEP rapid submit: 100 ms follow-up queues behind the first turn
TimeoutError: Page.wait_for_selector: Timeout 10000ms exceeded.
  - waiting for locator("button[aria-label=\"Remove queued prompt 1\"]")

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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 6, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 2a473c6cfe

ℹ️ 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[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026

@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: 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".

Comment thread unsloth/models/rl.py
Comment on lines +1080 to +1081
if "seq_lengths" in names:
return _mark_capped(dataset, cap, drop_unsupervised)

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 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 👍 / 👎.

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.

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.

Comment thread unsloth/models/rl.py
Comment on lines +1186 to +1190
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])
)

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 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 👍 / 👎.

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.

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.

Comment thread unsloth/models/rl.py
Comment on lines +846 to +850
if (kind or getattr(dataset, "_format_type", None)) == "custom":
return None
except Exception:
return None
return getattr(dataset, "_fingerprint", None)

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 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 👍 / 👎.

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.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

Review notes, plus a real defect this round found

Before the PR

SFTTrainer(...) failed to construct on every TRL >= 1.0.0, because both halves of the trip are ours: unsloth/trainer.py auto-enables padding-free whenever padding_free is left at its None default, and the max_length_check codegen always wrote args.max_length, so TRL's 1.0.0 guard fired:

ValueError: When `padding_free=True` without packing, `max_length` is not enforced. Either enable
packing (e.g., `packing=True, packing_strategy='bfd'`), provide already truncated inputs, or set
`max_length=None`.

After the PR

On a TRL that carries the guard, padding-free keeps max_length = None and the truncation length moves to max_seq_length, where Unsloth's own dataset prep enforces it. TRL < 1.0.0 receives exactly the same args as before, because the block is emitted only when the guard text is present in the TRL source.

Real or theoretical

Real, and it is the default path: essentially every SFT run leaves padding_free at None.

The defect I found this round

The 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 trl_has_guard fixture skips 26 of these tests. Install a TRL that actually has the guard and 5 of them fail; on TRL >= 1.7.0 a 6th does. That is the whole point of the PR going untested.

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 sft_trainer.py directly: SFTTrainer.evaluate does not exist up to 1.6.0 and appears in 1.7.0, where it calls _prepare_dataset with

packing = self.args.packing if self.args.eval_packing is None else self.args.eval_packing

and the if packing: block sits at the same indentation as if not is_processed:, so a pre-tokenized split gets packed too. TRL's "skips datasets that are already tokenized" comment covers the formatting and tokenizing steps only, not truncation or packing. So from 1.7.0 the packer really does own a split handed to evaluate(), and the late cap was cutting each row at the cap first, discarding the overflow wrapped and bfd_split exist to redistribute. _trl_prepares_late_evals now reads that off the class instead of a version number, and packs_late is passed per entry point because predict and both dataloader builders stay the base Trainer's on every TRL. It also joins the memo key: evaluate and get_eval_dataloader see the same object within one call and only the first may skip the cut.

2. An emptied split left __init__ as a bare StopIteration. When the cap sits below where the supervision starts, the filter drops every row. Every TRL 1.x then reads next(iter(train_dataset)) in __init__ to resolve completion_only_loss and _is_vision_dataset (AST-checked: unconditional in 1.0.0, 1.4.0, 1.5.1, 1.6.0, 1.7.0 and 1.9.2), so the user got a StopIteration naming nothing. It now says which knob to turn.

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 max_length and reports the rows instead.

Verified

147 passed on trl 0.24.0, 1.0.0, 1.5.1, 1.6.0, 1.7.0, 1.8.0 and 1.9.2 (transformers 5.14.1, datasets 5.0.1, CPU), each in a clean venv with the compiled cache dropped between versions so the generated module is regenerated, not reused. On 0.24.0 it is 121 passed, 26 skipped, which is what CI has been seeing.

Both new behaviours are pinned by discriminating tests: removing the packs_late gate turns test_eval_packing_on_a_late_split_follows_whether_trl_packs_it red on its own, and removing the emptied-split raise turns test_a_cap_below_all_supervision_is_a_clear_error red on its own. The eval-packing test drives stub trainers for both sides of 1.7.0, so it pins the wrapper's logic rather than whichever TRL is installed, and the version fact is pinned separately against trl.__version__.

If merged, what could it break

The new branch is reached only when evaluate is handed a split and TRL's own evaluate prepares it and packing is on for evals. predict, get_eval_dataloader and get_test_dataloader pass packs_late=False unconditionally, so every path that worked before is untouched, and on any TRL below 1.7.0 the probe answers False and the behaviour is identical to the previous commit. _eval_packing_on is deliberately the same expression as the generated block's _unsloth_eval_packing, so the late cap and the construction-time cap cannot drift apart. No public symbol moves, so older unsloth_zoo and existing Unsloth Studio installs are unaffected.

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 Repo tests (CPU), failing 5 tests in tests/studio/install/test_install_llama_prebuilt_logic.py and one chat-runtime TS assertion, none of which this PR touches.

Triage of the 7 open items

All seven rejected, each against something I could run rather than argue:

item why
Include dataset read formats in the cache token Dataset.set_format is @fingerprint_transform-decorated, so _fingerprint does move. Distinct on base, columns-only, torch, numpy and reset, on datasets 4.4.1 and 5.0.1.
Ignore hidden supervision columns when filtering filter and map read the backing Arrow table, not the formatted view, so reading a hidden labels under set_format(columns=["input_ids"]) does not raise. datasets 4.4.1 and 5.0.1, plain and torch.
Key cached caps by the supervision mode self.completion_only_loss is assigned only in __init__, AST-checked on 1.7.0 and 1.9.2. It cannot change between two evaluate() calls.
Evict persistent dataloaders when swapping splits Upstream. Trainer.get_eval_dataloader returns the cached loader before it looks at its argument under dataloader_persistent_workers. Reproduced with a bare transformers.Trainer, no unsloth involved.
Truncate channel-major position IDs TRL hard-codes signature columns to ["input_ids", "labels", "seq_lengths"] and remove_unused_columns defaults True, so a dataset position_ids is dropped before any collator sees it.
Reject overlength late packed splits seq_lengths only comes from pack_dataset, which chunks to exactly max_length. Truncating hits the stale-seq_lengths problem the comment describes; raising turns a working eval into a crash.
Preserve streams whose iterators wrap shared state Reproduced the row loss, but both proposed remedies cost more: replaying the probed row duplicates the first row for every restartable custom stream and leaves a one-shot chain, so a second eval pass yields nothing.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 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".

Comment thread unsloth/models/rl.py
# 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,

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 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 👍 / 👎.

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.

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.

Comment thread unsloth/models/rl.py
Comment on lines +1183 to +1184
not hasattr(dataset, "map")
or not hasattr(dataset, "filter")

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 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 👍 / 👎.

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.

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-compatible map/filter, map path, correct.
  • with_transform datasets: caught by the transform == "custom" arm already in the condition. TRL refuses these too.
  • torch.utils.data.Dataset / IterableDataset, plain lists: no map/filter, so _CappedRows / _CappedStream, correct.
  • pandas.DataFrame, the one real type with map and filter meaning something else, never reaches this branch: _column_names iterates it to column-name strings, the probed row is not a dict, input_ids is not among the names, and _cap returns 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 6a7d6c8c6d

ℹ️ 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

Live evidence from a notebook run, in case it is useful here.

nb/Liquid_LFM2-Conversational.ipynb on a Kaggle T4, with trl 1.9.2 installed, fails against unsloth main with exactly this guard:

When `padding_free=True` without packing, `max_length` is not enforced. Either
enable packing (e.g., `packing=True, packing_strategy='bfd'`), provide already
truncated inputs, or set `max_length=None`

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: e84618449e

ℹ️ 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".

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.

2 participants