Repository navigation
common : --fit grows the ubatch of MoE models into spare VRAM, for up to 2.5x faster prompt processing - #321
Conversation
A MoE ubatch reads the weights of nearly every expert, and uploads them when the experts are in host memory, so prompt processing pays one pass over all experts per ubatch. Without -ub, MoE models now use the logical batch (up to 4096) instead of 512. -ub still overrides it. With a draft or MTP model the larger default applies only when the tensor overrides keep the experts in host memory. The draft context follows the main context's ubatch, so both compute buffers grow, and with the whole model on the GPU that can overrun VRAM.
|
Initial version ( Recording the first approach and its numbers here, because the body will change if the Approach: MoE models (GGUF Results:
Why it's being reworked: a fixed default ignores how much VRAM is free. On a nearly full card:
The next version lets |
Replaces the fixed MoE default from the previous commit. Without -ub, --fit now places the weights and the context at the default ubatch as before, then doubles n_ubatch towards n_batch (up to 4096) while the larger compute buffers still fit in the memory left over on every device. The fit never gives up context or device weights for a bigger ubatch, and a draft or MTP context that follows the main ubatch is measured with it. -ub still overrides it, and -fit off keeps the default.
The growth stays on by default. -fitub off (or LLAMA_ARG_FIT_UBATCH=off) keeps the ubatch at its default while --fit still places the weights and the context, so the behaviour can be switched off without pinning -ub 512.
-fitub becomes -fitu (as -fitp, -fitt, -fitc), the option moves next to the other --fit options, and the log line names it as the way to turn the growth off.
|
@danielhanchen Reopening this because it looks like it fits with your open MoE PRs instead of overlapping them. If you don't think we need it, feel free to close it. What it does: MoE models still process prompts in chunks of 512 tokens unless you pass How it fits with your PRs. I merged this PR into each head and measured prompt speed with experts in RAM (
With the whole model in VRAM, the gain is smaller but still there: about 1.2x on the R9700 and 1.46x to 1.62x on the A100. On the L4 it stays at 512, because there's no room left over. Dense models are never touched. Correctness: greedy outputs are byte-identical with and without this PR on every pair, card and config, and answer speed doesn't change. Running each PR with The merges were local. Both had small conflicts, in |
…ubatch The growth inferred that the draft follows the target from equal ubatch values, so --spec-draft-n-ubatch set to the target's ubatch was measured at the grown size while the draft context is created at the user's value. Pass whether the draft follows from the caller instead.
|
Codex review on a mirror of |
|
AMD, model fully in VRAM, which the table above didn't cover yet. Radeon AI PRO R9700 32 GB, Windows 11, ROCm 7.1, prebuilt
Mean of 2 launches per row, alternating order. Decode output identical across all launches. Same result as the CUDA fully-in-VRAM rows: 2048 is the sweet spot, and 4096 adds nothing. |
Upstream moved the fit call into common_fit_apply and takes model paths as vectors (get_paths, hp_nsk). The ubatch growth is re-applied on that API: common_fit_apply keeps the fit status and grows the ubatch after a successful fit, and the extra model is measured by its own helper so that common_params_fit_impl stays as upstream has it.
…ed and host memory - Sliding-window models keep their ubatch unless --swa-full: the SWA cache holds n_swa + n_ubatch cells and every decode step attends over all of them (gemma-4 and gpt-oss decode slower at 2048). - Only the default ubatch grows: presets and tools that set n_ubatch themselves (gpt-oss presets, 2048) keep it, as -ub does. - CPU-only runs keep their ubatch and skip the extra probe. - The growth stops when the host buffers it projects (the pinned compute buffer grows with the ubatch) would leave less than 1 GiB of available system memory (MemAvailable on Linux, ullAvailPhys on Windows). - test-arg-parser covers -ub at the default value and -fitu.
Codex Review Summary: ✅ CompletedThis 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. |
…ices and mmap in the ubatch growth - Keep the ubatch when the main model's context memory grows with it: that is a sliding-window cache, whatever the GGUF metadata says (Llama 4 without the sliding_window key still uses an 8192 chunked window), and --swa-full is covered because its cache does not grow. One reference probe at the fitted ubatch, skipped without devices. - Stop when a draft that follows the main ubatch also uses a device the main model does not: that device's margin is not checked. - Count resident weights in the host check unless the loader will mmap them (mmap supported, and for AUTO every device supports mmap). - One sentence per comment line.
…fault ubatch - An integrated GPU (CUDA UMA such as DGX Spark, APUs) reports free system memory, so the host buffers the growth projects are subtracted from its budget as well. - A refit (a server waking from sleep reloads from params) starts again at the default ubatch and grows into what is free then, instead of fitting weights and context around the ubatch grown before.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5624905858
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (!params.lora_adapters.empty() || (!params.mmproj.path.empty() && !params.mmproj_use_gpu)) { | ||
| return; // adapters and a CPU projector load into the memory the fit left, which the growth would take |
There was a problem hiding this comment.
Budget the TTS projector before allowing ubatch growth
For non-SWA MoE TTS backbones such as Drama3 or ZONOS3, a GPU projector still passes this guard. Its memory has not been reserved. The TTS loader creates the text context before loading the projector, without adding its allocation to fit_params_target. Growth can therefore consume VRAM needed by a projector larger than the remaining fit margin, turning a configuration that worked at ubatch 512 into an OOM during mtmd_init_from_file. Disable growth for this caller or reserve its projector before fitting. Written with GPT-6.1 Sol
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3767186: llama-tts keeps the default ubatch, like llama-mtmd-cli and llama-mtmd-debug, since its projector loads after the fit.
| std::vector<llama_device_memory_data> ret(devs.size() + 1); | ||
| ret.back().mb = measured.back().mb; | ||
| // host RAM always taken, whatever the main model's mmap: CPU extra buffers, and weights the draft copies | ||
| ret.back().mb.context += cpu_extra; |
There was a problem hiding this comment.
Exclude shared MTP weights from the extra host-memory charge
With MTP and CPU-repacked experts, this adds shared model weights to the extra context charge. The later shares_model cleanup clears only mb.model, not mb.context. Since cpu_extra includes model allocations and MTP reuses the target model, the host check charges the same repacked weights once for the target and again for the MTP context. When available RAM covers one copy but not two, this incorrectly rejects every ubatch increase despite sufficient memory. Keep CPU model bytes separate from context/compute bytes and omit the shared model portion. Written with GPT-6.1 Sol
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3767186: an MTP head that shares the target model is no longer charged for the CPU repacked weight bytes; its own CPU context and compute buffers still count.
… keep the default ubatch in llama-tts
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 37671861cb
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| std::vector<llama_device_memory_data> dmds = common_get_device_memory_data_impl( | ||
| paths_model, mparams, cparams, devs, hp_ngl, hp_nsk, hp_nct, hp_nex, log_level, &cpu_extra); |
There was a problem hiding this comment.
Budget CUDA MoE scratch before accepting ubatch growth
For CUDA FP16/BF16 MoEs, this estimate omits the scratch buffers used by the cuBLAS fallback. Those buffers grow with the ubatch but are not included in the scheduler's memory report. For a 4096-token ubatch with 16 active experts and 4096-wide inputs/outputs, src1_sorted and dst_sorted alone require 1.5 GiB, versus 192 MiB at 512 tokens. The growth loop can therefore accept 4096 with the default 1 GiB margin remaining and then encounter a CUDA OOM when processing a full ubatch, even though the 512-token baseline fits. Budget this batch-dependent scratch before accepting growth. Written with GPT-6.1 Sol
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining: by default the growth stops at n_batch (2048), where this scratch is about 0.75 GiB and stays inside the 1 GiB margin the fit keeps for allocations it cannot see; 4096 needs an explicit larger -b on an FP16/BF16 MoE that sits right at the margin, the same exposure a user has today passing -ub 4096.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 37671861cb
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| // An OpenVINO dGPU is counted too, which only makes its check stricter. | ||
| static bool common_fit_dev_shares_host_memory(ggml_backend_dev_t dev) { | ||
| const std::string reg = ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev)); | ||
| return ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_IGPU || reg == "OpenCL" || reg == "HTP" || reg == "OPENVINO"; |
There was a problem hiding this comment.
Include managed CUDA allocations in the host-memory budget
On Linux with GGML_CUDA_ENABLE_UNIFIED_MEMORY=1 on a discrete CUDA GPU, this helper still returns false. That mode allocates with cudaMallocManaged and reports available host RAM as device headroom, so the device and host checks can independently spend the same RAM while managed buffers spill beyond VRAM. A mocked-budget run of the actual growth loop with 8 GiB host headroom and 2 GiB VRAM accepts ubatch 2048 even though combined host demand rises from 6.75 GiB at 512 to 9.25 GiB; automatic growth can therefore exhaust host memory for a configuration that fits at the default. Account for managed-memory spill in the host budget, or skip growth for this mode. Written with GPT-6.1 Sol
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining: GGML_CUDA_ENABLE_UNIFIED_MEMORY is an opt-in mode where the user already chooses to oversubscribe VRAM into pageable host memory (managed allocations page rather than fail), so it is outside the default path this growth budgets.
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
… parameters of the memory probe
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |




What this does
llama.cpp reads a prompt in chunks called ubatches. The default chunk is 512 tokens. For MoE models (Qwen3-30B-A3B, DeepSeek, Qwen3.8-Flash-Next and so on), every chunk has to run through all the experts' weights once. So a 4,600-token prompt means 10 trips through every expert. When the experts live in system RAM, each trip also copies them to the GPU again.
Bigger chunks mean fewer trips, but each chunk needs more memory while it runs. So this PR lets
--fitdecide:--fitplaces the weights and the context exactly as it does today, at 512.n_batch, max 4096) as long as every device still keeps the fit's margin free and host RAM keeps 1 GiB free.The log says when it kicks in:
MoE model, n_ubatch = 2048 fits in free memory (set -ub or -fitu off to override).When it stays at 512
The growth only runs where it is a measured win and its memory can be budgeted. Everything else keeps today's behaviour byte for byte:
expert_count= 0).--lora) or a multimodal projector on the CPU (--no-mmproj-offload), which load into the memory the fit leaves.llama-mtmd-cli,llama-mtmd-debugandllama-tts, which load the projector after the fit without reserving its memory.-ub/LLAMA_ARG_UBATCH, or a preset or tool that sets its own chunk size.-fit off, or-fitu off(--fit-ubatch off,LLAMA_ARG_FIT_UBATCH=off) to turn off just the growth.--spec-draft-n-ubatchis kept.Memory checks
Each doubling re-measures memory with the fit's own probe and is kept only if all of these hold:
--fit-targetmargin free.MemAvailable, capped by any cgroup v1 or v2 memory limit up to the container root.How this ships
The unslothai prebuilt is an upstream release tag plus the pins listed in
scripts/unsloth/pr-set.json, merged in order. This PR is one pin: its diff is exactly one change on top of upstreamb13004(the PR's base branch,base/upstream-a105b1924), 12 files undercommon/,tests/,tools/mtmd/,tools/tts/and the tool READMEs. It adds no fork-only code beyond that. Once upstream carries an equivalent change, the pin is dropped.The change leaves the signature of the fit's memory probe (
common_get_device_memory_data_impl) untouched: the CPU extra buffers it needs (repacked weights) are collected through a scoped collector set by the caller. Other pins that extend that probe, such as the MoE cache sizing in #251, therefore merge with this one without a conflict. Checked by running the nightly's merge (git diff3, then the additive add/add resolver) of this head on top of upstreamb13007plus the current pin set including #251:common/fit.cppmerges cleanly,common/common.cppresolves as pure add/add, and every file this PR touches compiles in the merged tree.Results
Prompt processing, same machine, with and without the change. These numbers were measured on an earlier version of this PR. Since then, sliding-window models (the gpt-oss rows) keep 512 and are listed separately below; the other rows are unaffected by the later scope limits.
-cmoe)--fitspills experts-cmoe)-cmoe)-cmoe)-cmoe)-ubset by hand, details)-cmoe)--fitspills experts-cmoe)-ub 1024by hand does the sameSliding-window models, measured before the scope limit and now left at 512 (use
-ub 2048by hand for these numbers): gpt-oss-20b on L4 2,751 to 3,441 tok/s, on A100 4,489 to 5,693 tok/s, on RTX PRO 6000 16,657 to 18,794 tok/s.Generation speed doesn't change. What changes is how long you wait for the first word (4,565 prompt tokens divided by the prompt speeds above):
Accuracy
Perplexity on wikitext-2 (Qwen3.8-Flash-Next, experts in RAM): 5.365 at ubatch 512 and 5.370 at 2048, error bars ±0.08. This is the same tiny numeric difference you get today by passing
-ub 2048yourself. When the growth does not apply, the output matches the base exactly.Where to look in the code
common.cppcommon_fit_apply_ubatch: the gate (no-ub, no LoRA adapters or CPU projector, MoE, a GPU, a host RAM reading) and the call after a successful fit.common.cppcommon_host_memory_available: free host RAM, capped by the cgroup v1 / v2 limit.fit.cppcommon_fit_n_ubatch: doubles the ubatch, re-measures, stops on a growing context (sliding window), a draft on a device outside the main model's, or a device / host margin miss.fit.cppcommon_fit_dev_shares_host_memory,common_fit_extra_memory: which devices draw on host RAM, whether a model is mmapped, and the draft / MTP memory measurement.fit.cppcommon_measure_memory: the router estimate; its minimum is refit at the default ubatch.arg.cpp: the-fitu/--fit-ubatchswitch;-ubrecords that it was given.Tradeoffs
-ub 2048still works if you want the speed anyway.How it was tested
test-arg-parsercovers-uband-fitu; CPU build and tests pass at the current head; the pin set merges cleanly with this PR onb13004/b13005.b13004andb13004+ this PR, 3 long prompts each, greedy):--swa-full-ub 2048-cmoe-ub 2048;-fitu offand-ub 512give base's 512 output--fitplacement-ub 2048-cmoe-ub 2048; same with--no-repack37671861con an L4 (static builds of the PR base and base + this PR, a check that only the head binary has--fit-ubatch): gpt-oss-20b and Qwen3-0.6B unchanged (512, same output and buffers); Qwen3-30B-A3B UD-Q2_K_XL with-cmoeand with--fitplacement grow to 2048 with the same weight placement and output identical to base with-ub 2048;-fitu offand-ub 512reproduce base.