Skip to content

Unsloth Studio / Desktop: add a Benchmarks page that sweeps speculative decoding, KV cache and RAM offload settings on the loaded GGUF - #11808

Open
LeoBorcherding wants to merge 91 commits into
unslothai:mainfrom
LeoBorcherding:studio-benchmarks-page
Open

LeoBorcherding wants to merge 91 commits into
unslothai:mainfrom
LeoBorcherding:studio-benchmarks-page

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #11646 (Phase 1: config sweeps on the model you already run).

What This Does

Chat already has a lot of speed settings: speculative decoding (MTP, ngram, DSpark, DFlash), how many tokens to draft, KV cache type, context length, parallel slots, and how much of the model to keep on the GPU versus system RAM. The best mix depends on your model and your hardware, and until now the only way to find it was to change one setting, send a chat message, eyeball the speed, and repeat.

This PR adds a Benchmarks page (sidebar, under More) that does that loop for you. Pick a GGUF model, pick what to compare, press Run. It loads each setup in turn on your own machine, runs the same prompts against it, and shows a live chart of tokens per second. When it finishes you get the winner, how much faster it is than your baseline, and a button that applies the winning settings to Chat. Every run is saved to History.

Sweep What it compares
Speculative decoding Off, Auto (default), ngram, MTP, MTP + ngram, DSpark, DFlash. Modes the model can't run are skipped with the reason
MTP draft depth Speculation off against MTP at 1 to 8 draft tokens
Ngram tuning Ngram alone, MTP alone and both together, across ngram key length and discard floor
DSpark tuning DSpark at 1 to 8 draft tokens, plus its draft cache at q8_0 and q4_0
KV cache type f16, q8_0 and q4_0
Context length The same prompt at growing context windows, with load time and VRAM for each
Parallel slots 1, 2, 4 slots (what reserving slots costs one chat, not multi-user throughput)
RAM offload Auto fit against experts on CPU (MoE) or GPU layers (dense) at several levels, and everything on the GPU. Pinned at 8K context so only the split changes
Auto-tune Off, MTP 1 to 4, ngram, MTP + ngram; picks the fastest and hands it to Chat

Nothing is sent anywhere: it talks to the local llama-server Unsloth Studio already runs, and results live in studio.db.

How It Looks

Screenshots from Unsloth Studio (web) on a Colab L4 (22.5 GB), llama.cpp b11876, at f31ac9f741.

A sweep, live and finished

gemma-4-12B-it-qat UD-Q4_K_XL, speculative decoding: MTP 4 was fastest at 72.5 tok/s, 2.17x speculation off (33.4). DSpark and DFlash rows say why they were skipped (this gemma ships no drafter).

speculative decoding sweep

speculative decoding results

The MTP draft depth sweep on the same model:

MTP draft depth chart

On a model this small it's the honest answer that speculation doesn't help: Qwen3.5-0.8B MTP runs fastest with it off (237 tok/s), and the page says "nothing beat speculation off".

RAM offload

The rows are built from the model: MoE models get "experts on CPU" at 12 / 24 / 36 / all of their expert layers, dense models get GPU layers at 25 / 50 / 75%. The table records VRAM for each row. When a row runs out of memory, the hungrier rows after it are skipped instead of failing one by one.

MoE offload chart

Qwen3-30B-A3B, 8K UD-Q4_K_XL (17.7 GB) VRAM UD-Q8_K_XL (36 GB) VRAM
Auto fit 97.6 tok/s 17.7 GB 46.5 tok/s 21.1 GB
All on GPU 97.3 17.7 GB skipped (a lighter row ran out of memory)
Experts on CPU, 12 of 48 53.4 13.8 GB out of memory
Experts on CPU, 24 of 48 35.9 10.0 GB 24.2 18.6 GB
Experts on CPU, 36 of 48 29.2 6.2 GB 19.1 11.5 GB
Experts on CPU, all 48 23.3 2.2 GB 15.8 3.3 GB

MoE Q8 offload

skipped row reason

Auto-tune and Apply to chat

Auto-tune picked MTP 3 (67.6 tok/s; MTP 4 at 68.9 was inside the 3% noise rule). Apply to chat relaunched llama-server with --spec-type draft-mtp --spec-draft-n-max 3, and /api/inference/status reads the same.

auto-tune

Sharing the server

A sweep uses the one llama-server Chat uses, so it holds a lease while it runs:

  • Another tab or device gets "Another benchmark is running" instead of a second run. A tab closed mid-run frees the lease within 45 s.
  • A load or unload from Chat or the API gets a 409 ("A benchmark is running on this model. Stop it on the Benchmarks page or let it finish, then try again.").
  • Chat and API requests still go through; the run counts them and says so in its footer, since those rows may read slow.

