Skip to content

Lift the TRL ceiling to 1.13.0 and gate the range that was already being tested - #11137

Merged
danielhanchen merged 349 commits into
pr/lift-transformers-capfrom
pr/lift-trl-cap
Sep 29, 2026
Merged

danielhanchen merged 349 commits into
pr/lift-transformers-capfrom
pr/lift-trl-cap

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

Summary

pyproject.toml caps TRL at <=0.24.0. That cap was set on 2025-11-03 in a9ff4e2, when 0.24.0 was the newest TRL on PyPI. About thirty releases have shipped since then, including a new major version: PyPI's latest is 1.13.0.

The cap is also behind this repository's own code:

  • unsloth/models/rl_replacements.py gates openenv_vllm_reload_weights on TRL >= 0.26.0 and vllm_generation_init_patch on >= 0.28.0. Under trl<=0.24.0, no install can reach either floor, so both patches return early for every user. They were written and shipped anyway, and nothing went red.
  • version-compat-ci.yml already runs an unpinned, blocking latest TRL lane (1.13.0 today) and passes. consolidated-tests-ci.yml carries a blocking trl>=1,<2 lane in both this repo and unsloth-zoo.
  • tests/version_compat/ refers to TRL 1.x behaviour by version throughout, for example the 1.7.0 chunked_nll default (trl#5846) and the 1.10.0 reload_weights deletion.

This PR raises the TRL ceiling to 1.13.0 and keeps the !=0.19.0 exclusion. It also widens the datasets window, because otherwise the new TRL ceiling cannot be reached (see below). Finally, it updates every site that mirrored the old numbers and adds a gate so the next drift fails the build.

Why datasets has to move too

Every TRL 1.x release requires datasets>=4.7.0, and pyproject.toml declares datasets<4.4.0. pip does not raise an error on this conflict. It backtracks to the newest TRL whose datasets floor fits, so raising only the TRL line would advertise 1.13.0 and install 0.29.1.

resolve (Linux, Python 3.12) datasets trl
TRL lifted, datasets unchanged 4.3.0 0.29.1
this PR 4.8.5 1.13.0

The new window is datasets>=3.4.1,!=4.0.*,!=4.1.0,!=4.4.*,!=4.5.0,<5.0.0. It is the specifier #8810 proposed, and it keeps both kinds of exclusion that have a reason behind them:

  • !=4.0.* and !=4.1.0: real torchcodec audio-decoding reports.
  • !=4.4.* and !=4.5.0: exactly the range patch_datasets in unsloth/import_fixes.py refuses at import.

The old <4.4.0 was broader than that guard. The only other datasets pin in the tree is Studio's datasets==4.3.0, which is left alone (see "What this PR does not change").

The change was measured before it was proposed:

  • Data preparation is byte-identical across datasets 4.3.0, 4.6.0, 4.7.0, 4.8.5 and 5.0.1, at all 16 of 16 checkpoints.
    • Path: standardize_data_formats, standardize_sharegpt, get_chat_template, train_on_responses_only, sft_prepare_dataset and the collator.
    • Recipes: ShareGPT and instruction.
    • The num_proc policy was tested both in-process and at its default.
    • Compared: exact input_ids, attention_mask, labels and -100 mask positions, not dataset fingerprints.
  • Training numerics (Llama-3.2-1B LoRA SFT, 8 steps):
    • The difference between arms was smaller than the same-arm noise floor.
    • Steps 1 and 2 were bit-identical across arms.
  • Real notebooks passed on Kaggle T4s at both the old and the new resolve. This included:
    • the deprecated-API conversational notebook;
    • an audio/TTS notebook, the only datasets breakage that has actually been reported in this area.

Delivered, not just advertised: the unsloth_zoo side

pip intersects this package's window with unsloth_zoo's, so each widened range reaches users only once a published zoo release carries the same ceiling.

axis zoo requirement state
trl <=1.13.0 unslothai/unsloth-zoo#1260, released in 2026.9.5 delivered; the floor here is already unsloth_zoo>=2026.9.7
datasets window unslothai/unsloth-zoo#1341, merged advertised until a zoo release carries it

tests/test_trl_cap_sites.py enforces this in both directions:

  • test_the_declared_zoo_floor_can_supply_the_declared_trl_window is live and fails if the zoo floor drops below 2026.9.5.
  • The datasets twin is deferred on ZOO_FLOOR_WITH_LIFTED_DATASETS_CAP = None, because a zoo floor that no published release satisfies would make unsloth uninstallable. A companion test checks PyPI and goes red on its own once a zoo release carries the widened window. When that happens, the fix is one edit: name the release and raise unsloth_zoo>= to match.

Merge order: unsloth-zoo#1341 first, then a zoo release, then the floor bump described above. This PR is safe to land before that. Until then pip resolves datasets under 4.4.0 and TRL 0.29.1, which is already inside today's window.

The zoo release that carries #1341 should also carry unslothai/unsloth-zoo#1400. With TRL 1.7 or later, gpt-oss LoRA SFT fails on its first step ('int' object has no attribute 'to'): TRL requests MoE router logits by default, and zoo's patched gpt-oss model forward did not return them. Measured on the Kaggle T4 gptoss leg's own script, it fails on zoo main with TRL 1.13.0 on transformers 5.5.0 and 5.17.0, and passes with TRL 0.24.0. With #1400 it passes on all three, and the TRL 0.24.0 run is bit-identical to main.

Changes

  • pyproject.toml, both requirement lists (huggingfacenotorch, colab-new):

    • trl <=0.24.0 to <=1.13.0;
    • datasets to the window above;
    • the zoo-floor comment now states each axis's delivered/advertised status.
  • studio/backend/requirements/no-torch-runtime.txt: the same two specifiers.

  • version-compat-ci.yml:

    • the ceiling lane's 'trl==0.24.0' becomes 'trl==1.13.0', and its datasets pin takes the new window;
    • the paths: entry and the cap-suite invocation are updated.
  • notebooks-ci.yml:

    • 'trl>=0.22,<0.26' becomes 'trl>=0.22,<=1.13.0';
    • 'datasets>=3.4,<5' becomes the pyproject window.

    Both old ranges were already wrong before this PR:

    • <0.26 excluded the TRL pins (0.26.2, 0.28.0, 0.29.1, 1.9.2) that 30 notebooks in unslothai/notebooks carry, so the job dumped an API surface those notebooks never run on.
    • >=3.4,<5 admitted 4.4.0-4.5.0, which patch_datasets refuses at import.
  • scripts/scan_packages_baseline.json: four reviewed entries for TRL 1.x modules that the package scanner flags by pattern, for example the importlib.import_module in trl/_lazy_module.py. Without them the scan fails on the lifted resolve.

  • New tests/test_trl_cap_sites.py, wired into the existing cap-site-consistency job. It reads files only and makes no network calls, except for the self-expiring deferral check, which skips when offline. The key assertion is test_no_trl_runtime_guard_is_unreachable_through_the_declared_window. It parses the Version(importlib_version("trl")) < Version(...) early returns in rl_replacements.py and fails if the declared window cannot reach one of those floors, which is exactly the check the shipped cap failed.

The Windows ARM64 Arrow-overlay pin this branch used to carry was split into #11911, which has merged; after merging main, those lines are no longer part of this diff.

Mutation table

Each row is a change that should turn the new suite red. The tree was restored between rows.

# Mutation Caught
M1 pyproject.toml both sites back to <=0.24.0 yes (6 failed)
M2 !=0.19.0 dropped yes (2 failed)
M3 only no-torch-runtime.txt left on <=0.24.0 yes (1 failed)
M4 notebooks-ci.yml back to 'trl>=0.22,<0.26' yes (1 failed)
M5 both unpinned latest lanes given continue_on_error: true yes (1 failed)
M6 tests/test_trl_cap_sites.py removed from pull_request.paths yes (1 failed)
M7 cap set to <=0.25.0, below the 0.26.0 runtime guard yes (5 failed)

M4 matters most. Under M1, a range check would not flag that lane, because trl>=0.22,<0.26 does contain 0.24.0. So PINNED_BY_DESIGN is keyed on (workflow, exact requirement string) rather than on filename, and it has its own negative control.

Evidence

TRL sweep. Each TRL version ran the whole of tests/version_compat/ in its own venv. The environment matched version-compat-ci.yml, with CPU torch and transformers 5.17.0. There were zero failures at every point:

TRL tests/version_compat/
0.22.2 1777 passed, 219 skipped
0.24.0 pass
0.29.1 pass
1.0.0 1808 passed, 188 skipped
1.6.0 pass
1.7.0 pass
1.13.0 1814 passed, 182 skipped

The skips fall as TRL rises, because tests gated on newer TRL behaviour start running. For example, test_trl_loss_normalization_contract.py goes from 1 skip at 0.24.0 ("this TRL has no _chunked_cross_entropy_loss") to 0 at 1.13.0. Under the shipped cap, that assertion could not run on any TRL a user could install. unsloth-zoo's tests/test_loss_normalization_contract.py skips for the same reason.

These seven are the measured releases. The window admits about twenty-five more that were not run individually. NEWLY_ADMITTED lists only the measured ones, so a later edit cannot claim more coverage than was measured.

Current head (3aa6eeb8c, after merging the updated #11016 and main).

  • The full local suite gave 1953 passed, 224 skipped, 0 failed. Environment: transformers 5.17.0, torch 2.13.0, datasets 5.0.1.
  • The two GRPO source rewrites in rl_replacements.py were checked against the real upstream sources at TRL 0.18.2, 0.20.0, 0.22.2, 0.24.0, 0.29.1, 1.0.0 and 1.13.0. At every version the anchors match, the rewritten source parses, and applying the rewrite twice changes nothing.

Every site that spells the cap

unslothai/unsloth

  • pyproject.toml (two lists) and no-torch-runtime.txt: changed.
  • version-compat-ci.yml:
    • the ceiling lane: changed;
    • the 'trl==0.18.2' floor lanes: unchanged, correct.
  • notebooks-ci.yml: changed.
  • consolidated-tests-ci.yml lines 209/213 and 2279/2283: the deliberate trl>=0.18.2,<1.0.0 / trl>=1,<2 split. Unchanged, and allowlisted with that reason.
  • studio/backend/requirements/single-env/constraints.txt:10, trl==0.23.1: unchanged (see below).
  • The rl_replacements.py runtime guards at 0.26.0 and 0.28.0: unchanged, and now reachable.

unslothai/unsloth-zoo

What this PR does not change

  • Studio's single-env pins keep trl==0.23.1 and datasets==4.3.0. The cap controls which releases pip install may resolve. Those pins control which release the pinned installer ships, and moving them needs its own resolved lockfile. Lift the transformers ceiling to 5.17.0 and align the mirrored CI caps #11016 gives the same reasoning for transformers==5.5.0.
  • datasets 5.x stays excluded by <5.0.0, even though 5.0.1 measured clean above. The runtime guard and the notebooks were not validated against it, so it belongs in its own change.

Base

This PR is stacked on pr/lift-transformers-cap (#11016), which extends the cap-site-consistency job and the version-compat lanes that this PR edits. #11136 has merged. Retarget to main once #11016 lands.

@danielhanchen
danielhanchen changed the base branch from main to pr/lift-transformers-cap September 16, 2026 18:33
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 16, 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-29T13:22:54.295687Z fcd711c Manual request
🔒 Security Review ✅ Completed 2026-09-17T09:00:00.293571Z 741db3a Manual request

Security findings

Finding details are still loading. Check the individual review comments.

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

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed against main: pyproject.toml caps trl at 0.24.0 while rl_replacements.py:2888 and :2967 gate patches on 0.26.0 and 0.28.0, so neither can run on a resolvable install. Will get this reviewed alongside the unsloth-zoo half, since the intersection does not move until both land.

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed against main: pyproject.toml caps trl at 0.24.0 while rl_replacements.py:2888 and :2967 gate patches on 0.26.0 and 0.28.0, so neither can run on a resolvable install. Will get this reviewed alongside the unsloth-zoo half, since the intersection does not move until both land.

danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Sep 17, 2026
… own guards (#1260)

unsloth's pyproject and this one both cap TRL at <=0.24.0, set 2025-11-03. pip
resolves the intersection, so this file is what actually decides which TRL a
user gets, and lifting the cap in unsloth alone changes nothing.

The cap makes a real guard unreachable. unsloth/models/rl_replacements.py gates
vllm_generation_init_patch on Version(importlib_version("trl")) >= 0.28.0. That
patch is what stops a second vLLM instance being built when fast_inference
already has one. Under a <=0.24.0 window the floor is not resolvable, so on
every configuration a user can install the guard returns immediately and the
second instance gets built. The sibling gate on openenv_vllm_reload_weights
(>= 0.26.0) is unreachable the same way.

Raises the ceiling to 1.13.0, the newest release on PyPI and the newest the
sweep was run against, at both sites, keeping !=0.19.0.

Also restates the `.[core]` rationale comment in consolidated-tests-ci.yml as
the mechanism rather than as a version number, since this commit moves the
number it quoted.

Must land together with unslothai/unsloth#11137. Either alone leaves the
intersection where it was.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 741db3af58

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

danielhanchen added a commit that referenced this pull request Sep 17, 2026
…o that slices it

TRL 0.22.x-0.23.x has neither forward_kwargs nor num_images. Three things followed
from that, and a singular `image` column holding a list makes all three reachable.

The no-grad old and reference logprob calls take four hand named processor tensors
and no counts, so the shared chunker slices an image indexed image_grid_thw by
sample index. Build the counts before those calls rather than in the output block,
which only runs once they have returned, and hand the whole mapping to all three
call sites.

The same versions save only those four keys, so spatial_shapes, num_tiles and the
Gemma position ids never leave the processor and the gradient forward runs without
arguments the model requires. Copy the same mapping into the output, which also
carries token_type_ids across, widened over the completion the way TRL 0.24.0
widens it in place before the identical call. A copy that cannot be made to fit,
as after max_prompt_length truncation, is dropped rather than sent.

split_pixel_values_by_grid before TRL 1.1.0 splits pixel_values by GRID ROW, one
element per image, and leaves image_grid_thw flat. shuffle_sequence_dict then takes
its length from prompt_ids, so a row holding two images has that list permuted
wrongly and truncated to the sample count. Regroup it per sample and split the grid
the way 1.1.0 does, and merge the grid back after the slice, which TRL's own unsplit
does not do before 1.1.0. All-ones rather than a length comparison decides when the
axes already coincide: num_images = [0, 2] over two samples makes the counts agree
while the axes still differ.

Finally, both logprob paths raise without unsloth_zoo.grpo_vision_chunks while the
declared floor still admits 2026.9.4, which does not export it, so a dependency
compliant install raised for every vision batch including the single image grid
models that worked before. Move the floor to 2026.9.5, the same release #11137
names, rather than keeping a fallback: a fallback could only cover the no-grad half,
since the gradient half lives inside the zoo's own grpo_accumulated_loss, and half a
fallback makes the two policies disagree.

Tested across trl 0.22.2, 0.23.0, 0.23.1, 0.24.0, 0.26.2, 0.29.1, 1.0.0, 1.1.0,
1.5.0, 1.7.0, 1.9.2, 1.11.0, 1.12.0 and 1.13.0: the legacy rewrite fires on the
three 0.2x releases and on nothing else, and no anchor warning is raised anywhere.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 0ee6b2809d

ℹ️ 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 Sep 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 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: 05cd2fadd0

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


def start_update() -> dict:
"""Kick off a background update job chaining the llama phase with a whisper phase that runs only when whisper is behind; either phase no-ops cleanly when its component is current or unmanaged. Idempotent: a second call while one is running returns the in-flight job."""
if update_checks_disabled():

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 the update opt-out to backend switches

When UNSLOTH_DISABLE_UPDATE_CHECK=1, this guard blocks /update and the new backend-status logic hides the picker, but an owner can still call POST /api/llama/backend directly: start_backend_switch() remains unguarded and invokes _start_llama_job(), whose planning resolves release assets and can download/install them. This bypasses the newly enforced opt-out for API clients, so apply the same check to backend-switch mutations (or enforce it in the shared job entry point).

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Out of scope for this PR rather than wrong. This PR changes dependency windows, four CI workflows and tests; studio/backend/utils/llama_cpp_update.py is byte-identical to the merge base here (git diff <merge-base> HEAD -- studio/backend/utils/llama_cpp_update.py is empty), so nothing in this diff reaches start_backend_switch(). The observation itself does look right on main: the only UNSLOTH_DISABLE_UPDATE_CHECK reference in that file is at line 1023, and start_backend_switch at line 1031 does not consult it. That belongs to whichever PR introduced the backend picker, not here.

@danielhanchen

Copy link
Copy Markdown
Member Author

One measured data point for the range, from the transformers side, and one residual the ceiling bump alone does not close.

transformers 5.3.0 changed transformers.utils.import_utils._is_package_available to return a tuple even when return_version=False:

transformers 4.57.6 / 5.0.0 / 5.2.0 : _is_package_available("absent_pkg") -> False
transformers 5.3.0  / 5.8.1 / 5.17.0: _is_package_available("absent_pkg") -> (False, None)

TRL <= 0.28.0 stores that straight into _vllm_available, _mergekit_available, _weave_available, _vllm_ascend_available. A 2-tuple is truthy, so every optional dependency reports present and from trl import GRPOTrainer dies on the import it then attempts. Executed, one venv per cell:

TRL \ transformers 4.57.6 5.0.0 5.2.0 5.3.0 5.8.1 5.17.0
0.24.0 pass pass pass FAIL No module named 'mergekit' FAIL FAIL
0.28.0 pass pass pass FAIL No module named 'weave' FAIL FAIL

0.29.0 vendors its own bool-returning _is_package_available, which is the fix, so the real constraint is a hard floor on the (transformers, TRL) plane: transformers >= 5.3.0 requires TRL >= 0.29.0.

The residual: raising the ceiling to 1.13.0 lets a resolver reach a good pair, it does not stop it choosing a bad one. With trl>=0.18.2,!=0.19.0,<=1.13.0 and transformers<=5.5.0 (or 5.17.0 after #11016), transformers==5.4.0 with trl==0.24.0 is still inside the declared window and still cannot import GRPOTrainer. A drift gate on the numbers will not see that, because both numbers are in range. Worth either a floor that encodes the pairing, or a version_compat case that asserts the declared window contains no importable-but-broken pair.

@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: 25faa6337e

ℹ️ 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 +3307 to +3309
_USER_ANTHROPIC_BLOCK_TYPES = frozenset(
{"text", "image", "tool_use", "tool_result", "search_result", "document"}
)

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 Validate newly accepted reference blocks

Adding search_result and document only to this allowlist still parses them through AnthropicUnknownBlock, whose only required field is type. Consequently, a request such as a user turn containing only {"type":"search_result"} or a content document with no renderable content passes validation, but anthropic_reference_block_text() returns an empty string and the converter silently drops the entire turn. This defeats the user-message validation intended to prevent forwarding an altered or empty conversation; define typed models or otherwise require these blocks to produce content before accepting them.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same reason as the other item: out of scope here, not incorrect. studio/backend/models/inference.py is byte-identical to this PR's merge base (git diff <merge-base> HEAD -- studio/backend/models/inference.py is empty), and this PR's 18 files are dependency specifiers, four CI workflows, two Studio requirements files, one test docstring and the test suites. The allowlist at line 3308 and AnthropicUnknownBlock at 3312 are untouched by it. The behaviour described is also already stated in that file's own comments at 3299 and 3399, so if it needs tightening it wants its own change against main rather than a dependency-cap PR.

danielhanchen added a commit that referenced this pull request Sep 17, 2026
…a list (#11031)

* Forward every GRPO vision kwarg, and accept an image column holding a list

Two GRPO vision bugs.

The logprob paths dropped multimodal inputs. TRL passes everything the processor
produced into its per token logprob helper and stores the same set in the dict
compute_loss receives, but the Unsloth replacements read a hand written list of
four keys. spatial_shapes (LFM2-VL), num_tiles (LFM2-VL, InternVL) and
image_position_ids (Gemma 4) reached neither pass, and a model that does not
emit image_grid_thw had its pixel_values replaced by None, so the reference and
old logprobs were computed from the text alone. Both passes now read one key
tuple that unsloth_zoo owns and chunk through one shared slicer, so a key added
there reaches both. Three supporting defects went with it:

- The rewrite that saves max_left_pad matched only the first two lines of TRL's
  num_images output block, which since TRL 1.7.0 also holds a nested num_tiles
  line. The nested line ended up inside the try/except, so num_tiles never
  reached the inputs dict and the tile indexed slicing had nothing to index
  with. The anchor now covers the whole block.
- The GRPO hidden state forward wrapper replaced the forward with a bare
  (*args, **kwargs) function. transformers validates generate's kwargs against
  inspect.signature(self.forward), so every kwarg a VLM takes only on forward
  looked unused and LFM2-VL GRPO died in generation with "The following
  model_kwargs are not used by the model: ['pixel_values',
  'pixel_attention_mask', 'spatial_shapes']". The wrapper now uses
  functools.wraps.
- The old zoo fallback list in compute_loss now names all ten keys.

A singular image column holding a list of images crashed. TRL wraps whatever
example["image"] holds in a list of its own, so a cell carrying two images
reaches the processor as [[[img, img]]] and both make_nested_list_of_images and
the processor reject it with "Invalid input type. Must be a single image, a list
of images, or a list of batches of images.". The extraction is now rewritten to
treat a list cell as the plural images form, on both the TRL 0.22.x and the TRL
1.x spelling, and TRL 0.22.x's one image placeholder per example is widened to
the cell's length. Where no known spelling matches, a named error says which
column to rename instead of failing inside the processor.

With this, one real GRPO step on LFM2-VL-450M completes end to end, and the
chunked logprobs match a single whole batch forward exactly.

Fixes #6960
Fixes #3605

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Collect the GRPO multimodal inputs through one helper, and probe the zoo by import

Three changes on top of the shared key tuple.

The old unsloth_zoo fallback list was a second copy of the key names written
inline in compute_loss, and the logprob pass had no fallback at all: without the
zoo helper it collected nothing, so a run that only carried token_type_ids lost
them, having sliced them itself before. Both now go through one
_unsloth_grpo_vision_inputs, which prefers the zoo's tuple and names the keys
once for a zoo too old to export it. Only the image indexed slicing belongs to
the zoo, and that is the one case that still refuses to run, loudly.

pixel_position_ids joins the fallback list, matching unsloth_zoo: it is the
TRL 1.0.x name for image_position_ids.

The multi image gate used to decide whether the installed zoo could serve the
run by grepping inspect.getsource(grpo_accumulated_loss) for the string
num_images. That function delegates its slicing to the shared chunker now, so
the name survives there only as a local nobody reads, and removing it, which is
what a linter asks for, turned a working multi image run into a false 'Please
upgrade unsloth_zoo'. The gate probes for grpo_vision_chunks by import first and
keeps the source grep only for a zoo older than that helper.

* Expose the GRPO forward signature without a __wrapped__ link

functools.wraps set __wrapped__, and accelerate's extract_model_from_parallel
with keep_fp32_wrapper False walks that chain and rebinds what it lands on, so
once prepare_model had recorded _original_forward the hidden-state wrapper was
removed on every GRPO step and the vocabulary-wide logits came back. Setting
__signature__ gives generate the same answer with no link to follow.

* Add the AGPL-3.0 header to the new GRPO test files

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reduce comment volume in the GRPO vision kwarg paths and their tests

* Gate the gradient path on the zoo chunker too

With beta = 0 and num_iterations = 1 there are no reference or old logprobs to
compute, so the no-grad pass that carries the upgrade check never runs. An older
grpo_accumulated_loss accepts arbitrary kwargs, ignores the keys it does not
know and replaces pixel_values with None for a model with no image_grid_thw, so
a vision run trained on the text alone without saying so. Check for
grpo_vision_chunks before the gradient call whenever pixels are present.

* Skip the zoo driven multi image tests when the installed zoo predates the helpers

* Persist every vision kwarg in the batch, and keep each sample's tiles with it

* Count the images a legacy TRL never counted

* Carry the whole vision batch through a legacy TRL, and require the zoo that slices it

TRL 0.22.x-0.23.x has neither forward_kwargs nor num_images. Three things followed
from that, and a singular `image` column holding a list makes all three reachable.

The no-grad old and reference logprob calls take four hand named processor tensors
and no counts, so the shared chunker slices an image indexed image_grid_thw by
sample index. Build the counts before those calls rather than in the output block,
which only runs once they have returned, and hand the whole mapping to all three
call sites.

The same versions save only those four keys, so spatial_shapes, num_tiles and the
Gemma position ids never leave the processor and the gradient forward runs without
arguments the model requires. Copy the same mapping into the output, which also
carries token_type_ids across, widened over the completion the way TRL 0.24.0
widens it in place before the identical call. A copy that cannot be made to fit,
as after max_prompt_length truncation, is dropped rather than sent.

split_pixel_values_by_grid before TRL 1.1.0 splits pixel_values by GRID ROW, one
element per image, and leaves image_grid_thw flat. shuffle_sequence_dict then takes
its length from prompt_ids, so a row holding two images has that list permuted
wrongly and truncated to the sample count. Regroup it per sample and split the grid
the way 1.1.0 does, and merge the grid back after the slice, which TRL's own unsplit
does not do before 1.1.0. All-ones rather than a length comparison decides when the
axes already coincide: num_images = [0, 2] over two samples makes the counts agree
while the axes still differ.

Finally, both logprob paths raise without unsloth_zoo.grpo_vision_chunks while the
declared floor still admits 2026.9.4, which does not export it, so a dependency
compliant install raised for every vision batch including the single image grid
models that worked before. Move the floor to 2026.9.5, the same release #11137
names, rather than keeping a fallback: a fallback could only cover the no-grad half,
since the gradient half lives inside the zoo's own grpo_accumulated_loss, and half a
fallback makes the two policies disagree.

Tested across trl 0.22.2, 0.23.0, 0.23.1, 0.24.0, 0.26.2, 0.29.1, 1.0.0, 1.1.0,
1.5.0, 1.7.0, 1.9.2, 1.11.0, 1.12.0 and 1.13.0: the legacy rewrite fires on the
three 0.2x releases and on nothing else, and no anchor warning is raised anywhere.

* Keep the legacy vision prologue off a text batch, and off a newer TRL entirely

Three corrections to the previous commit.

Gemma 3's processor returns token_type_ids with no images at all
(return_mm_token_type_ids defaults True), and the prologue read the processor
before testing has_images, so a text only GRPO run on TRL 0.22.x-0.23.x started
forwarding an all zeros mask where main forwarded nothing. Both PrefixGrouper and
sequence packing are keyed on that name being absent, on the no-grad side here and
on the gradient side in the zoo, so the run silently lost both fast paths. Gate the
whole prologue the way TRL 0.24.0 gates forward_kwargs, on `images is not None`,
and drop the two spellings when the processor produced no pixels, which is what an
image column with every cell empty looks like.

A width equal to prompt+completion was kept untouched rather than dropped. On these
versions prompt_inputs is prompt only, so that width can only be an untruncated
prompt reached through max_prompt_length, and truncate_with_protected_tokens keeps
the image tokens but moves them, leaving the marks at the wrong offsets. Only the
prompt width is widened now; everything else is dropped.

The prologue is also emitted only for the versions whose call sites consume it.
0.24.0 and up leave prompt_inputs unbound at that anchor so it fell through anyway,
but not emitting it makes their generated source byte for byte what it was: patched
_generate_and_score_completions now compares identical to 772802c for 0.24.0,
0.26.2, 0.29.1, 1.0.0, 1.1.0, 1.5.0, 1.7.0, 1.9.2, 1.11.0, 1.12.0 and 1.13.0, and
differs only on 0.22.2, 0.23.0 and 0.23.1.

* Defer the unsloth_zoo 2026.9.5 floor until the release exists

2026.9.5 is not on PyPI, so declaring it in pyproject.toml makes the package
unresolvable for everyone, which is worse than the raise the floor prevents.
Put the three dependency lines back to 2026.9.4 and skip the gate that asserts
the floor in the same commit, so the pin and its test move together instead of
turning CI red. The upgrade message still names 2026.9.5, and the assertion that
checks it stays live. Dropping the skip re-arms the floor when the release ships.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Refuse a multi image row on a TRL whose reference calls lost the counts

Normalising the singular `image` cell is only half of a multi image row. On TRL
0.22.x-0.23.x the reference logprob call sites also have to carry the image counts,
or the vision batch is sliced by sample index and every image after the first is
dropped, which the model reports as a token/feature mismatch that names neither the
column nor the fix.

Every TRL from 0.22.2 to 0.23.1 takes all three call site rewrites, and 0.24.0 and
up pass forward_kwargs and need none, so nothing in the supported range changes
behaviour here. If those call sites ever drift, the existing warning is now paired
with the guard that already exists for an unmatched cell anchor, so the user gets
the unsloth level error instead of the mismatch. A single image row is unaffected.

* Keep a padded per sample image axis when the counts sum to the batch size

A padded per sample pixel_values (Idefics, SmolVLM) and a flat image indexed one
have the same first dimension when num_images sums to the sample count, so a mixed
batch such as [2, 0] was split as if it were image indexed: both padded rows went
to the first sample and the second received an empty tensor, with no error raised.
Nothing in the batch distinguishes the two readings, so keep TRL's layout there, as
every version does today. All ones is excluded because both readings agree on it.
The list branch already guards the same collision.

* Refuse a multi image cell on a TRL that cannot size its placeholders

TRL 0.20.0 and 0.21.0 take the legacy image cell spelling the normalisation rewrites,
but predate prepare_multimodal_messages entirely: they inline one {"type": "image"}
per user message with no count. Normalising a two image cell there sent the processor
two images against one placeholder, and the prologue counted the same cells, so nothing
else in the batch disagreed and the mismatch surfaced inside the processor, naming
neither the column nor the fix. That is the outcome the named refusal exists to replace,
and it was not firing, because its gate only asked whether the cell had been normalised.

Both versions are inside the declared pin, trl>=0.18.2,!=0.19.0,<=0.24.0.

The gate now also asks whether the placeholders were sized. Measured over the 28 TRL
releases on this box from 0.18.2 to 1.13.0: only 0.20.0 and 0.21.0 change, gaining the
refusal, and the generated source for every other version is byte for byte what it was.
A single image cell is unaffected on every version.

* Declare the unsloth_zoo 2026.9.5 floor now that the release is published

2026.9.5 is on PyPI and carries grpo_vision_chunks, so the floor that was
deferred for want of a release can be declared. Three pyproject sites move
from 2026.9.4 to 2026.9.5, and the skip comes off the floor assertion in
tests/test_grpo_vision_zoo_floor.py.

The four installer sites that pass --no-deps also move, from 2026.9.3. On
those paths uv ignores package metadata by definition, so the literal on the
command line is the only floor there is and the pyproject pin does not reach
them. The seven sites without --no-deps are left alone: there the resolver
intersects the spec with unsloth's own metadata, so they are already covered.

tests/studio/install/test_installer_zoo_floor_parity.py ties the two together
so they cannot drift a third time.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read every row in the singular image column refusal, not only the first

The guard inspected inputs[0] alone, so a batch whose first row holds a bare image and
whose second holds a list passed it. The normalisation then gave that later row several
images while a TRL that cannot size its placeholders still emitted one, and the mismatch
surfaced inside the processor naming neither the column nor the fix. A dataset mixing a
bare image with a list is exactly the shape that puts the list somewhere other than row 0.

Every row is read now, and the message says which row. Shapes that pass today still pass,
including a batch with no image column, rows that are not dicts, an empty batch and None.

* Give an empty legacy image cell no placeholder, and demote an all empty column

On TRL 0.22.x and 0.23.x an empty cell took one placeholder while the prologue counted it
as zero, so a batch mixing an image bearing row with an empty one reached the processor a
placeholder ahead of its pixels. Measured against a real Gemma 3 processor, one image and
one empty cell:

    main                        Invalid input type. Must be a single image, ...
    one placeholder for empty   Prompt contained 1 image tokens but received 0 images.
    no placeholder for empty    ok, pixel_values (1, 3, 896, 896)

Zero placeholders alone is not enough: an all empty column then reaches the processor as
[[], []] against no placeholders, which is an IndexError rather than a text run. TRL demotes
that batch itself from 0.24.0, so the same guard is ported here and the column becomes a
text batch, which is a case that failed on main as well.

The guard mirrors TRL's own all(img_list == []), so it never fires for a None cell and that
column still fails exactly as it does on main, as the description records.

Only 0.22.0 through 0.23.1 change: 0.20.0 and 0.21.0 do not take this rewrite, and 0.24.0
and up size their own placeholders. Verified by diffing the generated source across the
28 TRL releases on this box.

* Refuse a multi image row on a legacy vLLM server run, and demote the flag with it

Two gaps on TRL 0.22.x and 0.23.x that the processor fix does not reach, because the vLLM
paths there read the raw cells rather than the processor kwargs.

The server path hands those cells to VLLMClient.generate, which does
[pil_to_base64(img) for img in images] over the top level entries, so a cell holding two
images arrives at list.save(...) and dies with an AttributeError naming neither the column
nor the fix. Before this branch that row died earlier, inside the processor, so the path was
unreachable; making the processor accept it is what exposes it. The refusal is injected on
these versions too and handed the trainer, so it fires only when use_vllm is set and
vllm_mode is server. Colocate mode and a run without vLLM both go through the processor and
keep working, checked explicitly.

Demoting an all empty image column emptied kwargs but left has_images true, and every vLLM
branch is gated on that flag rather than on kwargs, so the batch still submitted [[], ...]
as an image payload and server mode called .save() on an empty list. The flag is cleared
with the kwargs.

Measured over the 28 TRL releases here: only 0.22.0 through 0.23.1 change, which are exactly
the versions that take the legacy cell spelling and size their placeholders. 0.20.0 and
0.21.0 already refuse unconditionally, and 0.24.0 and up are byte for byte what they were.

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
@danielhanchen danielhanchen self-assigned this Sep 18, 2026
* Library: equal size chat cards, drop loading placeholders

* Library: size grid rows to the tallest card instead of clipping

---------

Co-authored-by: Maheswar Kumar <[email protected]>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…a list (unslothai#11031)

* Forward every GRPO vision kwarg, and accept an image column holding a list

Two GRPO vision bugs.

The logprob paths dropped multimodal inputs. TRL passes everything the processor
produced into its per token logprob helper and stores the same set in the dict
compute_loss receives, but the Unsloth replacements read a hand written list of
four keys. spatial_shapes (LFM2-VL), num_tiles (LFM2-VL, InternVL) and
image_position_ids (Gemma 4) reached neither pass, and a model that does not
emit image_grid_thw had its pixel_values replaced by None, so the reference and
old logprobs were computed from the text alone. Both passes now read one key
tuple that unsloth_zoo owns and chunk through one shared slicer, so a key added
there reaches both. Three supporting defects went with it:

- The rewrite that saves max_left_pad matched only the first two lines of TRL's
  num_images output block, which since TRL 1.7.0 also holds a nested num_tiles
  line. The nested line ended up inside the try/except, so num_tiles never
  reached the inputs dict and the tile indexed slicing had nothing to index
  with. The anchor now covers the whole block.
- The GRPO hidden state forward wrapper replaced the forward with a bare
  (*args, **kwargs) function. transformers validates generate's kwargs against
  inspect.signature(self.forward), so every kwarg a VLM takes only on forward
  looked unused and LFM2-VL GRPO died in generation with "The following
  model_kwargs are not used by the model: ['pixel_values',
  'pixel_attention_mask', 'spatial_shapes']". The wrapper now uses
  functools.wraps.
- The old zoo fallback list in compute_loss now names all ten keys.

A singular image column holding a list of images crashed. TRL wraps whatever
example["image"] holds in a list of its own, so a cell carrying two images
reaches the processor as [[[img, img]]] and both make_nested_list_of_images and
the processor reject it with "Invalid input type. Must be a single image, a list
of images, or a list of batches of images.". The extraction is now rewritten to
treat a list cell as the plural images form, on both the TRL 0.22.x and the TRL
1.x spelling, and TRL 0.22.x's one image placeholder per example is widened to
the cell's length. Where no known spelling matches, a named error says which
column to rename instead of failing inside the processor.

With this, one real GRPO step on LFM2-VL-450M completes end to end, and the
chunked logprobs match a single whole batch forward exactly.

Fixes unslothai#6960
Fixes unslothai#3605

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Collect the GRPO multimodal inputs through one helper, and probe the zoo by import

Three changes on top of the shared key tuple.

The old unsloth_zoo fallback list was a second copy of the key names written
inline in compute_loss, and the logprob pass had no fallback at all: without the
zoo helper it collected nothing, so a run that only carried token_type_ids lost
them, having sliced them itself before. Both now go through one
_unsloth_grpo_vision_inputs, which prefers the zoo's tuple and names the keys
once for a zoo too old to export it. Only the image indexed slicing belongs to
the zoo, and that is the one case that still refuses to run, loudly.

pixel_position_ids joins the fallback list, matching unsloth_zoo: it is the
TRL 1.0.x name for image_position_ids.

The multi image gate used to decide whether the installed zoo could serve the
run by grepping inspect.getsource(grpo_accumulated_loss) for the string
num_images. That function delegates its slicing to the shared chunker now, so
the name survives there only as a local nobody reads, and removing it, which is
what a linter asks for, turned a working multi image run into a false 'Please
upgrade unsloth_zoo'. The gate probes for grpo_vision_chunks by import first and
keeps the source grep only for a zoo older than that helper.

* Expose the GRPO forward signature without a __wrapped__ link

functools.wraps set __wrapped__, and accelerate's extract_model_from_parallel
with keep_fp32_wrapper False walks that chain and rebinds what it lands on, so
once prepare_model had recorded _original_forward the hidden-state wrapper was
removed on every GRPO step and the vocabulary-wide logits came back. Setting
__signature__ gives generate the same answer with no link to follow.

* Add the AGPL-3.0 header to the new GRPO test files

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reduce comment volume in the GRPO vision kwarg paths and their tests

* Gate the gradient path on the zoo chunker too

With beta = 0 and num_iterations = 1 there are no reference or old logprobs to
compute, so the no-grad pass that carries the upgrade check never runs. An older
grpo_accumulated_loss accepts arbitrary kwargs, ignores the keys it does not
know and replaces pixel_values with None for a model with no image_grid_thw, so
a vision run trained on the text alone without saying so. Check for
grpo_vision_chunks before the gradient call whenever pixels are present.

* Skip the zoo driven multi image tests when the installed zoo predates the helpers

* Persist every vision kwarg in the batch, and keep each sample's tiles with it

* Count the images a legacy TRL never counted

* Carry the whole vision batch through a legacy TRL, and require the zoo that slices it

TRL 0.22.x-0.23.x has neither forward_kwargs nor num_images. Three things followed
from that, and a singular `image` column holding a list makes all three reachable.

The no-grad old and reference logprob calls take four hand named processor tensors
and no counts, so the shared chunker slices an image indexed image_grid_thw by
sample index. Build the counts before those calls rather than in the output block,
which only runs once they have returned, and hand the whole mapping to all three
call sites.

The same versions save only those four keys, so spatial_shapes, num_tiles and the
Gemma position ids never leave the processor and the gradient forward runs without
arguments the model requires. Copy the same mapping into the output, which also
carries token_type_ids across, widened over the completion the way TRL 0.24.0
widens it in place before the identical call. A copy that cannot be made to fit,
as after max_prompt_length truncation, is dropped rather than sent.

split_pixel_values_by_grid before TRL 1.1.0 splits pixel_values by GRID ROW, one
element per image, and leaves image_grid_thw flat. shuffle_sequence_dict then takes
its length from prompt_ids, so a row holding two images has that list permuted
wrongly and truncated to the sample count. Regroup it per sample and split the grid
the way 1.1.0 does, and merge the grid back after the slice, which TRL's own unsplit
does not do before 1.1.0. All-ones rather than a length comparison decides when the
axes already coincide: num_images = [0, 2] over two samples makes the counts agree
while the axes still differ.

Finally, both logprob paths raise without unsloth_zoo.grpo_vision_chunks while the
declared floor still admits 2026.9.4, which does not export it, so a dependency
compliant install raised for every vision batch including the single image grid
models that worked before. Move the floor to 2026.9.5, the same release unslothai#11137
names, rather than keeping a fallback: a fallback could only cover the no-grad half,
since the gradient half lives inside the zoo's own grpo_accumulated_loss, and half a
fallback makes the two policies disagree.

Tested across trl 0.22.2, 0.23.0, 0.23.1, 0.24.0, 0.26.2, 0.29.1, 1.0.0, 1.1.0,
1.5.0, 1.7.0, 1.9.2, 1.11.0, 1.12.0 and 1.13.0: the legacy rewrite fires on the
three 0.2x releases and on nothing else, and no anchor warning is raised anywhere.

* Keep the legacy vision prologue off a text batch, and off a newer TRL entirely

Three corrections to the previous commit.

Gemma 3's processor returns token_type_ids with no images at all
(return_mm_token_type_ids defaults True), and the prologue read the processor
before testing has_images, so a text only GRPO run on TRL 0.22.x-0.23.x started
forwarding an all zeros mask where main forwarded nothing. Both PrefixGrouper and
sequence packing are keyed on that name being absent, on the no-grad side here and
on the gradient side in the zoo, so the run silently lost both fast paths. Gate the
whole prologue the way TRL 0.24.0 gates forward_kwargs, on `images is not None`,
and drop the two spellings when the processor produced no pixels, which is what an
image column with every cell empty looks like.

A width equal to prompt+completion was kept untouched rather than dropped. On these
versions prompt_inputs is prompt only, so that width can only be an untruncated
prompt reached through max_prompt_length, and truncate_with_protected_tokens keeps
the image tokens but moves them, leaving the marks at the wrong offsets. Only the
prompt width is widened now; everything else is dropped.

The prologue is also emitted only for the versions whose call sites consume it.
0.24.0 and up leave prompt_inputs unbound at that anchor so it fell through anyway,
but not emitting it makes their generated source byte for byte what it was: patched
_generate_and_score_completions now compares identical to 772802c for 0.24.0,
0.26.2, 0.29.1, 1.0.0, 1.1.0, 1.5.0, 1.7.0, 1.9.2, 1.11.0, 1.12.0 and 1.13.0, and
differs only on 0.22.2, 0.23.0 and 0.23.1.

* Defer the unsloth_zoo 2026.9.5 floor until the release exists

2026.9.5 is not on PyPI, so declaring it in pyproject.toml makes the package
unresolvable for everyone, which is worse than the raise the floor prevents.
Put the three dependency lines back to 2026.9.4 and skip the gate that asserts
the floor in the same commit, so the pin and its test move together instead of
turning CI red. The upgrade message still names 2026.9.5, and the assertion that
checks it stays live. Dropping the skip re-arms the floor when the release ships.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Refuse a multi image row on a TRL whose reference calls lost the counts

Normalising the singular `image` cell is only half of a multi image row. On TRL
0.22.x-0.23.x the reference logprob call sites also have to carry the image counts,
or the vision batch is sliced by sample index and every image after the first is
dropped, which the model reports as a token/feature mismatch that names neither the
column nor the fix.

Every TRL from 0.22.2 to 0.23.1 takes all three call site rewrites, and 0.24.0 and
up pass forward_kwargs and need none, so nothing in the supported range changes
behaviour here. If those call sites ever drift, the existing warning is now paired
with the guard that already exists for an unmatched cell anchor, so the user gets
the unsloth level error instead of the mismatch. A single image row is unaffected.

* Keep a padded per sample image axis when the counts sum to the batch size

A padded per sample pixel_values (Idefics, SmolVLM) and a flat image indexed one
have the same first dimension when num_images sums to the sample count, so a mixed
batch such as [2, 0] was split as if it were image indexed: both padded rows went
to the first sample and the second received an empty tensor, with no error raised.
Nothing in the batch distinguishes the two readings, so keep TRL's layout there, as
every version does today. All ones is excluded because both readings agree on it.
The list branch already guards the same collision.

* Refuse a multi image cell on a TRL that cannot size its placeholders

TRL 0.20.0 and 0.21.0 take the legacy image cell spelling the normalisation rewrites,
but predate prepare_multimodal_messages entirely: they inline one {"type": "image"}
per user message with no count. Normalising a two image cell there sent the processor
two images against one placeholder, and the prologue counted the same cells, so nothing
else in the batch disagreed and the mismatch surfaced inside the processor, naming
neither the column nor the fix. That is the outcome the named refusal exists to replace,
and it was not firing, because its gate only asked whether the cell had been normalised.

Both versions are inside the declared pin, trl>=0.18.2,!=0.19.0,<=0.24.0.

The gate now also asks whether the placeholders were sized. Measured over the 28 TRL
releases on this box from 0.18.2 to 1.13.0: only 0.20.0 and 0.21.0 change, gaining the
refusal, and the generated source for every other version is byte for byte what it was.
A single image cell is unaffected on every version.

* Declare the unsloth_zoo 2026.9.5 floor now that the release is published

2026.9.5 is on PyPI and carries grpo_vision_chunks, so the floor that was
deferred for want of a release can be declared. Three pyproject sites move
from 2026.9.4 to 2026.9.5, and the skip comes off the floor assertion in
tests/test_grpo_vision_zoo_floor.py.

The four installer sites that pass --no-deps also move, from 2026.9.3. On
those paths uv ignores package metadata by definition, so the literal on the
command line is the only floor there is and the pyproject pin does not reach
them. The seven sites without --no-deps are left alone: there the resolver
intersects the spec with unsloth's own metadata, so they are already covered.

tests/studio/install/test_installer_zoo_floor_parity.py ties the two together
so they cannot drift a third time.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read every row in the singular image column refusal, not only the first

The guard inspected inputs[0] alone, so a batch whose first row holds a bare image and
whose second holds a list passed it. The normalisation then gave that later row several
images while a TRL that cannot size its placeholders still emitted one, and the mismatch
surfaced inside the processor naming neither the column nor the fix. A dataset mixing a
bare image with a list is exactly the shape that puts the list somewhere other than row 0.

Every row is read now, and the message says which row. Shapes that pass today still pass,
including a batch with no image column, rows that are not dicts, an empty batch and None.

* Give an empty legacy image cell no placeholder, and demote an all empty column

On TRL 0.22.x and 0.23.x an empty cell took one placeholder while the prologue counted it
as zero, so a batch mixing an image bearing row with an empty one reached the processor a
placeholder ahead of its pixels. Measured against a real Gemma 3 processor, one image and
one empty cell:

    main                        Invalid input type. Must be a single image, ...
    one placeholder for empty   Prompt contained 1 image tokens but received 0 images.
    no placeholder for empty    ok, pixel_values (1, 3, 896, 896)

Zero placeholders alone is not enough: an all empty column then reaches the processor as
[[], []] against no placeholders, which is an IndexError rather than a text run. TRL demotes
that batch itself from 0.24.0, so the same guard is ported here and the column becomes a
text batch, which is a case that failed on main as well.

The guard mirrors TRL's own all(img_list == []), so it never fires for a None cell and that
column still fails exactly as it does on main, as the description records.

Only 0.22.0 through 0.23.1 change: 0.20.0 and 0.21.0 do not take this rewrite, and 0.24.0
and up size their own placeholders. Verified by diffing the generated source across the
28 TRL releases on this box.

* Refuse a multi image row on a legacy vLLM server run, and demote the flag with it

Two gaps on TRL 0.22.x and 0.23.x that the processor fix does not reach, because the vLLM
paths there read the raw cells rather than the processor kwargs.

The server path hands those cells to VLLMClient.generate, which does
[pil_to_base64(img) for img in images] over the top level entries, so a cell holding two
images arrives at list.save(...) and dies with an AttributeError naming neither the column
nor the fix. Before this branch that row died earlier, inside the processor, so the path was
unreachable; making the processor accept it is what exposes it. The refusal is injected on
these versions too and handed the trainer, so it fires only when use_vllm is set and
vllm_mode is server. Colocate mode and a run without vLLM both go through the processor and
keep working, checked explicitly.

Demoting an all empty image column emptied kwargs but left has_images true, and every vLLM
branch is gated on that flag rather than on kwargs, so the batch still submitted [[], ...]
as an image payload and server mode called .save() on an empty list. The flag is cleared
with the kwargs.

Measured over the 28 TRL releases here: only 0.22.0 through 0.23.1 change, which are exactly
the versions that take the legacy cell spelling and size their placeholders. 0.20.0 and
0.21.0 already refuse unconditionally, and 0.24.0 and up are byte for byte what they were.

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
danielhanchen and others added 21 commits September 29, 2026 01:24
* Studio: say when a model only partly fits on the GPU

Reported as novice users getting burned by dense models auto-spilling to
RAM. The spill itself is right, and refusing instead would break running a
large model on a small card, which is what people want it for. The problem
is that it is silent.

llama.cpp already logs 'offloaded N/M layers to GPU' and Studio already
matches it, then collapses it to a bool, so 12/60 and 60/60 both answer
True. In Auto mode gpu_layers on the wire is -1 because that is the
REQUEST, and Studio does not choose the split: it decides the model does
not provably fit and hands placement to --fit on. So a half-offloaded load
was byte-identical to a full one and got the same green 'loaded' toast,
leaving a stopwatch as the only way to find out.

The counts are kept now, published as offloaded_layers and
offload_total_layers, and a split load gets a warning toast naming the
split and suggesting a smaller quantization. All-on-GPU is unchanged. No
layers on the GPU is left to the existing CPU-fallback path rather than
folded in, so nothing double-warns.

Placement is untouched: same flags, same decisions, only the reporting.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: limit the partial-offload warning to automatic placement, and show it on auto-loads too

Two follow-ups from review.

Manual mode is now excluded. When the user pins the split themselves
(gpu_memory_mode == "manual"), llama.cpp reports exactly the layer count they
asked for, so telling them a smaller quantization would fit entirely on the GPU
is advice against their own choice. isPartialOffload now takes gpuMemoryMode and
returns false for it.

The automatic load path now carries the counts. A chat sent with no model loaded
goes through loadAutoLoadCandidate/showAutoLoadSuccess, which never runs the
interactive runtime hook and forwarded only cpu_fallback_reason, so the silent
partial split stayed silent on the one path a new user hits first.
showAutoLoadSuccess takes the counts and both call sites forward them.

The wording moved into partialOffloadDescription so the two paths cannot drift.

* Studio: warn on an all-CPU auto load, respect an extras -ngl, and cover the other load paths

Four follow-ups from review.

Zero offloaded layers is now a warning rather than an exclusion. It was left
out on the grounds that the CPU-fallback path already reported it, but
cpu_fallback_reason is only ever set for the Vulkan startup-crash recovery, so
an ordinary --fit on load that got nothing onto the GPU announced plain success.
That is the worst version of the problem this change exists for. It gets its own
wording rather than the partial one.

An -ngl passed through llama-server extras now counts as the user's own choice.
Auto mode respects an inherited -ngl instead of stripping it (manual mode is the
one that strips), so gpu_memory_mode alone cannot tell a spill Studio allowed
from a split the user asked for. The backend records whether extras overrode the
placement, beside the counts and from the same extras the load launched with,
and the response carries it as offload_overridden.

Compare mode and recipe runs are covered too. A recipe run loaded its model with
no panel open and toasted plain success unconditionally; compare mode has no
per-pane success toast, but a pane that landed half on the CPU does not just run
slow, it invalidates the comparison being timed, so it warns. All four load
paths now read the split through one shared helper.

The count parser breaks a tie on load order instead of the larger N. Nothing
forces a drafter to have fewer layers than its target, and llama.cpp logs the
main model first, so a fully offloaded 32-layer drafter could otherwise report
32/32 over a main model that got half its layers onto the GPU.

* Studio: count a CPU --device as deliberate placement for the offload warning

A --device naming no GPU overrides the layer count outright, so llama.cpp
reports 0/M for a load the user asked to run on CPU. The provenance flag only
covered the layer and fit flags, so that load drew the new all-CPU warning and
was told a smaller quantization would leave room on the GPU.

Reuses _device_selection_is_cpu, which already decides this for the memory
policy and reads the LLAMA_ARG_DEVICE env twin as well as argv.

* Studio: do not warn on a GPU-less host, on Manual with Auto layers, or over a known CPU reason

Five follow-ups from review.

A CPU-only host no longer gets the warning. llama.cpp logs "offloaded 0/N
layers to GPU" there like anywhere else, so publishing that count told every
user without a GPU that a smaller quantization would leave room on one they do
not have. The counts are now gated on the same question the classifier asks: a
GPU was detected, the load intended to use it, and it was not a deliberate
CPU-only or arch-gated launch.

Manual mode with GPU Layers on Auto now warns. That configuration hands
placement back to llama.cpp exactly like Auto mode does, but the response still
reads "manual", so suppressing on the mode alone silenced a real automatic
spill. The decision reads the requested count instead.

A --fit on in extras is no longer read as a pinned split. The provenance check
used the wider flag set, which also carries --fit, but --fit on asks llama.cpp
to choose the placement, which is the case worth reporting. --fit off pins
nothing by itself, so the layer flags alone are the right question.

A known reason for the CPU wins over the counts. A recovered Vulkan startup
crash leaves a 0/M line behind it, and the recipe and compare paths read that as
"nothing fit", blaming the model's size for a backend crash and recommending a
quantization that changes nothing. The helper now reads cpu_fallback_reason off
the same response, so every path gets the crash wording without repeating the
precedence rule.

The Audio page is the fifth load path. It loads a GGUF TTS variant and toasted
plain success, so an automatically split TTS model was as silent there as
everywhere else.

* Studio: separate a GPU backend that did not load from a fit that placed no layers

Both log the same 'offloaded 0/M' line, so a user whose CUDA runtime failed to
resolve was told none of the layers fit and that a smaller quantization would
leave room. Re-downloading a smaller model cannot repair a backend, and the load
already logs the cudart64_X.dll remediation for exactly this state.

llama.cpp prints its device table whenever a GPU backend is visible to it, so an
all-CPU table while Studio itself detected a GPU is the backend failure. That
scan already existed inside classify_gpu_offload_lines as a disconfirmation; it
is now llama_saw_gpu_device, used there and recorded per load as
gpu_backend_unavailable.

The all-CPU warning reads it and says the GPU could not be used, that this is a
backend problem rather than a size one, and points at the llama-server log. A
genuine zero-layer fit keeps the size wording.

* Studio: trim comments in the partial offload report

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio tests: give the shared backend double the two offload runtime fields

* Studio: launch llama-server at trace verbosity so the offload split is logged again

* Studio: report splits on Metal and env-pinned layers, keep the startup log head, soften the quantization advice

* Studio: use template literals for the offload warning text

* Studio: read Metal device rows, flag a failed Metal backend, and cap the active llama-server log

* Studio: keep a positive offload count on builds the local GPU probe cannot see

* Studio: trim comments in the offload report

* Studio tests: stub the offload helpers in the auto-load harness and pin the widened recipe toast

* Studio: ignore a --device the gpu_ids pin stripped when deciding the split is the user's

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
On a Mac, the merged and base Hub pushes uploaded the whole save folder: export_metadata.json with the absolute path of the source checkpoint, leftovers from an earlier export to the same folder, and an unticked Private switch made an existing private repo public. Both pushes now open the repo like every other Unsloth Studio push, skip the local metadata, and upload a clean second save when the folder was reused.
Open the More menu only on click. Hovering the row no longer opens it, and the pointer override that kept the tooltip from closing is gone, so the tooltip no longer covers the open menu. The tooltip also stays closed when the menu returns focus to the row after a choice, so no label is left next to the collapsed sidebar. Hover and keyboard focus still show the label.

Render the sidebar resize edge only while the sidebar is expanded. A collapsed sidebar no longer shows the border highlight or the expand and resize tooltip on hover. The expanded edge still resizes and collapses as before, and the desktop app's edge strip is unchanged.

Update the More menu tests for click-only opening and add a test that a collapsed sidebar renders no resize edge. The full frontend suite, TypeScript checks and the desktop contract tests pass.
* Keep earlier messages when you send audio

* Drop the reply to an earlier recording along with it

* fix(studio): keep earlier voice and image-only turns in audio-input history

An earlier recording or picture sent without text replays as an empty user turn. Dropping it together with its reply meant a voice-only conversation still lost every earlier exchange; the reply is kept, with the empty turn, as the GGUF path already does. Turns after the newest user turn are left out, as before the branch, and a recording turn whose text is only whitespace is captioned with the transcribe default on MLX, as the structured CUDA render already appends it.

---------

Co-authored-by: Lyxot <[email protected]>
Chat images are now turned the way their EXIF orientation says before they reach the model (GGUF, transformers and MLX), using the same rule image editing already follows. Untagged images are still sent byte for byte. A tagged JPEG is re-encoded with its source quantization tables and subsampling.
…nto it (#6741)

* Studio: stop the llama.cpp graph-scheduler abort reload loop and harden CPU-only / multi-NUMA GGUF inference

On a CPU-only host, large MLA / sparse-attention / MTP GGUFs (e.g. GLM-5.2) abort in
llama.cpp's graph scheduler (GGML_ASSERT(*cur_backend_id != -1) in
ggml_backend_sched_split_graph) because the backend cannot run an op in the graph.
Studio showed a generic "invalid GGUF or out of memory" message and, since a startup
crash 500s the load, the UI replayed /load and re-read the whole model (hundreds of GB)
into the same crash on a loop while sitting at 99%.

Changes (all in studio/backend):
- Detect the scheduler abort, memo (binary, model) as non-retryable, and fail the next
  /load fast with an actionable message (mirrors the existing tensor-split memo).
- CPU-only safe defaults (user flags still win): --fit off (its estimator hits the same
  abort, llama.cpp #21932, and mis-counts MTP KV #23472/#24117), --flash-attn off, and
  an auto context capped to a RAM-aware ceiling.
- NUMA auto-interleave: wrap with numactl --interleave=all when the model overflows the
  largest node's free RAM but fits across all nodes.
- CPU RAM preflight warning when weights exceed available RAM.

GPU and Apple paths are unchanged. Adds unit tests for the classifier, the memo, the
NUMA decision, and the CPU-only command defaults.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: pair --numa distribute with numactl --interleave=all

Per llama.cpp multi-NUMA guidance (ggml-org/llama.cpp#19102), numactl
--interleave=all alone does not spread pages evenly across nodes; it must be paired
with --numa distribute. Add it when auto-interleave engages, unless the user already
set --numa.

* Studio: address review feedback on the CPU-only / NUMA hardening

- Emit --fit off explicitly on CPU. The flag defaults to on in recent llama.cpp, so
  setting use_fit = False only skipped --fit on and still ran the graph-reserve
  fitting step (same abort path) on the first attempt.
- Key the scheduler-abort memo per variant (model plus hf_variant / gguf_path) so a
  failed quant does not block trying a different quant of the same repo, which the
  error message itself suggests.
- Move the memo fail-fast guard ahead of _kill_process so a known-bad reload does not
  tear down a working server before returning the error.
- Floor the CPU context to the minimum when weights alone exceed the RAM budget, where
  the fit helper returns the requested ceiling unchanged and KV could OS-kill the load.
- Decide NUMA interleave on the resident footprint (weights plus KV at the capped
  context), not weights alone, so a model whose weights fit a node but whose footprint
  does not still interleaves.

Adds tests for each fix.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: address follow-up review on the abort memo and NUMA footprint

- Size the NUMA footprint KV estimate for the launched --parallel slots (it defaulted
  to n_parallel=1), so a multi-slot KV that overflows a node still triggers interleave.
- Include the launch settings (context, spec, extra_args) in the scheduler-abort memo
  key, so an identical replay stays blocked but changing -c, disabling spec, or picking
  a different quant (the recovery the error message recommends) is allowed to retry.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: tighten CPU-only detection and resident-footprint accounting

Follow-up review on the CPU-only / NUMA hardening:

- Treat a user-forced zero offload (-ngl 0 / --n-gpu-layers 0 / --gpu-layers 0)
  as CPU-only even when a GPU is visible, so the safe defaults (--fit off,
  --flash-attn off, NUMA interleave) and the RAM-aware context fit apply instead
  of a GPU launch that then runs on CPU and hits the graph-reserve abort.
- Size the CPU context fit against the fitted footprint (weights + compute
  buffer), not raw weights, so a context that only fits when the buffer is
  ignored can no longer slip through and get OS-killed at startup.
- Size the NUMA interleave decision against the full resident footprint
  (fitted weights + KV at the launched parallel slots + MTP reserve).

model_size_fit and the MTP reserve are bound before the fit try so the
GPU-selection except path cannot leave them unbound. New and updated unit
tests plus the offline simulation cover the zero-offload path and the math.

* Studio: refine CPU footprint accounting and defer the abort memo

Follow-up review on the CPU-only / NUMA hardening:

- Account for MTP memory in the CPU context fit. mtp_engaged alone is a no-op
  once budget_frac is set, so pass the byte-accurate MTP overhead fn; the cap no
  longer ignores the MTP draft KV.
- Fit auto contexts at or below the 32k ceiling too, not only above it, so a
  large small-context GGUF that still exceeds RAM is reduced toward the minimum
  instead of being OS-killed at startup.
- Recompute the NUMA footprint MTP reserve at the post-cap context; the pre-cap
  reserve overstated a capped million-token model and could skip a viable
  interleave.
- Surface the "interleave cannot help" decision (footprint exceeds total RAM
  across all nodes), not only the missing-numactl case.
- Defer recording the scheduler-abort memo until the text-only mmproj fallback
  is ruled out, so a vision model that recovers text-only is not blocked by the
  fail-fast guard on its next load.

Unit tests and the offline simulations updated and passing.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: respect explicit --numa and reorder the NUMA total-RAM check

Follow-up review on the CPU-only / NUMA hardening:

- Respect an explicit user --numa policy. Auto-interleave wraps the process with
  a numactl argv prefix the user cannot override, so when the user sets --numa we
  now skip the wrapper (and --numa distribute) instead of forcing interleaving
  over their placement.
- Check the total-RAM condition before numactl availability in decide_interleave,
  so a model too large for total free RAM gets the smaller-quant / free-memory
  guidance instead of being told to install numactl, which could never help.

Unit tests cover both cases.

* Studio: extend CPU-force detection, advertise the capped ceiling, gate MLA MTP

Follow-up review on the CPU-only / NUMA hardening:

- Detect --device/-dev none as a CPU-only launch too, not just -ngl 0, and treat
  the GPU-layers and device controls independently (each flag's last value wins).
- Lower max_available_ctx when the CPU cap reduces the launched context, so /status
  and the UI safe-zone advertise the real window instead of the unlaunched native
  size.
- Skip the MTP reserve in the CPU cap and NUMA footprint when Auto drops embedded
  MTP for MLA models (GLM-5.2/DeepSeek/Kimi); the launch emits ngram-mod there, so
  reserving a target-KV copy needlessly shrank the context. GPU paths keep the
  existing _mtp_will_engage.
- Stub structlog/loggers/httpx in the new CPU-default and NUMA test files so a
  dependency-light run can collect them, matching the existing abort test.

The two test files now pass in a pytest-only venv (the import previously failed on
structlog via loggers). Unit tests (44) and simulations pass.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: make CPU-default source assertions whitespace-insensitive

The formatter wraps long argument lines, so pin the MTP fit/footprint assertions
on whitespace-stripped source instead of an exact single line.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: reserve fallback MTP RAM, bound NUMA on smallest node, capture abort early

Follow-up review on the CPU-only / NUMA hardening:

- Reserve a flat MTP fraction in the CPU context fit when MTP engages but the draft
  KV cannot be byte-sized (mtp_overhead_fn is None): budget_frac otherwise skips the
  flat reserve, so the fit could pick a context that OOMs once the draft allocates.
- Bound the NUMA local-placement decision on the smallest node's free RAM, not the
  largest. The loader is not pinned, so first-touch may land on any node; interleave
  a footprint that fits only the larger node instead of gambling on placement.
- Capture the first launch's scheduler abort before the no-spec MTP fallback resets
  the stdout tail, then fold it into the terminal memo decision, so a fallback that
  fails for another reason does not drop the memo and let the UI replay the load.

Unit tests and the offline simulations updated and passing.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: cpuset-aware NUMA topology and env-forced CPU offload detection

Follow-up review on the CPU-only / NUMA hardening:

- Restrict the NUMA topology to the cpuset-allowed nodes (/proc/self/status
  Mems_allowed_list). numactl --interleave=all only spans those, so under a
  Docker/systemd cpuset that exposes the host's nodes but allows one, the
  decision no longer sums RAM the child cannot use and wrap a launch that OOMs.
- Honor env-forced CPU offload: _extra_args_forces_cpu_offload now also reads the
  inherited LLAMA_ARG_N_GPU_LAYERS / LLAMA_ARG_DEVICE the child would apply, so a
  GPU host running with LLAMA_ARG_N_GPU_LAYERS=0 or LLAMA_ARG_DEVICE=none gets the
  CPU-only safe defaults. CLI extras still win over the env.

Unit tests and the offline simulations updated and passing.

* Studio: trim comments in the CPU-only / NUMA hardening

* Studio: key the scheduler-abort memo on the whole load request

Toggling Tensor Parallelism, GPU placement or cache types now retries a load
that aborted in the graph scheduler instead of failing fast. The CPU context fit
also keeps the flat MTP reserve when the draft KV cannot be sized, matching the
GPU fit.

* Studio: only apply CPU-only launch defaults on a host with no GPU in play

A Metal Mac, a Vulkan build whose probe sees nothing, and an explicit GPU pick
all still run on a GPU, so they keep --fit and flash attention. A user zero
offload now flags CPU-only without bypassing the planner's host-RAM advisory,
and a stale --device none that a GPU pick strips no longer counts.

CPU flash attention off now flows through planned_flash_attn, so the KV and
compute estimates price the attention mode the child runs, and a quantized V
cache keeps flash attention on instead of being reset to f16.

* Studio: only wrap llama-server with numactl when it can set the policy

Docker's default seccomp profile refuses set_mempolicy without CAP_SYS_NICE, and
numactl then exits before exec'ing the server, so an oversized CPU-only load in
the container died instead of loading without interleave. Probe numactl once and
fall back to no wrap, naming --cap-add=SYS_NICE.

* Studio: keep flash attention on for CPU-only GGUF loads

Measured on a 2-socket Xeon with llama-server forced to CPU, 2450-token prompt,
5 alternating repeats: flash attention off cut prefill from 1461 to 611 tok/s on
Qwen3-0.6B Q4_K_M and from 145 to 122 tok/s on Qwen3-8B Q4_K_M, with decode
within noise. The scheduler abort it was meant to avoid reproduces with flash
attention off too, so CPU-only launches keep the managed default and only drop
--fit.

* Studio: read NUMA sysfs and /proc files as UTF-8

The repo's text-IO lint requires every read to name its encoding, since the
locale default is cp1252 on Windows.

* Studio: slim to the graph-scheduler abort fix

Keep only what the reported bug needs: recognise GGML_ASSERT(*cur_backend_id != -1),
say what it means, and fail fast on an identical reload instead of re-reading the
weights into the same crash. The same assert also fires when the model does not fit
in memory, so the message names both causes.

Drop the CPU-only launch defaults (--fit off, 32k context cap, RAM preflight) and
the numactl interleave: each changed behaviour for every CPU user without fixing
the abort, and the context cap shrank loads that fit. They can come back as their
own PRs with measurements.

* Studio: drop a banner comment in the scheduler-abort tests

* Studio: match only the scheduler split abort, and let a reload retry it

sched_reserve / graph_reserve frames appear in every reserve-time crash, so a CUDA
out-of-memory abort (GGML_ASSERT(err == cudaSuccess) under ggml_gallocr_reserve_n)
was reported as the scheduler abort and memo-blocked. Require the assert text or the
ggml_backend_sched_split_graph frame it fires in.

The same assert can mean the model did not fit, and freeing memory can make the
identical load succeed, so an explicit reload (force_reload) bypasses the memo;
automatic replays stay blocked.

* Tighten the scheduler-abort memo: other split_graph aborts, Hub cache hint, forced reload, text-only retry

* Key the scheduler-abort memo on the VRAM budget too

* Key the scheduler-abort memo on the Model Memory settings

* Trim comments

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…ng batches (#12207)

Inductor lowers a static query length below 128 to flex_decoding, whose
logsumexp gets a padded batch stride from comprehensive_padding. The
flex backward template indexes LSE as contiguous, so with batch > 1 every
row after the first reads a shifted LSE and the gradients blow up
(Qwen3.5 LoRA on B200: 550 non-finite LoRA grads at step 0).
…ls (#12236)

The GGUF admission count sent the estimate's "[image]" placeholder to llama-server, which rejects it as invalid base64; a failed count reserves the whole shared KV pool, so other chats waited. Media parts are now left out of the count and each image keeps its per-image allowance.

Fixes #12058
A tool call spawned with preexec_fn forks, and the child ran cleanup that waits on locks other threads held at the fork, so it never exec'd and the call stayed on Running. The child now leaves inherited chat-database connections and huggingface_hub's shared HTTP client alone.
… of ignoring it (#12243)

* Read remote image URLs on safetensors and MLX models

* Fetch only the image a single-image model reads

* Fetch only the user-turn images a multi-image model reads

* Ignore system and developer images in the non-GGUF fetch

* Skip the fetch when a single-image model will refuse the turn

* test(studio): expect remote image URLs to be fetched on the non-GGUF path

Two chat tests pinned the old behaviour, where a lone remote image URL on a safetensors model was dropped and the turn answered without it. One now uses a payloadless data URL to keep checking that a single unreadable part is not a multi-image call, and the other checks that an unfetchable URL is refused and closes the monitor row. Also cover a single-image model preferring the user's image over a newer assistant one.

* fix(studio): refuse a second image before fetching a remote one

On a single-image safetensors or MLX model, a turn with one remote image URL plus a distinct top-level image_base64 is refused as one image per message. The fetch ran first, so the caller waited on the image host and got the fetch error instead when the URL failed. Count the distinct legacy image in the pre-fetch check, as the refusal does.

* fix(studio): let auto-switch load a non-GGUF model for remote image URLs

The switch preflight treated a remote image as unreadable on a safetensors or MLX target: a remote-only request was refused with "Remote image URLs are not supported", and several remote images for a multi-image target were refused as one image per message. The chat path now fetches those URLs, so the same request was served by a resident model but refused when Unsloth Studio had to load it first. Drop the refusal and count https images as fetched when checking the target's image shape; a failed fetch is a 400 after the load, as on a GGUF target.

* chore(studio): use the generic label for chat remote image fetch logs

The chat fetcher now serves safetensors and MLX models too, so its log lines no longer name llama-server.

* test(studio): share setup across the non-GGUF remote image tests

Route every case through one helper for the scripted safetensors backend and the fetch stubs, and cover a developer-role image beside the system one.

* fix(studio): refuse an unfetchable image scheme before switching to a non-GGUF model

Loading a safetensors or MLX model for a request with an http:, file: or other non-https image URL evicted the resident model, and only the fetch after the load refused the scheme. Check the schemes of the images that model will fetch before the switch: the selected one, and on a multi-image model every user turn's. The fetch and the check now share one list of those parts.

* fix(studio): read the switch preflight's selected image as the fetch will

The non-GGUF switch preflight still took the selected image and the legacy-image clause of its multi-image check from the pre-fetch parse, which drops remote URLs. So an older malformed data URL behind a newer https image refused a request the loaded model would serve, and an assistant's https image beside a distinct image_base64 loaded the target before being refused as one image per message. Take both from the image the fetch selects.

* fix(studio): keep validating a distinct legacy image before a non-GGUF switch

When the image a non-GGUF target reads is a remote URL, the switch preflight stopped validating a distinct top-level image_base64, so a multi-image target loaded before a malformed one was refused. Validate it again in that case.

---------

Co-authored-by: Lyxot <[email protected]>
…ds (#12261)

* Composer attachments: first page previews, Library icons, lighter cards

* Attachment previews: parse only visible cards, reuse the attachment text decoder, respect MIME kind

* Attachment previews: unmount document previews once offscreen

* Attachment previews: parse at most two Office thumbnails at once

* Attachment previews: first PDF page only, queue text thumbnail reads

* Attachment previews: first slide only for presentation thumbnails

* Attachment previews: parse only the first slide and the opening of a DOCX for thumbnails

* Attachment previews: cap sheet parsing for spreadsheet thumbnails

* Attachment previews: cap the sheet tabs listed in spreadsheet thumbnails

* Attachment previews: queue PDF thumbnail loads, inflate only kept DOCX images

* Attachment previews: share one inflate budget across the DOCX thumbnail repack

* Attachment previews: no nested controls in thumbnails (sheet tabs as labels, no DOCX links)

* Attachment previews: Markdown thumbnails render links and task boxes as text

* Attachment previews: restore only image parts referenced by kept DOCX elements

* Attachment previews: follow the text adapter before binary document viewers

* Attachment previews: restore images in the notes kept DOCX paragraphs refer to
vLLM >= 0.24 raises ImportError at import under transformers < 5. The startup
GuidedDecodingParams fix imports vllm.sampling_params, so with transformers
4.57.x and a recent vLLM installed, import unsloth itself failed, even for SFT
or GRPO without fast_inference. disable_broken_vllm now also recognises that
refusal and disables vLLM with a warning, as it does for an ABI-broken build.
fast_inference = True then reports why vLLM is unavailable instead of asking
to install it.
* Fix fused LoRA dtype mismatch on fp32 activations into fp16/bf16 weights

The fused LoRA ops are decorated with @custom_fwd, which disables
autocast. When an fp32 activation (for example the fp32 output of
fast_rms_layernorm on an fp32 hidden/residual stream) reaches a fused
LoRA path whose base weight is fp16/bf16, nothing downcasts the
activation, so torch.matmul raises:

    expected mat1 and mat2 to have the same dtype: float != c10::Half

This is not torch-version specific; torch.matmul never auto-promotes a
mixed fp16/fp32 matmul.

Reconcile the dtypes at the matmul_lora choke point: after dequantizing
W (both the plain and the fast_dequantize branches, not the fp8 branch),
downcast X to the base weight compute dtype the way autocast would for a
plain Linear, and keep the LoRA A/B cast dtype consistent with it.

Keep the backward pass dtype-consistent: LoRA_MLP, LoRA_QKV and LoRA_W
now record the original input dtype in ctx.input_dtype, pin the saved
activation to the compute dtype, cast the incoming gradients to that
dtype, and cast the returned dX back to the original input dtype to honor
the autograd grad-dtype contract. Every added branch is a no-op when the
dtypes already match, so normal fp16/bf16/fp32 training is unchanged.

* Tighten fused-LoRA dtype-fix comments

* Avoid recomputing LoRA B-projected gradient in fused-LoRA backward

Each fused-LoRA backward computed dY @ B.t() (the LoRA-B projected gradient,
shape (batch*seq, r)) twice per projection: once for the A weight gradient and
once for the dX accumulation. Hoist it into a single temporary and reuse it in
both, removing 6 small matmuls per layer (3 in LoRA_QKV, 2 in LoRA_MLP, 1 in
LoRA_W). Results are bitwise identical; measured about 2 to 3 percent faster on
the LoRA forward plus backward for qkv and mlp in both 16-bit and 4-bit.

* Follow the produced output dtype in matmul_lora, not the base weight

Pinning the LoRA compute dtype to W.dtype regressed a case that works on
main: under autocast the base matmul produces `out` in the autocast dtype,
not W's, and `out.addmm_(XA, B)` for the LoRA term is in-place and so is
not autocast-eligible. An fp16 activation against a bf16 base weight under
fp16 autocast then raised

    RuntimeError: self and mat2 must have the same dtype, but got Half and BFloat16

Derive the LoRA operand dtype from `out` instead, which is the dtype the
base matmul actually produced in both regimes, and skip the activation
pre-cast entirely when autocast is on, since autocast reconciles the matmul
itself and pre-casting would only round the activation through a second
dtype. The autocast query sits behind the existing dtype comparison, so the
ordinary matching-dtype path does not pay for it.

Over the activation x base weight x adapter dtype x inplace x rows x
autocast product (1350 cells), against main: 612 cells that raised now run,
306 are bit-identical, 432 still raise (all of them an autocast dtype that
disagrees with the base weight, which the trainer already rejects at setup),
0 regressions and 0 cells whose values or dtypes moved.

tests/test_fused_lora_activation_dtype.py pins both halves: the fp32
activation case fails on main, and the autocast case fails on this branch
before this commit.

Also corrects three comments that said custom_fwd disables autocast. It does
not with cast_inputs=None; the mechanism is that in-place addmm_ and
matmul(out=) are not autocast-eligible.

* Reconcile base weights in the fused LoRA backward, and dequantize NF4 in fp32

Two defects the forward-side dtype fix exposed, both reproduced through the
public loader with FastLanguageModel.from_pretrained(dtype = torch.float32).

First, the backward passes dequantize the base weight in its own dtype and
then feed it to `torch.matmul(..., out = X)` and `dX.addmm_(...)`. Neither
form is autocast-eligible, so an fp32 base weight against a bf16 compute
dtype raised

    RuntimeError: expected mat1 and mat2 to have the same dtype, but got: c10::BFloat16 != float

_dequantize_to reconciles the weight at the six dequantize sites in
LoRA_MLP, LoRA_QKV and LoRA_W. It is a no-op whenever the dtypes already
agree, which is every ordinary fp16/bf16/fp32 run.

Second, with the crash gone, fp32 + load_in_4bit trained to a nonsense loss
(15.1 against 0.75 for the same model in bf16). fast_dequantize allocates
`out` with quant_state.dtype but dispatched the NF4 kernel two ways only,
fp16 or bf16, so an fp32 quant_state wrote bf16 bits into an fp32 buffer.
Measured against bitsandbytes' own dequantize_4bit, the error was 0.127 on
weights of magnitude 0.09. bitsandbytes exports cdequantize_blockwise_fp32_nf4;
binding it and making all three dispatch sites three-way takes that error to
exactly 0, and the loss to 0.7428 against 0.7427 for the same model in fp16.

That second one is a pre-existing bug on main, not something this PR
introduced. It was unreachable only because the crash above got there first.

Over the full kernel-level product (1350 cells) against main: 1044 cells that
raised now run, 306 are bit-identical, 0 regressions, 0 cells whose values or
dtypes moved.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Add the fp32 NF4 kernel to the bitsandbytes readiness probe

kernels/utils.py now binds cdequantize_blockwise_fp32_nf4 at module scope, and
tests/python/test_bitsandbytes_kernel_readiness.py asserts the probe list matches
those binds exactly. Without this the probe would also clear a wheel that cannot
serve the fp32 dequantize path.

* Query autocast with the torch device name, and fail open if it is rejected

DEVICE_TYPE is "hip" on ROCm and "mlx" on Apple Silicon, and torch's autocast
APIs accept neither:

    torch.is_autocast_enabled("hip")
    RuntimeError: unknown device type for autocast in get_autocast_dispatch_key_from_device_type

so the new probe turned the mismatched-dtype case, the one this branch exists
to support, into a crash on every ROCm box. DEVICE_TYPE_TORCH already maps hip
to cuda and mlx to mps.

"npu" is rejected too on a torch build without that backend registered, which
DEVICE_TYPE_TORCH does not remap, so the device name is resolved once at import
and falls back to "assume no ambient autocast" when torch will not take it. That
fails OPEN: matmul_lora reconciles the dtypes itself, which is the behaviour that
makes the mismatched case work at all, rather than erroring on the probe.

Resolving it once also keeps the query off the per-matmul path; what remains
there is a module-global lookup behind the existing dtype comparison.

The 1350-cell matrix is unchanged by this: 1044 fixed, 306 bit-identical, 0
regressions, 0 cells whose values or dtypes moved.

Reported by Codex.

* Let the autocast device-name test run on the CPU-only legs

The file was marked `gpu` module-wide, so every test in it was deselected on any
runner without an accelerator. That is the wrong way round for
test_autocast_probe_uses_the_torch_device_name: it is pure Python, and it is
exactly the check that needs to run on the non-CUDA platforms, since the defect
it pins (torch.is_autocast_enabled("hip") raising on ROCm) cannot show up on the
NVIDIA box the rest of the file needs.

Marking the three matmul tests individually instead: 7 passed / 1 deselected
under -m gpu, 1 passed / 7 deselected without it, where before it was 0 and 8.

* Keep the legacy zero-argument autocast probe for torch 2.1 to 2.3

`torch.is_autocast_enabled` only grew its device-name argument in 2.4, and this
repo still ships extras for older ones (cu118onlytorch211, cu121onlytorch220 and
siblings); this very file already branches on `Version(torch.__version__) <
Version("2.4.0")` for custom_fwd. The single try/except therefore caught the
TypeError on those versions and pinned the probe to "always disabled", so
matmul_lora would pre-cast the activation to the weight dtype and then let
autocast cast it again, changing results by that extra rounding.

Three tiers now, resolved once at import: the device-name form on 2.4+, the
zero-argument form on 2.1-2.3, and only if neither answers, fail open to
"assume no ambient autocast".

The 1350-cell matrix is unchanged: 1044 fixed, 306 bit-identical, 0 regressions,
0 cells whose values or dtypes moved.

Reported by Codex.

* Trim comments

* Cover the fused LoRA backward and fp32 NF4 dequant under mixed dtypes

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Move the dY @ B.t() reuse in the fused LoRA backward to its own PR

* Skip the fused LoRA kernels for float32 base weights instead of reconciling dtypes inside them

fast_lora.py and matmul_lora go back to main. patch_peft_model now leaves float32 models on
PEFT's own forward and says why in the patch summary. Inference keeps two fp32 fixes: NF4
dequantize uses bitsandbytes' fp32 kernel, and single-token decode skips the fp16/bf16-only
4bit gemv.

* Gate the fp32 LoRA fallback GPU tests on has_real_cuda

* Trim comments

---------

Co-authored-by: oobabooga <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
* Let the chat model use the Decision API through MCP

* Let managed accounts enable the Decisions MCP preset

* Stub the Decisions MCP names in the desktop health test

* Match a Decisions MCP row saved under another port

* Fix Decisions MCP validation and menu state

* Disable Decisions tools with the API

* Normalize Decisions loopback URLs

* Align Decisions auth and URL matching

* Classify mounted Decisions auth correctly

* Parse Decisions URL authorities

* Refresh Decisions state consistently

* Preserve raw Decisions URL paths

* Accept empty Decisions URL ports

* Align Decisions URL port parsing

* Hide disabled Decisions tools from discovery

* Ignore parser-stripped URL whitespace

---------

Co-authored-by: Maheswar Kumar <[email protected]>
Co-authored-by: mahiatlinux <[email protected]>
… scaling (#12193)

* Average GRPO gradients across DDP ranks and keep MiniCPM3's pre-head scaling in the hidden-state fallback

* Reduce oversized GRPO gradients in place and give the extracted wrapper tests the new helpers

* Free the rejected hidden states before GRPO re-runs the forward for full logits

* Trim comments

* Look up the GRPO pre-head divisor once per model instead of per forward
* Add Qwen2.5 Coder model support to registry and chat templates

* Register Qwen2.5 Coder meta directly in its registry test

* Use the Qwen2.5 Coder Ollama modelfile for the coder chat template aliases

* Accept the qwen-25-coder spelling for the Qwen2.5 Coder chat template

---------

Co-authored-by: Samama Farooq <[email protected]>
* Do not fail a cached dataset load on a bookkeeping write

load_cached_hf_dataset calls mark_app_processed_dataset_cache_complete right
after the dataset has already loaded, uncaught. That call raises in ordinary
situations:

  cache purged mid-load (the user deletes the dataset cache) -> FileNotFoundError
  studio cache root gone                                     -> OSError
  read-only volume or full disk                              -> PermissionError

Probed against a real cached snapshot in an isolated studio home: with the entry
directory read-only the load raises PermissionError, and the identical load with
it writable returns 51760 rows. The data was fine; only the metadata write failed.

The flag it records is advisory. Nothing outside dataset_processed_cache.py reads
`complete` back, and no load, inventory or deletion path gates on it. The blast
radius is not advisory though: FileNotFoundError and PermissionError both classify
as cache-artifact errors, so a normal start discards a good cached dataset and
re-downloads the whole thing from the Hub, while an offline start or a resume that
requires exact resources has no fallback and fails the run outright.

Make it best effort and log, matching how the rest of the module already treats
this cache -- _read_cache_entry, iter_app_processed_dataset_caches and
delete_app_processed_dataset_caches all swallow (OSError, RuntimeError, ValueError).

The new test fails with PermissionError without this change. tests/
test_dataset_cache_paths.py is 87 passed with it, alongside test_training_cached_start
(162), test_gguf_load_cache_reuse (40) and hub/tests/test_dataset_services (31).

* Keep unsafe processed-cache paths fatal when marking completion

Codex flagged that the new best-effort handler around
mark_app_processed_dataset_cache_complete swallowed the function's path
safety checks alongside its metadata write. Marking is the only
validation that runs after load_dataset, so it is what catches the cache
entry being swapped for a symlink, or resolving outside the trusted cache
root, in the window between prepare_app_processed_dataset_cache and the
completion write. Swallowing that handed back a dataset read from an
untrusted location.

Split the two concerns. mark_app_processed_dataset_cache_complete now
raises UnsafeDatasetCachePathError for the cases it can positively
identify as untrusted -- a root that is present but does not resolve
inside the trusted root, an entry escaping the root, and a symlinked
entry or cache dir -- and a plain FileNotFoundError for a root that is
simply gone. load_cached_hf_dataset re-raises the unsafe error and keeps
swallowing only the failures that mean "the bookkeeping write did not
land": purged entry, read-only studio home, full disk.

UnsafeDatasetCachePathError subclasses OSError, so existing callers that
catch OSError are unaffected. Security posture is unchanged from before
this PR for every unsafe case; only the benign write failures are now
non-fatal, which is the bug this PR set out to fix.

Adds two tests: a real symlink swapped in after prepare is reported as
unsafe, and an unsafe path still fails the cached load.

* Classify a symlinked cache entry before resolving it

Codex P2 on 84e2870. The symlink check sat after entry.path.resolve(strict=True),
so a symlink whose target is removed between the load and the completion marking
raised FileNotFoundError from the resolve, never reaching the check. The caller
reads that as "the entry was purged" and continues, which hides the swap the check
exists to catch.

Reproduced against a real cached snapshot in an isolated studio home: with
entry.path replaced by a dangling symlink, marking raised FileNotFoundError
(swallowed as benign) instead of UnsafeDatasetCachePathError.

Hoist the symlink classification above the strict resolve. Nothing else moves, and
the escape check still runs on the resolved path.

The new test fails with FileNotFoundError without this change. Suites at baseline:
test_dataset_cache_paths 90, test_training_cached_start 162,
hub/tests/test_dataset_services 31.

* Classify symlinked cache ancestors, not just the leaf

Codex P2 on bbc3741. The guard tested is_symlink() on entry.path and
entry.cache_dir only. When a hashed ancestor is swapped instead -- the repo-key or
hub-key directory -- is_symlink() on the leaf reports False, so a dangling ancestor
fell through to the strict resolve, raised FileNotFoundError, and the best-effort
caller read it as a benign purge. A swapped parent redirects the entry just as
effectively as a swapped leaf.

Reproduced against a real cached snapshot in an isolated studio home:

  dangling symlink at leaf        -> UnsafeDatasetCachePathError (already caught)
  dangling symlink at parent      -> FileNotFoundError (swallowed)
  dangling symlink at grandparent -> FileNotFoundError (swallowed)

_symlinked_component walks every component from the trusted root down to the target
and returns the first symlink, so all three now raise UnsafeDatasetCachePathError.
It returns None when the path is not lexically under the root, leaving that to the
existing escape check.

The new test is parametrized over leaf / parent / grandparent; the parent and
grandparent cases fail without this change. Suites at baseline:
test_dataset_cache_paths 93, test_training_cached_start 162,
hub/tests/test_dataset_services 31.

* Classify symlinked root ancestors as unsafe, not as a purge

Codex P2 on c20a711, the same class one level higher. _cache_root_is_present
tested only the snapshot-loads leaf. A dangling symlink at an ancestor inside
cache_root() -- hf-datasets, say -- leaves is_symlink() False on the leaf and
exists() False because it follows the broken parent, so a redirected root read as
a plain missing directory and the caller swallowed it as a benign purge.

Reproduced against a real cached snapshot in an isolated studio home, before:

  hf-datasets is_symlink   : True
  snapshot-loads is_symlink: False   (the leaf itself is not a link)
  snapshot-loads exists    : False   (follows the dangling parent)
  -> FileNotFoundError, swallowed

_cache_root_is_present now walks the components from cache_root() down to
snapshot-loads with the same helper used below the root, so any link in the chain
counts as present-but-unresolvable.

That closes the whole chain. Verified end to end, dangling symlink at:

  entry / repo_dir / snapshot-loads / hf-datasets -> UnsafeDatasetCachePathError
  genuine purge, no symlink anywhere              -> FileNotFoundError (benign)

The benign case matters as much as the unsafe ones: tightening this must not turn
an ordinary cache purge into a hard failure, so it has its own test asserting the
error is a plain FileNotFoundError and not the unsafe subclass.

Suites at baseline: test_dataset_cache_paths 96, test_training_cached_start 162,
hub/tests/test_dataset_services 31.

* Classify the configured cache root itself, and keep live symlinks working

Codex P2 on 2b2b177. The descendant walk started BELOW configured_root, so a
dangling symlink at the configured cache directory itself left every walked child
reporting is_symlink() False and exists() False, and the redirected root was again
read as a plain purge.

Classify configured_root before walking its descendants. That sets the trust
boundary explicitly: the configured cache root and everything under it is ours to
classify, and anything ABOVE it is the user's own filesystem layout, deliberately
out of scope.

This path only runs once resolution has already failed, so a cache directory
symlinked to another volume -- a legitimate and common setup -- resolves normally
and never reaches the classification. That is now pinned by its own test, because
the risk in tightening this repeatedly is breaking someone who moved their cache
off the system disk:

  dangling symlink at cache_root -> UnsafeDatasetCachePathError
  LIVE symlink at cache_root     -> marks completion normally

Suites at baseline: test_dataset_cache_paths 98, test_training_cached_start 162,
hub/tests/test_dataset_services 31.

* Narrow the best-effort completion write to the try/except and leaf checks

Drops the ancestor/root symlink classification layer per review. Unsafe
leaf symlinks and root escapes still raise; purges, read-only homes and
full disks now only log.

---------

Co-authored-by: Daniel Han <[email protected]>
# Conflicts:
#	.github/workflows/version-compat-ci.yml
#	pyproject.toml
#	tests/version_compat/test_trl_loss_normalization_contract.py
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: fcd711caf2

ℹ️ 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
danielhanchen merged commit c9570fe into pr/lift-transformers-cap Sep 29, 2026
127 of 133 checks passed
@danielhanchen
danielhanchen deleted the pr/lift-trl-cap branch September 29, 2026 18:32
danielhanchen added a commit that referenced this pull request Sep 30, 2026
The TRL lift (#11137) landed on this branch as one squash commit that also carried a snapshot of main from its own merges. Every file outside the two PRs' own changes now takes main's version; pyproject.toml, version-compat-ci.yml and the version_compat tests keep this branch's cap and floor-lane changes.
danielhanchen added a commit that referenced this pull request Oct 2, 2026
#11016)

* Lift the transformers ceiling to 5.17.0 and align the torch mirror

transformers<=5.5.0 was the ceiling, and 5.5.0 is exactly where the prequantized bnb-4bit
checkpoints lose quant_state on every Linear4bit (#9867, #10010, #10017, #10276): measured
352 of 352 on unsloth/Qwen3.8-27B-unsloth-bnb-4bit, with the reporters' own
"mat1 and mat2 shapes cannot be multiplied (10x5120 and 1x15728640)" on the forward. On
transformers 5.17.0 the same load is 0 of 352 and the forward returns logits. The ceiling
also put the Gemma 4 E4B LoRA fix one patch release out of reach, since that shipped in
5.5.2 (#5355).

Raise the cap at both pyproject sites, keeping every != exclusion, and move the CI lanes
that mirrored it:

- studio-backend-ci.yml installed 'transformers>=4.51,<5.5' in two jobs, which had drifted
  BELOW the published ceiling: it excludes 5.5.0, the release every user resolved.
- notebooks-ci.yml installed '<5.6' while notebooks in unslothai/notebooks pin 5.10.1,
  5.15.0 and 5.15.1, so the API surface it dumps came from a release those notebooks
  never run on.
- studio-export-capability-ci.yml installed 'torch>=2.4,<2.13', which excludes the torch
  unsloth_zoo now admits.

version-compat-ci.yml gets the two ends of the range it was missing. zoo-imports-under-spoof
and grpo-fake-run each become a two-lane include matrix: a floor lane (py3.10, torch 2.6.0,
transformers 4.57.6, TRL 0.22.2, PEFT 0.18.0) and a latest lane that pins nothing. A new
torch-free cap-site-consistency job runs the window-drift assertions on ubuntu, windows and
macos. tests/version_compat/test_transformers_pinned_symbols.py gains v5.15.0 through
v5.17.0.

Studio's single-env keeps transformers==5.5.0. That pin is not this cap: it is the version
the pinned installer ships, locked in step with a tokenizers window transformers enforces
at import, and widening only the darwin override reproduces the Apple Silicon failure its
comment documents. The comment now says so.

Evidence: the whole 4.57.6 plus 5.0 to 5.17 sweep, and a real 27B bnb-4bit load on both
sides of the old ceiling.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Install torchcodec and hf_transfer where the two new lanes need them

Both new version-compat lanes went red on their first run and both reasons are
about what the lane installs, not about the cap.

torchcodec carries a compiled extension linked against one libtorch build, and
torch on these lanes comes from the CPU index. Listed in the package step it was
taken from PyPI, where the wheel is the accelerator flavour, and next to a
torch 2.14.0+cpu it cannot dlopen. unsloth then does what it is supposed to do
and disables it, seating the sys.modules absence sentinel, after which
datasets 5 answers any Dataset.from_dict with

    ModuleNotFoundError: No module named 'torchcodec.decoders';
    'torchcodec' is not a package

and the GRPO lane fails during collection. Moving it back onto the torch install
line, which is where it sat before this branch split the lanes, lets pip prefer
the matching +cpu build. Verified in a clean venv: torch 2.14.0+cpu with
torchcodec 0.16.0+cpu imports torchcodec.decoders and builds a Dataset, the same
pair with PyPI torchcodec 0.16.0 is what CI hit. The floor lane's 0.2 row is not
published on that index at all, so the extra index still serves it from PyPI.

hf_transfer is a declared unsloth_zoo dependency and the zoo is installed here
with --no-deps, so the lane has to supply it. unsloth sets
HF_HUB_ENABLE_HF_TRANSFER=1 around from_pretrained, and the huggingface_hub 0.x
that the floor lane's transformers 4.57.6 pulls raises instead of falling back
when the package is absent, which took out 45 tests.

* Keep the pip cache names literal in the two new matrix jobs

tests/studio/test_pip_cache_naming.py reads the workflow as text and requires
every pip-cache-restore name to be lowercase letters, digits and dashes,
because it goes into the cache key verbatim and the janitor groups on it. The
two new include matrices named the cache after the matrix slug, which the
action itself would have accepted at run time but which fails that lint, and
took the workflow-trigger lint job down with it.

The per lane name was not needed anyway. The key already carries the
interpreter, pip-v2-name-os-arch-pyMINOR-hash, and the two lanes are python
3.10 and 3.12, so they cannot overwrite each other's wheels. Both names are
back to the literals they had before the split, with the reasoning written next
to them and a note that two lanes sharing one python would need the job split
instead.

tests/studio/test_pip_cache_naming.py: 116 passed, and 1 failed 115 passed
without this change.

* Trigger the version-window drift job on every cap file it scans

* Run the floor lane on the declared minima, and scope the pin exception to one requirement

* Pin the GRPO floor lane to the declared TRL and transformers minima

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim the comments in the files this PR touches

Delete-first pass over the changed files: collapse multi-line rationale to
one line, drop measured numbers, section banners, spacer lines and
restatements of the code. Comments, docstrings and whitespace only, AST
gated; no behaviour change.

* Trim the export-capability workflow comments too

* Read the transformers compat matrix from PyPI instead of pinning it

This suite exists to say which versions the cap may be lifted to, so a hand-maintained
tag list answers for the day it was edited. It now takes every minor at or above the
4.57.6 floor, latest patch of each, the same way tests/vllm_compat does for vLLM.

One tag per minor keeps the matrix bounded as upstream keeps releasing. A patch that
broke something specific earns its place in _ALWAYS rather than a blanket every-patch
sweep: 5.5.0 is the old ceiling and still the Apple Silicon cap, 5.16.0 first required
tokenizers>=0.23.1. Yanked, rc, dev and post releases are skipped, since pip will not
install them.

_TAG_OVERRIDES carries the one place upstream disagrees with itself: PyPI 5.10.4 is
tagged v5.10.3. A frozen fallback list covers an unreachable PyPI, so a network failure
cannot quietly shrink the matrix to nothing and report green.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep the load bearing tags when PyPI cannot be read

* Anchor the matrix to the ceiling pyproject declares

* Resolve the matrix once so every xdist worker collects the same one

* Anchor the patch releases the notebooks pin

* Import the declared ceiling, and let the unpinned lane be a canary

* Give the ceiling lane its own pip cache key

* Anchor the shared matrix too, and derive the ceiling tag through the override table

* Split the PyPI-tracking matrix out of the cap lift

The dynamic matrix, its anchors and the CI lane restructure move to their own PR.
This branch keeps the cap lift, the four cap sites, the drift gate and a static tag
list that covers the window the cap opens: 4.57.6 and every 5.x minor through the
declared ceiling v5.17.0, plus the v5.10.1 and v5.15.1 pins several notebooks carry.

* Raise the transformers floor to 4.52.4, which is the oldest one that imports

The declared floor was transformers>=4.51.3 beside peft>=0.18.0, and that pair
cannot import: peft declares no transformers floor of its own, and peft 0.18.0
imports GradientCheckpointingLayer from transformers.modeling_layers at
peft/tuners/lora/model.py:26, a module that first exists in transformers 4.52.0.
pip resolved it happily and import unsloth then raised ModuleNotFoundError.

4.52.4 rather than 4.52.0 because 4.52.0 through 4.52.3 were already rejected by
name; those exclusions are now dominated by the floor and drop out.

Measured, not inferred: the floor lane's import set was run at 4.51.3 (5 failed,
21 passed, matching CI exactly), 4.52.0, 4.52.4, 4.53.1 and 4.54.1 (34 passed
each), so modeling_layers was the only missing piece.

tests/test_transformers_cap_sites.py grows the mirror of its ceiling gate:
TESTED_FLOOR, a check that both version-compat floor lanes pin the declared
floor, and a negative control that the window still refuses 4.51.3.

test_trl_loss_normalization_contract.py checked DPO with hasattr, which has been
false since trl 0.21 declared loss_type with a default_factory, so that half was
skipped on recent TRL and wrong at the floor. DPO and KTO are now compared to
pristine TRL, whose values are version-dependent, while GRPO stays the literal
bnpo that rl.py deliberately pins.

* Let the TRL floor lane's training tests run at the declared floor

The lane's two loaders passed dtype = torch.float32 to from_pretrained. That
kwarg is rejected at the transformers 4.52.4 floor, where from_pretrained
forwards it into the model constructor, so 45 tests died with
TypeError: LlamaForCausalLM.__init__() got an unexpected keyword argument 'dtype'
the moment the lane could import at all. torch_dtype spans the window but is
deprecated from 4.57.6 on, so neither literal is safe: load with neither kwarg
and cast after, asserting the parameter dtype really is float32 so the cast
cannot silently no-op.

tests/version_compat/test_no_dtype_kwarg_at_load.py keeps it that way, an AST
scan of every test in the directory for a dtype or torch_dtype kwarg on
from_pretrained, with five parametrised controls including a dtype kwarg that is
not a load at all.

test_pristine_trl_config_without_max_seq_length_still_truncates asserted a
precondition it cannot control: the regression only exists on a TRL that dropped
max_seq_length, and trl 0.18.2 still declares it. It skips with that reason now,
the same way the file already skips an unreachable hub.

* Add the call-site guard that keeps a dtype kwarg out of these loaders

An AST scan of tests/version_compat for a dtype or torch_dtype kwarg on
from_pretrained. Neither spelling holds across the declared transformers window:
dtype raises TypeError at the 4.52.4 floor and torch_dtype is deprecated from
4.57.6 on, so the durable rule is to load without either and cast the result.
Five parametrised controls, including a dtype kwarg that is not a load.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Require the unsloth_zoo release that carries the same transformers ceiling

pip intersects unsloth's transformers window with unsloth_zoo's own, and
published unsloth_zoo 2026.9.4 still says transformers<=5.5.0, which is exactly
the cap this PR lifts. Without a matching zoo floor the lift is advertised and
not delivered.

Move the declared zoo floor to the first release expected to carry the lift and
add a gate: with the floor back at 2026.9.4 the new test fails, naming the
intersection.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read the tightest upper bound, and keep the exemption list honest

_ceiling took max over the upper bounds, so raising a cap by adding a bound
without removing the old one (<=5.17.0,<=5.18.0) reported 5.18.0 while pip still
resolved at 5.17.0. Take the tightest bound instead, with < beating <= at equal
versions.

PINNED_BY_DESIGN carried a placeholder for a requirement no lane spells. That is
not documentation, it pre-authorises that exact string: reintroduce
transformers<=5.5.0 in that workflow and the scan finds it and then skips it. The
dict is empty now, and a new test requires every entry to match a requirement a
lane really spells today.

* Hold the unsloth_zoo floor at 2026.9.4 until the matching release ships

unsloth_zoo 2026.9.5 does not exist on PyPI; 2026.9.4 is the newest
published release. `unsloth_zoo>=2026.9.5` is therefore a floor no release
satisfies, which makes unsloth uninstallable rather than merely
under-delivering the lifted transformers window, and it blocks this PR.

Revert the three pyproject sites to 2026.9.4, which is what main carries,
and rewrite the comment above the floor so it no longer contradicts the
pin: it now says the floor is held here and names what still needs the
newer zoo.

The gate that asserts the floor is deferred rather than deleted, so it
stays the reminder to raise the pin later.
ZOO_FLOOR_WITH_LIFTED_TRANSFORMERS_CAP is None, the test skips with a
reason naming unslothai/unsloth-zoo#1227, and setting the constant to the
release that ships #1227 re-enables it in one edit. The half of that gate
that does not depend on which release the floor names, that there is
exactly one zoo floor and that it is a real lower bound, still holds at
2026.9.4 and is split out into test_pyproject_declares_one_unsloth_zoo_floor,
which keeps running.

Known and accepted while this stands: pyproject advertises transformers up
to 5.17.0 while the resolvable zoo still caps it at 5.5.0, so the lift is
declared but not yet delivered.

* Track PyPI for the transformers compat matrix (#11136)

The static tag list answers for the day it was edited. This reads the releases from
PyPI, keeps one tag per minor to stay bounded, and merges the anchors no automatic
rule can derive: the floor, the old Apple Silicon ceiling, the tokenizers breakpoint,
the patch releases the notebooks pin, and the ceiling pyproject itself declares.

Six failure modes found in review, each with a named test and each mutation proven:
a fallback that dropped the anchors, a ceiling anchored to a literal, xdist workers
collecting different matrices, a later patch evicting a pinned one, two CI lanes
minting one pip cache key, and the shared matrix file bypassing the anchor merge.

The CI lane restructure comes with it, since the matrix is what it feeds: floor,
ceiling and latest on three interpreters and so three cache keys, with latest marked
non-blocking because resolving outside the declared window is its job.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Raise the unsloth_zoo floor to 2026.9.5

Main moved to 2026.9.5 in #11210, so this branch's 2026.9.4 was a
regression against main. 2026.9.5 also settles the second of the two
reasons the floor was tracked: it carries the generated-sentinel fix
(unslothai/unsloth-zoo#1259). The transformers half stays outstanding,
since 2026.9.5 still declares transformers<=5.5.0 pending
unslothai/unsloth-zoo#1227.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Make the zoo deferral expire by itself instead of on a hand-written constant

Codex raised (P1) that `unsloth_zoo>=2026.9.5` still admits a zoo whose own metadata
says `transformers<=5.5.0`, so pip intersects the widened range back down and users
keep resolving 5.5.0. That is correct, and it is measured: enumerating all 230
published transformers releases, this branch widens the unsloth side by 26 cells, but
the range a user actually resolves (ours intersected with published unsloth_zoo
2026.9.5) moves by 0 newly admitted cells. 229 of 230 cells are identical and the one
that moves is 4.51.3 becoming rejected, which is the floor fix.

The requested remedy cannot be applied here. Raising the unsloth_zoo floor to the
release carrying unslothai/unsloth-zoo#1227 requires that release to exist, and it does
not; a floor no published release satisfies makes unsloth uninstallable, which is why
the floor never leads the release. That reasoning is already in the comment above the
floor and in the deferred gate's docstring.

What was genuinely wrong is the shape of the deferral.
`test_the_declared_zoo_floor_can_supply_the_declared_transformers_window` skips while
`ZOO_FLOOR_WITH_LIFTED_TRANSFORMERS_CAP` is None, and that constant is hand-written, so
on the day #1227 ships nothing turns red: the gate keeps skipping and the floor keeps
naming a zoo that caps at 5.5.0 for as long as nobody looks. That is "a site left
behind after the window moves does not go red", which is the failure this whole file
exists to catch, reproduced inside its own deferral.

`test_the_zoo_deferral_expires_when_the_zoo_release_ships` closes it. It asks PyPI what
the newest published unsloth_zoo allows and fails only on POSITIVE evidence that the
deferral is obsolete, naming the release to pin and the constant to set. No network, a
timeout, a malformed answer or a zoo with no readable ceiling all leave it skipped, so
it can never go red by failing to reach PyPI. That preserves the property that put this
suite on the three-OS cap-site job: offline runs stay honest.

Verified in all three directions rather than by reading:
  shipped zoo (2026.10.1 admitting 5.17.0) -> fails, message names the release
  PyPI unreachable                         -> Skipped, never a failure
  live PyPI today                          -> zoo 2026.9.5 caps 5.5.0 < declared 5.17.0,
                                              so the deferral correctly stands
Suite is 25 passed, 1 skipped.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Start the symbol matrix at the declared floor, and anchor the release with no tag

Codex raised (P2) that `_FLOOR` was a literal 4.57.6 while this PR moves the declared
floor to 4.52.4, so `_release_tags()` discarded every 4.52 through 4.56 release and the
matrix could stay green while a source-pattern or symbol dependency broke supported
users. Confirmed: the floor was the only hardcoded end of the window in this file, since
the ceiling is already read from pyproject through `_CAP` for exactly this reason.

`_FLOOR` is now derived the same way, by `_declared_floor()`, taking the LOWEST `>=` in
the file so a marker-gated half declaring a higher floor cannot raise it and hide
releases the other half still admits. A bad read falls back to 4.52.4 rather than
widening the matrix to every release ever published.

Widening it turned up a real defect, which is the point of having done it. On the first
run 4.54.1 failed five checks, all on the fetch rather than on a symbol:

    v4.54.1: src/transformers/trainer[.py|/__init__.py] both missing

4.54.1 is on PyPI and inside the window, but upstream never pushed a v4.54.1 tag. The
only 4.54 refs are v4.54.0 and v4.54-release. Checked directly rather than assumed:

    v4.54.1  tag ref                  HTTP 404
    v4.54.0  __init__ __version__     4.54.0   (so it is NOT this release)
    v4.54-release __version__         4.54.1   (trainer.py HTTP 200)

so the entry is `"4.54.1": "v4.54-release"`, the same shape as the existing 5.10.4 entry
and for the same documented reason. `_sort_key` now resolves a tag back through the
override table before parsing it, since a tag whose name is not a version string has to
sort by the release it carries.

With both changes the matrix runs 4.52.4 through the ceiling: 523 passed, 9 skipped,
against 506 passed, 21 skipped and 5 failed when the floor was widened alone.

`test_the_matrix_starts_at_the_declared_floor` keeps it from drifting back. Mutation
proven: restoring the 4.57.6 literal turns it red on 23 of 28 tags, and the restored
tree is 28 passed.

* Start the outage fallback at the declared floor too

Codex raised (P2) that deriving `_FLOOR` fixed only the live path: `_TAGS_FALLBACK` is a
separate frozen list and still began at v4.57.6, so any PyPI failure dropped every 4.52
through 4.56 check and CI could go green straight through a regression at the low end
this PR newly supports. Correct, and it is the same defect as the one just fixed, one
code path over. `_ALWAYS` does not cover it either: those anchors are the Apple Silicon
ceiling and the tokenizers breakpoint, both 5.x.

The fallback now starts at the declared floor, one tag per supported minor below the old
start: v4.52.4, v4.53.3, v4.54-release, v4.55.4, v4.56.2. 4.54 goes in under its real tag
for the reason `_TAG_OVERRIDES` already records.

`test_the_outage_fallback_reaches_the_declared_floor` holds it there under a simulated
outage, asserting both that the oldest tag reached is at or below the declared floor and
that no supported minor between 4.52 and 4.56 is missing, so restoring one tag while
dropping the rest does not pass. Mutation proven: putting the fallback back to a
v4.57.6 start turns it red, restored is 2 passed. Full suites 577 passed, 10 skipped.

* Keep the ceiling lane inside the declared datasets window, and compare zoo bounds by membership

Two P2 items from the last review, both genuine.

The ceiling lane installed `datasets` bare. Both checkout installs in that job use
--no-deps, so pyproject's `datasets>=3.4.1,!=4.0.*,!=4.1.0,<4.4.0` never reaches the
resolver and the bare name takes the newest release, which is datasets 5 today. A
blocking lane whose purpose is to isolate compatibility with the transformers ceiling
would instead fail on a datasets release the project does not support. It now carries the
declared window verbatim, as the floor lane already does. The `latest` lane stays bare on
purpose: resolving outside the window is that lane's entire job.

The second is a bug in the deferral-expiry check added earlier in this PR.
`_newest_published_zoo_transformers_ceiling` recorded `<` and `<=` alike as a bare
ceiling Version, so a future zoo declaring `transformers<5.17.0` would have been read as
covering this project's `<=5.17.0` window and expired the deferral on a release that
still cannot resolve our ceiling. It now keeps whole SpecifierSets and asks whether the
declared ceiling is a MEMBER of the published zoo's window, which is the actual question.

Verified both directions against the case named in the review:

    zoo `>=4.52.4,<5.17.0`   -> deferral correctly STANDS, no false expiry
    zoo `>=4.52.4,<=5.17.0`  -> correctly fails, naming the release to pin

Suites are 577 passed, 10 skipped.

* Let the GRPO left-pad probe resolve at the declared TRL floor

The injected probe tried has_images and fell back to images with no third
branch. TRL 0.18.2 and 0.19.1 bind neither name in
_generate_and_score_completions and have no vision path at all, so the
fallback raised NameError out of the except handler and took GRPO
training down at the bottom of the declared window. 0.20.0 through
0.23.1 bind has_images, 0.24.0 and up bind images.

Resolve a text-only flag through all three cases, then compute the pad
once. tests/version_compat/test_grpo_left_pad_probe_at_the_floor.py
executes the rewritten function against each binding shape and
re-derives the table from upstream sources, and is wired into both GRPO
fake-run lanes.

Also names tests/version_compat/test_no_dtype_kwarg_at_load.py in the
pinned-symbol matrix, which is what test_version_compat_bundle.py asks
of every suite that exists.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Resolve the GRPO importance sampling level at the declared TRL floor

The rewritten compute_loss read self.importance_sampling_level
unconditionally and passed it to both the no-grad and the gradient loss
path. That attribute is GSPO's and arrived in TRL 0.20.0, as a
GRPOConfig field the trainer copies onto itself. 0.18.2 and 0.19.1 have
neither the field nor the attribute, so GRPO training died in the first
training_step at the bottom of the declared window:

    AttributeError: 'UnslothGRPOTrainer' object has no attribute
    'importance_sampling_level'

Read off upstream rather than inferred: grpo_trainer.py binds
self.importance_sampling_level 0 times at 0.18.2 and 0.19.1, and 5 or
more from 0.20.0 on, with grpo_config.py matching.

Resolve through the trainer attribute, then the config field, then
'token'. The fallback is not invented: 'token' is the default TRL's own
field declares, it is what unsloth_zoo's grpo_compute_loss already
defaults to, and 0.18.2 has no sequence level path at all. Versions
that bind the attribute are unaffected, since it is found first.

tests/version_compat/test_grpo_importance_sampling_level_at_the_floor.py
execs the real rewritten source and captures the level the loss
actually receives, over both loss paths and all three binding shapes,
and re-derives the upstream table so a future TRL that moves the knob
fails here rather than in a training loop. Mutation checked: reverting
either call site turns 4 of 7 red, and the 3 that stay green are the
arms the bug never touched.

Second of this family, after the left-pad probe. Same shape: injected
source assuming a TRL binding the floor does not have.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Supply the Docker Hub credential the way the workflow now takes it

Both harnesses handed the step its key by replacing `${{ secrets.DOCKER_API_KEY }}`
in the `run:` body. The key has since moved into the step's `env:` block so it is
never a command-line argument, which means that replace matches nothing: the body
builder died with KeyError, curl was handed an empty request, and the step still
exited 0 because the failure was inside a pipeline. The stub also logged only
"$*", and the auth body is passed on stdin via `--data-binary @-`, so the
identifier could not be observed even when it was sent.

The harnesses now set DOCKER_API_KEY in the environment and the stub appends the
stdin body to the log, only when curl was actually told to read stdin. Both halves
are load-bearing: removing either one fails the assertion again.

The workflows themselves are correct and unchanged; an empty token is caught by
their own `-z "$TOKEN"` check. This was the test harness drifting behind them.

A new test in each file pins that the step takes DOCKER_API_KEY from `env:` and
keeps no `${{ }}` in its body, so a rename fails loudly instead of quietly
returning these assertions to describing an empty request.

* Cut the comments in the files this PR authors

Opening comment-reduction pass over the five files this PR writes in full or
near enough. 422 comment lines to 342 across them, 26.9 percent to 23.0.
Long rationales collapse to the one fact that is not recoverable from the
code: the version tables, the traps each constant exists to avoid, and the
citations. Tracebacks and narration go, since the PR description carries them.

Files the PR barely touches are left alone. rl_replacements.py changes 27
lines of 3658 and test_trl_padding_free_max_length.py 21 of 3678; rewriting
their comments would grow the diff well past what a dependency cap lift
should contain.

Comment-only, AST-verified with comment_tools.py check: 5/5 code unchanged.

* Second comment sweep: delete the restating summary lines

Sweep one shortened, this one deletes. Each remaining paragraph docstring
loses the summary line that restated the test name, keeping the fact the
name does not carry. 342 comment lines to 301 across the files this PR
authors, 23.0 percent to 20.5; from 422 at the start of the pass.

Not taken to the 15 percent target: what is left is version tables, the
trap each constant exists to avoid, and issue citations, and cutting those
is the one outcome worth avoiding.

Comment-only, AST-verified with comment_tools.py check.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Skip the GRPO floor suites off-runner instead of erroring collection

Both files import the real rewriter, so unlike the cap-site suites they
cannot be file-only. On a runner without torch `import unsloth` raises its
own ImportError("Unsloth: torch not found"), and a bare module-scope import
turns that into a COLLECTION ERROR: the cross-platform staging run was red
on ubuntu, macos and windows for exactly this, having tested nothing.

pytest.importorskip does NOT cover this case, which is worth writing down
because it is the obvious first fix and it does not work: it skips a module
that is ABSENT and re-raises an ImportError the module body raised itself,
which is precisely what unsloth does here. Verified against a stub package
that raises ImportError on import: importorskip still ends in "1 error
during collection", the try/except ends in "1 skipped".

Both directions checked on the real files: with torch present all 13 tests
run, and against a stub unsloth that raises, both modules skip and the run
exits clean.

* Lift the TRL ceiling to 1.13.0 and gate the range that was already being tested (#11137)

* Keep more VRAM headroom on Windows CUDA, and say when a hand-set context does not fit (#11368)

* Stop a Windows host-RAM spill from looking like a healthy load

On Windows, cudaMalloc does not allocate device memory directly. It asks the
WDDM kernel memory manager, which treats VRAM and system RAM as one demand
paged pool, and since driver 536.40 an allocation past the end of VRAM
succeeds out of host RAM instead of returning out of memory. The load starts,
exits 0, answers /health, and nvidia-smi shows a healthy card, while decode
re-reads the spilled bytes over PCIe on every token.

Linux has no such path. The same allocation fails with "cudaMalloc failed:
out of memory" and llama-server exits, which is measurable: with 12 GiB free,
Qwen3-VL-8B at -c 65536 asks for 9216.00 MiB in one allocation and refuses to
start. That is why every rung of the spawn loop's recovery ladder is gated on
a non-zero exit code, and why the whole ladder is dead on the one platform
that needs it.

Three changes:

Raise the per-device reserve to 1024 MiB on Windows with a discrete CUDA
build, capped at an eighth of the card so it stays proportionate on small
GPUs. This is not a new magic number, it is the per-device margin llama.cpp's
own fitter keeps when nobody tells it otherwise, and where our estimate
carries all the risk we should be at least as conservative as the child would
have been. Linux and macOS budgets are unchanged, and the monotonicity
property in _vram_reserve_floor_mib still holds at every fraction.

After a full GPU pin comes up healthy, check that the load is actually
resident. Windows exposes the spilled bytes itself through the
'\GPU Adapter Memory(*)\Shared Usage' counter behind Task Manager's shared
memory figure, which nvidia-smi cannot see because on WDDM it reports
dedicated VRAM only. That counter is per adapter rather than per process, so
it is believed only when the device side independently shows the child short
of the weights plus KV cache that full offload must place on the card. Report
only, no recovery.

Warn when a hand-set context does not fit. The planner already prices this
correctly and already hands the load to --fit, but said nothing about why the
context was flexed. The notice also re-prices at q8_0 and mentions it when
that would make the configuration fit, rather than changing a user's cache
dtype for them.

Refs #11349, #11336

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim comments in the Windows sysmem fallback change

* Keep the residency check and context notice from making false claims

The residency check read only -ngl and --fit, so a user extra appended after the
pin that keeps weights or the KV cache on the host (--cpu-moe, -ot, -ncmoe,
-nkvo, --device none, or their LLAMA_ARG_ env twins) was reported as a host RAM
spill. The =-form overrides (--gpu-layers=10, --fit=on) were missed the same way.

The overcommit notice offered the Auto fallback anchor as the largest context
that fits when the weights alone overflow every GPU subset, so lowering the
context to that figure would still not fit. Only offer a context when one fits.

* Scope the residency check to CUDA builds, the loaded adapter and its own process

Arm only when the resolved build is CUDA: a Vulkan launch on an NVIDIA host has
no CUDA sysmem fallback and its ordinals are not NVML indices.

Read Dedicated Usage beside Shared Usage and count shared growth only on the
adapters whose VRAM grew across the spawn, so a display iGPU's churn on an
Optimus laptop is no longer booked as the model's spill.

Hand the verifier thread a snapshot of the armed state and the child it was
started for, and drop its result if that child has since been replaced.

* Check residency before the load returns, and keep its advice accurate

Run the residency check synchronously once the final child is ready, after
every post-health respawn, so the verdict describes the process that is
actually serving and reaches the load response. A warning written after the
response was never shown. The spill notice is appended to an earlier one
instead of losing first-notice-wins.

Offer q8_0 only when the cache is still f16, cap the counted adapters at the
number of pinned cards, key the sysmem-fallback cache by the resolved binary,
and use the Windows wording in the context notice only for CUDA builds.

* Gate the direct spill signal on a full card, and settle before re-baselining

The measured delta carries the CUDA context and compute buffers, so requiring
it to fall short of the weights+KV floor masked small spills such as the 74 MiB
case. WDDM only spills once dedicated VRAM is exhausted, so count shared growth
when a pinned card is nearly full instead.

Wait for a killed retry child's VRAM to settle before sampling the next
baseline, and price the q8_0 hint's compute scratch at q8_0.

* Report the measured spill, judge a full card by its own reserve, drop a stale notice

Name the counter's measured shared-memory growth as the spill amount on a
direct hit; the floor delta can be negative there, since it carries the CUDA
context and compute buffers. Treat a card as full below its proportional
sysmem-fallback reserve rather than a flat 1 GiB, so small cards are not
flagged. Publish the context overcommit notice only when the final plan still
hands the load to --fit on, since slot reduction can re-pin it.

* Word the context notice for planned offload, and tighten the spill report

The overcommit notice fires only once the load was handed to --fit on or a
spill plan, both of which place host tensors deliberately, so the Windows
driver-fallback wording and NVIDIA setting never applied there. Use the CPU
offload wording on every OS.

Sum only positive shared growth across pinned adapters, report spills under
1 GiB in MiB instead of rounding them to 0.0 GB, and key the fallback
classification by build revision so an in-place runtime update is re-read.

* Disarm the residency check on a KV layout change, skip the notice under -nkvo

A retry that respawns with a different slot count or unified-KV setting holds a
different cache than the floor was priced for, so disarm instead of comparing
against the stale floor. With KV offload disabled the cache stays on the host,
so the context overcommit priced from GPU KV bytes is not real.

* Do not cache an empty backend scan

_installed_ggml_backends returns an empty set for an unreadable lib dir instead
of raising, so the transient-failure rule has to cover that result too. Also let
the residency tests import their sibling harness when run on their own.

* Keep host-only tensors out of the residency floor, and tighten the notices

Subtract an untied token_embd (kept on the CPU at full offload) and MTP blocks
that do not load from the floor, by the same rules _unified_need_now uses, so a
healthy load is not flagged as a spill. Skip the context notice when the user
placed tensors on the CPU or fixed the layer count, offer q8_0 only when flash
attention is planned on, and name the executable actually launched in the
driver-setting advice.

* Trim comments added during review

* Drop the post-load residency check; keep the Windows reserve and the context notice

The spill detector could not be validated on Windows NVIDIA hardware and was most
of this change's size and risk. Keep the two parts that stand on their own: the
raised sysmem-fallback reserve on Windows CUDA builds, and the advisory when a
hand-set context does not fit. The backend classifier tests move to the reserve's
test file.

* Skip the context notice for an env-fixed layer count or at the native ceiling

An inherited LLAMA_ARG_N_GPU_LAYERS is a deliberate placement like the argv
flags. When the ceiling sweep stopped at the native context, a larger rope-
scaled window was never searched, so the largest context that fits is unknown.

* Skip the context notice when the user turns the fitter off

User extras follow the generated --fit on, so a trailing --fit off disables the
fitter and nothing moves layers to the CPU; the notice would claim otherwise.

* Register the q8_0 what-if in the split-rate call-site guard

* Trim comments in the Windows reserve change

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Unsloth Studio (AMD): keep export off a GPU PyTorch has no kernels for, like the iGPU (#11946)

* Studio: keep export off a GPU the installed PyTorch has no kernels for

* Trim comments restating the code

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Read the hot-path I/O cost at its steady minimum across repeats (#12029)

* Unsloth Studio: a companion fetch with no denoiser no longer blocks deleting its base (#11828)

A cached repo counts as needing a companion base only if it holds a runnable denoiser. The VAE-only fetch the native engine leaves in unsloth/Qwen-Image-2.1-FP8, and the default pre-cast fp8 text encoder a diffusers load caches at that repo's root, no longer pin Qwen/Qwen-Image-2.1 from a row the On Device list cannot act on. A prequant repo holding its DiT checkpoint still pins its base.

Fixes #11825.

* Studio: stop Python tool network calls from skipping the host allowlist (#11172)

* Studio: check the sandbox host allowlist for keyword, variable and aliased hosts in Python network calls

* Drop two sandbox comments that restate the code below them

* Keep resolving a network alias when the name is rebound elsewhere

* Rank network alias stores by the call they reach and ask on depth exhaustion

* Refuse a network target that is out of policy on any competing store

* Check a connect receiver that is a tracked client on any path

* Keep a valueless store unresolved instead of dropping it

* Read class-body names in source order and match only urllib3 calls that connect

* Check every candidate signature and scope attribute receivers to their owner

* Check the proxy and pool entry points urllib3 exports

* Carry unpacked values to the target they bind

* Memoize alias resolution so a branching chain stays linear

* Ask when alias resolution gives up on the callee

* Expand conditionals so every branch of a target is checked

* Let an unconditional rebinding replace the value a later read sees

* Check session and pool request methods, and only supersede on a certain binding

* Keep the enclosing binding when a class store may not run

* Take each client method's URL position from its real signature

* Check client base URLs, parameter defaults and self-referential stores

* Resolve prebuilt requests and check explicit proxy destinations

* Cover OPTIONS and the modules these APIs are actually defined in

* Resolve a client kept on an attribute

* Follow base classes, cover session uploads and websockets, drop the quadratic scan

* Make a binding take effect at the end of its statement

* Resolve a walrus callee to the callable it assigns

* Apply the literal-target fallback only to listed entry points

* Only read a call result as its constructor when that names a known client

* Cover raw urllib3 connections, renamed receivers and disabled proxies

* Treat the lowercase session factory and aiohttp's request helper as entry points

* Resolve constant getattr dispatch and cover aiohttp uploads

* Check the payload where a request is built

* Bind a definition name after its header runs

* Keep the stores that resolved when a sibling store hits a cycle

* Resolve a connect receiver with the same resolver as every other callee

* Put a client's connect in the target table and stop reading stores that have not run

* Generate the urllib3 URL factory specs from the module that defines each

* Keep source order inside the body that does the reading

* Check the encoded pool helpers and a proxy set on the session

* Give attribute stores the same reaching rule as name stores

* Tie a receiver's attributes to the binding in effect at the call

* Parse the URL the client will send, and follow a mutated proxy mapping

* Sequence a finally block with the statements that follow the try

* Key attribute stores on the whole receiver path

* Read attribute stores under the dotted paths they are recorded with

* Port client, proxy and SSH egress coverage onto the alias screen from main

* Trim comments on the ported egress tables

* Track annotated assignments, share proxies across client copies, skip static methods

* Treat local client subclasses as the client, and follow aliased proxy mappings

* Read base_url stores on a client and in-place proxy merges

* Scope client destination attributes to the client that reads them, and cover asyncssh.connection

* Resolve network submodule paths to the names their package re-exports

* Read a proxy without a scheme as a host

* Skip mapping keys and None destinations

* Skip no_proxy entries in proxy mappings

* Screen uploads through httpx stream, and follow clients passed to local functions

* Track subclasses of connecting classes, and read httpx transport proxies

* Follow clients passed to local methods

* Propagate clients along every recorded copy, and bind unbound method calls

* Track clients bound by loop and comprehension targets

* Follow clients returned by local factories, and link helper parameters to their callers

* Follow factory methods and awaited factories

* Follow aliases of local functions

* Read class-body clients in their own body, and read authority-relative URLs

* Screen PoolManager.connection_from_host

* Bind calls and index flows after every alias is collected

* Tighten comments on the egress screen additions

* Screen datagram destinations on sendto and sendmsg

* Apply proxy stores after binding, and read proxy environment variables

* Resolve os and environ aliases for proxy environment stores

* Screen urllib openers and ProxyHandler mappings

* Follow wrapper instances, read environment mappings, and scope environment proxies

* Reach inherited client methods through self, and read expanded environment updates

* Read mutated environment mappings and os.environ merges, and honour aiohttp trust_env

* Resolve environment keys held in variables, and bind local constructor arguments

* Treat lambdas bound to a name as local functions

* Handle annotated assignments through the same binding path as plain ones

* Follow inherited initializers, inline wrappers, environ aliases and super()

* Carry os.environ through helper parameters

* Check asyncssh tunnel and proxy_command, and honour httpx trust_env=False

* Treat a paramiko sock argument as unreadable

* Screen asyncssh.connect_reverse, and follow clients returned by properties

* Carry the os module through assignments and helper parameters

* Check SSH routing keywords from one table, including Fabric gateway

* Limit the sock routing rule to SSHClient.connect

* Check asyncssh connection options, and read named proxy mappings

* Follow bound local methods saved under another name

* Track proxy-manager factories and SOCKSProxyManager as pool clients

* Read a path with a relative literal prefix as hostless

* Read a wholesale os.environ replacement

* Trim comments in the egress screen additions

* Index shadowed names by scope so the egress screen stays linear on class-heavy code

* Read a backslash as the end of the host, and follow class attributes and unpacked factory tuples

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read proxy writes through os.environb, and fail closed on a Fabric connect_kwargs sock

* Never trust a host with a backslash, and read filled-in Fabric kwargs and getattr environ writes

* Check positional SSH route arguments for paramiko connect and Fabric Connection

* Read an explicit environ __ior__ call like update

* Trim comments in the egress screen fixes

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Maheswar Kumar <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Studio: center collapsed sidebar icons and tighten the rail (#12031)

* Studio: center collapsed sidebar icons and tighten the rail

The nav icon's expanded-row nudge also applied in the collapsed rail,
leaving each icon 2px right of its hover circle. Drop it there, use
30px round hover targets throughout the rail (including the open
sidebar toggle), and sit the settings cog one nav row above the avatar.

* Studio: shrink collapsed sidebar hover circles to 28px

* Unsloth Studio: list a GGUF with no header metadata under On Device on the Images page (#11830)

* Studio Hub: classify a GGUF whose header names no architecture from its name

unsloth/Qwen-Image-2.1-GGUF files carry no general.* keys at all, so _arch_to_task answered None. The Images picker filters On Device rows on an exact task and dropped the row; the unfiltered Chat picker listed it and refused it. A readable header that names nothing now takes the same name-only route as a cloud placeholder.

* Trim comments on the no-architecture GGUF classification

* Keep the MiniMax-H3 conditioner out of the name-only video route

---------

Co-authored-by: Daniel Han <[email protected]>

* Keep the conversion backfill's donor stub off the transformers package (#12034)

* Unsloth Desktop: show Stopping… after Stop so a pending cancel doesn't look ignored (#11976)

* Studio: show Stopping… after Stop so a pending cancel doesn't look ignored

* Studio: tighten stop-label comments

---------

Co-authored-by: Daniel Han <[email protected]>

* Studio: stop edit_file writing a compacted-argument placeholder into files (#11950)

* Studio: stop edit_file writing a compacted-argument placeholder into files

* Trim comments in the compaction receipt guard

---------

Co-authored-by: Daniel Han <[email protected]>

* Studio: decode Wan video in fp16 with channels_last_3d convs (#11999)

* Studio: decode the Wan video VAE in fp16 with channels_last_3d convs

* Format

* Trim the fp16 decode docstring

* Trim fp16 decode comments

* Unsloth Studio: refuse picking a hosted FP8/INT8 checkpoint repo as a pipeline before it downloads (#11829)

* Studio: refuse a pipeline pick of a hosted prequant repo before it stages anything

A pick of unsloth/Qwen-Image-2.1-FP8 with no file name is a pipeline load, and validate_load_request let it through: the family detects from the id and unsloth/ clears the trust gate. The plan staged the repo's 14 GB of checkpoints, then from_pretrained 404d on the model_index.json the repo does not have. The hosted prequant repos are now a table (prequant_only_repo_ids) and a pipeline pick of one is refused with the base repo and precision to pick instead.

* Skip the hosted prequant-repo pipeline refusal when repo_id is an existing local path

- The new prequant-repo pipeline refusal matched the repo id by exact string, so a local pipeline directory cloned to that same relative name (e.g. ./unsloth/Qwen-Image-2.1-FP8 with a valid model_index.json) was wrongly rejected. It now skips the refusal for local paths and lets the existing local manifest validation handle them.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: trim comments in prequant pipeline-pick refusal

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>

* Studio: stop the second prompt length recompiling Qwen-Image on the max tier and with int8 (#11842)

* Studio: compile the prompt-length dims of Qwen-Image DiT blocks dynamic from the first render

The max tier (and torchao weights on the default tier) compiles DiT blocks with
automatic dynamic, so the first prompt's token count was compiled static and the
first prompt of a different length recompiled every block graph into the
generalised form it then kept (Qwen-Image-2.1: 14 s int8 default, 31 s bf16 max,
51 s int8 max; Qwen-Image: 52-57 s max).

Name the block inputs whose size follows the prompt in
torch.compiler.config.dynamic_sources, set only around the owning transformer's
forward and restored even when it raises, so the first compile already builds the
generalised graphs. The first segment start of Qwen-Image-2.1 stays static, which
keeps clear of the torchao CantSplit that dynamic=True hits. The compile-cache key
gains the allowlist only for these families. torch without the knob (2.6) is
unchanged.

* Studio: also mark Qwen-Image's text inputs dynamic when FBCache calls the blocks through hooks

FBCache is on by default for Qwen-Image, and its hooks pass the block inputs as
kwargs (or a resumed frame's stack after a graph break), so the plain L[...]
names never matched and the second prompt length still recompiled. Suffix
patterns cover those paths on torch 2.8+.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: ruff format

* Arm the prompt-length allowlist only on torch 2.8+

torch 2.7 caches its first read of compiler.config.dynamic_sources for the
life of the process, so scoping the list to one forward is either ignored or
leaks it into every later compile. 2.8 re-reads it when it changes and adds
regex matching (is_dynamic_source), which the FBCache hook paths also need.
Older torch keeps today's behaviour.

* Trim comments

* Trim comments on the prompt-length allowlist

* Trim dynamic text dims comments

* Drop dead torch<2.1 hook fallback and redundant in-test skips

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten dynamic text dims docstrings

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Studio: size the image memory plan at the dtype the pipeline loads in (SDXL resident on 24 GB) (#11922)

* Studio: size the diffusion memory plan at the dtype the pipeline loads in

The pipeline memory plan summed the cached shard bytes, which is what a repo
stores rather than what the load holds. SDXL and SDXL-Turbo publish fp32
weights (12.9 GB) that load as 6.5 GB in bf16/fp16, so 20-24 GB cards planned
whole-model offload for a model that fits resident, and a 16 GB unified-memory
Mac refused it outright. Lumina-2 and Z-Image-Turbo ship fp32 shards the same
way, and a cache holding fp16 variant twins, .bin twins or a single-file
checkpoint beside the pipeline counted weights the loader never opens.

Price each cached weight file the way from_pretrained materialises it:
default-variant component files only, safetensors over a .bin twin, and a
file whose floats are all wider than the load dtype at that dtype. Mixed
precision, quantised and fp8 files, components whose class pins modules in
fp32, and fp32 loads keep their stored size, and the estimate only ever
lowers. Download sizes and disk checks are unchanged.

* Studio: let the mirrored companion stub take the load itemsize

* Studio: shorten the load-dtype sizing comments

* Studio: widen half-precision weights on an fp32 load, keep a .bin the loader falls back to

An fp32 target (a Mac without bf16, an fp16-incompatible family on an fp16
card) materialises bf16/fp16 shards at four bytes per element, so price every
float at the load width there. A .bin is dropped only when its folder holds a
safetensors checkpoint the loader can select: an unsharded file, or shards with
their index.

* Studio: honour Transformers' non-strict fp32 pins only on fp16 loads

Transformers upcasts _keep_in_fp32_modules only when the load dtype is fp16
and _keep_in_fp32_modules_strict for both halves; Diffusers upcasts its set
for both. A bf16 load of an fp32 T5 checkpoint is therefore priced at bf16.

* Studio: price fp32-pinned modules at four bytes in half-precision loads

A component whose class keeps modules in fp32 (T5's wo at fp16, a strict or
Diffusers pin at either half) holds those tensors at four bytes whatever the
checkpoint stores, so price them per tensor instead of leaving the file at
its stored size.

* Studio: match fp32 pins against the parameter path the way each loader does

* Studio: price a surviving .bin checkpoint at the load dtype too

* Studio: count a tied .bin weight once when pricing it

* Studio: trim comments in the load-dtype memory plan

* Studio: stop MiniMax-H3 recompiling on the second caption and the first i2v (#11880)

* Studio: compile the prompt-length dims of Qwen-Image DiT blocks dynamic from the first render

The max tier (and torchao weights on the default tier) compiles DiT blocks with
automatic dynamic, so the first prompt's token count was compiled static and the
first prompt of a different length recompiled every block graph into the
generalised form it then kept (Qwen-Image-2.1: 14 s int8 default, 31 s bf16 max,
51 s int8 max; Qwen-Image: 52-57 s max).

Name the block inputs whose size follows the prompt in
torch.compiler.config.dynamic_sources, set only around the owning transformer's
forward and restored even when it raises, so the first compile already builds the
generalised graphs. The first segment start of Qwen-Image-2.1 stays static, which
keeps clear of the torchao CantSplit that dynamic=True hits. The compile-cache key
gains the allowlist only for these families. torch without the knob (2.6) is
unchanged.

* Studio: also mark Qwen-Image's text inputs dynamic when FBCache calls the blocks through hooks

FBCache is on by default for Qwen-Image, and its hooks pass the block inputs as
kwargs (or a resumed frame's stack after a graph break), so the plain L[...]
names never matched and the second prompt length still recompiled. Suffix
patterns cover those paths on torch 2.8+.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: ruff format

* Arm the prompt-length allowlist only on torch 2.8+

torch 2.7 caches its first read of compiler.config.dynamic_sources for the
life of the process, so scoping the list to one forward is either ignored or
leaks it into every later compile. 2.8 re-reads it when it changes and adds
regex matching (is_dynamic_source), which the FBCache hook paths also need.
Older torch keeps today's behaviour.

* Trim comments

* Studio: compile MiniMax-H3's packed length dynamic from the first render

A new caption changes H3's packed video + audio + caption length, and the
first new caption after load recompiled the denoiser blocks (about 11 to 22 s).
Name those inputs in the prompt-length allowlist so the first compile is
already general, and keep the small-M int8 padding free of a branch on the
row count when traced, which otherwise guarded the caption length to <= 31
rows and recompiled the refiner on the first i2v (a 540-row caption).

* Pad traced rows with arithmetic max so a concrete row count still compiles

torch.sym_max on a concrete int is rejected by dynamo on torch 2.8 and older,
so a static compile of a padded int8 Linear broke (fullgraph drops the DiT to
eager). builtin max() compiles but left an m <= pad_to guard behind on an
inductor cache hit. (m + p + |m - p|) // 2 does neither.

* Trim comments on the prompt-length allowlist

* Trim comments on the H3 allowlist and traced row padding

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim dynamic text dims comments

* Drop dead torch<2.1 hook fallback and redundant in-test skips

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten dynamic text dims docstrings

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Unsloth Studio / Desktop: log what an image load and each generation actually resolved to (#11994)

* Studio: log what an image load and each generation actually resolved to

* Studio: trim comments on the resolved and generation log lines

* Studio: build the diffusion.loaded resolved field from the committed load state

* Studio: log the applied denoise strength and native sd.cpp LoRAs in diffusion.generated

* Studio: log the effective upscale factor, and only for the upscale workflow

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Unsloth Studio: stop offering "Continue" on a base repo that only holds a GGUF's text encoder and VAE (#11644)

* Unsloth Studio: stop offering "Continue" on a base repo that only holds a GGUF's text encoder and VAE

A companion-only snapshot stays partial so no picker loads it, but a new
companion_prefetch flag keeps the Hub from presenting it as an unfinished
download whose Continue pulls the denoiser the GGUF replaces.

* Carry companion_prefetch through the local listing the Hub merges

The Hub merges /api/hub/cached-models with /api/hub/local, and the local
scanner knew nothing about companion-only snapshots. After a real GGUF
load, its row for the base repo stayed Partial, and the detail pane still
offered Continue at 33 GB. When the base repo held VAE and encoder shards,
the same scanner classified it as a complete safetensors model instead,
and the Hub offered Run on a pipeline with no denoiser.

The local scanner now reads the same signal on the snapshot it lists:
such rows are partial, as the cached listing marks them, and carry
companion_prefetch. The frontend honours the flag on local rows too.

* Keep a companion-only base repo out of model Discover's on-device and partial states

buildDiscoverRows read partial and on-device straight off the cached or
local row, so the new flag never reached the model Discover grid: the repo
still read as a partial download there.

* Show a companion-only base repo as a plain Download, not On device with Run

Excluding the flag from the partial hf_cache branch sent the local row into the
fully local view, which claims the repo is on device and offers Run on a
pipeline with no denoiser. Keep the branch and clear only the partial state.

* Key the Discover memo on the companion flag

A companion fetch finishing leaves partial true on both listings and flips only
companion_prefetch, so the signature the model Discover memo is keyed on did not
change and the grid kept the repo as on device and partial.

* Trim companion_prefetch comments

* Keep Delete on a companion-only repo's download card

The card gated its repo menu (Delete, path) on isDownloaded || isPartial,
and a companion-only repo is now neither, so 19 GB of borrowed text
encoder and VAE could no longer be deleted from the detail pane.

* Drop the green On device dot from a companion-only inventory row

* Trim comments

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: Daniel Han <[email protected]>

* Apply SFTConfig.router_aux_loss_coef to MoE models that cache it at init (#12006)

* Apply SFTConfig.router_aux_loss_coef to MoE models that cache it at init

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten router_aux_loss_coef sync comments

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Load only the language model for text_only on repo-code composites (#11861)

* Load only the language model for text_only on repo-code composites

FastModel.from_pretrained(text_only = True) skipped the vision tower only for
families with their own text decoder (gemma3 -> gemma3_text). A repo-code
composite such as Nemotron-3-Nano-Omni (llm_config + vision_config +
sound_config, one wrapper class in auto_map) failed that test, so the whole
wrapper was loaded and its forward required pixel_values.

When trust_remote_code is set, the parent config is repo code, and every
parameter of the text sub-config's causal LM (built on the meta device) is
stored under exactly one checkpoint prefix, load that causal LM alone with a
key_mapping stripping the prefix. Anything else keeps the previous full-model
load, so no text weight can be left randomly initialised.

* Also find the decoder of a repo-code composite under llm_config

InternVL and Llama-Nemotron-Nano-VL keep the decoder config as llm_config
without the text_config alias get_text_config() reads, so the text-only
plan never saw it. Fall back to llm_config / language_config; the
full-coverage checkpoint check still decides whether the branch is taken.

* Keep the full-model load for repo-code composites on transformers 4.x

transformers 4.x decides base-model vs task-model prefix handling from the
checkpoint keys before key_mapping renames them, so a language_model.
prefixed checkpoint either raises "state dictionary ... corrupted" or, with
tied embeddings, loads every text weight as missing. Decline the text-only
plan below 5.0 and skip the positive tests there.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Record the commit a trusted load ran repo code at

A merged export that re-reads the repo's config with its code pins it
to this commit instead of the branch head. Under text_only the model's
config is the nested text config, which carries no commit, so the
composite config's commit is taken before the remap.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Pin the text-only config of a repo-code composite to the parent commit

* Read a cached unsharded checkpoint when the text-only plan runs offline

* Keep the full composite for adapters trained on it under text_only

* Decline the text-only plan for repo-code composites under fast_inference

* Accept sequence-valued auto_map entries in the text-only self-reference check

* Rebase llm_int8_skip_modules once from the parent names for nested text prefixes

* Pass torch_device to PeftModel.from_pretrained in the text-only adapter test

* Probe sharded .bin composites for the text-only plan from their index

* Pass local_files_only to the nested text class lookup of the text-only plan

* Read adapter_model.bin names when deciding whether an adapter fits the text model

* Probe the text-only plan at the commit its config was resolved at

* Decline the text-only plan when the nested text class lives in another repository

* Probe the text-only plan checkpoint under the requested subfolder

* Keep the full composite for a device_map keyed on its module names

* Probe the text-only plan checkpoint at the requested variant and cache_dir

* Resolve the nested text class at the requested code_revision

* Keep the full composite for an adapter on wrapper-only modules

* Rebase the caller's quantization_config skip modules for the text-only plan

* Stamp the code_revision commit as the trusted remote code commit

* Stamp the rebased quantization_config on the text-only decoder

* Save the text-only decoder under its standalone weight names

* Pin the wrapper-only adapter test's PEFT load to the CPU

* Give the text-only test namespace the remote class resolver resolve_model_class now calls

* Trim comments in text-only remote composite loading

* Add the license header to the text-only remote composite tests

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Try the text-only plan when a repo-code wrapper is its own text config (InternVL)

* Rebase every quantization module-name list on the text model, and keep the full model for a regex that names the prefix

* Detect a quantization regex that escapes any dot of a nested text prefix

* Tighten comments in the text-only remote composite path

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Put back the unsloth_zoo modules the device map opt-in tests stub (#12038)

* Studio: pass tool_result is_error through to the model on /v1/messages (#11962)

Keep the Anthropic tool_result is_error flag on /v1/messages and mark failed tool output with an Error: prefix (or a short note when the output is empty) so the local model can tell a failed tool call from an empty success.

* SentenceTransformer: add opt-in…
JoshuaL3000 pushed a commit to JoshuaL3000/unsloth that referenced this pull request Oct 4, 2026
unslothai#11016)

* Lift the transformers ceiling to 5.17.0 and align the torch mirror

transformers<=5.5.0 was the ceiling, and 5.5.0 is exactly where the prequantized bnb-4bit
checkpoints lose quant_state on every Linear4bit (#9867, #10010, #10017, #10276): measured
352 of 352 on unsloth/Qwen3.8-27B-unsloth-bnb-4bit, with the reporters' own
"mat1 and mat2 shapes cannot be multiplied (10x5120 and 1x15728640)" on the forward. On
transformers 5.17.0 the same load is 0 of 352 and the forward returns logits. The ceiling
also put the Gemma 4 E4B LoRA fix one patch release out of reach, since that shipped in
5.5.2 (#5355).

Raise the cap at both pyproject sites, keeping every != exclusion, and move the CI lanes
that mirrored it:

- studio-backend-ci.yml installed 'transformers>=4.51,<5.5' in two jobs, which had drifted
  BELOW the published ceiling: it excludes 5.5.0, the release every user resolved.
- notebooks-ci.yml installed '<5.6' while notebooks in unslothai/notebooks pin 5.10.1,
  5.15.0 and 5.15.1, so the API surface it dumps came from a release those notebooks
  never run on.
- studio-export-capability-ci.yml installed 'torch>=2.4,<2.13', which excludes the torch
  unsloth_zoo now admits.

version-compat-ci.yml gets the two ends of the range it was missing. zoo-imports-under-spoof
and grpo-fake-run each become a two-lane include matrix: a floor lane (py3.10, torch 2.6.0,
transformers 4.57.6, TRL 0.22.2, PEFT 0.18.0) and a latest lane that pins nothing. A new
torch-free cap-site-consistency job runs the window-drift assertions on ubuntu, windows and
macos. tests/version_compat/test_transformers_pinned_symbols.py gains v5.15.0 through
v5.17.0.

Studio's single-env keeps transformers==5.5.0. That pin is not this cap: it is the version
the pinned installer ships, locked in step with a tokenizers window transformers enforces
at import, and widening only the darwin override reproduces the Apple Silicon failure its
comment documents. The comment now says so.

Evidence: the whole 4.57.6 plus 5.0 to 5.17 sweep, and a real 27B bnb-4bit load on both
sides of the old ceiling.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Install torchcodec and hf_transfer where the two new lanes need them

Both new version-compat lanes went red on their first run and both reasons are
about what the lane installs, not about the cap.

torchcodec carries a compiled extension linked against one libtorch build, and
torch on these lanes comes from the CPU index. Listed in the package step it was
taken from PyPI, where the wheel is the accelerator flavour, and next to a
torch 2.14.0+cpu it cannot dlopen. unsloth then does what it is supposed to do
and disables it, seating the sys.modules absence sentinel, after which
datasets 5 answers any Dataset.from_dict with

    ModuleNotFoundError: No module named 'torchcodec.decoders';
    'torchcodec' is not a package

and the GRPO lane fails during collection. Moving it back onto the torch install
line, which is where it sat before this branch split the lanes, lets pip prefer
the matching +cpu build. Verified in a clean venv: torch 2.14.0+cpu with
torchcodec 0.16.0+cpu imports torchcodec.decoders and builds a Dataset, the same
pair with PyPI torchcodec 0.16.0 is what CI hit. The floor lane's 0.2 row is not
published on that index at all, so the extra index still serves it from PyPI.

hf_transfer is a declared unsloth_zoo dependency and the zoo is installed here
with --no-deps, so the lane has to supply it. unsloth sets
HF_HUB_ENABLE_HF_TRANSFER=1 around from_pretrained, and the huggingface_hub 0.x
that the floor lane's transformers 4.57.6 pulls raises instead of falling back
when the package is absent, which took out 45 tests.

* Keep the pip cache names literal in the two new matrix jobs

tests/studio/test_pip_cache_naming.py reads the workflow as text and requires
every pip-cache-restore name to be lowercase letters, digits and dashes,
because it goes into the cache key verbatim and the janitor groups on it. The
two new include matrices named the cache after the matrix slug, which the
action itself would have accepted at run time but which fails that lint, and
took the workflow-trigger lint job down with it.

The per lane name was not needed anyway. The key already carries the
interpreter, pip-v2-name-os-arch-pyMINOR-hash, and the two lanes are python
3.10 and 3.12, so they cannot overwrite each other's wheels. Both names are
back to the literals they had before the split, with the reasoning written next
to them and a note that two lanes sharing one python would need the job split
instead.

tests/studio/test_pip_cache_naming.py: 116 passed, and 1 failed 115 passed
without this change.

* Trigger the version-window drift job on every cap file it scans

* Run the floor lane on the declared minima, and scope the pin exception to one requirement

* Pin the GRPO floor lane to the declared TRL and transformers minima

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim the comments in the files this PR touches

Delete-first pass over the changed files: collapse multi-line rationale to
one line, drop measured numbers, section banners, spacer lines and
restatements of the code. Comments, docstrings and whitespace only, AST
gated; no behaviour change.

* Trim the export-capability workflow comments too

* Read the transformers compat matrix from PyPI instead of pinning it

This suite exists to say which versions the cap may be lifted to, so a hand-maintained
tag list answers for the day it was edited. It now takes every minor at or above the
4.57.6 floor, latest patch of each, the same way tests/vllm_compat does for vLLM.

One tag per minor keeps the matrix bounded as upstream keeps releasing. A patch that
broke something specific earns its place in _ALWAYS rather than a blanket every-patch
sweep: 5.5.0 is the old ceiling and still the Apple Silicon cap, 5.16.0 first required
tokenizers>=0.23.1. Yanked, rc, dev and post releases are skipped, since pip will not
install them.

_TAG_OVERRIDES carries the one place upstream disagrees with itself: PyPI 5.10.4 is
tagged v5.10.3. A frozen fallback list covers an unreachable PyPI, so a network failure
cannot quietly shrink the matrix to nothing and report green.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep the load bearing tags when PyPI cannot be read

* Anchor the matrix to the ceiling pyproject declares

* Resolve the matrix once so every xdist worker collects the same one

* Anchor the patch releases the notebooks pin

* Import the declared ceiling, and let the unpinned lane be a canary

* Give the ceiling lane its own pip cache key

* Anchor the shared matrix too, and derive the ceiling tag through the override table

* Split the PyPI-tracking matrix out of the cap lift

The dynamic matrix, its anchors and the CI lane restructure move to their own PR.
This branch keeps the cap lift, the four cap sites, the drift gate and a static tag
list that covers the window the cap opens: 4.57.6 and every 5.x minor through the
declared ceiling v5.17.0, plus the v5.10.1 and v5.15.1 pins several notebooks carry.

* Raise the transformers floor to 4.52.4, which is the oldest one that imports

The declared floor was transformers>=4.51.3 beside peft>=0.18.0, and that pair
cannot import: peft declares no transformers floor of its own, and peft 0.18.0
imports GradientCheckpointingLayer from transformers.modeling_layers at
peft/tuners/lora/model.py:26, a module that first exists in transformers 4.52.0.
pip resolved it happily and import unsloth then raised ModuleNotFoundError.

4.52.4 rather than 4.52.0 because 4.52.0 through 4.52.3 were already rejected by
name; those exclusions are now dominated by the floor and drop out.

Measured, not inferred: the floor lane's import set was run at 4.51.3 (5 failed,
21 passed, matching CI exactly), 4.52.0, 4.52.4, 4.53.1 and 4.54.1 (34 passed
each), so modeling_layers was the only missing piece.

tests/test_transformers_cap_sites.py grows the mirror of its ceiling gate:
TESTED_FLOOR, a check that both version-compat floor lanes pin the declared
floor, and a negative control that the window still refuses 4.51.3.

test_trl_loss_normalization_contract.py checked DPO with hasattr, which has been
false since trl 0.21 declared loss_type with a default_factory, so that half was
skipped on recent TRL and wrong at the floor. DPO and KTO are now compared to
pristine TRL, whose values are version-dependent, while GRPO stays the literal
bnpo that rl.py deliberately pins.

* Let the TRL floor lane's training tests run at the declared floor

The lane's two loaders passed dtype = torch.float32 to from_pretrained. That
kwarg is rejected at the transformers 4.52.4 floor, where from_pretrained
forwards it into the model constructor, so 45 tests died with
TypeError: LlamaForCausalLM.__init__() got an unexpected keyword argument 'dtype'
the moment the lane could import at all. torch_dtype spans the window but is
deprecated from 4.57.6 on, so neither literal is safe: load with neither kwarg
and cast after, asserting the parameter dtype really is float32 so the cast
cannot silently no-op.

tests/version_compat/test_no_dtype_kwarg_at_load.py keeps it that way, an AST
scan of every test in the directory for a dtype or torch_dtype kwarg on
from_pretrained, with five parametrised controls including a dtype kwarg that is
not a load at all.

test_pristine_trl_config_without_max_seq_length_still_truncates asserted a
precondition it cannot control: the regression only exists on a TRL that dropped
max_seq_length, and trl 0.18.2 still declares it. It skips with that reason now,
the same way the file already skips an unreachable hub.

* Add the call-site guard that keeps a dtype kwarg out of these loaders

An AST scan of tests/version_compat for a dtype or torch_dtype kwarg on
from_pretrained. Neither spelling holds across the declared transformers window:
dtype raises TypeError at the 4.52.4 floor and torch_dtype is deprecated from
4.57.6 on, so the durable rule is to load without either and cast the result.
Five parametrised controls, including a dtype kwarg that is not a load.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Require the unsloth_zoo release that carries the same transformers ceiling

pip intersects unsloth's transformers window with unsloth_zoo's own, and
published unsloth_zoo 2026.9.4 still says transformers<=5.5.0, which is exactly
the cap this PR lifts. Without a matching zoo floor the lift is advertised and
not delivered.

Move the declared zoo floor to the first release expected to carry the lift and
add a gate: with the floor back at 2026.9.4 the new test fails, naming the
intersection.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read the tightest upper bound, and keep the exemption list honest

_ceiling took max over the upper bounds, so raising a cap by adding a bound
without removing the old one (<=5.17.0,<=5.18.0) reported 5.18.0 while pip still
resolved at 5.17.0. Take the tightest bound instead, with < beating <= at equal
versions.

PINNED_BY_DESIGN carried a placeholder for a requirement no lane spells. That is
not documentation, it pre-authorises that exact string: reintroduce
transformers<=5.5.0 in that workflow and the scan finds it and then skips it. The
dict is empty now, and a new test requires every entry to match a requirement a
lane really spells today.

* Hold the unsloth_zoo floor at 2026.9.4 until the matching release ships

unsloth_zoo 2026.9.5 does not exist on PyPI; 2026.9.4 is the newest
published release. `unsloth_zoo>=2026.9.5` is therefore a floor no release
satisfies, which makes unsloth uninstallable rather than merely
under-delivering the lifted transformers window, and it blocks this PR.

Revert the three pyproject sites to 2026.9.4, which is what main carries,
and rewrite the comment above the floor so it no longer contradicts the
pin: it now says the floor is held here and names what still needs the
newer zoo.

The gate that asserts the floor is deferred rather than deleted, so it
stays the reminder to raise the pin later.
ZOO_FLOOR_WITH_LIFTED_TRANSFORMERS_CAP is None, the test skips with a
reason naming unslothai/unsloth-zoo#1227, and setting the constant to the
release that ships #1227 re-enables it in one edit. The half of that gate
that does not depend on which release the floor names, that there is
exactly one zoo floor and that it is a real lower bound, still holds at
2026.9.4 and is split out into test_pyproject_declares_one_unsloth_zoo_floor,
which keeps running.

Known and accepted while this stands: pyproject advertises transformers up
to 5.17.0 while the resolvable zoo still caps it at 5.5.0, so the lift is
declared but not yet delivered.

* Track PyPI for the transformers compat matrix (#11136)

The static tag list answers for the day it was edited. This reads the releases from
PyPI, keeps one tag per minor to stay bounded, and merges the anchors no automatic
rule can derive: the floor, the old Apple Silicon ceiling, the tokenizers breakpoint,
the patch releases the notebooks pin, and the ceiling pyproject itself declares.

Six failure modes found in review, each with a named test and each mutation proven:
a fallback that dropped the anchors, a ceiling anchored to a literal, xdist workers
collecting different matrices, a later patch evicting a pinned one, two CI lanes
minting one pip cache key, and the shared matrix file bypassing the anchor merge.

The CI lane restructure comes with it, since the matrix is what it feeds: floor,
ceiling and latest on three interpreters and so three cache keys, with latest marked
non-blocking because resolving outside the declared window is its job.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Raise the unsloth_zoo floor to 2026.9.5

Main moved to 2026.9.5 in #11210, so this branch's 2026.9.4 was a
regression against main. 2026.9.5 also settles the second of the two
reasons the floor was tracked: it carries the generated-sentinel fix
(unslothai/unsloth-zoo#1259). The transformers half stays outstanding,
since 2026.9.5 still declares transformers<=5.5.0 pending
unslothai/unsloth-zoo#1227.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Make the zoo deferral expire by itself instead of on a hand-written constant

Codex raised (P1) that `unsloth_zoo>=2026.9.5` still admits a zoo whose own metadata
says `transformers<=5.5.0`, so pip intersects the widened range back down and users
keep resolving 5.5.0. That is correct, and it is measured: enumerating all 230
published transformers releases, this branch widens the unsloth side by 26 cells, but
the range a user actually resolves (ours intersected with published unsloth_zoo
2026.9.5) moves by 0 newly admitted cells. 229 of 230 cells are identical and the one
that moves is 4.51.3 becoming rejected, which is the floor fix.

The requested remedy cannot be applied here. Raising the unsloth_zoo floor to the
release carrying unslothai/unsloth-zoo#1227 requires that release to exist, and it does
not; a floor no published release satisfies makes unsloth uninstallable, which is why
the floor never leads the release. That reasoning is already in the comment above the
floor and in the deferred gate's docstring.

What was genuinely wrong is the shape of the deferral.
`test_the_declared_zoo_floor_can_supply_the_declared_transformers_window` skips while
`ZOO_FLOOR_WITH_LIFTED_TRANSFORMERS_CAP` is None, and that constant is hand-written, so
on the day #1227 ships nothing turns red: the gate keeps skipping and the floor keeps
naming a zoo that caps at 5.5.0 for as long as nobody looks. That is "a site left
behind after the window moves does not go red", which is the failure this whole file
exists to catch, reproduced inside its own deferral.

`test_the_zoo_deferral_expires_when_the_zoo_release_ships` closes it. It asks PyPI what
the newest published unsloth_zoo allows and fails only on POSITIVE evidence that the
deferral is obsolete, naming the release to pin and the constant to set. No network, a
timeout, a malformed answer or a zoo with no readable ceiling all leave it skipped, so
it can never go red by failing to reach PyPI. That preserves the property that put this
suite on the three-OS cap-site job: offline runs stay honest.

Verified in all three directions rather than by reading:
  shipped zoo (2026.10.1 admitting 5.17.0) -> fails, message names the release
  PyPI unreachable                         -> Skipped, never a failure
  live PyPI today                          -> zoo 2026.9.5 caps 5.5.0 < declared 5.17.0,
                                              so the deferral correctly stands
Suite is 25 passed, 1 skipped.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Start the symbol matrix at the declared floor, and anchor the release with no tag

Codex raised (P2) that `_FLOOR` was a literal 4.57.6 while this PR moves the declared
floor to 4.52.4, so `_release_tags()` discarded every 4.52 through 4.56 release and the
matrix could stay green while a source-pattern or symbol dependency broke supported
users. Confirmed: the floor was the only hardcoded end of the window in this file, since
the ceiling is already read from pyproject through `_CAP` for exactly this reason.

`_FLOOR` is now derived the same way, by `_declared_floor()`, taking the LOWEST `>=` in
the file so a marker-gated half declaring a higher floor cannot raise it and hide
releases the other half still admits. A bad read falls back to 4.52.4 rather than
widening the matrix to every release ever published.

Widening it turned up a real defect, which is the point of having done it. On the first
run 4.54.1 failed five checks, all on the fetch rather than on a symbol:

    v4.54.1: src/transformers/trainer[.py|/__init__.py] both missing

4.54.1 is on PyPI and inside the window, but upstream never pushed a v4.54.1 tag. The
only 4.54 refs are v4.54.0 and v4.54-release. Checked directly rather than assumed:

    v4.54.1  tag ref                  HTTP 404
    v4.54.0  __init__ __version__     4.54.0   (so it is NOT this release)
    v4.54-release __version__         4.54.1   (trainer.py HTTP 200)

so the entry is `"4.54.1": "v4.54-release"`, the same shape as the existing 5.10.4 entry
and for the same documented reason. `_sort_key` now resolves a tag back through the
override table before parsing it, since a tag whose name is not a version string has to
sort by the release it carries.

With both changes the matrix runs 4.52.4 through the ceiling: 523 passed, 9 skipped,
against 506 passed, 21 skipped and 5 failed when the floor was widened alone.

`test_the_matrix_starts_at_the_declared_floor` keeps it from drifting back. Mutation
proven: restoring the 4.57.6 literal turns it red on 23 of 28 tags, and the restored
tree is 28 passed.

* Start the outage fallback at the declared floor too

Codex raised (P2) that deriving `_FLOOR` fixed only the live path: `_TAGS_FALLBACK` is a
separate frozen list and still began at v4.57.6, so any PyPI failure dropped every 4.52
through 4.56 check and CI could go green straight through a regression at the low end
this PR newly supports. Correct, and it is the same defect as the one just fixed, one
code path over. `_ALWAYS` does not cover it either: those anchors are the Apple Silicon
ceiling and the tokenizers breakpoint, both 5.x.

The fallback now starts at the declared floor, one tag per supported minor below the old
start: v4.52.4, v4.53.3, v4.54-release, v4.55.4, v4.56.2. 4.54 goes in under its real tag
for the reason `_TAG_OVERRIDES` already records.

`test_the_outage_fallback_reaches_the_declared_floor` holds it there under a simulated
outage, asserting both that the oldest tag reached is at or below the declared floor and
that no supported minor between 4.52 and 4.56 is missing, so restoring one tag while
dropping the rest does not pass. Mutation proven: putting the fallback back to a
v4.57.6 start turns it red, restored is 2 passed. Full suites 577 passed, 10 skipped.

* Keep the ceiling lane inside the declared datasets window, and compare zoo bounds by membership

Two P2 items from the last review, both genuine.

The ceiling lane installed `datasets` bare. Both checkout installs in that job use
--no-deps, so pyproject's `datasets>=3.4.1,!=4.0.*,!=4.1.0,<4.4.0` never reaches the
resolver and the bare name takes the newest release, which is datasets 5 today. A
blocking lane whose purpose is to isolate compatibility with the transformers ceiling
would instead fail on a datasets release the project does not support. It now carries the
declared window verbatim, as the floor lane already does. The `latest` lane stays bare on
purpose: resolving outside the window is that lane's entire job.

The second is a bug in the deferral-expiry check added earlier in this PR.
`_newest_published_zoo_transformers_ceiling` recorded `<` and `<=` alike as a bare
ceiling Version, so a future zoo declaring `transformers<5.17.0` would have been read as
covering this project's `<=5.17.0` window and expired the deferral on a release that
still cannot resolve our ceiling. It now keeps whole SpecifierSets and asks whether the
declared ceiling is a MEMBER of the published zoo's window, which is the actual question.

Verified both directions against the case named in the review:

    zoo `>=4.52.4,<5.17.0`   -> deferral correctly STANDS, no false expiry
    zoo `>=4.52.4,<=5.17.0`  -> correctly fails, naming the release to pin

Suites are 577 passed, 10 skipped.

* Let the GRPO left-pad probe resolve at the declared TRL floor

The injected probe tried has_images and fell back to images with no third
branch. TRL 0.18.2 and 0.19.1 bind neither name in
_generate_and_score_completions and have no vision path at all, so the
fallback raised NameError out of the except handler and took GRPO
training down at the bottom of the declared window. 0.20.0 through
0.23.1 bind has_images, 0.24.0 and up bind images.

Resolve a text-only flag through all three cases, then compute the pad
once. tests/version_compat/test_grpo_left_pad_probe_at_the_floor.py
executes the rewritten function against each binding shape and
re-derives the table from upstream sources, and is wired into both GRPO
fake-run lanes.

Also names tests/version_compat/test_no_dtype_kwarg_at_load.py in the
pinned-symbol matrix, which is what test_version_compat_bundle.py asks
of every suite that exists.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Resolve the GRPO importance sampling level at the declared TRL floor

The rewritten compute_loss read self.importance_sampling_level
unconditionally and passed it to both the no-grad and the gradient loss
path. That attribute is GSPO's and arrived in TRL 0.20.0, as a
GRPOConfig field the trainer copies onto itself. 0.18.2 and 0.19.1 have
neither the field nor the attribute, so GRPO training died in the first
training_step at the bottom of the declared window:

    AttributeError: 'UnslothGRPOTrainer' object has no attribute
    'importance_sampling_level'

Read off upstream rather than inferred: grpo_trainer.py binds
self.importance_sampling_level 0 times at 0.18.2 and 0.19.1, and 5 or
more from 0.20.0 on, with grpo_config.py matching.

Resolve through the trainer attribute, then the config field, then
'token'. The fallback is not invented: 'token' is the default TRL's own
field declares, it is what unsloth_zoo's grpo_compute_loss already
defaults to, and 0.18.2 has no sequence level path at all. Versions
that bind the attribute are unaffected, since it is found first.

tests/version_compat/test_grpo_importance_sampling_level_at_the_floor.py
execs the real rewritten source and captures the level the loss
actually receives, over both loss paths and all three binding shapes,
and re-derives the upstream table so a future TRL that moves the knob
fails here rather than in a training loop. Mutation checked: reverting
either call site turns 4 of 7 red, and the 3 that stay green are the
arms the bug never touched.

Second of this family, after the left-pad probe. Same shape: injected
source assuming a TRL binding the floor does not have.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Supply the Docker Hub credential the way the workflow now takes it

Both harnesses handed the step its key by replacing `${{ secrets.DOCKER_API_KEY }}`
in the `run:` body. The key has since moved into the step's `env:` block so it is
never a command-line argument, which means that replace matches nothing: the body
builder died with KeyError, curl was handed an empty request, and the step still
exited 0 because the failure was inside a pipeline. The stub also logged only
"$*", and the auth body is passed on stdin via `--data-binary @-`, so the
identifier could not be observed even when it was sent.

The harnesses now set DOCKER_API_KEY in the environment and the stub appends the
stdin body to the log, only when curl was actually told to read stdin. Both halves
are load-bearing: removing either one fails the assertion again.

The workflows themselves are correct and unchanged; an empty token is caught by
their own `-z "$TOKEN"` check. This was the test harness drifting behind them.

A new test in each file pins that the step takes DOCKER_API_KEY from `env:` and
keeps no `${{ }}` in its body, so a rename fails loudly instead of quietly
returning these assertions to describing an empty request.

* Cut the comments in the files this PR authors

Opening comment-reduction pass over the five files this PR writes in full or
near enough. 422 comment lines to 342 across them, 26.9 percent to 23.0.
Long rationales collapse to the one fact that is not recoverable from the
code: the version tables, the traps each constant exists to avoid, and the
citations. Tracebacks and narration go, since the PR description carries them.

Files the PR barely touches are left alone. rl_replacements.py changes 27
lines of 3658 and test_trl_padding_free_max_length.py 21 of 3678; rewriting
their comments would grow the diff well past what a dependency cap lift
should contain.

Comment-only, AST-verified with comment_tools.py check: 5/5 code unchanged.

* Second comment sweep: delete the restating summary lines

Sweep one shortened, this one deletes. Each remaining paragraph docstring
loses the summary line that restated the test name, keeping the fact the
name does not carry. 342 comment lines to 301 across the files this PR
authors, 23.0 percent to 20.5; from 422 at the start of the pass.

Not taken to the 15 percent target: what is left is version tables, the
trap each constant exists to avoid, and issue citations, and cutting those
is the one outcome worth avoiding.

Comment-only, AST-verified with comment_tools.py check.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Skip the GRPO floor suites off-runner instead of erroring collection

Both files import the real rewriter, so unlike the cap-site suites they
cannot be file-only. On a runner without torch `import unsloth` raises its
own ImportError("Unsloth: torch not found"), and a bare module-scope import
turns that into a COLLECTION ERROR: the cross-platform staging run was red
on ubuntu, macos and windows for exactly this, having tested nothing.

pytest.importorskip does NOT cover this case, which is worth writing down
because it is the obvious first fix and it does not work: it skips a module
that is ABSENT and re-raises an ImportError the module body raised itself,
which is precisely what unsloth does here. Verified against a stub package
that raises ImportError on import: importorskip still ends in "1 error
during collection", the try/except ends in "1 skipped".

Both directions checked on the real files: with torch present all 13 tests
run, and against a stub unsloth that raises, both modules skip and the run
exits clean.

* Lift the TRL ceiling to 1.13.0 and gate the range that was already being tested (#11137)

* Keep more VRAM headroom on Windows CUDA, and say when a hand-set context does not fit (#11368)

* Stop a Windows host-RAM spill from looking like a healthy load

On Windows, cudaMalloc does not allocate device memory directly. It asks the
WDDM kernel memory manager, which treats VRAM and system RAM as one demand
paged pool, and since driver 536.40 an allocation past the end of VRAM
succeeds out of host RAM instead of returning out of memory. The load starts,
exits 0, answers /health, and nvidia-smi shows a healthy card, while decode
re-reads the spilled bytes over PCIe on every token.

Linux has no such path. The same allocation fails with "cudaMalloc failed:
out of memory" and llama-server exits, which is measurable: with 12 GiB free,
Qwen3-VL-8B at -c 65536 asks for 9216.00 MiB in one allocation and refuses to
start. That is why every rung of the spawn loop's recovery ladder is gated on
a non-zero exit code, and why the whole ladder is dead on the one platform
that needs it.

Three changes:

Raise the per-device reserve to 1024 MiB on Windows with a discrete CUDA
build, capped at an eighth of the card so it stays proportionate on small
GPUs. This is not a new magic number, it is the per-device margin llama.cpp's
own fitter keeps when nobody tells it otherwise, and where our estimate
carries all the risk we should be at least as conservative as the child would
have been. Linux and macOS budgets are unchanged, and the monotonicity
property in _vram_reserve_floor_mib still holds at every fraction.

After a full GPU pin comes up healthy, check that the load is actually
resident. Windows exposes the spilled bytes itself through the
'\GPU Adapter Memory(*)\Shared Usage' counter behind Task Manager's shared
memory figure, which nvidia-smi cannot see because on WDDM it reports
dedicated VRAM only. That counter is per adapter rather than per process, so
it is believed only when the device side independently shows the child short
of the weights plus KV cache that full offload must place on the card. Report
only, no recovery.

Warn when a hand-set context does not fit. The planner already prices this
correctly and already hands the load to --fit, but said nothing about why the
context was flexed. The notice also re-prices at q8_0 and mentions it when
that would make the configuration fit, rather than changing a user's cache
dtype for them.

Refs #11349, #11336

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim comments in the Windows sysmem fallback change

* Keep the residency check and context notice from making false claims

The residency check read only -ngl and --fit, so a user extra appended after the
pin that keeps weights or the KV cache on the host (--cpu-moe, -ot, -ncmoe,
-nkvo, --device none, or their LLAMA_ARG_ env twins) was reported as a host RAM
spill. The =-form overrides (--gpu-layers=10, --fit=on) were missed the same way.

The overcommit notice offered the Auto fallback anchor as the largest context
that fits when the weights alone overflow every GPU subset, so lowering the
context to that figure would still not fit. Only offer a context when one fits.

* Scope the residency check to CUDA builds, the loaded adapter and its own process

Arm only when the resolved build is CUDA: a Vulkan launch on an NVIDIA host has
no CUDA sysmem fallback and its ordinals are not NVML indices.

Read Dedicated Usage beside Shared Usage and count shared growth only on the
adapters whose VRAM grew across the spawn, so a display iGPU's churn on an
Optimus laptop is no longer booked as the model's spill.

Hand the verifier thread a snapshot of the armed state and the child it was
started for, and drop its result if that child has since been replaced.

* Check residency before the load returns, and keep its advice accurate

Run the residency check synchronously once the final child is ready, after
every post-health respawn, so the verdict describes the process that is
actually serving and reaches the load response. A warning written after the
response was never shown. The spill notice is appended to an earlier one
instead of losing first-notice-wins.

Offer q8_0 only when the cache is still f16, cap the counted adapters at the
number of pinned cards, key the sysmem-fallback cache by the resolved binary,
and use the Windows wording in the context notice only for CUDA builds.

* Gate the direct spill signal on a full card, and settle before re-baselining

The measured delta carries the CUDA context and compute buffers, so requiring
it to fall short of the weights+KV floor masked small spills such as the 74 MiB
case. WDDM only spills once dedicated VRAM is exhausted, so count shared growth
when a pinned card is nearly full instead.

Wait for a killed retry child's VRAM to settle before sampling the next
baseline, and price the q8_0 hint's compute scratch at q8_0.

* Report the measured spill, judge a full card by its own reserve, drop a stale notice

Name the counter's measured shared-memory growth as the spill amount on a
direct hit; the floor delta can be negative there, since it carries the CUDA
context and compute buffers. Treat a card as full below its proportional
sysmem-fallback reserve rather than a flat 1 GiB, so small cards are not
flagged. Publish the context overcommit notice only when the final plan still
hands the load to --fit on, since slot reduction can re-pin it.

* Word the context notice for planned offload, and tighten the spill report

The overcommit notice fires only once the load was handed to --fit on or a
spill plan, both of which place host tensors deliberately, so the Windows
driver-fallback wording and NVIDIA setting never applied there. Use the CPU
offload wording on every OS.

Sum only positive shared growth across pinned adapters, report spills under
1 GiB in MiB instead of rounding them to 0.0 GB, and key the fallback
classification by build revision so an in-place runtime update is re-read.

* Disarm the residency check on a KV layout change, skip the notice under -nkvo

A retry that respawns with a different slot count or unified-KV setting holds a
different cache than the floor was priced for, so disarm instead of comparing
against the stale floor. With KV offload disabled the cache stays on the host,
so the context overcommit priced from GPU KV bytes is not real.

* Do not cache an empty backend scan

_installed_ggml_backends returns an empty set for an unreadable lib dir instead
of raising, so the transient-failure rule has to cover that result too. Also let
the residency tests import their sibling harness when run on their own.

* Keep host-only tensors out of the residency floor, and tighten the notices

Subtract an untied token_embd (kept on the CPU at full offload) and MTP blocks
that do not load from the floor, by the same rules _unified_need_now uses, so a
healthy load is not flagged as a spill. Skip the context notice when the user
placed tensors on the CPU or fixed the layer count, offer q8_0 only when flash
attention is planned on, and name the executable actually launched in the
driver-setting advice.

* Trim comments added during review

* Drop the post-load residency check; keep the Windows reserve and the context notice

The spill detector could not be validated on Windows NVIDIA hardware and was most
of this change's size and risk. Keep the two parts that stand on their own: the
raised sysmem-fallback reserve on Windows CUDA builds, and the advisory when a
hand-set context does not fit. The backend classifier tests move to the reserve's
test file.

* Skip the context notice for an env-fixed layer count or at the native ceiling

An inherited LLAMA_ARG_N_GPU_LAYERS is a deliberate placement like the argv
flags. When the ceiling sweep stopped at the native context, a larger rope-
scaled window was never searched, so the largest context that fits is unknown.

* Skip the context notice when the user turns the fitter off

User extras follow the generated --fit on, so a trailing --fit off disables the
fitter and nothing moves layers to the CPU; the notice would claim otherwise.

* Register the q8_0 what-if in the split-rate call-site guard

* Trim comments in the Windows reserve change

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Unsloth Studio (AMD): keep export off a GPU PyTorch has no kernels for, like the iGPU (#11946)

* Studio: keep export off a GPU the installed PyTorch has no kernels for

* Trim comments restating the code

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Read the hot-path I/O cost at its steady minimum across repeats (#12029)

* Unsloth Studio: a companion fetch with no denoiser no longer blocks deleting its base (#11828)

A cached repo counts as needing a companion base only if it holds a runnable denoiser. The VAE-only fetch the native engine leaves in unsloth/Qwen-Image-2.1-FP8, and the default pre-cast fp8 text encoder a diffusers load caches at that repo's root, no longer pin Qwen/Qwen-Image-2.1 from a row the On Device list cannot act on. A prequant repo holding its DiT checkpoint still pins its base.

Fixes #11825.

* Studio: stop Python tool network calls from skipping the host allowlist (#11172)

* Studio: check the sandbox host allowlist for keyword, variable and aliased hosts in Python network calls

* Drop two sandbox comments that restate the code below them

* Keep resolving a network alias when the name is rebound elsewhere

* Rank network alias stores by the call they reach and ask on depth exhaustion

* Refuse a network target that is out of policy on any competing store

* Check a connect receiver that is a tracked client on any path

* Keep a valueless store unresolved instead of dropping it

* Read class-body names in source order and match only urllib3 calls that connect

* Check every candidate signature and scope attribute receivers to their owner

* Check the proxy and pool entry points urllib3 exports

* Carry unpacked values to the target they bind

* Memoize alias resolution so a branching chain stays linear

* Ask when alias resolution gives up on the callee

* Expand conditionals so every branch of a target is checked

* Let an unconditional rebinding replace the value a later read sees

* Check session and pool request methods, and only supersede on a certain binding

* Keep the enclosing binding when a class store may not run

* Take each client method's URL position from its real signature

* Check client base URLs, parameter defaults and self-referential stores

* Resolve prebuilt requests and check explicit proxy destinations

* Cover OPTIONS and the modules these APIs are actually defined in

* Resolve a client kept on an attribute

* Follow base classes, cover session uploads and websockets, drop the quadratic scan

* Make a binding take effect at the end of its statement

* Resolve a walrus callee to the callable it assigns

* Apply the literal-target fallback only to listed entry points

* Only read a call result as its constructor when that names a known client

* Cover raw urllib3 connections, renamed receivers and disabled proxies

* Treat the lowercase session factory and aiohttp's request helper as entry points

* Resolve constant getattr dispatch and cover aiohttp uploads

* Check the payload where a request is built

* Bind a definition name after its header runs

* Keep the stores that resolved when a sibling store hits a cycle

* Resolve a connect receiver with the same resolver as every other callee

* Put a client's connect in the target table and stop reading stores that have not run

* Generate the urllib3 URL factory specs from the module that defines each

* Keep source order inside the body that does the reading

* Check the encoded pool helpers and a proxy set on the session

* Give attribute stores the same reaching rule as name stores

* Tie a receiver's attributes to the binding in effect at the call

* Parse the URL the client will send, and follow a mutated proxy mapping

* Sequence a finally block with the statements that follow the try

* Key attribute stores on the whole receiver path

* Read attribute stores under the dotted paths they are recorded with

* Port client, proxy and SSH egress coverage onto the alias screen from main

* Trim comments on the ported egress tables

* Track annotated assignments, share proxies across client copies, skip static methods

* Treat local client subclasses as the client, and follow aliased proxy mappings

* Read base_url stores on a client and in-place proxy merges

* Scope client destination attributes to the client that reads them, and cover asyncssh.connection

* Resolve network submodule paths to the names their package re-exports

* Read a proxy without a scheme as a host

* Skip mapping keys and None destinations

* Skip no_proxy entries in proxy mappings

* Screen uploads through httpx stream, and follow clients passed to local functions

* Track subclasses of connecting classes, and read httpx transport proxies

* Follow clients passed to local methods

* Propagate clients along every recorded copy, and bind unbound method calls

* Track clients bound by loop and comprehension targets

* Follow clients returned by local factories, and link helper parameters to their callers

* Follow factory methods and awaited factories

* Follow aliases of local functions

* Read class-body clients in their own body, and read authority-relative URLs

* Screen PoolManager.connection_from_host

* Bind calls and index flows after every alias is collected

* Tighten comments on the egress screen additions

* Screen datagram destinations on sendto and sendmsg

* Apply proxy stores after binding, and read proxy environment variables

* Resolve os and environ aliases for proxy environment stores

* Screen urllib openers and ProxyHandler mappings

* Follow wrapper instances, read environment mappings, and scope environment proxies

* Reach inherited client methods through self, and read expanded environment updates

* Read mutated environment mappings and os.environ merges, and honour aiohttp trust_env

* Resolve environment keys held in variables, and bind local constructor arguments

* Treat lambdas bound to a name as local functions

* Handle annotated assignments through the same binding path as plain ones

* Follow inherited initializers, inline wrappers, environ aliases and super()

* Carry os.environ through helper parameters

* Check asyncssh tunnel and proxy_command, and honour httpx trust_env=False

* Treat a paramiko sock argument as unreadable

* Screen asyncssh.connect_reverse, and follow clients returned by properties

* Carry the os module through assignments and helper parameters

* Check SSH routing keywords from one table, including Fabric gateway

* Limit the sock routing rule to SSHClient.connect

* Check asyncssh connection options, and read named proxy mappings

* Follow bound local methods saved under another name

* Track proxy-manager factories and SOCKSProxyManager as pool clients

* Read a path with a relative literal prefix as hostless

* Read a wholesale os.environ replacement

* Trim comments in the egress screen additions

* Index shadowed names by scope so the egress screen stays linear on class-heavy code

* Read a backslash as the end of the host, and follow class attributes and unpacked factory tuples

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read proxy writes through os.environb, and fail closed on a Fabric connect_kwargs sock

* Never trust a host with a backslash, and read filled-in Fabric kwargs and getattr environ writes

* Check positional SSH route arguments for paramiko connect and Fabric Connection

* Read an explicit environ __ior__ call like update

* Trim comments in the egress screen fixes

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Maheswar Kumar <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Studio: center collapsed sidebar icons and tighten the rail (#12031)

* Studio: center collapsed sidebar icons and tighten the rail

The nav icon's expanded-row nudge also applied in the collapsed rail,
leaving each icon 2px right of its hover circle. Drop it there, use
30px round hover targets throughout the rail (including the open
sidebar toggle), and sit the settings cog one nav row above the avatar.

* Studio: shrink collapsed sidebar hover circles to 28px

* Unsloth Studio: list a GGUF with no header metadata under On Device on the Images page (#11830)

* Studio Hub: classify a GGUF whose header names no architecture from its name

unsloth/Qwen-Image-2.1-GGUF files carry no general.* keys at all, so _arch_to_task answered None. The Images picker filters On Device rows on an exact task and dropped the row; the unfiltered Chat picker listed it and refused it. A readable header that names nothing now takes the same name-only route as a cloud placeholder.

* Trim comments on the no-architecture GGUF classification

* Keep the MiniMax-H3 conditioner out of the name-only video route

---------

Co-authored-by: Daniel Han <[email protected]>

* Keep the conversion backfill's donor stub off the transformers package (#12034)

* Unsloth Desktop: show Stopping… after Stop so a pending cancel doesn't look ignored (#11976)

* Studio: show Stopping… after Stop so a pending cancel doesn't look ignored

* Studio: tighten stop-label comments

---------

Co-authored-by: Daniel Han <[email protected]>

* Studio: stop edit_file writing a compacted-argument placeholder into files (#11950)

* Studio: stop edit_file writing a compacted-argument placeholder into files

* Trim comments in the compaction receipt guard

---------

Co-authored-by: Daniel Han <[email protected]>

* Studio: decode Wan video in fp16 with channels_last_3d convs (#11999)

* Studio: decode the Wan video VAE in fp16 with channels_last_3d convs

* Format

* Trim the fp16 decode docstring

* Trim fp16 decode comments

* Unsloth Studio: refuse picking a hosted FP8/INT8 checkpoint repo as a pipeline before it downloads (#11829)

* Studio: refuse a pipeline pick of a hosted prequant repo before it stages anything

A pick of unsloth/Qwen-Image-2.1-FP8 with no file name is a pipeline load, and validate_load_request let it through: the family detects from the id and unsloth/ clears the trust gate. The plan staged the repo's 14 GB of checkpoints, then from_pretrained 404d on the model_index.json the repo does not have. The hosted prequant repos are now a table (prequant_only_repo_ids) and a pipeline pick of one is refused with the base repo and precision to pick instead.

* Skip the hosted prequant-repo pipeline refusal when repo_id is an existing local path

- The new prequant-repo pipeline refusal matched the repo id by exact string, so a local pipeline directory cloned to that same relative name (e.g. ./unsloth/Qwen-Image-2.1-FP8 with a valid model_index.json) was wrongly rejected. It now skips the refusal for local paths and lets the existing local manifest validation handle them.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: trim comments in prequant pipeline-pick refusal

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>

* Studio: stop the second prompt length recompiling Qwen-Image on the max tier and with int8 (#11842)

* Studio: compile the prompt-length dims of Qwen-Image DiT blocks dynamic from the first render

The max tier (and torchao weights on the default tier) compiles DiT blocks with
automatic dynamic, so the first prompt's token count was compiled static and the
first prompt of a different length recompiled every block graph into the
generalised form it then kept (Qwen-Image-2.1: 14 s int8 default, 31 s bf16 max,
51 s int8 max; Qwen-Image: 52-57 s max).

Name the block inputs whose size follows the prompt in
torch.compiler.config.dynamic_sources, set only around the owning transformer's
forward and restored even when it raises, so the first compile already builds the
generalised graphs. The first segment start of Qwen-Image-2.1 stays static, which
keeps clear of the torchao CantSplit that dynamic=True hits. The compile-cache key
gains the allowlist only for these families. torch without the knob (2.6) is
unchanged.

* Studio: also mark Qwen-Image's text inputs dynamic when FBCache calls the blocks through hooks

FBCache is on by default for Qwen-Image, and its hooks pass the block inputs as
kwargs (or a resumed frame's stack after a graph break), so the plain L[...]
names never matched and the second prompt length still recompiled. Suffix
patterns cover those paths on torch 2.8+.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: ruff format

* Arm the prompt-length allowlist only on torch 2.8+

torch 2.7 caches its first read of compiler.config.dynamic_sources for the
life of the process, so scoping the list to one forward is either ignored or
leaks it into every later compile. 2.8 re-reads it when it changes and adds
regex matching (is_dynamic_source), which the FBCache hook paths also need.
Older torch keeps today's behaviour.

* Trim comments

* Trim comments on the prompt-length allowlist

* Trim dynamic text dims comments

* Drop dead torch<2.1 hook fallback and redundant in-test skips

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten dynamic text dims docstrings

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Studio: size the image memory plan at the dtype the pipeline loads in (SDXL resident on 24 GB) (#11922)

* Studio: size the diffusion memory plan at the dtype the pipeline loads in

The pipeline memory plan summed the cached shard bytes, which is what a repo
stores rather than what the load holds. SDXL and SDXL-Turbo publish fp32
weights (12.9 GB) that load as 6.5 GB in bf16/fp16, so 20-24 GB cards planned
whole-model offload for a model that fits resident, and a 16 GB unified-memory
Mac refused it outright. Lumina-2 and Z-Image-Turbo ship fp32 shards the same
way, and a cache holding fp16 variant twins, .bin twins or a single-file
checkpoint beside the pipeline counted weights the loader never opens.

Price each cached weight file the way from_pretrained materialises it:
default-variant component files only, safetensors over a .bin twin, and a
file whose floats are all wider than the load dtype at that dtype. Mixed
precision, quantised and fp8 files, components whose class pins modules in
fp32, and fp32 loads keep their stored size, and the estimate only ever
lowers. Download sizes and disk checks are unchanged.

* Studio: let the mirrored companion stub take the load itemsize

* Studio: shorten the load-dtype sizing comments

* Studio: widen half-precision weights on an fp32 load, keep a .bin the loader falls back to

An fp32 target (a Mac without bf16, an fp16-incompatible family on an fp16
card) materialises bf16/fp16 shards at four bytes per element, so price every
float at the load width there. A .bin is dropped only when its folder holds a
safetensors checkpoint the loader can select: an unsharded file, or shards with
their index.

* Studio: honour Transformers' non-strict fp32 pins only on fp16 loads

Transformers upcasts _keep_in_fp32_modules only when the load dtype is fp16
and _keep_in_fp32_modules_strict for both halves; Diffusers upcasts its set
for both. A bf16 load of an fp32 T5 checkpoint is therefore priced at bf16.

* Studio: price fp32-pinned modules at four bytes in half-precision loads

A component whose class keeps modules in fp32 (T5's wo at fp16, a strict or
Diffusers pin at either half) holds those tensors at four bytes whatever the
checkpoint stores, so price them per tensor instead of leaving the file at
its stored size.

* Studio: match fp32 pins against the parameter path the way each loader does

* Studio: price a surviving .bin checkpoint at the load dtype too

* Studio: count a tied .bin weight once when pricing it

* Studio: trim comments in the load-dtype memory plan

* Studio: stop MiniMax-H3 recompiling on the second caption and the first i2v (#11880)

* Studio: compile the prompt-length dims of Qwen-Image DiT blocks dynamic from the first render

The max tier (and torchao weights on the default tier) compiles DiT blocks with
automatic dynamic, so the first prompt's token count was compiled static and the
first prompt of a different length recompiled every block graph into the
generalised form it then kept (Qwen-Image-2.1: 14 s int8 default, 31 s bf16 max,
51 s int8 max; Qwen-Image: 52-57 s max).

Name the block inputs whose size follows the prompt in
torch.compiler.config.dynamic_sources, set only around the owning transformer's
forward and restored even when it raises, so the first compile already builds the
generalised graphs. The first segment start of Qwen-Image-2.1 stays static, which
keeps clear of the torchao CantSplit that dynamic=True hits. The compile-cache key
gains the allowlist only for these families. torch without the knob (2.6) is
unchanged.

* Studio: also mark Qwen-Image's text inputs dynamic when FBCache calls the blocks through hooks

FBCache is on by default for Qwen-Image, and its hooks pass the block inputs as
kwargs (or a resumed frame's stack after a graph break), so the plain L[...]
names never matched and the second prompt length still recompiled. Suffix
patterns cover those paths on torch 2.8+.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: ruff format

* Arm the prompt-length allowlist only on torch 2.8+

torch 2.7 caches its first read of compiler.config.dynamic_sources for the
life of the process, so scoping the list to one forward is either ignored or
leaks it into every later compile. 2.8 re-reads it when it changes and adds
regex matching (is_dynamic_source), which the FBCache hook paths also need.
Older torch keeps today's behaviour.

* Trim comments

* Studio: compile MiniMax-H3's packed length dynamic from the first render

A new caption changes H3's packed video + audio + caption length, and the
first new caption after load recompiled the denoiser blocks (about 11 to 22 s).
Name those inputs in the prompt-length allowlist so the first compile is
already general, and keep the small-M int8 padding free of a branch on the
row count when traced, which otherwise guarded the caption length to <= 31
rows and recompiled the refiner on the first i2v (a 540-row caption).

* Pad traced rows with arithmetic max so a concrete row count still compiles

torch.sym_max on a concrete int is rejected by dynamo on torch 2.8 and older,
so a static compile of a padded int8 Linear broke (fullgraph drops the DiT to
eager). builtin max() compiles but left an m <= pad_to guard behind on an
inductor cache hit. (m + p + |m - p|) // 2 does neither.

* Trim comments on the prompt-length allowlist

* Trim comments on the H3 allowlist and traced row padding

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim dynamic text dims comments

* Drop dead torch<2.1 hook fallback and redundant in-test skips

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten dynamic text dims docstrings

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Unsloth Studio / Desktop: log what an image load and each generation actually resolved to (#11994)

* Studio: log what an image load and each generation actually resolved to

* Studio: trim comments on the resolved and generation log lines

* Studio: build the diffusion.loaded resolved field from the committed load state

* Studio: log the applied denoise strength and native sd.cpp LoRAs in diffusion.generated

* Studio: log the effective upscale factor, and only for the upscale workflow

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Unsloth Studio: stop offering "Continue" on a base repo that only holds a GGUF's text encoder and VAE (#11644)

* Unsloth Studio: stop offering "Continue" on a base repo that only holds a GGUF's text encoder and VAE

A companion-only snapshot stays partial so no picker loads it, but a new
companion_prefetch flag keeps the Hub from presenting it as an unfinished
download whose Continue pulls the denoiser the GGUF replaces.

* Carry companion_prefetch through the local listing the Hub merges

The Hub merges /api/hub/cached-models with /api/hub/local, and the local
scanner knew nothing about companion-only snapshots. After a real GGUF
load, its row for the base repo stayed Partial, and the detail pane still
offered Continue at 33 GB. When the base repo held VAE and encoder shards,
the same scanner classified it as a complete safetensors model instead,
and the Hub offered Run on a pipeline with no denoiser.

The local scanner now reads the same signal on the snapshot it lists:
such rows are partial, as the cached listing marks them, and carry
companion_prefetch. The frontend honours the flag on local rows too.

* Keep a companion-only base repo out of model Discover's on-device and partial states

buildDiscoverRows read partial and on-device straight off the cached or
local row, so the new flag never reached the model Discover grid: the repo
still read as a partial download there.

* Show a companion-only base repo as a plain Download, not On device with Run

Excluding the flag from the partial hf_cache branch sent the local row into the
fully local view, which claims the repo is on device and offers Run on a
pipeline with no denoiser. Keep the branch and clear only the partial state.

* Key the Discover memo on the companion flag

A companion fetch finishing leaves partial true on both listings and flips only
companion_prefetch, so the signature the model Discover memo is keyed on did not
change and the grid kept the repo as on device and partial.

* Trim companion_prefetch comments

* Keep Delete on a companion-only repo's download card

The card gated its repo menu (Delete, path) on isDownloaded || isPartial,
and a companion-only repo is now neither, so 19 GB of borrowed text
encoder and VAE could no longer be deleted from the detail pane.

* Drop the green On device dot from a companion-only inventory row

* Trim comments

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: Daniel Han <[email protected]>

* Apply SFTConfig.router_aux_loss_coef to MoE models that cache it at init (#12006)

* Apply SFTConfig.router_aux_loss_coef to MoE models that cache it at init

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten router_aux_loss_coef sync comments

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Load only the language model for text_only on repo-code composites (#11861)

* Load only the language model for text_only on repo-code composites

FastModel.from_pretrained(text_only = True) skipped the vision tower only for
families with their own text decoder (gemma3 -> gemma3_text). A repo-code
composite such as Nemotron-3-Nano-Omni (llm_config + vision_config +
sound_config, one wrapper class in auto_map) failed that test, so the whole
wrapper was loaded and its forward required pixel_values.

When trust_remote_code is set, the parent config is repo code, and every
parameter of the text sub-config's causal LM (built on the meta device) is
stored under exactly one checkpoint prefix, load that causal LM alone with a
key_mapping stripping the prefix. Anything else keeps the previous full-model
load, so no text weight can be left randomly initialised.

* Also find the decoder of a repo-code composite under llm_config

InternVL and Llama-Nemotron-Nano-VL keep the decoder config as llm_config
without the text_config alias get_text_config() reads, so the text-only
plan never saw it. Fall back to llm_config / language_config; the
full-coverage checkpoint check still decides whether the branch is taken.

* Keep the full-model load for repo-code composites on transformers 4.x

transformers 4.x decides base-model vs task-model prefix handling from the
checkpoint keys before key_mapping renames them, so a language_model.
prefixed checkpoint either raises "state dictionary ... corrupted" or, with
tied embeddings, loads every text weight as missing. Decline the text-only
plan below 5.0 and skip the positive tests there.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Record the commit a trusted load ran repo code at

A merged export that re-reads the repo's config with its code pins it
to this commit instead of the branch head. Under text_only the model's
config is the nested text config, which carries no commit, so the
composite config's commit is taken before the remap.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Pin the text-only config of a repo-code composite to the parent commit

* Read a cached unsharded checkpoint when the text-only plan runs offline

* Keep the full composite for adapters trained on it under text_only

* Decline the text-only plan for repo-code composites under fast_inference

* Accept sequence-valued auto_map entries in the text-only self-reference check

* Rebase llm_int8_skip_modules once from the parent names for nested text prefixes

* Pass torch_device to PeftModel.from_pretrained in the text-only adapter test

* Probe sharded .bin composites for the text-only plan from their index

* Pass local_files_only to the nested text class lookup of the text-only plan

* Read adapter_model.bin names when deciding whether an adapter fits the text model

* Probe the text-only plan at the commit its config was resolved at

* Decline the text-only plan when the nested text class lives in another repository

* Probe the text-only plan checkpoint under the requested subfolder

* Keep the full composite for a device_map keyed on its module names

* Probe the text-only plan checkpoint at the requested variant and cache_dir

* Resolve the nested text class at the requested code_revision

* Keep the full composite for an adapter on wrapper-only modules

* Rebase the caller's quantization_config skip modules for the text-only plan

* Stamp the code_revision commit as the trusted remote code commit

* Stamp the rebased quantization_config on the text-only decoder

* Save the text-only decoder under its standalone weight names

* Pin the wrapper-only adapter test's PEFT load to the CPU

* Give the text-only test namespace the remote class resolver resolve_model_class now calls

* Trim comments in text-only remote composite loading

* Add the license header to the text-only remote composite tests

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Try the text-only plan when a repo-code wrapper is its own text config (InternVL)

* Rebase every quantization module-name list on the text model, and keep the full model for a regex that names the prefix

* Detect a quantization regex that escapes any dot of a nested text prefix

* Tighten comments in the text-only remote composite path

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Put back the unsloth_zoo modules the device map opt-in tests stub (#12038)

* Studio: pass tool_result is_error through to the model on /v1/messages (#11962)

Keep the Anthropic tool_result is_error flag on /v1/messages and mark failed tool output with an Error: prefix (or a short note when the output is empty) so the local model can tell a failed tool call from an empty success.

* SentenceTransformer: add opt-in…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.