Repository navigation
Keep up with transformers 5.x, TRL 0.22.x and peft - #7866
danielhanchen merged 20 commits into
Conversation
|
Follow-up on the overlap note in the description: I checked it rather than leaving it as a guess. This branch and #7854 both touch All six of my open unsloth branches stack onto |
Five compatibility failures, each of which stopped a load or a run outright.
transformers 5.x turns PretrainedConfig subclasses into dataclasses. vLLM's
transformers_utils/configs/deepseek_vl2.py declares
vision_config: VisionEncoderConfig
with no default, and a dataclass will not accept a non-default field after an
inherited default one:
TypeError: non-default argument 'vision_config' follows default argument
That fires while importing vllm.transformers_utils.configs, which takes down
import vllm and, because unsloth imports vLLM, import unsloth as well. Seen in
the wild as unsloth: "ABSENT: TypeError".
PretrainedConfig.__init_subclass__ is patched rather than vLLM's source, so it
covers every affected class in any vLLM version instead of one file, and the
original stays reachable through __wrapped__: an irreversible monkey patch
cannot be tested against the failure it fixes, and cannot be undone by anyone
debugging a config problem downstream of it.
The window is narrower than it first looked. transformers 5.6.0 started passing
kw_only=True to the dataclass, which removes the ordering rule entirely, so the
fix now stands down on 5.6.0+ rather than monkey patching every config subclass
for no benefit. Read from the source rather than pinned to a version, since the
change could be backported. Verified live on three transformers: 4.57.6 (no-op),
5.5.0 (failure reproduces, fix works), 5.14.1 (upstream handles it, fix stands
down).
offload_embedding = True raised NotImplementedError on a tied-embedding model.
It is a VRAM optimisation, not a correctness switch, and on a tied model
embed_tokens IS lm_head, so offloading strands the output projection on CPU and
frees nothing. Turned off with a message instead, the way fast_inference already
degrades. Resolved before _attach_bnb_multidevice_hooks, which returns early
while the flag is still True; resolving it later would silently skip hook
attachment for exactly these models. WSL and Windows pass through unchanged,
since the offload block skips those platforms and probing there would be a code
path that never used to run.
peft imports symbols transformers no longer ships. Backfilling whole missing
modules was not enough: transformers 5.0.0.dev0 has conversion_mapping but not
_MODEL_TO_CONVERSION_PATTERN, so individual names are backfilled rather than a
real module being replaced wholesale.
On TRL 0.22.x a VLM skips dataset preparation and picks the vision collator from
_is_vlm alone. Fine-tuning a VLM on a text-only dataset then reaches the trainer
with a raw text column and transformers strips everything:
ValueError: No columns in the dataset match the model's forward method
signature ... The following columns have been ignored: [text]
Magistral_(24B)-Reasoning-Conversational fails exactly this way; it pins
trl==0.22.2 and trains a VLM on a plain text dataset. TRL 0.25.1+ fixed this by
keying off _is_vision_dataset, so that is what gets back-ported, and it no-ops
where TRL already defines the flag.
49dca2c to
e26a817
Compare
…hen a peft stand-in is not equivalent
Four things, all narrowing rather than widening.
_backfill_dataclass_defaults decided "no default yet" with `name not in
cls.__dict__`, which is class-local. A config subclass that re-annotates an
inherited field without assigning to it already has a default, through the MRO,
and None overwrote it. Reproduced directly: a child re-annotating a parent field
whose default is 7 came back None. dataclass reads defaults with getattr, so
hasattr is the test that matches what dataclass will do.
_backfill_missing_peft_symbols installs inert donors: an empty conversion
pattern, mapping lookups that return None. That is the truth on transformers 4
and on a transformers 5 that never had the symbol, and it is not the truth for a
transformers 5 that has conversions and renamed one, where peft would silently
skip work. Checked every released wheel from 5.0.0 to 5.6.0: all eleven names
are present, so this only fires on a dev build. It now warns for anything beyond
the pattern rather than repairing the import in silence.
The live control test observed PretrainedConfig before anything had imported
unsloth, so run on its own it had nothing to unwrap and skipped itself instead
of proving the failure is real. It installs the patch first now.
find_spec imports the parent packages, so `find_spec("trl.trainer.sft_trainer")`
raises rather than returning None when trl is absent, and the skipif marker
failed collection instead of skipping.
Tests: 4384 passed against 4377 on the same tree with these changes stashed,
same 1310 environment failures either way (version_compat and vllm_compat fetch
upstream sources per tag; the GPUs here are busy), and zero failures present on
this branch that are not also on its base.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c97f062e5d
ℹ️ 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".
| 'args.dataset_kwargs.get("skip_prepare_dataset", False) or self._is_vlm', | ||
| 'args.dataset_kwargs.get("skip_prepare_dataset", False)' | ||
| " or (self._is_vlm and self._is_vision_dataset)", |
There was a problem hiding this comment.
Route VLM text preparation through the tokenizer
When this backport runs on TRL 0.22/0.23 with a VLM ProcessorMixin and a standard text-only dataset ({"text": ...}), this replacement makes skip_prepare_dataset false, so TRL's _prepare_dataset is called with the processor object. That path uses tokenizer-only attributes such as processing_class.eos_token while adding EOS, whereas VLM processors expose them on processing_class.tokenizer, so the load now fails with an AttributeError before tokenization instead of fixing the text-only path. Please route the text-only branch through the tokenizer, or proxy the tokenizer attrs, when enabling preparation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
TRL's _prepare_dataset never runs in the patched trainer, so processing_class.eos_token is not reached. rl_replacements.py:502 (sft_trainer_prepare_dataset) swaps the whole method for unsloth_zoo's sft_prepare_dataset, applied by the edit_functions loop at rl.py:2173, and that implementation starts with is_vlm = hasattr(processing_class, \"tokenizer\") / tokenizer = processing_class.tokenizer and tokenizes through the inner tokenizer. I ran the replacement over the real trl 0.22.2 and 0.23.0 sft_trainer.py sources: both are replaced, the output contains no processing_class.eos_token, and the signature regex matches on both versions. So enabling preparation is what makes the text-only VLM path work rather than breaking it.
Importing unsloth.import_fixes goes through unsloth/__init__.py, which reaches _gpu_init and pulls torch, numpy and unsloth_zoo: measured at 10.6s and 8288 modules. The helper under test is plain Python, and import_fixes.py has only stdlib plus packaging at module level, so the file-spec load the adjacent test_peft_symbol_backfill.py already uses works here too, at 0.01s with none of that stack resident. A dependency-light run failed before reaching the code under test; under a meta-path finder that raises on torch, numpy, unsloth_zoo, unsloth, transformers, peft and trl, the three tests now pass.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5ce9ef9eef
ℹ️ 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".
| # MUST be first: installs the PretrainedConfig guard before anything | ||
| # imports vLLM, whose config classes otherwise raise TypeError at | ||
| # import time under transformers 5.x and take `import unsloth` down. | ||
| fix_transformers5_bare_annotation_configs() |
There was a problem hiding this comment.
Install the config guard before probing vLLM
In environments with affected Transformers 5.x and vLLM installed, _gpu_init has already called disable_broken_vllm() above, and that probe does a bare import vllm, before this guard is installed. That first import can hit the same bare-annotation TypeError and be swallowed as a non-ABI vLLM failure, so the early vLLM probe runs without the promised guard and never re-runs its lazy compiled-extension checks after the guard is active. Move this call into the initial import_fixes block before disable_broken_vllm().
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The premise does not hold: vllm/init.py is lazy (MODULE_ATTRS plus getattr) at every tag from v0.11.2 to v0.19.1, so the eager closure of import vllm is vllm, env_override, envs, logger, utils.torch_utils, version. transformers_utils is never reached, confirmed live against the installed vllm 0.15.1 (configs imported? False). Even forcing the failure, _is_broken_vllm_error only matches undefined symbol / .so / cannot open shared object file, and the real text is non-default argument follows default argument, so VLLM_BROKEN is never set and the retry after the guard succeeds. The ordering comment at _gpu_init.py:202-204 is wrong though, and I will correct it.
| try: | ||
| return "kw_only=True" in inspect.getsource(hook) | ||
| except Exception: | ||
| return False |
There was a problem hiding this comment.
Fall back to the version when source is unavailable
When Transformers 5.6+ is installed from a source-stripped/frozen package where inspect.getsource() raises, this returns False and still applies the monkey patch even though upstream kw_only=True already removed the ordering failure. In that context _backfill_dataclass_defaults() changes genuinely required bare annotations into None defaults, so config classes can be created with missing required fields; use the known version window as the fallback instead of treating unreadable source as needing the patch.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The mechanism is real in isolation but the window is wrong, which makes the remedy worse than the bug. Reading the tags: kw_only=True landed in 5.5.1, not 5.6.0, and 5.0.0 to 5.3.0 have no init_subclass at all, so the true window is 5.4.0 to 5.5.0. Hardcoding the stated window would wrongly patch 5.5.1 through 5.14.1. Reading the source is what gets 5.5.1 right. The unreadable-source state is also unreachable: unsloth calls inspect.getsource unguarded on third-party classes in rl.py:988 and compiler.py:1393, so such an install cannot load a model at all.
Comment-only. Checked against the published wheels and the commits that introduced each change: - kw_only=True on config dataclasses landed in 5.5.1, not 5.6.0. It was backported: 5.5.1 on the 5.5 branch, 5.6.0 on main, both from transformers#45139. - The window needing the bare-annotation fix is 5.4.0 to 5.5.0. 5.0.0-5.3.0 have no PretrainedConfig.__init_subclass__ at all. - vllm/__init__.py is lazy at every tag from 0.11.2 on, so importing vllm never reaches transformers_utils.configs. The guard is still worth installing early, but not for the reason the comment gave. - _is_vision_dataset landed in TRL 0.24.0, not 0.25.1 (trl#4080). 0.24.0's sft_trainer.py line is byte-identical to 0.25.1's, which is what the backport's no-op guard matches on.
The previous commit corrected the comments but left this test asserting the probe returns False until 5.6.0, so it would fail on 5.5.1 through 5.5.4, which is exactly where the fix correctly stands down. Verified against the extracted wheels: 5.4.0 and 5.5.0 have no kw_only=True in configuration_utils.py, 5.5.1 and 5.6.0 both do.
A stripped or frozen install ships bytecode only, and inspect.getsource then raises. Answering False there patched a 5.5.1+ install that needs nothing, and since the backfill runs before the upstream hook, fields upstream means to be required keyword arguments would silently gain a None default. Falls back to 5.4.0 <= v < 5.5.1, the only window with the ordering rule and no kw_only=True. Half open so 5.5.0.post1 and other 5.5.0 rebuilds stay inside. Readable source still decides, since the backport means the version alone cannot see the truth. An unreadable or unparseable version stands down: without positive evidence the install needs the patch, the better failure is the loud TypeError the patch would have prevented, not a config that quietly accepts a missing required field. Uses packaging's Version directly rather than this module's wrapper, which raises on anything its regex misses and rewrites pre-release suffixes upwards, moving dev builds across the edge.
|
Codex Review: Didn't find any major issues. Swish! 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". |
pre-commit.ci's ruff-format-with-kwargs hook reported "files were modified by
this hook" and could not push the result back, so the check stayed red.
Applied locally instead.
Three source-asserting tests had to be made robust rather than re-pinned,
since the reformatting is legitimate and will happen again:
- test_the_flag_is_recorded_beside_the_dtype counted the literal
"self._autocast_enabled = (", which the formatter collapsed onto one line.
Now pairs each _autocast_dtype initialiser with a nearby flag assignment by
position, so it still catches a genuinely missing one.
- test_the_original_error_is_still_reported anchored on a whole f-string
literal, which the formatter merged with the hint that follows it. Anchors
on the message text alone now; either shape satisfies the intent.
- test_the_source_beats_the_version_fallback exposed a real fragility rather
than a test problem: the detector matched the literal "kw_only=True", so any
whitespace in transformers' own source would have read an install that needs
nothing as one that needs patching. Made whitespace-tolerant.
|
Codex Review: Didn't find any major issues. Nice work! 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". |
One conflict, in the swallow around the patched trl trainer build: main replaced the logger.info with a warning_once that names the consequence, which is the better message, so main's wording wins. Resolved that hunk alone rather than taking either whole file, so this branch's own rl.py changes survive.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 26d062150d
ℹ️ 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".
| import transformers | ||
| if Version(transformers.__version__) < Version("5.0.0"): | ||
| return | ||
| from transformers.configuration_utils import PretrainedConfig |
There was a problem hiding this comment.
Import the v5 config class before patching it
In Transformers 5.x the base config class was renamed to PreTrainedConfig (capital T), while the legacy PretrainedConfig name is not present in the 5.4/5.5 configuration_utils.py that this workaround targets. In an affected Transformers 5.4.0–5.5.0 environment this import raises, gets swallowed by the broad except, and the guard is never installed, so the vLLM bare-annotation config import still crashes exactly as before. Please fall back to PreTrainedConfig here before deciding to skip the patch.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Checked this against both versions in the window and the import does not raise, so I am not taking this one.
PreTrainedConfig is indeed the real class name from 5.x, but the legacy spelling is kept as a working alias, and the import in question resolves through it:
transformers 5.5.0
PretrainedConfig importable : True
PreTrainedConfig importable : True
class PreTrainedConfig in configuration_utils source : True
from transformers.configuration_utils import PretrainedConfig -> PreTrainedConfig
transformers 5.4.0
from transformers.configuration_utils import PretrainedConfig -> PreTrainedConfig
Both installed clean into a throwaway venv and imported directly. So on 5.4.0 and 5.5.0, the two ends of the window this patch targets, nothing is swallowed by the except and the guard is installed as intended.
The rename is real and worth knowing about, so if the alias is ever dropped this becomes correct. It is not correct today, and adding a fallback now would only add an unreachable branch.
`_transformers_needs_bare_annotation_fix` pinned the window to
`5.4.0 <= v < 5.5.1`. The rule arrived in 5.4.0 and `kw_only=True` retired it
in 5.5.1, but that landed as a backport on the 5.5 branch and on main
separately, so a version number mislabels any build that carries it early or
late, and says nothing about a future release that brings the rule back.
It now defines a throwaway subclass in exactly the shape vLLM uses, a default
followed by a bare annotation, and reports whether `__init_subclass__` raises.
Same answer on every version I checked, derived rather than tabulated:
4.57.6 False 5.4.0 True 5.5.1 False
5.3.0 False 5.5.0 True 5.6.0 False
The unreadable-source fallback keeps the same conservative default: without
positive evidence the install needs patching, answer False, since the better
failure is the loud TypeError the patch would have prevented rather than a
config that quietly accepts a missing required field.
The test that faked `transformers.__version__` to reach the fallback is
replaced. Faking a version deliberately no longer changes the answer, so that
is now asserted as the regression, alongside a test that a config whose
`__init_subclass__` raises is detected whatever it calls itself.
…nto pr/transformers5-and-trl-compat # Conflicts: # tests/test_dataclass_default_backfill.py # unsloth/import_fixes.py
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 959a608e86
ℹ️ 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".
| anchor, | ||
| anchor + " # Unsloth: back-port of TRL 0.24.0's dataset-based check, so a\n" | ||
| " # text-only fine-tune of a VLM is prepared and collated as text.\n" | ||
| ' self._is_vision_dataset = "image" in dataset_sample or "images" in dataset_sample\n', |
There was a problem hiding this comment.
Classify message-only VLM samples as vision data
When a TRL 0.22.x VLM SFT dataset is represented as chat messages containing media but has no top-level image/images key, this new gate is false, so the rewritten trainer now chooses the text collator and runs _prepare_dataset instead of keeping the previous vision path. That is a supported shape in this repo: _VISION_DATASET_KEYS includes video/videos and the video validation tests build samples as {"messages": [{... {"type": "video", "video": ...}}]} (unsloth/trainer.py:147-204, tests/test_video_path_validation.py:114-117). Please include those existing vision markers/message scans when backporting the dataset gate so actual vision/video datasets are not treated as text-only.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Checked this against the actual 0.22.x/0.23.x code and it does not hold.
On TRL 0.22.2 and 0.23.0 the "previous vision path" cannot process a message-only sample at all: DataCollatorForVisionLanguageModeling._collate_language_modeling starts with images = [example["images"] for example in examples] (0.22.2 sft_trainer.py:380, 0.23.0:387), an unconditional top-level lookup. Ran both shapes you cite through the real 0.22.2 collator with a Qwen2-VL processor:
PRE-PR VISION PATH FAILS: KeyError 'images'
VIDEO SHAPE FAILS: KeyError 'images'
The second is exactly {"messages": [{"role": "user", "content": [{"type": "video", "video": p}]}]} from test_video_path_validation.py. So the branch the gate diverts away from was already a hard KeyError for that shape, and there is nothing to preserve.
The gate is also upstream-faithful and version-scoped. TRL keys on the same two top-level names from 0.24.0 through 1.9.2 (self._is_vision_dataset = "image" in dataset_sample or "images" in dataset_sample), and the backport no-ops where TRL defines it. Running the patcher over four trees: 0.22.2 patched, 0.23.0 patched, 0.24.0 unpatched, 1.9.2 unpatched.
On _VISION_DATASET_KEYS: that helper keys on dataset.column_names, so a message-only dataset has the single column messages and is not vision there either. And the real vision/video flow passes UnslothVisionDataCollator, where rl.py already forces args.dataset_kwargs = {"skip_prepare_dataset": True} before init, so those datasets never reach _prepare_dataset regardless of this gate. test_video_path_validation.py exercises check_dataset_for_missing_videos, not the collator gate.
PR tests still green: 34 passed, 6 skipped.
|
Ran the full declared range in isolated venvs. The library code holds across all of it; one test had a wrong premise inside the range, fixed in Ten combinations, all on torch 2.9.1+cu128 (one torch satisfies every combination), Python 3.13:
The 4.57.6 rows skip the whole live file, correctly gated off on transformers 4.x. The bug. So Control: on origin/main in the same venv the whole file fails with Beyond the five test files: One thing this PR does not cover, worth a separate change. The runtime range works, but pip cannot install the top of it. Note also |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
…ral one unslothai#7866 landed a general peft-symbol backfill that covers the same two transformers submodules this branch does, and both are hasattr-gated, so whichever runs first decides what _MODEL_TO_CONVERSION_PATTERN IS. The general pass donates an inert {}, which answers every lookup with a silent None; this branch installs a map that refuses a fused-MoE lookup it cannot answer. With the general pass first the symbol is already present, this pass finds nothing missing, and a fused MoE adapter loads with its LoRA targets unconverted and no error. Keeping both: this one first for the MoE stand-in and because it re-passes (conversion_mapping imports from core_model_loading at its own module top, so one pass cannot fix an install carrying both drifts), then the general pass for anything the pair above does not name, which is a no-op wherever this one already ran. Two tests pin the order, verified by swapping the calls.
Five compatibility failures, each of which stopped a load or a run outright.
transformers 5.x broke vLLM's config classes at import
transformers 5.x turns
PretrainedConfigsubclasses into dataclasses. vLLM'stransformers_utils/configs/deepseek_vl2.pydeclaresvision_config: VisionEncoderConfigwith no default, and a dataclass will not accept a non-default field after an inherited default one:That fires while importing
vllm.transformers_utils.configs, which takes downimport vllmand, because unsloth imports vLLM,import unslothas well. It was seen in the wild asunsloth: "ABSENT: TypeError".PretrainedConfig.__init_subclass__is patched rather than vLLM's source, so it covers every affected class in any vLLM version instead of one file. The original stays reachable through__wrapped__, because an irreversible monkey patch cannot be tested against the failure it fixes, and cannot be undone by anyone debugging a config problem downstream of it.The window is narrower than it first looked, and this is worth knowing. transformers 5.6.0 started passing
kw_only=Trueto the dataclass, with a comment saying exactly why, which removes the ordering rule entirely. So the fix now stands down on 5.6.0+ rather than monkey patching every config subclass for no benefit. The check reads the source rather than pinning a version, since the change could be backported, and unreadable source falls back to applying the fix.I found this because the control test, the one that asserts the failure is real without the fix, failed against a real transformers 5.14.1. That is the test doing its job: it is there precisely so the fix cannot silently stop testing anything.
Verified live on three transformers:
offload_embeddingfailed the load on tied modelsIt raised
NotImplementedErroron a tied-embedding model. But it is a VRAM optimisation, not a correctness switch, and on a tied modelembed_tokensislm_head, so offloading strands the output projection on CPU and frees nothing. It is now turned off with a message, the wayfast_inferencealready degrades.Resolved before
_attach_bnb_multidevice_hooks, which returns early while the flag is stillTrue. Resolving it later would silently skip hook attachment for exactly these models. WSL and Windows pass through unchanged, since the offload block skips those platforms anyway and probing the embeddings there would be a code path that never used to run.peft symbols transformers stopped shipping
Backfilling whole missing modules was not enough. transformers 5.0.0.dev0 has
conversion_mappingbut not_MODEL_TO_CONVERSION_PATTERN, so individual names are backfilled rather than a real module being replaced wholesale.TRL 0.22.x gated SFT vision paths on the model, not the dataset
On TRL 0.22.x a VLM skips dataset preparation and picks the vision collator from
_is_vlmalone. Fine-tuning a VLM on a text-only dataset then reaches the trainer with a rawtextcolumn, no tokenized columns exist, and transformers strips everything:Magistral_(24B)-Reasoning-Conversationalfails exactly this way: it pinstrl==0.22.2and trains a VLM on a plaintextdataset. Merging the signature columns is not enough, because with preparation skipped none of those tokenized columns are ever produced. TRL 0.25.1+ fixed this by keying the decisions off_is_vision_dataset, so that is what gets back-ported, and it no-ops where TRL already defines the flag.Note on overlap
This touches
unsloth/models/rl.py, as does #7854, but in a different place: this adds_backport_vision_dataset_gateand one call site, while #7854 changes the exception handler in_patch_trl_rl_trainers. If they conflict textually it is at a hunk boundary, not semantically. Zero torchao content, so no overlap with #7856.