Skip to content

vendor: update subprocess.h - #26061

Merged
ngxson merged 1 commit into
masterfrom
xsn/bump_subproc
Jul 24, 2026
Merged

ngxson merged 1 commit into
masterfrom
xsn/bump_subproc

Conversation

@ngxson

@ngxson ngxson commented Jul 24, 2026

Copy link
Copy Markdown
Collaborator

Overview

Bump subprocess.h to latest version, 8671cee1fc09f11a70ce3782a0ee13177c3aa387

New version has CWD support, requires for the upcoming stdio MCP support

Requirements

@ngxson
ngxson requested review from a team and ggerganov as code owners July 24, 2026 05:23
@ngxson ngxson mentioned this pull request Jul 24, 2026
4 tasks done
@ngxson
ngxson merged commit 0cea362 into master Jul 24, 2026
25 of 29 checks passed
@max-krasnyansky

max-krasnyansky commented Jul 24, 2026 •

Copy link
Copy Markdown
Member

@ngxson Heads up. This breaks Android builds that use older platform version.
This update needs ANDROID_PLATFORM=android-34
Our defaults are 28, for Snapdragon we use 31.

~/src/llama.cpp-hb$ git grep ANDROID_PLATFORM
.github/workflows/build-android.yml:          cmake -D ANDROID_ABI=arm64-v8a -D ANDROID_PLATFORM=android-31 -D CMAKE_TOOLCHAIN_FILE=${ANDROID_NDK_ROOT}/build/cmake/android.toolchain.cmake -D GGML_NATIVE=OFF -DGGML_CPU_ARM_ARCH=armv8.5-a+fp16+i8mm -G Ninja -D LLAMA_OPENSSL=OFF -D GGML_OPENMP=OFF -B build
.github/workflows/build-android.yml:            -DANDROID_PLATFORM=android-28 \
.github/workflows/release.yml:            -DANDROID_PLATFORM=android-28 \
docs/android.md:  -DANDROID_PLATFORM=android-28 \
docs/backend/OPENCL.md:  -DANDROID_PLATFORM=24 \
docs/backend/OPENCL.md:  -DANDROID_PLATFORM=android-28 \
docs/backend/snapdragon/CMakeUserPresets.json:            "ANDROID_PLATFORM": "android-34",
docs/build.md:  -DANDROID_PLATFORM=24 \
docs/build.md:  -DANDROID_PLATFORM=android-28 \

I'm good with bumping the defaults to 34.

This is the error with default builds.

/opt/android-ndk-r29/toolchains/llvm/prebuilt/linux-x86_64/bin/clang++ --target=aarch64-none-linux-android31 --sysroot=/opt/android-ndk-r29/toolchains/llvm/prebuilt/linux-x86_64/sysroot -DGGML_BACKEND_SHARED -DGGML_SHARED -DGGML_USE_CPU -DGGML_USE_HEXAGON -DGGML_USE_OPENCL -DLLAMA_BUILD -DLLAMA_SHARED -DMTMD_VIDEO -Dmtmd_EXPORTS -I/workspace/tools/mtmd/. -I/workspace/tools/mtmd/../.. -I/workspace/tools/mtmd/../../vendor -I/workspace/ggml/src/../include -I/workspace/src/../include -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security  -march=armv8.7a+fp16+dotprod+i8mm -fvectorize -ffp-model=fast -fno-finite-math-only -flto -D_GNU_SOURCE -O3 -DNDEBUG -O3 -DNDEBUG -fPIC -Wmissing-declarations -Wmissing-noreturn -Wall -Wextra -Wpedantic -Wcast-qual -Wno-unused-function -Wunreachable-code-break -Wunreachable-code-return -Wmissing-prototypes -Wextra-semi -Wno-cast-qual -Wno-missing-prototypes -pthread -MD -MT tools/mtmd/CMakeFiles/mtmd.dir/mtmd-helper.cpp.o -MF tools/mtmd/CMakeFiles/mtmd.dir/mtmd-helper.cpp.o.d -o tools/mtmd/CMakeFiles/mtmd.dir/mtmd-helper.cpp.o -c /workspace/tools/mtmd/mtmd-helper.cpp
In file included from /workspace/tools/mtmd/mtmd-helper.cpp:40:
/workspace/tools/mtmd/../../vendor/sheredom/subprocess.h:1215:19: error: use of undeclared identifier 'posix_spawn_file_actions_addchdir_np'; did you mean 'posix_spawn_file_actions_addclose'?
 1215 |     posix_error = posix_spawn_file_actions_addchdir_np(&actions, process_cwd);
      |                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      |                   posix_spawn_file_actions_addclose
/opt/android-ndk-r29/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include/spawn.h:92:5: note: 'posix_spawn_file_actions_addclose' declared here
   92 | int posix_spawn_file_actions_addclose(posix_spawn_file_actions_t _Nonnull * _Nonnull __actions, int __fd) __INTRODUCED_IN(28);
      |     ^
In file included from /workspace/tools/mtmd/mtmd-helper.cpp:40:
/workspace/tools/mtmd/../../vendor/sheredom/subprocess.h:1215:66: error: cannot initialize a parameter of type 'int' with an lvalue of type 'const char *const'
 1215 |     posix_error = posix_spawn_file_actions_addchdir_np(&actions, process_cwd);
      |                                                                  ^~~~~~~~~~~
/opt/android-ndk-r29/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include/spawn.h:92:101: note: passing argument to parameter '__fd' here
   92 | int posix_spawn_file_actions_addclose(posix_spawn_file_actions_t _Nonnull * _Nonnull __actions, int __fd) __INTRODUCED_IN(28);
      |                                                                                                     ^
2 errors generated.

@ngxson

ngxson commented Jul 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

I don't think the router mode should be compiled for android target, the OS would likely block the creation of process anyway

We should make a compile flag to exclude this system altogether

I'll push a PR for it

danielhanchen added a commit to unslothai/llama.cpp that referenced this pull request Aug 7, 2026
* sync : ggml

