OpenVINO: Qwen3.5, memory optimization, and test-recurrent-state-rollback (llama/26952)
* OpenVINO backend: 1) enable gpt-oss moe on OV bk; 2) enable mxfp4 support
* OpenVINO backend: disable TOPK_MOE op test
* OpenVINO Backend: Add op FILL support
* OpenVINO backend: enable set rows with multi dims
* fix the name missmatch in setrow + view
* OpenVINO backend: enable op GGML_UNARY_OP_SIGMOID
* OpenVINO Backend: enable SQR & SQRT
* OpenVINO backend: 1) ensure unique node names for OpenVINO; 2) add org_src to recorde the src ggml tensor for OpenVINO dynamic shape infer
* OpenVINO backend: enable fallback for openVINO to CPU backend
* OpenVINO backend: fix accurace issue in gemma3n arch test
* fix mpt failed case
* OpenVINO backend: clean nodeinfo
* OpenVINO Backend: enable zero-size copy for view
* add concat ssm_conv in compute_dynamic_dim
enable qwen35
Fix after rebase
remove logging
* OpenVINO backend: disable EXP with FP32, which failed in op test. Root reason: the backend test initializes unary op inputs over a wide range, [-150, 150]. For FP32, exp(x) overflows around x ~= 88.7, so this test can randomly generate values right in or beyond the overflow region
* OpenVINO backend: fix CPY op test failed issue
* OpenVINO backend: fix GATED_DELTA_NET op test failed issue
* handle in-place op, handle qwen35 dynamic clearing of cache in cgraph
* handle qwen35 dynamic clearing of cache correctly
* Enable qwen35 dense multi seq
* Fix qwen35 9b gqa
* Fix after rebase
* Disable SOLVE_TRI
* openvino: fix NEOX RoPE accuracy on GPU stateful (mixed-rank Multiply)
In stateful mode the NEOX RoPE branch fed rank-3 data ([S, n_heads,
head_size]) into the Multiply against the rank-4 cos/sin tables
([1, S, 1, n_dims/2]). That mixed-rank broadcast is miscomputed by the
OpenVINO GPU plugin, corrupting the rotated Q/K and producing garbage
output (e.g. Phi-3-mini). Lift the data to rank-4 before the split/
Multiply so the operands are equal-rank, matching what the TYPE_NORMAL
branch already does. CPU and stateless paths are unaffected.
Phi-3-mini-Q4_K_M, wiki.test perplexity, GPU stateful:
before: PPL = 27120.43
after: PPL = 6.2263 (CPU reference: 6.2251)
* OpenVINO backend: 1) remove the unique name in llama.cpp; 2) add new ov name in ov bk; 3) fix issue in arch test & op test with latest code update
* OpenVINO Backenb: remove changes in llama.cpp
* Doc change (use x64 Native Tools Command Prompt for VS)
* Cleaner sentence
Co-authored-by: Copilot Autofix powered by AI <redacted>
* OpenVINO Backend: cache key upgrade includes all src name
* OpenVINO Backend: enable llama arch test on ci
* OpenVINO Backend: move parameter node creating from decoder into translate
* OpenVINO Backend: create extra input ov node move from decoder to translate
* fix for op regression due to is_model_splitted
* openvino: fix CPY writeback for recurrent state rollback
Detect the rollback conv/gdn state writeback CPY nodes structurally
instead of by tensor name, since the rollback path in
build_conv_state does not call cb() and left the nodes unnamed. Add
per-node runtime offsets (rs_slot_begin_*, rs_src_begin_*) so the
cached IR handles any kv head, sequence count and snapshot slot for
both the conv state and the GDN state writeback.
Assisted-by: GitHub Copilot
* qwen35 moe
* optimize MoE expert aggregation with ReduceSum
* Skip GET_ROWS inaccurate test
* openvino: fallback dynamic MUL_MAT_ID shapes
* OpenVINO Backend: fix error in arch test model mpt
* fix error caused by cpy in arch test model kimi-linear
* OpenVINO Backend: fix error in arch test model minimax-m3
* openvino: fix GPU mul_mat_id op tests
* ggml-openvino: add GGML_OPENVINO_RELEASE_WEIGHTS to reclaim host weight RSS on GPU
The OpenVINO weight Constants are zero-copy views into host buffers
allocated by the backend (ggml_aligned_malloc, anonymous memory). On GPU
the plugin holds its own device copy after compile_model, so these host
pages are dead weight for inference. For a 1B Q4_K_M model this leaves
~850 MB of host RSS resident that the GPU path never reads again.
Add an opt-in GGML_OPENVINO_RELEASE_WEIGHTS mode that madvise(MADV_DONTNEED)s
the registered host weight buffers once the model is compiled, dropping
their resident pages while keeping the mappings valid (ggml still owns the
lifetime; tensors still point in). Measured steady-state RSS drops from
~1555 MB to ~710 MB on Llama-3.2-1B-Q4_K_M (Arc iGPU) with unchanged
throughput and correct output.
The GPU backend uses a single dynamic-shape model for both prefill and
decode, so a graph is compiled once and reused; the only event that forces
a recompile is clear_caches() on backend teardown. The change therefore:
- releases on the first cache-hit (model compiled, plugin has its copy);
- pins the compiled-model cache across backend teardown so a later
context reuses it instead of recompiling against the dropped pages;
- fails loud (GGML_ABORT) on a cache-miss recompile or on a second model
load, both of which would otherwise read zeroed weights or silently
reuse the wrong compiled graph.
Scope/limitations (all fail loud, never silently wrong): GPU only (the CPU
plugin reads the host Constants at inference time), one model per process,
and stable graph shapes. This reduces steady-state RSS, not the transient
compile-time peak. All changes are confined to the OpenVINO backend.
* ggml-openvino: stream weight requantization to cut the compile-time RSS peak
requantize_to_buffers() dequantized the entire tensor to a temporary
std::vector<float> of n_elements before requantizing. For token_embd.weight
(128256 x 2048) that transient is ~1 GB (1B model) / ~2 GB (8B), and it is
the single largest contributor to the OpenVINO compile-time memory peak --
it also fires twice for token_embd (once at load, once at graph build,
because token_embd is loaded via a CPU/mmap buffer and not cached as an OV
weight extra).
Stream the dequant instead: process a fixed window of complete rows
(CHUNK_ROWS=256) into a small scratch buffer and quantize/convert each chunk
straight into the output buffers. The transient F32 footprint is now
CHUNK_ROWS*ne0 floats regardless of tensor size.
quantize_q8_0/q8_1 gain an optional block_offset arg (default 0) so a chunk
writes its weights/scales/zp at the correct block. Streaming is applied to
the Q8_0_C / Q8_1_C / F16 targets (the large requant cases); the u4 (Q4_0)
path keeps the whole-array call because it packs two weights per byte with
running zp ORs, and a fallback handles any future target whose block size
does not divide a row.
Measured peak RSS (cold compile, GPU): 1B 2868 -> 1809 MB (-1.06 GB);
8B 11618 -> 9608 MB (-2.0 GB). Output verified unchanged
("capital of France is Paris"); throughput unchanged. Unlike
GGML_OPENVINO_RELEASE_WEIGHTS this reduces the transient peak, not just
steady-state, and needs no env flag. All changes confined to the OpenVINO
backend.
* ggml-openvino: avoid redundant token_embd requantization at compile
token_embd.weight is referenced twice in the graph path: as the GET_ROWS
embedding (a CPU/mmap-buffer tensor) it was re-extracted/re-requantized on
every weight-node build, and is_model_splitted() built a full (naive) set of
weight nodes just to test name membership — each requant is a ~1-2 GB F32
dequant of the 262M-element embedding.
Two changes:
- Add collect_weight_names(): a name-only collector for topology checks.
is_model_splitted() now uses it instead of create_weight_nodes(cgraph,
true), so the splitted-check no longer triggers any weight extraction.
- Memoize weight nodes built from non-OpenVINO buffers in a process-lifetime
cache keyed by tensor->data. These tensors have no OV buffer context to own
a cached extra, so without this they were rebuilt on every (re)compile;
prefill and decode graphs now share one build (verified: 2nd graph hits the
cache instead of re-requantizing).
Peak RSS is unchanged (the streaming-requant commit already removed the F32
transient); this removes redundant compile-time work. Output verified
unchanged ("capital of France is Paris"). Confined to the OpenVINO backend.
* ggml-openvino: gate compile-memory optimizations behind GGML_OPENVINO_REDUCE_COMPILE_MEM
The streaming requantization and the non-OpenVINO-buffer weight-node cache
(plus the name-only is_model_splitted path that pairs with it) are now opt-in
via GGML_OPENVINO_REDUCE_COMPILE_MEM. When unset, requantize_to_buffers()
fully materializes the F32 buffer and weights are rebuilt per compile exactly
as before; when set, the streaming path and the cross-compile weight cache
are used.
Default off keeps behavior identical to upstream unless explicitly enabled.
Verified: flag off -> peak RSS 2800 MB (original), flag on -> 1810 MB; output
"capital of France is Paris" in both modes. (GGML_OPENVINO_RELEASE_WEIGHTS,
added earlier, remains a separate opt-in for the steady-state release.)
* ggml-openvino: add frontend model cache (GGML_OPENVINO_MODEL_CACHE_DIR)
The plugin-level ov::cache_dir caches the compiled blob keyed by the OV
model, but producing that model still runs the full frontend every time:
weight requantization (incl. the large token_embd F32 transient) and the
ggml->OV graph conversion. This adds an opt-in frontend cache keyed off a
fingerprint computed directly from the ggml cgraph, so a hit imports a
previously exported CompiledModel and skips requant + convert + compile
entirely.
Key (model-cache.{h,cpp}) = 64-bit FNV-1a of: graph topology (n_nodes + per
node op/name), a sampled per-weight fingerprint (name/shape/type + bounded
head+tail byte sample), and blob-affecting config (device, flash-attn, rope
params, REDUCE_COMPILE_MEM/stateful flags, OpenVINO version). A sidecar
manifest stores every weight's fingerprint and is re-verified on load, so a
sampled-hash collision cannot cause a wrong-model hit (verified: two
different quantizations of the same model produce distinct cache entries).
Flow (dynamic single-model path only; split models defer to ov::cache_dir):
on a verified hit, core.import_model() restores the CompiledModel and a
lightweight decoder is built with a names-only weight map (membership is all
the decoder needs for I/O mapping; weights live in the imported model). On a
miss, compile as usual then export the blob (atomic temp+rename, manifest
written first). The frontend cache supersedes ov::cache_dir, so CACHE_DIR/
CACHE_MODE are stripped from the config used for the cached compile and the
import — a blob compiled with cache_dir set cannot be re-imported.
Measured 8B Q4_K_M (GPU): full requant+convert+compile 15.3s -> import 6.3s
(~2.4x faster compile phase). Output verified unchanged on cold and warm,
standalone and combined with REDUCE_COMPILE_MEM + RELEASE_WEIGHTS. Default
off; confined to the OpenVINO backend.
* ggml-openvino: harden frontend model cache correctness
The frontend model cache imports a previously exported CompiledModel keyed by a fingerprint of the ggml graph, weights, and blob-affecting config. The original key covered device, stateful execution, REDUCE_COMPILE_MEM, RoPE params, OpenVINO version, topology, and sampled weights, but missed runtime/frontend toggles that can change the lowered graph or the I/O binding contract. That made it possible to reuse a blob produced under a different OpenVINO backend configuration.
Add a small extra-config helper for the dynamic model-cache path and fold in the effective values of GGML_OPENVINO_DISABLE_KV_SLICE and GGML_OPENVINO_MANUAL_GQA_ATTN. MANUAL_GQA_ATTN is keyed by the behavior that actually takes effect: an explicit env value wins, otherwise GPU defaults to enabled and other devices default to disabled. This matches flash_attn_ext lowering and avoids unnecessary cache splits for equivalent configurations while separating genuinely different attention graphs.
DISABLE_KV_SLICE is also included because it changes the KV-cache tensor shape/output binding strategy used around imported models. Even when weights and graph topology are identical, switching this flag should not inherit a CompiledModel cache entry created for a different binding mode.
Also make cache artifact publication cleaner: write manifest.tmp and blob.tmp, publish the blob first, and publish the manifest last. Cache hits already require both blob and a verified manifest, so making the manifest the final visible artifact avoids leaving an apparently complete manifest for a failed or interrupted blob export. Temporary files are removed on the handled failure paths.
While touching this path, fix the indentation of the non-imported compile branch so the cache miss flow is easier to review. Behavior is otherwise unchanged: verified hits still import, misses still create weights, convert, compile, export, and create the infer request normally.
* ggml-openvino: add memory optimization umbrella switch
Add GGML_OPENVINO_MEMORY_OPTIMIZE as a single opt-in switch for the OpenVINO backend memory-saving paths. The existing fine-grained GGML_OPENVINO_REDUCE_COMPILE_MEM and GGML_OPENVINO_RELEASE_WEIGHTS variables remain supported and explicitly override the umbrella switch when set, so users can still bisect or disable one side of the optimization independently.
Centralize the policy in ggml_openvino_reduce_compile_mem_enabled() and ggml_openvino_release_weights_enabled(device). The umbrella switch enables compile-memory reductions everywhere REDUCE_COMPILE_MEM is used today: streaming requantization, non-OV weight-node caching, split-model weight-name collection, and the frontend model-cache fingerprint. On GPU it also enables host weight-buffer release unless GGML_OPENVINO_RELEASE_WEIGHTS is explicitly set.
Keep host weight release GPU-only because it relies on the plugin holding its own device copy after compile_model. Update the fail-fast diagnostic and comments to mention GGML_OPENVINO_MEMORY_OPTIMIZE, so users who enable the umbrella switch get accurate guidance if a later cache-miss recompile would read released host weight pages.
* ggml-openvino: rename compiled model cache env
Rename the frontend export/import cache environment variable from GGML_OPENVINO_MODEL_CACHE_DIR to GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR. The cache stores blobs produced by ov::CompiledModel::export_model() and restores them with core.import_model(), so the new name distinguishes it from GGML_OPENVINO_CACHE_DIR, which configures OpenVINO plugin-level ov::cache_dir.
Update the registered env var, the cache-directory lookup, and comments around the frontend compiled-model cache. The old GGML_OPENVINO_MODEL_CACHE_DIR name is removed rather than kept as a fallback so there is a single spelling for the new option.
* docs: document OpenVINO memory optimization env vars
Add runtime configuration entries for the newly recognized OpenVINO environment variables.
Document GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR as the frontend compiled-model cache used to export and import compiled blobs for matching single-graph models.
Document GGML_OPENVINO_MEMORY_OPTIMIZE as the umbrella switch, including how GGML_OPENVINO_REDUCE_COMPILE_MEM and the GPU-only GGML_OPENVINO_RELEASE_WEIGHTS override or inherit from it.
* ggml-openvino: fix Qwen3VL crash and deepstack correctness bug
1. GGML_OP_PAD was missing from compute_node_dynamic_dims(), causing a crash
on decode for models that pad the token embedding (n_embd -> n_embd_inp).
PAD never reorders/merges dims, so it keeps the same dynamic dim index as
its source.
2. process_view_input_new() chained VIEW inputs through src[0] (the
immediate op-graph parent) using offsets treated as relative to that
parent. But ggml_tensor::view_offs is always absolute from the true root
allocation (ggml collapses VIEW-of-VIEW chains internally). For the
per-layer deepstack view ("embd (view)", whose src[0] is "embd" - itself
an already-narrowed, zero-offset VIEW of the padded root, with the SAME
ggml shape as the deepstack view but a different absolute offset), this
caused an out-of-bounds re-slice that silently fell back to returning the
wrong (already-resolved sibling) tensor. In practice every deepstack ADD
ended up adding the real base token embedding into the residual stream
instead of zero, corrupting generation ("Hello my name is
1000000..."
instead of coherent text). Fixed by detecting this pattern (same shape as
the immediate src, different absolute offset) and re-slicing directly
from the untouched root tensor using the innermost view's absolute
offset.
Also adds a GGML_OPENVINO_DEBUG_NODE=<name1>,<name2>,... env var that attaches
extra debug Result nodes for arbitrary intermediate tensors, without binding
them to any ggml buffer (avoiding the risk of reading a ggml buffer that has
since been overwritten by a later in-place op). This was instrumental in
diagnosing bug #2 above and is left in as a general-purpose debugging aid.
* ggml-openvino: fix IMROPE inp_pos padding for NPU static shapes
IMROPE's inp_pos tensor packs 4 stacked t/h/w/e position planes into
ne[0] = 4*n_tokens instead of one value per token. On NPU's static-shape
path, inp_pos was padded/shaped as if it held a single plane, which
interleaved padding across the 4 planes and desynced later reshapes
from the rest of the (chunk_size-wide) graph.
- add GgmlOvDecoder::get_inp_pos_n_planes() to detect IMROPE's 4-plane layout
- get_graph_input_shape(): size inp_pos as n_planes * chunk_size (prefill)
or n_planes (decode) instead of assuming 1 value per token
- get_ov_input_tensor_static_prefill(): pad each plane to chunk_size
independently instead of one flat block
- get_ov_input_tensor_static_decode(): copy n_planes contiguous values
instead of asserting/copying a single scalar
* disable test-llama-archs tests.
* openvino: gate fallback with env var
* Revert changes in test-llama-archs
* Apply editor config
* reject CPY with quantized destination as unsupported
---------
Co-authored-by: Xuejun <redacted>
Co-authored-by: Mustafa Cavus <redacted>
Co-authored-by: virajwad <redacted>
Co-authored-by: Copilot Autofix powered by AI <redacted>
Co-authored-by: suryasidd <redacted>
Co-authored-by: Mustafa Cavus <redacted>
Co-authored-by: Ravi Panchumarthy <redacted>
Support host pinned mem to improve SYCL Host-to-Device Memory Access (llama/26789)
* support host pinned mem, ggml_backend_sycl_host_buffer_type_get_max_size,
* fix the thread-safe issue
ggml-cpu/ops: vectorize flash-attention V-cache F16 to F32 conversion (llama/26947)
Co-authored-by: jinzihao <redacted>
gguf : harden loader against malformed tensor dims and metadata types (llama/25596)
* gguf : harden loader against malformed tensor dims and metadata types
* gguf: address review on malformed-metadata hardening
- report the expected vs. actual type when general.alignment is not u32
- use ggml_nelements() > 0 for the zero-element guard and keep the
representability checks visually aligned
- add test-gguf cases for a wrong-typed alignment key and a zero-dim
tensor (both used to crash: assert-abort and SIGFPE respectively)
Ran tests/test-gguf: 164/164 pass. Used an AI assistant to help draft
these edits; reviewed and verified by me.
* cont : less comments
Co-authored-by: Georgi Gerganov <redacted>
---------
Co-authored-by: Georgi Gerganov <redacted>
kleidiai: Add runtime feature detection mechanism for aarch64/kleidiai (llama/26076)
* Add runtime feature detection mechanism for aarch64/kleidiai
Signed-off-by: Jonathan Clohessy <redacted>
* Address Review Comments
Signed-off-by: Jonathan Clohessy <redacted>
* Add log warning for NSMC reserved value
Signed-off-by: Jonathan Clohessy <redacted>
* Address review comments
Signed-off-by: Jonathan Clohessy <redacted>
* Fix Rebase, move code from cpu-feats to ggml-feats
Signed-off-by: Jonathan Clohessy <redacted>
* Address naming of runtime feature struct
Signed-off-by: Jonathan Clohessy <redacted>
---------
Signed-off-by: Jonathan Clohessy <redacted>
opencl: use flat mv q5_k when weight exceeds image1d_buffer_t limit (llama/26880)
CUDA: only disable CUDA graphs when mul_mat_id actually needs a stream sync (llama/26802)
opencl: transpose the K tile in local memory for FA prefill kernels (llama/26428)
ggml-webgpu : refactor several wgsl files and simplify flash_attn wgsl. (llama/26134)
metal : fix NORM/RMS_NORM for row lengths that leave a partial simdgroup (llama/26708)
ggml_metal_op_norm sized the threadgroup with
`nth = std::min(nth, args.ne00_t)`, which can leave nth not a multiple of
the simdgroup size. The kernels finish their row reduction with a
cross-simdgroup step where each lane of the last simdgroup reads one
per-simdgroup partial sum out of shmem_f32:
if (tiisg == 0) { shmem_f32[sgitg] = sumf; }
threadgroup_barrier(mem_flags::mem_threadgroup);
sumf = shmem_f32[tiisg];
sumf = simd_sum(sumf);
When the last simdgroup is partial it has fewer lanes than the
threadgroup has simdgroups, so the tail of the partial sums is never
read and the row sum is too small. For ne00_t = 33 nth becomes 33: two
simdgroups, but only one lane in the second, so one of the two partial
sums is dropped. The mean and variance are then wrong for the whole row.
Round ne00_t up to a whole number of simdgroups instead. Rounding up
rather than dropping the clamp keeps the threadgroup as small as
possible: deleting the line would raise nth to the next power of two
(ne00_t = 544 -> 1024 instead of 544), which costs idle lanes on 26 row
lengths below 8192 that were already correct, including 1536 and 3584.
GGML_OP_NORM is affected as well as GGML_OP_RMS_NORM - both dispatch
through ggml_metal_op_norm.
No mainstream LLM hidden size hits this: ne00_t is ne00/4 on the
vectorized path, so 4096, 8192, 2048 and friends all give a multiple of
32. It is reachable from other norm shapes, e.g. 320-channel norms.
Add NORM and RMS_NORM cases for ne0 = 33, 132 and 260 across the
existing eps values. 33 exercises the scalar path and 132/260 the
vectorized one, since only those divide by 4.
Before, on M3 Pro:
test-backend-ops test -b MTL0 -o NORM 25/50
test-backend-ops test -b MTL0 -o RMS_NORM 26/51
After:
test-backend-ops test -b MTL0 -o NORM 50/50
test-backend-ops test -b MTL0 -o RMS_NORM 51/51
test-backend-ops test -b MTL0 13943/13943
sycl : Support DSv4 OPs: LIGHTNING_INDEXER,DSV4_HC_COMB,DSV4_HC_POST,DSV4_HC_PRE (llama/26568)
* support DSv4 OPs: LIGHTNING_INDEXER,DSV4_HC_COMB,DSV4_HC_POST,DSV4_HC_PREwq
* update ops.md
* fix format issue
metal : avoid `threadgroup` matrix array instantiation in kernel_lightning_indexer (llama/26646)
- In MSL, declaring an array of matrix types like `threadgroup half4x4` causes
a 'no matching constructor' compilation error because MSL matrix types do not
have zero-argument default constructors and threadgroup variables cannot have
initializers.
- Fix this by declaring a POD `threadgroup half` array instead and casting
to `threadgroup half4x4 *` for matrix indexing.
Signed-off-by: JamePeng <redacted>
vulkan: fix submission batching size, add debug tools for diagnosing causes of DeviceLost drivers errors (llama/26371)
* vulkan: add debug tooling to get more information about a DeviceLost error
* fix submission threshold applied too late
* use logging macros, throw instead of aborting
* clean up circular dependency
whisper : heap out-of-bounds read in log_mel_spectrogram on very short audio (#3956)
log_mel_spectrogram reflect-pads the start of the audio buffer by reading 200 samples from samples[1], with no check that the input has that many samples. Audio shorter than 201 samples reads past the end of `samples` (heap out-of-bounds read); the existing minimum-length check runs later, in whisper_full_with_state, after this access.
Clamp the reflected count to the available input. Normal-length audio (n_samples >= 201) is unchanged.
whisper,parakeet : reject invalid n_dims in tensor header to prevent stack-buffer-overflow on malformed model files (#3957)
* fix: reject invalid n_dims in tensor header to prevent stack-buffer-overflow on malformed model files
* Validate n_dims value in model file loading
Add error handling for invalid n_dims in model file.
vulkan: Introduce driver version check for Windows Intel GPU to mitigate crashing (llama/25192)
* Removed crash guard for Intel
Crash fixed from driver 32.0.101.8860
* Added driver version check for windows
* Change to convert from driverVersion rather than string
* No need to use signed
* Refactor
* allow GPU other than Xe2+
* adjusted function body position
ggml-webgpu: improve flash_attn_vec for quantized KV at long contexts (llama/25956)
* improve fa of quantized kv cache
* Fix some bugs and some comments.
* fix v type check and some comments
* Fix build error caused by rebasing
* editorconfig checking pass
sync : ggml (#3962)
* hexagon: tiling, tracing and optimizations for unary ops (llama/25474)
* hexagon: tile wide rows in pointwise unary ops to avoid VTCM overflow
* unary: reject permuted tensors for now (not used by models)
* hex-unary: replace divs with fastdiv
* hex-unary: add vtcm layout and host computed kernel params
* hex-unary: move fastdiv init into kernel params
* hex-unary: add specialized thread functions to improve generated code
* hex-unary: tracing instrumentation for unary ops
* hex-unary: factor out hvx kernels, streamline and remove more duplication
* ggml-hexagon: fix std::min collision with Windows min macro
* hex-cmake: make lto build happy
---------
Co-authored-by: Max Krasnyansky <redacted>
* ggml : process data in smaller chunks in CUDA ggml_top_k() and ggml_argsort() to reduce temporary buffers memory usage (llama/24776)
* ggml : process data in smaller chunks in CUDA ggml_top_k() implementation to reduce temporary buffers memory usage
* ggml : allocate tmp_dst only only once before the loop
* chore : whitespaces
Co-authored-by: Georgi Gerganov <redacted>
* ggml : use chunked processing in both CUDA CUB top-k and argsort implementations
* chore : separate argsort_f32_i32_cuda_bitonic() call from return statement
Co-authored-by: Johannes Gäßler <redacted>
* chore : replace ternary operators with min/max
---------
Co-authored-by: Stanisław Szymczyk <redacted>
Co-authored-by: Georgi Gerganov <redacted>
Co-authored-by: Johannes Gäßler <redacted>
* opencl: cluster-parallel decode FA for Adreno (llama/25473)
* ggml-et: Initial ET backend (llama/24179)
* ggml-et: Add performance logging
* ggml-et: Quants helpers
* ggml-et: Add MUL_MAT kernel
* ggml-et: Add ROPE kernel
* ggml-et: Add RMS_NORM kernel
* ggml-et: Add GLU kernel
* ggml-et: Add SOFT_MAX kernel
* ggml-et: Add GET_ROWS kernel
* ggml-et: Add CONT kernel
* ggml-et: Add SET_ROWS kernel
* ggml-et: Add MUL_MAT_ID kernel
* ggml-et: Build et kernels as part of ggml
* ggml-et: Embed kernels with fs fallback
* ggml-et: Build fixes
* ggml-et: Add MUL_MAT F32xF32 op
* ggml_et: Add MUL_MAT_ID op
* ggml-et: Disable offloading for debug
* ggml-et: Refactor out block ops
* ggml-et: ggml backend API changes
* ggml-et: Add RESHAPE/TRANSPOSE to supported
* ggml-et: Add CONT_F16
* ggml-et: Add supported ops doc
* gglm-et: Initial doc
* ggml-et: Remove runtime import hacks
We can now import the runtime by a simple find_package(), so we
can cleanup the CMakeLists.txt.
* ggml-et: Fix GET_ROWS kernel
Fix lost batch dimension.
Also clean vibe-comments.
* ggml-et: Fix SET_ROWS kernel
Remove incorrect broadcasting guard.
* ggml-et: Use custom instruction for fp32->fp16
* ggml-et: Vectorize set_rows fp32->fp16
* ggml-et: Fix ROPE kernel (yarn)
ggml-et: fix et_logf
WIP: Fix ramp
WIP: fix ROPE!
* ggml-et: Better sinf
* ggml-et: Fix SOFT_MAX
Add `max_bias` and `sink` support.
* ggml-et: Fix CONT
Reorder from contiguous write to read with atomic stores.
* ggml-et: Fix elmap kernel
Remainder handlin
* ggml-et: Fix MUL_MAT MUL_MAT_ID remainders
* ggml-et: Fix ET-SOC reference
* ggml-et: Fix embed kernels scripts for old python
This allows GGML-ET to build on pre-3.8 python.
* Add sysemu support with compile time flag `-DGGML_ET_SYSEMU=ON` (llama/6)
* Example using ET-Soc-1 emulator configuration
Example usage:
```bash
cmake -B build -DGGML_CUDA=OFF -DGGML_ET=ON -DLLAMA_CURL=OFF -DGGML_CCACHE=ON
cmake --build build --config Release -j $(nproc)
time ./build/bin/test-backend-ops
./build/bin/llama-server \
--model Qwen3-0.6B-Q8_0.gguf \
--alias Qwen3-0.6B-Q8_0 \
-fa 0 \
--ctx-size 1024 \
--no-warmup \
--host 127.0.0.1 \
--port 8080
```
* build: proper dep tracking for kernels
* support host using MOLD linker
* initial multi core GET_ROW F32 implementation
* vectorized q8 dequant
* wip: cland warning clenaups and initial logging refactor
* wip: message default message cleanup
* chore: message cleanups
* cmake cleanup
* migrate to use platform provided functions
* cmake back into subdir
* support et_print() in kernels
* fix: repair kernel building
* perf: operations run async by default
* debug: proper kernel dep tracking and error detection on kenrel launch
* fix: kernel binary dep tracking and fixing get_rows_f32 erroring
* perf: back to doing async kernel runs by default
* perf: vectorize and parallel device memset
* merge matmul work
* misc: align allocation and enable all offload
* misc: delete deadcode and respect memory limits
* fix: repair tensor debug print
* fix: loosen RMS_NORM op percision
* feat: Q4_0 GET_ROWS
* perf: FP32 MUL_MAT using TensorFMA
* update limitations
* perf: redue L1 load in compute_block_dot_product_q8_0
* feat: save kernel mapping (name to id) when profiling is enabled
* chore: memops cleanup
* perf: parallelize softmax by rows
* perf: vectorize 2nd phase of softmax
* perf: ban GET_ROWS from offloaded
* perf: vectorize and non-atomic for eltwise ops and sub support
* perf: vectorize normal rope
* perf: glu runs in parallel
* merge: manually merge saqib's work on kernel fixes
* perf: more vectorized RoPE
* perf: parallelize mul_mat_id
* perf: parallelize set_rows_f32
* perf: vectorize softmax
* feat: support kernel fusion and fuse RMS_NORM + MUL
* fix: mostly resolve test-backend-ops failure in SOFT_MAX and ROPE
* fix: bump max rope dims for gemma
* feat: GeGLU and SCALE support to fully offload Gemma
* perf: faster device memset
* feat: get_rows supporting Q4_K and avoid cont cache coherent issues
* better F32 MM
* feat: NORM for ET backend
* feat: SQR for ET backend
* feat: UNARY on ET
* feat: el_map support broadcasting for ET
* feat: SUM_ROWS in ET backend
* feat: more ops in ET backend
* feat: WKV* operators in ET backend
* perf: parallelize operators across cacheline instead of row
* perf: parallelize get_rows on cacheline
* wip: baseline FlashAttention for ET backend
* wip: enough FA and CPY f32->f16 to run llama 3.1 fully offloaded with FA on
* feat: f16 x f16 -> f32 MM using matrix engine
* wip: f16 FlashAttention using matrix engine
* wip: clean up
* feat: barriers
* perf: optimize FA_F16 in ET
* perf: vectorize pack_k_for_transpose16
* perf: prefetch next loop matrix tile
* perf: FlashAttention 2nd MM uses TensorFMA and optimizations
* cleanup: flashattention reorg
* perf: optimizations and fixes
* feat: L2SCP API and make FlashAttention support DV = 256 for gemma
* perf: parallelize norms beyond single row
* feat: GATED_DELTA_NET support and relaxed L2_NORM requirment
* feat: loosen RMS_NORM, NORM, ROPE contingous req too
* feat: repeat supports brocasting on dim 0 and loosen cont check
* feat: FILL and DIAG operator
* feat: loosen UNARY support chcek
* feat: TRI support
* feat: SOLVE_TRI support
* feat: basic SET support
* feat: loosen CONT req
* perf: fp16_to_fp32 use ASM
* feat: IMROPE support
* feat: PAD support
* feat: global barrier
* fix: view must live on the same backend as backing tensor
* feat: relax CONCAT in ET backend
* feat: dead simple CUMSUM implementation
* feat: basic SSM_CONV support
* feat: loosen CONCAT req
* feat: relax GATED_DELTA_NET and add SET support proper
* cleanup: cleanup LCM math
* feat: SWIGLU single input
* feat: SSM_SCAN support
* feat: el_map supports non aligned tensors in best effort
* feat: basic GROUP_NORM support
* feat: loosen MUL_MAT capablities slightly
* feat: loosen MUL_MAT and GET_ROWS and add IM2COL
* feat: special case for softmax 1x1x1x1
* feat: loosen SOFT_MAX req in ET backend
* fix: el_map unaligned acse fixes
* perf: optimize zero_acc_vec in flash_attn_ext_f16_me
* perf: use hart 1 for packing in MM and FA for FP16
* feat: kernel semaphore
* perf: better instruction sequence in FlashAttention
* fix: gated_delta_net with proper masking
* perf: better parallelization for GATED_DELTA_NET
* perf: parallelize SSM_CONV over nr
* perf: vectorize SSM_CONV
* perf: optimize MUL_MAT for q8
* feat: support Gemma 4
* fix: support multi-device
* feat: broader GLU support
* feat: unary ops supports view
* fix: repair fp16 MM using matrix engine
* perf: handle large N GEMV better
* perf: better q8_0 MM
* perf: better set_rows
* add back deleted files
* fix: repair after merge
* feat: POC version of uberkernel
* feat: RMS_NORM in uberkernel
* feat: add more kernels into usage
* chore: clean up uberkernel compilation
* perf: faster flash attention
* perf: opt flash attention for large seq length
* feat: loosen op bounds. clamp and mean support
* perf: vectorize ssm_scan
* perf: slightly faster FA
* perf: FlashAttention parallel MM and load
* perf: fuse Q8 MM and ADD
* feat: basic conv kernel for ET
* softMAx_test
* set_rows_f32
* get_rows and cont
* testing
* set_rows_exp
* Junk addition
* Narrowing the issue
* Update flash_attn_ext_f16_me.c
Focusing FA_ext_f16_me
* test
* Eviction updated
* Detailed cache eviction debug
* mulmat
* removeal of `BUILD_FOR_UBERKERNEL` flag
* cleaning...
* fix: balance FCC0 count
* feat: implement mul_mat and mul_mat_id for Q4_0 type
* optimize uberkernel plan upload
* add mul_mat q4 into uberkernel
* enable gating flush to just uberkernel
* update docs for ET
* update op support for ET
* et-backend: optimize Q4_0 and Q8_0 mul_mat_id row accumulations
* et-backend: specialize mul_mat_id kernels for Q4_0 and Q8_0
* et-backend: fix RoPE YaRN corr_dim formula and handle degenerate inputs
* test-backend-ops: add DeepSeek-V2-Lite RoPE test coverage
* et-backend: add Q4_0 mul_mat matrix-engine kernel using TensorFMA32
* et-backend: vectorize Q4_0 matrix-engine dequantization
* et-backend: support hybrid matrix/vector engine execution for Q4_0 mul_mat tail
* et-backend: run partial-N tiles on matrix engine for Q4_0 mul_mat
* et-backend: route Q4_0 mul_mat N < 53 to vecdot for better prefill latency
* Update uberkernel.c
* Update unary_f32.c
* gemma 4
* bisect gemma4: enable scale_f32 only
* bisect gemma4: +rms_norm_f32
* bisect gemma4: +rms_norm_mul_f32
* bisect gemma4: disable rms_norm_mul_f32 -- BREAKS OUTPUT
* bisect gemma4: +rope_f32 (skip rms_norm_mul)
* bisect gemma4: +el_map_f32
* bisect gemma4: +softmax_f32
* bisect gemma4: +get_rows_f32
* bisect gemma4: +glu_f32
* bisect gemma4: +mul_mat_f32 +mul_mat_f32_matrix_engine
* bisect gemma4: +mul_mat_f16 +mul_mat_f16_matrix_engine
* bisect gemma4: +mul_mat_Q8_0 +mul_mat_Q4_0
* bisect gemma4: +flash_attn_ext_f32 +flash_attn_ext_f16_me
* bisect gemma4: +mul_mat_id_f32
* bisect gemma4: +sum_rows_f32
* bisect gemma4: +cont_f16
* bisect gemma4: +fill_f32
* bisect gemma4: +unary_f32 (all ops re-enabled except rms_norm_mul)
* Update rms_norm_mul_f32.c
* bisect2 gemma4 n64: +scale_f32 only
* bisect2 gemma4 n64: +rms_norm_f32 +rope_f32
* bisect2 gemma4 n64: +rms_norm_mul_f32 (with ET_UBERKERNEL eviction fix)
* bisect2 gemma4 n64: +el_map +get_rows +glu +softmax (skip rms_norm_mul)
* bisect2 gemma4 n64: all ops enabled except rms_norm_mul
* bisect2 n64: test unary+cont+fill+sum_rows (no mul_mat/flash_attn)
* bisect2 n64: +mul_mat_f32 +mul_mat_f32_matrix_engine
* bisect2 n64: +mul_mat_f16 +mul_mat_f16_matrix_engine
* bisect2 n64: +mul_mat_Q8_0 +mul_mat_Q4_0
* bisect2 n64: +mul_mat_Q8_0 only (disable Q4_0)
* bisect2 n64: +mul_mat_Q4_0 only (Q8_0 breaks)
* bisect2 n64: +mul_mat_id +flash_attn_ext (skip Q8_0)
* run-3: matmul + rms_norm_mul
* run-4
* Revert "run-4"
* run5
* changes after cleanup
* cleanup before upstream
* restrict changes into ET backend
* move kernel embedding from Python to CMake
* move uberkernel gen into CMake
* apply clang format
* update CMake style
* update to match C and C++ style
* use source ggml and quant headers instead of ET's
* MROPE support
* absorb view ops into same branch as none
* fix bad rebase
* add marty1885 to codeowners
* oops
* remove redundant newline
* fix CI editor warnings
---------
Co-authored-by: Vidas <redacted>
Co-authored-by: Gianluca Guida <redacted>
Co-authored-by: Gianluca Guida <redacted>
Co-authored-by: ubergarm <redacted>
Co-authored-by: SaqibAkram-10xE <redacted>
Co-authored-by: Rehan Qasim <redacted>
* hexagon: improve ARGSORT performance for small tensors (llama/25512)
* hex-sort: add efficient bitomic sort in hvx regs up to 1024 elements
* hex-sort: fix inverted vrors
* hex-sort: specialize sort functions for the common cases
* hex-sort: add tracing and local context
* opencl: add int8 dp4 dense and MoE prefill optimization for Adreno GPUs (llama/25537)
* opencl: add int8 dp4 dense and moe GEMM
* opencl: refactor
---------
Co-authored-by: Li He <redacted>
* Vulkan: route large matmuls to medium tile on Adreno (llama/24877)
* [Vulkan] Fixes llama-cli breaking over longer promts sizes
The llama-cli was breaking for longer promts sizes for q4_0 quantized networks. Causing due to insufficient shared memory.
* Removed the un-used Adreno device
* Updated matmul for small pipeline.
* ggml : add GGML_OP_LIGHTNING_INDEXER that implements DeepSeek V3.2/V4 lightning indexer (llama/24231)
* ggml : add GGML_OP_LIGHTNING_INDEXER that implements DeepSeek V3.2/V4 lightning indexer
* ggml : remove scale parameters from lightning indexer OP, add f16 mask parameter
* tests : add GGML_OP_LIGHTNING_INDEXER tests
* ggml : bump RPC version
* chore : check if lightning indexer input tensors are not transposed
* tests : count flops instead of bandwidth in lightning indexer test
* chore : add missing const
* chore : whitespace
* ggml : renamed variables in CPU lightning indexer implementation
* ggml : fix lightning indexer mask broadcasting
* tests : tests for lightning indexer mask broadcasting
* chore : whitespace
* llama : use GGML_OP_LIGHTNING_INDEXER in DeepSeek V3.2 and DeepSeek V4 models
---------
Co-authored-by: Stanisław Szymczyk <redacted>
* cuda: Don't crash when querying memory on device with no free memory. (llama/25157)
If a Cuda device has no or limited available memory, the actual call
to cudaMemGetInfo() itself can cause a fatal crash due to a cuda out
of memory error (there is not enough memory to actually query memory)
This causes an issue because we query memory for all devices at
startup even if the user isn't trying to use the device for inference.
Fix this by making the error non-fatal and assigning zero total/free
memory to the device. This will have the downstream effect of the fit
algorithm not trying to put any layers on it, which is desired outcome
vs hard crashing.
this also prevents crashes in cuda enabled builds when user explicitly
passes '-dev none'
* gguf : reject empty metadata keys (llama/24917)
* sycl: add Q2_K to DMMV reorder path (llama/25064)
Signed-off-by: Todd Malsbary <redacted>
* sycl: add fused top-k MoE (llama/25217)
* sycl: add fused top-k MoE
* sycl: address review: GGML_SYCL_ENABLE_FUSION env, move fusion dispatch to topk-moe
* sycl: print GGML_SYCL_ENABLE_FUSION at startup like other env vars
Co-Authored-By: Claude Fable 5 <redacted>
---------
Co-authored-by: Claude Fable 5 <redacted>
* gguf : add tensor shape accessor (llama/24405)
* gguf : add tensor shape accessors
* gguf : return tensor shape as const int64_t *
* gguf : remove n_dims accessor, keep only gguf_get_tensor_ne
* vulkan: Use native e2m1 and e4m3 conversions for mxfp4/nvfp4 (llama/25338)
This uses the new VK_EXT_shader_ocp_microscaling_types extension to do fp4 type
promotions, and also uses the float8 extension to do ue4m3 promotions for
nvfp4. It's reasonable to assume that an implementation that supports fp4 will
also support fp8, so we don't need to handle all possible combinations of
support.
* CUDA: refactor MMQ kernel configuration (llama/24127)
* CUDA: refactor MMQ kernel configuration
* fix Blackwell config
* remove legacy code
* metal : add Q2_0 support (llama/25419)
* sycl: set fattn_vec_nthreads to 256 for Battlemage (llama/25205)
Currently detects lunarlake + battlemage / xe2 and
sets the value to 256.
Keeps default at 128, Intel's ARC Alchemist's prefered value.
* kleidiai : add SME2 f32 kernel (llama/24414)
* kleidiai : add SME2 f32 kernel
* enable dynamic scheduling for SME2 f32 kernel
* ggml: uniformize im2col dst_type for all conv ops (llama/23660)
* ggml: uniformize im2col dst_type for all conv ops
* Update ggml/src/ggml.c
Co-authored-by: Georgi Gerganov <redacted>
* ggml : uniformize im2col casting logic across all conv ops
* fix : allow im2col_f16 to accept any kernel type
---------
Co-authored-by: Georgi Gerganov <redacted>
* ggml : add a set of functions for checking contiguity of inner tensor dimensions (llama/25650)
Co-authored-by: Stanisław Szymczyk <redacted>
* vulkan/cpu: Support f16 as SET_ROWS src. (llama/25432)
* vulkan/cpu: Support f16 as SET_ROWS src.
This adds full support for f16 SET_ROWS (equivalent to f32) to vulkan and CPU
backends, and adds more backend tests.
* Set DenormPreserve 16 when supported, to try to fix failures on Intel
* tune error threshold
* update metal supports_op
* opencl: fix a dp4a bug for devices where cl_khr_integer_dot_product is unavailable (llama/25639)
* opencl: do not fail backend init on devices without cl_khr_integer_dot_product
* opencl: do not call dp4 kernels when dp is unavailable
---------
Co-authored-by: Li He <redacted>
* hexagon: fix hmx-queue signal enum-narrowing problem (llama/25677)
* opencl: avoid the vec path in GEMV for unaligned row stride (llama/25671)
The f16 GEMV kernels take a vectorized path for ne00 >= 128 that casts the row
pointers to half4 or float4. When the row stride is not aligned, the wide load
becomes misaligned. On devices that require natural alignment for vector loads,
the kernel reads garbage. This is the case Intel GPUs and the kernels produce
incorrect results there. Adreno happpens to be byte addressable and the kernels
happen to work.
* opencl: handle OOB write in noshuffle GEMV kernels (odd ne01) (llama/25640)
* opencl: do not use `clCreateBufferWithProperties` when targeting CL 2.x (llama/25673)
* Flash Attention with XMX engine via oneDNN (llama/25222)
* [SYCL] F16 (default) Flash Attention with XMX engine via oneDNN graph API; Qwen3.6-27b-Q8_0 prefill speed up x1.21 at p=512 and x4.26 at p=80k
* [SYCL] Address review on FA oneDNN path. Result: llama-bench---pp512; 32% increase with fa1; llama-perplexity---0.11% difference; tested model: mradermacher/Meta-Llama-3.1-8B-Instruct-Q8_0.gguf
* PR-25222 revision v2: addressed audits
* [SYCL] flash-attn oneDNN SDPA KV F16 rev 3.0: add BMG gate + multi-device sync. Narrow the scrope of this PR to Battlemage only (bmg; Xe2). Other archs (e.g., alchemist) fall back to existing FA kernel. When device_count >1, apply stream -> wait_and_throw(), validated working path for multi-gpu sync fix by @maxious.
Co-authored-by: maxious <redacted>
* updated comment on bmg gate, noted the issue
---------
Co-authored-by: scientist3 <redacted>
Co-authored-by: hmscider <redacted>
Co-authored-by: maxious <redacted>
* sycl: Increase minimum buffer size for USM system allocations (llama/25525)
Raise the threshold for minimum buffer size from 1 GiB to 4 GiB, based
on real-world experiments of overcommitting device memory with model
weights larger than available VRAM, for example Qwen3.5-35B-A3B-Q8
running on a B70.
Also add a debug message to better track USM system allocations.
Signed-off-by: Francois Dugast <redacted>
* sycl : implement xielu op (llama/25550)
* sycl : support kernel type fp16 for conv2d_dw (llama/25653)
* sycl : fix get_rows Q2_K, Q4_K, Q5_K (llama/25656)
* ggml: add f16 out_prod support for CPU and out_prod op for Vulkan (llama/23997)
* metal: fuse snake activation (mul, sin, sqr, mul, add) (llama/25459)
* metal: fuse snake activation (mul, sin, sqr, mul, add)
Mirror the CUDA, Vulkan and CPU snake fusion: same matcher on the naive
5-op chain, same F32 contract on a and inv_b, same F32/F16/BF16 kernel
with F32 compute. Follows the Metal backend idioms: bf16 instantiation
gated behind GGML_METAL_HAS_BF16 and concurrency ranges checked on the
remaining chain nodes before encoding, as done by the bin fusion.
Covered by the existing backend-agnostic SNAKE_FUSE tests.
* metal: absorb snake fusion into ggml_metal_op_bin
Extract the matcher to ggml_metal_op_can_fuse_snake, mirroring the
Vulkan naming, and dispatch the fused path from ggml_metal_op_bin.
The encode loop switch is back to a single call per case.
Address review from ggerganov
* metal: fix indentation in ggml_metal_op_can_fuse_snake
* cuda : relax tensor contiguity requirements for quantized concat (llama/25678)
* cuda : relax tensor contiguity requirements for quantized concat
* tests : add test cases for non-contiguous quantized concat
* ggml : relax contiguity requirements for quantized concat
---------
Co-authored-by: Stanisław Szymczyk <redacted>
* CUDA: tighter MMQ src1 buffer size for native fp4 (llama/25613)
* opencl: fix two issues on flash attention for Adreno a7x (llama/25697)
* opencl: route `sub_group_shuffle_xor` to qcom ext when KHR ext is unavailable
KHR `sub_group_shuffle_xor` is not defined by compiler when
`cl_qcom_subgroup_shuffle` is present, causing certain FA
kernels fail to build. Define the KHR shuffle_xor using
the qcom extension.
* opencl: skip FA kernels with mixed and quant types for A7x to avoid compiler crash
* cuda : CUDA GGML_OP_LIGHTNING_INDEXER implementation (generic vector kernel + wmma kernel) (llama/25545)
* cuda : CUDA GGML_OP_LIGHTNING_INDEXER implementation (generic vector kernel + wmma kernel)
* chore : remove indentation of #pragma unroll
* cuda : remove unnecessary kernel template declarations
* cuda : add WARPS_PER_BLOCK and K_VECS_PER_BLOCK template parameters in lightning indexer kernels to avoid duplication of constants.
* cuda : relax MMA architecture requirements to Turing in lightning indexer implementation
* chore : renamed variables
* chore : rename ggml_cuda_op_lightning_indexer() to ggml_cuda_lightning_indexer()
* chore : TODO for AMD rocWMMA
* chore : whitespace formatting
* chore : another variable rename to fix problems caused by shadowing
* chore : yet another rename, this time uppercased all constants
* cuda : added alignment checks for Q and K tensors in lightning indexer implementation
---------
Co-authored-by: Stanisław Szymczyk <redacted>
* opencl: exclude some moe kernels on Adreno a7x (llama/25698)
* opencl: exclude Adreno A7x from using Adreno MoE kernels
Some compilers for A7x devices miscompile the repack kernels, corrupting
the weights and causing MoE models to generate garbage output
* opencl: exclude A6x and unknown Adreno from MoE weights repack
* cuda: extract Q1_0 elements via __byte_perm (llama/25628)
* opencl: disable FA and MoE weights repack to work around compiler issues for Adreno 850 GPU (llama/25745)
* opencl: workaround for A850 compiler compat
* opencl: fix DX compiler version parsing and cleanup
---------
Co-authored-by: Li He <redacted>
* CUDA: dedup MoE gate/up activation quantization (llama/25441)
* CUDA: dedup MoE gate/up activation quantization (fp4)
For MoE gate/up projections the src1 activation is broadcast across the
routed experts (ne11 == 1), so ids_src1 maps every one of a token's
n_expert_used slots to the same physical row. The MMQ path therefore
re-quantized each token's activation n_expert_used times.
For fp4 (NVFP4/MXFP4) src0, quantize each unique token row once instead of
once per expert. For NVFP4 a single quantize+scatter kernel
(quantize_scatter_mmq_nvfp4) quantizes each token once and writes the
resulting block_fp4_mmq straight to all n_expert_used slots, using an
inverse token->compact-row map (build_tok2c). MXFP4, and
GGML_CUDA_MOE_QUANT_GATHER=1, use a two-kernel variant: quantize unique
rows then gather into the expert-sorted layout (gather_mmq_fp4_blocks).
Both are bit-identical to the previous gather-then-quantize path (identical
source data, deterministic per-block quantization), verified by
test-backend-ops MUL_MAT_ID (type_a=nvfp4, broadcast b=1; 790/790 for the
default, gather, and per-expert paths) and by coherent end-to-end
generation. Set GGML_CUDA_NO_MOE_QUANT_DEDUP=1 to force the original
per-expert path.
Same-binary A/B on RTX 5090 (sm_120), Qwen3.6-35B-A3B-NVFP4 prefill @8192
(nsys, graphs-off; the unchanged mul_mat_q GEMM confirms stable clocks):
activation-quant GPU-busy drops 61% (78.2 -> 30.4 ms) with the fused
quantize+scatter, vs 33% (78.2 -> 52.8 ms) for the two-kernel gather. The
fused path avoids materializing and re-reading the 8x compact buffer,
writing the expert copies directly from registers.
* CUDA: bounds-check token ids in build_tok2c_kernel
Guard against malformed ids_src1: skip out-of-range token ids (t < 0 or
t >= n_tokens) and drop entries beyond n_expert_used per token instead of
writing past the token's tok2c region. No behavior change for valid MoE
routing data; test-backend-ops MUL_MAT_ID 790/790.
* Refactor the code based on review comments
- Removed previously added kernels that were not necessary anymore\
- Added an inverse mapping from (token, slot) to compact row. Each token is quantized once and scattered to its compact rows.
* Adding q8_1 support for dedup and addressing review comments
* Add pragma unrolls
* Remove redundant cudaMemsetAsync call
* Removing follow up redundancies
---------
Co-authored-by: praneshgo <redacted>
* ggml-cuda : restore prop.integrated on HIP builds (llama/24233)
PR #16308 set info.devices[id].integrated = false unconditionally for all
CUDA/HIP devices as a workaround for corrupted output on Jetson Orin
(#15034). On HIP/ROCm the device's real hipDeviceProp_t.integrated flag is
needed: with the cached field forced to false, supports_buft() refuses
CUDA host buffers on AMD APU/UMA parts, while get_type() already reads
prop.integrated (#23007) — an inconsistency that breaks integrated-GPU
host-buffer use on ROCm.
Guard the workaround so it only applies to non-HIP (CUDA) builds and
restore prop.integrated for HIP, keeping the Jetson workaround intact for
CUDA.
Fixes #23977
Signed-off-by: liminfei-amd <redacted>
* Enable CUDA graphs on volta+turing (llama/25749)
* CUDA: Support CUDA Virtual Devices (llama/25228)
* support cuda virtual devices
* disable NCCL path when virtual devices are used
* label virtual devices in description; add GPUx2 server CI jobs
* code refactor
* vulkan: when using transfer queue for async copies, sync on event_wait to avoid race (llama/25229)
* kleidiai: Add SME vs SME2 distinction in kernel dispatch (llama/25478)
The current integration treats SME as a single capability (CPU_FEATURE_SME)
with no distinction between SME(v1) and SME2. The kernels dispatched under
CPU_FEATURE_SME use SME2-specific instructions, making dispatch incorrect
on SME(v1)-only hardware.
We introduce build-time and runtime distinction between SME and SME2, and
wire SME(v1) and SME2 kernels based on actual hardware support.
* hexagon: L2 cache handling rework (dirty bit tracking with lazy flushing) and more MUL_MAT updates (llama/25762)
* hex-mm: fix artificial limit in the solver that restricted number of act-prep threads
* hex-mm: fix warning
* hex-prof: do not apply --top to the timeline report
* hmx-mm: add suport for tiled act-processing to better distribute hvx work
* hex-l2: add tracing for l2flush events
* workqueue: redo the legacy workpool api to match hmx-queue and dma-queue
* hmx-mm: fix f32 activation buffer alignmnet for nhvx=5,6,7
* hex-work: minor cleanup for work-queue apis
* hex-work: further cleanup of the work-queue api
* hex-l2: optimize l2flushes at the opbatch level
* hex-work: remove unused mask
* hex-work: no need to drop hvx ctx in the work-queue
* hex-work: add explicit wakeup/suspend and make threads spin
* hex-bufs: mark any non-weight tensor as compute
* hex-dma: dma-queue support for alias queues and cached dma
* hex-l2: track tensor aliases and delay or skip flushes as much as possible
* hex-l2: simplify tensor alias handling
* hex-l2: handle overlapping views as a circular list of aliases
* hex-tens: add flags helper
* hex-l2: add helper for marking tensors clearn/dirty
* hex-l2: mark binary and rope outputs as l2-clean and keep the rest as is for now
* hex-l2: proper support for handling all tensor overlap scenarios
* hex-trace: instrument matmul init code and cleanup trace checks
* hex-thread: introduce dedicated main thread with explicit stack and priority
* hex-l2: track dirty state as bitmap and introduce threaded flush
* hex-trace: remove redundant checks for ctx != null
* hex-l2: allocate entire context as one buffer and l2fetch it after big flushes
* hex-l2: disable tensor clearing in binary and rope for now seems to cause issues with fusion
* hmx-mm: update act proc to use fastdivs and fix DMA overflow
* hmx-mm: make MUL_MAT_ID kernels robust to multi-chunk cases (start_row>0)
* hex-queue: remove obsolete queue interfaces and flush hmx-queue at the end of the op-batch
* hex-queue: dont use early wakeup for small op-batches
* hex-tensors: properly cap max_tensors in op-batches and dirty_map
* hex-l2: make sure threaded l2flush does proper rounding
* hex-l2: factor out htp_tensor_flush for reuse (if needed)
* hex-l2: optimize tensor flushes by coalescing flush-all
* hex-l2: optimize multi-threaded flush
* hex-drv: futureproof version checks
* hexagon: fix errors and warnings on windows
* hex-main: update main thread to only use dspqueue_read, dspqueue_peek is not available on some platforms
* hex-main: add fallback mode for dspqueue with callbacks
* hex-main: introduce fallback mode for using dspqueue callbacks for full op processing
* hex-main: remove early wakeup, not helping and seems to cause some errors with certain batch sizes
* hex-l2: make sure to use invalidate version of flushall
* hex-l2: dont try to trace early l2flush at the start of op-batch
* hex-main: remove offset_ctx that must be zero anyway
* hex-hmx: fix hmx_queue_depth to use idx_write - idx_read
* hex-hmx: use atomic_load for idx_read/write
* hex-main: add static assert to make sure n_threads are aligned
* DeepseekV4: Add fused hyper-connection ops (llama/25585)
* dsv4 hc-ops
* add missing files;
* add cparams
* update rpc version
* address review comments
* address review comments
* docs: added a note about using OpenCl with Adreno 810 (llama/25786)
* opencl: loads quants as uint for q4_K and q5_K flat mv (optimization for Adreno A7x GPUs) (llama/25780)
* opencl: load quant as uint in mv_q4_k_f32_flat
helps older compilers (e.g., E031.41, boosts 2x),
no impact on newer compilers (e.g., E031.45 or newer)
* opencl: load quant as uint in mv_q5_K_f32_flat
helps older compilers (e.g., E031.41)
* opencl: format
---------
Co-authored-by: Li He <redacted>
* opencl: add ABS op (llama/25115)
* sycl: fix row calculation when K_QUANTS_PER_ITERATION is 1 (llama/25690)
* sycl: fix incorrect row calculation when K_QUANTS_PER_ITERATION=1
Signed-off-by: Todd Malsbary <redacted>
* sycl: use K_QUANTS_PER_ITERATION for non-reordered Q5_K kernel
This is the only Q5_K kernel that was not using KQPI.
Signed-off-by: Todd Malsbary <redacted>
* sycl: add missing second half processing to reordered q5_k
Error found while running
GGML_SYCL_PRIORITIZE_DMMV=1 \
build/bin/test-backend-ops test -o MUL_MAT
Signed-off-by: Todd Malsbary <redacted>
* sycl: fix potential off-by-one error
Signed-off-by: Todd Malsbary <redacted>
* sycl: fix missing row > nrows check
Signed-off-by: Todd Malsbary <redacted>
---------
Signed-off-by: Todd Malsbary <redacted>
* vulkan: Support Q2_0 (llama/25430)
* vulkan: Support Q2_0
The backend perf tests for mat-vec-mul weren't very good at first (worse than
q2_k), doubling the rows per workgroup made a big difference.
* reorder
* resolve merge conflict, adjust err threshold for f16->q2_0 set_rows
* ggml-blas: default hadamard mul_mat to cpu routine (llama/25710)
Signed-off-by: Aaron Teo <redacted>
* ggml : bump version to 0.17.0 (ggml/1568)
* opencl: transpose q4_K noshuffle scales for coalesced reads (llama/25805)
* opencl: read/write MoE dp4a activation tiles to local memory as 128-bit (vectorized LD/ST perf opt) for Adreno GPUs (llama/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 (llama/25797)
* opencl: Support broadcast for Adreno MUL_MAT and honor `view_offs` for Adreno Q8_0 MUL_MAT for llama-server multi-stream (llama/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 <redacted>
* hexagon: add CLAMP op (llama/25934)
* CUDA: vectorize same-type get_rows with int4 copy (llama/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 (llama/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 (llama/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 <redacted>
* Update ggml/src/ggml-vulkan/ggml-vulkan.cpp
Co-authored-by: Jeff Bolz <redacted>
* Update ggml/src/ggml-vulkan/ggml-vulkan.cpp
Co-authored-by: Jeff Bolz <redacted>
* Update ggml/src/ggml-vulkan/ggml-vulkan.cpp
Co-authored-by: Jeff Bolz <redacted>
* Update ggml/src/ggml-vulkan/ggml-vulkan.cpp
Co-authored-by: Jeff Bolz <redacted>
* Update ggml/src/ggml-vulkan/ggml-vulkan.cpp
Co-authored-by: Jeff Bolz <redacted>
* 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 <redacted>
* kleidiai : warn once when a weight type has no KleidiAI kernel (llama/25701)
* cuda: add sqrt_softplus in topk-moe for dsv4 (llama/25896)
* hexagon: check tensor type when reusing descriptors (llama/25968)
* cuda: GET_ROWS quants (llama/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 (llama/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
* ggml: enable PowerPC backend variants on AIX (llama/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
* hexagon: activation ops update (llama/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 <redacted>
* CUDA: Improve NVFP4 W4A4 activation quantization (llama/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
* metal : add f16 type support to leaky relu (llama/25981)
* CUDA: fix external compilation of q1_0 MMQ (llama/25778)
* hexagon: fix Windows crash when op_poll is enabled (llama/26029)
* hexagon: further improved pipeline of the core bits (L2, DMA, MM, FA) (llama/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
* opencl: do not treat NULL-mask flash attention as causal (llama/25771)
* opencl: cache compiled cl_program binaries on disk (llama/26050)
* HIP: remove rocWMMA FlashAttention (llama/26046)
* Update ggml/src/gguf.cpp : Defined virtual keyword for destructor of gguf_writer_base (llama/25867)
Without a virtual destructor, deleting a derived object through a
base-class pointer only invokes the base destructor, skipping the
derived one.
* hexagon: partial im2col support (llama/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.
* opencl: fix fused RMS norm mul view offset (llama/26085)
* ggml-cpu: Enable BF16 tiled gemm optimization on PowerPC (llama/26068)
* ggml : adjust logic for offloading ops to weight's backend (llama/25832)
* ggml : adjust logic for offloading ops to weight's backend
* llama : dsv4 graph fixes
* sycl(build): parallelize ocloc invocations (llama/25903)
* Disable -ffast-math on HIP (llama/25495)
* ggml-metal: FWHT kernel for metal backend (llama/25924)
* metal fwht wip
* shape guard and formatting
* formatting
* Formatting and typos
Co-authored-by: YiChen Lv <redacted>
* fix narrowing issue
Co-authored-by: YiChen Lv <redacted>
* cont : minor style
---------
Co-authored-by: YiChen Lv <redacted>
Co-authored-by: Georgi Gerganov <redacted>
* sycl: fix use-after-return of the SDPA scale in the oneDNN flash-attention path (llama/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 <redacted>
* 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 <redacted>
* ggml-cuda: add chunked SSD matmul for Mamba-2 prefill acceleration (llama/22675)
* ggml-cuda: add chunked SSD matmul for Mamba-2 prefill acceleration
* cuda: added SSD CICD fixes for CUDA / HIP / MUSA / MSVC.
* ggml-cuda: review comments fixed.
* ggml-cuda: Fuse M matrix materialization into pre_matmul kernel and enabled test.
* ggml-cuda: test updates and fixes
* ggml-cuda: test updates to remove hardcoding of tensor initialise data limits.
* ggml-cuda: ssd minor review comment fixed.
* ggml-cuda: ssd minor CICD fixed.
* CUDA SSD: Fixes correctness by promoting s0_stride_seq to int64_t, improves memory coalescing in ssm_ssd_prepare_dt_kernel, and boosts efficiency by merging B_weighted and C_scaled; also addresses prior review comments.
* cuda: fix sdata read-write race in prepare_dt fallback scan loop
* vulkan: add iq4_nl support back to FA (llama/24585)
* vulkan: add iq4_nl support back to FA
I was originally concerned about wasting shared memory on the LUT, but it's small
and unlikely to matter in practice.
Also support q1_0 for non-coopmat2.
Fixes #23681
* remove q1_0 FA support
* ggml : set output of view src (llama/25729)
* llama-graph: set_outputs to t->view_src
* change set_output to GGML_ASSERT about views not being outputs
* sampler : avoid views in outputs
* cont : fix dist sampler
* cont : consistent logits handling
* ggml : set output of view src
* graph : simplify set_outputs()
* cont : cleanup
Co-authored-by: Gaurav Garg <redacted>
---------
Co-authored-by: Georgi Gerganov <redacted>
Co-authored-by: Gaurav Garg <redacted>
* opencl: skip the Adreno KQ/KQV image kernels for multi-stream batches (llama/26189)
The Adreno KQ/KQV image1d kernels (ggml_cl_mul_mat_kq_kqv_adreno) ignore
dim 3 entirely: the sub-buffer covers only nb02*ne02 bytes and the kernel
receives no ne03/ne13/nb03/nb13 arguments. With the unified KV cache,
multi-sequence batches (e.g. llama-perplexity with its default -b 2048,
n_seq=4, or a multi-slot llama-server) present KQ/KQV as 4D tensors with
ne3 = n_stream, so every stream past the first reads the first stream's
K/V and produces garbage. Flash attention masks the bug where it is
enabled; devices where FA is declined (e.g. Adreno 740) hit it with
default settings.
Route ne03/ne13 > 1 to the general path, which handles dim 3, and honor
view_offs when creating the sub-buffers (currently always 0 for tensors
reaching this function, but the function would silently misread any
future view).
Llama-3.2-1B-Instruct Q4_0, wiki.test.raw, 8 chunks, -ngl 99:
- Adreno 740, default: PPL 1817.64 -> 15.61
- Adreno 740, -fa 0: PPL 1941.64 -> 15.61
- Adreno 840, -fa 0: PPL 1943.90 -> 15.50
- single-stream (-b 512) results unchanged (15.6090)
- test-backend-ops -o MUL_MAT on 740: identical before/after (909 OK,
12 pre-existing q6_K failures)
* ggml-webgpu: Fix some binding alias issues to support all archs, fix recurrent-state-rollback test (llama/25931)
* Add overlap glu variant to support all archs, fix recurrent-state-rollback test
* format
* Fix all arch overlapped ranges
* format
* diagnose bus error on apple ci
* More testing
* more testing
* more targeted testing
* Fix bug in alignment for > 4gb buffer offsets
* Fix bug in view offsets
* Try avoiding multi_buffers
* not fixed yet, more logging :(
* Handle edge case in set_rows
* Try looking at view source
* Skip deepseek32 for now and clean up trace infrastructure
* simplify skipping
* last cleanup
* actually final cleanup
* update handling of overlap
* format
* try skipping other failing model
* add rdna3.5, and 3 to mmq configs so they can be tuned independently. (llama/26199)
* RPC: add tensor_memset (llama/25912)
* sycl: contiguous fast path + 32-bit index math for unary elementwise ops (llama/25946)
* sycl: contiguous fast path + 32-bit index math for unary elementwise ops
* sycl: use fastdiv for elementwise index math
* ggml-cuda : disable MMQ on devices with less than 48 KiB shared memory (llama/26141)
ggml_cuda_should_use_mmq() selects MMQ purely from the quantization
type. The current MMQ configurations are designed and maintained against
a minimum of 48 KiB per-block shared memory, the limit provided by
NVIDIA Pascal GPUs and later. On devices that report less, no supported
MMQ tile fits and mul_mat_q_switch_J() aborts when every tile size
exceeds the device's per-block shared memory budget.
Disable MMQ when smpbo < 48 KiB so the caller falls back to the BLAS
path instead of hitting GGML_ABORT. Some current MUSA QY1 devices
report only 28 KiB and are covered by this guard.
Reproduced on a Moore Threads MTT S70 (arch mp_21, 28 KiB shared memory
per block) with an RWKV-7 0.1B Q8_0 model:
$ llama-bench -m rwkv7-g1d-0.1b-Q8_0.gguf -p 128 -n 0
J_best=0
ggml/src/ggml-cuda/template-instances/../mmq.cuh:1521: fatal error
(core dumped)
Only prefill (batch > 1) is affected; token generation is fine. After
the fix the same device falls back to the BLAS path:
Q8_0 pp128 1470.7 t/s, tg8 55.3 t/s (was: abort)
FP16 unchanged
Q4_K_M unchanged
This matches a -DGGML_CUDA_FORCE_CUBLAS=ON build (pp128 1464.2 t/s),
which confirms the fallback path is the one being taken.
This is not MUSA-specific: any device with less than 48 KiB per-block
shared memory is affected.
Co-authored-by: KakaruHayate <redacted>
* ggml : Fix issue with kleidiai ci and stringop overflow warning (llama/26277)
Signed-off-by: Jonathan Clohessy <redacted>
* metal: fix memory unwire if model is freed without any GPU operations (llama/26082)
* metal: fix memory leak if model is freed without any GPU operations
* metal: run dummy work only if residency sets are used
* metal: wrap function in #if defined
* metal: measure system-wide wired memory in test
* metal: always build regression test
Co-authored-by: YiChen Lv <redacted>
---------
Co-authored-by: YiChen Lv <redacted>
* CUDA: add Q2_0 support (llama/25707)
* ggml : bump version to 0.18.0 (ggml/1576)
* sync : ggml
* parakeet : update parakeet test models generation
This commit updates the parakeet test models to ensure that the random
values generated for mel filters are not negative. This will otherwise
cause a debug assertion and fail the parakeet-test.
Refs: https://github.com/ggml-org/whisper.cpp/actions/runs/
30547589734/job/
90887624319?pr=3962
---------
Signed-off-by: Todd Malsbary <redacted>
Signed-off-by: Francois Dugast <redacted>
Signed-off-by: liminfei-amd <redacted>
Signed-off-by: Aaron Teo <redacted>
Signed-off-by: Jonathan Clohessy <redacted>
Co-authored-by: Aparna M P <redacted>
Co-authored-by: Max Krasnyansky <redacted>
Co-authored-by: fairydreaming <redacted>
Co-authored-by: Stanisław Szymczyk <redacted>
Co-authored-by: Johannes Gäßler <redacted>
Co-authored-by: Hongqiang Wang <redacted>
Co-authored-by: Martin Chang <redacted>
Co-authored-by: Vidas <redacted>
Co-authored-by: Gianluca Guida <redacted>
Co-authored-by: Gianluca Guida <redacted>
Co-authored-by: ubergarm <redacted>
Co-authored-by: SaqibAkram-10xE <redacted>
Co-authored-by: Rehan Qasim <redacted>
Co-authored-by: Li He <redacted>
Co-authored-by: Raman Shinde <redacted>
Co-authored-by: cphlipot <redacted>
Co-authored-by: Rohit Mahesh <redacted>
Co-authored-by: Todd Malsbary <redacted>
Co-authored-by: Frosty40 <redacted>
Co-authored-by: Claude Fable 5 <redacted>
Co-authored-by: QuintinShaw <redacted>
Co-authored-by: Jeff Bolz <redacted>
Co-authored-by: Pasha Khosravi <redacted>
Co-authored-by: Titaniumtown <redacted>
Co-authored-by: Charles Xu <redacted>
Co-authored-by: JusteLeo <redacted>
Co-authored-by: Chyan <redacted>
Co-authored-by: hmscider <redacted>
Co-authored-by: scientist3 <redacted>
Co-authored-by: hmscider <redacted>
Co-authored-by: maxious <redacted>
Co-authored-by: Francois Dugast <redacted>
Co-authored-by: Andrew Smith <redacted>
Co-authored-by: Neo Zhang <redacted>
Co-authored-by: Michael Lamothe <redacted>
Co-authored-by: Pascal <redacted>
Co-authored-by: leonardHONG <redacted>
Co-authored-by: David Friehs <redacted>
Co-authored-by: Pranesh Gonegandla <redacted>
Co-authored-by: praneshgo <redacted>
Co-authored-by: liminfei-amd <redacted>
Co-authored-by: Alexander Heisler <redacted>
Co-authored-by: Anav Prasad <redacted>
Co-authored-by: Ruben Ortlam <redacted>
Co-authored-by: Rajendra Matcha <redacted>
Co-authored-by: Aman Gupta <redacted>
Co-authored-by: akleine <redacted>
Co-authored-by: Gezahegne <redacted>
Co-authored-by: Aaron Teo <redacted>
Co-authored-by: Todor Boinovski <redacted>
Co-authored-by: Piotr Wilkin (ilintar) <redacted>
Co-authored-by: Markus Ebner <redacted>
Co-authored-by: Winston Ma <redacted>
Co-authored-by: Kamalesh VS <redacted>
Co-authored-by: Wei Wang <redacted>
Co-authored-by: m1el <redacted>
Co-authored-by: shalinib-ibm <redacted>
Co-authored-by: Oliver Simons <redacted>
Co-authored-by: Ilia Ilmer <redacted>
Co-authored-by: adgup-qti <redacted>
Co-authored-by: kumaal <redacted>
Co-authored-by: Yongmin Yoo 유용민 <redacted>
Co-authored-by: yzyyzyhhh <redacted>
Co-authored-by: Beinsezii <redacted>
Co-authored-by: Nick Lafleur <redacted>
Co-authored-by: YiChen Lv <redacted>
Co-authored-by: meatposes <redacted>
Co-authored-by: Bhavik Sharda <redacted>
Co-authored-by: Gaurav Garg <redacted>
Co-authored-by: Reese Levine <redacted>
Co-authored-by: Geramy Loveless <redacted>
Co-authored-by: Kakaru <redacted>
Co-authored-by: KakaruHayate <redacted>
Co-authored-by: Jonathan Clohessy <redacted>
Co-authored-by: Niklas Wenzel <redacted>
Co-authored-by: Daniel Bevenius <redacted>
opencl: Q6_K GEMM/GEMV fix for ne01 of weights that are not multiples of 128. (llama/25464)
* opencl: fix garbled output for Q6_K weights with ne01 % 128 != 0 on Adreno
Observed with granite-3.1-3b-a800m-instruct, whose vocab is an odd number.
Route Q6_K dense mul_mat with ne01 % 128 != 0 off the noshuffle path:
decode (ne1==1) uses the correct flat GEMV and the matching GEMM (ne1>1)
falls back to CPU (the flat convert has no verified small-batch GEMM kernel
for these shapes). All standard hidden/FFN/vocab dims are multiples of 128
and keep the noshuffle path.
* opencl: reserve alignment slack for the SOA subbuffer carve in alloc size
set_tensor carves quantized weights into per-component subbuffers (d/q,
ql/qh/s/d, ...) whose origins are each rounded up to the device base
address alignment. When a component's size is not a multiple of the
alignment, the carve extends past ggml_nbytes(tensor) and the last
subbuffer overlaps the next tensor in the pool -- e.g. q6_K [1536, 49155]:
size_s = 49155*96 ends 32 bytes past a 128-byte boundary, so the d
subbuffer ends 96 bytes past the tensor's allocation, and whichever of the
two neighboring tensors is uploaded last silently corrupts the other (here:
the last vocab rows' block scales). This affects any quant type whose
component sizes can be misaligned, on any shape with ne01 not a multiple of
the alignment granularity; standard power-of-two dims are unaffected.
Implement get_alloc_size for the OpenCL buffer type and reserve the
worst-case carve slack (4 aligned gaps; 5 components max, q5_K) for
quantized tensors. Costs at most 512 bytes per quantized tensor at the
observed 128-byte alignment.
* opencl: use lm based q6_k mm when ne1 is not multiple of 128
---------
Co-authored-by: Li He <redacted>
opencl: ragged-tile MoE prefill FP16 GEMM optimization (skip padded expert tiles) (llama/25433)
* opencl: ragged-tile MoE prefill GEMM (skip padded expert tiles)
The MoE prefill GEMM groups tokens into TILESIZE_N=32 per-expert tiles; at low
tokens-per-expert most tiles are mostly padding. When a tile's upper 16 slots
are all padding (router index 0xFFFFFFFF), skip the second dotx16_reduce8 half.
Numerically identical (skipped lanes are padding). Applied to all eight *_f32_ns
MoE GEMMs; default on, opt out with GGML_OPENCL_MOE_RAGGED_FP16=0.
* opencl: quarter-granularity ragged MoE tile-skip (8-col skip-groups)
Replace the two half-tile dotx16_reduce8 calls in the 8 *_f32_ns MoE GEMMs with
four dotx8_reduce4 (8-column) calls, skipping each empty trailing skip-group
independently. Padding is always trailing, so the kernel rounds the valid count
up to the skip granularity and skips fully-padding groups. Byte-identical to the
non-skipped path. New env GGML_OPENCL_MOE_RAGGED_GRAN={8,16,32} (quarter/half/
off); default quarter.
* opencl: move ragged moe env var in cl_init
---------
Co-authored-by: Li He <redacted>