Skip to content

Stop a comment in unsloth_zoo from silently disabling the patched SFT trainer - #10854

Merged
danielhanchen merged 2 commits into
mainfrom
fix-sft-anchor-comment-drift
Sep 13, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
fix-sft-anchor-comment-drift

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

On current main against current unsloth_zoo, import unsloth prints:

Could not build the patched trl.trainer.sft_trainer, so training will use trl's
own trainer instead: RuntimeError: Unsloth: source anchor not found
(sft_prepare_dataset pack_dataset call); the patched function is out of sync
with this TRL / unsloth_zoo version. Please file a bug report.

Every SFT run then quietly uses TRL's own trainer, losing the packing and truncation fixes rl_replacements.py exists to apply. It is a warning, not an error, so a run looks normal.

Cause

Nothing in the Zoo's code moved. unsloth-zoo #1192 added a # noqa: F821 to the pack_dataset( call while building an undefined-name lint gate, and our literal anchor stopped matching a line that had only grown a comment:

repo's literal anchor present in zoo source? -> False
anchor + the zoo's trailing comment present?  -> True

The # noqa is correct on its own terms. pack_dataset really is an undefined name at that point, reached only past a bare-name probe, and the Zoo has no way to know this file string-matches its source. The brittleness is ours.

It is also not a one-off risk. We edit comments in bulk (#10504 "Reduce comment volume", #10116 "Trim comments"), so an anchored line gaining or losing a comment is routine drift, and today it silently disables a load-bearing patch.

Fix

_require_replace tries the literal anchor first, then the same anchor with an optional trailing comment allowed on each line. The only drift that still raises is drift in the code itself.

The literal branch is untouched and tried first, so any Zoo that matched before takes the identical path and produces identical output. Fixing the shared helper covers all five _require_replace call sites rather than just the pack_dataset one.

Checks

Against the 12 most recent unsloth_zoo revisions of dataset_utils.py, 2026-07-01 through 2026-09-12:

zoo rev date literal matches tolerant matches result
93aaae7 2026-09-12 no yes patch applied
7c9a7ac 2026-08-12 yes yes patch applied
94b8860 2026-08-09 yes yes patch applied
4096342 2026-08-08 yes yes patch applied
f2f5531 2026-08-05 yes yes patch applied
17e76fd 2026-08-05 yes yes patch applied
8fd68b1 2026-08-04 yes yes patch applied
9411f77 2026-08-04 yes yes patch applied
4d140e0 2026-07-30 yes yes patch applied
d9298b2 2026-07-11 yes yes patch applied
7f4c6be 2026-07-03 yes yes patch applied
d4440e6 2026-07-01 yes yes patch applied

Only #1192 needs the tolerant form. The 11 older ones still match literally, which is the backwards-compatibility claim stated as a measurement rather than an argument.

The change is pure string matching over the Zoo's own source, so it touches no torch, TRL, transformers or PEFT API surface and carries no version sensitivity of its own.

The new test covers the exact shape that broke, a comment on an inner anchored line, a # inside a string literal (not a comment, so it must still match exactly), and asserts the tolerance does NOT reach across a real code change. tests/utils/test_packing.py and tests/utils/test_dataset_num_proc.py, which already cover these anchor helpers, pass together: 169 passed.

Suite effect, pytest tests/ -n 64: 30 failures to 16. The 16 that go away all trace to this one anchor:

  • tests/utils/test_packing.py 5 to 0
  • tests/version_compat/test_trl_padding_free_max_length.py 9 to 1 (the last one is datasets importing VideoReader, removed in torchvision 0.28, unrelated)
  • tests/version_compat/test_trl_grpo_fake_run.py 1 to 0
  • tests/version_compat/test_trl_fake_train_cpu.py 1 to 0
  • tests/python/test_rl_config_pickling.py 1 to 0

The remaining 16 are separate and not addressed here: 7 pass in isolation and only fail under -n 64 (GPU contention), 2 are tests asserting on process-global sys.modules, 1 is unsloth_zoo/vllm_utils.py hard-importing a module path vllm 0.29 removed, and the rest are environment (transformers 5.17.0 against our <=5.5.0 pin, Triton without sm_100 kernels on this box, torchcodec build variants, an HTTP 401).

… trainer

`import unsloth` against current unsloth_zoo prints:

    Could not build the patched trl.trainer.sft_trainer, so training will
    use trl's own trainer instead: Unsloth: source anchor not found
    (sft_prepare_dataset pack_dataset call)

and every SFT run then falls back to TRL's own trainer, losing the packing
and truncation fixes rl_replacements exists to apply. Nothing in the Zoo's
code moved. unsloth-zoo #1192 put a `# noqa: F821` on the `pack_dataset(`
call while building an undefined-name lint gate, and the literal anchor
here stopped matching a line that had only grown a comment:

    repo's literal anchor present in zoo source? -> False
    anchor + the zoo's trailing comment present?  -> True

The `# noqa` is correct on its own terms: `pack_dataset` really is an
undefined name at that point, reached only past a bare-name probe, and the
Zoo has no way to know this file string-matches its source. The brittleness
is ours, and it is not a one-off risk: this repo edits comments in bulk
(#10504, #10116), so an anchored line growing or losing a comment is
routine drift.

_require_replace now tries the literal anchor first and a form of the same
anchor that allows an optional trailing comment per line second, so the
only drift that still raises is drift in the code itself. The literal
branch is untouched, so any Zoo that matched before takes the identical
path and produces identical output.

Checked against the 12 most recent unsloth_zoo revisions of
dataset_utils.py (2026-07-01 through 2026-09-12): the literal anchor still
matches on the 11 older ones, only #1192 needs the tolerant form, and the
patch applies on all 12.

Fixing the shared helper covers all five _require_replace call sites, not
just the pack_dataset one.

Test covers the exact shape that broke, a comment on an inner anchored
line, a `#` inside a string literal (not a comment, must still match), and
asserts the tolerance does NOT reach across a real code change.

Without this, of 30 failures in `pytest tests/ -n 64`, 16 trace back here:
tests/utils/test_packing.py 5 -> 0, version_compat/test_trl_padding_free
9 -> 1, plus test_trl_grpo_fake_run, test_trl_fake_train_cpu and
test_rl_config_pickling.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-13T07:29:03.943508Z f2c77e8 PR opened
🔒 Security Review ✅ Completed 2026-09-13T07:31:41.638878Z f2c77e8 PR opened
ℹ️ About Codex in GitHub

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

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

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

@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: f2c77e84dc

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +497 to +498
if old in function:
return function.replace(old, new, count)

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 Apply tolerant matching after partial literal matches

When an anchor is expected multiple times and upstream adds a comment to only one occurrence, old in function remains true, so this branch returns after replacing only the unchanged occurrence and never tries the tolerant pattern. The existing count = 2 call for the two sft_prepare_dataset tokenizing map blocks is affected: one block can silently miss _unsloth_map_diagnostics, leaving worker failures on that path with the opaque original error. Apply the tolerant matcher to the remaining requested occurrences after literal replacements rather than returning immediately.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen merged commit 89a10db into main Sep 13, 2026
27 checks passed
@danielhanchen
danielhanchen deleted the fix-sft-anchor-comment-drift branch September 13, 2026 07:34
danielhanchen added a commit that referenced this pull request Sep 13, 2026
…it falls back (#10862)

Repo tests (CPU) carried timeout-minutes: 30 under a comment claiming the job
measured 13.4 minutes. Across the last 40 runs of it on main the pytest step
alone measures 852s to 1683s, and the install plus the four steps after it add
a further 351s, so the worst measured run needs 33.9 minutes. Run 0eedeee
passed at 1738s, 62 seconds under the cap.

Which run loses is a property of the runner, not of the PR. #10849 and #10861
were both cancelled at 30m1x against a green main, on branches that touch none
of this.

The cap also fires mid-step, so the run blames whichever step was unlucky. On
both of those it was "Shell installer tests", 84s in and unrelated, and the
shell, CLI and Docker steps never ran at all, so those PRs silently lost that
coverage too.

Raised to 45, which is what the backend pytest job in this same file already
uses after the identical failure mode. A backstop is only worth raising if
something below it can still name a hang, so this picks up that job's other two
guards, with numbers measured from this suite rather than copied: --timeout=330
against a tail of 63.6s, 48.3s and a run of ~31s cases (this step is ~2.2x
slower on a 4-vCPU runner than on the box that measured them, so the worst
legitimate test is ~140s and the cap is ~2.4x that), and an outer
timeout --signal=INT --kill-after=60 2100, which is 1.25x the worst of the 40
runs and still lands 4 minutes under the job cap.

Separately, tests/utils/test_packing.py now routes its three unbound
_prepare_dataset tests through _fake_sft_self(). They pass a SimpleNamespace as
self, which is fine against the patched implementation (it reads data_collator
and nothing else) and is not fine against TRL's own, which reaches for
self._is_vlm. So when the SFT patch silently falls back, as it did between
unsloth-zoo #1192 and #10854, all four report

    AttributeError: 'types.SimpleNamespace' object has no attribute '_is_vlm'

which names the fake object and not the patcher. Those four were the loudest of
16 failures across five files that all had the one cause. They now assert the
patch applied first and say so.

Padding the namespace out with _is_vlm would be worse than the AttributeError:
the tests would then quietly pass against TRL's trainer and assert nothing
about Unsloth's.

Checked both directions. On main tests/utils/test_packing.py is 62 passed, 2
skipped. Against fc66948, the commit before #10854, the same four fail with
"trl.SFTTrainer is 'SFTTrainer', so Unsloth's SFT patch did not apply". The
--timeout=330 flag was run over the five slowest files in the discovered set:
143 passed, no spurious kills, including the tests that deliberately hang.
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.

1 participant