Skip to content

Merge main into pip - #10513

Merged
danielhanchen merged 211 commits into
pipfrom
merge-main-into-pip-2026-09
Sep 8, 2026
Merged

danielhanchen merged 211 commits into
pipfrom
merge-main-into-pip-2026-09

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Merges main into pip. pyproject.toml was the only conflict.

pip is the branch that gets uploaded to PyPI, and PyPI rejects any PEP 508 direct reference in Requires-Dist (Invalid value for requires_dist. Error: Can't have direct dependency, pypi/warehouse#7136), so the resolution keeps that rule and takes everything else main added.

Extras brought across

All 22 extras main added since the last merge are here:

  • cu126/cu128/cu130onlytorch2110, and cu126/cu130onlytorch2120 and onlytorch2121, plus their -torch and -ampere-torch wrappers. The torch trio keeps main's +cuNNN pins verbatim, since those are plain version specifiers and publish fine. The xFormers rows become xformers==0.0.35 with the two platform markers merged into the single marker this branch already uses everywhere else, because the wheel URL cannot go into published metadata.
  • torch==2.10.0 added to the three onlytorch2100 leaves, matching main, so ARM64 stays on 2.10 where the x86-64-only xFormers wheel and its transitive pin are skipped.
  • audio-torch211, plus main's tightened python_version ceilings on the older audio-torch rows.

The 30 extras main carries that this branch still does not are the same ones as before the merge: the intel*, rocm* and flashattentiontorch*cu12x families, which pin wheels by URL from the Intel, AMD and GitHub release indexes and have no PyPI equivalent.

Base torch ceiling

Raised from <2.12.0 to <2.13.0. The new 2.12 leaves pin torch==2.12.x, and this branch declares the full runtime in [project].dependencies, so a <2.12.0 base made those extras unresolvable against their own base dependencies.

Two drifts fixed in the same file

Both had a red test on pip pointing straight at them before this merge:

  • jinja2>=3.1.0 was missing from the studio extra while studio/backend/requirements/studio.txt lists it, so pip install "unsloth[studio]" built a venv the server cannot boot.
  • src-tauri/icons/icon.icns and icon.png were missing from studio package-data, so the published wheel shipped no icon for install.sh to build the macOS .app and Linux .desktop launchers from.

Test guards

Three guards asserted main's spelling of an xFormers pin rather than the property being guarded, so they could only ever hold on one branch. They now accept both forms and are unchanged in verdict on main:

  • test_torch2110_cuda_extras.py and test_windows_xformers_wheel_match.py check the version and the Linux/Windows markers on both forms, and the index only on the URL form, which is the only form that carries one.
  • test_scan_packages.py: torch is digest-pinned in the scan baseline and is a range here, because a published wheel cannot exact-pin torch without putting every pip install unsloth on one build. Allowed by name, only for the pyproject half, with the bound itself asserted so it cannot become open ended.
  • test_wheel_smoke_publish_guard.py (pip only) read two checked-in files with the platform default encoding, which main's new test_source_read_encoding.py flags.

The first three are also going to main separately so the two branches stop diverging on them.

Testing

Every test file that reads pyproject.toml, on the merge result:

2695 passed, 187 skipped in 174s

origin/pip had 13 failures in that same set before this merge, and origin/main's copies of the three adapted guards pass unchanged.

danielhanchen and others added 30 commits September 2, 2026 06:10
* Add DeepSeek Harness (dsh) to unsloth start

Claude-Session: https://claude.ai/code/session_01NMn7rbPGP6zaxhFu6tcaFg

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

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

* Pin dsh permission mode and forward --reasoning-effort

* Apply repo kwarg-spacing format to the new dsh tests

* fix: reject unrelated dsh executables

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

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

* fix: resolve the intended DeepSeek Harness binary

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: imagineer99 <[email protected]>
* Stop non-streaming Anthropic generation when the client disconnects

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

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

* Studio: record an abandoned non-streaming run as cancelled

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
* Restore the comment tails the trim cut off

The comment passes in #10112, #10115, #10116 and #10118 enforced the 120-column
limit by chopping the physical line rather than rewrapping it, so a block's last
sentence stops mid-thought and the clause carrying the reason goes with it. 63
blocks across 38 files, restored from the pre-merge text and rewrapped at word
boundaries.

The ones that matter most are load-bearing:

    -# The FLAVOR, never the index URL it came from
    +# The FLAVOR, never the index URL it came from: a pinned index can carry a token in its userinfo, query or
    +# fragment, and the manifest is world readable.

    -# Do not guess the cause: the preflight line the app already printed says
    +# Do not guess the cause: the preflight line the app already printed says which of the two it is, and naming the
    +# wrong one sends the reader to the wrong fix.

Only blocks where the pre-merge text continues the same sentence where the
current text stops are touched: a dangling function word, an unbalanced bracket
or code span, a trailing abbreviation, or a lowercase continuation. A block that
ends on punctuation before a new sentence was shortened on purpose and is left
alone. No word is invented; every restored word comes from the pre-merge text.
Pragmas, shebangs, coding lines, licence headers and rule-line banners are
skipped, and the change is scoped to the 569 files those four PRs touched.

comment_tools.py check is 38/38 comment-only. Full suite is 65 failed / 18693
passed, matching main exactly.

* Revert the geglu restoration, that block was never truncated

* Restore five comments the trim overwrote with another comment's text
…t formats (#9738)

* Studio: accept subtitle, caption and the rest of the common attachment formats

.srt and .vtt are plain UTF-8 but were on no allowlist, so the picker greyed
them out and a native drop was refused outright. Same story for a long tail of
ordinary text formats, and for audio and video containers the backend already
decodes.

Text: 80 extensions to 285. Subtitles (.srt .vtt .sbv .ass .ssa .sub .lrc),
docs (.tex .bib .adoc .org .rmd .qmd), data (.jsonc .json5 .geojson .har .plist
.avsc), localisation (.po .strings .resx .xliff .ics .vcf .eml), templates
(.erb .ejs .hbs .jinja .twig .liquid .razor .pug) and ~120 more languages
(.hs .ml .ex .erl .fs .clj .zig .nim .cr .cu .cuh .sol .cairo .mojo .f90 .cob
.ada), shaders, shells and build files.

Audio: .opus .aac .aiff .aif .aifc .caf .wma .amr .mp2. Every one of these
already decodes through libsndfile or librosa in _decode_audio_mono, so the
picker was stricter than the pipeline. .webm and .mp4 stay off the extension
list: the audio adapter runs before the video one and would claim video files.

Video: .m4v .mpg .mpeg .wmv .flv .3gp .ogv, all of which ffmpeg reads. .ts and
.mts stay off because they are TypeScript here.

Also mirrors the lists into native_path_policy.rs and the MIME tables in
native_intents.rs, and replaces native_clipboard.rs's hand-copied 70-extension
duplicate with a TEXT_ATTACHMENT_EXTS lookup so it cannot drift again.
Syntax highlighting gains 167 shiki mappings for the new formats.

Images stay at jpeg/png/webp/gif on purpose: files go to the model as raw
base64, and the external providers accept only those four.

* Fix attachment type detection edge cases

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

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

* Fix remaining attachment review issues

* Fix attachment review edge cases

* Fix remaining attachment review findings

* Fix latest attachment review findings

* Fix attachment format parity edge cases

* Handle legacy attachment format edge cases

* Bound the audio-input decode and handle two more legacy attachment cases

Three findings from the latest review round.

The non-GGUF audio-input path decoded with torchaudio and never applied the
decoded-duration cap, unlike the GGUF path. A low-bitrate AMR or WMA under the
25 MB upload limit can hold hours of PCM, so the decode now checks the reported
length, reads at most one frame past the cap when the container hides its
length, and returns 413 rather than a server error.

A subtitle saved in a legacy code page decoded as lenient UTF-8, replacing
every non-ASCII byte. Text attachments now decode UTF-8 strictly and fall back
to windows-1252, which maps every byte, so the text arrives readable. A
streaming decode keeps a bounded preview that cuts a character in half on
UTF-8 rather than treating the cut as a legacy encoding.

Compiled gfortran .mod modules are gzip, which the tracker-module check does
not see, so they were decoded as text. Browser, native drop and native
clipboard intake now reject them; text .mod files including go.mod and
uncompressed gfortran modules stay accepted.

The fourth finding, that the generic text MIME fallback in native_intents.rs
and native_clipboard.rs stamps every text extension text/plain, is not
reproducible. is_text_attachment_name matches the whole filename against
TEXT_ATTACHMENT_NAMES, which holds only "containerfile", so the early return
cannot fire for .json, .csv, .plist or .vtt. The Rust tests said to be failing
pass: 429 of 429, including clipboard_file_mime_types_cover_text_attachments,
which asserts data.json stays application/json.

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

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

* Name an undecodable encoding instead of guessing it, and reject OLE templates

Two findings from the latest review round.

The windows-1252 fallback added in the previous commit was wrong for anything
outside Western Europe: the same byte is a different letter in windows-1252,
windows-1251 and Shift-JIS, so a Russian or Japanese subtitle decoded cleanly
into confident mojibake. Which one it is cannot be known from the bytes, and
mojibake is worse than a refusal here because nothing downstream can tell it is
wrong. Text attachments now fail with UndecodableTextError naming the file and
asking for UTF-8. The composer decodes while attaching so the message arrives
with the file rather than at send, and the preview already renders a failed
read as an error state.

This also covers the earlier lenient-UTF-8 behaviour, which replaced every
non-ASCII byte and attached the file as though it had been read.

Legacy Word .dot and PowerPoint .pot templates are OLE compound files sharing
their extensions with Graphviz and gettext, so they were decoded as text.
Browser, native drop and native clipboard intake now reject the OLE signature;
Graphviz .dot and gettext .pot stay accepted.

* Bound text attachments, and honour the charset an email declares

Two findings from the latest review round, both on the previous commit.

Reading while attaching made the missing size bound reachable much earlier: a
multi-gigabyte .mbox held its bytes and its decoded string at once, in the
webview, before the user could send anything. The adapter now stops at 20 MB
before any read, matching MAX_NATIVE_TEXT_BYTES so the browser and desktop
paths accept the same sizes. A test reads the Rust constant and asserts the two
agree.

Refusing every non-UTF-8 file was too broad for email. An 8-bit .eml or .mbox
declares its charset in the Content-Type header, so that is knowable rather
than guessed, and is now honoured, including across folded header lines. It is
tried only after UTF-8 fails, so a modern message is never remapped by a stale
declaration, and a message declaring nothing is still reported rather than
guessed at.

Writing those tests turned up a hole in the previous commit: decoding always
passed stream:true, so a file whose last byte was a dangling UTF-8 lead byte
had that byte dropped silently instead of reported. Tolerating a cut tail is
only correct when the input really was cut, which only the caller knows, so
that is now a parameter the bounded preview sets and a whole-file read does
not.

* Read a text attachment once instead of once per stage

Decoding while attaching, added in the previous commit to report a bad encoding
early, left the file being read twice: add() decoded all of it, discarded the
result, and send() decoded it again. At the 20 MB cap that is two full reads and
two decoded strings per attachment.

Both stages now go through readTextAttachmentOnce, which caches the decoded text
in a WeakMap keyed by the File, so a removed attachment retains nothing. A
regression counts arrayBuffer calls across the two stages.

* Accept a dropped Dockerfile and Makefile, as the picker already does

assistant-ui derives a file's extension as `.${name.split(".").pop()}`, so an
extensionless Dockerfile reads as ".dockerfile" and the picker claims it through
the token already in the accept list. The drop classifier and the mirrored Rust
policy recognised only Containerfile, so the same file dropped from the desktop
shell was refused.

Both lists now carry every conventional extensionless name whose token is
present. A name with no such token, GNUmakefile for instance, stays out of both
rather than being widened. The regression derives the expectation from the
matcher's own rule instead of restating the list.

* Bound the probe-failure decode, and read declared charsets per container

Four findings from the latest review round.

A container torchaudio.info cannot read was still loaded whole to find out how
long it was, which is what the duration cap exists to prevent. That case now
goes to the bounded decoder the GGUF path uses, which stops at the cap as
frames arrive. torchaudio.load is never called without a frame bound.

Reading only the first Content-Type meant a multipart message with the charset
on its parts was refused, while an mbox holding messages in different charsets
was decoded end to end with the first one and silently corrupted. The scan now
collects every declaration: one distinct charset decodes the file, several
refuse it by name rather than corrupting all but one part.

A vCard 2.1 declares its encoding on the property, so .vcf files now use the
same scan instead of being refused for carrying bytes they describe.

Compare mode classified audio only by file.type, which browsers leave empty for
several of the containers this branch added, so a dropped .wma or .amr was
ignored and the picker hid it. It now shares the chat composer's accept list
and its name fallback.

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

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

* Scan the whole file for charset declarations, not the first pages

The declaration scan stopped at 64 KiB, so an mbox whose later message declared
a different charset was decoded end to end as the first one. Reproduced with an
ISO-8859-1 message followed past the cutoff by a windows-1251 one: the Cyrillic
came out as Latin mojibake, which is the failure the unanimity rule was added to
prevent, just moved behind a byte offset.

Any cutoff has that failure, so there is no longer one. The attachment is
already capped at 20 MB and the scan only runs once UTF-8 has failed, which at
that size costs 46 ms; a valid UTF-8 file never reaches it.

* Bound decoded audio by samples, and honour two more declared encodings

Five findings from the latest review round.

The decoders capped audio by duration alone, which is rate-relative: 30 minutes
at 48 kHz retains 86M float32 samples where the same speech at 16 kHz retains
29M, and np.concatenate doubles whichever it is. An absolute ceiling now sits
beside the clock, set at 48 kHz for the full 30 minutes so it never bites before
the advertised limit at any ordinary rate.

The librosa fallback ran the whole file through audioread and checked the length
afterwards, which is too late to matter. It now asks for the native rate and
reads a window bounded by both the clock and that ceiling.

The email scan matched any line starting with Content-Type, so quoted mail or a
config snippet in a body counted as a second declaration and refused a file that
says one thing. It now reads only header blocks: from the start, an mbox
separator, or a MIME boundary, to the first blank line. Real part headers still
count, so genuinely mixed containers are still refused.

An XML document states its encoding in the prolog. That is read from the bytes
rather than the extension, so .resx, .xliff, .xlf, .svg and the project files
are all covered rather than refused for carrying what they describe.

Pasting a video used the 20 MB source cap while the picker and the drop path
took up to 72 MB, so most clips reported no readable clipboard files. Video now
has its own budget, mirrored from the drop path with a test that reads it.

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

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

* Apply the sample ceiling to torchaudio, and decode declarations strictly

Three findings from the latest review round.

A successful torchaudio.info bypassed _decode_audio_mono, so the decoded-sample
ceiling never ran on that path and load() still bounded only by the clock, at
every channel and the native rate. load() is now used only when info reports a
length that fits the ceiling; anything wider goes to the bounded reader, which
downmixes as it reads. A file inside the 30-minute limit is streamed rather than
refused, so the advertised limit still means what it says.

The declared-charset paths decoded leniently, so a .po or an XML prolog claiming
UTF-8 while holding broken bytes came through as replacement characters. That is
the corruption the strict default exists to prevent, reached through the branch
that trusts the file. Declarations are now decoded strictly and refused by name
when the bytes do not match, with the same allowance for a preview that cut a
character in half. Single-byte charsets map every byte and are unaffected.

Pasting a 3GP still used the audio-sized provisional limit while other videos
moved to the video budget last commit, so a 3GP video above 25 MB was skipped
before its tracks could be read. It is read under the video bound like the drop
path, and the audio cap is reapplied afterwards if the tracks say audio-only.

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

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

* Fix a quadratic header scan, and decode every declaration strictly

Six findings from the latest review round.

The header-block scan restarted its search from every candidate boundary, so a
body of diff hunks, where every line begins with dashes, was quadratic: a
megabyte took 14 seconds, on the UI thread inside add(). One forward pass over
the lines, slicing only the header regions, takes 8 ms for the same input.

An XML prolog is the document's encoding by specification, but it was only
consulted after UTF-8 failed, so bytes that happen to be valid UTF-8 decoded
into different characters than the document states it holds. The prolog now
decides first. Mail and vCard declarations stay a fallback, since mislabelled
8-bit mail is common and its bytes being valid UTF-8 is the better evidence.

The UTF-16 BOM branch decoded leniently and ignored the truncation flag, so an
odd trailing byte or an unpaired surrogate was padded with a replacement
character and attached as though it had been read. It goes through the same
strict decoder as everything else now.

Without a sample rate there is no window that bounds the librosa fallback: 30
minutes is gigabytes at a high rate. An unprobeable rate is refused rather than
read to find out, which costs nothing a container that soundfile and PyAV both
declined would otherwise get.

An overlong upload on the GGUF path reported 400 "Could not decode" while the
non-GGUF path reported 413 with the limit, so a long but valid file was
indistinguishable from corrupt audio.

The sample-ceiling regression allocated the production constant, 346 MB per
run. It uses a small monkeypatched ceiling, since the check is what is
under test.

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

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

* Read a 3GP's tracks, and only trust a declaration where one can be made

Cap a torchaudio read by the sample ceiling as well as the clock. num_frames
is the value being distrusted there, so a container that understates it was
still allowed to read rate * 30 minutes: 345M frames per channel at 192 kHz.

Classify an audio-only 3GP from its BMFF handlers before an adapter is picked.
A composite matches on name and MIME, both of which say video, so a voice
recording was refused on an audio model and sent as frames on a video one. The
native readers already inspect the tracks; the browser and compare now do too.

Reopen mail headers only at a boundary a header declared. Any line starting
with "--" reopened them, so a signature marker or a closing delimiter turned
the body back into headers and a quoted Content-Type became a second charset.

Read a vCard charset only from a property's parameters. The whole-file scan
matched inside values, so an escaped ";CHARSET=" in a NOTE counted as a second
declaration and refused a card that names exactly one.

Make PyAV optional in the audio container tests, as the other suites do.

* Read a 3GP's track table without holding the container

Walk the top-level boxes through slices and read only moov. The handlers are
there and the samples are in mdat beside it, so reading the file to reach one
retained the whole clip: 64 MB for a single drop, and a batch of ten at once
through Promise.all. A 2 MB container now costs under 4 KB of reads, and a
batch is inspected one file at a time.

Treat a "From " line as a separator only in an mbox. An archive escapes the
one a body starts with; a standalone .eml has no separator at all, so an
ordinary sentence opening that way reopened the headers and a quoted
Content-Type below it became a second charset.

Offer .3gp in the compare audio dialog. A platform that maps the extension to
video/3gpp, or to nothing, greys out a voice recording the surface would take,
and the track inspection cannot run on a file that was never selectable. The
dialog hint and the routing accept are separate constants now: the audio
adapter is matched before the video one, so claiming the name for routing
would take every 3GP video as audio.

* Decide a vCard's encoding from its own parameters, before UTF-8

A card declaring CHARSET=windows-1252 whose bytes happen to be valid UTF-8
decoded as UTF-8, delivering characters it never named. A property parameter
is written by the exporter, like an XML prolog and a gettext header, so it
decides first now. Only when the card names exactly one: several stays the
ambiguous case and keeps its existing path. A mail Content-Type remains the
one fallback, because clients mislabel 8-bit mail constantly.

Clear MIME boundaries at an mbox separator. A boundary belongs to the message
that named it, and carrying one forward let a later body line repeating it
reopen the headers there.

Read a gettext header past the 64 KiB prefix. A catalog with more comments
than that above its header entry was refused for carrying exactly the bytes
the header describes. The prefix still settles the common case; only a miss
reads the rest, which the attachment cap already bounds.

Give the video reference picker the same accept and classification as its own
drop path. This PR widened the drop list to wma, amr, caf and the rest, but
the button still asked for audio/* and the check still demanded a MIME, so a
browser reporting "" hid those files and then refused them.

* Read every vCard property under its own charset, and bound a decode block

CHARSET is a property parameter, so a 2.1 card may put windows-1252 on FN and
windows-1251 on NOTE. Refusing that as an ambiguous container was wrong: the
card says plainly what each value holds. Names and parameters are ASCII by the
grammar, so only the value after the delimiter takes the property's charset,
and a folded line continues the one above. The reading is all-or-nothing: a
property whose bytes break its own declaration, or that names a charset the
platform lacks, falls back to the refusal rather than emitting a guess. A MIME
container still needs a parser this is not, so mail is unchanged.

Size a libsndfile block by channels as well as frames. blocks() allocates
frames * channels and yields a copy, so a frame budget chosen for mono let a
255-channel container reach 49 MB twice over from an upload capped at 25. The
samples kept are mono, since each block is downmixed as it arrives, so this
bounds the transient only. Nothing common moves: the divisor first bites past
about 20 channels at 48 kHz.

* Let each declaration speak for what it actually covers

A vCard CHARSET covers its own property whatever the count, so one declaration
does not settle the file. An export holding a 2.1 card beside a 3.0 one, which
cannot declare anything, read the whole bundle in the 2.1 card's charset and
turned the other into mojibake. Every card with a declaration takes the
per-property read now, and falls back to the old whole-file one when it cannot
account for a value.

Unfold a header block before pulling its boundary out. A wrapped
"multipart/mixed;\r\n boundary=..." was never matched, so no part header was
scanned and the charset those parts declare went unread.

Drop a boundary at its closing delimiter. "--inner--" ends that multipart for
good, and keeping the token let a later sibling repeating the line reopen the
headers.

Compare declarations by encoding rather than spelling. windows-1252, CP1252
and latin1 are three names for one decoder, so an archive using two of them
was refused as multi-charset when a single decoder reads all of it.

Read an XML declaration to its own ">". The grammar puts no bound on the
whitespace between the parts, so the 256-byte prefix could cut `encoding` off.
Five bytes still settle whether there is a declaration at all.

Read a 3GP's tracks in the reference picker too. The audio dialog offers .3gp
now, the picker classifies before the kind check as chat and compare do, and a
file already stamped audio is no longer claimed by the video extension list.

* Match a charset parameter by its name, not by where it appears

An unanchored search took the first "charset=" anywhere in a Content-Type, so
`text/plain; name="charset=windows-1251.txt"; charset=windows-1252` read the
filename: an unsupported label that refused a valid message, or a supported
one that quietly picked the wrong decoder. The value's parameters are split
outside quotes now and only a parameter actually named charset counts.

Read a truncated vCard per property as well. The preview pane decodes a
prefix, and applying the sole declaration to all of it showed Café for text
the sent attachment renders as Café. Only a prefix's last line can end
mid-character, so that one line is read leniently and the rest stay strict.

Drop the size condition on 3GP track inspection. It sat at the composer's
video cap while the video reference surface accepts a larger file, so a
recording in between skipped inspection and was staged as a video reference on
its extension alone. A ceiling that has to track every surface's limit is one
that will fall behind another, and the box walk is already bounded by box
count and by the size of the track table rather than by the file.

* Hold a forwarded container to the duration limit its headers declare

wav and mp3 are passed to llama-server untouched, and that return sits ahead
of every bounded decoder, so neither the duration cap nor the sample ceiling
ever ran on them. A 16 kbps mp3 holds hours inside the 25 MB upload cap. Both
are now measured from their own headers: a RIFF byte rate against the PCM
actually carried, and a walk of the MPEG frame headers that stops as soon as
the running total passes the cap. A container whose headers cannot say is
still forwarded, so this refuses what it can prove and invents nothing.

Take boundaries only from a multipart Content-Type, parsed as parameters. A
quoted `filename="report; boundary=fake"` on any header at all registered a
delimiter, and a body line repeating it reopened the headers.

Look for a declaration in the whole file when previewing a prefix. A gettext
header below a megabyte of translator comments sat outside the preview slice,
so the preview reported an error for a file the attachment decodes.

Inspect a 3GP whatever MIME the browser gave it, and correct the type in both
directions. The type comes from the same ambiguous extension, so a platform
reporting audio/3gpp reports it for a clip too, and the audio adapter is
matched before the video one.

Give the reference drop zone the accept its own dialog uses. The zone filters
on the name before the classifier can see the file, so the narrower chat list
refused a recording the button takes.

* Answer an overlong upload the same way whether or not a swap is running

The pre-switch preflight caught every exception and reported "could not be
decoded" with a 400, so the same valid file read as a 413 with an actionable
limit when the model was already loaded and as a decode failure when a model
switch happened to be in flight. Both preflight paths now let the duration
error through, and one helper owns the message so the three sites cannot drift.

Resolve escapes when unquoting a header parameter. The splitter already
honoured them, so a value carrying an escaped quote stopped at that quote and
kept its backslashes: the boundary never matched its own delimiter line, and
the part headers below it went unread.

Take a pasted video up to the limit the native reader uses. Rust reads a clip
to 75,497,280 bytes while the frontend held every non-audio file to 20 MB with
a 25 MB total, so a larger clip was read and encoded natively and then thrown
away, taking the rest of the paste with it.

* Transcode audio without holding three copies of it, and honour every vCard charset declaration

A 17.5 MB six-minute FLAC, well inside the upload cap, drove 573 MB of
transient through the llama audio path. The resampler built two float64
grids the length of the recording, the WAV encoder allocated the whole
array again for each of flatten, the nan scrub, abs, normalise and scale,
and the block reader held every block and then joined them into a second
full array. Same bytes out, 188 MB in.

A vCard that declared a charset with no decoder here was refused when it
declared nothing else and accepted, escapes left literal, when another
property declared a second one: the fallback read the card as UTF-8 and
its other bytes happened to be ASCII. A declaration the per-property read
cannot honour is now reported.

* Read an XML declaration and a gettext header for what they are

A processing instruction opens with the same five bytes as a declaration:
`<?xml-stylesheet ... encoding="windows-1252"?>` on a UTF-8 document was
taken for the prolog and the file came back as mojibake, with nothing
raised. XML's grammar puts whitespace after the target, which is exactly
what separates the two, so that is now required.

PO concatenates adjacent quoted pieces, so a header split as
`charset=windows-` then `1252\n` read as the label `windows-` and the
catalog was refused for declaring a charset it does not. The entry's pieces
are joined and unescaped before the charset is taken from them. The 64 KiB
prefix reached the same truncation on its own, so an entry that runs to the
cut is now re-read from the whole file rather than answered from half a
value.

* Keep decoded audio in order, and hold every forwarded container to the cap

Four things the bounded audio path got wrong.

The soundfile reader preallocates a buffer from the header's frame count and
re-tested the fit for every block. Once a block overflowed into the tail, a
shorter later block still fit the space left over and was written there,
landing ahead of the blocks that overflowed before it. The length stayed
right, so nothing downstream noticed, and what reached the model was the same
recording with a piece of it moved. Sweeping the block-length and declared-
length space, 144 combinations came back reordered. The buffer is now latched
closed by the first block it cannot hold.

_wav_seconds divided by nAvgBytesPerSec, which is redundant with the sample
rate and block alignment beside it and so is the one field that can be moved
alone. Inflating it by ten thousand made fifty minutes of PCM read as fractions
of a second, and a short file is forwarded to llama-server without any bounded
decoder seeing it. It is recomputed now, and the declaration is taken only
where it agrees.

_mp3_seconds returned the seconds it had counted whenever the frame walk
stopped, including when it stopped on bytes it could not read. A decoder
resynchronises past junk and plays the rest, so four stray bytes after the
tenth frame presented two hours as two and a half seconds. It now distinguishes
a complete walk from an abandoned one, and _prepare_audio_for_llama treats an
unestablished length as a reason to decode rather than a reason to forward.
That costs a transcode and puts the file back under both ceilings.

Last, _decode_audio_base64 used to call torchaudio.load outright, so an
environment carrying only torchaudio could decode audio. torchaudio 2.9 removed
info(), which is what routes such an install into the streaming chain, and that
chain needs libsndfile, PyAV or librosa. An install predating PyAV as a base
requirement would have lost audio input on upgrade; it falls back to load()
now, under the same backstop.

* Say why a text attachment was refused, and know one more tracker module

Three things in the intake path, found by running it in Chromium, Firefox and
WebKit rather than only under Node.

unsupportedCharsetError returned a plain Error. The composer toasts an
UndecodableTextError and rethrows anything else, so this one refusal, alone
among the seven in TextAttachmentAdapter.add, produced no message: the drop
path logged it to the console and the picker path turned it into an unhandled
rejection, and either way the attachment simply never appeared. The labels that
reach it are not exotic. The Encoding Standard maps ISO-2022-KR, HZ-GB-2312 and
the ISO-2022-CN family to "replacement", which TextDecoder is required to
refuse, so a Korean or Chinese card or message declaring its own charset
vanished silently on every engine. It carries the file name and the charset now,
and the message that was already written for it is finally shown.

TRACKER_MOD_MAGICS was missing !PM!, ProTracker's other four-channel marker,
which file(1) lists at offset 1080 beside M.K. The Soundtracker fallback does
not rescue one either: in a 31-sample layout byte 470 lands inside a sample
name rather than the order table, so a !PM! module was read as UTF-8 text,
which is the outcome these sniffers exist to prevent. The two tables are
hand-mirrored, so there is now a test that compares them.

The BMFF fixtures returned a bare Uint8Array, which is generic over
ArrayBufferLike and so includes SharedArrayBuffer. BlobPart accepts neither
that nor a view onto it, and every one of these ends up inside a File, so
tsc reported twelve errors and the frontend build gate was red.

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

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

* Measure a forwarded WAV only when it is PCM, and bound the last-resort decode

Two things the previous round got wrong.

_wav_seconds recomputed nAvgBytesPerSec as sample_rate * nBlockAlign. Those
identities hold only for WAVE_FORMAT_PCM: for every other tag both fields are
the codec's business, and an IMA ADPCM nBlockAlign is a whole compressed block
rather than one sample frame. A 505-frame block therefore overstated the byte
rate 505-fold, and a three-hour ADPCM recording well inside the 25 MB upload cap
read as twenty-one seconds, which is short enough to forward untouched. The
format tag now decides: PCM and IEEE float keep the arithmetic, extensible is
resolved through its SubFormat GUID, and everything else reports no duration and
goes to the bounded decoder.

The torchaudio-only fallback called load() with no bound. torchaudio 2.9's load
is an alias for load_with_torchcodec, whose body decodes the whole file with
get_all_samples() and only then slices to num_frames, so passing num_frames
would have bounded the return value and not the allocation. Since it is exactly
2.9 dropping info() that routes an install into this fallback, that read was
unbounded, and 25 MB of Opus holds hours of PCM. It asks torchcodec for the
sample rate, channel count and duration first, refuses past the ceilings, and
reads a bounded range; with no bounded reader available it refuses rather than
reading.

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

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

* Keep a preview as lenient as its own adapter, and stop holding PyAV output twice

Two findings from the round before last that were never answered.

readBoundedText used to call Blob.text(). It now decodes through the strict text
path, and that path belongs to the files the text adapter owns, where refusing
beats sending mojibake to a model. A .html file is the HTML adapter's, and it
sends a windows-1252 page happily, so routing its preview through the strict
decoder meant opening an attachment that had already been accepted threw
UndecodableTextError on a byte the adapter itself reads. The preview follows the
adapter now: text-adapter names stay strict, everything else reads as before.

The PyAV decoder held every resampled block in a list and then handed the list to
np.concatenate, which allocates the result while the list is still live. At the
48 kHz sample ceiling that is two 346 MB arrays for one 30-minute upload. It
fills the output as it copies, dropping each block on the way, so the cost is one
array and one block. The copy order is the decode order.

* Studio: stream PyAV output and validate MP3 trailers to EOF

The PyAV decoder collected every resampled block and joined them at the end.
Dropping each block after copying it does not bound anything: the blocks are
small enough that freeing them returns them to the allocator's free lists
rather than to the OS, so resident memory only grows. Measured on 30 minutes
of 48 kHz mono, peak was 672 MB with np.concatenate and 665 MB with the fill
loop, against a 330 MB waveform. Each block is now written into one output
buffer as it arrives, sized from the container duration and doubling when that
was absent or under-reported: 330 MB declared, 354 MB undeclared.

_mp3_seconds recognised a metadata trailer by its magic alone, so the ID3v1 tag
that 'cat one.mp3 two.mp3' leaves between the two streams read as the end of the
recording. Five seconds of frames, a TAG, then forty minutes of frames reported
4.99 seconds and was forwarded past the duration cap. Trailers now have to
account for their own length and reach EOF, and a walk that cannot returns None
so the file is decoded instead.

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

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

* Studio: make the audio attachment tests run on a Windows checkout

Two failures from a Windows staging run of this suite, neither of them about
audio. read_text() follows the locale encoding, which is cp1252 on a stock
Windows runner, and the module the parity test reads holds bytes cp1252 cannot
decode, so it raised UnicodeDecodeError instead of comparing anything. And five
tests imported torch directly for the fake tensors they hand to the fake
torchaudio, which fails rather than skips where torch is absent; they now use
importorskip, as the PyAV fixtures in the same file already do.

* Studio: hold PyAV allocations to the limit the decode enforces

Two limits bind a decode at once, the thirty-minute clock and a rate-independent
sample count, and the decode refuses at whichever is smaller. The buffer sizing
did not read the same bound. The initial allocation clamped only to the sample
count, so an 8 kHz file declaring three hours reserved 86.4M floats (330 MB) on
the way to being refused at 14.4M (55 MB), and the doubling that covers an
under-reported duration was not clamped at all: 48 kHz declaring twenty minutes
and holding twenty-one grew to 115.2M against an 86.4M limit, with the old
buffer still live for the copy.

_decoded_sample_ceiling is now the single source for all three, so the
allocation, the growth target and the refusal cannot drift apart. The growth
clamp cannot starve a write, since the sample count has already been checked
against that same ceiling.

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

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

* Studio: stream the soundfile decode into one bounded buffer too

The PyAV path was fixed to write each block into a single growing buffer, but
the soundfile path kept the branch that motivated it. When libsndfile reports
no usable frame count, or one past the ceiling, the declared length is dropped,
nothing is preallocated, and every block is held until a final concatenate
allocates a second copy of the recording. Measured with a source reporting zero
frames for a 30-minute 48 kHz decode: 592.6 MB peak against a 329.6 MB
waveform.

Now one append-only buffer that doubles when it runs short and is clamped to
_decoded_sample_ceiling: 352.0 MB for the same decode, with the returned array
byte-identical. An honest header is still only trusted once the decode has met
half of it, so it sizes the growth rather than buying an array up front, and
ordering is now correct by construction rather than by a latch.

Two tests asserted the old mechanism instead of the behaviour and were restated:
one required the final concatenate to happen, and one required no allocation at
all before the cap refuses, which a streaming buffer cannot promise. The
guarantee they were protecting, that nothing the header claims is allocated, is
now asserted directly against the ceiling.

---------

Co-authored-by: Unsloth <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
…ization (#9317)

* Join the Windows GPU adapter counters to torch devices on the adapter LUID

Windows ROCm has no amd-smi and hipMemGetInfo does not see other processes, so
used VRAM comes from the per-adapter "GPU Adapter Memory\Dedicated Usage"
counter. Nothing keyed that counter to a torch device, so it was attributed by
ranking usages against device capacities, and a value was emitted only when
capacity FORCED the pairing. One visible GPU forces nothing -- there is no
smaller card for its usage to exceed -- so the single-GPU host, the common AMD
Windows case, always read Unknown. The host aggregate needed the counters to
number the visible devices exactly, which the Basic Render Driver and an idle
iGPU break, so it was unknown too.

Windows names each counter instance after the adapter LUID, and DirectX keeps a
record per LUID under HKLM\SOFTWARE\Microsoft\DirectX carrying the same
Description string torch reports as props.name. Join on that instead: identity
needs no disambiguation, so a lone card resolves exactly, and a busy foreign
adapter beside an idle Radeon no longer blocks the read. Every case the join
cannot establish falls back to the capacity ranking unchanged.

* Decline the DirectX adapter map when a record will not read

Reading an adapter subkey could fail and leave the rest of the map
standing. A partial map is indistinguishable from a complete one at the
join, so a visible card whose own record was unreadable could be handed a
hidden same-named card's counter. Adapter records are GUID-named, which
tells them from ShaderCache without inferring it from a missing VendorId,
and any read failure past that point now empties the map, which falls
back to capacity ranking.

The join itself now tries two keys. DirectX takes the Description from
the driver INF and HIP fills props.name from the ASIC record, so one card
can reach the two sides spelled differently: the trademark marks and the
spacing around them are normalized away, and when the names still
disagree the gfx target both sides also carry settles it
(AdapterFamily=AMD_NAVI44:gfx1200 against gcnArchName=gfx1200). That is
what an iGPU beside a dGPU needs, where the archs differ but the
marketing names may not resolve. Name first, because it separates a 9070
from a 9070 XT where the shared arch cannot. The arch pass runs only when
every AMD record has a family, so a driver too old to write one cannot
let the records that have it answer for the adapter that does not.

Verified live on Windows 11 / RX 9060 XT: the walk skips ShaderCache and
the Basic Render Driver and resolves the card's own counter.

* Studio: ask HIP for the adapter LUID before inferring it from the DirectX record

Stacks on #8863. That PR reaches a device through what the two sides say
about it, the DirectX Description or the gfx target, which cannot separate
two cards of one model: both report one string and one arch, so both get the
aggregate and neither a figure of its own. HIP already knows the answer.
hipDeviceProp_tR0600 carries the same DXGI LUID the GPU Adapter Memory
counter instances are named after, so asking the runtime joins on the adapter
rather than on anything about it, and identical cards resolve.

Idea and the R0600 route from @pablo86gr in #8793, with its two review
findings addressed. Ordinals come from visible_ordinal, not from dev_meta
positions, which are compacted when a device fails to probe and would
otherwise hand ordinal 0's LUID to the card that survived at ordinal 1.
luidDeviceNodeMask is read and used: a linked-node adapter puts several
ordinals behind one LUID while the counters index its nodes as phys_N, and
nothing pairs the two, so those ordinals report unknown per device and the
mask is what says whether their counters are all of that adapter's nodes or
whether one belongs to a node HIP is not showing.

The offsets are hardcoded, so the name is read back from the head of the
struct and compared against the device's own; a layout that ever moved is
caught rather than trusted. The probe declines as a whole, like the DirectX
map, and falls back to it: off Windows, runtime not loaded in this process,
symbol absent, an ordinal that will not answer, an all-zero LUID.

Verified on Windows 11 / RX 9060 XT with the runtime loaded: HIP reports
luid 0x14ad4 node mask 0, the live counter instance is
luid_0x00000000_0x00014ad4_phys_0, and the HIP join and the DirectX join
independently agree on the same figure. The probe resolves it with
torch.cuda.is_initialized() still False, so a telemetry poll does not buy a
context to ask.

Split out of #8863 at review request.

* Bound the HIP-joined counter by the carve-out, not the displayed total

_adapter_counter_capacity arrived with #8863's merged form, after this
branch was cut, so the HIP join is the one caller still bounding with
total_bytes. On a unified APU that total is the whole driver pool, which
no counter reading can exceed, and the join runs ahead of the DirectX one
that would have declined.

* Studio: count only this adapter's engines in the Windows AMD GPU utilization

The GPU Engine instances are named after the adapter, exactly like the memory
ones -- pid_<pid>_luid_0x<high>_0x<low>_phys_<n>_eng_<n>_engtype_3D -- and the
3D utilization summed every one of them. That is the whole host's 3D load
reported as this card's: on a laptop the display iGPU's work, and on the
reporting host the Basic Render Driver's instances were being summed in.

Narrowed to the card's own LUID. Which LUID is safe to filter on is not
obvious: a linked-node adapter puts several ordinals behind one, and the node
mask alone cannot settle it, since one bit set reads the same whether the
ordinal owns the only node or one of two. What settles it is the node count
the VRAM join already checks, the number of counter instances that LUID has.
So the join hands the LUID back only for a device it established is the whole
of what that LUID names, and the engine query filters on that. Where it did
not establish that, the LUID is absent and the sum stays the host's, which is
what it has always been.

That also drops a second identity probe per poll: the utilization path was
asking HIP again for something the VRAM path had just resolved. The key is
internal, and neither endpoint spreads these dicts into its payload.

Stacks on the HIP probe, which is what supplies the LUID. Split out of #8863
at review request.

* Filter the engine samples here rather than in the counter path

The narrowing is right and the reading it corrects is real: simulated against
the shape off the reporting host, this card at 17% beside an iGPU and the Basic
Render Driver at 61% between them, the poll reported 78 before and 17 after.

Where it was done is the problem. Putting the LUID in the counter path hands the
selection to PDH, and no test in this repo can run PDH, so the three tests here
were asserting the shape of a string while a mock decided the number. Both of
these mutants left them green: dropping engtype_3D from the pattern, so Copy and
VideoDecode instances sum in, and unioning *engtype_3D* back in beside the LUID,
which is the whole-host sum this branch exists to stop reporting.

It also left the value unguarded. Utilization Percentage is a cooked counter over
an instance list that is created and destroyed as work starts, and the previous
form took whatever the pre-summed expression printed: a non-finite sample reached
the payload as inf, which json.dumps rejects and no browser will parse, and a
value above the PowerShell clamp passed straight through at 250.

So the path goes back to a bare wildcard and the rows are filtered here, which is
what _rocm_windows_perf_counter_vram_by_adapter -- the counter that resolves the
LUID being matched -- already does. The sum, the clamp and the sanity checks are
in Python now, where the tests reach them, and the three tests assert numbers.

Ten cases added, all of them things the old shape could not ask: a longer LUID
that starts the same, engtype_3d in lower case (hosts emit both spellings and the
old pattern relied on PDH folding it), compute engines only, an idle engine
reading 0 rather than unknown, NaN and infinite and negative and unparseable
samples, the clamp, an instance name with no LUID in it, no instances at all, a
high LUID half, and the internal luid key staying out of both payloads with a
negative control so a declined join cannot pass it. 53 in the file.

Also .get("luid") at the call site instead of ["luid"]: two suites already stub
_rocm_windows_per_device_vram with records that have no such key, and they reach
this line the moment one of them is used with get_gpu_utilization.

Simulated across [Windows, Linux, WSL, macOS] x [NVIDIA, AMD, CPU-only] with the
vendor SMI answering and unavailable, on 3.11 and 3.13: 42 of 58 host shapes
produce byte-identical payloads, and every one that moves is Windows ROCm with
the join having proved ownership.

* Trim the comments on the engine utilization filtering

* Take node identity, not node count, as whole-adapter ownership

Equal counts say how many nodes an ordinal owns, never which. One ordinal
holding node 0 of a linked adapter, whose own counter instance is missing while
the node it does not own still reports, gives one counter against one owned node
and passes:

    only the HIDDEN node emits -> ([5368709120.0], 5368709120.0, [86889])

The third element is the LUID being handed back as whole-adapter, so the engine
query then sums the other node's 3D work as this card's, on top of the hidden
node's bytes landing in used_gb.

luidDeviceNodeMask names the nodes rather than counting them (bit i is node i,
so a plain adapter reads 1 and not 0), so where the mask is present the observed
phys_N set has to be exactly those nodes. A zero mask names nothing and keeps
the count check alone, which is the pre-existing behaviour for adapters that are
not linked.

The check only ever withdraws an ownership claim, never grants one, so a host
where phys_N and the mask index differently loses the narrowing and falls back
to the unfiltered sum rather than attributing wrongly.

Reported by Codex. The used_gb half of the same shape belongs to the HIP join
underneath this branch and is left alone here.

* Keep the engine type in the counter path, match the adapter here

GPU Engine is instanced per process AND per engine, so a bare wildcard asks
PowerShell to format every engine type of every GPU-using process into text that
the loop here then discards down to 3D. On a busy host that is the bulk of the
sample set, inside a 5 second timeout on the monitor poll, and a timeout reads as
no utilization rather than as an error.

The engine type is not what this branch narrows. It was in the path before it and
belongs there: one segment, no interior wildcard, and it is the restriction that
keeps the set small. Only the adapter LUID moved into Python, which is the part
the tests need to reach.

The Python engtype check stays as well, since it costs nothing and covers the
engtype_3d spelling directly rather than relying on PDH folding the case.

Reported by Codex.

* Unpack the carve-out join test three-wide

_match_adapter_used_by_hip_luid returns the whole-adapter LUID as a third value,
so the carve-out bound test on this base cannot unpack it two-wide any more:

    ValueError: too many values to unpack (expected 2)

Only reachable once this branch sits on a base that has that test, which is why
it did not show up while the branch was behind.

* Tighten the comments on the engine LUID filter

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
* Fix diffusion offload host RAM retention

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

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

* Keep diffusion benchmark JSON standards compliant

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

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

* Harden the offload reclaimer and cover the video path

Follow-ups from reviewing this branch, verified against a real whole-model
offloaded run (Z-Image-Turbo bnb-4bit, low_vram forcing offload on one B200).

Do not make ctypes a hard import. diffusion_memory sits on the import path of
diffusion, video, llama_cpp, sd_cpp_backend and routes.inference, so on a
Python built without libffi (no _ctypes, a common source or pyenv build) this
branch turned "allocator pressure is unavailable" into "the whole inference
stack fails to import". Import it defensively and decline to resolve when it
is missing. It stays a module attribute so the existing reclaimer tests keep
patching diffusion_memory.ctypes.

Say something when the allocator cannot be trimmed. The call site discards the
return value and an unresolved reclaimer returned False silently, so a
permanent no-op on musl, an unsupported platform, or a ctypes-less build was
invisible while host RAM climbed. Log it once at info.

Reclaim on the video path too. video.py plans the same policies through the
same apply_memory_plan and can engage offload_policy "model", but never
reclaimed, so video generations kept the retention this branch fixes for
images. Video weights are larger, so the retention is worse there. Placed
after progress is cleared: the trim can block for a few hundred ms on a large
heap and the page should not still read active while it runs.

Tests: a Linux-guarded case that calls the real glibc malloc_trim and asserts
argtypes/restype by value, since every existing reclaimer test replaces ctypes
and none of them would notice the symbol or the ABI breaking; the ctypes-less
path; the log-once behaviour; the video call site across all five policies;
and the benchmark's /proc RSS fallback plus the new flag defaulting to off.

Measured against this branch's base, 1024x1024, 9 steps, fixed seed, 1 warmup
plus 8 measured generations: host RSS growth 3103.8 -> 33.7 MiB, steady-state
RSS 15.8 -> 8.6 GB, peak VRAM 0.0%, median latency +1.9%, PSNR infinite (bit
identical). A gc.collect() only arm stayed at 16.6 GB, so the native trim is
what does the work. Trim cost measured in place: 288 ms on the first
generation, then 34 to 59 ms steady.

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

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

* Correct the video reclaim comment about progress state

generate_progress() re-asserts active from _generate_job_active after
self._gen is cleared, so the claim that the page is idle across the trim was
only true for the synchronous path, not a background begin_generate job.
Comment only, no behaviour change.

* Tighten the comments added by this branch

Post-convergence comment pass: 30 comment lines down to 10 across the six
files with non-docstring comments. Kept the facts a reader would otherwise
have to rediscover: why ctypes is optional and must stay a module attribute,
why the trim runs after progress is cleared, and the glibc malloc_trim return
convention the ABI assertion relies on.

* Close the cancel window the video reclaim opened, and guard the baseline path

Two review catches, both reproduced with a failing test first.

The video epilogue ran the host-allocator trim after its last cancel.is_set()
check but before the finally that deregisters the event. The trim blocks for a
few hundred ms, so a Stop landing in that window was answered true by
cancel_generate() while this clip was still returned and persisted by
_run_generate_body. Deregister under the same lock cancel_generate takes and
re-check inside it, matching the image backend's epilogue. Before the fix the
new test fails with "cancel_generate answered true for a clip that was still
persisted".

--write-baseline accepts any path, so a baseline can legitimately sit on
compare.json or compare.png inside the directory a later --compare writes to;
the report then overwrote the reference metrics. Refuse the collision up front,
before the generation is paid for rather than after. Before the fix the new
test sees _compare return 0 with the baseline clobbered.

* Apply the repo kwarg-spacing formatter to the new tests

The two tests added in b806418 were not clean under the pinned
ruff-format-with-kwargs hook, so pre-commit.ci kept trying to fix them and its
autofix push kept losing a race with mine. Run the hook's own output instead.

* Tighten the comments added by the last two fixes

Final post-convergence pass over the comments this branch added after the
previous one: 10 lines down to 6. Dropped the assertion restatement whose
message already says the same thing, and collapsed the two rationale blocks
while keeping why the deregistration has to precede the trim and why the
baseline path collision is refused up front.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
* Add a CPU option for loading audio models

Audio loads take an accelerator whenever one exists, with no way to say
otherwise. That is a problem when the GPU is the scarce resource: a card
already holding a chat model, a training run wanting every spare byte, or a
checkpoint that will not fit at all. Whisper and the smaller TTS models run
fine on CPU, so this makes the placement the user's call.

Adds an auto/cpu/gpu preference, defaulting to auto (today's behaviour):

- Settings > Voice > "Load into" for dictation, sent with the explicit load
  and with the implicit one dictation triggers on first use.
- Audio page > "Load model into" for TTS. Changing it ejects the resident
  model so the choice takes effect instead of sitting unapplied.
- UNSLOTH_AUDIO_DEVICE for headless and CLI use.
- API: device on SttLoadRequest, TranscribeRequest and
  /audio/transcribe/raw; audio_device on LoadRequest and
  ValidateModelRequest.

All three audio stacks honour it through the CPU path each already had for
training: Transformers Whisper picks cpu/float32, whisper.cpp gets --no-gpu,
llama.cpp gets -ngl 0, and native audio picks its device in the constructor.
GGUF TTS translates the same choice into gpu_layers 0, since audio_device
does nothing there.

Notable decisions:

- device=None means no opinion, not auto. A caller that never sends one (the
  OpenAI-compatible route) must not drag a model off the device another
  surface asked for, or the two thrash a reload apiece.
- One gate, keyed on the audio type, keeps a CPU-placed load out of the
  training coexistence check, the GPU arbiter, the memory preflight and the
  already-loaded shortcut. Keyed on the type so a chat model cannot send
  audio_device and walk past those guards.
- MiniMax Music 3 on CPU is refused in preflight, not in the worker, since
  past preflight the switch has already evicted the resident model.
- No training-teardown exemption for CPU native audio: that worker runs
  detect_hardware() before it places anything, so it holds a CUDA context
  whatever the weights are on. The STT sidecars do get one, because their
  worker never touches CUDA.

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

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

* Stop a CPU audio load taking, needing and holding the GPU it asked to avoid

Three placement bugs, all reachable in the case the option exists for: a card
that is already full.

A forced-CPU load still ran GPU selection. Automatic selection returns every
card needed to hold the checkpoint and the worker forwards that list to
NativeAudioBackend.load_model, which rejects more than one as unsupported
sharding. The same estimate also becomes expected_free_gb, so the settle wait
raises "GPU memory from the previous inference worker was not released" when an
Images or Video pipeline holds the card, aborting the load after the previous
worker has already been shut down. A load that takes no card now selects none,
which closes both paths at once.

The stale CHAT claim was dropped only after the load returned. A download and
load can run for minutes, and across that window an Images or Video acquire_for
still finds CHAT owning the GPU, runs the chat evictor, sees this model in
loading_models and cancels it. acquire_for evicts only when the arbiter has an
owner, so releasing before the load lets the two coexist. The post-load release
stays, since it covers a claim re-taken while the load ran.

A GPU-resident mtmd server could report holding no VRAM. _load_locked records
the user's standing CPU wish in _forced_cpu even on the branch that deliberately
does not restart a server with a request in flight, and the training probe ORed
that wish with _gpu_disabled, which is the fact. Training then skipped the
teardown and started beside a server still at -ngl 99. The probe now prefers the
fact wherever a sidecar keeps one. whisper.cpp is unaffected: it writes
_forced_cpu only next to a spawned --no-gpu and clears it on release, so there
the flag is the fact.

Also, the audio suites no longer depend on UNSLOTH_AUDIO_DEVICE being unset.
Seven tests asserted placement against no opinion, so a host configured with the
server-wide default this PR adds failed them on correct behaviour.

Four regression tests, each confirmed to fail without its fix. Backend 38981
passing, every remaining failure already present on main and none introduced.

* Add the missing AGPL-3.0 header to audio_device.py

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

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

* Read source under test as UTF-8 so the guard tests run on Windows

read_text() defaults to the locale encoding. On windows-latest that is cp1252,
and routes/inference.py is UTF-8, so four tests died with a UnicodeDecodeError
on byte 0x81 while passing on every other runner. Found by the cross-platform
staging run, not reproducible on Linux without forcing the locale.

* Say where UNSLOTH_AUDIO_DEVICE reaches, since it does not reach GGUF

It was documented as a server-wide default, but the llama.cpp path never
consults it: placement there comes from gpu_memory_mode and gpu_layers, read at
request time, and nothing knows a GGUF is audio until llama-server reports its
audio_type after the load. There is no point early enough to translate the
default into zero offload, so an operator who set it to keep VRAM free still got
automatic GPU offload for a GGUF TTS, with nothing saying so.

The Audio page translates it from the catalog it already has. A headless caller
has to send the placement fields itself, and both docstrings now say that.

* Keep a CPU-mode GGUF audio codec off the GPU, and keep MiniMax loaded

Two placement bugs the audio device preference did not reach.

The GGUF audio codec picked its own device. A CPU-mode load sets zero
offload for the language model, so nothing else in that load touches the
GPU, but init_audio_codec still read torch.cuda.is_available() on its own
and put the codec on the card. The load then held VRAM after being
classified as holding none. It now follows the placement the server
already decided for that load.

Selecting CPU RAM also ejected a resident MiniMax Music 3, which cannot
run on CPU at all. The user lost the loaded model and got nothing back.
Selecting CPU now says why it is not available and leaves the model
where it is.

* Decode audio where the codec is, and stop a CPU load taking things it does not need

Three placements a CPU RAM audio load still got wrong.

The GGUF codec now loads on CPU, but decoding still asked for CUDA
whenever a card existed. The decoders build their input tensors on the
device they are handed, so SNAC and DAC failed on a device mismatch and
BiCodec moved the codec onto the card, taking the VRAM the mode exists to
avoid. The codec manager records where each codec actually went and
decoding follows it. That also covers the reuse case, where a codec
already resident from an earlier load never moves to the device a later
request asked for.

Releasing the CHAT claim before the load left a still-resident GPU model
unowned, and acquire_for evicts nobody when the arbiter has no owner, so
an Images or Video load could allocate straight over it. The release is
now handed to load_model, which runs it once the previous worker has
exited and its memory is back: after the danger, still ahead of the
download that made holding the claim untenable. A worker that will not
exit keeps the claim, which is then telling the truth.

The export teardown ran unconditionally to free VRAM for the incoming
model. A CPU load masks the accelerators and wants none of it, so this
was killing a running export for nothing.

* Decide whisper.cpp placement under the loading flag, and keep the catalog's GGUF answer

Two ways a CPU RAM choice still ended up on the GPU.

whisper.cpp chose between GPU and --no-gpu before publishing _loading.
The training hook reads is_loading() without that method's lock, so a
switch from a CPU-resident model to Auto landing in that window was
invisible to a training run starting concurrently: training saw no load
in flight, read the outgoing model's CPU placement, preserved it as
holding no VRAM, and the command already built then started a GPU-backed
server beside the run. The decision now happens after the flag is
published, where the hook cancels the startup and waits for it to settle.

The Audio picker identifies some GGUF repos only from the catalog, when
no exact variant exists and neither the repo id nor the load id spells
gguf. That answer was recomputed from the ids alone at load time and lost,
so a CPU RAM load of one omitted gpu_layers: 0 and speculative_type off,
and the backend, which ignores audio_device for GGUF, put it on the card.
The catalog's answer now travels with the load through both queue points
and both staged replays.

* Match the repo's kwarg formatter on the CHAT release binding

* Raise the startup transfer budget for the audio placement control

Measured both sides on the same build. This branch's merge base comes in at
1,560.9 KB transfer, 1.6 KB under the old 1,562.5 KB ceiling; the branch comes
in at 1,562.6 KB. The control costs about 1.7 KB of startup transfer and the
headroom left was 1.6 KB, so it went over by a tenth of a kilobyte.

What actually reaches the first screen is small and none of it is deferrable:
the new control's en strings, its persisted voice-settings preference, and the
pill-tabs variant. The Audio page and the Voice settings tab are both already
split out of the entry, so the page itself costs nothing until it is opened.

Raw is untouched, with 126.7 KB still to spare.

* Tighten the comments this branch added

Two sweeps over the 269 comment lines the branch introduced, down to 132.
Section banners and restatements deleted outright; multi-line rationales
collapsed to the fact that keeps someone from reintroducing the bug.

What survives names a specific mistake: the ordering the whisper.cpp
loading flag depends on, why the CHAT claim is dropped mid-load rather
than at either end, why the export teardown is gated, and why decoding
follows the codec's recorded placement.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
* Security audit: sync the zoo compiler.py digest pin with the approved baseline

#10187 re-approved unsloth-zoo 2026.8.17 and moved the compiler.py obfuscation
finding's pinned digest in scan_packages_baseline.json, but the same digest is
written a second time in the test that guards the pin, and that copy was left
on the old value. The pin and its guard have disagreed since, so
test_context_dependent_unsloth_zoo_findings_are_digest_pinned fails on main and
on every open PR, taking Repo tests (CPU) and workflow-trigger lint with it.

This is the follow-up write only. The review the pin exists to force already
happened in #10187; nothing here re-approves anything.

* Stop the zoo digest pin living in two places

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

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

* Require a pin on every new zoo variant, not just one per pair

---------

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

* Security audit: re-approve the four torch findings that 2.14.0 opened

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

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

* Pin the three new torch exec/anti-analysis entries to the reviewed 2.14.0 files

---------

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

* Pin the multi-turn determinism probe to a backend that can be deterministic

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

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

---------

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

* Stop the stall-window comparison being decided by one noisy sample

* Take the majority of the rounds, not the best of them
* Studio: report a truncated /v1/responses turn as incomplete

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

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

* Fix incomplete Responses output states

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

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

* Handle filtered Responses as incomplete

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Etherl <[email protected]>
* Studio: stop the update banners floating off the corner

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

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

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Etherl <[email protected]>
danielhanchen and others added 15 commits September 8, 2026 05:14
…them

The refusal added here answered input_file and file_id images, but only on a user
turn and only for those two shapes. Four ways of losing an attachment in silence
were left:

- system, developer and assistant turns each return via `continue` before the
  parts loop, so an attachment on those turns was still dropped;
- an input_image with neither image_url nor file_id was dropped;
- an input_image whose detail falls outside the documented set fails its typed
  variant, degrades to the catch-all, and took a servable url down with it;
- an unmodelled part was dropped, which is what /chat/completions stopped doing
  in #10255.

_responses_tool_output_content had already written the first three rules for the
same shapes arriving as a tool result, so this reuses its wording rather than
inventing a second vocabulary for one question. The attachment refusal is hoisted
above the role branches; the generic "parts of type 'X' are not supported" stays
on the user branch so an assistant replay turn keeps its lenient text flatten and
a client round-tripping prior output is not made to fail.

An image carrying image_url and file_id together still resolves from the url on
both paths: file_id means "instead of a url", not "in addition to one".
A valid input_image on a system, developer or assistant turn passed every shape
check and was then dropped anyway: those branches flatten content through
_responses_message_text, which keeps text parts and nothing else. The turn
answered 200 about an image the model never saw, which is the same data loss the
rest of this change removes, just one step further along.

Refused rather than forwarded. Chat Completions wants a plain string on system
and assistant, and the strict templates this normaliser exists to satisfy reject
a multimodal array there, so there is nowhere to forward it to. The message names
the role and points at the user turn, which is where an image can be served.

User turns are untouched: an image with a url still resolves exactly as before.
input_audio on a system, developer or assistant turn was still dropped in
silence: the generic refusal runs on the user branch, and the attachment refusal
knew only input_file and input_image. The same turn already returned 400 on a
user role, so one endpoint answered two ways about identical data loss.

Fixed by inverting the test rather than naming more attachment types. These roles
are flattened by _responses_message_text, which keeps text and discards the rest,
so the question is which parts a flatten may drop without losing something the
caller sent. That is input_text and output_text, which survive as text, plus
refusal and summary_text, which are the model's own output metadata that clients
round-trip and the prompt does not need. Everything else is refused.

An allowlist, not an input_ prefix test: OpenAI's part enumeration is input_text,
input_image, output_text, refusal, input_file, computer_screenshot and
summary_text, so a prefix test would have let computer_screenshot through. It
also means a part type nobody has seen yet is refused on these roles instead of
vanishing, which is the point of the change.

Assistant replay is unaffected: a turn carrying refusal or summary_text still
flattens to its text exactly as before.
{"type":"input_text"} fails ResponsesInputTextPart and becomes a
ResponsesUnknownContentPart wearing a known type name. The flattenable allowlist
matches on the name, so it waved the part through on system, developer and
assistant turns, and _responses_message_text then dropped it: a text-only system
turn disappeared and the request still succeeded.

On a user turn it was refused, but as "parts of type 'input_text' are not
supported", which is untrue and sends the caller looking for the wrong problem.

Both come from the same gap, so both are closed by exempting only real
ResponsesInputTextPart / ResponsesOutputTextPart instances and telling a
malformed one what it is missing, in the words _responses_tool_output_content
already uses for the same shape in a tool result.
The flattenable allowlist matched refusal and summary_text on every role that
flattens. They are the model's own output metadata, so dropping them is free on
an assistant replay turn and only there: on system or developer they are content
the caller wrote, and they went the way of every other part the flatten does not
keep. Alongside text the turn still answered; alone it disappeared.

The same part was already refused on a user turn, so this was one endpoint giving
two answers about the same loss, which is what the rest of this change removes.

Split the allowlist by role rather than by type alone. Assistant replay is
unchanged, and asserted: a turn carrying refusal or summary_text still flattens
to its text.
The docstring said unmodelled parts are skipped during normalisation, which
stopped being true when they started being refused by name. Its real job is the
422: lenient validation so an unrelated turn is never answered with a schema
dump, exactly as UnknownContentPart works on the Chat Completions side.
…10447)

* Studio: recover saved context when switching back to a snapshot path

* Studio: drop the Python pin of the switch-back lookup

* Studio: keep the switch-back lookup stable under biome

The new call sits at 89 columns, past biome's default 80, so running the
repo's own `npm run biome:fix` rewraps it across four lines. Both new tests
assert on the source text of `rememberedConfigFor` and match the single-line
form, so the formatter breaks them.

Wrap the call here and match either form in the tests, the way
llama-extra-args-panel-hydration.test.ts already does. With this the tests
pass whether or not the file has been formatted, and still fail against the
old `resolveInitialConfig` call.

---------

Co-authored-by: danielhanchen <[email protected]>
* Studio: install the MLX stack on fresh macOS installs

install.sh sets SKIP_STUDIO_BASE=1 so the core packages are not reinstalled,
but that flag also gated the by-name MLX install. On the fresh path mlx-lm
then only arrived transitively, nothing held tokenizers inside its
<=0.23.0 window, and Train and Export came up disabled until
`unsloth studio update` was run.

* Keep GGUF-only installs free of the MLX stack

The ungated MLX step also ran under --no-torch on Apple Silicon, where
install.sh sets both SKIP_STUDIO_BASE and UNSLOTH_NO_TORCH. These are direct
package args so NO_TORCH_SKIP_PACKAGES cannot filter them. Gate on NO_TORCH,
matching the MLX health probe below.

* Keep fresh MLX installs on supported versions

* Expand MLX installer compatibility and failure coverage

* Skip the MLX step where the pinned wheels do not exist

The pins are not installable everywhere Apple Silicon is, and pip_install
exits on failure, so on those hosts this step ends the whole install.

  mlx 0.32.1 / mlx-metal 0.32.1  macosx_14_0_arm64 wheels only, no sdist
  the whole pinned set            cp310 and up, no cp39 wheel

Read off the index rather than reasoned about:

  uv pip install --python-platform aarch64-apple-darwin mlx==0.32.1
    -> no wheels with a matching platform tag (e.g. macosx_13_0_arm64)
  the same resolve at --python-version 3.9
    -> no wheels with a matching Python implementation tag (e.g. cp39)

Before this branch, macOS 13 arm64 reached neither failure: the fresh path
skipped the step, and the update path was unpinned and resolved mlx 0.29.3.
Running it on fresh installs and pinning it turns both into an abort with no
manifest written, i.e. a venv the CLI then reports as half-built.

Nothing is lost by stepping aside, because those hosts cannot have a usable
stack in the first place. mlx_repair's own floors (mlx>=0.22, mlx-lm>=0.31.2,
mlx-vlm>=0.4.4) are unsatisfiable there:

  uv pip install --python-platform aarch64-apple-darwin 'mlx-lm>=0.31.2'
    -> mlx>=0.30.4 has no wheels with a matching platform tag

The unpinned resolve the update path used was worse than nothing: mlx-lm
0.29.1 and mlx-vlm 0.3.9 are both under those floors, so Studio rejected the
stack anyway, and it dragged transformers to 5.16.1, the version
overrides-darwin-arm64.txt documents as stranding tokenizers and breaking
every `import transformers` on macOS arm64.

Both branches spend a progress slot, so the denominator does not depend on
the host, and the gate the budget is computed from is unchanged.

test_no_torch_skips_mlx_stack.py reads the guard out of the AST and the step
now sits one branch deeper, so it walks the enclosing chain and asserts on the
outermost test, which is still the platform gate it exists to protect.

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

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

* Tighten the comments on the MLX install step

Comment lines only, AST-verified: 66 removed for 30 added across the three files.
Every load-bearing fact stays, including the wheel provenance the two floor
constants are read from.

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…zoo vendors the GDN kernels (#10487)

* Studio: stop installing flash-linear-attention and tilelang, unsloth_zoo vendors the GDN kernels

unsloth_zoo now ships the gated-delta FLA kernels in unsloth_zoo/_vendored/fla and
injects them as a real top-level fla during `import unsloth`, where it also rebinds
transformers' is_flash_linear_attention_available probe and sets FLA_TILELANG=0.
That makes the worker's pip installs inert: the vendored tree shadows any pip
flash-linear-attention at 0.5.1 or older, so the wheels Studio pulled were paid for
and never imported, and the TileLang backend was switched off before FLA could
dispatch to it. This removes those install paths, their skip env vars, the
tvm-ffi repair, the transformers model-type discovery that gated them, and the
FLA hook on the availability gate; causal-conv1d, mamba-ssm and the long-context
flash-attn install keep their existing gating and wheel-first logic unchanged. The
worker now logs FLA availability from the vendored import once the trainer has
imported unsloth, rather than from pip metadata.

Verified on this box that after `import unsloth` fla resolves to
unsloth_zoo/_vendored/fla, FLA_TILELANG is 0 and is_flash_linear_attention_available()
is True even with pip flash-linear-attention 0.5.0 and tilelang 0.1.8 installed. Ran
the rewritten studio/backend/tests/test_training_worker_flash_attn.py (45 passed), every
studio backend test that imports worker.py (3679 passed, 1 skipped), tests/kaggle
(1032 passed), ruff check over the repo and the canonical scripts/run_ruff_format.py
over each edited file.

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

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

* Trim two comments to one line

* Studio: keep the ROCm FLA_TILELANG guard and tighten the no-install tests

Dropping the installers also dropped the HIP guard, so a user who already has a pip
flash-linear-attention plus tilelang would let FLA's dispatcher pick the TileLang backend on
ROCm, where tilelang has no HIP GEMM. _install_fast_path_hooks sets FLA_TILELANG=0 again when
torch.version.hip is truthy, via setdefault so an explicit user value still wins, and it imports
torch lazily so nothing new is pulled in before transformers. The no-install tests were weaker
than they looked: the shutil.which double returned None for everything, so the uv branch of every
installer was never built, and the source check only rejected the exact pinned spec
"flash-linear-attention==". They are now parametrized over uv present and absent, and the source
check parses worker.py with ast and rejects any string constant starting with one of the four
package names, allowlisting the two prose log lines by exact text. Also adds direct coverage for
_flash_linear_attention_importable in both directions and corrects three comments that named the
deleted _torch_has_hip helper or claimed fla is not importable before from_pretrained, which the
vendored injection at import unsloth makes false.

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

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

* Studio: detect rocm-tagged torch builds and a broken apache-tvm-ffi in the FLA_TILELANG guard

Move the FLA_TILELANG guard out of _install_fast_path_hooks into a small
_guard_fla_tilelang helper and give it back the second HIP signal the removed
_torch_has_hip helper had, since AMD SDK and Radeon ROCm wheels can leave
torch.version.hip unset while still tagging torch.__version__ with rocm.
It also restores the offline half of the old tvm-ffi protection: when a
leftover pip tilelang is importable and apache-tvm-ffi is 0.1.10 or 0.1.11,
which fault with "CUDA: misaligned address" on sm_100, set FLA_TILELANG=0
instead of installing or downgrading anything. Both checks use setdefault, so
an explicit user FLA_TILELANG still wins, and the source guard test gains the
two bare package names its probes pass while still failing on any pip spec.

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

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

* Studio: run the FLA_TILELANG guard before the fast-path hook opt-out

UNSLOTH_STUDIO_SKIP_FAST_PATH_HOOKS=1 returned before the ROCm and
broken tvm-ffi guard ran, so a retained pip fla could still dispatch to
TileLang on that path. The guard now runs first; the opt-out only skips
the hooks.

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

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

* Trim the guard docstring to one line

* Studio: restore FLA_TILELANG after each test, context aware no-install check, accurate guard log

A test that calls monkeypatch.delenv on an already absent FLA_TILELANG records no undo, so the
guard's os.environ.setdefault created the variable and leaked it into later tests and xdist
workers; a module level autouse fixture now snapshots and restores FLA_TILELANG and
UNSLOTH_STUDIO_SKIP_FAST_PATH_HOOKS exactly, present or absent. The torch stub used by the guard
tests now pins torch.__version__ as well as torch.version.hip, so the CUDA case is not turned into
a ROCm case by the host's own rocm tagged wheel. The source allowlist stopped forbidding a bare
"tilelang" once those names were added to it wholesale, so the check is now context aware: a
constant naming the vendored stack passes only as one of the two prose log lines or as the sole
argument of importlib.util.find_spec / importlib.metadata.version, and any occurrence in a list or
tuple literal, or in an append / extend / concatenation argument, fails. Finally the guard only
logs the disabling line when it actually set the value, says so plainly when an environment
override is kept, and reports a skipped detection at debug level instead of swallowing it.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…onical docs link (#10492)

* Docker Hub README: xformers is amd64 only, GB10 runs through PTX, canonical docs link

The Hub page claimed xformers in every image; the arm64 images carry
none because there is no cu128 aarch64 wheel. It also listed GB10 among
the compiled targets while TORCH_CUDA_ARCH_LIST stops at 12.0+PTX, so
sm_121 runs through PTX JIT. The docs link now points at the canonical
Docker page. Reported in #10491.

* Docker Hub README: GB10 runs sm_120 SASS through forward compatibility, only JIT paths need CUDA 13
…U prebuilt (#10495)

* Docker Studio: keep the base image's CUDA llama.cpp instead of the CPU prebuilt

docker/Dockerfile.studio symlinks Studio's llama.cpp dir at the base image's baked CUDA bundle and then runs install.sh --local, but no GPU is visible during an image build, so studio/setup.sh hands install_llama_prebuilt.py a host with has_usable_nvidia=False and _linux_published_attempts() resolves the CPU bundle for the arch and installs it over the CUDA one. setup.sh now honours UNSLOTH_LLAMA_KEEP_PREBUILT=1 through a new _keep_installed_gpu_prebuilt(), which keeps an installed bundle whose UNSLOTH_PREBUILT_INFO.json records a GPU backend from the requested fork at the requested tag, and Dockerfile.studio sets that knob and then fails the build if /opt/unsloth/llama.cpp/libggml-cuda.so is gone after install.sh, mirroring the base Dockerfile's own unresolved-library guard. The knob is opt-in and every other path is untouched: an explicit UNSLOTH_LLAMA_CPP_BACKEND, UNSLOTH_LLAMA_PR, UNSLOTH_LLAMA_FORCE_COMPILE and --with-llama-cpp-dir are all decided before it, a stale tag, a different fork, a CPU or force_cpu marker and a tree with no llama-server are all still replaced, and the arm64 CPU last resort is additionally gated so it cannot undo a kept bundle.

Contrary to the report this is not arm64 only. Streaming the Studio install layer of the published unsloth/unsloth:latest straight from the registry shows the same whiteouts on both arches: opt/unsloth/llama.cpp/.wh.libggml-cuda.so and opt/unsloth/llama.cpp/build/bin/.wh.libggml-cuda.so appear in the arm64 child sha256:967df570 and in the amd64 child sha256:177bba4f alike, and the resolver run against the live b10840-mix-d5c17a0 manifest with no GPU picks app-...-linux-arm64-cpu.tar.gz on aarch64 and app-...-linux-x64-cpu.tar.gz on x86_64. The fix is therefore arch independent.

Verification without a GPU: the new tests/studio/install/test_docker_studio_keep_cuda_prebuilt.py adds 22 tests, two of which pin the CPU resolution on both arches through the real selector, seventeen drive setup.sh's keep decision out of the live script under a stubbed aarch64 PATH with a failing nvidia-smi against real base-image and installer-written markers, and three pin the wiring. tests/studio/install passes 3968 tests with 6 skips, tests/python/test_docker_llama_prebuilt_probe.py passes 5, all 32 tests/sh scripts that read setup.sh exit 0, bash -n studio/setup.sh is clean and docker buildx build --check on docker/Dockerfile.studio reports no warnings. docker/unsloth_llama_update.sh and docker/fetch_llama_prebuilt.py already agree on amd64 to linux-x64-cuda12-portable and arm64 to linux-arm64-cuda13-portable and needed no change; a full arm64 Studio image build is left to CI.

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

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

* Docker Studio: a full mix release pin must match the kept bundle exactly

_keep_installed_gpu_prebuilt() normalized both sides of the tag comparison to
their base build, so UNSLOTH_LLAMA_TAG=b10840-mix-new against a marker recording
b10840-mix-old collapsed to b10840 on both sides and the stale bundle was kept.
A requested tag that is not a bare bNNNN is now required to match one of the
marker's recorded release_tag / tag / upstream_tag exactly, while a bare base
build pin keeps the existing normalized comparison and latest still accepts;
UNSLOTH_LLAMA_RELEASE_TAG is passed in as a fourth argument and must equal the
marker's release_tag exactly, independently of the tag check.
Dockerfile.studio is unaffected: it passes UNSLOTH_LLAMA_TAG=latest by default
and sets no release tag. tests/studio/install/test_docker_studio_keep_cuda_prebuilt.py
covers exact mix match, a different mix from the same base build, a bare base
pin, and a matching and mismatching UNSLOTH_LLAMA_RELEASE_TAG.

---------

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

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 8, 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-08T13:44:20.486187Z 4beb7ae PR opened
ℹ️ About Codex in GitHub

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

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

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

pyproject.toml was the only conflict. Resolved keeping this branch's rule -- no
PEP 508 direct reference anywhere in the metadata, because PyPI rejects those in
Requires-Dist and this is the branch that gets uploaded -- while taking every
extra main added.

  * cu126/cu128/cu130 onlytorch2110, and cu126/cu130 onlytorch2120 and
    onlytorch2121, plus their -torch and -ampere-torch wrappers. The torch trio
    keeps main's +cuNNN pins verbatim; the xFormers rows become `xformers==0.0.35`
    with the two platform markers merged into the one this branch uses, since the
    wheel URL cannot be published.
  * torch==2.10.0 added to the three onlytorch2100 leaves, matching main.
  * audio-torch211, and main's tightened python_version ceilings on the older
    audio-torch rows.
  * base torch ceiling raised to <2.13.0. The 2.12 leaves pin torch==2.12.x, which
    a <2.12.0 base made unresolvable against its own base dependencies.

The 30 extras main carries that this branch still does not are the same ones as
before the merge: the intel, rocm and flashattention*cu12x families, which pin
wheels by URL from the Intel, AMD and GitHub release indexes.

Two long-standing drifts in the same file, both with a red test pointing straight
at them:

  * jinja2>=3.1.0 was missing from the studio extra while studio.txt lists it, so
    `pip install "unsloth[studio]"` built a venv the server cannot boot.
  * src-tauri/icons/icon.icns and icon.png were missing from studio package-data,
    so the published wheel had no icon for install.sh to build the macOS .app and
    Linux .desktop launchers from.

Test guards updated to accept both spellings of an xFormers pin rather than only
main's, so they hold on either branch:

  * test_torch2110_cuda_extras.py and test_windows_xformers_wheel_match.py check
    the version and the Windows/Linux markers on both forms, and the index only on
    the URL form, which is the only form that carries one.
  * test_scan_packages.py: torch is digest-pinned in the baseline and is a range
    here, because this branch declares the whole runtime in [project].dependencies
    and a published wheel cannot exact-pin torch. Allowed by name, and only for the
    pyproject half, with the bound itself asserted.
  * test_wheel_smoke_publish_guard.py reads two checked-in files with the platform
    default encoding, which main's new test_source_read_encoding.py flags.

The full set of tests that read pyproject.toml is green: 2695 passed, 187 skipped.
origin/pip had 13 failures in that same set before this merge.
@danielhanchen
danielhanchen force-pushed the merge-main-into-pip-2026-09 branch from 4beb7ae to 0673b18 Compare September 8, 2026 13:36
@danielhanchen
danielhanchen merged commit 7ff0bc0 into pip Sep 8, 2026
18 of 114 checks passed
@danielhanchen
danielhanchen deleted the merge-main-into-pip-2026-09 branch September 8, 2026 13:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.