* opencl: transpose q4_K noshuffle scales for coalesced reads (#25805)

* opencl:  read/write MoE dp4a activation tiles to local memory as 128-bit (vectorized LD/ST perf opt) for Adreno GPUs (#25810)

* opencl: read MoE dp4a activation tile as 128-bit local loads

* opencl: vectorize MoE dp4a activation staging as 128-bit loads

* opencl: load and use `kernel_gemm_moe_q6_k_f32_ns` from bin kernel lib (#25797)

* llama-quant : exclude i32 ffn_gate_tid2eid routing table from quantization (#25787)

DeepSeek-V4's ffn_gate_tid2eid tensor is an i32 token-id -> expert-id
index table, not weights. It was never added to the name-based
exclusion list alongside ffn_gate_inp.weight, so llama-quantize tries
to quantize it and fails since i32 cannot convert to a float type.

Fixes ggml-org/llama.cpp#25754

Signed-off-by: Yash Raj Pandey <[email protected]>

* model: rotate injected K/V cache for DFlash (#25823)

* dflash: rotate injected K/V cache when using K/V quantization

* Update src/models/dflash.cpp

Co-authored-by: Georgi Gerganov <[email protected]>

* clearer format

* remove trailing whitespace

---------

Co-authored-by: Georgi Gerganov <[email protected]>

* opencl: Support broadcast for Adreno MUL_MAT and honor `view_offs` for Adreno Q8_0 MUL_MAT for llama-server multi-stream (#25910)

* opencl: handle broadcast for adreno gemm/gemv_noshuffle

* opencl: honor view_offs for adreno noshuffle gemm/gemv

* opencl: general GEMM/GEMV support broadcast

* opencl: remove unnecessary tests

* opencl: remove unnecessary comments

---------

Co-authored-by: Li He <[email protected]>

* ui: enable the agentic flow when only the JS sandbox is active (#25865)

The agentic gate counted MCP servers, builtin and custom tools but not
frontend tools, so with the JS sandbox as the only tool source the
agentic flow was skipped, no tools field reached the server and the
chat template rendered without the tool system prompt.

The sandbox is fully client-side: frontendTools derives from the
Developer settings toggle alone, counting it in the gate restores that
single source of truth.

* UI: fix Settings/Display tool call content toggle (#25783)

* ui: fix Show tool call in progress toggle ignored

The showToolCallInProgress setting was disconnected from the render
path during the agentic content rework: getDefaultExpanded() returns
a hardcoded false for tool call sections and an unconditional effect
auto-expands the currently executing tool call regardless of the
setting.

Drive default expansion of all tool call section types from the
setting and remove the now redundant auto-expand effect. Manual
toggling still takes precedence over the default in both directions.

* ui: rename Show tool call in progress to Always show tool call content

The previous name suggested symmetry with Show thought in progress,
which only applies while inference is running, but tool call content
stays expanded after completion. Rename the label, the settings key
and the syncable server key to alwaysShowToolCallContent. The synced
parameter never worked under its previous name so no migration is
needed.

* ui: fix collapsed user bubble with markdown rendering (#25869)

Edge paragraph margins are now zeroed at the source in
markdown-content.css, but the user bubble and the system message still
carried the -my-4 compensation for them. The uncompensated negative
margins shrank the wrapper 2rem below its content, collapsing
single-line user bubbles into a scrollable sliver and skewing the
system message expand threshold.

* llama_dsv4: write only used rows in state (#25325)

* llama_dsv4: write only used rows in state

* add TODO about conflating token pos with kv rows

* ui: Sidebar Conversations Bulk Action + Improved Settings logic/UI (#25815)

* feat: WIP

* feat: Replace conversation rename flow with unified AlertDialog component

* feat: Add radio group component and consolidate title generation settings

* refactor: Remove JS Sandbox global toggle and migrate legacy user state

* chore: Formatting

* refactor: Cleanup

Co-authored-by: Aleksander Grygier <[email protected]>

* refactor: Cleanup

* refactor: Marquee selection hook

* feat: UI improvements

* refactor: Bulk db operations

* fix: optimize bulk conversation deletion to handle ancestor chains

* refactor: remove pairedKey mechanism from settings system

* fix: remove redundant onclick handler from dialog cancel button

* chore: pin @lucide/svelte to exact version

* feat: Run JavaScript tool disabled by default

* fix: correct active conversation deletion tracking in bulk delete

* feat: improve shift-key multi-selection support in sidebar via keyboard

* refactor: Retrieve JS Tool enabling via Developer Settings

* nits: sync, dialog wording, cycle guard, and lockfile follow-ups

- Restore titleGenerationUseLLM registry entry so it syncs across devices again
- Mention fork cascade in the bulk delete confirmation dialog
- Clear newParent on cycle guard break so children never point at a deleted conversation
- Align @lucide/svelte in package-lock.json with the exact pin in package.json

---------

Co-authored-by: Pascal <[email protected]>

* hexagon: add CLAMP op (#25934)

* CUDA: vectorize same-type get_rows with int4 copy (#25929)

k_get_rows_float did a scalar one-element-per-thread copy and recomputed the
row-invariant work (index load, fast_div_modulo, src/dst row pointers) for
every element. Hoist that out of the per-element loop, and add a vectorized
path (k_get_rows_float_vec) that copies one int4 (16 B) per thread for the
contiguous same-type (no-cast) case.

The vectorized path is gated at compile time (is_same<src0_t, dst_t>) and at
runtime on 16-byte alignment of the base pointers and all row strides and on
ne00 % VEC == 0. Vectorizing divides the block count by VEC, so a small
single-row gather can drop below the device CU count and regress; an
occupancy gate keeps those on the block-rich scalar path.

On Strix Halo (gfx1151) the DeltaNet recurrent-state gather (ne00=524288)
drops 18.6us -> 13.0us (rocprofv3 HW timestamps), faster than the Vulkan
backend, with no regression on the small conv-state gather; total get_rows
-27%. test-backend-ops GET_ROWS passes (47/47).

Assisted-by: Claude Opus 4.8

* ggml-openvino: Add GGML_BACKEND_DL_IMPL invocation for OpenVINO backend (#25795)

This adds the missing `GGML_BACKEND_DL_IMPL()` macro invocation, that other backends have.

Fixes #25586 for me

* vulkan: Refactor vk_queue to use per-instance mutexes and unique handles (#23570)

* Refactor vk_queue to use per-instance mutexes and unique handles

* integrates VK_KHR_internally_synchronized_queues, abstracting the queue submission into a polymorphic interface that completely bypasses host-side mutex locking when driver-side synchronization is supported

* fix compilation error

* fix duplicate pNext chain for VkPhysicalDeviceInternallySynchronizedQueuesFeaturesKHR

* add fallback defines for VK_KHR_internally_synchronized_queues

* add null checks for queues in vk_device_struct destructor

* use unique_ptr for outer queues to enforce exclusive ownership and optimize lifetime

* use static constexpr for eInternallySynchronizedKHR

* add lock guard to ggml_vk_create_aliased_queue for thread safety

* initialize sync_query_features.internallySynchronizedQueues to VK_FALSE

* reuse sync_query_features for internallySynchronizedQueues and simplify chaining

* refactor internallySynchronizedQueues detection

* fix internallySynchronizedQueues query guard

* use eInternallySynchronizedKHR constant

* fix self-referential alias for eInternallySynchronizedKHR

* use macro for eInternallySynchronizedKHR fallback

* fix internallySynchronizedQueues query timing in ggml-vulkan.cpp to prevent device creation mismatch

* reset sync_query_features.pNext before reusing in device creation chain, also removed the redundant second probe call

* refactor internally synchronized queues detection to use chained feature query and avoid redundant API calls

* Update ggml/src/ggml-vulkan/ggml-vulkan.cpp

Co-authored-by: Jeff Bolz <[email protected]>

* Update ggml/src/ggml-vulkan/ggml-vulkan.cpp

Co-authored-by: Jeff Bolz <[email protected]>

* Update ggml/src/ggml-vulkan/ggml-vulkan.cpp

Co-authored-by: Jeff Bolz <[email protected]>

* Update ggml/src/ggml-vulkan/ggml-vulkan.cpp

Co-authored-by: Jeff Bolz <[email protected]>

* Update ggml/src/ggml-vulkan/ggml-vulkan.cpp

Co-authored-by: Jeff Bolz <[email protected]>

* Update ggml/src/ggml-vulkan/ggml-vulkan.cpp

Co-authored-by: Jeff Bolz <[email protected]>

* rename sync_enable_features to internally_synchronized_queues_features

* queue_flags is still computed before has_internally_synchronized_queues is set

* fix trailing whitespace

* replace eInternallySynchronizedKHR macro with static constexpr

* preserve source queue semantics in single-queue aliased transfer queue

* vulkan: fix cmd_pool access via pointer for compute_queue unique_ptr

* vulkan: lock queue during debug label emission when not internally synchronized

---------

Co-authored-by: Jeff Bolz <[email protected]>

* server : properly handle null llama_context (#25868)

Co-authored-by: Stanisław Szymczyk <[email protected]>

* server: return 400 instead of 500 on validation error with X-Conversation-Id (#25760)

* server: return 400 instead of 500 on validation error with X-Conversation-Id

set_req() attaches the spipe as soon as the header is present, before the request
body is parsed. When params validation throws, set_next() never runs and next_orig
stays empty, so on_complete() called it and crashed with std::bad_function_call,
turning the prepared 400 JSON into a generic 500.

on_complete() now treats an empty next_orig as "streaming never started" and evicts
the session installed by set_req(), so a failed request leaves nothing behind for
discovery or replay. This also covers valid requests that carry the header but do
not stream, which previously left an empty finalized session in the map until the
GC TTL.

* ui: do not send the backend_sampling placeholder

On a fresh profile the syncable settings hold the empty string placeholder meaning
"let the server decide". Every neighbor field goes through the hasValue() guard
that filters it, except backend_sampling, which sent the placeholder verbatim and
made every default settings completion fail validation.

Guard the field with hasValue() like its neighbors. hasValue(false) is true, so an
explicit false still reaches the server and the intent of #18781 (send both true
and false) is preserved. Only the placeholder is filtered.

* common: resolve draft repo to its requested sidecar (#25955)

With -hfd pointing to a repo shipping speculative sidecars, the draft
resolved to the main model of that repo, since find_best_model()
excludes sidecar files, and the explicit draft plan suppressed the
sidecar discovery on the -hf repo.

The draft plan already discovers its sidecars, they were just never
consumed. Wire them as the draft, following the fallback pattern of
the main plan, so this now works as expected:

llama-server -hf repo -hfd repo --spec-type draft-dflash

* kleidiai : warn once when a weight type has no KleidiAI kernel (#25701)

* cuda: add sqrt_softplus in topk-moe for dsv4 (#25896)

* hexagon: check tensor type when reusing descriptors (#25968)

* mtmd : use align_corners for qwen3vl vision position embedding interpolation (#25781)

The Qwen3-VL learned position embedding is interpolated to the runtime patch
grid with the default bilinear+antialias (align_corners=False) sampling, while
the transformers reference uses align_corners=True (torch.linspace(0, side-1, T)).
The mismatch scales grounding coordinates about the image center, growing with
image size and per-axis for non-square images (see #16880).

* convert: fix handle HunyuanVL XD-RoPE config (#25514)

Signed-off-by: wendadawen <[email protected]>

* Add support for Laguna XS.2 & M.1 (#25165)

* llama-arch: fix DeepSeek4 APE tensor op (#25945)

* cuda: GET_ROWS quants (#25962)

* cuda: add k-quant support to GET_ROWS

Device-side embedding lookups require GET_ROWS to handle the k-quants
used by common GGUF recipes (Q4_K_M stores token_embd as q6_K). Without
it the backend rejects the op and the scheduler falls back to the host,
copying the full embedding matrix back on every token in single-device
graphs.

Factor the super-block dequantizers out of the dequantize_block kernels
in convert.cu into shared device functions in dequantize.cuh and reuse
them from a new k_get_rows_kq kernel : one thread block dequantizes one
(dst row, super-block) pair with the existing thread layouts, 32 threads
for q4_K and 64 for the other k-quants.

Covers q2_K to q6_K in get_rows_cuda and supports_op. i-quants are left
as a TODO.

* cuda: add i-quant support to GET_ROWS

Extends the shared super-block dequantizers to the nine i-quants and
reuses them from k_get_rows_kq with the 32-thread layout of the matching
convert.cu kernels. supports_op gates the k-quant and i-quant path on
ne0 being a multiple of QK_K, which iq4_nl does not guarantee on its
own (QK4_NL sub-blocks). mxfp4 is left as a TODO.

* cuda: add mxfp4 support to GET_ROWS

Moves the mxfp4 dequantizer into the shared super-block helpers and
reuses it from k_get_rows_kq with the 32-thread layout of the matching
convert.cu kernel. mxfp4 joins the ne0 % QK_K gate in supports_op since
its 32-value sub-blocks do not guarantee QK_K-aligned rows on their own.
This closes GET_ROWS type coverage on CUDA: every quantized GGML type
now takes the direct device path.

* cuda: gate the GET_ROWS row size only for 32-value sub-block types

Address review from @pwilkin: the i-quant commit replaced the return
shared by the whole supported type cascade, so f16/f32/bf16/i32 and the
legacy quants also inherited the ne0 % QK_K == 0 gate and any row size
that is not a multiple of 256 fell back to the scheduler. Split the
cascade: unconditional support is restored everywhere, the gate stays
only on iq4_nl and mxfp4 whose 32-value sub-blocks do not guarantee the
QK_K super-blocks the kernel iterates on.

* webgpu : add CONV_2D_DW (depthwise conv2d) kernel (#25847)

* webgpu : add CONV_2D_DW (depthwise conv2d) kernel

Implement GGML_OP_CONV_2D_DW for the WebGPU backend,
ported from the Vulkan backend's conv2d_dw.comp.

Assisted-by: Claude Opus-4.8

* Remove unnecessary comments in webgpu support

* update supported ops tables, triggered by adding webgpu CONV_2D_DW

* ci : fix SYCL package shared library lookup (#25987)

* ggml: enable PowerPC backend variants on AIX (#25983)

* ggml: enable PowerPC backend variants on AIX

Allow the PowerPC CPU backend variants to be built on AIX by extending the platform check in the CMake configuration. This reuses the existing PowerPC backend implementations without changing their behavior.

Also fix a missing semicolon in the PowerPC Q0 matmul implementation.

* Fix missing semicolon in sgemm.cpp

* Fix DeepSeek4 crafted template (#25414)

* chat: fix DS4 template to explicitly follow reference behavior

* Support DeepSeekv4 flag (`drop_reasoning`).

* fix: hook DS3.2 parser for DS4 as well

* fix: add tool result reordering

* fix: post-merge

* common: infer the speculative type from the draft repo sidecars (#25989)

With -hfd pointing to a repo that ships mtp-/dflash-/eagle3- sidecars
and no --spec-type given, the draft resolved to a full model while the
sidecar was the intended draft.

When the speculative types are still at their default, discover the
sidecars of the draft repo, pick the first available following the
existing mtp > dflash > eagle3 priority, and set the corresponding
type, so this now works without any extra flag:

llama-server -hf repo:Q3_K_M -hfd repo:Q8_0

An explicit --spec-type disables the inference, and a draft repo
without sidecars keeps resolving to a full model as before.

* minor: fix reasoning preserve var for DS4 [no ci] (#25999)

* feat(ui): add symbolic math support to JS sandbox via nerdamer (#25948)

* feat(ui): add symbolic math support to JS sandbox via nerdamer

Preload nerdamer (with decimal.js) in the sandboxed worker,
exposing the `nerdamer` global for symbolic computation:
simplify, expand, factor, diff, integrate, solve, laplace,
ilt, limit, partfrac, gcd/lcm, roots, coefficients, and more.

Mirrors the math.js integration pattern from the
feature/sandbox-symbolic-math branch, but uses nerdamer
for a lighter, more focused symbolic math engine.

* Update sandbox-harness.ts

* docs(ui): update sandbox tool description with detailed nerdamer usage guide

* Clarify nerdamer usage in sandbox tool description

Updated the description of the sandbox tool to clarify usage of nerdamer.

* ui: build nerdamer sandbox prelude from vendored source

Replace the vendored all.min.js with the readable nerdamer-prime
source and its two bundled deps (big-integer, decimal.js), licenses
included. A vite plugin bundles and minifies them at build time with
the upstream esbuild flags, exposed as virtual:nerdamer and imported
lazily on first sandbox use. The vendors package.json pins commonjs
so the project level type: module does not break esbuild format
detection. The harness gains a CSP removing network egress from the
worker, and browser tests cover the prelude, exact arithmetic, the
fetch block and the timeout.

Upstream snapshot: together-science/nerdamer-prime@1936145

* feat(ui): make symbolic math (nerdamer) a user-toggleable setting

- Add SYMBOLIC_MATH_ENABLED setting key and registry entry (checkbox, default false)
- Convert SANDBOX_TOOL_DEFINITION to buildSandboxToolDefinition(includeSymbolicMath)
  so the tool description includes/excludes nerdamer API docs dynamically
- Cache sandbox harness per variant ('nerdamer' / 'plain') for instant toggle
- Deprecate SANDBOX_TOOL_DEFINITION constant alias for backward compatibility
- Update tools store to pass symbolic math config into tool definition

* docs(ui): tell LLM to list nerdamer functions first, do not guess

* test(ui): enable symbolic math in sandbox tests via settingsStore config

* style(ui): fix formatting for tools.svelte.ts

---------

Co-authored-by: Pascal <[email protected]>

* mtmd: use RAII for setting and resetting non-causal attention (#25723)

* mtmd: use RAII for setting and resetting non-causal attention

* mtmd: drop dependency on <optional>

* mtmd: shorten class and variable names

* hexagon: activation ops update (#25974)

* hex-geglu: optimized all-in-one geglu microkernel

* hex-geglu: enable non-contiguous src and strided DMA

* hex-act: enable non-contiguous srs and strided DMA for rest of ACT ops

* hex-act: generalize GLU per-thread functions via DEFINE_GLU_PER_THREAD macro

* hexagon: move UNARY_SILU and UNARY_GELU to unary-ops

* hex-act: replace the generic ops_context scratchpad usage with a local htp_vtcm_layout computation per act op.

---------

Co-authored-by: Max Krasnyansky <[email protected]>

* CUDA: Improve NVFP4 W4A4 activation quantization (#25730)

* Squash history before conflict-resolution during rebase on master

WIP commit

Add 32-byte loads, restore per-block amax

Use nvfp4x4 intrinsic when available

Fuse per-channel amax and quantization kernels

Do pointer arithmetic only once on x

Remove unnecessary ternary in the load

We assert on host side that ne00 is 64-aligned

Add back scale-search, but optimize it with intrinsics

Code cleanup

Make scale in MMQ-epilogue NVFP4-specific/restrictive for now

Remove unneeded include, add comment

Fix trailing whitespace

Guard __builtin_align__(32) struct to NVIDIA

Seems like HIP doesn't have this available, see https://github.com/ggml-org/llama.cpp/actions/runs/29438651734/job/87431623001

* compiler massaging to avoid unnecessary LDCs

* kvalues_mxfp4 -> kvalues_nvfp4 in quantize_mmq_nvfp4

* Always pass in src1_scale.ptr

* Extract ggml_cuda_is_aligned helper

* ui: Add a "Default" option for the reasoning selector (#25846)

* ui: add Default reasoning option that defers to the server

The webui always injected enable_thinking, overriding the chat template
default and the --reasoning flag, breaking models that reason
unconditionally (e.g. Gemma 4 E4B) on a fresh client.

Default sends nothing so the server decides, Off and effort levels
force the value as before. All choices are remembered.

Also remove the boolean thinking API from the conversations store and
drop ChatFormReasoningEffortSubmenu.svelte (dead code).

* ui: close the whole menu tree on reasoning level selection

The reasoning levels were raw buttons inside the SubContent, so
selecting one only closed the submenu via manual state while the root
dropdown stayed open. DropdownMenu.Item closes the full tree on select
like the sibling entries and brings native keyboard navigation.

* ui: prevent the add menu tooltip from flashing when the dropdown closes

* contrib: allow all AI-generated code in general (#26012)

* conversion: fix non-MoE NomicBert GGUF conversion error (#25996)

* metal : add f16 type support to leaky relu (#25981)

* contrib: fix leftovers from the AI usage policy update (#26030)

* args: refactor mlock/mmap/directio into load-mode (#20834)

* args: overhaul mmap/mlock/dio into single arg

Signed-off-by: Aaron Teo <[email protected]>

* docs: update docs with llama-gen-docs

Signed-off-by: Aaron Teo <[email protected]>

* chore: satisfy code quality

Signed-off-by: Aaron Teo <[email protected]>

* args: make the `+` sign an actual modifier now

Signed-off-by: Aaron Teo <[email protected]>

* chore: general code clean up + comments

Signed-off-by: Aaron Teo <[email protected]>

* arg: fix deprecated flags support

Signed-off-by: Aaron Teo <[email protected]>

* arg: quick sanity check

Signed-off-by: Aaron Teo <[email protected]>

* bench: sync llama-bench argument parsing

Signed-off-by: Aaron Teo <[email protected]>

* fix: bugfix variable behaviour + llama-bench lm column size

Signed-off-by: Aaron Teo <[email protected]>

* arg: inverse commands should do the opposite instead of doing nothing

Signed-off-by: Aaron Teo <[email protected]>

* bench: fix incorrect dash

Signed-off-by: Aaron Teo <[email protected]>

* bench: fix missing modifiers for deprecated flags

Signed-off-by: Aaron Teo <[email protected]>

* llama: switch back to thread_local

Signed-off-by: Aaron Teo <[email protected]>

* arg: switch back to single enum

Signed-off-by: Aaron Teo <[email protected]>

* docs: update arg docs

Signed-off-by: Aaron Teo <[email protected]>

* chore: fix missing `mlock` from llama_load_mode_from_str + cleanup llama-bench

Signed-off-by: Aaron Teo <[email protected]>

* llama: fix mlock not activating

Signed-off-by: Aaron Teo <[email protected]>

* arg: add deprecation warning when old and new flags are combined

Signed-off-by: Aaron Teo <[email protected]>

* arg: cont add comment for todo in the future

Signed-off-by: Aaron Teo <[email protected]>

* docs: sync with upstream

Signed-off-by: Aaron Teo <[email protected]>

* docs: re-sync with upstream again

Signed-off-by: Aaron Teo <[email protected]>

---------

Signed-off-by: Aaron Teo <[email protected]>

* CUDA: fix external compilation of q1_0 MMQ (#25778)

* hexagon: fix Windows crash when op_poll is enabled (#26029)

* hexagon: further improved pipeline of the core bits (L2, DMA, MM, FA) (#26049)

* hex-l2: use dirty ranges for flushing

* hex-l2: simplify range based flush logic

* hex-l2: optimize dirty range scans

* hex-hvx: support for reduce_max_i32

* hex-mm: optimize fused MUL_MAT+ADD to use vtcm for bias when it fits

* hex-mmid: optimize mmid row-mapping generation

* hex-mmid: optimize mmid row-mapping generation

* hex-mmid: optimize mmid row-mapping generation (round2)

* hmx-mm: optimize output proc by tiling (col-chunking)

* hex-fa: start the next q dmas a bit earlier

* hex-fa: prefetch Q even earlier

* hvx-fa: optimize softmax to keep things in hvx registers

* hex-fa: hoist const register init in softmax loop

* hmx-fa: kick off next-qkv DMAs before o-proc

* hmx-fa: hoist various checks out of the inner loop

* hmx-fa: adjust the cost model to better balance softmax work across hvx threads

* hmx-fa: overlap diag rescale build with last HMX task

* hmx-fa: optimize idx update in output proc

* hmx-fa: unroll the softmax loops for improved perf

* hmx-fa: overlap qk-dot with softmax, double-buffer p and s tiles

* hex-trace: double the default number of trace entries

* hex-trace: add trace events for opbatch and buffer mgmt

* hex-trace: overhaul tracing to simplify runtime event handling and support opbatch stats

* hex-trace: replace ascii timeline diagram with pipeline bubbles detector

* hex-trace: handle missing start/stop events

* hex-dma: always log stop/start trace events even for dummy dmas

* hex-scripts: fix flake warnings

* vendor: update subprocess.h (#26061)

* cohere2 moe template parser: enforce JSON schema for text responses if a response schema is provided (#26018)

* UI: Fix settings precedence, Factory < Admin (--ui-config-file) < Users (Settings panel) (#26002)

* skill: create `add-new-model` and `code-review` (#26042)

* skill: add new model

* add common pitfalls

* add code review skill

* nits

* add codeowners

* add security review section

* mention about skills in agents.md

* add design review

* exclude ggml-gh-bot

* Apply suggestions from code review

Co-authored-by: Piotr Wilkin (ilintar) <[email protected]>
Co-authored-by: Xuan-Son Nguyen <[email protected]>

* conversion-time weight modification

* nits

---------

Co-authored-by: Piotr Wilkin (ilintar) <[email protected]>

* opencl: do not treat NULL-mask flash attention as causal (#25771)

* opencl: cache compiled cl_program binaries on disk (#26050)

* HIP: remove rocWMMA FlashAttention (#26046)

* llama: various bug fixes (#26051)

* server: support "reasoning_effort": "none" in OAI API (#26045)

* support "reasoning_effort": "none" in OAI API

* handle reasoning.effort: "none" in OAI responses API

* clarify non-"none" values of reasoning_effort have no effect

* use json_value instead of body.at

* ui: fix MCP server display name conflicts in tools lists (#26011)

* ui: fix MCP server display name conflicts in tools lists

Tool groups were keyed by display label so two servers reporting
the same name broke the keyed each blocks and only one was visible.
Key rendering, expand state and toggles by the stable server id
instead, and suffix duplicate labels with a counter in config order.

* ui: customizable MCP server display name with autofill

Add a display name field to the MCP server form, add and edit alike.
The custom name takes precedence over the server-reported one, so two
servers reporting the same name can be told apart; clearing the field
returns to the automatic label. In the add dialog a debounced preview
handshake prefills the field with the server-reported name: a manual
edit freezes the autofill, stale responses are discarded, failures
stay silent, and an unedited prefill is not persisted so the label
keeps following the server.

* ui: fix recursive fetch passthrough in the client test setup

The original fetch was captured inside beforeEach, where it is the
previous test's spy since vi.spyOn returns the existing one, so the
default passthrough recursed on itself for any URL outside the
mocked set. Capture the real fetch once at module load.

* model: add GLM 5.2 Indexer support (#25407)

* Start building graph - reuse deepseek32

* Enable kv cache and rotation for glm_dsa architecture

Just follow Deepseek 3.2 for now.

* Reuse prev_top_k for "shared" indexer layers

* GLM 5.2 uses LLAMA_ROPE_TYPE_NORM for the indexer.

This is transformers' `apply_rotary_pos_emb_interleave`

* Default indexer types to GLM pattern

Previous converted GGUFs like https://huggingface.co/unsloth/GLM-5.2-GGUF write indexer weights to _all_ layers, even if they are only required for "full" types. This PR relies on a new key "%s.attention.indexer.types"; if absent, it will use the default GLM 5.2 schedule as defined in https://huggingface.co/zai-org/GLM-5.2/blob/main/config.json#L26.

Note that conversion is not saving this key yet.

* Save indexer types to gguf, restore on load

* Use ggml_lightning_indexer when cparams.fused_lid

Co-authored-by: fairydreaming <[email protected]>

* GLM 5 and 5.1 use full indexers

Co-authored-by: fairydreaming <[email protected]>

* Fix indentation

* Ensure array is zero-filled

* Prefer explicit std::fill

* Assert prev_top_k exists for shared indexer

---------

Co-authored-by: fairydreaming <[email protected]>

* ui: remove render effects (#26083)

* ui: remove viewport fade in and smooth autoscroll bottom snap

fadeInView mounted every message and markdown block at opacity 0 and
relied on an IntersectionObserver to reveal it. When the observer never
fires (blocks mounted offscreen during long agentic loops) the content
stays invisible forever while still present in the DOM. Remove the
action, its orphaned isElementInViewport util and all call sites:
blocks now render visible immediately.

AutoScrollController.scrollToBottom defaulted to behavior smooth and is
invoked every 100 ms while streaming. Each tick restarts an easing
animation toward a moving scrollHeight, producing a random elastic bump
of a few pixels when the user reaches the bottom and autoscroll
reengages. Default to instant scrolling; the user facing scroll down
button keeps its smooth behavior.

* ui: skip rendering of offscreen chat messages via content-visibility

Apply content-visibility auto with contain-intrinsic-size to chat
messages so the browser skips layout and paint for messages outside
the viewport. The DOM stays complete: component state, find-in-page,
text selection, and the mutation based autoscroll are unaffected, and
browsers without support simply ignore the properties.

* ui: remove conversation switch fade

Switching conversations faded the message list out and in over 500 ms
plus a 300 ms route delay, deferring the message refresh behind two
requestAnimationFrame calls. Remove the fade, its navigation hooks and
dead state, and refresh messages directly so switching is only bound
by actual render time.

* ui: describe present behavior in comments and drop unused parameter

* ui: anchor the context gauge popup to the form with plain CSS

The stats card was portaled to body and repositioned in script on
every ancestor scroll event, trailing the page by one frame while
streaming. Render it as an absolutely positioned sibling of the input
box inside the already relative form, so nothing runs during scroll.

The card sits just above the dial, centered on it and overlapping the
textarea, from a single measurement of the dial center and top taken
when it opens; the dial and the card share the same positioning frame,
so the values stay exact while the card is open. Mouse pointers open
on hover with a grace delay to reach the card, touch pointers toggle
on tap, any press outside the card and the dial closes it, and Enter
and Space toggle from the keyboard. The card lives outside the input
box because its overflow-hidden and backdrop-filter would clip any
positioned descendant.

* ui: extract context gauge popup constants and relocate its state store

Move the placement values and the close grace delay to
lib/constants/context-gauge-popup.ts, matching the auto-scroll
constants layout, and move the popup state module from the component
folder to lib/stores where runes modules live in this codebase.

* ui: declare the context gauge popup card ref as $state

* ui: reduce per-token render cost when streaming  (#26053)

* performance harness - the empirical root

Assisted-by: Claude Opus 4.8

* 210.36ms -> 2.67ms per streamed token

Assisted-by: Claude Opus 4.8

* 11.58ms -> 0.62ms per streamed token

Assisted-by: Claude Opus 4.8

* 22.02ms -> 3.33ms per streamed token

Assisted-by: Claude Opus 4.8

* 3.07ms -> 1.36ms per streamed token at 40 messages

Assisted-by: Claude Opus 4.8

---------

Co-authored-by: Zach Winter <[email protected]>

* tests: synchronize save-load-state generation (#26056)

* common : add support for multiple end sequences in the reasoning budget sampler (#25544)

* common : extract trie/ac to a separate file

* common : support multiple token sequences in the reasoning budget sampler

* common/trie : return matched word index

* common/trie : rename "word" to "pattern"

* common/reasoning-budget : expose matched end sequence

* common/sampling : replay end sequence when reasoning budget is done

* cont : update to use multiple end sequences

* cont : clean up

* Update ggml/src/gguf.cpp : Defined virtual keyword for destructor of gguf_writer_base (#25867)

Without a virtual destructor, deleting a derived object through a
base-class pointer only invokes the base destructor, skipping the
derived one.

* vendor : update cpp-httplib to 0.51.0 (#26067)

Signed-off-by: Adrien Gallouët <[email protected]>

* server : add missing task parameters(adaptive_target, adaptive_decay) in generation_settings (#25830)

These two parameters were overlooked when task parameters were being JSONized
within `generation_settings` and have been added. A regression test has been
added to prevent the problem from recurring and it passes.

Fixes #25803

* server: add format arg to datetime tool (#26117)

* common : skip empty implicit default preset (#25643)

The INI parser creates an implicit default section for top-level metadata.
After reserved keys such as `version` are skipped, that section can have no
model options but was still added and exposed in router mode.

Skip only the empty implicit default while preserving real default presets,
named presets, and the global `[*]` settings.

Signed-off-by: JS van Dijk <[email protected]>
Co-authored-by: JS van Dijk <[email protected]>

* hexagon: partial im2col support (#26007)

* hexagon: add IM2COL op

Add Hexagon IM2COL support targeting only patch-embedding convolutions.

* hexagon: im2col refactor and cleanup

* hex-im2col: instrument and update im2col.

* hex-im2col: add local htp_vtcm_layout computation.

* server: support MCP stdio (#26062)

* move server_pipe to common

* init impl

* vendor: update subprocess.h

* add server_mcp_stdio

* stderr drain

* server_mcp_transport

* server_mcp_stdio is now framing-only, no json

* internal/mcp-stdio: integration + tests + fixes (#26075)

* server-mcp: harden transport and wire up the tool integration

Builds on the transport/manager architecture (server_mcp_transport + server_pipe)
with the hardening and integration the draft did not yet have.

Hardening:
* Reader and stderr pumps are polled (running-aware) instead of blocking on a read
  that only ends at EOF. subprocess_terminate() SIGKILLs only the direct child, so a
  grandchild the MCP server spawned that inherited the pipe would otherwise keep the
  write end open and hang teardown (both warmup shutdown at startup and process
  shutdown). The writer is likewise non-blocking + polled.
* Windows: resolve the command through PATHEXT so "npx" (npm ships npx.cmd, never
  npx.exe) spawns, matching POSIX's PATH search; and enumerate the parent environment
  as UTF-8 (GetEnvironmentStringsW) instead of the active code page.
* server_pipe gains an opt-in max_size (default unbounded, so the router's streaming
  use is unchanged); the MCP reply queue uses it so a server that streams unsolicited
  notifications between requests cannot grow it without bound.

Integration:
* --mcp-servers-config / --mcp-servers-json flags; enabling MCP restricts default CORS
  to localhost, same as --tools.
* MCP tools are exposed through /tools (and chat-completions) as <server>_<tool>,
  skipping names that collide with a built-in or another MCP tool.
* Manager lifecycle wired into llama_server(): warmup at start, shutdown() from the
  signal handler before the HTTP server drains, blocking teardown in clean_up().
* SIGPIPE ignored so a child dying mid-write yields EPIPE rather than killing us.

Assisted-By: Claude Opus 4.8 <[email protected]>

* server-mcp: add MCP test suite with grandchild deadlock regression test

21 tests over the /tools endpoint: tool discovery/invocation, timeouts, crash
recovery and respawn cooldown, warmup partial failure, malformed and batched
notification+response output, tool-definition shape, and prompt shutdown during a
slow call.

The last test spawns an MCP server that leaves a grandchild inheriting its
stdout/stderr and asserts the server both starts and stops promptly. Verified it
fails (5s SIGKILL fallback on a deadlocked reader-join) when the pump is made to
ignore the running flag, and passes with the polled reader.

Assisted-By: Claude Opus 4.8 <[email protected]>

* clean up

* clean up 2

* even stricter life cycle

* nits

* nits 2

---------

Co-authored-by: Xuan Son Nguyen <[email protected]>

* fix some edge cases

* fix last_error data race

* fix response schema + docs

* server: fix MCP zombie leak and timeout-induced transport teardown

join_pumps() never reaped the child, leaking one zombie per spawn:
call subprocess_join() before subprocess_destroy().

A per-call timeout permanently closed from_server and got a healthy
transport evicted: add close_on_stop to server_pipe::read() and pass
false from send_rpc(), where should_stop is a per-request deadline
and a late reply is already skipped on id mismatch.

Also drop the unreachable disconnect cancellation in
server_mcp_tool::invoke(): support_stream is false, st is always null.

(cherry picked from commit e6de1ec043174fd0570b1e60d47f06c7c19d620d)

Assisted-by: Claude Opus 4.8

* server: make MCP test fixtures JSON-RPC 2.0 compliant

Add the missing notification guard to mcp_malformed_server.py and
mcp_burst_server.py (the latter treated id 0 as a notification and
replied to unknown ones; its notification table is now unused).

Return -32602 instead of -32601 for unknown tools: tools/call is a
valid method, the tool name is the invalid parameter.

Also fix the test module docstring: tools are named <server>_<tool>.

(cherry picked from commit 74a08e8c311dabf3b49d06cc6d754b0097ae7a38)

Assisted-by: Claude Opus 4.8

---------

Co-authored-by: Piotr Wilkin (ilintar) <[email protected]>
Co-authored-by: Pascal <[email protected]>

* common : use-after-free when loading LoRA adapter fails (#25611)

* ggml-webgpu: Fix WASM compilation with OpenMP (#25943)

* Fix emscripten compilation with openmp

* Separate wasm job to its own workflow

* Add flags necessary for newer emsdk

* Just disable openmp

* Update triggers

* ui: fix context gauge card regressions and land at the conversation end (#26099)

The context gauge card starts monitoring like the dial does, because
its own processing state instance only follows the live stream while
its monitoring flag is set. It also gets back the text-sm and ring
classes the removed hover card wrapper used to inject, which restores
its layout. Routing to a conversation now lands at the bottom
instantly and keeps the pin one frame at a time until the page height
settles, since content-visibility size realizations and syntax
highlight passes grow the page without DOM mutations.

* opencl: fix fused RMS norm mul view offset (#26085)

* model: Add MiniMax-M3 (MSA: MiniMax Sparse Attention) support (#24908)

* Add preliminary MiniMax-M3 support

Text-only port that re-uses existing components: MiniMax-M2 style GQA with
per-head QK-norm and partial rotary, DeepSeek-V3 style leading-dense and
routed/shared experts, and swigluoai activation. Sparse attention is not
yet supported (dense fallback); vision tower and MTP heads are dropped.

* MiniMax-M3 vision tower (mmproj + clip graph)

* Delete m3_vision_ref.py

* Update clip.cpp

* MSA

* Update constants.py

* Update minimax.py

* Cache creation. Working withotu flash attention

* Added flash attention for sparse layers

* Decomposed slow cpu OP into GPU + CPU ops. Massive speedup over long ctx

* Rewrote indexer op to be cuda native. Modified flash attention to match per group block picking

* Implement sparse attention calc out of stock ops.

* Fix a cache allocation and cont issue

* Fixed -fa auto crash, flagged debug spots

* Delete vocab.json

* Delete model.safetensors.index.json

* Delete generation_config.json

* Delete Minimax directory

* Handled multi stream case to fall back on Dense Attention

* Development scaffolding cleanup. No functional change to the decode or
4-way paths. Full debug harness remains at <8136a9c68ed7a5eb009aa67bba3fda8062f4648f> for reproducing the
selection-parity validation.

* Remove redundant comment from minimax-m3.cpp

* Changed 3 Gelu Ops for vision into Gelu_erf ops

* Assert that n_kv is multiple of 128

* Rename MSA index tensors to indexer convention

Note: All GGUFs generated before this change will need to be regenerated.

* Fix incorrect Assert

* Review driven changes (#3)

* Remove comment from conversion minimax.py

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Remove whitespaces from constants.py

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Tighten comment in minimax.py

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* inherit MiniMax-M3 from MiniMax-M2

* drop dead text_config fallbacks

* Add indexer writer methods

* Reuse LLM_FFN_SWIGLU_OAI_MOE

* Remove duplicate  indexer setters, add only block_size/local_blocks, follow value naming convention

* Fix conversion error /gguf_writer.py

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Update gguf-py/gguf/gguf_writer.py

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Update gguf-py/gguf/tensor_mapping.py

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Update conversion/minimax.py

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Update conversion/minimax.py

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Remove whitespace in src/llama-kv-cache.cpp

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Remove Whitespace in Update src/llama-model.h

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Remove whitespace in src/llama-hparams.h

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* remove multimodal code upon maintainer request. Will be made as a separate PR

* Whitespace clean in tensor_mapping.py

* Log cache size on launch, block ctx shift, support prompt caching

Log indexer cache size on launch

Disallow ctx shift

Support prompt caching

* Update minimax-m3.cpp

* Optimize implementation, add multi stream support. 

Fully rewrote minimax-m3.cpp for speed and buffer size gains:

Unified the 4-way + decode, 1 FA call per layer instead of 4, with the groups mapped onto ne[3]

Custom CPU op now emits block-level mask, expanded on GPU, which causes CPU to GPU transfer to shrinks at prefill

Decode: ~25 nodes/layer vs ~50, no per-group concats/conts

Unified selection semantics, so both regimes rank bs + local bias (position-anchored local force), which means prefill/decode can no longer disagree on selection

can_reuse on the MSA bias input. Graph reuse at decode restored (was rebuilding the full graph every token)

In-place mask adds, shrinking compute buffer ~6.8 to ~4.2 GiB at ub2048/62k

Multi-stream: MSA now runs with -np N when kv_unified=false. Decode stays batched across streams (still 1 FA call), prefill loops per stream. dense fallback only for --kv-unified + multi-seq

Measured effect on expert offload bound setup: decode 6.2(4WAY)–7.15(MSA_decode) -> 7.7~7.8 t/s, flat from 5k to 60k+. prefill around 10% faster. buffer about 20% smaller, multi-user support.

* set default cache type to F32

* Fix potential DSA double indexer cache  allocation bug, only allocate in-cache k_idx for archs that opt in

* remove F16 downcasts in MSA attention, force F32 indexer score accum

* Add Minimax eos to llama vocab

* Guard edge case where idx cache can become stale after a tail trim

* Update llama-kv-cache.h

* Update llama-kv-cache.cpp

* Update llama-kv-cache.cpp

* Update llama-kv-cache.h

* Update llama-kv-cache.cpp

* Review driven changes

* style fix

* indexer hparams are required

* fix tests

* fix lint

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: Sigbjørn Skjæret <[email protected]>
Co-authored-by: Xuan Son Nguyen <[email protected]>

* mtmd: add GLM-5.2-Vision (#26126)

Co-authored-by: Eric Hartford <[email protected]>

* common: add `subproc.h` wrapper, disabled on android/ios (#26102)

* add common/subproc.h|cpp

* add compile flag LLAMA_SUBPROCESS

* disabled by default on android and ios

* test-jinja: use common subproc

* mtmd: disable video if subproc is not set

* disable subproc on wasm

* make is_created atomic

* migrate server-mcp

* ui: detect the conversation import format from file contents (#26121)

* ui: detect the conversation import format from file contents

iOS resolves every accept entry to a UTI and has none for ".jsonl", so the
picker greyed out exported conversations. Drop the accept filter and pick the
parser from the file contents: ZIP magic bytes, then a first "session" record
for JSONL, otherwise the legacy JSON format.

Also remove the unused importConversations() picker and an orphan doc comment,
and cover each format with unit tests.

* ui: report what a conversation import actually wrote

The import summary echoed the selection back, so re-importing conversations
already in the database claimed success while nothing was written and only a
console warning said otherwise.

Return the imported and skipped conversations from the database layer, list the
written ones in the summary, and count the rest in a toast.

* ui: name the literals of the JSONL conversation format

Introduce SessionRecordType and SESSION_HARNESS, and reuse the existing
NEWLINE constant, so the record format lives in one place.

This also covers the writer side, which predates the import path under
review and carried the same literals: an enum stated by the reader alone
lets the two sides drift.

Values are unchanged, so an export stays byte identical.

* Keep Minimax's indexer tensors at F32 for speed and accuracy (#26144)

* Keep Minimax's indexer tensors at F32 for speed and accuracy

* name -> new_name

* ui: fix system message edit box not expanding to fit content (#26006)

The in-conversation system-message edit textarea had a fixed min-height and no auto-resize, so long messages were crammed to 2 lines. Reused existing autoResizeTextarea helper on input and when the editor opens, and added max-height to cap growth.

* mtmd: fix android build (#26150)

* mtmd: Add Vision Support for Minimax-M3 (#25113)

* Add preliminary MiniMax-M3 support

Text-only port that re-uses existing components: MiniMax-M2 style GQA with
per-head QK-norm and partial rotary, DeepSeek-V3 style leading-dense and
routed/shared experts, and swigluoai activation. Sparse attention is not
yet supported (dense fallback); vision tower and MTP heads are dropped.

* MiniMax-M3 vision tower (mmproj + clip graph)

* Delete m3_vision_ref.py

* Update clip.cpp

* MSA

* Update constants.py

* Update minimax.py

* Cache creation. Working withotu flash attention

* Added flash attention for sparse layers

* Decomposed slow cpu OP into GPU + CPU ops. Massive speedup over long ctx

* Rewrote indexer op to be cuda native. Modified flash attention to match per group block picking

* Implement sparse attention calc out of stock ops.

* Fix a cache allocation and cont issue

* Fixed -fa auto crash, flagged debug spots

* Delete vocab.json

* Delete model.safetensors.index.json

* Delete generation_config.json

* Delete Minimax directory

* Handled multi stream case to fall back on Dense Attention

* Development scaffolding cleanup. No functional change to the decode or
4-way paths. Full debug harness remains at <8136a9c68ed7a5eb009aa67bba3fda8062f4648f> for reproducing the
selection-parity validation.

* Remove redundant comment from minimax-m3.cpp

* Changed 3 Gelu Ops for vision into Gelu_erf ops

* Assert that n_kv is multiple of 128

* Rename MSA index tensors to indexer convention

Note: All GGUFs generated before this change will need to be regenerated.

* Fix incorrect Assert

* Review driven changes (#3)

* Remove comment from conversion minimax.py

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Remove whitespaces from constants.py

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Tighten comment in minimax.py

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* inherit MiniMax-M3 from MiniMax-M2

* drop dead text_config fallbacks

* Add indexer writer methods

* Reuse LLM_FFN_SWIGLU_OAI_MOE

* Remove duplicate  indexer setters, add only block_size/local_blocks, follow value naming convention

* Fix conversion error /gguf_writer.py

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Update gguf-py/gguf/gguf_writer.py

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Update gguf-py/gguf/tensor_mapping.py

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Update conversion/minimax.py

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Update conversion/minimax.py

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Remove whitespace in src/llama-kv-cache.cpp

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Remove Whitespace in Update src/llama-model.h

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Remove whitespace in src/llama-hparams.h

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Update minimax_m3.cpp

Rewrite code comment based on feedback and to better reflect the actual architecture, and reuse existing build_vit

* Rename minimax_m3.cpp to minimax-m3.cpp

* Update CMakeLists.txt

* Remove debug code from clip.cpp

* Update clip.cpp

* Update comments in tools/mtmd/models/minimax-m3.cpp

* Permute Q/K at conversion, drop precomputed sin/cos

* Log cache size on launch, block ctx shift, support prompt caching

Log indexer cache size on launch

Disallow ctx shift

Support prompt caching

* Update minimax-m3.cpp

* Optimize implementation, add multi stream support. 

Fully rewrote minimax-m3.cpp for speed and buffer size gains:

Unified the 4-way + decode, 1 FA call per layer instead of 4, with the groups mapped onto ne[3]

Custom CPU op now emits block-level mask, expanded on GPU, which causes CPU to GPU transfer to shrinks at prefill

Decode: ~25 nodes/layer vs ~50, no per-group concats/conts

Unified selection semantics, so both regimes rank bs + local bias (position-anchored local force), which means prefill/decode can no longer disagree on selection

can_reuse on the MSA bias input. Graph reuse at decode restored (was rebuilding the full graph every token)

In-place mask adds, shrinking compute buffer ~6.8 to ~4.2 GiB at ub2048/62k

Multi-stream: MSA now runs with -np N when kv_unified=false. Decode stays batched across streams (still 1 FA call), prefill loops per stream. dense fallback only for --kv-unified + multi-seq

Measured effect on expert offload bound setup: decode 6.2(4WAY)–7.15(MSA_decode) -> 7.7~7.8 t/s, flat from 5k to 60k+. prefill around 10% faster. buffer about 20% smaller, multi-user support.

* set default cache type to F32

* Fix potential DSA double indexer cache  allocation bug, only allocate in-cache k_idx for archs that opt in

* remove F16 downcasts in MSA attention, force F32 indexer score accum

* Add Minimax eos to llama vocab

* Guard edge case where idx cache can become stale after a tail trim

* Update llama-kv-cache.h

* Update llama-kv-cache.cpp

* Update llama-kv-cache.cpp

* Update llama-kv-cache.h

* Change resize Pad to none, resize alg to Bicubic Pillow

* Review driven changes

* Update llama-kv-cache.cpp

* rm unrotated pos_t

* fused rope w + pad

* rename merge --> merger for consistency

* add review skill for mtmd

* graph should use hparams n_merge

* fix lint

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: Sigbjørn Skjæret <[email protected]>
Co-authored-by: Xuan Son Nguyen <[email protected]>

* ui: Fix symbolic math tool JS sandbox prompt (#26131)

* Update sandbox.ts

* Update sandbox.ts

* Update sandbox.ts

* Update sandbox.ts

* Revise nerdamer description in sandbox constants

Updated NERDAMER_DESCRIPTION to clarify usage and warnings.

* server + ui: fix stream routes for model names containing a slash (#26137)

* server + ui: refactor resumable stream routes to query string conv_id

The conversation id can embed a model name containing slashes
(ggml-org/...) in router mode, which the decoded path splits before the
:conv_id param is captured, so stop and resume never matched the
session. Move the id to the conv_id query string on the public routes
and on the internal router -> child hop, where slashes survive
encoding. Handlers are unchanged since query and path params land in
the same map. Add a regression test with a slashed model name.

* server: move stream route docs to server-stream.h

Address review: ngxson wants the main server.cpp registration code kept
clean and simple, with route-level explanations living in the header.
Move the query string rationale and the lookup ownership note next to
the handler declarations in server-stream.h, and shorten the wiring
comment to a pointer.

* server: cancel a pending request when its stream is stopped during model load

The conversation was registered in the conv map only after the blocking
autoload wait, so a stop issued while the model loaded found nothing to
cancel and the request went on to generate an orphan once the load
ended. Register the conversation before the wait and give the entry a
ticket: a stop erases the entry, and the parked request checks its
ticket after the wait and aborts with 400 instead of starting. A newer
request on the same conversation replaces the entry, so only the
stopped request is cancelled. Add a regression test that stops during
the load window.

* server + ui: resume a stream after a page reload during model load

A pending request died with the client socket when the page was
reloaded while its model was loading, so no session ever existed and
the conversation had nothing to recover. A session request that waited
for a load now detaches from the client socket and reaches the child
regardless, the session buffer receives the generation, and the resume
route answers 503 while the owner is loading so the client retries
instead of dropping its state. The WebUI persists the pending stream at
send time, quietly polls on 503, and attaches once the session exists.
Add a regression test that drops the client during the load window.

* ui: show the model load progress again after a page refresh

The resume wait was invisible, so a conversation refreshed while its
model was loading showed nothing until the first byte. On a 503 from
the resume probe, mark the conversation as loading again so the
assistant row persisted at send time renders the processing info, and
target the model frozen in the persisted stream state for the
progress, since the row has no model yet and the dropdown may not be
restored.

* fix CI

* fix CI bis

* args: add `-lm mlock` where it mlocks but doesnt mmap (#26135)

* arg: add `-lm mlock` where it mlocks but doesnt mmap

Signed-off-by: Aaron Teo <[email protected]>

* docs: rm unwanted docs changes

Signed-off-by: Aaron Teo <[email protected]>

* docs: revert auto-formatting

Signed-off-by: Aaron Teo <[email protected]>

* bench: fix automated review point 3

Signed-off-by: Aaron Teo <[email protected]>

* arg: revert the meaning of --mlock to non-mmap'ed mlock

Signed-off-by: Aaron Teo <[email protected]>

* docs: update docs

Signed-off-by: Aaron Teo <[email protected]>

* docs: remove extra changes from `llama-gen-docs`

Signed-off-by: Aaron Teo <[email protected]>

---------

Signed-off-by: Aaron Teo <[email protected]>

* ggml-cpu: Enable BF16 tiled gemm optimization on PowerPC (#26068)

* docs: add exception about weight folding (#26168)

* docs: add exception about weight folding

* add example

* common: fix explicit -md precedence over draft sidecar resolution (#26165)

* common: fix explicit -md precedence over draft sidecar resolution

Follow-up of #25955, an explicit --model-draft file given with -hfd
was silently overridden by the sidecar resolution of the draft repo,
and its path was never resolved to a local file.

An explicit draft file selection now disables the sidecar resolution,
so the manual CLI configuration wins over the automatic one.

* common: apply the -hfd tag to the sidecar resolution

The sidecar selection was anchored on the primary of the draft plan,
so a tag without a matching full model aborted the whole plan, and
the sidecar quant silently followed the default model pick.

The tag now anchors the sidecar directly: exact tag match first, then
closest quant to the tag, and a requested sidecar resolves even when
no full model matches the tag. A wired draft sidecar also counts as
an explicit draft, so the main plan no longer downloads a second one.

* common: promote speculative load logs from trace to info

Show the loaded draft model and the MTP draft context at the default
verbosity, for consistency with the mmproj and primary logs.

Co-authored-by: Georgi Gerganov <[email protected]>

---------

Co-authored-by: Georgi Gerganov <[email protected]>

* tests : remove unnecessary sync in test-save-load-state (#26166)

* ggml : adjust logic for offloading ops to weight's backend (#25832)

* ggml : adjust logic for offloading ops to weight's backend

* llama : dsv4 graph fixes

* sycl(build): parallelize ocloc invocations (#25903)

* fit : count nextn (MTP) blocks in n_gpu_layers so front layers stay on GPU (#26177)

* model: Add support for Nanbeige4.2 (#25994)

* support nanbeige4.2 model

* fix

* fix flake8 Lint check

* fix loop bound check and drop redundant head_dim

---------

Co-authored-by: root <[email protected]>

* common : add common_print_available_devices() (#26170)

Signed-off-by: Adrien Gallouët <[email protected]>

* mtmd: support MiMo-V2.5 audio input (RVQ-based model) (#26190)

* gguf converter for mimo audio

* fix conv

* cpp impl

* nits

* nits 2

* Disable -ffast-math on HIP (#25495)

* contrib : add guideline about the "merge ready" label (#26178)

* contrib : add guideline about the "merge ready" label

* cont : add ref

[no ci]

* spec: add eagle3-v3 support for gpt-oss model (#25794)

* ggml-metal: FWHT kernel for metal backend (#25924)

* metal fwht wip

* shape guard and formatting

* formatting

* Formatting and typos

Co-authored-by: YiChen Lv <[email protected]>

* fix narrowing issue

Co-authored-by: YiChen Lv <[email protected]>

* cont : minor style

---------

Co-authored-by: YiChen Lv <[email protected]>
Co-authored-by: Georgi Gerganov <[email protected]>

* server : add extra trace log for prompt similarity (#26218)

* sycl: fix use-after-return of the SDPA scale in the oneDNN flash-attention path (#25880)

* sycl: fix use-after-return of the SDPA scale in the oneDNN flash-attention path

The scale was uploaded with an async memcpy sourced from a stack local. On the
in-order queue that copy is ordered behind the K/V staging kernels; once n_kv is
large enough (>= ~26k observed on Arc Pro B70) the staging outlives the host
stack frame and the copy reads recycled memory, feeding the SDPA a garbage scale.
Output then collapses to a single repeated token and the KV cache is poisoned
for the rest of the session.

Short contexts win the race by accident, and test-backend-ops caps
FLASH_ATTN_EXT at kv=1024, which is why CI never caught it. The previous
device_count > 1 wait_and_throw() gate (and reverting it, PR #25741) fixes the
symptom only by keeping the frame alive across the copy at the cost of a host
sync on every FA call.

Fix: cache one device scalar per (device, value) -- the scale is constant per
model -- and upload it synchronously once. The single-device fast path (no
per-call host sync) is then safe: every device-side hazard already serializes
on the in-order queue. The multi-GPU conservative wait is kept unchanged.

Also:
- GGML_SYCL_FA_ONEDNN_MAX_KV env (0 = unlimited): optional n_kv ceiling that
  routes very long sequences to the native FA kernel.
- test-backend-ops: FLASH_ATTN_EXT F16 cases up to kv=65536 (Qwen3.6-27B
  geometry hsk=hsv=256 GQA 6, and hsk=128 GQA 4), closing the kv=1024 blind
  spot. Note the race itself needs a live multi-op pipeline to reproduce;
  single-op runs pass even on broken builds.

Verified on Arc Pro B70 (bmg_g31), Qwen3.6-27B Q4_K, -c 131072: output
byte-identical at temp 0 to the native FA path through 32k-deep prefill, with
prefill depth-flat at 820-840 t/s (vs 340-350 native at 32k depth).

Assisted-by: Claude Fable 5

* sycl: handle GGML_SYCL_FA_ONEDNN_MAX_KV like the other runtime env vars and document it

Review feedback on #25880:
- read the variable once at backend init into g_ggml_sycl_fa_onednn_max_kv via
  ggml_sycl_get_env, and print it in the startup env listing (-lv 4 shows it)
- document GGML_SYCL_FA_ONEDNN and GGML_SYCL_FA_ONEDNN_MAX_KV in the SYCL.md
  runtime table

Also trim the added FLASH_ATTN_EXT cases to kv={4096,16384}: the 32768/65536
shapes exceed the legacy NMSE threshold on both the oneDNN and native kernels
(long-sequence fp16 accumulation drift, present before this PR) and would fail
CI for an unrelated reason.

Assisted-by: Claude Fable 5

* sycl: clarify GGML_SYCL_FA_ONEDNN_MAX_KV default is disabled

Assisted-by: Claude Fable 5

* sycl: state default behavior of GGML_SYCL_FA_ONEDNN_MAX_KV explicitly

Assisted-by: Claude Fable 5

* Update ggml/src/ggml-sycl/fattn-onednn.cpp

Co-authored-by: Neo Zhang <[email protected]>

* sycl: write the SDPA scale from a kernel instead of caching it

The per-(device, value) scale cache was a function-local static
unordered_map with no synchronization, so concurrent backend instances
could access and rehash it at the same time.

Write the scalar with a single_task instead. The value is captured into
the command, so no host memory has to outlive the call -- which is what
the use-after-return fix needed in the first place. That removes the
shared container, the leaked device allocation and the string key, and
it also closes the remaining async-memcpy-from-a-stack-local on the
first flash-attention call.

Ordering does not rely on timing: the queue is created with
sycl::property::queue::in_order and the dnnl stream wraps that same
queue, so the write completes before the SDPA reads the scalar. The
multi-GPU wait_and_throw() branch is unchanged.

Also drop the <cstdlib> include, which is unused.

Assisted-by: Claude Opus 5

---------

Co-authored-by: Neo Zhang <[email protected]>

* common/chat: add specialized minimax m3 parser (#26210)

* spec: add DSpark speculative decoding (#25173)

* spec: add DSpark speculative decoding

DSpark (DeepSpec, 2026) on top of the merged DFlash drafter. It reuses the
DFlash encoder/decoder graph, target feature extraction and KV-cache injection,
and the verify/accept path unchanged; the draft model is a new "dspark" arch
adding a low-rank Markov head (markov_w1/w2) and an optional (unused here)
confidence head. No new public APIs.

The proposal is the only change: the block is anchor-first (position 0 already
predicts the first draft) and the decoder graph applies a semi-autoregressive,
previous-token conditioned logit bias in-graph, chained per block position:

  logits'(i) = logits(i) + markov_w2 . markov_w1[prev(i)]
  prev(0)    = the block's anchor token, prev(i>0) = argmax(logits'(i-1))

vectorized across all blocks in the batch; the anchors are fed through a
dedicated graph input (token 0 of every block). Greedy stays lossless
(verify unchanged, same as DFlash).

- new arch "dspark" (llama_model_dspark : llama_model_dflash, reuses the graph,
  loads the markov/confidence tensors; shares the target's embed/lm_head).
- Qwen3DSparkModel converter.
- new spec type "draft-dspark" (common_speculative_impl_draft_dspark :
  common_speculative_impl_draft_dflash, overrides draft() only: submits whole
  anchor-first blocks and greedily reads back the biased logits).

* spec: read draft block size in the dflash impl

* docs: add DSpark section to speculative.md

* spec: keep dspark block size read in the dspark impl

* dspark : add TODOs for incomplete parts

- confidence head is loaded but not used yet
- confidence-scheduled prefix pruning is not implemented
- the in-graph Markov chain…
satindergrewal pushed a commit to satindergrewal/llama.cpp that referenced this pull request Aug 12, 2026
LogicDaemon added a commit to LogicDaemon/llama-cpp-turboquant that referenced this pull request Sep 6, 2026
commit bfe452a6d315b776c2e06f7f11c45bd6cd9766b4
Author: LogicDaemon <[email protected]>
Date:   Sat Sep 5 13:29:03 2026 +0400

    Squashed commit of the following:

    commit 10f8aff
    Author: thecodacus <[email protected]>
    Date:   Tue Aug 25 23:39:14 2026 +0530

        perf: lower default --cpu-tp-margin to 512 MiB

        Measured on a 12GB RTX 3060 with a dense 27B Q4_K_M: tightening the margin
        raises both decode and prefill, since every MiB reclaimed moves weights off
        the CPU leg. 1024 -> 640 -> 384 MiB gave 7.4 -> 7.8 -> 8.1 t/s decode and
        14.4 -> 15.2 -> 16.5 t/s prefill. 512 keeps headroom for larger contexts;
        raise it if the GPU runs out of memory.

    commit e406c8c
    Author: thecodacus <[email protected]>
    Date:   Tue Aug 25 22:08:09 2026 +0530

        feat: add --cpu-tp to use the CPU as a tensor-parallel device

        llama.cpp's tensor-parallel meta device already dispatches each member
        backend asynchronously before synchronising, but the CPU is excluded from
        the device list. Adding it lets the GPU and CPU compute row-slices of every
        weight matrix concurrently instead of running one after the other.

        The GPU share is sized from the measured free VRAM (minus --cpu-tp-margin)
        so VRAM is saturated, and the CPU takes only the remainder. The CPU is
        appended last so the GPU subgraph is already in flight when the CPU
        backend blocks on its own.

    commit d927e7d
    Author: Anirban Kar <[email protected]>
    Date:   Tue Aug 25 15:58:16 2026 +0530

        docs: add MoE expert cache usage and tuning guide to README (TheTom#8)

        * docs: add MoE expert cache usage and tuning guide to README

        * docs: document async CPU split overlap and VRAM headroom rule

    commit 0ac3d9b
    Author: Anirban Kar <[email protected]>
    Date:   Sun Aug 23 04:08:21 2026 +0530

        feat: overlap CPU cold-expert and GPU hot-expert computation in the MoE cache (TheTom#9)

        * feat: overlap CPU cold-expert chain with GPU hot chain (GGML_SCHED_ASYNC_CPU)

        The dual-path MoE cache ran its two chains serially: the scheduler
        blocks on CPU splits, and the cold chain's input copies drain the whole
        CUDA stream. Three changes make them concurrent, gated behind
        GGML_SCHED_ASYNC_CPU=1:

        - sched: CPU splits execute on a persistent worker thread; the main
          loop keeps launching later splits and joins lazily at the first split
          that is CPU or reads a CPU-resident input
        - graph: cold chain is built before the hot chain so the hot split
          follows it and carries no cross-backend inputs (launches while the
          worker computes)
        - graph: the merge add is pinned to CPU so it does not pull the hot
          chain into a split that waits on the cold result

        * feat: GGML_SCHED_ASYNC_CPU=2 diagnostic mode (worker without graph restructure)

        * fix: mark expert cache pack buffer as weights

        Without the weights usage flag the scheduler's assignment pass does not
        pin the pack tensors to their backend, so a CPU-assigned consumer (the
        pinned merge in async mode) propagates backward and pulls the hot
        matmuls onto the CPU, copying pack weights over PCIe every layer.

        * feat: make async CPU splits the default, expose --sched-async-cpu flag

        Replaces the GGML_SCHED_ASYNC_CPU env var: the overlap is now on by
        default and controlled through llama_context_params.sched_async_cpu.
        - ggml: ggml_backend_sched_set_async_cpu() setter, env read removed
        - llama: context param + cparams plumbing, graph gate reads cparams
        - common: --sched-async-cpu / --no-sched-async-cpu (server, cli)
        - llama-bench: sched_async_cpu test dimension (--sched-async-cpu 0,1
          benches both in one run, column shown as 'sac' when non-default)

        * fix: restrict CPU-pinned merge to decode-size batches

        For prefill batches the CPU merge and its per-layer activation copies
        cost more than the overlap hides (pp256 regressed 307 -> 257 t/s).
        Decode and MTP verify batches (n_tokens <= 8) keep the overlap.

    commit 8e5bc28
    Author: Anirban Kar <[email protected]>
    Date:   Sat Jul 25 03:54:47 2026 +0530

        feat: wire MoE expert cache into laguna graph (TheTom#6)

    commit ac743f8
    Author: Anirban Kar <[email protected]>
    Date:   Sat Jul 25 00:41:02 2026 +0530

        feat: MoE expert cache — keep hot routed experts resident in VRAM (TheTom#5)

        * feat: llama-moe-trace tool + expert-cache policy simulator

        Phase 0 of the MoE expert-cache work: capture routed expert ids
        (ffn_moe_topk) per layer per decode step via the scheduler eval
        callback — backend-agnostic, so CPU-offloaded expert layers are
        traced too. Companion simulate.py replays traces against cache
        policies (static top-S, LRU, LFU-decay, periodic re-election) and
        prints hit-rate vs VRAM-budget curves plus routing-skew stats to
        decide whether expert caching is worth building at all.

        * fix: moe-trace — common_init_from_params returns ptr with accessors

        * fix: moe-trace — include arg.h for common_params_parse

        * fix: moe-trace — take output path from MOE_TRACE_OUT env, -o not in this arg set

        * fix: moe-trace — topk tensor is a strided view; copy full byte range and index by nb

        Sizing the host buffer as n_used*n_tokens under-allocated: ffn_moe_topk
        is a view over the argsort output, so nb[1] spans n_expert ids per row
        and ggml_backend_tensor_get writes the whole strided range (heap
        corruption, malloc corrupted-top-size abort mid-prefill).

        * feat: moe-trace simulator v2 — model upload bytes/token and miss/upload cost per policy

        * feat: mul_mat_id tolerates id=-1 (skip) on CPU and CUDA fallback path

        Groundwork for the hot/cold expert-pack split: an id of -1 means the
        routed expert is not owned by this pack. The op contributes a zeroed
        output row for that slot so hot-pack and cold-pack results merge
        additively. CUDA fast paths (mmvq_id/mmq_id/mmf_id) still assert
        non-negative ids and are handled next.

        * feat: id=-1 skip support in CUDA mul_mat_id fast paths + tests

        mmid.cu gains a generic kernel that zeroes the dst rows of (token,
        slot) pairs whose expert id is -1; mmq and mmf launch it after the
        shared mm_ids_helper (which already drops unmatched ids from its
        compact mapping), and mmvq launches it before its kernels, which now
        early-return instead of using a negative id as a channel index (out
        of bounds read otherwise). test-backend-ops gains skip_ids variants
        of MUL_MAT_ID covering the mmvq/mmq/mmf/fallback dispatch corners.

        * fix: skip_ids MUL_MAT_ID test cases were inside an #if 0 block

        * fix: mm_ids_helper compact map corruption when ids contain -1

        Negative ids inflated nex_prev for every expert, opening a phantom
        region at the head of the compact arrays that nothing wrote; the mmq
        quantize preprocessing iterates the flat range and read garbage row
        indices (illegal memory access). Skipped ids now occupy no compact
        position, ids_src1 is sentinel-filled, and the quantize gather/scatter
        kernels skip negative entries.

        * fix: mmvf id=-1 skip guard (float mul_mat_id vec path)

        Same treatment as mmvq: kernels early-return on a negative expert id
        instead of using it as a channel index, and the host launcher
        pre-zeroes the dst rows of skipped slots. Fixes wrong results (and a
        latent out-of-bounds channel read) for f16/f32 MUL_MAT_ID with -1 ids
        at small batch sizes.

        * fix: zero-init ids_dst before mm_ids_helper — garbage tail entries in the
        compact map caused pool-layout-dependent illegal memory accesses when ids
        contain -1 (tile-padded reads consumed uninitialized row indices)

        * feat: route MUL_MAT_ID with skip-capable ids away from mmq/mmf

        Ops whose ids may contain -1 announce it via op_params[0]; the CUDA
        dispatch then uses only the paths with verified skip support (mmvq
        for small batches, the general gather/scatter path otherwise).
        Large-batch mmq with sparse ids shows a pool-layout-dependent fault
        that resists isolation (all indexing audits pass; sanitizer and
        cuda-gdb unusable on the target driver); since the expert-pack
        design only decodes through packs, the safe route costs nothing in
        practice. mmq/mmf guards from earlier commits remain as hardening.

        * fix: op_params write in test — ggml_set_op_params_i32 is internal-only

        * feat: MoE expert cache loader — hot-pack build from routing profile

        init_moe_expert_cache() runs post-load: reads a moe-trace profile
        (GGML_MOE_CACHE_PROFILE) and slot count (GGML_MOE_CACHE_SLOTS), and for
        each CPU-resident MoE layer builds GPU-resident hot packs of the top-S
        experts plus i32 remap tables (hot: global->slot or -1; cold: global id
        or -1). Graph wiring (build_moe_ffn dual path) is the next commit; these
        tensors are unused until then, so this is behavior-neutral.

        * feat: MoE expert cache graph wiring — dual hot/cold mul_mat_id in build_moe_ffn

        When a layer carries hot packs, routed ids are remapped through
        moe_map_hot/cold (get_rows) and each expert projection runs as two
        skip-flagged mul_mat_id ops — hot pack on GPU, original tensors for
        cold — whose zero-padded outputs sum to the exact single-tensor
        result. Engaged for qwen35moe (separate gate/up/down, no expert
        scales); layers with merged gate_up, scales, or no packs use the
        unchanged path.

        * fix: flatten routed ids before map get_rows (batched-gather shape rule)

        * fix: topk ids are a strided view - cont before flatten for map lookup

        * fix: sched expert-copy path skips id=-1 (hot/cold expert split)

        * fix: restructure MoE pack dual path into full FFN chains per residency side

        Per-projection hot/cold interleave let the scheduler's split minimizer
        assign hot up/down matmuls to CPU, copying the GPU pack weights over
        PCIe every layer. Building one unbroken gate-up-swiglu-down chain per
        side keeps the hot pack on GPU; skipped (-1) rows stay zero through
        swiglu so a single add of the two chain outputs is exact.

        * feat: wire MoE expert cache into deepseek2 graph (GLM-4.7-Flash)

        * feat: add --moe-cache-profile and --moe-cache-slots flags

        Plumbed through llama_model_params; env vars remain as fallback so
        existing deployments keep working. Flags allow per-model settings in
        multi-model serving.

        * docs: fix moe-trace usage comment (output path is MOE_TRACE_OUT env)

    commit cd72c28
    Author: Anirban Kar <[email protected]>
    Date:   Fri Jul 24 17:53:41 2026 +0530

        fix: restore closing brace lost in dequantize.cuh merge resolution

    commit 34f893e
    Merge: 40f2036 8f5ab83
    Author: Anirban Kar <[email protected]>
    Date:   Fri Jul 24 17:52:26 2026 +0530

        merge: sync upstream master into perf

    commit 8f5ab83
    Author: Matt Thompson <[email protected]>
    Date:   Fri Jul 24 03:54:47 2026 -0700

        cohere2 moe template parser: enforce JSON schema for text responses if a response schema is provided (ggml-org#26018)

    commit 0cea362
    Author: Xuan-Son Nguyen <[email protected]>
    Date:   Fri Jul 24 08:02:23 2026 +0200

        vendor: update subprocess.h (ggml-org#26061)

    commit 40f2036
    Author: Anirban Kar <[email protected]>
    Date:   Sun Jul 19 04:34:24 2026 +0530

        feat: fused turbo MMA flash-attention decode (turbo4/3/2, GQA tensor-core path) (TheTom#4)

        * feat(fattn): fused turbo4 MMA decode path (opt-in) — based on the spiritbuun fork MMA approach, adapted to graph-rotated Q

        Port buun's fused turbo4 tensor-core (MMA) flash-attention DECODE kernel into
        the turbo fork as an OPT-IN path (GGML_TURBO_MMA_FUSED=1, default OFF), routing
        turbo4-K==turbo4-V, D in {128,256}, decode (Q->ne[1]<=4) onto the GQA-packed MMA
        path so KV is read once per head-group instead of once per query head.

        How it works:
        - fattn-mma-f16.cuh: add flash_attn_ext_turbo4_load_tile (dequant turbo4 blocks
          -> SRAM in the f16 row-major half2 layout) seeded with OUR Lloyd-Max centroids
          (turbo-quant.cuh:297, NOT buun's -0.2415xx table). Thread type_K/type_V through
          iter/process_tile/global flash_attn_ext_f16 (defaults F16 -> existing f16/q8 MMA
          byte-identical). For turbo: force nstages=0 (the cp.async multi-stage path would
          read raw turbo bytes as half2), pass RAW byte pitch nb11/nb21 (not /sizeof(half2)),
          and dequantize K/V in the load tiles. sizeof(block_turbo4_0)-driven pointer math
          (66B block, no rnorm) — never assumes a fixed offset.
        - fattn-mma-turbo.cuh + 14 instance files (7 reachable ncols pairs x D in {128,256}):
          host launcher reusing the f16 device kernel with type_K/type_V=TURBO4_0 and
          need_f16_K/V=false so launch_fattn does NOT pre-convert KV to f16.
        - fattn.cu: switch_ncols2 -> per-ncols2 dispatchers (only the 7 compiled instances),
          env latch, and the gate (Q untouched — our fork already rotates Q at the graph
          level, so NO inline FWHT / src swap, which would double-rotate Q).

        Results (Qwen3.6-35B-A3B turbo4, GQA8, D=256, 5090):
          depth   MMA      VEC+PDL   buun
          8192    213.8    188.5     200    (+6.9% vs buun)
          16384   207.6    171.7     193    (+7.5% vs buun)
          32768   191.3    141.1     187    (+2.3% vs buun)
        MMA holds flat at depth where VEC collapses; the gap vs VEC grows with KV length.

        Quality: Mean KLD vs f16 base = 0.008396 (== VEC baseline). The MMA path is NOT
        strictly token-identical to VEC — MMA and VEC accumulate the P*V (VKQ) reduction in
        f16 with different reduction trees, so a near-tie greedy token can flip (~1/25 on a
        hard tie; same irreducible f16-order effect that exists between base f16-MMA and
        f16-VEC, and within the VEC-vs-base "same-top-p" 96.3% noise floor). Because strict
        token-identity does not hold, the gate DEFAULTS OFF and ships as opt-in; VEC remains
        the untouched default/kill-switch.

        (cherry picked from commit 5450669510a5cd0a356a863923b057f2552c6fbb)
        (cherry picked from commit b3e51cf)

        * turbo4 MMA decode: default ON (GQA-packed tensor-core path, quality-neutral; GGML_TURBO_MMA_FUSED=0 kill-switch)

        (cherry picked from commit 726234b538194c644be4066e1413b91f9edf12e7)
        (cherry picked from commit 38dc665)

        * fattn: extend fused MMA decode to turbo3 + turbo2 (parity on turbo4; extends the MMA path to turbo3/2)

        The GQA-packed tensor-core decode path was turbo4-only; turbo3/turbo2 fell back to
        VEC and collapsed at depth (turbo3 tg32 224->124 from d2048->d32768), losing to
        spiritbuun there. Added flash_attn_ext_turbo3_load_tile (3-bit split index: 2 low
        bits from qs + 1 high bit from signs) and flash_attn_ext_turbo2_load_tile (plain
        2-bit), type-dispatched both the K and V MMA load sites, and routed the gate by
        K->type. is_turbo_kv already matches any non-f16 KV, so the kernel needed only the
        per-type tile loaders + instances (14 instance files now emit all three types).

        Correctness: MMA decode is bit-exact to VEC (Mean KLD @2048 chunks=8:
        turbo3 0.020278==0.020278, turbo2 0.041490==0.041490, turbo4 0.009296 unchanged).

        Decode tg32 (qwen3.6-35B-A3B, RTX 5090), MMA now flat at depth:
          turbo3  2k/8k/16k/32k = 224/225/217/203  (buun 193/193/183/178; was VEC 224/187/160/124)
          turbo2  2k/8k/16k/32k = 228/224/217/203  (buun 213/210/204/200; was VEC 229/218/203/183)

        turbo3/turbo2 now hold flat at depth (neither fork had them on the MMA path before). GGML_TURBO_MMA_FUSED=0 restores VEC.

        (cherry picked from commit 57ad5edd53a7fced0b99fecb99326132cbdb65d0)
        (cherry picked from commit 4e223ee)

        * fix(fattn): gate turbo2 fused-MMA decode to head_dim 128

        Tester @everson isolated a turbo2-only decode regression on RTX 5060 Ti
        (Gemma-12B, head_dim 256): turbo2/turbo2 -2.46% at 8K to -1.17% at 200K,
        fully restored by GGML_TURBO_MMA_FUSED=0 at every depth, while turbo3 was
        neutral and turbo4 exact parity. At 2-bit KV the fused path's GQA-pack
        saving is tiny while its dequant/no-pipeline overhead is unchanged, so on
        head_dim 256 it is neutral on high-bandwidth GPUs (Ornith-35B and a dense
        Gemma-4-12B on RTX 5090, both within noise) and only costs on
        bandwidth-limited cards.

        turbo2 fused remains a large depth win on dense head_dim 128 (Llama-3.1-8B
        on RTX 5090: +7% at 8K, +24% at 32K, +69% at 131K), so this gates turbo2
        fused to head_dim 128 only; head_dim 256 turbo2 falls through to VEC, which
        is the exact baseline path GGML_TURBO_MMA_FUSED=0 restored. turbo3 and
        turbo4 fused are unchanged at both head dims.

        Also corrects the stale "default OFF" gate comments to match the
        default-ON code.

        (cherry picked from commit 539ce5d)

        ---------

        Co-authored-by: TheTom <[email protected]>

    commit 4cd54c6
    Author: Anirban Kar <[email protected]>
    Date:   Sun Jul 19 04:14:41 2026 +0530

        fix: allow mixed turbo/q8_0 KV cache types in CUDA flash-attention selection (TheTom#3)

        * fix: allow mixed turbo/q8_0 KV cache types in CUDA flash-attention selection

        Without GGML_CUDA_FA_ALL_QUANTS (the default), kernel selection
        rejected any K/V type mismatch. A turbo KV setup is almost always
        mixed (ctk q8_0 + ctv turbo2/3), so the flash-attention probe failed,
        FA was auto-disabled, and context creation either refused the
        quantized V cache outright or fell back to the non-FA path whose
        KQ buffer (~8.7 GiB at 64k ctx, ubatch 1024) OOMs at load.

        Allow exactly the mixed pairs that have FA template instances
        compiled in: turbo2/3/4 against each other, q8_0, and f16. Also gate
        turbo head-dim geometry (multiples of 64; 128 for turbo4) so shapes
        without a compiled instance report unsupported instead of asserting
        at dispatch.

        Forcing -fa on masked the bug (the probe is skipped); server
        deployments use fa auto and hit it on every load.

        * feat: accept turbo2/3/4 cache type names in llama-bench

        The common arg parser already accepts them for llama-completion and
        llama-server; llama-bench has its own name table and rejected -ctk/-ctv
        turbo values.

    commit 9338207
    Author: Anirban Kar <[email protected]>
    Date:   Sun Jul 19 01:59:58 2026 +0530

        CUDA: add Q2_0 support (TheTom#2)

        Co-authored-by: Pasha Khosravi <[email protected]>

    commit 170322f
    Author: Anirban Kar <[email protected]>
    Date:   Sat Jul 18 15:27:13 2026 +0530

        feat: TurboQuant KV-cache quantization — all backends (TheTom#1)

        * feat: TurboQuant KV-cache quantization — core types + CPU backend

        Port of the TurboQuant codec (arXiv 2504.19874, reference:
        TheTom/llama-cpp-turboquant) onto this fork's base: WHT-rotated polar
        quantization for the KV cache.

        - new types TURBO2_0/TURBO3_0/TURBO4_0 (KV, 2/3/4-bit blocks of 128)
          and TQ3_1S/TQ4_1S (WHT-rotated Lloyd-Max weight formats), renumbered
          for this tree's type table
        - GGML_OP_TURBO_WHT + ggml_turbo_wht() builder (forward/inverse
          Walsh-Hadamard rotation with sign arrays, InnerQ scale hook)
        - ggml-turbo-quant.c codec core, rotation data tables, CPU op +
          vec_dot paths, type traits, quantize-chunk wiring
        - CUDA/Metal/Vulkan kernel sources imported (wired in follow-ups)
        - verified: test-turbo-quant round-trip on CPU (cosine 0.986-0.996)

        * feat: turbo KV cache — graph wiring and CLI types

        - pre-rotate Q (forward WHT) at every cache-backed attention site when
          K is a turbo type; no-op otherwise
        - inverse WHT on attention output in both FA and non-FA paths of
          build_attn_mha (group size derived from K, contiguity enforced)
        - register turbo2/3/4 as --cache-type-k/--cache-type-v values
        Core scope: no InnerQ scaling, no head-dim padding — turbo KV requires
        128-aligned (or 64-group) head dims

        * feat: turbo KV cache — Metal backend (WHT kernel + FA dispatch)

        Wire the TurboQuant Metal backend host side and kernels on top of the
        CPU core already on this branch.

        Metal kernels (ggml-metal.metal):
        - Inlined turbo-wht.h (WHT sign arrays incl. half4 variants + FWHT
          butterfly + rotate fwd/inverse) and the turbo2/3/4 centroids.
        - quantize/dequantize_turbo2_0/3_0/4_0 (+_t4) and full-block cache.
        - kernel_turbo_wht (O(d log d) Walsh-Hadamard rotation op) and
          kernel_turbo4_dequant_f16 bulk prefill dequant.
        - kernel_set_rows_turbo/2/4 cache-quantize kernels + instantiations.
        - flash_attn_ext / flash_attn_ext_vec instantiations for symmetric and
          asymmetric turbo2/3/4 and q8_0<->turbo pairs.
        - TurboFlash two-pass kernels (p1/p2), default-disabled via env.

        Host side:
        - ggml-metal-device.cpp: get_pipeline_turbo_wht; flash-attn pipeline
          base names now encode both K and V types (k%s_v%s) so asymmetric K/V
          pairs resolve unambiguously. All existing FA kernel host_names in the
          shader renamed to match.
        - ggml-metal-device.m: TurboQuant compile-time env prep (4-mag LUT auto
          select, sparse-V, profile mode); supports_op accepts turbo K types and
          asymmetric turbo/q8_0 FA pairs; GGML_OP_TURBO_WHT.
        - ggml-metal-ops.cpp: GGML_OP_TURBO_WHT encode case + impl; asymmetric
          K/V assert relaxation; TurboFlash gating (use_turbo_flash, extra_tmp
          sizing, force-nonvec) + two-pass dispatch; +128 float FA smem for the
          turbo block cache.
        - ggml-metal-impl.h / -device.h / -ops.h: kargs (turbo_wht,
          turbo_flash_p1/p2), FC offsets, pipeline/op declarations.

        Adaptations vs the reference tree (older upstream vintage):
        - Reference intertwines separate TQ3_1S/TQ4_1S weight-quant work; only
          the turbo KV-cache lines are ported here.
        - set_rows_turbo dispatch selection is not wired: our upstream refactored
          get_pipeline_set_rows/kernel_set_rows_q32 to a different signature, and
          it is out of scope for this KV port. supports_op therefore does not
          claim CPY/SET_ROWS turbo support, so cache writes fall back to CPU;
          the set_rows_turbo shader kernels are present for when dispatch lands.
        - No InnerQ scale tensors touched (graph passes nullptr scale).

        * feat: turbo KV cache — CUDA backend (set-rows quantize, fattn vec dispatch, dequant)

        Port the TurboQuant CUDA backend from the reference implementation, adapted
        to this newer upstream vintage:

        - set-rows.cu: k_set_rows_turbo2/3/4 kernels (WHT rotation + norm-corrected
          PolarQuant KV write, InnerQ calibration hooks) + dispatch. turbo4 rnorm
          write dropped (field removed from block_turbo4_0 on this branch).
        - dequantize.cuh: dequantize_turbo2/3/4_0 and dequantize_tq3_1s/tq4_1s
          device functions.
        - convert.cu: turbo + TQ dequant cases in the fp16/fp32 contiguous and
          non-contiguous dispatch tables; warp-cooperative TQ4_1S dequant kernel.
        - fattn-common.cuh: vec_dot_fattn_vec_KQ_turbo2/3/4_0, dequantize_V_turbo*
          and get_vec_dot_KQ / get_dequantize_V dispatch entries.
        - fattn-vec.cuh: turbo K types take the float-Q path (Q_q8_1 off), turbo V
          uses the ne=4 quantized dequant path; extern decls for the 21 compiled
          K/V type combinations. Reference-side perf extras (shared-mem centroid
          LUT, sparse-V skip, nthreads tuning) intentionally not ported.
        - fattn.cu: turbo types accepted in kv_type_supported, vec kernel cases
          registered. Decode goes through the VEC kernel; prefill converts KV to
          f16 via the ported nc dequant path.
        - fattn-mma-turbo.cuh: reduced to a stub launcher. No typed MMA kernel
          exists in the reference either; the pre-existing template instances now
          compile against the stub and the dispatcher never selects this path.
        - ggml-cuda.cu: GGML_OP_TURBO_WHT dispatch + supports_op, SET_ROWS turbo
          gates (head_dim % 64, turbo4 % 128).
        - CMakeLists.txt: turbo fattn-vec instances added to the non-FA_ALL_QUANTS
          build.

        Verified on RTX 3060 (sm_86) with Bonsai-27B-Q1_0, partial offload, fa on:
        coherent generation for turbo2/3/4; perplexity over 4 chunks:
        f16 KV 7.9486 +/- 0.73, turbo3 KV 8.0261 +/- 0.74 (CUDA) vs 8.0279 (CPU-only).

        * feat: turbo KV cache — Vulkan backend (set-rows quantize, turbo3 FA dispatch, WHT op)

        - register turbo_wht.comp and set_rows turbo2/3/4 quantize variants in
          vulkan-shaders-gen; add dedicated DATA_A_TURBO3_0 flash-attn SPIR-V
          (scalar + coopmat1) with turbo3-only K/V bindings
        - copy_to_quant: 128-thread per-block set_rows path (normalize, randomized
          WHT, Lloyd-Max centroid quantize, subgroup pack), shared WHT tables
          across the three turbo widths
        - flash_attn_dequant: turbo2/3/4 centroid dequant macros wired into the
          FaTypeK/FaTypeV runtime switch (ids 43/44/45); f16 K/V aliases guarded
          out under DATA_A_TURBO3_0
        - ggml-vulkan: GGML_OP_TURBO_WHT pipeline + dispatch, turbo set_rows
          pipelines (required subgroup size 32), FA pipeline selection for
          turbo3, supports_op gates (128-elem blocks, turbo3 K/V symmetry,
          scalar/coopmat1 only — cm2 falls back to scalar)

        * fix: extern initialization warning and C linkage for wht group size

        CI builds with -Werror: defining the GGML_API-decorated global with an
        initializer warns on every platform. Plain definition in the C TU; the
        C++ consumer now declares it extern "C" (it previously referenced a
        mangled symbol).

        * feat: turbo2/turbo4 FA dequant for Vulkan

        - generalize the dedicated turbo flash-attn SPIR-V path from turbo3-only
          to all three tiers: DATA_A_TURBO_KV umbrella define in types.glsl gates
          out the f16/q4/q5/q8 K/V binding aliases in flash_attn.comp,
          flash_attn_cm1.comp and flash_attn_dequant.glsl for any turbo tier
        - flash_attn_dequant: per-compilation dequantize4 for DATA_A_TURBO2_0
          (2-bit centroids, fp16 norm + 32B idx) and DATA_A_TURBO4_0 (4-bit
          nibble idx, fp16 norm + fp16 aux + 64B) alongside the turbo3 one
        - vulkan-shaders-gen: register flash_attn_f32_f16_turbo{2,4}_0 scalar +
          coopmat1 variants via a per-tier loop
        - ggml-vulkan: FA pipeline selection picks the matching turbo SPIR-V for
          turbo2/turbo4 k_type (scalar + cm1), supports_op requires symmetric
          K/V per tier (turbo2/turbo2, turbo3/turbo3, turbo4/turbo4)

        * fix: bump RPC proto patch version for GGML_OP_TURBO_WHT

        * fix: export WHT group size via GGML_API for Windows shared builds

        * fix: HIP/MUSA portability for turbo kernels

        - map cudaMemcpyToSymbol/FromSymbol and __ballot_sync in vendor headers
        - pass explicit width to __shfl*_sync (HIP macros take 4 args)
        - drop unused warp_id locals flagged by nvcc -Werror

        * fix: drop SYCL turbo fattn-vec instances (no turbo dequant support in SYCL fattn)

        * fix: size vec_dot buffer by vec_dot_type and handle turbo/tq types in quantize test

        - tmp_q2 overflowed for types with vec_dot_type F32 (4 bytes per element)
        - skip turbo KV types: they quantize in the rotated domain, round trip
          does not reproduce the input by design
        - tq3_1s uses the 3-bit and lowbit thresholds

        * fix: add turbo fattn-vec instances to HIP and MUSA source lists

        * fix: add turbo fattn vec kernels to HIP VGPR ignore list

        The gfx908 build of the ncols=2 turbo3 vec kernels lands at 259 total
        VGPRs, slightly over the 256 gate. Register them like the other known
        high-pressure fattn kernels.

    commit 0888217
    Merge: 5e7f627 7d56da7
    Author: Anirban Kar <[email protected]>
    Date:   Fri Jul 17 20:02:48 2026 +0530

        chore: sync perf with upstream master

    commit 5e7f627
    Author: Anirban Kar <[email protected]>
    Date:   Wed Jul 8 23:56:46 2026 +0530

        docs(readme): add usage + benchmark instructions for the MoE-offload optimizations

    commit 5f83fbb
    Author: thecodacus <[email protected]>
    Date:   Thu Jul 2 12:42:55 2026 +0000

        ggml : size prefetch slots per layer and fix fallback use-after-free

        Profiling showed the 2-slot rotation stalls ~5.5ms per layer waiting for
        the down_exps upload: 3 tensors per MoE layer need 3 slots for a full
        layer of lookahead. Default is now 3 (one layer), configurable via the
        env var value, degrading to however many slots fit on OOM.

        Also fixes a use-after-free: on a failed slot regrow the repointed
        staging tensors kept dangling pointers into freed device memory, which
        graph reuse carried into later evals. Staging repoints are now restored
        right after kernel launch, slots are sized once from the graph max, and
        allocation happens before freeing.

        Qwen3.6-35B-A3B pp2048 on RTX 3060: 1643 -> 1880 t/s (mainline: 1143).

    commit 1163cb3
    Author: thecodacus <[email protected]>
    Date:   Thu Jul 2 12:16:39 2026 +0000

        ggml : overlap offloaded expert weight uploads with compute

        At large batch sizes virtually every expert is used, so the per-layer
        routing-ids readback that mainline waits on buys nothing while forcing a
        full device sync per expert tensor (3x per MoE layer). Above a batch
        threshold, upload the full expert tensors through a second backend
        instance on the same device (own stream) with two event-ordered staging
        slots, so uploads for tensor N+1 overlap compute of tensor N.

        Qwen3.6-35B-A3B pp2048 on RTX 3060 (-ncmoe 26, ub 2048): 1383 -> 1663 t/s.
        Generation output verified token-identical; decode path unaffected.
        Opt-in via GGML_SCHED_PREFETCH_EXPERTS=1.

    commit 20f5994
    Author: thecodacus <[email protected]>
    Date:   Thu Jul 2 09:44:53 2026 +0000

        llama : pin mmap-backed CPU weights for faster H2D uploads

        Wire the existing GGML_CUDA_REGISTER_HOST path back up: after model load,
        cudaHostRegister the mmap pages backing weights kept in system memory.
        Recovers pageable-copy losses when MoE experts are streamed to the GPU
        during prefill (n-cpu-moe): Qwen3.6-35B-A3B pp2048 1144 -> 1385 t/s on
        RTX 3060. Opt-in via GGML_CUDA_REGISTER_HOST=1, unchanged otherwise.
LogicDaemon added a commit to LogicDaemon/llama-cpp-turboquant that referenced this pull request Sep 7, 2026
commit 10f8aff
Author: thecodacus <[email protected]>
Date:   Tue Aug 25 23:39:14 2026 +0530

    perf: lower default --cpu-tp-margin to 512 MiB

    Measured on a 12GB RTX 3060 with a dense 27B Q4_K_M: tightening the margin
    raises both decode and prefill, since every MiB reclaimed moves weights off
    the CPU leg. 1024 -> 640 -> 384 MiB gave 7.4 -> 7.8 -> 8.1 t/s decode and
    14.4 -> 15.2 -> 16.5 t/s prefill. 512 keeps headroom for larger contexts;
    raise it if the GPU runs out of memory.

commit e406c8c
Author: thecodacus <[email protected]>
Date:   Tue Aug 25 22:08:09 2026 +0530

    feat: add --cpu-tp to use the CPU as a tensor-parallel device

    llama.cpp's tensor-parallel meta device already dispatches each member
    backend asynchronously before synchronising, but the CPU is excluded from
    the device list. Adding it lets the GPU and CPU compute row-slices of every
    weight matrix concurrently instead of running one after the other.

    The GPU share is sized from the measured free VRAM (minus --cpu-tp-margin)
    so VRAM is saturated, and the CPU takes only the remainder. The CPU is
    appended last so the GPU subgraph is already in flight when the CPU
    backend blocks on its own.

commit d927e7d
Author: Anirban Kar <[email protected]>
Date:   Tue Aug 25 15:58:16 2026 +0530

    docs: add MoE expert cache usage and tuning guide to README (TheTom#8)

    * docs: add MoE expert cache usage and tuning guide to README

    * docs: document async CPU split overlap and VRAM headroom rule

commit 0ac3d9b
Author: Anirban Kar <[email protected]>
Date:   Sun Aug 23 04:08:21 2026 +0530

    feat: overlap CPU cold-expert and GPU hot-expert computation in the MoE cache (TheTom#9)

    * feat: overlap CPU cold-expert chain with GPU hot chain (GGML_SCHED_ASYNC_CPU)

    The dual-path MoE cache ran its two chains serially: the scheduler
    blocks on CPU splits, and the cold chain's input copies drain the whole
    CUDA stream. Three changes make them concurrent, gated behind
    GGML_SCHED_ASYNC_CPU=1:

    - sched: CPU splits execute on a persistent worker thread; the main
      loop keeps launching later splits and joins lazily at the first split
      that is CPU or reads a CPU-resident input
    - graph: cold chain is built before the hot chain so the hot split
      follows it and carries no cross-backend inputs (launches while the
      worker computes)
    - graph: the merge add is pinned to CPU so it does not pull the hot
      chain into a split that waits on the cold result

    * feat: GGML_SCHED_ASYNC_CPU=2 diagnostic mode (worker without graph restructure)

    * fix: mark expert cache pack buffer as weights

    Without the weights usage flag the scheduler's assignment pass does not
    pin the pack tensors to their backend, so a CPU-assigned consumer (the
    pinned merge in async mode) propagates backward and pulls the hot
    matmuls onto the CPU, copying pack weights over PCIe every layer.

    * feat: make async CPU splits the default, expose --sched-async-cpu flag

    Replaces the GGML_SCHED_ASYNC_CPU env var: the overlap is now on by
    default and controlled through llama_context_params.sched_async_cpu.
    - ggml: ggml_backend_sched_set_async_cpu() setter, env read removed
    - llama: context param + cparams plumbing, graph gate reads cparams
    - common: --sched-async-cpu / --no-sched-async-cpu (server, cli)
    - llama-bench: sched_async_cpu test dimension (--sched-async-cpu 0,1
      benches both in one run, column shown as 'sac' when non-default)

    * fix: restrict CPU-pinned merge to decode-size batches

    For prefill batches the CPU merge and its per-layer activation copies
    cost more than the overlap hides (pp256 regressed 307 -> 257 t/s).
    Decode and MTP verify batches (n_tokens <= 8) keep the overlap.

commit 8e5bc28
Author: Anirban Kar <[email protected]>
Date:   Sat Jul 25 03:54:47 2026 +0530

    feat: wire MoE expert cache into laguna graph (TheTom#6)

commit ac743f8
Author: Anirban Kar <[email protected]>
Date:   Sat Jul 25 00:41:02 2026 +0530

    feat: MoE expert cache — keep hot routed experts resident in VRAM (TheTom#5)

    * feat: llama-moe-trace tool + expert-cache policy simulator

    Phase 0 of the MoE expert-cache work: capture routed expert ids
    (ffn_moe_topk) per layer per decode step via the scheduler eval
    callback — backend-agnostic, so CPU-offloaded expert layers are
    traced too. Companion simulate.py replays traces against cache
    policies (static top-S, LRU, LFU-decay, periodic re-election) and
    prints hit-rate vs VRAM-budget curves plus routing-skew stats to
    decide whether expert caching is worth building at all.

    * fix: moe-trace — common_init_from_params returns ptr with accessors

    * fix: moe-trace — include arg.h for common_params_parse

    * fix: moe-trace — take output path from MOE_TRACE_OUT env, -o not in this arg set

    * fix: moe-trace — topk tensor is a strided view; copy full byte range and index by nb

    Sizing the host buffer as n_used*n_tokens under-allocated: ffn_moe_topk
    is a view over the argsort output, so nb[1] spans n_expert ids per row
    and ggml_backend_tensor_get writes the whole strided range (heap
    corruption, malloc corrupted-top-size abort mid-prefill).

    * feat: moe-trace simulator v2 — model upload bytes/token and miss/upload cost per policy

    * feat: mul_mat_id tolerates id=-1 (skip) on CPU and CUDA fallback path

    Groundwork for the hot/cold expert-pack split: an id of -1 means the
    routed expert is not owned by this pack. The op contributes a zeroed
    output row for that slot so hot-pack and cold-pack results merge
    additively. CUDA fast paths (mmvq_id/mmq_id/mmf_id) still assert
    non-negative ids and are handled next.

    * feat: id=-1 skip support in CUDA mul_mat_id fast paths + tests

    mmid.cu gains a generic kernel that zeroes the dst rows of (token,
    slot) pairs whose expert id is -1; mmq and mmf launch it after the
    shared mm_ids_helper (which already drops unmatched ids from its
    compact mapping), and mmvq launches it before its kernels, which now
    early-return instead of using a negative id as a channel index (out
    of bounds read otherwise). test-backend-ops gains skip_ids variants
    of MUL_MAT_ID covering the mmvq/mmq/mmf/fallback dispatch corners.

    * fix: skip_ids MUL_MAT_ID test cases were inside an #if 0 block

    * fix: mm_ids_helper compact map corruption when ids contain -1

    Negative ids inflated nex_prev for every expert, opening a phantom
    region at the head of the compact arrays that nothing wrote; the mmq
    quantize preprocessing iterates the flat range and read garbage row
    indices (illegal memory access). Skipped ids now occupy no compact
    position, ids_src1 is sentinel-filled, and the quantize gather/scatter
    kernels skip negative entries.

    * fix: mmvf id=-1 skip guard (float mul_mat_id vec path)

    Same treatment as mmvq: kernels early-return on a negative expert id
    instead of using it as a channel index, and the host launcher
    pre-zeroes the dst rows of skipped slots. Fixes wrong results (and a
    latent out-of-bounds channel read) for f16/f32 MUL_MAT_ID with -1 ids
    at small batch sizes.

    * fix: zero-init ids_dst before mm_ids_helper — garbage tail entries in the
    compact map caused pool-layout-dependent illegal memory accesses when ids
    contain -1 (tile-padded reads consumed uninitialized row indices)

    * feat: route MUL_MAT_ID with skip-capable ids away from mmq/mmf

    Ops whose ids may contain -1 announce it via op_params[0]; the CUDA
    dispatch then uses only the paths with verified skip support (mmvq
    for small batches, the general gather/scatter path otherwise).
    Large-batch mmq with sparse ids shows a pool-layout-dependent fault
    that resists isolation (all indexing audits pass; sanitizer and
    cuda-gdb unusable on the target driver); since the expert-pack
    design only decodes through packs, the safe route costs nothing in
    practice. mmq/mmf guards from earlier commits remain as hardening.

    * fix: op_params write in test — ggml_set_op_params_i32 is internal-only

    * feat: MoE expert cache loader — hot-pack build from routing profile

    init_moe_expert_cache() runs post-load: reads a moe-trace profile
    (GGML_MOE_CACHE_PROFILE) and slot count (GGML_MOE_CACHE_SLOTS), and for
    each CPU-resident MoE layer builds GPU-resident hot packs of the top-S
    experts plus i32 remap tables (hot: global->slot or -1; cold: global id
    or -1). Graph wiring (build_moe_ffn dual path) is the next commit; these
    tensors are unused until then, so this is behavior-neutral.

    * feat: MoE expert cache graph wiring — dual hot/cold mul_mat_id in build_moe_ffn

    When a layer carries hot packs, routed ids are remapped through
    moe_map_hot/cold (get_rows) and each expert projection runs as two
    skip-flagged mul_mat_id ops — hot pack on GPU, original tensors for
    cold — whose zero-padded outputs sum to the exact single-tensor
    result. Engaged for qwen35moe (separate gate/up/down, no expert
    scales); layers with merged gate_up, scales, or no packs use the
    unchanged path.

    * fix: flatten routed ids before map get_rows (batched-gather shape rule)

    * fix: topk ids are a strided view - cont before flatten for map lookup

    * fix: sched expert-copy path skips id=-1 (hot/cold expert split)

    * fix: restructure MoE pack dual path into full FFN chains per residency side

    Per-projection hot/cold interleave let the scheduler's split minimizer
    assign hot up/down matmuls to CPU, copying the GPU pack weights over
    PCIe every layer. Building one unbroken gate-up-swiglu-down chain per
    side keeps the hot pack on GPU; skipped (-1) rows stay zero through
    swiglu so a single add of the two chain outputs is exact.

    * feat: wire MoE expert cache into deepseek2 graph (GLM-4.7-Flash)

    * feat: add --moe-cache-profile and --moe-cache-slots flags

    Plumbed through llama_model_params; env vars remain as fallback so
    existing deployments keep working. Flags allow per-model settings in
    multi-model serving.

    * docs: fix moe-trace usage comment (output path is MOE_TRACE_OUT env)

commit cd72c28
Author: Anirban Kar <[email protected]>
Date:   Fri Jul 24 17:53:41 2026 +0530

    fix: restore closing brace lost in dequantize.cuh merge resolution

commit 34f893e
Merge: 40f2036 8f5ab83
Author: Anirban Kar <[email protected]>
Date:   Fri Jul 24 17:52:26 2026 +0530

    merge: sync upstream master into perf

commit 8f5ab83
Author: Matt Thompson <[email protected]>
Date:   Fri Jul 24 03:54:47 2026 -0700

    cohere2 moe template parser: enforce JSON schema for text responses if a response schema is provided (ggml-org#26018)

commit 0cea362
Author: Xuan-Son Nguyen <[email protected]>
Date:   Fri Jul 24 08:02:23 2026 +0200

    vendor: update subprocess.h (ggml-org#26061)

commit 40f2036
Author: Anirban Kar <[email protected]>
Date:   Sun Jul 19 04:34:24 2026 +0530

    feat: fused turbo MMA flash-attention decode (turbo4/3/2, GQA tensor-core path) (TheTom#4)

    * feat(fattn): fused turbo4 MMA decode path (opt-in) — based on the spiritbuun fork MMA approach, adapted to graph-rotated Q

    Port buun's fused turbo4 tensor-core (MMA) flash-attention DECODE kernel into
    the turbo fork as an OPT-IN path (GGML_TURBO_MMA_FUSED=1, default OFF), routing
    turbo4-K==turbo4-V, D in {128,256}, decode (Q->ne[1]<=4) onto the GQA-packed MMA
    path so KV is read once per head-group instead of once per query head.

    How it works:
    - fattn-mma-f16.cuh: add flash_attn_ext_turbo4_load_tile (dequant turbo4 blocks
      -> SRAM in the f16 row-major half2 layout) seeded with OUR Lloyd-Max centroids
      (turbo-quant.cuh:297, NOT buun's -0.2415xx table). Thread type_K/type_V through
      iter/process_tile/global flash_attn_ext_f16 (defaults F16 -> existing f16/q8 MMA
      byte-identical). For turbo: force nstages=0 (the cp.async multi-stage path would
      read raw turbo bytes as half2), pass RAW byte pitch nb11/nb21 (not /sizeof(half2)),
      and dequantize K/V in the load tiles. sizeof(block_turbo4_0)-driven pointer math
      (66B block, no rnorm) — never assumes a fixed offset.
    - fattn-mma-turbo.cuh + 14 instance files (7 reachable ncols pairs x D in {128,256}):
      host launcher reusing the f16 device kernel with type_K/type_V=TURBO4_0 and
      need_f16_K/V=false so launch_fattn does NOT pre-convert KV to f16.
    - fattn.cu: switch_ncols2 -> per-ncols2 dispatchers (only the 7 compiled instances),
      env latch, and the gate (Q untouched — our fork already rotates Q at the graph
      level, so NO inline FWHT / src swap, which would double-rotate Q).

    Results (Qwen3.6-35B-A3B turbo4, GQA8, D=256, 5090):
      depth   MMA      VEC+PDL   buun
      8192    213.8    188.5     200    (+6.9% vs buun)
      16384   207.6    171.7     193    (+7.5% vs buun)
      32768   191.3    141.1     187    (+2.3% vs buun)
    MMA holds flat at depth where VEC collapses; the gap vs VEC grows with KV length.

    Quality: Mean KLD vs f16 base = 0.008396 (== VEC baseline). The MMA path is NOT
    strictly token-identical to VEC — MMA and VEC accumulate the P*V (VKQ) reduction in
    f16 with different reduction trees, so a near-tie greedy token can flip (~1/25 on a
    hard tie; same irreducible f16-order effect that exists between base f16-MMA and
    f16-VEC, and within the VEC-vs-base "same-top-p" 96.3% noise floor). Because strict
    token-identity does not hold, the gate DEFAULTS OFF and ships as opt-in; VEC remains
    the untouched default/kill-switch.

    (cherry picked from commit 5450669510a5cd0a356a863923b057f2552c6fbb)
    (cherry picked from commit b3e51cf)

    * turbo4 MMA decode: default ON (GQA-packed tensor-core path, quality-neutral; GGML_TURBO_MMA_FUSED=0 kill-switch)

    (cherry picked from commit 726234b538194c644be4066e1413b91f9edf12e7)
    (cherry picked from commit 38dc665)

    * fattn: extend fused MMA decode to turbo3 + turbo2 (parity on turbo4; extends the MMA path to turbo3/2)

    The GQA-packed tensor-core decode path was turbo4-only; turbo3/turbo2 fell back to
    VEC and collapsed at depth (turbo3 tg32 224->124 from d2048->d32768), losing to
    spiritbuun there. Added flash_attn_ext_turbo3_load_tile (3-bit split index: 2 low
    bits from qs + 1 high bit from signs) and flash_attn_ext_turbo2_load_tile (plain
    2-bit), type-dispatched both the K and V MMA load sites, and routed the gate by
    K->type. is_turbo_kv already matches any non-f16 KV, so the kernel needed only the
    per-type tile loaders + instances (14 instance files now emit all three types).

    Correctness: MMA decode is bit-exact to VEC (Mean KLD @2048 chunks=8:
    turbo3 0.020278==0.020278, turbo2 0.041490==0.041490, turbo4 0.009296 unchanged).

    Decode tg32 (qwen3.6-35B-A3B, RTX 5090), MMA now flat at depth:
      turbo3  2k/8k/16k/32k = 224/225/217/203  (buun 193/193/183/178; was VEC 224/187/160/124)
      turbo2  2k/8k/16k/32k = 228/224/217/203  (buun 213/210/204/200; was VEC 229/218/203/183)

    turbo3/turbo2 now hold flat at depth (neither fork had them on the MMA path before). GGML_TURBO_MMA_FUSED=0 restores VEC.

    (cherry picked from commit 57ad5edd53a7fced0b99fecb99326132cbdb65d0)
    (cherry picked from commit 4e223ee)

    * fix(fattn): gate turbo2 fused-MMA decode to head_dim 128

    Tester @everson isolated a turbo2-only decode regression on RTX 5060 Ti
    (Gemma-12B, head_dim 256): turbo2/turbo2 -2.46% at 8K to -1.17% at 200K,
    fully restored by GGML_TURBO_MMA_FUSED=0 at every depth, while turbo3 was
    neutral and turbo4 exact parity. At 2-bit KV the fused path's GQA-pack
    saving is tiny while its dequant/no-pipeline overhead is unchanged, so on
    head_dim 256 it is neutral on high-bandwidth GPUs (Ornith-35B and a dense
    Gemma-4-12B on RTX 5090, both within noise) and only costs on
    bandwidth-limited cards.

    turbo2 fused remains a large depth win on dense head_dim 128 (Llama-3.1-8B
    on RTX 5090: +7% at 8K, +24% at 32K, +69% at 131K), so this gates turbo2
    fused to head_dim 128 only; head_dim 256 turbo2 falls through to VEC, which
    is the exact baseline path GGML_TURBO_MMA_FUSED=0 restored. turbo3 and
    turbo4 fused are unchanged at both head dims.

    Also corrects the stale "default OFF" gate comments to match the
    default-ON code.

    (cherry picked from commit 539ce5d)

    ---------

    Co-authored-by: TheTom <[email protected]>

commit 4cd54c6
Author: Anirban Kar <[email protected]>
Date:   Sun Jul 19 04:14:41 2026 +0530

    fix: allow mixed turbo/q8_0 KV cache types in CUDA flash-attention selection (TheTom#3)

    * fix: allow mixed turbo/q8_0 KV cache types in CUDA flash-attention selection

    Without GGML_CUDA_FA_ALL_QUANTS (the default), kernel selection
    rejected any K/V type mismatch. A turbo KV setup is almost always
    mixed (ctk q8_0 + ctv turbo2/3), so the flash-attention probe failed,
    FA was auto-disabled, and context creation either refused the
    quantized V cache outright or fell back to the non-FA path whose
    KQ buffer (~8.7 GiB at 64k ctx, ubatch 1024) OOMs at load.

    Allow exactly the mixed pairs that have FA template instances
    compiled in: turbo2/3/4 against each other, q8_0, and f16. Also gate
    turbo head-dim geometry (multiples of 64; 128 for turbo4) so shapes
    without a compiled instance report unsupported instead of asserting
    at dispatch.

    Forcing -fa on masked the bug (the probe is skipped); server
    deployments use fa auto and hit it on every load.

    * feat: accept turbo2/3/4 cache type names in llama-bench

    The common arg parser already accepts them for llama-completion and
    llama-server; llama-bench has its own name table and rejected -ctk/-ctv
    turbo values.

commit 9338207
Author: Anirban Kar <[email protected]>
Date:   Sun Jul 19 01:59:58 2026 +0530

    CUDA: add Q2_0 support (TheTom#2)

    Co-authored-by: Pasha Khosravi <[email protected]>

commit 170322f
Author: Anirban Kar <[email protected]>
Date:   Sat Jul 18 15:27:13 2026 +0530

    feat: TurboQuant KV-cache quantization — all backends (TheTom#1)

    * feat: TurboQuant KV-cache quantization — core types + CPU backend

    Port of the TurboQuant codec (arXiv 2504.19874, reference:
    TheTom/llama-cpp-turboquant) onto this fork's base: WHT-rotated polar
    quantization for the KV cache.

    - new types TURBO2_0/TURBO3_0/TURBO4_0 (KV, 2/3/4-bit blocks of 128)
      and TQ3_1S/TQ4_1S (WHT-rotated Lloyd-Max weight formats), renumbered
      for this tree's type table
    - GGML_OP_TURBO_WHT + ggml_turbo_wht() builder (forward/inverse
      Walsh-Hadamard rotation with sign arrays, InnerQ scale hook)
    - ggml-turbo-quant.c codec core, rotation data tables, CPU op +
      vec_dot paths, type traits, quantize-chunk wiring
    - CUDA/Metal/Vulkan kernel sources imported (wired in follow-ups)
    - verified: test-turbo-quant round-trip on CPU (cosine 0.986-0.996)

    * feat: turbo KV cache — graph wiring and CLI types

    - pre-rotate Q (forward WHT) at every cache-backed attention site when
      K is a turbo type; no-op otherwise
    - inverse WHT on attention output in both FA and non-FA paths of
      build_attn_mha (group size derived from K, contiguity enforced)
    - register turbo2/3/4 as --cache-type-k/--cache-type-v values
    Core scope: no InnerQ scaling, no head-dim padding — turbo KV requires
    128-aligned (or 64-group) head dims

    * feat: turbo KV cache — Metal backend (WHT kernel + FA dispatch)

    Wire the TurboQuant Metal backend host side and kernels on top of the
    CPU core already on this branch.

    Metal kernels (ggml-metal.metal):
    - Inlined turbo-wht.h (WHT sign arrays incl. half4 variants + FWHT
      butterfly + rotate fwd/inverse) and the turbo2/3/4 centroids.
    - quantize/dequantize_turbo2_0/3_0/4_0 (+_t4) and full-block cache.
    - kernel_turbo_wht (O(d log d) Walsh-Hadamard rotation op) and
      kernel_turbo4_dequant_f16 bulk prefill dequant.
    - kernel_set_rows_turbo/2/4 cache-quantize kernels + instantiations.
    - flash_attn_ext / flash_attn_ext_vec instantiations for symmetric and
      asymmetric turbo2/3/4 and q8_0<->turbo pairs.
    - TurboFlash two-pass kernels (p1/p2), default-disabled via env.

    Host side:
    - ggml-metal-device.cpp: get_pipeline_turbo_wht; flash-attn pipeline
      base names now encode both K and V types (k%s_v%s) so asymmetric K/V
      pairs resolve unambiguously. All existing FA kernel host_names in the
      shader renamed to match.
    - ggml-metal-device.m: TurboQuant compile-time env prep (4-mag LUT auto
      select, sparse-V, profile mode); supports_op accepts turbo K types and
      asymmetric turbo/q8_0 FA pairs; GGML_OP_TURBO_WHT.
    - ggml-metal-ops.cpp: GGML_OP_TURBO_WHT encode case + impl; asymmetric
      K/V assert relaxation; TurboFlash gating (use_turbo_flash, extra_tmp
      sizing, force-nonvec) + two-pass dispatch; +128 float FA smem for the
      turbo block cache.
    - ggml-metal-impl.h / -device.h / -ops.h: kargs (turbo_wht,
      turbo_flash_p1/p2), FC offsets, pipeline/op declarations.

    Adaptations vs the reference tree (older upstream vintage):
    - Reference intertwines separate TQ3_1S/TQ4_1S weight-quant work; only
      the turbo KV-cache lines are ported here.
    - set_rows_turbo dispatch selection is not wired: our upstream refactored
      get_pipeline_set_rows/kernel_set_rows_q32 to a different signature, and
      it is out of scope for this KV port. supports_op therefore does not
      claim CPY/SET_ROWS turbo support, so cache writes fall back to CPU;
      the set_rows_turbo shader kernels are present for when dispatch lands.
    - No InnerQ scale tensors touched (graph passes nullptr scale).

    * feat: turbo KV cache — CUDA backend (set-rows quantize, fattn vec dispatch, dequant)

    Port the TurboQuant CUDA backend from the reference implementation, adapted
    to this newer upstream vintage:

    - set-rows.cu: k_set_rows_turbo2/3/4 kernels (WHT rotation + norm-corrected
      PolarQuant KV write, InnerQ calibration hooks) + dispatch. turbo4 rnorm
      write dropped (field removed from block_turbo4_0 on this branch).
    - dequantize.cuh: dequantize_turbo2/3/4_0 and dequantize_tq3_1s/tq4_1s
      device functions.
    - convert.cu: turbo + TQ dequant cases in the fp16/fp32 contiguous and
      non-contiguous dispatch tables; warp-cooperative TQ4_1S dequant kernel.
    - fattn-common.cuh: vec_dot_fattn_vec_KQ_turbo2/3/4_0, dequantize_V_turbo*
      and get_vec_dot_KQ / get_dequantize_V dispatch entries.
    - fattn-vec.cuh: turbo K types take the float-Q path (Q_q8_1 off), turbo V
      uses the ne=4 quantized dequant path; extern decls for the 21 compiled
      K/V type combinations. Reference-side perf extras (shared-mem centroid
      LUT, sparse-V skip, nthreads tuning) intentionally not ported.
    - fattn.cu: turbo types accepted in kv_type_supported, vec kernel cases
      registered. Decode goes through the VEC kernel; prefill converts KV to
      f16 via the ported nc dequant path.
    - fattn-mma-turbo.cuh: reduced to a stub launcher. No typed MMA kernel
      exists in the reference either; the pre-existing template instances now
      compile against the stub and the dispatcher never selects this path.
    - ggml-cuda.cu: GGML_OP_TURBO_WHT dispatch + supports_op, SET_ROWS turbo
      gates (head_dim % 64, turbo4 % 128).
    - CMakeLists.txt: turbo fattn-vec instances added to the non-FA_ALL_QUANTS
      build.

    Verified on RTX 3060 (sm_86) with Bonsai-27B-Q1_0, partial offload, fa on:
    coherent generation for turbo2/3/4; perplexity over 4 chunks:
    f16 KV 7.9486 +/- 0.73, turbo3 KV 8.0261 +/- 0.74 (CUDA) vs 8.0279 (CPU-only).

    * feat: turbo KV cache — Vulkan backend (set-rows quantize, turbo3 FA dispatch, WHT op)

    - register turbo_wht.comp and set_rows turbo2/3/4 quantize variants in
      vulkan-shaders-gen; add dedicated DATA_A_TURBO3_0 flash-attn SPIR-V
      (scalar + coopmat1) with turbo3-only K/V bindings
    - copy_to_quant: 128-thread per-block set_rows path (normalize, randomized
      WHT, Lloyd-Max centroid quantize, subgroup pack), shared WHT tables
      across the three turbo widths
    - flash_attn_dequant: turbo2/3/4 centroid dequant macros wired into the
      FaTypeK/FaTypeV runtime switch (ids 43/44/45); f16 K/V aliases guarded
      out under DATA_A_TURBO3_0
    - ggml-vulkan: GGML_OP_TURBO_WHT pipeline + dispatch, turbo set_rows
      pipelines (required subgroup size 32), FA pipeline selection for
      turbo3, supports_op gates (128-elem blocks, turbo3 K/V symmetry,
      scalar/coopmat1 only — cm2 falls back to scalar)

    * fix: extern initialization warning and C linkage for wht group size

    CI builds with -Werror: defining the GGML_API-decorated global with an
    initializer warns on every platform. Plain definition in the C TU; the
    C++ consumer now declares it extern "C" (it previously referenced a
    mangled symbol).

    * feat: turbo2/turbo4 FA dequant for Vulkan

    - generalize the dedicated turbo flash-attn SPIR-V path from turbo3-only
      to all three tiers: DATA_A_TURBO_KV umbrella define in types.glsl gates
      out the f16/q4/q5/q8 K/V binding aliases in flash_attn.comp,
      flash_attn_cm1.comp and flash_attn_dequant.glsl for any turbo tier
    - flash_attn_dequant: per-compilation dequantize4 for DATA_A_TURBO2_0
      (2-bit centroids, fp16 norm + 32B idx) and DATA_A_TURBO4_0 (4-bit
      nibble idx, fp16 norm + fp16 aux + 64B) alongside the turbo3 one
    - vulkan-shaders-gen: register flash_attn_f32_f16_turbo{2,4}_0 scalar +
      coopmat1 variants via a per-tier loop
    - ggml-vulkan: FA pipeline selection picks the matching turbo SPIR-V for
      turbo2/turbo4 k_type (scalar + cm1), supports_op requires symmetric
      K/V per tier (turbo2/turbo2, turbo3/turbo3, turbo4/turbo4)

    * fix: bump RPC proto patch version for GGML_OP_TURBO_WHT

    * fix: export WHT group size via GGML_API for Windows shared builds

    * fix: HIP/MUSA portability for turbo kernels

    - map cudaMemcpyToSymbol/FromSymbol and __ballot_sync in vendor headers
    - pass explicit width to __shfl*_sync (HIP macros take 4 args)
    - drop unused warp_id locals flagged by nvcc -Werror

    * fix: drop SYCL turbo fattn-vec instances (no turbo dequant support in SYCL fattn)

    * fix: size vec_dot buffer by vec_dot_type and handle turbo/tq types in quantize test

    - tmp_q2 overflowed for types with vec_dot_type F32 (4 bytes per element)
    - skip turbo KV types: they quantize in the rotated domain, round trip
      does not reproduce the input by design
    - tq3_1s uses the 3-bit and lowbit thresholds

    * fix: add turbo fattn-vec instances to HIP and MUSA source lists

    * fix: add turbo fattn vec kernels to HIP VGPR ignore list

    The gfx908 build of the ncols=2 turbo3 vec kernels lands at 259 total
    VGPRs, slightly over the 256 gate. Register them like the other known
    high-pressure fattn kernels.

commit 0888217
Merge: 5e7f627 7d56da7
Author: Anirban Kar <[email protected]>
Date:   Fri Jul 17 20:02:48 2026 +0530

    chore: sync perf with upstream master

commit 5e7f627
Author: Anirban Kar <[email protected]>
Date:   Wed Jul 8 23:56:46 2026 +0530

    docs(readme): add usage + benchmark instructions for the MoE-offload optimizations

commit 5f83fbb
Author: thecodacus <[email protected]>
Date:   Thu Jul 2 12:42:55 2026 +0000

    ggml : size prefetch slots per layer and fix fallback use-after-free

    Profiling showed the 2-slot rotation stalls ~5.5ms per layer waiting for
    the down_exps upload: 3 tensors per MoE layer need 3 slots for a full
    layer of lookahead. Default is now 3 (one layer), configurable via the
    env var value, degrading to however many slots fit on OOM.

    Also fixes a use-after-free: on a failed slot regrow the repointed
    staging tensors kept dangling pointers into freed device memory, which
    graph reuse carried into later evals. Staging repoints are now restored
    right after kernel launch, slots are sized once from the graph max, and
    allocation happens before freeing.

    Qwen3.6-35B-A3B pp2048 on RTX 3060: 1643 -> 1880 t/s (mainline: 1143).

commit 1163cb3
Author: thecodacus <[email protected]>
Date:   Thu Jul 2 12:16:39 2026 +0000

    ggml : overlap offloaded expert weight uploads with compute

    At large batch sizes virtually every expert is used, so the per-layer
    routing-ids readback that mainline waits on buys nothing while forcing a
    full device sync per expert tensor (3x per MoE layer). Above a batch
    threshold, upload the full expert tensors through a second backend
    instance on the same device (own stream) with two event-ordered staging
    slots, so uploads for tensor N+1 overlap compute of tensor N.

    Qwen3.6-35B-A3B pp2048 on RTX 3060 (-ncmoe 26, ub 2048): 1383 -> 1663 t/s.
    Generation output verified token-identical; decode path unaffected.
    Opt-in via GGML_SCHED_PREFETCH_EXPERTS=1.

commit 20f5994
Author: thecodacus <[email protected]>
Date:   Thu Jul 2 09:44:53 2026 +0000

    llama : pin mmap-backed CPU weights for faster H2D uploads

    Wire the existing GGML_CUDA_REGISTER_HOST path back up: after model load,
    cudaHostRegister the mmap pages backing weights kept in system memory.
    Recovers pageable-copy losses when MoE experts are streamed to the GPU
    during prefill (n-cpu-moe): Qwen3.6-35B-A3B pp2048 1144 -> 1385 t/s on
    RTX 3060. Opt-in via GGML_CUDA_REGISTER_HOST=1, unchanged otherwise.
zbrad pushed a commit to zbrad/llama.cpp that referenced this pull request Sep 10, 2026
LogicDaemon added a commit to LogicDaemon/llama-cpp-turboquant that referenced this pull request Sep 15, 2026
commit 10f8aff
Author: thecodacus <[email protected]>
Date:   Tue Aug 25 23:39:14 2026 +0530

    perf: lower default --cpu-tp-margin to 512 MiB

    Measured on a 12GB RTX 3060 with a dense 27B Q4_K_M: tightening the margin
    raises both decode and prefill, since every MiB reclaimed moves weights off
    the CPU leg. 1024 -> 640 -> 384 MiB gave 7.4 -> 7.8 -> 8.1 t/s decode and
    14.4 -> 15.2 -> 16.5 t/s prefill. 512 keeps headroom for larger contexts;
    raise it if the GPU runs out of memory.

commit e406c8c
Author: thecodacus <[email protected]>
Date:   Tue Aug 25 22:08:09 2026 +0530

    feat: add --cpu-tp to use the CPU as a tensor-parallel device

    llama.cpp's tensor-parallel meta device already dispatches each member
    backend asynchronously before synchronising, but the CPU is excluded from
    the device list. Adding it lets the GPU and CPU compute row-slices of every
    weight matrix concurrently instead of running one after the other.

    The GPU share is sized from the measured free VRAM (minus --cpu-tp-margin)
    so VRAM is saturated, and the CPU takes only the remainder. The CPU is
    appended last so the GPU subgraph is already in flight when the CPU
    backend blocks on its own.

commit d927e7d
Author: Anirban Kar <[email protected]>
Date:   Tue Aug 25 15:58:16 2026 +0530

    docs: add MoE expert cache usage and tuning guide to README (TheTom#8)

    * docs: add MoE expert cache usage and tuning guide to README

    * docs: document async CPU split overlap and VRAM headroom rule

commit 0ac3d9b
Author: Anirban Kar <[email protected]>
Date:   Sun Aug 23 04:08:21 2026 +0530

    feat: overlap CPU cold-expert and GPU hot-expert computation in the MoE cache (TheTom#9)

    * feat: overlap CPU cold-expert chain with GPU hot chain (GGML_SCHED_ASYNC_CPU)

    The dual-path MoE cache ran its two chains serially: the scheduler
    blocks on CPU splits, and the cold chain's input copies drain the whole
    CUDA stream. Three changes make them concurrent, gated behind
    GGML_SCHED_ASYNC_CPU=1:

    - sched: CPU splits execute on a persistent worker thread; the main
      loop keeps launching later splits and joins lazily at the first split
      that is CPU or reads a CPU-resident input
    - graph: cold chain is built before the hot chain so the hot split
      follows it and carries no cross-backend inputs (launches while the
      worker computes)
    - graph: the merge add is pinned to CPU so it does not pull the hot
      chain into a split that waits on the cold result

    * feat: GGML_SCHED_ASYNC_CPU=2 diagnostic mode (worker without graph restructure)

    * fix: mark expert cache pack buffer as weights

    Without the weights usage flag the scheduler's assignment pass does not
    pin the pack tensors to their backend, so a CPU-assigned consumer (the
    pinned merge in async mode) propagates backward and pulls the hot
    matmuls onto the CPU, copying pack weights over PCIe every layer.

    * feat: make async CPU splits the default, expose --sched-async-cpu flag

    Replaces the GGML_SCHED_ASYNC_CPU env var: the overlap is now on by
    default and controlled through llama_context_params.sched_async_cpu.
    - ggml: ggml_backend_sched_set_async_cpu() setter, env read removed
    - llama: context param + cparams plumbing, graph gate reads cparams
    - common: --sched-async-cpu / --no-sched-async-cpu (server, cli)
    - llama-bench: sched_async_cpu test dimension (--sched-async-cpu 0,1
      benches both in one run, column shown as 'sac' when non-default)

    * fix: restrict CPU-pinned merge to decode-size batches

    For prefill batches the CPU merge and its per-layer activation copies
    cost more than the overlap hides (pp256 regressed 307 -> 257 t/s).
    Decode and MTP verify batches (n_tokens <= 8) keep the overlap.

commit 8e5bc28
Author: Anirban Kar <[email protected]>
Date:   Sat Jul 25 03:54:47 2026 +0530

    feat: wire MoE expert cache into laguna graph (TheTom#6)

commit ac743f8
Author: Anirban Kar <[email protected]>
Date:   Sat Jul 25 00:41:02 2026 +0530

    feat: MoE expert cache — keep hot routed experts resident in VRAM (TheTom#5)

    * feat: llama-moe-trace tool + expert-cache policy simulator

    Phase 0 of the MoE expert-cache work: capture routed expert ids
    (ffn_moe_topk) per layer per decode step via the scheduler eval
    callback — backend-agnostic, so CPU-offloaded expert layers are
    traced too. Companion simulate.py replays traces against cache
    policies (static top-S, LRU, LFU-decay, periodic re-election) and
    prints hit-rate vs VRAM-budget curves plus routing-skew stats to
    decide whether expert caching is worth building at all.

    * fix: moe-trace — common_init_from_params returns ptr with accessors

    * fix: moe-trace — include arg.h for common_params_parse

    * fix: moe-trace — take output path from MOE_TRACE_OUT env, -o not in this arg set

    * fix: moe-trace — topk tensor is a strided view; copy full byte range and index by nb

    Sizing the host buffer as n_used*n_tokens under-allocated: ffn_moe_topk
    is a view over the argsort output, so nb[1] spans n_expert ids per row
    and ggml_backend_tensor_get writes the whole strided range (heap
    corruption, malloc corrupted-top-size abort mid-prefill).

    * feat: moe-trace simulator v2 — model upload bytes/token and miss/upload cost per policy

    * feat: mul_mat_id tolerates id=-1 (skip) on CPU and CUDA fallback path

    Groundwork for the hot/cold expert-pack split: an id of -1 means the
    routed expert is not owned by this pack. The op contributes a zeroed
    output row for that slot so hot-pack and cold-pack results merge
    additively. CUDA fast paths (mmvq_id/mmq_id/mmf_id) still assert
    non-negative ids and are handled next.

    * feat: id=-1 skip support in CUDA mul_mat_id fast paths + tests

    mmid.cu gains a generic kernel that zeroes the dst rows of (token,
    slot) pairs whose expert id is -1; mmq and mmf launch it after the
    shared mm_ids_helper (which already drops unmatched ids from its
    compact mapping), and mmvq launches it before its kernels, which now
    early-return instead of using a negative id as a channel index (out
    of bounds read otherwise). test-backend-ops gains skip_ids variants
    of MUL_MAT_ID covering the mmvq/mmq/mmf/fallback dispatch corners.

    * fix: skip_ids MUL_MAT_ID test cases were inside an #if 0 block

    * fix: mm_ids_helper compact map corruption when ids contain -1

    Negative ids inflated nex_prev for every expert, opening a phantom
    region at the head of the compact arrays that nothing wrote; the mmq
    quantize preprocessing iterates the flat range and read garbage row
    indices (illegal memory access). Skipped ids now occupy no compact
    position, ids_src1 is sentinel-filled, and the quantize gather/scatter
    kernels skip negative entries.

    * fix: mmvf id=-1 skip guard (float mul_mat_id vec path)

    Same treatment as mmvq: kernels early-return on a negative expert id
    instead of using it as a channel index, and the host launcher
    pre-zeroes the dst rows of skipped slots. Fixes wrong results (and a
    latent out-of-bounds channel read) for f16/f32 MUL_MAT_ID with -1 ids
    at small batch sizes.

    * fix: zero-init ids_dst before mm_ids_helper — garbage tail entries in the
    compact map caused pool-layout-dependent illegal memory accesses when ids
    contain -1 (tile-padded reads consumed uninitialized row indices)

    * feat: route MUL_MAT_ID with skip-capable ids away from mmq/mmf

    Ops whose ids may contain -1 announce it via op_params[0]; the CUDA
    dispatch then uses only the paths with verified skip support (mmvq
    for small batches, the general gather/scatter path otherwise).
    Large-batch mmq with sparse ids shows a pool-layout-dependent fault
    that resists isolation (all indexing audits pass; sanitizer and
    cuda-gdb unusable on the target driver); since the expert-pack
    design only decodes through packs, the safe route costs nothing in
    practice. mmq/mmf guards from earlier commits remain as hardening.

    * fix: op_params write in test — ggml_set_op_params_i32 is internal-only

    * feat: MoE expert cache loader — hot-pack build from routing profile

    init_moe_expert_cache() runs post-load: reads a moe-trace profile
    (GGML_MOE_CACHE_PROFILE) and slot count (GGML_MOE_CACHE_SLOTS), and for
    each CPU-resident MoE layer builds GPU-resident hot packs of the top-S
    experts plus i32 remap tables (hot: global->slot or -1; cold: global id
    or -1). Graph wiring (build_moe_ffn dual path) is the next commit; these
    tensors are unused until then, so this is behavior-neutral.

    * feat: MoE expert cache graph wiring — dual hot/cold mul_mat_id in build_moe_ffn

    When a layer carries hot packs, routed ids are remapped through
    moe_map_hot/cold (get_rows) and each expert projection runs as two
    skip-flagged mul_mat_id ops — hot pack on GPU, original tensors for
    cold — whose zero-padded outputs sum to the exact single-tensor
    result. Engaged for qwen35moe (separate gate/up/down, no expert
    scales); layers with merged gate_up, scales, or no packs use the
    unchanged path.

    * fix: flatten routed ids before map get_rows (batched-gather shape rule)

    * fix: topk ids are a strided view - cont before flatten for map lookup

    * fix: sched expert-copy path skips id=-1 (hot/cold expert split)

    * fix: restructure MoE pack dual path into full FFN chains per residency side

    Per-projection hot/cold interleave let the scheduler's split minimizer
    assign hot up/down matmuls to CPU, copying the GPU pack weights over
    PCIe every layer. Building one unbroken gate-up-swiglu-down chain per
    side keeps the hot pack on GPU; skipped (-1) rows stay zero through
    swiglu so a single add of the two chain outputs is exact.

    * feat: wire MoE expert cache into deepseek2 graph (GLM-4.7-Flash)

    * feat: add --moe-cache-profile and --moe-cache-slots flags

    Plumbed through llama_model_params; env vars remain as fallback so
    existing deployments keep working. Flags allow per-model settings in
    multi-model serving.

    * docs: fix moe-trace usage comment (output path is MOE_TRACE_OUT env)

commit cd72c28
Author: Anirban Kar <[email protected]>
Date:   Fri Jul 24 17:53:41 2026 +0530

    fix: restore closing brace lost in dequantize.cuh merge resolution

commit 34f893e
Merge: 40f2036 8f5ab83
Author: Anirban Kar <[email protected]>
Date:   Fri Jul 24 17:52:26 2026 +0530

    merge: sync upstream master into perf

commit 8f5ab83
Author: Matt Thompson <[email protected]>
Date:   Fri Jul 24 03:54:47 2026 -0700

    cohere2 moe template parser: enforce JSON schema for text responses if a response schema is provided (ggml-org#26018)

commit 0cea362
Author: Xuan-Son Nguyen <[email protected]>
Date:   Fri Jul 24 08:02:23 2026 +0200

    vendor: update subprocess.h (ggml-org#26061)

commit 40f2036
Author: Anirban Kar <[email protected]>
Date:   Sun Jul 19 04:34:24 2026 +0530

    feat: fused turbo MMA flash-attention decode (turbo4/3/2, GQA tensor-core path) (TheTom#4)

    * feat(fattn): fused turbo4 MMA decode path (opt-in) — based on the spiritbuun fork MMA approach, adapted to graph-rotated Q

    Port buun's fused turbo4 tensor-core (MMA) flash-attention DECODE kernel into
    the turbo fork as an OPT-IN path (GGML_TURBO_MMA_FUSED=1, default OFF), routing
    turbo4-K==turbo4-V, D in {128,256}, decode (Q->ne[1]<=4) onto the GQA-packed MMA
    path so KV is read once per head-group instead of once per query head.

    How it works:
    - fattn-mma-f16.cuh: add flash_attn_ext_turbo4_load_tile (dequant turbo4 blocks
      -> SRAM in the f16 row-major half2 layout) seeded with OUR Lloyd-Max centroids
      (turbo-quant.cuh:297, NOT buun's -0.2415xx table). Thread type_K/type_V through
      iter/process_tile/global flash_attn_ext_f16 (defaults F16 -> existing f16/q8 MMA
      byte-identical). For turbo: force nstages=0 (the cp.async multi-stage path would
      read raw turbo bytes as half2), pass RAW byte pitch nb11/nb21 (not /sizeof(half2)),
      and dequantize K/V in the load tiles. sizeof(block_turbo4_0)-driven pointer math
      (66B block, no rnorm) — never assumes a fixed offset.
    - fattn-mma-turbo.cuh + 14 instance files (7 reachable ncols pairs x D in {128,256}):
      host launcher reusing the f16 device kernel with type_K/type_V=TURBO4_0 and
      need_f16_K/V=false so launch_fattn does NOT pre-convert KV to f16.
    - fattn.cu: switch_ncols2 -> per-ncols2 dispatchers (only the 7 compiled instances),
      env latch, and the gate (Q untouched — our fork already rotates Q at the graph
      level, so NO inline FWHT / src swap, which would double-rotate Q).

    Results (Qwen3.6-35B-A3B turbo4, GQA8, D=256, 5090):
      depth   MMA      VEC+PDL   buun
      8192    213.8    188.5     200    (+6.9% vs buun)
      16384   207.6    171.7     193    (+7.5% vs buun)
      32768   191.3    141.1     187    (+2.3% vs buun)
    MMA holds flat at depth where VEC collapses; the gap vs VEC grows with KV length.

    Quality: Mean KLD vs f16 base = 0.008396 (== VEC baseline). The MMA path is NOT
    strictly token-identical to VEC — MMA and VEC accumulate the P*V (VKQ) reduction in
    f16 with different reduction trees, so a near-tie greedy token can flip (~1/25 on a
    hard tie; same irreducible f16-order effect that exists between base f16-MMA and
    f16-VEC, and within the VEC-vs-base "same-top-p" 96.3% noise floor). Because strict
    token-identity does not hold, the gate DEFAULTS OFF and ships as opt-in; VEC remains
    the untouched default/kill-switch.

    (cherry picked from commit 5450669510a5cd0a356a863923b057f2552c6fbb)
    (cherry picked from commit b3e51cf)

    * turbo4 MMA decode: default ON (GQA-packed tensor-core path, quality-neutral; GGML_TURBO_MMA_FUSED=0 kill-switch)

    (cherry picked from commit 726234b538194c644be4066e1413b91f9edf12e7)
    (cherry picked from commit 38dc665)

    * fattn: extend fused MMA decode to turbo3 + turbo2 (parity on turbo4; extends the MMA path to turbo3/2)

    The GQA-packed tensor-core decode path was turbo4-only; turbo3/turbo2 fell back to
    VEC and collapsed at depth (turbo3 tg32 224->124 from d2048->d32768), losing to
    spiritbuun there. Added flash_attn_ext_turbo3_load_tile (3-bit split index: 2 low
    bits from qs + 1 high bit from signs) and flash_attn_ext_turbo2_load_tile (plain
    2-bit), type-dispatched both the K and V MMA load sites, and routed the gate by
    K->type. is_turbo_kv already matches any non-f16 KV, so the kernel needed only the
    per-type tile loaders + instances (14 instance files now emit all three types).

    Correctness: MMA decode is bit-exact to VEC (Mean KLD @2048 chunks=8:
    turbo3 0.020278==0.020278, turbo2 0.041490==0.041490, turbo4 0.009296 unchanged).

    Decode tg32 (qwen3.6-35B-A3B, RTX 5090), MMA now flat at depth:
      turbo3  2k/8k/16k/32k = 224/225/217/203  (buun 193/193/183/178; was VEC 224/187/160/124)
      turbo2  2k/8k/16k/32k = 228/224/217/203  (buun 213/210/204/200; was VEC 229/218/203/183)

    turbo3/turbo2 now hold flat at depth (neither fork had them on the MMA path before). GGML_TURBO_MMA_FUSED=0 restores VEC.

    (cherry picked from commit 57ad5edd53a7fced0b99fecb99326132cbdb65d0)
    (cherry picked from commit 4e223ee)

    * fix(fattn): gate turbo2 fused-MMA decode to head_dim 128

    Tester @everson isolated a turbo2-only decode regression on RTX 5060 Ti
    (Gemma-12B, head_dim 256): turbo2/turbo2 -2.46% at 8K to -1.17% at 200K,
    fully restored by GGML_TURBO_MMA_FUSED=0 at every depth, while turbo3 was
    neutral and turbo4 exact parity. At 2-bit KV the fused path's GQA-pack
    saving is tiny while its dequant/no-pipeline overhead is unchanged, so on
    head_dim 256 it is neutral on high-bandwidth GPUs (Ornith-35B and a dense
    Gemma-4-12B on RTX 5090, both within noise) and only costs on
    bandwidth-limited cards.

    turbo2 fused remains a large depth win on dense head_dim 128 (Llama-3.1-8B
    on RTX 5090: +7% at 8K, +24% at 32K, +69% at 131K), so this gates turbo2
    fused to head_dim 128 only; head_dim 256 turbo2 falls through to VEC, which
    is the exact baseline path GGML_TURBO_MMA_FUSED=0 restored. turbo3 and
    turbo4 fused are unchanged at both head dims.

    Also corrects the stale "default OFF" gate comments to match the
    default-ON code.

    (cherry picked from commit 539ce5d)

    ---------

    Co-authored-by: TheTom <[email protected]>

commit 4cd54c6
Author: Anirban Kar <[email protected]>
Date:   Sun Jul 19 04:14:41 2026 +0530

    fix: allow mixed turbo/q8_0 KV cache types in CUDA flash-attention selection (TheTom#3)

    * fix: allow mixed turbo/q8_0 KV cache types in CUDA flash-attention selection

    Without GGML_CUDA_FA_ALL_QUANTS (the default), kernel selection
    rejected any K/V type mismatch. A turbo KV setup is almost always
    mixed (ctk q8_0 + ctv turbo2/3), so the flash-attention probe failed,
    FA was auto-disabled, and context creation either refused the
    quantized V cache outright or fell back to the non-FA path whose
    KQ buffer (~8.7 GiB at 64k ctx, ubatch 1024) OOMs at load.

    Allow exactly the mixed pairs that have FA template instances
    compiled in: turbo2/3/4 against each other, q8_0, and f16. Also gate
    turbo head-dim geometry (multiples of 64; 128 for turbo4) so shapes
    without a compiled instance report unsupported instead of asserting
    at dispatch.

    Forcing -fa on masked the bug (the probe is skipped); server
    deployments use fa auto and hit it on every load.

    * feat: accept turbo2/3/4 cache type names in llama-bench

    The common arg parser already accepts them for llama-completion and
    llama-server; llama-bench has its own name table and rejected -ctk/-ctv
    turbo values.

commit 9338207
Author: Anirban Kar <[email protected]>
Date:   Sun Jul 19 01:59:58 2026 +0530

    CUDA: add Q2_0 support (TheTom#2)

    Co-authored-by: Pasha Khosravi <[email protected]>

commit 170322f
Author: Anirban Kar <[email protected]>
Date:   Sat Jul 18 15:27:13 2026 +0530

    feat: TurboQuant KV-cache quantization — all backends (TheTom#1)

    * feat: TurboQuant KV-cache quantization — core types + CPU backend

    Port of the TurboQuant codec (arXiv 2504.19874, reference:
    TheTom/llama-cpp-turboquant) onto this fork's base: WHT-rotated polar
    quantization for the KV cache.

    - new types TURBO2_0/TURBO3_0/TURBO4_0 (KV, 2/3/4-bit blocks of 128)
      and TQ3_1S/TQ4_1S (WHT-rotated Lloyd-Max weight formats), renumbered
      for this tree's type table
    - GGML_OP_TURBO_WHT + ggml_turbo_wht() builder (forward/inverse
      Walsh-Hadamard rotation with sign arrays, InnerQ scale hook)
    - ggml-turbo-quant.c codec core, rotation data tables, CPU op +
      vec_dot paths, type traits, quantize-chunk wiring
    - CUDA/Metal/Vulkan kernel sources imported (wired in follow-ups)
    - verified: test-turbo-quant round-trip on CPU (cosine 0.986-0.996)

    * feat: turbo KV cache — graph wiring and CLI types

    - pre-rotate Q (forward WHT) at every cache-backed attention site when
      K is a turbo type; no-op otherwise
    - inverse WHT on attention output in both FA and non-FA paths of
      build_attn_mha (group size derived from K, contiguity enforced)
    - register turbo2/3/4 as --cache-type-k/--cache-type-v values
    Core scope: no InnerQ scaling, no head-dim padding — turbo KV requires
    128-aligned (or 64-group) head dims

    * feat: turbo KV cache — Metal backend (WHT kernel + FA dispatch)

    Wire the TurboQuant Metal backend host side and kernels on top of the
    CPU core already on this branch.

    Metal kernels (ggml-metal.metal):
    - Inlined turbo-wht.h (WHT sign arrays incl. half4 variants + FWHT
      butterfly + rotate fwd/inverse) and the turbo2/3/4 centroids.
    - quantize/dequantize_turbo2_0/3_0/4_0 (+_t4) and full-block cache.
    - kernel_turbo_wht (O(d log d) Walsh-Hadamard rotation op) and
      kernel_turbo4_dequant_f16 bulk prefill dequant.
    - kernel_set_rows_turbo/2/4 cache-quantize kernels + instantiations.
    - flash_attn_ext / flash_attn_ext_vec instantiations for symmetric and
      asymmetric turbo2/3/4 and q8_0<->turbo pairs.
    - TurboFlash two-pass kernels (p1/p2), default-disabled via env.

    Host side:
    - ggml-metal-device.cpp: get_pipeline_turbo_wht; flash-attn pipeline
      base names now encode both K and V types (k%s_v%s) so asymmetric K/V
      pairs resolve unambiguously. All existing FA kernel host_names in the
      shader renamed to match.
    - ggml-metal-device.m: TurboQuant compile-time env prep (4-mag LUT auto
      select, sparse-V, profile mode); supports_op accepts turbo K types and
      asymmetric turbo/q8_0 FA pairs; GGML_OP_TURBO_WHT.
    - ggml-metal-ops.cpp: GGML_OP_TURBO_WHT encode case + impl; asymmetric
      K/V assert relaxation; TurboFlash gating (use_turbo_flash, extra_tmp
      sizing, force-nonvec) + two-pass dispatch; +128 float FA smem for the
      turbo block cache.
    - ggml-metal-impl.h / -device.h / -ops.h: kargs (turbo_wht,
      turbo_flash_p1/p2), FC offsets, pipeline/op declarations.

    Adaptations vs the reference tree (older upstream vintage):
    - Reference intertwines separate TQ3_1S/TQ4_1S weight-quant work; only
      the turbo KV-cache lines are ported here.
    - set_rows_turbo dispatch selection is not wired: our upstream refactored
      get_pipeline_set_rows/kernel_set_rows_q32 to a different signature, and
      it is out of scope for this KV port. supports_op therefore does not
      claim CPY/SET_ROWS turbo support, so cache writes fall back to CPU;
      the set_rows_turbo shader kernels are present for when dispatch lands.
    - No InnerQ scale tensors touched (graph passes nullptr scale).

    * feat: turbo KV cache — CUDA backend (set-rows quantize, fattn vec dispatch, dequant)

    Port the TurboQuant CUDA backend from the reference implementation, adapted
    to this newer upstream vintage:

    - set-rows.cu: k_set_rows_turbo2/3/4 kernels (WHT rotation + norm-corrected
      PolarQuant KV write, InnerQ calibration hooks) + dispatch. turbo4 rnorm
      write dropped (field removed from block_turbo4_0 on this branch).
    - dequantize.cuh: dequantize_turbo2/3/4_0 and dequantize_tq3_1s/tq4_1s
      device functions.
    - convert.cu: turbo + TQ dequant cases in the fp16/fp32 contiguous and
      non-contiguous dispatch tables; warp-cooperative TQ4_1S dequant kernel.
    - fattn-common.cuh: vec_dot_fattn_vec_KQ_turbo2/3/4_0, dequantize_V_turbo*
      and get_vec_dot_KQ / get_dequantize_V dispatch entries.
    - fattn-vec.cuh: turbo K types take the float-Q path (Q_q8_1 off), turbo V
      uses the ne=4 quantized dequant path; extern decls for the 21 compiled
      K/V type combinations. Reference-side perf extras (shared-mem centroid
      LUT, sparse-V skip, nthreads tuning) intentionally not ported.
    - fattn.cu: turbo types accepted in kv_type_supported, vec kernel cases
      registered. Decode goes through the VEC kernel; prefill converts KV to
      f16 via the ported nc dequant path.
    - fattn-mma-turbo.cuh: reduced to a stub launcher. No typed MMA kernel
      exists in the reference either; the pre-existing template instances now
      compile against the stub and the dispatcher never selects this path.
    - ggml-cuda.cu: GGML_OP_TURBO_WHT dispatch + supports_op, SET_ROWS turbo
      gates (head_dim % 64, turbo4 % 128).
    - CMakeLists.txt: turbo fattn-vec instances added to the non-FA_ALL_QUANTS
      build.

    Verified on RTX 3060 (sm_86) with Bonsai-27B-Q1_0, partial offload, fa on:
    coherent generation for turbo2/3/4; perplexity over 4 chunks:
    f16 KV 7.9486 +/- 0.73, turbo3 KV 8.0261 +/- 0.74 (CUDA) vs 8.0279 (CPU-only).

    * feat: turbo KV cache — Vulkan backend (set-rows quantize, turbo3 FA dispatch, WHT op)

    - register turbo_wht.comp and set_rows turbo2/3/4 quantize variants in
      vulkan-shaders-gen; add dedicated DATA_A_TURBO3_0 flash-attn SPIR-V
      (scalar + coopmat1) with turbo3-only K/V bindings
    - copy_to_quant: 128-thread per-block set_rows path (normalize, randomized
      WHT, Lloyd-Max centroid quantize, subgroup pack), shared WHT tables
      across the three turbo widths
    - flash_attn_dequant: turbo2/3/4 centroid dequant macros wired into the
      FaTypeK/FaTypeV runtime switch (ids 43/44/45); f16 K/V aliases guarded
      out under DATA_A_TURBO3_0
    - ggml-vulkan: GGML_OP_TURBO_WHT pipeline + dispatch, turbo set_rows
      pipelines (required subgroup size 32), FA pipeline selection for
      turbo3, supports_op gates (128-elem blocks, turbo3 K/V symmetry,
      scalar/coopmat1 only — cm2 falls back to scalar)

    * fix: extern initialization warning and C linkage for wht group size

    CI builds with -Werror: defining the GGML_API-decorated global with an
    initializer warns on every platform. Plain definition in the C TU; the
    C++ consumer now declares it extern "C" (it previously referenced a
    mangled symbol).

    * feat: turbo2/turbo4 FA dequant for Vulkan

    - generalize the dedicated turbo flash-attn SPIR-V path from turbo3-only
      to all three tiers: DATA_A_TURBO_KV umbrella define in types.glsl gates
      out the f16/q4/q5/q8 K/V binding aliases in flash_attn.comp,
      flash_attn_cm1.comp and flash_attn_dequant.glsl for any turbo tier
    - flash_attn_dequant: per-compilation dequantize4 for DATA_A_TURBO2_0
      (2-bit centroids, fp16 norm + 32B idx) and DATA_A_TURBO4_0 (4-bit
      nibble idx, fp16 norm + fp16 aux + 64B) alongside the turbo3 one
    - vulkan-shaders-gen: register flash_attn_f32_f16_turbo{2,4}_0 scalar +
      coopmat1 variants via a per-tier loop
    - ggml-vulkan: FA pipeline selection picks the matching turbo SPIR-V for
      turbo2/turbo4 k_type (scalar + cm1), supports_op requires symmetric
      K/V per tier (turbo2/turbo2, turbo3/turbo3, turbo4/turbo4)

    * fix: bump RPC proto patch version for GGML_OP_TURBO_WHT

    * fix: export WHT group size via GGML_API for Windows shared builds

    * fix: HIP/MUSA portability for turbo kernels

    - map cudaMemcpyToSymbol/FromSymbol and __ballot_sync in vendor headers
    - pass explicit width to __shfl*_sync (HIP macros take 4 args)
    - drop unused warp_id locals flagged by nvcc -Werror

    * fix: drop SYCL turbo fattn-vec instances (no turbo dequant support in SYCL fattn)

    * fix: size vec_dot buffer by vec_dot_type and handle turbo/tq types in quantize test

    - tmp_q2 overflowed for types with vec_dot_type F32 (4 bytes per element)
    - skip turbo KV types: they quantize in the rotated domain, round trip
      does not reproduce the input by design
    - tq3_1s uses the 3-bit and lowbit thresholds

    * fix: add turbo fattn-vec instances to HIP and MUSA source lists

    * fix: add turbo fattn vec kernels to HIP VGPR ignore list

    The gfx908 build of the ncols=2 turbo3 vec kernels lands at 259 total
    VGPRs, slightly over the 256 gate. Register them like the other known
    high-pressure fattn kernels.

commit 0888217
Merge: 5e7f627 7d56da7
Author: Anirban Kar <[email protected]>
Date:   Fri Jul 17 20:02:48 2026 +0530

    chore: sync perf with upstream master

commit 5e7f627
Author: Anirban Kar <[email protected]>
Date:   Wed Jul 8 23:56:46 2026 +0530

    docs(readme): add usage + benchmark instructions for the MoE-offload optimizations

commit 5f83fbb
Author: thecodacus <[email protected]>
Date:   Thu Jul 2 12:42:55 2026 +0000

    ggml : size prefetch slots per layer and fix fallback use-after-free

    Profiling showed the 2-slot rotation stalls ~5.5ms per layer waiting for
    the down_exps upload: 3 tensors per MoE layer need 3 slots for a full
    layer of lookahead. Default is now 3 (one layer), configurable via the
    env var value, degrading to however many slots fit on OOM.

    Also fixes a use-after-free: on a failed slot regrow the repointed
    staging tensors kept dangling pointers into freed device memory, which
    graph reuse carried into later evals. Staging repoints are now restored
    right after kernel launch, slots are sized once from the graph max, and
    allocation happens before freeing.

    Qwen3.6-35B-A3B pp2048 on RTX 3060: 1643 -> 1880 t/s (mainline: 1143).

commit 1163cb3
Author: thecodacus <[email protected]>
Date:   Thu Jul 2 12:16:39 2026 +0000

    ggml : overlap offloaded expert weight uploads with compute

    At large batch sizes virtually every expert is used, so the per-layer
    routing-ids readback that mainline waits on buys nothing while forcing a
    full device sync per expert tensor (3x per MoE layer). Above a batch
    threshold, upload the full expert tensors through a second backend
    instance on the same device (own stream) with two event-ordered staging
    slots, so uploads for tensor N+1 overlap compute of tensor N.

    Qwen3.6-35B-A3B pp2048 on RTX 3060 (-ncmoe 26, ub 2048): 1383 -> 1663 t/s.
    Generation output verified token-identical; decode path unaffected.
    Opt-in via GGML_SCHED_PREFETCH_EXPERTS=1.

commit 20f5994
Author: thecodacus <[email protected]>
Date:   Thu Jul 2 09:44:53 2026 +0000

    llama : pin mmap-backed CPU weights for faster H2D uploads

    Wire the existing GGML_CUDA_REGISTER_HOST path back up: after model load,
    cudaHostRegister the mmap pages backing weights kept in system memory.
    Recovers pageable-copy losses when MoE experts are streamed to the GPU
    during prefill (n-cpu-moe): Qwen3.6-35B-A3B pp2048 1144 -> 1385 t/s on
    RTX 3060. Opt-in via GGML_CUDA_REGISTER_HOST=1, unchanged otherwise.
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