outside requests footer

History

history

Light, 1440 Dark, 1920
light dark

Under the Hood

  • Frontend (studio/frontend/src/features/benchmarks/): the runner loads each row through the same load endpoint Chat uses, streams completions, and times them. It only reloads the model when a row changes a load setting. Offload rows turn off the "too slow, stop early" floor, since slow is the expected answer there.
  • Backend (studio/backend/routes/benchmarks.py, storage/benchmark_runs_db.py): GET/PUT/DELETE /api/benchmarks/runs and POST /api/benchmarks/lease, stored in two new tables in studio.db (benchmark_runs, benchmark_results) created with CREATE TABLE IF NOT EXISTS, so no migration. BenchmarkTrafficMiddleware counts outside inference requests during a sweep and refuses outside loads and unloads.
  • Sidebar: a benchmarks nav entry under More, plus its id in the personalization allow-list.
  • No changes to how Chat loads or runs models. Apply to chat goes through the same settings Chat's own panel writes.

Known limitations

  • The picker lists every on-device model. A non-GGUF pick shows "loads first" and runs a full load before it's refused (80 s for a 0.6B on the transformers path).
  • Reloading the page mid-run saves the row that was generating as network error, and the rest stay queued; the run is marked Stopped early.
  • An out-of-memory row's reason quotes the tail of llama-server's load log, which is often token metadata rather than the allocation failure.
  • "Restore chat's settings after" restores Chat's settings, not whatever an API client had loaded.

Hardware coverage

No hosted GitHub runner has a GPU, and this page's numbers only mean something on a real one. The Strix Halo runner on ooba's fork is Linux on an AMD APU and doesn't run Unsloth Studio, so it can't see this PR. These tables are the test report.

Where it was run

Machine Commit What ran What it proves
Colab L4 22.5 GB, 53 GB RAM, Linux, driver 580.82.07, llama.cpp b11876 (CUDA), Unsloth Studio web f31ac9f741 Every sweep, dense and MoE RAM offload, a real out-of-memory skip, Auto-tune and Apply, History, Stop, tab close and reload, outside traffic and the 409s, light and dark at 1024 / 1440 / 1920 The whole page on NVIDIA / Linux in the browser
AMD Radeon AI PRO R9700 32 GB, Windows 11, llama.cpp ROCm b11139, Unsloth Desktop 73b20b43fa Speculative decoding, MTP depth, KV cache, dense RAM offload, Auto-tune, Apply to chat, History, light and dark The page on one AMD GPU on Windows. Measured before the 10-16 UI slimming and the main merges; no hardware behaviour has changed since

What is still missing

Setup Why we care
Apple silicon / Metal Unified memory: "VRAM" and RAM are the same pool, so the offload rows and the VRAM column may read oddly. The page loads and the header pill reads right on an M5 (checked at 60a396aeb4); no sweep has finished there
Two or more GPUs One header pill per GPU and a per-model offload split; neither seen with two cards
A model that ships a DSpark or DFlash drafter Those rows were only seen being skipped
A context row the server clamps The context steps stop at the max the server reports, so no row asked for more on these models; the clamp-and-skip path is covered by a unit test only
Linux on AMD Only Windows was run on AMD

Bottom line: the page works end to end on NVIDIA / Linux in the browser, including the MoE offload and out-of-memory paths, and on one AMD card on Windows. The biggest gap is Apple silicon.

Tests

Measured at 0b9c97be1a (up to date with main), macOS, Apple M5:

  • Frontend: typecheck, npm test 0 fail (14,180+ tests, including benchmarks-math.test.ts), npm run build, bundle:check, i18n:check:strict
  • Backend: test_benchmark_runs.py, test_personalization_settings.py, test_llama_server_args.py, test_text_io_encoding.py, test_llama_server_api_key_default.py, all pass
  • Every sweep, both RAM offload paths and the out-of-memory skip on a Colab L4
  • Auto-tune picks a winner, and Apply to chat relaunches llama-server with it
  • History: cards, filters, open a past run, delete, stopped-early badge
  • Stop, tab close (lease freed in 36 s), reload, outside requests counted, outside load/unload refused
  • Light and dark at 1024 / 1440 / 1920
  • Apple silicon sweep
  • Multi-GPU
  • DSpark / DFlash rows on a model with a drafter

Full results with logs: LeoBorcherding#310 (comment 6456743449).

…nd parallel-slot sweeps

