* cuda : port indexed bias FA onto the refactored loaders
Replays the #32740 bias support on the shared typed tile loader, adds bias
in F32 to match the CPU reference and routes rows via KV_indirection.
* cuda : return zeros for a fully masked FA query row
An all -inf mask row has a zero softmax sum, which divided gave NaN. Guard
the tile, vec and results-combine divisions so it gives zeros, as ggml-cpu.
* Code review from Fable
* fixup! cuda : port indexed bias FA onto the refactored loaders
* model : inkling2 order the conv ops so backends can fuse them
* CUDA: fuse the Inkling 2 short conv, depth mix, loop controller, L2 clip and situ chains
* ggml : support a BF16 src1 in MUL_MAT and MUL_MAT_ID (CPU, CUDA)
* ggml : fix MMVF expert offset overflow and tighten BF16 src1 gates
* ggml : strided BF16 src1 tests, explicit MUSA Q2_K rule, MMVF offset fix moved to its own PR
* cuda : move the MUL_MAT_ID MMVF rule into ggml_cuda_should_use_mmvf
* cuda : read a BF16 src1 in MMVF through a template parameter, for BF16 and FP8 weights only
* cuda : MMVF src1 pairs via ggml_cuda_cast, rename type to type_src0
The non-contiguous concat kernel mapped dst ne[2] and ne[3] directly to
gridDim.y and gridDim.z, which are limited to 65535. Larger tensors made
the launch fail with "invalid configuration argument". Cap the grid and
loop over the remaining rows in the kernel.
Fixes#32956
Assisted-by: Claude Opus 5.5
* CUDA: flash attention tile kernel for DKQ 576 with a GQA ratio of 2
The tile kernel for 576/512 only had variants for GQA ratios that are
multiples of 4, while the kernel selection accepts any ratio from 2,
so an MLA attention with a ratio of 2 aborted on GPUs that use the
tile kernel, such as RDNA. Add the 2 column configuration, copied from
the 512/512 one of each table, and dispatch even ratios to it. Odd
ratios have no tile variant: the selection now reports them as
unsupported instead of picking the tile kernel. Cover the ratios 2
and 3 in test-backend-ops.
* CUDA: pass the K/V types to the tile kernel for 576 with a GQA ratio of 2
#32901 added the K and V types as template parameters of the tile kernel,
the ratio 2 dispatch for DKQ 576 still used the old parameter list.
* CUDA: report DKQ 576 with a GQA ratio not divisible by 4 as unsupported by the tile kernel
Use the selection instead of a new tile specialization, as suggested in
review: drop the 2 column variant and only pick the tile kernel for
576/512 when the GQA ratio is a multiple of 4, the ncols2 = 4 and 16
variants it has. The ncols2 = 4 variant cannot serve a ratio of 2, a
block reads a single K/V head.
Build the gradient dy * (1 - y^2) from the forward output with existing
ops, no new op is needed. Add TANH to the gradient-checked unary ops.
Signed-off-by: gianni-cor <gianfranco.cordella@tether.io>
* metal : spread the short mat-vec lanes over src1 rows
The short mat-vec kernel (K < 32) mapped its 32 lanes to 32 src0 rows
and handled one src1 row per threadgroup, so with few src0 rows most
lanes were idle. It now covers min(ne01, 32) src0 rows of 32/that src1
rows.
This is the weighted sum over the depth states of Inkling 2 since
#32855 (1-3 src0 rows, K = number of states, 2304 src1 rows).
Inkling-2-Mini UD-Q4_K_XL, M5 Max, master -> this PR:
pp512 888 -> 1052 t/s, pp2048 771 -> 894 t/s, tg128 unchanged.
PPL and greedy output bit-identical, the graph is unchanged.
Tested: test-backend-ops -b MTL0 -o MUL_MAT (new small-K cases).
* cont : clean-up comment
---------
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
* model : add hy_v4_flash on the DSA iSWA cache
Tencent Hy4 flash is a hy_v4 trunk (iHC, gated MLA, sinks) with
sparse and sliding-window MLA layers, sandwich norms, latent routed
experts and deepseek41 Engram tables.
The sparse layers select their context with a pooled indexer: the
keys of 4 consecutive tokens are pooled by a per-channel softmax of a
gate plus a position bias, normed, and rotated at the position of the
first token. A token attends to the best scored pools of its sequence
plus its own pool.
The model runs on llama_kv_cache_dsa_iswa as dots3note does. The
indexer cache holds the projected value and gate of each token, and
the pools are rebuilt from the cells for every ubatch by
llama_kv_cache::set_input_kpool(), so there is no pooled state to
keep in sync with sequence edits, checkpoints or state save/restore.
The selection goes through ggml_top_k_mask with the pool members as
blocks and the token's own pool as extra cells.
Not covered yet: the MTP block (its tensors are skipped), the vision
tower, multiple KV streams, and backends without GGML_OP_TOP_K_MASK.
* convert : add hy_v4_flash
The converter of the hy_v4_flash model, without the vision parts.
The four Engram tables are written as one per_layer_token_embd
tensor of about 127 GB in BF16. Concatenating them with torch.cat
materializes the whole tensor at write time, so they are streamed one
table at a time in row chunks through the _StreamedBytes path of
deepseek41, which keeps the conversion within 100 GB of RAM.
* tests : add hy_v4_flash to test-llama-archs
A 4 layer fixture that alternates sparse and sliding-window layers,
with hyper-connections, one Engram module, an indexer on the sparse
layers and a latent width distinct from the expert width, so that a
transposed routed_down or routed_up is caught.
* kv-cache : do not shift the pooled indexer cache
The pooled indexer of hy_v4_flash caches the value and the gate of
each token, without a position: the pooled key is rotated in the
graph. A K-shift rotated these rows as if they were roped keys, which
broke the pooled keys after a context shift.
* tests : add the hy_v4_flash Metal fusion baseline
* model, mtmd : add hy_v4_flash vision
The vision tower of hy_v4_flash, with its projector in mtmd and its
converter.
The published files carry M-RoPE sections, so the text model runs the
interleaved M-RoPE path: the rope rows keep their reference order and
are reordered to NeoX halves in the graph. The tokens of an image share
their position, so the indexer pools now group consecutive tokens in
sequence order instead of consecutive positions, and a pooled key is
rotated at the four positions of its first member.
Without a backend that runs GGML_OP_TOP_K_MASK, the picked pools are
expanded to their cells and go through build_top_k_mask.
* CUDA: lightning indexer for 16 heads
hy_v4_flash scores its pools with 16 indexer heads, which the CUDA
backend did not support, so the scheduler ran the 12 sparse layers'
indexers on the CPU at every step. Both kernels already handle 16
heads: the mma kernel needs a multiple of 16 and the vector kernel
splits the heads in 4 passes.
* model : move the Hy4 flash Engram gathers before the token embeddings
With the gathers after build_inp_embd, the mixed embedding DUP and SET_ROWS
sat between two host nodes and stayed on the CPU. Those ops use every thread,
so all the CPU workers woke up on each decoded token for a 12K copy.
Gathering first lets the scheduler put them on the GPU, as in qwen4exp, and
leaves only small single threaded lookups on the host.
* llama : speed up the Hy4 flash pool inputs on long contexts
set_input_kpool deduplicated the pools through a map keyed by vectors even
with a single sequence, sorted cells that are already in order and scanned
every pool owner for each token. Dedup only when the ubatch has several
sequences, skip the sort when the cells are ordered and mark the earlier
pools of the token's sequence directly. At 129k cells the host cost of a
decode step drops from 4.0 ms to 0.5 ms, the logits are unchanged.
* llama : use a unified KV cache for Hy4 flash
The pools gather their members from a single KV stream, so a split cache
with several sequences hit an assert in the graph. Switch to the unified
cache with a warning, the sequences then share n_ctx.
* rm redundant code in mtmd
* clean up comments
---------
Co-authored-by: Xuan Son Nguyen <son@huggingface.co>
* cuda : support MROPE/IMROPE and tune block size in rms_norm_mul_rope
* cuda : use 64 threads for multi-token ncols <= 256 in rms_norm_mul_rope
Assisted-by: Antigravity
* Only run webgpu CI on my fork
* Add webgpu only workflow
* resolve merge conflicts
* add row check for softmax
* add test
* Add test to test case eval
* metal : use a range-reduced log1p for softplus
Use the atanh series for x in [-0.5, 1] and precise::log(1 + x) otherwise.
This avoids the cancellation in log(1 + exp(x)) for negative inputs and does
not rely on fast-math folding of (1 + e) - 1.
Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
* tests : add a softplus test for negative inputs
Use inputs in [-16.6, -16.0], where log(1 + exp(x)) has up to ~2x
relative error. This catches both the old form and the fast-math-folded
compensated form.
Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
* ggml : use log1pf in ggml_compute_softplus_f32
Use log1pf(expf(input)) so the host helper keeps the true value for
x < -16.64.
Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
Co-authored-by: IsNot-10 <209144869@qq.com>
* vulkan : use a range-reduced log1p for softplus
Use the atanh series for x in [-0.5, 1] and log(1 + x) otherwise.
Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
Co-authored-by: IsNot-10 <209144869@qq.com>
* opencl : use a range-reduced log1p for softplus
Use the atanh series for x in [-0.5, 1] and log(1 + x) otherwise.
Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
Co-authored-by: IsNot-10 <209144869@qq.com>
* vulkan : move log1p to utils.glsl
Move the range-reduced log1p out of unary.comp into utils.glsl so that
other ops such as topk_moe and ssm_scan can include it. The body is
unchanged; only the call site in op_softplus is renamed.
Co-authored-by: IsNot-10 <209144869@qq.com>
Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB)
---------
Co-authored-by: IsNot-10 <209144869@qq.com>
* GDN: use replay instead of rollback [WIP]
* memory : move rs_max with the sequence when find_slot swaps cells
find_slot swapped pos/src/rs_pend/seq_id of the cell it moves out of the
way, but not rs_max, so that sequence inherited the rollback depth of the
cell's previous owner. A smaller value made seq_rm refuse the rollback
(#31656), a larger one made snapshot mode restore the previous owner's
snapshots.
With rs_replay the pending columns are copied along with the state, so
rs_max follows the sequence. Without it only the final state is copied and
the snapshots stay behind, so the moved sequence gets rs_max 0.
* delta_net: drop the graph replay fallback
The graph fallback ran the replay as two gdn ops and copied the
committed state from the replay gdn when keep, from the main gdn
otherwise. Backends whose graph_optimize reorders nodes (Metal,
Vulkan) then give keep and non keep ubatches a different node order
for the same node count, and the scheduler reallocates on every
switch (abort under GGML_SCHED_DEBUG_REALLOC).
The replay now always runs in the gdn op. A device without the replay
in its gdn op leaves the op to the CPU through the scheduler, as for
any unsupported op. This removes LLAMA_RS_REPLAY=2, the replay probe,
rs_replay_fused and the rep_mask input.
* metal: replay the pending gated delta net tokens in the kernel
The gated delta net kernel replays the pending tokens of each seq
before the new ones, with the same state update as the main loop and
no attention output. With keep, it writes the state after the replay
and skips the final state.
The replay is a function constant of the pipeline, keep is a kernel
argument as on CUDA. The pending buffers fall back to src0 when the
op has no replay.
* vulkan: replay the pending gated delta net tokens in the shader
The gated delta net shader replays the pending tokens of each seq
before the new ones, with the same state update as the main loop and
no attention output. With keep, it writes the state after the replay
and skips the final state.
The replay is a specialization constant of the pipeline, keep is a
push constant as on CUDA. The pending buffers bind q when the op has
no replay. The result checker clones the op with its replay sources.
* webgpu: replay the pending gated delta net tokens in the shader
The gated delta net shader replays the pending tokens of each seq
before the new ones, with the same state update as the main loop and
no attention output. With keep, it writes the state after the replay
and skips the final state.
The replay is a define of the pipeline, keep is a param as on CUDA.
The replay count goes through workgroupUniformLoad, so that the loop
around the workgroup barriers stays uniform.
* delta_net: share the replay conv window views across layers
Each replay layer took its own view of the rs_rep_cols input. The
scheduler copies every view of a host input as a separate split input,
so a verify graph uploaded one copy per layer. The views of the delta
net and the PLE conv windows are now built once per graph, like the
s_copy views.
* vulkan: clamp the gated delta net replay count to n_pend
The replay count comes from a buffer, so the shader bounds it to the
pending rows before looping over them. The pipeline array comment now
names the replay index next to the other ones.
Address review from 0cc4m.
* hex-gdn: add support for replay
Enable replay in HVX path
Enable replay in HMX path
* gdn: fix rebase conflicts (missing cparams, etc)
* llama : drop the fused GDN probes brought back by the rebase
il parameter of build_delta_net. The rebase kept them (unused, auto_fgdn
was always false), so restore master's version of that code.
* delta_net : replay for the KDA models and Clover-MoE
Clover-MoE has the Qwen 3.5 layout and only needs the arch gate.
Kimi K3, Kimi K3.1, GLM5-Next and BailingMoE3 keep the q, k and v conv
windows one after the other in a row. With replay the row holds three
channels-first histories [d_inner, window + pending]:
build_conv_state_replay takes the gathered rows of the layer and the
block index. The pending gate rows hold S_v gates per head (KDA).
GLM5-Next gets the -sm tensor split rules for the replay rows.
Tested with test-llama-archs models: logits match snapshots bit for bit
with random rollbacks (CUDA, Vulkan, CPU), no graph re-plans, and
test-llama-context passes in both modes.
* cuda : same KDA update in the gated delta net main and replay loops
The KDA main loop called expf(g) twice inline, the replay loop reads
g from registers. On sm_89 nvcc fused the two loops differently, so a
replayed state was a few ulp off the state of the first pass. Compute
g into registers in the main loop too: replay matches snapshots bit for
bit on sm_89, and the sm_120 output does not change.
* opencl: support replay in GDN
* llama : replay inputs for the hybrid iswa rel memory input
build_inp_mem_hybrid_iswa_rel came in with the rebase: pass hparams and
cparams to build_rs_inp_impl and fill the replay inputs in set_input,
like the other hybrid inputs.
* webgpu: keep the gated delta net replay within the storage buffer limit
* delta_net : add ggml_gated_delta_net_ext, replay is the only rollback
ggml_gated_delta_net_ext takes the optional replay inputs and always
outputs one state. ggml_gated_delta_net(..., K) is back to its master
signature and is deprecated; both build the same op, so the backends
are unchanged.
The delta-net models (qwen35, qwen35moe, qwen4exp, clover-moe and the
KDA models) now always replay the kept tokens when n_rs_seq > 0. The
LLAMA_RS_REPLAY env flag and the snapshot branch of
build_recurrent_attn are removed.
test-backend-ops drops the K > 1 snapshot cases and the K parameter of
the gated delta net tests. The cache fusion test copies the single
state.
* ggml-cpu : spacemit: leave the gdn replay to the generic kernel
The RVV gated delta net kernel does not read the replay inputs. Return
false when op param 1 (n_pend) is set, so that the generic kernel runs
the op.
* vulkan : fill views at any offset
ggml_vk_fill bound dst without allowing a misaligned offset, so a fill
of a view whose offset is not a multiple of
minStorageBufferOffsetAlignment aborted. The recurrent state zeroing in
build_rs hits this with the wider replay conv rows on devices with a
64-byte alignment.
Bind dst from the aligned offset below it and pass the element offset
in KY. test_fill gets an offset to fill a view in place.
---------
Co-authored-by: Pascal <admin@serveurperso.com>
Co-authored-by: Max Krasnyansky <maxk@qti.qualcomm.com>
Co-authored-by: Li He <lih@qti.qualcomm.com>
* metal : batch concat rows and copy them in vector chunks
The concat kernel copied one element per thread, so wide rows with many rows ran at a
fraction of the memory bandwidth. Batch several rows per threadgroup and copy the
contiguous dim-0 elements in 4-element chunks when the row is contiguous.
Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
* test : cover concat vector and misaligned row paths
Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)
* metal : hoist the concat src1 row offset into scalars
Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)
* metal : peel to align the concat vector copy
Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)
* metal : vectorize concat rows along any dimension
Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)
* metal : specialize concat with function constants
Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)
* metal : drop the concat row-batch dispatch
Batching several rows per threadgroup reduces the number of threads by
the batch factor. On machines with a large GPU this leaves too few
requests in flight and the copy becomes latency bound:
M5 Ultra (36 CPU) f16 [1024,8,256,1] d=0 8.1 us -> 17.2 us
f32 [4096,8,256,1] d=0 35.4 us -> 118.5 us
f16 [4096,8,256,1] d=2 50.9 us -> 102.0 us
An interleaved sweep of the (nth, nrptg) dispatch over the concat perf
cases on an M2 Ultra and an M5 Ultra shows that the base dispatch is
best or tied for every shape once the rows are vectorized, and that the
gains of the previous commit come from the vector copy alone:
M2 Ultra f16 [1024,8,256,1] d=0 32.4 us -> 17.0 us
M5 Ultra f16 [1024,8,256,1] d=0 13.3 us -> 8.1 us
Keep the vector copy and the function-constant specialization, and
return to the original dispatch.
Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)
* metal : revert the concat function constants
Specializing the concat kernel on the concat dimension and on whether a
row is split across threadgroups with function constants makes the
strided scalar path slower. Interleaved over the concat perf cases on an
M5 Ultra, the specialized kernel is not faster than the plain one, and
it costs up to 18% on shapes that are already at the memory bandwidth
limit:
f32 [2050,8,256,1] b=255 d=0 21.0 us -> 25.1 us
f32 [2050,8,256,1] b=256 d=2 31.1 us -> 36.7 us
f16 [4096,8,256,1] b=256 d=2 31.2 us -> 36.7 us
Revert the specialization and keep copying rows with the runtime
arguments. The concat change is now limited to the kernel itself.
Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)
* compact bias on the existing FLASH_ATTN_EXT for CUDA, ROCm and Vulkan
* fixup! compact bias on the existing FLASH_ATTN_EXT for CUDA, ROCm and Vulkan
* remove the Vulkan support from this PR
* move the CUDA/HIP and Inkling 2 graph changes out of this PR
* CPU reference implementation of the indexed bias
* move the indexed bias test to test-backend-ops, add the bias in F32 on CPU
* incorporate review remarks
* llama, metal : support BF16 src1 for MUL_MAT and MUL_MAT_ID
Add GGML_PREC_BF16 handling for src1 on the Metal backend when the tensor
API is available: MUL_MAT with an F32 src0 stages the A tile as bfloat, and
MUL_MAT_ID stages src1 as bfloat instead of F16. The tensor path keeps src1
in F32 when it reads the operand directly.
Add a temporary LLAMA_MOE_AMAX_SKIP env var that disables the graph-level
amax rescaling for the MoE down projection and sets the BF16 src1 hint
instead. Apply the hint inside build_lora_mm_id so it reaches the matmul
before the per-expert scale and LoRA nodes wrap it.
Add MUL_MAT_ID src1 BF16 test cases to test-backend-ops.
Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
* metal : support BF16 src1 without the tensor API
Allow GGML_PREC_BF16 when the device has bfloat, not only when it has the
Metal4 tensor API.
Add legacy _prec_bf16 kernels for MUL_MAT and MUL_MAT_ID that stage src1 as
bfloat in the threadgroup and run the simdgroup multiply with bfloat A and B.
The F16 MUL_MAT_ID kernel uses half A on the tensor path and bfloat A on the
legacy path.
Cast the quantized dequantize outputs to the destination element type: the
older Metal compiler on M2 rejects implicit float to bfloat.
Tested on M2 Ultra (legacy): MUL_MAT_PREC_SRC1 24/24 and
MUL_MAT_ID_PREC_SRC1_BF16 30/30. Flint Q4_K_M with LLAMA_MOE_AMAX_SKIP=1:
pp512 -2.1%, tg128 +25.5% vs master. On M5 Max: pp512 +2.1%, tg128 +22.2%.
Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
* metal : derive matrix types with value_type helpers
Add value_type_4x4/value_type_2x4/value_type_8x8 helpers and use them in the MUL_MAT and MUL_MAT_ID kernels so the templates take only the underlying types and derive the matrix types. Add TODOs for the remaining kernels.
Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
* metal : derive matrix types in the remaining kernels
Use the value_type_* helpers in the flash-attention, top-k-mask, mul-mv and
count-equal kernels to derive the matrix/vector types from the underlying
scalar types, and simplify the FA_TYPES macros.
Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
* metal : enable BF16 in the tensor API metallib
The tensor API requires macOS 26, where bfloat is always available, so
define GGML_METAL_HAS_BF16 when compiling the tensor metallib. This makes
the bfloat specializations of the value_type helpers visible to
fa_tensor.metal and includes the prec_bf16 kernels in the prebuilt tensor
metallib.
Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
* metal : support GGML_PREC_F32 for src1 in MUL_MAT and MUL_MAT_ID
Split the tensor-API and legacy simdgroup mul_mm/mul_mm_id kernels into
separate files and library kinds, following the fa_tensor.metal example.
The legacy kernels, including the new _prec_f32 variants that stage src0
and src1 as float in shared memory, are compiled into the default mul_mm
library; the tensor variants live in a separate mul_mm_tensor library
kind and carry a _tensor host-name infix. Tensor devices run F32 src1
matmuls on the simdgroup path instead of the tensor API, which rounds
float operands to a reduced precision. This removes the MUL_MM_SG kind
and the #undef GGML_METAL_HAS_TENSOR compile. Add
MUL_MAT_ID_PREC_SRC1_F32 tests.
Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
* cont : indentation
* llama : move the MoE amax skip into the precision policy
Add llm_arch_mmid_down_bf16() for the architectures whose MoE down
projection uses the graph-level amax rescaling. Extract the precision
policy setup from load_tensors() into llama_model_base::load_prec_policy(),
and move the LLAMA_MOE_AMAX_SKIP handling there: it sets prec_src1 = BF16
for ffn_down_exps before the per-tensor policy is loaded. build_moe_ffn()
now skips the amax rescaling when the policy requests BF16.
Apply the policy with the original weight so cached experts get it, drop
the prec_src1 parameter from build_lora_mm_id(), and remove the prec_src1
serialization from the model saver.
Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
* cont : minor
* ggml : add SIGMOID backward pass
Sigmoid is used in Qwen3.5 hybrid models and had no backward pass.
Bump RPC protocol patch version for the new op.
Signed-off-by: gianni-cor <gianfranco.cordella@tether.io>
* replace assert with ggml_assert
Co-authored-by: Johannes Gäßler <johannesg@5d6.de>
* ggml : keep sigmoid backward checks in release builds
Assisted-by: Codex
* ggml : preserve existing operation IDs when adding SIGMOID_BACK
Assisted-by: Codex
---------
Signed-off-by: gianni-cor <gianfranco.cordella@tether.io>
Co-authored-by: Johannes Gäßler <johannesg@5d6.de>
Used angelX to optimize SYCL/drama 3 coordination, results are as follows
Each output reads only inputs with i*s0 <= idx < i*s0 + K, in the same ascending order as before.
Arc Pro B70, oneAPI 2026.1, test-backend-ops perf, base 9b56ccf00 vs patch, median of 3 same-boot A/B/A rounds, A/A 1.000-1.001:
| input [ne0, ne1] | kernel [K, OC, IC] | s0 | base us | patch us | speedup |
|---|---|---|---|---|---|
| [16, 1536] | [16, 768, 1536] | 8 | 3910.57 | 1348.59 | 2.90x |
| [128, 768] | [16, 384, 768] | 8 | 37735.00 | 1665.26 | 22.66x |
| [1024, 384] | [8, 192, 384] | 4 | 270371.75 | 1471.74 | 183.71x |
| [4096, 192] | [4, 96, 192] | 2 | 534614.63 | 752.74 | 710.23x |
Shapes are the drama 3 codec decoder upsampling stack, added as perf cases. Chained 4-layer stack at 1/4/24 input frames: base 66.3/847.4/28638.5 ms, patch 2.3/6.7/30.7 ms. Kernel numbers, not end-to-end TTS latency.
Correctness: test-backend-ops -o CONV_TRANSPOSE_1D 116/116 on base and patch, and 116/116 rebased on 3f03b1772. Seeded output dump (7.46 MB) byte-identical to base.
Full test-backend-ops aborts on base and patch alike at the non-F32 SWIGLU_OAI assert (element_wise.cpp:1187, see #30857). With only those cases excluded: 20145/20173 on base and patch, and every patch-run failure also fails on base.
Co-authored-by: Titaniumtown <titaniumtown@proton.me>
* ggml : add BF16 support to ROPE and SET_ROWS (CPU, CUDA)
* cuda : SET_ROWS from BF16 into quantized types and F8_E4M3
* cuda : fuse BF16 rope into a BF16 cache
* tests : trim the BF16 rope cases to one per code path
* Adds initial scheduler stress tests
* Adds new sleep op to simplify scheduler testing
* Adds testcase addressing https://github.com/ggml-org/llama.cpp/issues/23321
* Adds experimental vulkan GGML_OP_SLEEP
* Improves structure and naming of previous tests. Adds new tests,
including one which detects the nkvo-bug correctly, and validates the
proposed hotfix.
* Cleanup: Removes CUDA specific comments and nvtx-markers
* Fix: forgot to add sleep specific test case
* Fix oversights identified by CI
* Drops default prints so that it behaves like other ctests. Adds -v flag
to toggle this behavior
* Fix: Early exit in CPU-only settings (cause for graviton CI fails)
* Improves stress_test_linked_list by removing overlap with
test_chain_all_backends and test_pair_user_inputs. The latter ones test
either activations or user inputs in isolation and just once, whereas
the stress test tests all combinations multiple rounds
* Exclude ACCEL devices from new tests due to incompatibility
* Fixes vulkan test failure in llvmpipe
* Adds asserts, improves comments and some checks
* Fixes nitpicks in white-space and variable naming
* Adds comments that certain vk drivers could time OP_SLEEP incorrectly
* Drops limitiation to CPU/GPU in test-sleep
* Aligns OP_SLEEP guards in cuda with vk guards (input shape and
contiguity)
* Implements feedback for OP_SLEEP to work in place (no copy)
* Apply non-code suggestions from JohannesGaesslers code review
Co-authored-by: Johannes Gäßler <johannesg@5d6.de>
* Removes struct backend_supports; enables tests to return skip, instead
of only pass/fail
* Make clang-tidy happy
* Removes sched_backend_caps, improves create_test_scheduler according to
feedback (L149)
* Removes "name" field from struct sched_check in favor of
ggml_set_name/ggml_get_name
* Drops unnecessary shader_clock.comp test and guards
* Replaces sched_ prefixes with helper_ prefix
* Moves test suite to new RAII types for better memory management
* Adds sleep option to test_chain_all_backends
* Adds sleep option to first-run arm of the y-shaped test
* Fix switchcase order for legibility in stress_test_dag
* Simplfies stress_test_linked_list via double for-loop
* Adds pseudo-random input to stress_test_linked_list, and runs all
transitions both with and without CPU input (next to activation copy as
input)
* Fix RPC Proto patch due to GGML_OPS bump
* Adds ggml-cpp.h treatment to test-sleep.cpp
* Adds TODO pointers for subsequent additional tests.
* Apply suggestion to ggml.h
Co-authored-by: Johannes Gäßler <johannesg@5d6.de>
* Apply suggestion to tests/test-backend-sched.cpp
Co-authored-by: Johannes Gäßler <johannesg@5d6.de>
* Apply suggestion to tests/test-backend-sched.cpp
Co-authored-by: Johannes Gäßler <johannesg@5d6.de>
* Fixes node compatibility check to not take buffer locations into account.
This led to skipped tests due to incorrectly rejected ops due to wrong buffer locations in multi-GPU (which is one of the scheduler behaviors under test)
* Apply batched suggestions from gg code review
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
* Completes callsite change of gg-suggestion
* Switch test-sleep from std::chrono::steady_clock::now() to ggml_time_us
to avoid mac clock drift and spurious test failures.
This makes the test a bit nonsensical on CPU (same clock checks itself),
but the test still has merit on the other backends where
independent device clocks are used.
---------
Co-authored-by: Johannes Gäßler <johannesg@5d6.de>
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
* vulkan: Implement stream-k MUL_MAT
Stream-k tries to split chunks of 256 K elements evenly across all SMs.
Workgroups that finish a tile write to dst, others write to scratch, and
there's a resolve shader similar to split-k.
The shader code is implemented for scalar+cm1+cm2, but only currently enabled
for cm2. The heuristic for enabling on coopmat2 is pretty simple due to the
large tile size (one workgroup per SM), but would be more complex for the tile
sizes being used for cm1, and it doesn't make sense for me to tune that on
NVIDIA devices.
Assisted-by: Codex
* address review feedback
The MMQ kernels computed the dst tile offset (jt*J*stride_col_dst) in
32-bit int. For a dst with more than 2^31 elements, column tiles that
start past INT_MAX/nrows wrap around and write out of bounds.
This happens with an all-logits output head, e.g. llama-perplexity
-c 32768 -b 32768 -ub 16384 on a 248320-vocab model: the q8_0 output
matmul has a 248320 x 16384 dst (4.07e9 elements) and aborts with an
illegal memory access.
Widen the offsets in mul_mat_q and the stream-k fixup to int64_t, and
add a (disabled by default, ~9 GB) test-backend-ops case.
Assisted-by: Claude Opus 5.5
* model:add Zaya1 8B (Zyphra)
- Added the support for Zaya.
- Fixed the SSM_CONV case, so the model runs on cuda without abort.
Please enter the commit message for your changes. Lines starting
* Made the following changes based on the bot reviewer feedback:
1) Added runtime asserts when loading wrong KV head size, unsupported conv kernel size.
2) Removed the static cast usage.
3) Fixed double load of tokenizer.
4) Updated res_scale_in to be input tensor.
* - Moved the res_scale_in back to layer 0 to fix the cuda bug
* i) Removed the EOS addition.Team agreed that updating Tokenizer is the right move.
ii) Fixed formatting
* Fixed the comment to make it clear
---------
Co-authored-by: varun <varun_subramanian@zyphra.com>
* vulkan: expand bf16 support for unary and binary ops and rms_norm
* cpu: add bf16 support for scale, clamp, leaky_relu, swiglu_oai, swiglu_clamp, tri and diag
* fix sycl fill supports_op condition
* restore CUDA op order
* fix the SYCL fa with mkl error of a mask broadcast over heads or batches; add argument cache-ram to start-svr.sh
* add argument cache-ram to win-start-svr.bat
* fix format issue, remove --cache-ram in script: move to another PR
* Only run webgpu CI on my fork
* Add webgpu only workflow
* resolve merge conflicts
* save state
* save kernel
* add kernel back in
* fix merge issues with kernels
* updates
* update tests
* change invocation count and workgroup to be u32
* clang format
* clang format
* update docs
* format
* remove extra file
* vulkan: make the radix top-k tie selection deterministic
The radix select gathers the elements above the threshold and the ties
with an atomic counter, so with more ties than remaining slots the kept
columns depend on the thread scheduling.
Each subgroup now owns a contiguous chunk of the row with the same
column mapping in every pass, counts its kept elements, and writes them
at ranks from a scan of the subgroup totals; overflowing ties are ranked
in column order with a ballot, so the lowest tied columns win, as on
CUDA and Metal. The radix pipelines require subgroup arithmetic, ballot
and full subgroups. Enable the deterministic top-k check on Vulkan.
* optimize shader for AMD, Intel and Nvidia
---------
Co-authored-by: Ruben Ortlam <rortlam@redhat.com>
On AMD devices MUL_MAT_ID with an F32, F16 or BF16 src0 and at most 8 tokens always used MMVF.
MMVF reads src0 in pairs of values and asserts an even ne[0], so a rank 1 LoRA on MoE expert weights (lora_b has ne[0] == 1) aborted.
Use MMVF there only for an even ne[0]; other shapes take the existing fallback.
Fixes#30576
Assisted-by: GitHub Copilot
Signed-off-by: AMD ROCm Contributor <91481003+liminfei-amd@users.noreply.github.com>