Repository navigation
Studio: keep what you typed with an image when a chat is shortened - #10165
Conversation
GitHub Actions reproductionPinned head Run 33565907148 — green on What the probe reads off the two checkouts, on a 30 000-character image payload:
And what the model is handed after the reset, on a 20-message thread opened with a screenshot ( The block goes out empty before the fix. The instruction the user typed beside the picture is not late or truncated; it is absent. A/B verdict on The gate is deliberately not "everything is green": the suite carries failures that depend on the environment rather than on this change (the One case beyond imagesThe same mispricing hits a turn with no attachment at all. So the same words were carried when the client sent a string and dropped when it sent a list. Covered now by Harness: |
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
Before/after in the real Studio, and a correction to this PR's descriptionTwo isolated installs of this repo, merge base Both sides compacted identically —
The instruction was typed beside the screenshot 222 messages earlier. Before the fix it is not in the block; after it, it is. Correction:
|
CI, settled
Two reds remain, and neither is this PR's. Both fail identically on a clean
Both are source-grep contract assertions over |
|
Confirmed this hits |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Thanks @NilayYadav. Pricing the bullet instead fixes the opposite case in the same place. A turn carrying an attachment used to skip the filler check, so "ok" sent with a screenshot could become a bullet of its own. I compared against the merge base: the instruction is absent before and present after, and the filler case goes the other way. The test file passes on Linux, macOS and Windows apart from the archive reachability probes that need /proc. The two red checks are the unsloth_zoo scan digest failure, already red on main at this branch's merge base. |
* Publish only the wheel to PyPI, not the sdist (#10202) Co-authored-by: danielhanchen <[email protected]> * Bump install.sh / install.ps1 pin to unsloth>=2026.9.2 (#10203) Co-authored-by: danielhanchen <[email protected]> * Add DeepSeek Harness to unsloth start (#10097) * 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]> * Studio: stop generating when the client goes away (#10096) * 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> * Studio: keep an instruction typed with an attachment through a compaction (#10165) * Order the Ollama stop-token scan instead of leaving it to a set (#10101) --------- Co-authored-by: oobabooga <[email protected]> * Studio: replay a web_search result the way the client sent it (#10131) --------- Co-authored-by: oobabooga <[email protected]> * Studio: report context overflow the way Anthropic does, so Claude Code can compact (#10090) * Restore the comment tails the trim cut off (#10205) * 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 * Studio: accept subtitle, caption and the rest of the common attachment 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]> * Studio: count only this adapter's engines in the Windows AMD GPU utilization (#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 (#10184) * 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 b8064188b 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]> * Let audio models load into CPU RAM instead of the GPU (#10054) * 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…

When a long chat with a picture in it gets shortened to make room, the summary block leaves out whatever you typed alongside the picture, and often comes out empty. The model then answers as if you never said what you wanted.
Each message was being measured by its full size, and a picture is huge, so any message with one looked too big to keep. Only the words are ever carried over, and those are tiny.
Messages are now measured by the words that actually get carried. Also stops a message that only says something like "ok" from being carried just because a picture was attached to it.