Reloads the loaded GGUF once per setting, streams timed completions and keeps
llama-server's own timings. Rows that Studio fell back on are skipped with the
reason instead of charted. Prompts rotate across runs so the ngram cache can't
inflate its rows by copying a repeated answer. Phase 1 of unslothai#11646.
…ng and a setup side panel

Runs are saved as they go in two new studio.db tables (benchmark_runs,
benchmark_results) behind /api/benchmarks/runs, so a stopped or crashed
sweep keeps the rows it finished.

Auto-tune tries off, MTP 1-4, ngram and MTP + ngram, picks the fastest
(a simpler setting within 3% wins) and applies it to chat's Run Settings.
A DSpark tuning sweep covers draft depth and draft KV dtype.

Rows are bounded so an out-of-VRAM spill cannot freeze the machine: load
and generation time limits, a throughput floor, OOM labelling, and larger
context rows skipped after the first OOM.

Generations use chat's sampling settings. The chart footer and exports
list every Run Settings value plus GPU, backend, runtime, OS, threads and
RAM. The page is one screen: a setup side panel, the model strip, and the
results, with the live queue drawn as placeholder rows in the chart.
…s a RAM offload sweep

- Benchmark and History tabs. Setup, results and a Train-style run preview share the
  Benchmark tab; History is a card grid with each run's winner, speed-up and row bars.
- Chat's model picker in the tab bar: benchmark any on-device GGUF and quant, loaded
  first with chat's Run Settings. The picked quant now reaches the load and Apply to chat.
- RAM offload sweep: Studio's fit, then MoE expert layers on CPU from all to none
  (n_cpu_moe, scaled to the model's MoE layer count), GPU layer steps for dense models.
  Rows pin 8K context, run from least VRAM to most, and skip hungrier rows after an OOM.
  VRAM after each load is recorded and shown in the table.
- Header shows every GPU, VRAM and RAM used/total, CPU threads and the llama.cpp backend.
- The setup card fits the window and scrolls its Compare list instead of running off it.
- The chart stops growing past its natural width; queued rows draw as quiet lanes.
- The runs list carries each row's mean tok/s so History needs no per-run fetch.
- Number fields clamp when you leave them, not on every keystroke, so clearing one
  to type a new value no longer snaps it to the minimum.
- The Fastest tile names the baseline when nothing beats it (an offload sweep's Studio
  fit); the ratio tile says "nothing beat it" instead of a bare 0.04x.
- A sweep with one family (offload, KV, context) lists its rows flat; single-row
  families (DSpark, DFlash) keep their full names.
- Footer and History show the context rows actually ran at (8K pinned, or "varied").
- History marks a run cut short by Stop as "Stopped early", not "Complete".
- "vs Studio auto" keeps its capital; only "speculation off" reads lowercase mid-sentence.
- Table cells no longer wrap; tighter padding so all eight columns fit.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 24, 2026
urllib wraps only a failure to send the request in URLError. A server that
closes the connection before answering raises http.client.RemoteDisconnected
out of getresponse(), and a reset or short body mid-download raises
ConnectionResetError or IncompleteRead; is_retryable_url_error treated all of
them as fatal, so one dropped connection skipped every remaining attempt.

On unslothai#11808's no-Visual-Studio Windows leg that sent a clean install to the
source build on the first attempt:

  candidate attempt failed before activation for
  app-b11139-mix-a6922cc-windows-x64-cpu.zip: Remote end closed connection
  without response

ConnectionError and IncompleteRead are now retryable in prebuilt_core (llama.cpp
and whisper.cpp) and in install_node_prebuilt, which had the same gap. Both
download loops already restart from a fresh temp file or buffer, so a retry
cannot splice two bodies together.
…and context limit for picked models

- Benchmark runs that select a different GGUF via tuneModel left chat pointed at the benchmark target after finishing. The Restore-after option now reloads the model chat originally had open.
- With prompt rotation on, each swept variant was fed a different subset of the built-in prompts, so a throughput difference could come from prompt length rather than the setting. Every variant now runs the same prompt sequence.
- In context and offload sweeps, one unrelated generation error (e.g. a transient 500) marked the row as out-of-memory and skipped all remaining valid sizes/placements. Only genuine memory/limit/floor failures now trigger that skip.
- When benchmarking a GGUF other than the one loaded in chat, the context-length sweep used the resident model's context window. It now uses the selected model's own context length from its GGUF header.
…nal-save race

- Auto-tune's verdict card would label a cancelled run "Auto-tune picked" and let you apply a winner chosen from partial data, because it keyed off `finishedAt`, which the runner sets even on cancel. It now also requires every row to have reached an end (`ranToEnd`), matching the history grid.
- The first measured sample was counted twice in the live chart and mid-run snapshots because the live run shared its results array with the runner, which had already pushed that sample before emitting it. The live run now copies the array on start so each sample is appended once.
- A slow or in-flight mid-run save could complete after the final save and overwrite the finished benchmark run with a partial snapshot (`finishedAt: null`, fewer rows). The final save now drains any queued checkpoint save first, so it is always the last write.
…r an auto OOM, and skip the relative spill floor during warm-ups

- A Stop during the benchmark's initial model load (or metadata read) left Chat on the benchmark target model even with "Restore chat's settings after" enabled, because the swap happened outside the restore scope. The swap and setup now run inside that scope, and a swap-in-progress is tracked so an aborted load is still restored.
- When the offload sweep's automatic "Studio auto" row ran out of memory, every manual CPU-offload/GPU-layer row after it was wrongly skipped as a context failure, so the lower-VRAM placements the sweep exists to test never ran. Only context sweeps now mark a context as failed; offload rows recover from an auto-placement OOM.
- A variant with a slow cold start (e.g. modes that initialize a drafter or ngram cache on the first request) could be killed during warm-up for running below 20% of the fastest measured row, before its real throughput was ever measured. The relative spill threshold now applies only to measured runs; the absolute floor still guards warm-ups.

@LeoBorcherding LeoBorcherding left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Codex findings, via a mirror

Codex does not answer on this repository, so it ran against a copy of this pull request's commits at LeoBorcherding/unsloth-staging-review#23. It looked at 4341c20eda there, which is this PR's f337880b2 replayed onto main 1ecc01a30. Nothing was reviewed or resolved on the copy: the findings are here, in Codex's words, to be worked through on this pull request.

4 findings, inline below where the line is on this diff.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Pushed 4fbb928. The Context length sweep kept the previously selected model's context steps when the target model changed or when the GGUF header resolved after the sweep was picked, so it could benchmark the wrong window. Context rows now rebuild whenever the resolved max context changes. History cards reported the fastest non-baseline row as the winner even when the baseline was actually fastest, showing a slower setting with a below-1x ratio. Cards now pick the fastest row overall and compare separately, matching the results panel. Auto-tune could pick a candidate that measured one sample and then failed on a later run, and apply that failed setting to Chat. The verdict and the Apply action now only consider rows that ran to completion. On llama.cpp builds without --kv-unified, the Parallel slots sweep clamped every row to one slot yet charted 1/2/4 as distinct results. Rows whose requested slot count exceeds what the server actually served are now skipped with the reason instead of being charted.

…story winner, exclude errored rows from auto-tune, and skip clamped parallel-slot rows

- The Context length sweep kept the previously selected model's context steps when the target model changed or when the GGUF header resolved after the sweep was picked, so it could benchmark the wrong window. Context rows now rebuild whenever the resolved max context changes.
- History cards reported the fastest non-baseline row as the winner even when the baseline was actually fastest, showing a slower setting with a below-1x ratio. Cards now pick the fastest row overall and compare separately, matching the results panel.
- Auto-tune could pick a candidate that measured one sample and then failed on a later run, and apply that failed setting to Chat. The verdict and the Apply action now only consider rows that ran to completion.
- On llama.cpp builds without --kv-unified, the Parallel slots sweep clamped every row to one slot yet charted 1/2/4 as distinct results. Rows whose requested slot count exceeds what the server actually served are now skipped with the reason instead of being charted.

@LeoBorcherding LeoBorcherding left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Codex findings, via a mirror

Codex does not answer on this repository, so it ran against a copy of this pull request's commits at LeoBorcherding/unsloth-staging-review#23. It looked at 847261c203 there, which is this PR's 4fbb928c9 replayed onto main 1ecc01a30. Nothing was reviewed or resolved on the copy: the findings are here, in Codex's words, to be worked through on this pull request.

3 findings, inline below where the line is on this diff.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Pushed 2cc8367. When the sweep finished but the original chat model failed to reload, the failure was swallowed and the UI implied settings were restored. The runner now reports the restore failure and the Benchmarks page shows it, while still keeping the completed run. For context and offload sweeps on a newly picked model, Run was clickable before the model's metadata loaded, so the sweep could start using the resident model's context window or leftover offload rows. Run is now disabled for those sweeps until the picked model's header resolves. A benchmark run where every variant failed or was skipped before generating anything was discarded, losing the failure reasons. Such runs are now saved to History; a run cancelled before doing anything is still dropped.

…model metadata resolves, and persist runs that only produced failure diagnostics

- When the sweep finished but the original chat model failed to reload, the failure was swallowed and the UI implied settings were restored. The runner now reports the restore failure and the Benchmarks page shows it, while still keeping the completed run.
- For context and offload sweeps on a newly picked model, Run was clickable before the model's metadata loaded, so the sweep could start using the resident model's context window or leftover offload rows. Run is now disabled for those sweeps until the picked model's header resolves.
- A benchmark run where every variant failed or was skipped before generating anything was discarded, losing the failure reasons. Such runs are now saved to History; a run cancelled before doing anything is still dropped.

@LeoBorcherding LeoBorcherding left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Codex findings, via a mirror

Codex does not answer on this repository, so it ran against a copy of this pull request's commits at LeoBorcherding/unsloth-staging-review#23. It looked at e8bd73915d there, which is this PR's 2cc836799 replayed onto main 1ecc01a30. Nothing was reviewed or resolved on the copy: the findings are here, in Codex's words, to be worked through on this pull request.

3 findings, inline below where the line is on this diff.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Pushed fb780d1. On the Benchmarks page, if reading a non-resident GGUF's header failed, the request was swallowed and Run stayed disabled forever for context and offload sweeps with no explanation. The setup now surfaces the error and offers a Try again button that refetches, instead of silently blocking the run.

The studio/frontend/src/features/benchmarks/lib/bench-math.ts:359 finding is not actioned: Not actioned: the fixed [32,24,16,8] offload counts only run when the model's MoE-layer count is unknown, where the backend's clamp ceiling isn't available to deduplicate against. When the count is known (the normal path, from status or staged metadata) the rows are already scaled and de-duplicated via filter+Set, which is what the finding asks for. bench-math.ts:359 is left as a deliberate fallback.

The studio/frontend/src/features/benchmarks/stores/benchmarks-store.ts:211 finding is not fixed yet: Not fixed here, flagged as real: while a benchmark sweep runs it keeps reloading the shared llama-server, and nothing stops the user from sending a Chat message into it, which corrupts the measurement (contention or a wrong-config/failed request). The store-level guard only prevents a second sweep. A proper fix needs a benchmark lease or disabling Chat generation until the run and settings-restore finish; picking and wiring that mechanism through the chat runtime is a design decision left for the maintainer.

LeoBorcherding and others added 13 commits October 29, 2026 02:32
The sweeps throughput bars move out of BenchChart into BarRows / BarChart
(bar-chart.tsx), so the Evals and llama-bench tabs can draw the same rounded
bars, whiskers, grid and tooltip instead of their own div bars. Rows take a
value, an optional low/high whisker (clamped to the axis), a colour, a muted
tail and tooltip lines; groups add an optional heading band.

The SVG card (title, fine print, tooltip, literal colours for export) is
ChartFrame in chart-frame.tsx, and the pure geometry is chart-math.ts so the
layout and whisker clamp are unit tested. The headline Tile from the results
panel is exported as StatTile.

BenchChart renders byte-identical SVG for bars, runs and depth: 16 fixtures
(light and dark, bare and titled, pending rows, 16-row density, baseline
marker) rendered with react-dom/server before and after compare equal.
A CPU-only llama.cpp build still completes a manual placement, so rows like "All on GPU" charted CPU decoding. servedMismatch now skips manual GPU rows when the status reports gpu_backend_unavailable or offloaded_layers == 0.
…ared chart SVGs

main.py imports BenchmarkTrafficMiddleware from routes.benchmarks, which the desktop health test never stubbed. bar-chart.tsx and chart-frame.tsx draw viewBox SVG text pulled out of bench-chart.tsx, already allowlisted for the same reason.
…s as generations, outlast throttled renewals
…d KV flags, and tidy

Auto-switch and preview swap the server without a /load call, so a sweep's later rows could run on another model; both now 409 while a sweep holds the lease. KV and draft-cache rows drop chat's inherited -ctk/-ctv/-ctkd/-ctvd, which last-wins over the row. The progress bar counts only a failed row's missing reps, and a second Run click during the lease round trip is ignored. The per-group strip functions become one stripFlags. Adds the nav label to the 11 newer locales so i18n:check:strict passes, and tightens comments.
…ike a load

The lease check ran before the awaited swap gate, so a sweep could take the lease while a switch waited and then lose its model to it. The check now runs under the gate and counts the swap as a load in flight until the gate is released, so a lease is refused while it runs.
@LeoBorcherding

LeoBorcherding commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

Pushed 085b1c6e89, the head Codex reviewed with no major issues on the fork mirror (LeoBorcherding#310). Since b05e0b8f0f:

  • Expert-placement rows whose shape is unknown are skipped when they'd repeat another placement.
  • Draft-cache rows are skipped on a llama-server that has no draft KV cache flags.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants