Compare commits

..
26 Commits
Author SHA1 Message Date
Aleksander Grygier a6ac41c757 ui: match tool call timer font size to its title (#32922)
Assisted-by: Claude (Opus 5.5 Medium)
2026-11-24 09:25:18 +01:00
Aleksander Grygier 3fccd98e9d ui: let the chat form's model selection decide the submit state (#32920)
When the last assistant message came from a model that is no longer
available, the submit button stayed red and disabled even after an
available model was picked in the form, since availability checked the
conversation's model first. The form's selection now decides it; the
conversation's model only counts when nothing is selected.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-24 09:25:04 +01:00
Aman Gupta 4af4bb6d8a rpc : reuse one context for request tensors on the server (#32896) 2026-11-24 09:43:50 +02:00
Georgi GerganovandIsNot-10 b12f22d2f2 ggml : use a range-reduced log1p for softplus (#32655)
* 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>
2026-11-24 09:30:43 +02:00
losewayy d141011c25 vulkan: support state size 96 in ssm_scan (#32162)
* vulkan: support state size 96 in ssm_scan

Assisted-by: Claude Code

* vulkan: specialize ssm_scan state size

Assisted-by: Codex

* vulkan: clarify ssm_scan constant names

Assisted-by: Codex
2026-11-24 08:25:31 +01:00
lhez 12d47ba2f4 opencl: fix GDN QK offsets (#32747)
Assisted-by: Codex
2026-11-23 21:14:37 -08:00
lhezandHongqiang Wang af5c58347f opencl: add c8 q6_k coopk GEMM for up to n=8 spec verify (#32909)
Assisted-by: Codex

Co-authored-by: Hongqiang Wang <wangh@qti.qualcomm.com>
2026-11-23 17:12:33 -08:00
Max Krasnyansky c74c71a6f7 fix editor config in master (#32914) 2026-11-23 15:47:20 -08:00
Aldehir Rojas 38b9cad71d quantize : make local const static for MSVC (#32902) 2026-11-23 17:41:33 -06:00
d35dc4d9e6 GDN: use replay instead of rollback (#31669)
* 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>
2026-11-23 15:06:02 -08:00
Evan Huus c212d25ad3 server : preserve a prompt-cache entry until restores succeed (#32828)
Assisted-by: Codex
2026-11-23 21:50:29 +01:00
Hongqiang WangandLi He fd24ee26ad opencl: fetch the Adreno binary kernel library at configure time for Windows on Snapdragon (#31759)
* opencl: fetch the Adreno binary kernel library at configure time

Make GGML_OPENCL_USE_ADRENO_BIN_KERNELS an option, default ON, and add
GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH, default ON. On Windows, CMake
downloads the pinned adreno-opencl-kernels release from the Qualcomm
Software Center, verifies its SHA256, and copies the DLL and its license
next to the executables. A failed download is only a warning; the
backend then uses its builtin kernels.

The opencl-adreno release job turns the fetch off, since it ships only
ggml-opencl.dll.

* opencl: fetch the Adreno binary kernel library only on ARM64

The library is built for Windows on ARM64 only.

* opencl: add download timeout and better handle output dir

Assisted-by: Codex

* opencl: add .txt to license file

Assisted-by: Codex

---------

Co-authored-by: Li He <lih@qti.qualcomm.com>
2026-11-23 12:39:04 -08:00
Aleksander Grygier 8355b88625 ui: remove the Matte theme and the Light surfaces setting (#32906)
Paper is now the only light theme: its surface tokens stay the base
values, and the theme-matte overrides, the setting, its enum and the
Storybook surface switch are gone.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 21:38:18 +01:00
Georgi Gerganov 51831d47d0 metal : add NVFP4 support (#32825)
* metal : add NVFP4 support

Follow the MXFP4 path: add the UE4M3 scale decode, the NVFP4 dequantizers,
a dedicated mat-vec kernel with its MUL_MAT_ID, small-batch and MMA variants,
the mul_mm / mul_mm_id and tensor-op variants, and the get_rows and cpy
kernels. Enable the type in supports_op.

Tested on an M5 Max with ggml-org/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-GGUF:NVFP4
and test-backend-ops (MUL_MAT, MUL_MAT_ID, W4A8/W4A4, CPY, GET_ROWS).

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (2x DGX Spark (RDMA, TP=2))

* metal : skip the small-batch path for NVFP4

With the few-row MMA kernels covering ne11 3..16, the small-batch mat-vec
kernels are only reachable at ne11 = 2, where they are 17-59% slower than the
generic mat-vec kernel on an M2 Ultra and an M5 Max.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (2x DGX Spark (RDMA, TP=2))
2026-11-23 21:02:30 +02:00
Georgi Gerganov ab789a246c metal : batch concat rows and copy them in vector chunks (#32824)
* 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)
2026-11-23 21:01:41 +02:00
Piotr Wilkin (ilintar) 239242322d ggml: compact bias on the existing FLASH_ATTN_EXT (#32740)
* 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
2026-11-23 18:17:11 +01:00
Ed Addario 30ec35ae2e quantize: add option to automatically choose optimal quant types to reach a file/bpw target size at lowest error (#15550)
* Refactor pareto optimise and convexify
* Refactor lagrange_penalty()
* Refactor quantisation checks into its own function
* Exit loop if no better solution found
* Replace slope with cross product
* Adjust for small vector size
* Simplify candidates sorting
* Add comments to explain magic numbers
* Increase scale multiplier
* Move is_iq() into a lambda and remove unused variables
* Combine quant types
* Reduce bpw range
* Refactor outlier trimming
* Tighten worker allocator
* Check for direction reversal
* Simplify dequantisation
* Calculate bpw over all tensors
* Compute rows based on tensor shape and slice count
* Prioritise important tensors
* Select quantization type if target_bpw is set unless user specifies type and threads
* Relax lambda clamping
* Add signal handler
* Add save_bpw_state()
* Add load_bpw_state()
* Add delete_bpw_state()
* Persist progress
* Uninstall signal handler and cleanup
* Fix trimming logic
* Generate model ID hash
* Remove bias mode computation
* Remove --no-bias option
* Automatically determine if bias error is significant
* Reduce compute time by parallelising tensor processing - courtesy of https://github.com/ddh0
* Add quant types
* Add --keep-bpw-state option
* Refactor signal handlers
* Update quant types
* Minor refactoring
* Add tensor type and depth heuristics
* Add option to override bpw state file name
* Minor refactoring
* Finetune heuristics
* Update usage
* Fix lambda capture
* Update epsilon specifier
* Finetune heuristics
* Simplify tensor selection
* Read statistics from imatrix
* Add Euclidean-Cosine score to identify important tensors
* Improved is_important() logic
* Fix lambda capture bug in Windows and initialise candidate_types struct
* Remove processing statistics_data
* Add --disable-tensor-importance option
* Use more descriptive option naming
* Relax target bpw range
* Increase importance boost for final pass
* Add B/F16 to get_ftype()
* Process bpw targets up to B/F16
* Improve state checkpoint filename
* Add code comments
* Update usage()
* Update README.md
* Change checkpoint file magic
* Prepare for future optimization algorithms
* Add parse_target_size()
* Add --target-size option
* Implement target_size logic
* Update usage()
* Refactor parameter names
* Refactor option names
* Update parameter names
* Improve file handling
* Remove file deletion
* Refactor variable names
* Update usage()
* Add use_wce option
* Read statistics_data from imatrix
* Add experimental entropy-modulated weighted cosine error (WCE)
* Performance optimisations (AI assisted)
* Memory optimisations (AI assisted)
* Update output log
* Fix state file name generation and simplify_pareto() lambda capture
* Change tensor importance score logic
* Refactor is_quantizable()
* Improve WCE to be magnitude-aware
* Expected Output Error MSE
* Fix scale factor overwrite bug
* Test removing unused headers
* Remove wce flag
* Angle-aware/Magnitude-aware (MSE/WCE) hybrid error estimation
* Revert to weighted cosine error estimation
* Enhanced scaling factor
* Use centered‑normalized importance scaling factor (CNIF)
* Remove redundant logs
* Improve state file handling
* Update usage instructions
* Update ftype parsing logic
* Flag experimental features subject to future removal
* Fix --target-size description
* Fix "casts away qualifiers" compiler warning
* Exclude user defined tensors (--tensor-type) from the Lagrangian optimization
(courtesy of https://github.com/AesSedai)
* TurboQuant bias factor for inner-product sensitive tensors
* TurboQuant outlier mitigation
* Refactor TurboQuant improvements
* Fix remap tensor bug
* Remove --importance-pct option
* Refactor llama_model_quantize_params to expose a pure C interface
* Consolidate load/save process and remove --save-state flag
* Minor log output changes
* Use the tensor statistics' schema
* Add quant types
* Release finished tensors mmap allocation
* Reuse sample buffers
* Fix C2327 error when target compilation is a MS platform
* Minor refactoring and AI assisted optimizations
* Add uv.lock
* Minor refactoring and AI assisted optimizations
* Add Halko, Martinsson & Tropp randomized SVD condition number estimator
* Add kappa squashing functio
* Remove unnecessary includes
* Add required include
* Update python dependencies
* Fine-tune kappa mapping parameters
* Fine-tune CNIF beta parameters
* Fix fallback counter error
* Move to libllama and unmap weights offloaded to backend
* Remove unmap weights offloaded to backend
* Add winsorization
* Add adaptive tensor boosting
* Minor cosmetic changes
* Refactor processing of unused kv tensors
* Minor cosmetic change
* Implement --max-buffer-size in target_bpw_type()
* Fix 32-block fallback case
* tensor_type_override_for() DRY refactoring
* Fix typo and remove unused option
* Fix #28491 linking bug when compiling with BUILD_SHARED_LIBS=OFF
* Remove GGML_USE_METAL conditional macro and let the optimizer decide\
* Add --target-exclude
* Remove and ignore uv.lock
* Fix pinned tensors safety limits calculation
* Fix truncation error
* Add downwards greedy upgrade
* Add target bpw/size tests
* Guard imatrix schema
* Update --target-bpw/size descriptions and README.md
* Harden state checkpoint's file operations
* Link model and imatrix to state checkpoint
* Enforce and consume stats schema data
* Add stats schema tests
* Refactor signal handlers out of lib and harden the logic
* Improve handling of pinned tensors
* Add tests
* Add include to keep ubuntu-webgpu happy
* Moving new API entries to prevent brittle downstream apps failing
* Fix miscellaneous issues
2026-11-23 18:06:26 +01:00
Georgi Gerganov 87f816e87f metal : support BF16/F32 src1 for MUL_MAT and MUL_MAT_ID (#32677)
* 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
2026-11-23 18:46:12 +02:00
Aleksander Grygier 1d3aad2fd8 server: ask exec_shell_command for a short description of the command (#32894)
The shell tool's schema gains a required `description` argument, listed
first: a short plain-language line on what the command does. The tool
ignores it, as before; clients can show it in place of the raw command
while the call streams and in their logs. Calls without it still run.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 17:28:56 +01:00
Aleksander Grygier 325914defd ui: show an agentic reply as a grouped Agent Trace (#32879)
* ui: show tool calls in the trace as a grouped, plain-language log

Tool calls and all the reasoning around them, up to the answer, collapse
into one row whose title sums up what happened ("Ran 2 commands, read 1
file"), so a model that thinks before every call still reads as one row
of work. Two calls, or one call with reasoning beside it, make a group;
without per-turn stats a group spans turns.

Each call reads as a sentence: built-in tools get hand-written phrasing
in two tenses, MCP and unknown tools read as "Used <tool> <argument>",
and the generic block shows simple arguments as labelled fields. A call
that has the argument a display setting picks (description by default,
overridable per tool in Settings > Tools) shows it as the model wrote it
instead, for any tool that declares it. A shell row always shows the
command, after "Ran" or after that description, and opens into the
terminal; the permission card shows the command that would run.

An open group is a list of rows under one rule, with no icons in the
headings; a running row shimmers. While a group is live its title says
what is happening now ("Reading package.json", "Thinking"), with a timer
since the prompt was sent, and the loop records the task's total time,
which the response stats show. Thoughts and tool calls now stay collapsed
while generating, with a one-time migration of the saved old default.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: keep a live reply steady while its status changes

The status line ( Loading weights, Processing 40% ) sat above the content
before the first token and below it afterwards, and collapsed to nothing
while tokens streamed, so the stats and actions under it jumped. It is now
one row in the trace column with a trace row's box, shown only while
nothing else is moving, and while a tool group closes the reply it becomes
that group's live title instead.

The model badge shows from the start of a live reply, the user message
reserves its stats row while the prompt is processed, and a collapsed
group title is muted.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: glide a sent message to the top of the screen

Sending snapped the page to its bottom in one frame, and layout that
settled a moment later was followed with more snaps. The page now eases
there: the target is read again every frame, so late layout bends the
motion instead of ending it with a jump, and corrections shortly after a
send are glided to as well.

A frame that arrives late counts as one frame, so a busy page slows the
glide instead of skipping it. Wheel, touch and scroll keys hand the page
back at once; typing the next message does not. Reduced motion keeps the
jump.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: show tool images in the trace and in one slideshow of the thread

A closed tool group shows every image its calls produced under its title,
64px tall at their own proportions, in a carousel once they overflow; the
strip fades out when the group opens. A call with images shows tiny
thumbnails beside its title while its row is closed.

A group thumbnail, or an image in a user message, opens one slideshow of
every image, audio clip and video in the open thread, in thread order, at
the clicked item.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: quiet the conversation around its messages

Stats and actions under earlier messages stay hidden until the reader
points at the message or tabs into it, changing only opacity so nothing
moves; the latest exchange keeps them in view and touch screens keep them
shown. A Display setting, Always show message statistics, keeps every
message's statistics in view.

With them out of sight the spacing tightens: messages sit 1rem apart, the
answer sits 0.75rem from the trace rows around it, and the user message's
stats and actions sit closer together. A queued message no longer sticks
to the bottom of the screen and scrolls with the conversation.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: name the agentic reply an Agent Trace and give basic chat its own view

A reply that ran the agentic loop is now an Agent Trace: the component
that renders it is ChatMessageAgentTrace, with matching class names and
docs. A basic chat reply, with no tool calls, renders through the new
ChatMessageAssistantResponse as its reasoning and its answer, without the
trace's grouping, timer and permission handling. hasAgenticContent picks
the view, so a live reply becomes a trace the moment its first tool call
streams in.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 17:24:05 +01:00
Aleksander Grygier 1094646c1f ui: set code in messages at the size of the text around it (#32892)
Inline code and code blocks were 14px next to 16px text. Llama Mono
has Llama Sans's x-height, so the two read as one size without the
mono being scaled down. The chat form's editor follows.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 16:21:45 +01:00
Aleksander Grygier 27d0a1fc73 ui: unmount a closed collapsible's body after one transition (#32881)
bits-ui rebuilds the Collapsible.Content snippet args when its close
transition ends, which re-ran the region's effect and restarted the
unmount timer, so a closed body stayed mounted for two transitions
instead of one. Reading `open` through a derived keeps the effect from
rerunning when only the args object changes.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 16:20:15 +01:00
Aleksander Grygier b6d5ce4bc9 ui: drop tool calls cut off by Stop from the next request (#32738)
* ui: drop tool calls cut off by Stop from the next request

A tool call stopped mid-stream could stay on its message with cut-off
arguments. The server parses every call's arguments as JSON, so the next
message in that chat ("Continue") failed with "Failed to parse tool call
arguments as JSON". Requests now leave such calls out, with the tool results
that answer them, and send a call with no arguments as {}.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: add a demo trace that ends in a stopped tool call

A conversation whose last tool call was stopped while its arguments were
still streaming, for recording the fix in the previous commit.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 16:18:59 +01:00
bri-prism 1f3ea67fbf metal: resolve gpu timeout on iPhone for Bonsai (#31815) 2026-11-23 17:15:34 +02:00
Aleksander Grygier a0677c341b ui: use a red edge on the send button's error state (#32856)
The error state reused the primary button's edge, which shows as a light
ring in dark mode. Use the danger button's edge instead.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 15:47:30 +01:00
Aleksander Grygier 2359d27a36 ui: name the PWA from the build env and default it to Llama Chat (#32890)
The manifest is built in Node by its Vite plugin, where import.meta.env is not set, so it was
always named llama-ui whatever VITE_PUBLIC_APP_NAME said. The plugin now names it from the env
Vite loaded (.env files included), and the default name is Llama Chat.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 15:45:44 +01:00
222 changed files with 12678 additions and 2793 deletions
+1 -1
View File
@@ -1129,7 +1129,7 @@ jobs:
target: 'ggml-vulkan'
- backend: 'opencl-adreno'
arch: 'arm64'
defines: '-G "Ninja Multi-Config" -D CMAKE_TOOLCHAIN_FILE=cmake/arm64-windows-llvm.cmake -DCMAKE_PREFIX_PATH="$env:RUNNER_TEMP/opencl-arm64-release" -DGGML_OPENCL=ON -DGGML_OPENCL_USE_ADRENO_KERNELS=ON'
defines: '-G "Ninja Multi-Config" -D CMAKE_TOOLCHAIN_FILE=cmake/arm64-windows-llvm.cmake -DCMAKE_PREFIX_PATH="$env:RUNNER_TEMP/opencl-arm64-release" -DGGML_OPENCL=ON -DGGML_OPENCL_USE_ADRENO_KERNELS=ON -DGGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=OFF'
target: 'ggml-opencl'
steps:
+27
View File
@@ -117,14 +117,32 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
imatrix.chunk_size = chunk_size_key != -1 ? gguf_get_val_u32(ctx_gguf, chunk_size_key) : 0;
imatrix.n_layer_nextn = nextn_key != -1 ? gguf_get_val_u32(ctx_gguf, nextn_key) : 0;
const int64_t schema_idx = gguf_find_key(ctx_gguf, LLM_KV_IMATRIX_STATS_SCHEMA);
if (schema_idx != -1 && gguf_get_kv_type(ctx_gguf, schema_idx) == GGUF_TYPE_ARRAY &&
gguf_get_arr_type(ctx_gguf, schema_idx) == GGUF_TYPE_STRING) {
const int64_t n_schema = gguf_get_arr_n(ctx_gguf, schema_idx);
imatrix.stats_schema.resize(n_schema);
for (int64_t i = 0; i < n_schema; ++i) { imatrix.stats_schema[i] = gguf_get_arr_str(ctx_gguf, schema_idx, i); }
} else {
if (schema_idx != -1) {
LOG_WRN("%s: %s in %s is not an array of strings, using the default order\n", __func__, LLM_KV_IMATRIX_STATS_SCHEMA, fname.c_str());
}
imatrix.stats_schema = {
"sum_sq", "mean", "elements", "std_deviation", "skewness", "kurtosis", "gain", "h_norm", "l2_dist", "cossim", "pearson", "covariance",
};
}
const std::string in_sum_suffix{ ".in_sum" };
const std::string in_sum2_suffix{ ".in_sum2" };
const std::string counts_suffix{ ".counts" };
const std::string stats_suffix{ ".stats" };
struct sum_tensors {
struct ggml_tensor * in_sum = nullptr;
struct ggml_tensor * in_sum2 = nullptr;
struct ggml_tensor * counts = nullptr;
struct ggml_tensor * stats = nullptr;
};
std::map<std::string, sum_tensors> sums_counts_for;
@@ -138,6 +156,8 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
sums_counts_for[std::move(name)].in_sum2 = cur;
} else if (string_remove_suffix(name, counts_suffix)) {
sums_counts_for[std::move(name)].counts = cur;
} else if (string_remove_suffix(name, stats_suffix)) {
sums_counts_for[std::move(name)].stats = cur;
}
}
@@ -146,6 +166,7 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
const struct ggml_tensor * in_sum = sc.second.in_sum;
const struct ggml_tensor * in_sum2 = sc.second.in_sum2;
const struct ggml_tensor * counts = sc.second.counts;
const struct ggml_tensor * stats = sc.second.stats;
if (!in_sum2 || !counts || (in_sum != nullptr && ggml_nelements(in_sum) != ggml_nelements(in_sum2))) {
LOG_ERR("%s: mismatched sums and counts for %s\n", __func__, name.c_str());
@@ -182,6 +203,12 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
e.activations[j] = ((const float *) in_sum->data)[j];
}
}
if (stats && stats->type == GGML_TYPE_F32) {
const int64_t n_stats = ggml_nelements(stats);
e.stats.resize(n_stats);
for (int64_t j = 0; j < n_stats; ++j) { e.stats[j] = ((const float *) stats->data)[j]; }
}
}
gguf_free(ctx_gguf);
+2
View File
@@ -15,11 +15,13 @@ struct common_imatrix_entry {
std::vector<float> sums;
std::vector<float> activations;
std::vector<int64_t> counts;
std::vector<float> stats;
};
struct common_imatrix {
std::map<std::string, common_imatrix_entry> entries;
std::vector<std::string> datasets;
std::vector<std::string> stats_schema;
int32_t chunk_count = 0;
int32_t chunk_size = 0;
int32_t n_layer_nextn = 0;
+15 -8
View File
@@ -83,22 +83,29 @@ Since common quantizations are supported now, it is recommanded to download GGUF
A prebuilt binary kernel library has been introduced for Adreno GPUs.
It currently targets X2 GPUs (X2-90, X2-85 and X2-45) found in Snapdragon X2 SoC.
The library currently contains kernels for MUL_MAT_ID with Q4_0, Q4_1, Q4_K, MXFP4.
The library must be manually downloaded from https://softwarecenter.qualcomm.com/catalog/item/Adreno_Kernel_Library_GGML.
The library is published at https://softwarecenter.qualcomm.com/catalog/item/Adreno_Kernel_Library_GGML.
Its use is subject to the license in the `license.txt` file shipped with it.
To allow using the kernel library, add `-DGGML_OPENCL_USE_ADRENO_BIN_KERNELS=ON` when configuring with CMake.
Then, extract `adreno-opencl-kernels.dll` from the zip file downloaded from the above URL and put it alongside the executables.
The library is enabled by default (`GGML_OPENCL_USE_ADRENO_BIN_KERNELS=ON`).
On Windows on ARM64, CMake downloads the library version pinned in `ggml/src/ggml-opencl/CMakeLists.txt` during configuration (`GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=ON`).
The download is verified against a SHA256 hash, and the build copies `adreno-opencl-kernels.dll` and `LICENSE-adreno-opencl-kernels.txt` alongside the executables.
If the download fails, configuration continues with a warning.
To skip the download, add `-DGGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=OFF`, then extract `adreno-opencl-kernels.dll` from the zip file downloaded from the above URL and put it alongside the executables yourself.
If kernels compatible with the current GPU are found in the library, they will be loaded and used.
If the library is missing, the builtin kernels are used.
Add `-DGGML_OPENCL_USE_ADRENO_BIN_KERNELS=OFF` to disable the library entirely.
## CMake Options
The OpenCL backend has the following CMake options that control the behavior of the backend.
| CMake options | Default value | Description |
|:------------------------------------:|:--------------:|:------------------------------------------|
| `GGML_OPENCL_EMBED_KERNELS` | `ON` | Embed OpenCL kernels into the executable. |
| `GGML_OPENCL_USE_ADRENO_KERNELS` | `ON` | Use kernels optimized for Adreno. |
| `GGML_OPENCL_USE_ADRENO_BIN_KERNELS` | `OFF` | Allow using binary kernel lib for Adreno. |
| CMake options | Default value | Description |
|:--------------------------------------:|:--------------:|:--------------------------------------------------------|
| `GGML_OPENCL_EMBED_KERNELS` | `ON` | Embed OpenCL kernels into the executable. |
| `GGML_OPENCL_USE_ADRENO_KERNELS` | `ON` | Use kernels optimized for Adreno. |
| `GGML_OPENCL_USE_ADRENO_BIN_KERNELS` | `ON` | Allow using binary kernel lib for Adreno. |
| `GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH` | `ON` | Download the binary kernel lib for Adreno (Windows ARM64). |
## Decomposed Flash Attention
+2
View File
@@ -269,6 +269,8 @@ option(GGML_OPENCL "ggml: use OpenCL"
option(GGML_OPENCL_PROFILING "ggml: use OpenCL profiling (increases overhead)" OFF)
option(GGML_OPENCL_EMBED_KERNELS "ggml: embed kernels" ON)
option(GGML_OPENCL_USE_ADRENO_KERNELS "ggml: use optimized kernels for Adreno" ON)
option(GGML_OPENCL_USE_ADRENO_BIN_KERNELS "ggml: load the Adreno binary kernel library" ON)
option(GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH "ggml: fetch the Adreno binary kernel library" ON)
set (GGML_OPENCL_TARGET_VERSION "300" CACHE STRING
"ggml: OpenCL API version to target")
+39 -6
View File
@@ -2292,6 +2292,15 @@ extern "C" {
struct ggml_tensor * a,
struct ggml_tensor * sinks);
GGML_API bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a);
// Add table[indices[key, query], head, query] to the mask, in F32.
// Queries from all streams are flattened in stream order. Indices must be in [0, table->ne[0]).
GGML_API void ggml_flash_attn_ext_add_indexed_bias(
struct ggml_tensor * a,
struct ggml_tensor * table,
struct ggml_tensor * indices);
// TODO: needs to be adapted to ggml_flash_attn_ext
GGML_API struct ggml_tensor * ggml_flash_attn_back(
struct ggml_context * ctx,
@@ -2426,11 +2435,17 @@ extern "C" {
// beta : [1, H_v, n_tokens, n_seqs]
// state : [S_v, S_v, H_v, n_seqs] -- initial recurrent state s0
//
// the output packs the attention scores [S_v, H_v, n_tokens, n_seqs] followed by K state
// snapshots, most-recent first (slot 0 = final state, slot s = state s tokens back). K == 1
// keeps only the final state; when n_tokens < K only slots 0..n_tokens-1 are written.
// when n_tokens > K only slot 0 is guaranteed; backends may leave slots 1..K-1 unwritten.
GGML_API struct ggml_tensor * ggml_gated_delta_net(
// the output packs the attention scores [S_v, H_v, n_tokens, n_seqs] followed by the final state [S_v, S_v, H_v, n_seqs]
//
// replay (optional, set all of pend_k, pend_v, pend_gb and n_rep, or none): first runs the pending tokens of the
// previous ubatch, so that a rollback only drops pending tokens instead of restoring a snapshot
// pend_k : [S_k, H_k, n_pend, n_seqs]
// pend_v : [S_v, H_v, n_pend, n_seqs]
// pend_gb : [g0, H_v, 2*n_pend, n_seqs], the gates of the n_pend tokens, then their betas (in element 0)
// n_rep : I32 [n_seqs], number of pending tokens to replay (<= n_pend)
// the state output is the state after the replay if keep is true, else the final state.
// op param 1 is n_pend (0 without replay): backends that do not implement the replay reject the op when it is set
GGML_API struct ggml_tensor * ggml_gated_delta_net_ext(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * k,
@@ -2438,7 +2453,25 @@ extern "C" {
struct ggml_tensor * g,
struct ggml_tensor * beta,
struct ggml_tensor * state,
int64_t K);
struct ggml_tensor * pend_k,
struct ggml_tensor * pend_v,
struct ggml_tensor * pend_gb,
struct ggml_tensor * n_rep,
bool keep);
// the output packs the attention scores followed by K state snapshots, most-recent first (slot 0 = final state,
// slot s = state s tokens back). when n_tokens < K only slots 0..n_tokens-1 are written. when n_tokens > K only
// slot 0 is guaranteed; backends may leave slots 1..K-1 unwritten.
GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_gated_delta_net(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * k,
struct ggml_tensor * v,
struct ggml_tensor * g,
struct ggml_tensor * beta,
struct ggml_tensor * state,
int64_t K),
"use ggml_gated_delta_net_ext instead");
// DSA lightning indexer
//
+15
View File
@@ -152,6 +152,10 @@ static ggml_backend_buffer_type_t ggml_backend_meta_device_get_buffer_type(ggml_
static ggml_backend_buffer_type_t ggml_backend_meta_device_get_host_buffer_type(ggml_backend_dev_t dev);
static bool ggml_backend_meta_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
GGML_ASSERT(ggml_backend_dev_is_meta(dev));
const ggml_backend_meta_device_context * meta_dev_ctx = (const ggml_backend_meta_device_context *) dev->context;
return std::all_of(meta_dev_ctx->simple_devs.begin(), meta_dev_ctx->simple_devs.end(),
@@ -871,11 +875,22 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(
};
auto handle_gated_delta_net = [&](const std::vector<ggml_backend_meta_split_state> & src_ss) -> ggml_backend_meta_split_state {
// replay (src 6..9): the pending k, v and gates/betas are split by heads like k, v and g, n_rep is per seq
const bool replay = tensor->src[6] != nullptr;
if (src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED &&
src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[3].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED &&
src_ss[4].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[5].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED) {
for (int i = 6; replay && i < 10; i++) {
GGML_ASSERT(src_ss[i].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED);
}
return src_ss[0];
}
if (replay) {
GGML_ASSERT(src_ss[6].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[7].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[8].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[9].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED);
}
GGML_ASSERT(src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_1);
+2 -2
View File
@@ -2679,8 +2679,8 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten
return true;
case GGML_OP_FLASH_ATTN_EXT:
{
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
if (op->src[5] != nullptr) {
// K/V row lists and indexed bias are not supported
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
#ifdef ASCEND_310P
+4 -3
View File
@@ -3068,9 +3068,10 @@ struct ggml_cplan ggml_graph_plan(
} break;
case GGML_OP_GATED_DELTA_NET:
{
const int64_t S_v = node->src[2]->ne[0];
const int64_t K = ggml_get_op_params_i32(node, 0);
const int64_t per_thread = S_v + (K > 1 ? S_v * S_v : 0);
const int64_t S_v = node->src[2]->ne[0];
const int64_t K = ggml_get_op_params_i32(node, 0);
const bool keep = node->src[6] && ggml_get_op_params_i32(node, 2) != 0;
const int64_t per_thread = S_v + (K > 1 || keep ? S_v * S_v : 0);
cur = per_thread * sizeof(float) * n_tasks;
} break;
case GGML_OP_COUNT:
+4
View File
@@ -422,6 +422,10 @@ static ggml_backend_buffer_t ggml_backend_cpu_device_buffer_from_host_ptr(ggml_b
}
static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) {
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
const struct ggml_tensor * src0 = op->src[0];
const struct ggml_tensor * src1 = op->src[1];
+79 -5
View File
@@ -8981,6 +8981,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
const ggml_tensor * mask = dst->src[3];
const ggml_tensor * sinks = dst->src[4];
const ggml_tensor * kv_rows = dst->src[5];
const ggml_tensor * bias_table = dst->src[6];
const ggml_tensor * bias_indices = dst->src[7];
GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
@@ -9022,6 +9024,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
const int64_t rv2 = neq2/nev2;
const int64_t rv3 = neq3/nev3;
const int64_t n_bins = bias_table ? bias_table->ne[0] : 0;
// parallelize by q rows using ggml_vec_dot_f32
float scale = 1.0f;
@@ -9085,12 +9089,21 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
const int32_t * rows = kv_rows ? (const int32_t *) ((const char *) kv_rows->data + iq3*kv_rows->nb[1]) : nullptr;
// bias rows of this query and head, queries of all streams are flattened
const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr;
const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1)*bias_indices->nb[1]) : nullptr;
// online softmax / attention
// loop over n_kv and n_head_kv
// ref: https://arxiv.org/pdf/2112.05682.pdf
for (int64_t ic = ic_start; ic < ic_end; ++ic) {
const float mv = mp ? slope*GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f;
float mv = mp ? GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f;
if (bias) {
GGML_ASSERT(bins[ic] >= 0 && bins[ic] < n_bins);
mv += bias[bins[ic]];
}
mv *= slope;
if (mv == -INFINITY) {
continue;
}
@@ -9268,6 +9281,10 @@ static void ggml_compute_forward_flash_attn_ext_tiled(
const ggml_tensor * kv_rows = dst->src[5];
const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : nek1;
const ggml_tensor * bias_table = dst->src[6];
const ggml_tensor * bias_indices = dst->src[7];
const int64_t n_bins = bias_table ? bias_table->ne[0] : 0;
int ir = ir0;
while (ir < ir1) {
// q indices for the start of this tile
@@ -9346,8 +9363,15 @@ static void ggml_compute_forward_flash_attn_ext_tiled(
bool can_skip = true;
for (int tq = 0; tq < tile_rows; tq++) {
const ggml_fp16_t * mp_row = (const ggml_fp16_t *)((const char *) mask->data + (iq1 + tq)*mask->nb[1] + (iq2%mask->ne[2])*mask->nb[2] + (iq3%mask->ne[3])*mask->nb[3]);
const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1 + tq)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr;
const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1 + tq)*bias_indices->nb[1]) : nullptr;
for (int tk = 0; tk < kv_tile; tk++) {
mask32[tq * KV_TILE_SZ + tk] = slope * GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]);
float m = GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]);
if (bias) {
GGML_ASSERT(bins[ic + tk] >= 0 && bins[ic + tk] < n_bins);
m += bias[bins[ic + tk]];
}
mask32[tq * KV_TILE_SZ + tk] = slope * m;
if (mask32[tq * KV_TILE_SZ + tk] != -INFINITY) {
can_skip = false;
}
@@ -11289,11 +11313,19 @@ static void ggml_compute_forward_gated_delta_net_one_chunk(
// per-seq stride in floats (seq s starts at state + s * seq_stride)
const int64_t state_seq_stride = src_state->nb[3] / sizeof(float);
const int64_t per_thread = S_v + (K > 1 ? S_v * S_v : 0);
// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
const ggml_tensor * src_pk = dst->src[6];
const ggml_tensor * src_pv = dst->src[7];
const ggml_tensor * src_pgb = dst->src[8];
const ggml_tensor * src_n_rep = dst->src[9];
const int64_t n_pend = src_pk ? ggml_get_op_params_i32(dst, 1) : 0;
const bool keep = src_pk && ggml_get_op_params_i32(dst, 2) != 0;
const int64_t per_thread = S_v + (K > 1 || keep ? S_v * S_v : 0);
const int ith = params->ith;
float * delta = (float *)params->wdata + ith * per_thread + CACHE_LINE_SIZE_F32;
float * state_work = K > 1 ? (delta + S_v) : nullptr;
float * state_work = K > 1 || keep ? (delta + S_v) : nullptr;
// output layout: [attn_scores | new_states]
// attn_scores: S_v * H * n_tokens * n_seqs floats
@@ -11327,7 +11359,7 @@ static void ggml_compute_forward_gated_delta_net_one_chunk(
// For K=1, write directly to the single output slot to avoid an extra memcpy at the end.
// For K>1, work in scratch and copy out per-token when the slot is in range.
float * s_out = (K > 1)
float * s_out = (K > 1 || keep)
? state_work
: state_out_base + (iv3 * H + iv1) * S_v * S_v;
@@ -11336,6 +11368,48 @@ static void ggml_compute_forward_gated_delta_net_one_chunk(
const float * s_in = state_in_base + iv3 * state_seq_stride + iv1 * S_v * S_v;
memcpy(s_out, s_in, S_v * S_v * sizeof(float));
if (src_pk) {
const int64_t n_r = ((const int32_t *) src_n_rep->data)[iv3];
GGML_ASSERT(n_r >= 0 && n_r <= n_pend);
const char * pk = (const char *) src_pk->data + iv3*src_pk->nb[3] + ik1*src_pk->nb[1];
const char * pv = (const char *) src_pv->data + iv3*src_pv->nb[3] + iv1*src_pv->nb[1];
const char * pgb = (const char *) src_pgb->data + iv3*src_pgb->nb[3] + iv1*src_pgb->nb[1];
for (int64_t t = 0; t < n_r; t++) {
const float * k_d = (const float *) (pk + t*src_pk->nb[2]);
const float * v_d = (const float *) (pv + t*src_pv->nb[2]);
const float * g_d = (const float *) (pgb + t*src_pgb->nb[2]);
const float beta_val = *(const float *) (pgb + (n_pend + t)*src_pgb->nb[2]);
if (kda) {
for (int64_t i = 0; i < S_v; ++i) {
delta[i] = expf(g_d[i]);
}
for (int64_t j = 0; j < S_v; ++j) {
ggml_vec_mul_f32(S_v, &s_out[j * S_v], &s_out[j * S_v], delta);
}
} else {
ggml_vec_scale_f32(S_v * S_v, s_out, expf(g_d[0]));
}
for (int64_t j = 0; j < S_v; ++j) {
float sum = 0.0f;
ggml_vec_dot_f32(S_v, &sum, 0, &s_out[j * S_v], 0, k_d, 0, 1);
delta[j] = (v_d[j] - sum) * beta_val;
}
for (int64_t j = 0; j < S_v; ++j) {
ggml_vec_mad_f32(S_v, &s_out[j * S_v], k_d, delta[j]);
}
}
// the committed state, the new tokens go on in the scratch
if (keep) {
memcpy(state_out_base + (iv3 * H + iv1) * S_v * S_v, s_out, S_v * S_v * sizeof(float));
}
}
// attn output pointer for first token of this (head, seq)
float * attn_data = attn_out_base + (iv3 * n_tokens * H + iv1) * S_v;
+2 -1
View File
@@ -1156,7 +1156,8 @@ class tensor_traits_common : public tensor_traits_base {
}
return true;
case GGML_OP_GATED_DELTA_NET:
if (params->use_ref) {
// the generic kernel does the replay of pending tokens (op param 1)
if (params->use_ref || ggml_get_op_params_i32(op, 1) != 0) {
return false;
}
switch (op->src[0]->type) {
+4
View File
@@ -582,6 +582,10 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
return BEST_FATTN_KERNEL_NONE;
#endif// FLASH_ATTN_AVAILABLE
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
return BEST_FATTN_KERNEL_NONE;
}
const ggml_tensor * KQV = dst;
const ggml_tensor * Q = dst->src[0];
const ggml_tensor * K = dst->src[1];
@@ -485,6 +485,10 @@ static gdn_path select_gdn_mma_path(int device, const ggml_cuda_gdn_mma_args & a
} // namespace
using namespace ggml_cuda_gated_delta_net_mma;
bool ggml_cuda_gdn_mma_supported(int device, const ggml_cuda_gdn_mma_args & a) {
return a.state_out && select_gdn_mma_path(device, a) != gdn_path::ar;
}
bool ggml_cuda_gdn_mma_launch(int device, const ggml_cuda_gdn_mma_args & a, cudaStream_t stream) {
if (!a.state_out) {
return false;
@@ -32,4 +32,6 @@ struct ggml_cuda_gdn_mma_args {
bool eligible;
};
// true when ggml_cuda_gdn_mma_launch would run the chunked kernel for these args
bool ggml_cuda_gdn_mma_supported(int device, const ggml_cuda_gdn_mma_args & args);
bool ggml_cuda_gdn_mma_launch(int device, const ggml_cuda_gdn_mma_args & args, cudaStream_t stream);
+175 -29
View File
@@ -6,7 +6,25 @@
constexpr int gdn_cols_per_warp = 4;
template <int S_v, bool KDA, bool keep_rs_t, int cols_per_warp = gdn_cols_per_warp>
// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
struct gdn_replay_args {
const float * pk; // [S_v, H_k, n_pend, n_seqs]
const float * pv; // [S_v, H, n_pend, n_seqs]
const float * pgb; // [g0, H, 2*n_pend, n_seqs], gates then betas
const int32_t * n_rep; // [n_seqs]
int64_t sk1, sk2, sk3; // head, token and seq strides in floats
int64_t sv1, sv2, sv3;
int64_t sg1, sg2, sg3;
int n_pend;
bool keep; // write the state after the replay, not the final one
// optional: store the k, v, g, beta inputs of the new tokens (fused cpys)
float * st[4];
int64_t st2[4]; // token stride in floats
int64_t st3[4]; // seq stride in floats
};
template <int S_v, bool KDA, bool keep_rs_t, bool replay = false, int cols_per_warp = gdn_cols_per_warp>
__global__ void __launch_bounds__((ggml_cuda_get_physical_warp_size() < S_v ? ggml_cuda_get_physical_warp_size() : S_v) * 4, 2)
gated_delta_net_cuda(const float * q,
const float * k,
@@ -32,7 +50,8 @@ gated_delta_net_cuda(const float * q,
const uint3 rq3_magic,
float scale,
int64_t state_slot_stride,
int K) {
int K,
const gdn_replay_args rep) {
const uint32_t h_idx = blockIdx.x;
const uint32_t sequence = blockIdx.y;
@@ -72,6 +91,53 @@ gated_delta_net_cuda(const float * q,
s_shard[r] = curr_state[i];
}
if constexpr (replay) {
const int n_r = rep.n_rep[sequence];
const float * pk = rep.pk + sequence * rep.sk3 + iq1 * rep.sk1;
const float * pv = rep.pv + sequence * rep.sv3 + h_idx * rep.sv1;
const float * pgb = rep.pgb + sequence * rep.sg3 + h_idx * rep.sg1;
for (int t = 0; t < n_r; t++) {
const float * k_t = pk + t * rep.sk2;
const float v_col = pv[t * rep.sv2 + col];
const float * g_t = pgb + t * rep.sg2;
const float beta_val = pgb[(rep.n_pend + t) * rep.sg2];
float k_reg[rows_per_lane];
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
k_reg[r] = k_t[r * lanes_per_col + lane_in_col];
}
float g_reg[rows_per_lane];
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
g_reg[r] = expf(KDA ? g_t[r * lanes_per_col + lane_in_col] : g_t[0]);
}
// same update as below, without the attention output
float kv_shard = 0.0f;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
kv_shard += (KDA ? g_reg[r] : 1.0f) * s_shard[r] * k_reg[r];
}
const float kv_col = warp_reduce_sum<lanes_per_col>(kv_shard);
const float delta_col = (v_col - (KDA ? 1.0f : g_reg[0]) * kv_col) * beta_val;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
s_shard[r] = g_reg[r] * s_shard[r] + k_reg[r] * delta_col;
}
}
if (rep.keep) {
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
state[col * S_v + r * lanes_per_col + lane_in_col] = s_shard[r];
}
}
}
for (int t = 0; t < n_tokens; t++) {
const float * q_t = q + iq3 * sq3 + t * sq2 + iq1 * sq1;
const float * k_t = k + iq3 * sq3 + t * sq2 + iq1 * sq1;
@@ -93,6 +159,27 @@ gated_delta_net_cuda(const float * q,
q_reg[r] = q_t[i];
}
if constexpr (replay && !KDA) {
if (rep.st[0] != nullptr) {
// keep the inputs of this token pending: one CTA per k head writes k, each column its v
const bool first = blockIdx.z == 0 && threadIdx.y == 0 && col_in_warp == 0;
if (first && h_idx < neqk1_magic.z) {
float * dk = rep.st[0] + sequence * rep.st3[0] + t * rep.st2[0] + h_idx * S_v;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
dk[r * lanes_per_col + lane_in_col] = k_reg[r];
}
}
if (lane_in_col == 0) {
rep.st[1][sequence * rep.st3[1] + t * rep.st2[1] + h_idx * S_v + col] = v_t[col];
}
if (first && lane_in_col == 0) {
rep.st[2][sequence * rep.st3[2] + t * rep.st2[2] + h_idx] = *g_t;
rep.st[3][sequence * rep.st3[3] + t * rep.st2[3] + h_idx] = beta_val;
}
}
}
if constexpr (!KDA) {
const float g_val = expf(*g_t);
@@ -122,12 +209,18 @@ gated_delta_net_cuda(const float * q,
attn_data[col] = attn_col * scale;
}
} else {
// same arithmetic as the replay loop, so that a replayed state matches bit for bit
float g_reg[rows_per_lane];
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
g_reg[r] = expf(g_t[r * lanes_per_col + lane_in_col]);
}
// kv[col] = sum_i g[i] * S[i][col] * k[i]
float kv_shard = 0.0f;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
const int i = r * lanes_per_col + lane_in_col;
kv_shard += expf(g_t[i]) * s_shard[r] * k_reg[r];
kv_shard += g_reg[r] * s_shard[r] * k_reg[r];
}
float kv_col = warp_reduce_sum<lanes_per_col>(kv_shard);
@@ -140,8 +233,7 @@ gated_delta_net_cuda(const float * q,
float attn_partial = 0.0f;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
const int i = r * lanes_per_col + lane_in_col;
s_shard[r] = expf(g_t[i]) * s_shard[r] + k_reg[r] * delta_col;
s_shard[r] = g_reg[r] * s_shard[r] + k_reg[r] * delta_col;
attn_partial += s_shard[r] * q_reg[r];
}
@@ -170,6 +262,9 @@ gated_delta_net_cuda(const float * q,
}
if constexpr (!keep_rs_t) {
if (replay && rep.keep) {
return;
}
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
const int i = r * lanes_per_col + lane_in_col;
@@ -178,7 +273,7 @@ gated_delta_net_cuda(const float * q,
}
}
template <bool KDA, bool keep_rs_t>
template <bool KDA, bool keep_rs_t, bool replay = false>
static void launch_gated_delta_net(
const float * q_d, const float * k_d, const float * v_d,
const float * g_d, const float * b_d, const float * s_d,
@@ -188,7 +283,7 @@ static void launch_gated_delta_net(
int64_t sv1, int64_t sv2, int64_t sv3,
int64_t sb1, int64_t sb2, int64_t sb3,
int64_t neqk1, int64_t rq3,
float scale, int64_t state_slot_stride, int K, cudaStream_t stream) {
float scale, int64_t state_slot_stride, int K, const gdn_replay_args & rep, cudaStream_t stream) {
//TODO: Add chunked kernel for even faster pre-fill
const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size;
// four columns per warp (see the kernel); shrink the CTA when the wider CTA would leave
@@ -209,29 +304,29 @@ static void launch_gated_delta_net(
const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(grid_dims, block_dims, 0, stream);
switch (S_v) {
case 16:
ggml_cuda_kernel_launch(gated_delta_net_cuda<16, KDA, keep_rs_t>, launch_params,
ggml_cuda_kernel_launch(gated_delta_net_cuda<16, KDA, keep_rs_t, replay>, launch_params,
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H,
n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep);
break;
case 32:
ggml_cuda_kernel_launch(gated_delta_net_cuda<32, KDA, keep_rs_t>, launch_params,
ggml_cuda_kernel_launch(gated_delta_net_cuda<32, KDA, keep_rs_t, replay>, launch_params,
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H,
n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep);
break;
case 64: {
ggml_cuda_kernel_launch(gated_delta_net_cuda<64, KDA, keep_rs_t>, launch_params,
ggml_cuda_kernel_launch(gated_delta_net_cuda<64, KDA, keep_rs_t, replay>, launch_params,
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H,
n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep);
break;
}
case 128: {
ggml_cuda_kernel_launch(gated_delta_net_cuda<128, KDA, keep_rs_t>, launch_params,
ggml_cuda_kernel_launch(gated_delta_net_cuda<128, KDA, keep_rs_t, replay>, launch_params,
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H,
n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep);
break;
}
default:
@@ -353,34 +448,85 @@ static void ggml_cuda_op_gated_delta_net_impl(
state_slot_stride = cache->slot_stride;
}
{
const ggml_tensor * src_pend = dst->src[6];
gdn_replay_args rep = {};
if (src_pend) {
const ggml_tensor * src_pv = dst->src[7];
const ggml_tensor * src_pgb = dst->src[8];
GGML_ASSERT(K == 1);
rep.pk = (const float *) src_pend->data;
rep.pv = (const float *) src_pv->data;
rep.pgb = (const float *) src_pgb->data;
rep.n_rep = (const int32_t *) dst->src[9]->data;
rep.sk1 = src_pend->nb[1] / sizeof(float);
rep.sk2 = src_pend->nb[2] / sizeof(float);
rep.sk3 = src_pend->nb[3] / sizeof(float);
rep.sv1 = src_pv->nb[1] / sizeof(float);
rep.sv2 = src_pv->nb[2] / sizeof(float);
rep.sv3 = src_pv->nb[3] / sizeof(float);
rep.sg1 = src_pgb->nb[1] / sizeof(float);
rep.sg2 = src_pgb->nb[2] / sizeof(float);
rep.sg3 = src_pgb->nb[3] / sizeof(float);
rep.n_pend = ggml_get_op_params_i32(dst, 1);
rep.keep = ggml_get_op_params_i32(dst, 2) != 0;
if (cache != nullptr) {
for (int i = 0; i < 4; ++i) {
rep.st[i] = cache->in_dst[i];
rep.st2[i] = cache->in_nb2[i];
rep.st3[i] = cache->in_nb3[i];
}
}
}
#define GDN_LAUNCH_N(KDA, KEEP, REPLAY, N_TOKENS, REP) \
launch_gated_delta_net<KDA, KEEP, REPLAY>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, \
S_v, H, N_TOKENS, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, \
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, REP, stream)
#define GDN_LAUNCH(KDA, KEEP, REPLAY) GDN_LAUNCH_N(KDA, KEEP, REPLAY, n_tokens, rep)
if (!src_pend) {
ggml_cuda_gdn_mma_args args = ggml_cuda_gdn_mma_args_from_tensor(dst);
args.state_out = state_d;
if (ggml_cuda_gdn_mma_launch(ctx.device, args, stream)) {
return;
}
} else if (!rep.keep && rep.st[0] == nullptr) {
// the chunked kernels (not KDA) do not replay: replay the pending tokens into the state output, then
// run the new tokens from there in place (each thread reads and writes the same state elements)
ggml_cuda_gdn_mma_args args = ggml_cuda_gdn_mma_args_from_tensor(dst);
args.state = state_d;
args.state_out = state_d;
if (ggml_cuda_gdn_mma_supported(ctx.device, args)) {
gdn_replay_args rep_only = rep;
rep_only.keep = true;
GDN_LAUNCH_N(false, false, true, 0, rep_only);
ggml_cuda_gdn_mma_launch(ctx.device, args, stream);
return;
}
}
if (kda) {
if (keep_rs) {
launch_gated_delta_net<true, true>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
GDN_LAUNCH(true, true, false);
} else if (src_pend) {
GDN_LAUNCH(true, false, true);
} else {
launch_gated_delta_net<true, false>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
GDN_LAUNCH(true, false, false);
}
} else {
if (keep_rs) {
launch_gated_delta_net<false, true>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
GDN_LAUNCH(false, true, false);
} else if (src_pend) {
GDN_LAUNCH(false, false, true);
} else {
launch_gated_delta_net<false, false>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
GDN_LAUNCH(false, false, false);
}
}
#undef GDN_LAUNCH
#undef GDN_LAUNCH_N
}
void ggml_cuda_op_gated_delta_net(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
+5
View File
@@ -5,6 +5,11 @@
struct ggml_cuda_gated_delta_net_fused_cache {
float * data; // rollback slot 0
int64_t slot_stride; // between rollback slots (0 when K==1)
// rs_replay: the cpys of the k, v, g, beta inputs into the pending rows, null when not fused
float * in_dst[4] = {};
int64_t in_nb2[4] = {}; // token stride in elements
int64_t in_nb3[4] = {}; // seq stride in elements
};
void ggml_cuda_op_gated_delta_net(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
+41
View File
@@ -3647,6 +3647,47 @@ static int ggml_cuda_try_gdn_cache_fusion(
fused_state_cpy.data = (float *) dst->data; // rollback group 0 (newest)
fused_state_cpy.slot_stride = K > 1 ? (int64_t) (dst->nb[2] / sizeof(float)) : 0;
// rs_replay: the next 4 real nodes may store the k, v, g, beta inputs into the pending rows
if (gdn->src[6] != nullptr && gdn->src[3]->ne[0] == 1) {
int j = node_idx + skip + 1;
int skip_in = skip;
float * in_dst[4];
int64_t in_nb2[4];
int64_t in_nb3[4];
int i = 0;
for (; i < 4 && j < cgraph->n_nodes; ++j) {
const ggml_tensor * n = cgraph->nodes[j];
if (ggml_cuda_is_view_or_noop(n)) {
continue;
}
const ggml_tensor * in = gdn->src[1 + i];
const ggml_tensor * d = n->src[1];
// the cpy reads the whole input, directly or through a view of the same data
const ggml_tensor * s0 = n->src[0];
const bool whole_in = s0 == in || (s0 != nullptr && s0->data == in->data && ggml_are_same_shape(s0, in) &&
ggml_are_same_stride(s0, in));
if (n->op != GGML_OP_CPY || (n->flags & GGML_TENSOR_FLAG_OUTPUT) || !whole_in ||
d->type != GGML_TYPE_F32 || d->data == nullptr || !ggml_are_same_shape(d, in) ||
d->nb[0] != sizeof(float) || d->nb[1] != d->ne[0]*sizeof(float) || d->nb[2] != d->ne[0]*d->ne[1]*sizeof(float)) {
break;
}
in_dst[i] = (float *) d->data;
in_nb2[i] = d->nb[2] / sizeof(float);
in_nb3[i] = d->nb[3] / sizeof(float);
skip_in = j - node_idx;
++i;
}
if (i == 4) {
for (int c = 0; c < 4; ++c) {
fused_state_cpy.in_dst[c] = in_dst[c];
fused_state_cpy.in_nb2[c] = in_nb2[c];
fused_state_cpy.in_nb3[c] = in_nb3[c];
}
skip = skip_in;
}
}
return skip;
}
+3 -1
View File
@@ -1277,6 +1277,7 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm
if (op->type == GGML_TYPE_F32 && op->src[0] && op->src[0]->type == GGML_TYPE_F32 && op->src[1] &&
(op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) && op->src[2] &&
(op->src[2]->type == GGML_TYPE_F32 || op->src[2]->type == GGML_TYPE_F16) && op->src[4] == nullptr && op->src[5] == nullptr &&
!ggml_flash_attn_ext_has_indexed_bias(op) &&
ggml_is_contiguous_rows(op) && ggml_is_contiguous_rows(op->src[0])) {
float max_bias = 0.0f;
float logit_softcap = 0.0f;
@@ -1536,7 +1537,8 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm
op->src[4]->ne[0] == 1 && // beta is scalar per position
et_ggml_is_row_contiguous(op->src[0]) && et_ggml_is_row_contiguous(op->src[1]) &&
et_ggml_is_row_contiguous(op->src[2]) && ggml_is_contiguous(op->src[3]) &&
ggml_is_contiguous(op->src[4]) && ggml_is_contiguous(op->src[5])) {
ggml_is_contiguous(op->src[4]) && ggml_is_contiguous(op->src[5]) &&
ggml_get_op_params_i32(op, 1) == 0) { // no replay of pending tokens
supported = true;
} else {
supported = false;
+23 -2
View File
@@ -355,8 +355,8 @@ static bool htp_kparams_solve_flash_attn(
return false;
}
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
if (op->src[5] != nullptr) {
// K/V row lists and indexed bias are not supported
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
@@ -514,7 +514,12 @@ static bool htp_kparams_solve_gated_delta_net(
const struct ggml_tensor * g = op->src[3];
const struct ggml_tensor * beta = op->src[4];
const struct ggml_tensor * state = op->src[5];
const struct ggml_tensor * pend_k = op->src[6];
const struct ggml_tensor * pend_v = op->src[7];
const struct ggml_tensor * pend_gb = op->src[8];
const struct ggml_tensor * n_rep = op->src[9];
const struct ggml_tensor * dst = op;
const bool replay = pend_k != nullptr;
if (q->type != GGML_TYPE_F32 || k->type != GGML_TYPE_F32 || v->type != GGML_TYPE_F32 ||
g->type != GGML_TYPE_F32 || beta->type != GGML_TYPE_F32 || state->type != GGML_TYPE_F32 ||
@@ -552,6 +557,22 @@ static bool htp_kparams_solve_gated_delta_net(
dst->ne[2] != 1 || dst->ne[3] != 1) {
return false;
}
if ((pend_v != nullptr) != replay || (pend_gb != nullptr) != replay || (n_rep != nullptr) != replay) {
return false;
}
if (replay) {
const int64_t n_pend = ggml_get_op_params_i32(op, 1);
if (K != 1 || n_pend < 0 || pend_k->type != GGML_TYPE_F32 || pend_v->type != GGML_TYPE_F32 ||
pend_gb->type != GGML_TYPE_F32 || n_rep->type != GGML_TYPE_I32 ||
pend_k->nb[0] != sizeof(float) || pend_v->nb[0] != sizeof(float) || pend_gb->nb[0] != sizeof(float) ||
pend_k->ne[0] != k->ne[0] || pend_k->ne[1] != k->ne[1] || pend_k->ne[2] != n_pend || pend_k->ne[3] != n_seqs ||
pend_v->ne[0] != S_v || pend_v->ne[1] != H || pend_v->ne[2] != n_pend || pend_v->ne[3] != n_seqs ||
pend_gb->ne[0] != g->ne[0] || pend_gb->ne[1] != H || pend_gb->ne[2] != 2*n_pend || pend_gb->ne[3] != n_seqs ||
!ggml_is_contiguous(n_rep) || ggml_nelements(n_rep) != n_seqs) {
return false;
}
}
const uint32_t rq3 = (uint32_t) (n_seqs / q->ne[3]);
const uint32_t rk3 = (uint32_t) (n_seqs / k->ne[3]);
+80 -18
View File
@@ -574,7 +574,7 @@ static inline HVX_Vector gdn_add_scaled_dot8_f32(float * restrict dst0, float *
return Q6_V_vmux_QVV(q16, rA, Q6_V_vror_VR(rB, 128 - 16));
}
static inline void gdn_step_kda_f32(
static __attribute__((noinline)) void gdn_step_kda_f32(
float * restrict s_work,
float * restrict attn_out,
const float * restrict q_t,
@@ -662,7 +662,7 @@ static inline void gdn_step_kda_f32(
}
}
static inline void gdn_step_scalar_f32(
static __attribute__((noinline)) void gdn_step_scalar_f32(
float * restrict s_work,
float * restrict attn_out,
const float * restrict q_t,
@@ -748,6 +748,48 @@ static inline void gdn_step_scalar_f32(
}
}
static inline void gdn_replay_f32(
const struct htp_ops_context * octx,
float * restrict s_work,
uint32_t ik1,
uint32_t iv1,
uint32_t iv3,
bool kda,
float scale,
uint32_t S_v
) {
const struct htp_tensor * pend_k = octx->src[6];
const struct htp_tensor * pend_v = octx->src[7];
const struct htp_tensor * pend_gb = octx->src[8];
const struct htp_tensor * n_rep = octx->src[9];
if (!pend_k) {
return;
}
const uint32_t n_pend = (uint32_t) octx->op_params[1];
const int32_t raw_n_rep = ((const int32_t *) (uintptr_t) n_rep->data)[iv3];
const uint32_t n_steps = raw_n_rep <= 0 ? 0 : MIN((uint32_t) raw_n_rep, n_pend);
float unused_attn[128] __attribute__((aligned(128)));
const uint8_t * pk = (const uint8_t *) (uintptr_t) pend_k->data + (uint64_t) iv3 * pend_k->nb[3] + (uint64_t) ik1 * pend_k->nb[1];
const uint8_t * pv = (const uint8_t *) (uintptr_t) pend_v->data + (uint64_t) iv3 * pend_v->nb[3] + (uint64_t) iv1 * pend_v->nb[1];
const uint8_t * pgb = (const uint8_t *) (uintptr_t) pend_gb->data + (uint64_t) iv3 * pend_gb->nb[3] + (uint64_t) iv1 * pend_gb->nb[1];
for (uint32_t t = 0; t < n_steps; ++t) {
const float * k_t = (const float *) (pk + (uint64_t) t * pend_k->nb[2]);
const float * v_t = (const float *) (pv + (uint64_t) t * pend_v->nb[2]);
const float * g_t = (const float *) (pgb + (uint64_t) t * pend_gb->nb[2]);
const float beta_val = *(const float *) (pgb + (uint64_t) (n_pend + t) * pend_gb->nb[2]);
if (kda) {
gdn_step_kda_f32(s_work, unused_attn, k_t, k_t, v_t, g_t, beta_val, scale, S_v);
} else {
gdn_step_scalar_f32(s_work, unused_attn, k_t, k_t, v_t, g_t, beta_val, scale, S_v);
}
}
}
static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
struct htp_gdn_context * gctx = (struct htp_gdn_context *) data;
struct htp_ops_context * octx = gctx->octx;
@@ -792,6 +834,7 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int
const uint32_t state_seq_stride = kparams->state_seq_stride;
const uint64_t state_size_per_snap = (uint64_t) kparams->state_size_per_snap;
const dma_addr_t state_out_dma_base = dst_cache ? dst_cache->data : (dst->data + S_v * H * n_tokens * n_seqs * sizeof(float));
const bool keep = octx->src[6] && octx->op_params[2] != 0;
uint32_t ir_prefetch = gctx->row_start + ith;
int spad_idx = 0;
@@ -838,6 +881,10 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int
float * attn_data = dst_base + ((uint64_t) iv3 * n_tokens * H + iv1) * S_v;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
gdn_replay_f32(octx, s_work_curr, ik1, iv1, iv3, kparams->kda, scale, S_v);
if (keep) {
hvx_copy_f32_uu((uint8_t *) (uintptr_t) s_out, (const uint8_t *) s_work_curr, S_v * S_v);
}
for (uint32_t t = 0; t < n_tokens; ++t) {
const float * q_t = (const float *) ((const uint8_t *) (uintptr_t) q->data +
(uint64_t) iq3 * q->nb[3] + (uint64_t) t * q->nb[2] + (uint64_t) iq1 * q->nb[1]);
@@ -868,10 +915,9 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
// Push real write-back
dma_queue_push(dma_q, dma_make_data(s_out, s_work_curr),
S_v * sizeof(float), S_v * sizeof(float),
S_v * sizeof(float), S_v);
S_v * sizeof(float), keep ? 0 : S_v);
// Prefetch next block (if any)
if (ir_prefetch < row_end) {
@@ -932,6 +978,7 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int
const uint32_t state_seq_stride = kparams->state_seq_stride;
const dma_addr_t state_out_dma_base = dst_cache ? dst_cache->data : (dst->data + S_v * H * n_seqs * sizeof(float));
const bool keep = octx->src[6] && octx->op_params[2] != 0;
uint32_t ir_prefetch = gctx->row_start + ith;
int spad_idx = 0;
@@ -989,6 +1036,10 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int
(uint64_t) iv3 * beta->nb[3] + (uint64_t) iv1 * beta->nb[1]);
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
gdn_replay_f32(octx, s_work_curr, ik1, iv1, iv3, kparams->kda, scale, S_v);
if (keep) {
hvx_copy_f32_uu((uint8_t *) (uintptr_t) s_out, (const uint8_t *) s_work_curr, S_v * S_v);
}
if (kparams->kda) {
gdn_step_kda_f32(s_work_curr, attn_data, q_t, k_t, v_t, g_t, beta_val, scale, S_v);
} else {
@@ -996,10 +1047,9 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
// Push real write-back
dma_queue_push(dma_q, dma_make_data(s_out, s_work_curr),
S_v * sizeof(float), S_v * sizeof(float),
S_v * sizeof(float), S_v);
S_v * sizeof(float), keep ? 0 : S_v);
// Prefetch next block (if any)
if (ir_prefetch < row_end) {
@@ -1654,13 +1704,15 @@ struct htp_gdn_batch_context {
const struct htp_gdn_kernel_params * kparams;
};
static void gdn_hvx_init_state_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
static void gdn_hvx_replay_init_state_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
(void) n;
struct htp_gdn_batch_context * bctx = (struct htp_gdn_batch_context *) data;
struct htp_thread_trace * tr = th->trace;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, 0);
struct htp_gdn_head_ptrs * head = &bctx->heads[i];
gdn_replay_f32(bctx->octx, head->s_state, head->ik1, head->iv1, head->iv3,
bctx->kparams->kda, bctx->scale, bctx->S_v);
gdn_pack_s_col_tiles(head->s_col_tiles, head->s_f16, head->s_state, bctx->S_v);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, 0);
@@ -2038,6 +2090,7 @@ static int gated_delta_net_f32_hmx_chunked(
const uint32_t chunk_size = kparams->chunk_size;
const uint32_t n_chunks = kparams->n_chunks;
const uint32_t n_sv_tiles = S_v / 32;
const bool keep = octx->src[6] && octx->op_params[2] != 0;
struct htp_gdn_hmx_vtcm_layout L;
htp_gdn_hmx_vtcm_layout_build(&L, S_v, chunk_size, kparams->n_heads_batch, kparams->n_hvx, kparams->pipeline != 0);
@@ -2101,7 +2154,17 @@ static int gated_delta_net_f32_hmx_chunked(
}
if (n_chunks > 0) {
work_queue_run(wp, gdn_hvx_init_state_worker, &bctx, n_batch);
work_queue_run(wp, gdn_hvx_replay_init_state_worker, &bctx, n_batch);
if (keep) {
for (uint32_t h = 0; h < n_batch; ++h) {
dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state),
S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v);
}
for (uint32_t h = 0; h < n_batch; ++h) {
dma_queue_pop(dma_q);
}
}
const uint32_t chunk0_tokens = hex_smin(chunk_size, n_tokens);
for (uint32_t h = 0; h < n_batch; ++h) {
@@ -2254,12 +2317,14 @@ static int gated_delta_net_f32_hmx_chunked(
}
}
for (uint32_t h = 0; h < n_batch; ++h) {
dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state),
S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v);
}
for (uint32_t h = 0; h < n_batch; ++h) {
dma_queue_pop(dma_q);
if (!keep) {
for (uint32_t h = 0; h < n_batch; ++h) {
dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state),
S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v);
}
for (uint32_t h = 0; h < n_batch; ++h) {
dma_queue_pop(dma_q);
}
}
}
@@ -2270,7 +2335,7 @@ static int gated_delta_net_f32_hmx_chunked(
int op_gated_delta_net(struct htp_ops_context * octx) {
const struct htp_tensor * dst = octx->dst;
for (int i = 0; i < 6; i++) {
for (int i = 0; i < 10; i++) {
if (htp_tensor_is_extended(octx->src[i])) {
return HTP_STATUS_NO_SUPPORT;
}
@@ -2308,9 +2373,6 @@ int op_gated_delta_net(struct htp_ops_context * octx) {
);
row_start = range.start;
nrows = range.count;
} else if (octx->op_params[1] != 0) {
row_start = octx->op_params[1];
nrows = octx->op_params[2];
}
if (nrows == 0) {
+1 -1
View File
@@ -105,7 +105,7 @@ static inline bool ggml_impl_is_view(const struct ggml_tensor * t) {
}
static inline float ggml_compute_softplus_f32(float input) {
return (input > 20.0f) ? input : logf(1 + expf(input));
return (input > 20.0f) ? input : log1pf(expf(input));
}
// compute correction dims for YaRN RoPE scaling
+6 -5
View File
@@ -56,6 +56,7 @@ set(METALLIB_KERNEL_SOURCES
kernels/mul_mv.metal
kernels/mul_mv_mma.metal
kernels/mul_mm.metal
kernels/mul_mm_tensor.metal
kernels/quantize.metal
kernels/softmax.metal
kernels/norm.metal
@@ -223,21 +224,21 @@ else()
# the tensor API kernels go in a separate metallib, loaded only where supported
if (GGML_METAL_HAS_TENSOR_LIB)
set(AIR_MM_TENSOR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/mul_mm_tensor.air")
set(AIR_MM_TENSOR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/mul_mm_tensor_tensor.air")
# the tensor API needs OS 26+
set(XC_FLAGS_TENSOR ${XC_FLAGS} -mtargetos=${GGML_METAL_TARGET_OS}26.0${METAL_TARGET_SIM})
add_custom_command(
OUTPUT ${AIR_MM_TENSOR}
COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS_TENSOR} -DGGML_METAL_HAS_TENSOR -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/mul_mm.metal -o ${AIR_MM_TENSOR}
DEPENDS kernels/mul_mm.metal kernels/common.h kernels/dequantize.h ${METALLIB_COMMON} ggml-metal-impl.h
COMMENT "Compiling kernels/mul_mm.metal (tensor API)"
COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS_TENSOR} -DGGML_METAL_HAS_TENSOR -DGGML_METAL_HAS_BF16 -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/mul_mm_tensor.metal -o ${AIR_MM_TENSOR}
DEPENDS kernels/mul_mm_tensor.metal kernels/common.h kernels/dequantize.h ${METALLIB_COMMON} ggml-metal-impl.h
COMMENT "Compiling kernels/mul_mm_tensor.metal (tensor API)"
VERBATIM
)
set(AIR_FA_TENSOR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/fa_tensor_tensor.air")
add_custom_command(
OUTPUT ${AIR_FA_TENSOR}
COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS_TENSOR} -DGGML_METAL_HAS_TENSOR -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/fa_tensor.metal -o ${AIR_FA_TENSOR}
COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS_TENSOR} -DGGML_METAL_HAS_TENSOR -DGGML_METAL_HAS_BF16 -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/fa_tensor.metal -o ${AIR_FA_TENSOR}
DEPENDS kernels/fa_tensor.metal kernels/common.h ${METALLIB_COMMON} ggml-metal-impl.h
COMMENT "Compiling kernels/fa_tensor.metal (tensor API)"
VERBATIM
@@ -85,6 +85,7 @@ static bool ggml_metal_mul_mv_mma_type_supported(enum ggml_type type) {
case GGML_TYPE_Q1_0:
case GGML_TYPE_Q2_0:
case GGML_TYPE_MXFP4:
case GGML_TYPE_NVFP4:
case GGML_TYPE_Q2_K:
case GGML_TYPE_Q3_K:
case GGML_TYPE_IQ2_XXS:
@@ -134,6 +135,7 @@ static int64_t ggml_metal_mul_mv_mma_rows_min(enum ggml_type type) {
case GGML_TYPE_Q2_K:
case GGML_TYPE_IQ4_NL:
case GGML_TYPE_MXFP4:
case GGML_TYPE_NVFP4:
return 3;
default:
return 2;
+47 -10
View File
@@ -752,6 +752,8 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_gated_delta_net(
const int ne30 = op->src[3]->ne[0]; // G
// state is src[5], 4D [S_v, S_v, H_v, n_seqs] (s0 only); K is op param 0.
const int K = ggml_get_op_params_i32(op, 0);
// replay of pending tokens, see ggml_gated_delta_net_ext
const bool replay = op->src[6] != nullptr;
const int nsg = op->src[2]->ne[0]/32;
@@ -760,15 +762,16 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_gated_delta_net(
GGML_ASSERT(ne20 % 32 == 0);
snprintf(base, 256, "kernel_gated_delta_net_%s_%d", ggml_type_name(op->src[0]->type), nsg);
snprintf(name, 256, "%s_ne20=%d_ne30=%d_K=%d", base, ne20, ne30, K);
snprintf(name, 256, "%s_ne20=%d_ne30=%d_K=%d_rep=%d", base, ne20, ne30, K, replay ? 1 : 0);
ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
if (!res.pipeline) {
ggml_metal_cv_t cv = ggml_metal_cv_init();
ggml_metal_cv_set_int16(cv, ne20, FC_GATED_DELTA_NET + 0);
ggml_metal_cv_set_int16(cv, ne30, FC_GATED_DELTA_NET + 1);
ggml_metal_cv_set_int16(cv, K, FC_GATED_DELTA_NET + 2);
ggml_metal_cv_set_int16(cv, ne20, FC_GATED_DELTA_NET + 0);
ggml_metal_cv_set_int16(cv, ne30, FC_GATED_DELTA_NET + 1);
ggml_metal_cv_set_int16(cv, K, FC_GATED_DELTA_NET + 2);
ggml_metal_cv_set_bool (cv, replay, FC_GATED_DELTA_NET + 3);
res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
@@ -974,7 +977,15 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_meta
constexpr int NRA = SZ_SIMDGROUP * N_MM_BLOCK_Y * N_MM_SIMD_GROUP_Y;
constexpr int NRB = SZ_SIMDGROUP * N_MM_BLOCK_X * N_MM_SIMD_GROUP_X;
const bool has_tensor = ggml_metal_device_get_props(ggml_metal_library_get_device(lib))->has_tensor;
const ggml_metal_device_props * props_dev = ggml_metal_device_get_props(ggml_metal_library_get_device(lib));
const bool has_tensor = props_dev->has_tensor;
const bool prec_bf16 = props_dev->has_bfloat &&
ggml_prec_get_src(op, 1) == GGML_PREC_BF16 && tsrc1 == GGML_TYPE_F32 &&
(has_tensor ? tsrc0 == GGML_TYPE_F32 : tsrc0 != GGML_TYPE_BF16);
const bool prec_f32 = ggml_prec_get_src(op, 1) == GGML_PREC_F32 && tsrc1 == GGML_TYPE_F32;
const bool bc_out = has_tensor
? (op->ne[0] % NRA != 0 || op->ne[1] % NRB != 0)
@@ -986,7 +997,11 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_meta
const int16_t r2 = (int16_t) (ne12 / op->src[0]->ne[2]);
const int16_t r3 = (int16_t) (ne13 / op->src[0]->ne[3]);
snprintf(base, 256, "kernel_mul_mm_%s_%s", ggml_type_name(tsrc0), ggml_type_name(tsrc1));
const bool use_tensor = has_tensor && !prec_f32;
const char * infix = use_tensor ? "_tensor" : "";
const char * suffix = prec_f32 ? "_prec_f32" : (prec_bf16 ? "_prec_bf16" : "");
snprintf(base, 256, "kernel_mul_mm%s_%s_%s%s", infix, ggml_type_name(tsrc0), ggml_type_name(tsrc1), suffix);
snprintf(name, 256, "%s_bci=%d_bco=%d_ne12=%d_ne13=%d_r2=%d_r3=%d",
base, bc_inp, bc_out, ne12, ne13, r2, r3);
@@ -1006,7 +1021,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_meta
ggml_metal_cv_free(cv);
}
if (has_tensor) {
if (use_tensor) {
res.nr0 = NRA;
res.nr1 = NRB;
@@ -1016,7 +1031,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_meta
res.nr0 = 64;
res.nr1 = 32;
res.smem = bc_out ? 8192 : (4096 + 2048);
res.smem = prec_f32 ? 12288 : (bc_out ? 8192 : (4096 + 2048));
}
res.nsg = N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y;
@@ -1104,6 +1119,11 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mv(ggml_meta
nsg = N_SG_MXFP4;
nr0 = N_R0_MXFP4;
} break;
case GGML_TYPE_NVFP4:
{
nsg = N_SG_NVFP4;
nr0 = N_R0_NVFP4;
} break;
case GGML_TYPE_Q2_K:
{
nsg = N_SG_Q2_K;
@@ -1305,9 +1325,21 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm_id(ggml_m
const ggml_type tsrc0 = op->src[0]->type;
const ggml_type tsrc1 = op->src[1]->type;
const ggml_metal_device_props * props_dev = ggml_metal_device_get_props(ggml_metal_library_get_device(lib));
const bool prec_bf16 = props_dev->has_bfloat &&
ggml_prec_get_src(op, 1) == GGML_PREC_BF16 && tsrc1 == GGML_TYPE_F32 &&
tsrc0 != GGML_TYPE_BF16 && tsrc0 != GGML_TYPE_MXFP4 && tsrc0 != GGML_TYPE_NVFP4;
const bool prec_f32 = ggml_prec_get_src(op, 1) == GGML_PREC_F32 && tsrc1 == GGML_TYPE_F32;
const bool bc_inp = op->src[0]->ne[0] % 32 != 0;
snprintf(base, 256, "kernel_mul_mm_id_%s_%s", ggml_type_name(tsrc0), ggml_type_name(tsrc1));
const bool use_tensor = props_dev->has_tensor && !prec_f32;
const char * infix = use_tensor ? "_tensor" : "";
const char * suffix = prec_f32 ? "_prec_f32" : (prec_bf16 ? "_prec_bf16" : "");
snprintf(base, 256, "kernel_mul_mm_id%s_%s_%s%s", infix, ggml_type_name(tsrc0), ggml_type_name(tsrc1), suffix);
snprintf(name, 256, "%s_bci=%d", base, bc_inp);
ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
@@ -1321,7 +1353,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm_id(ggml_m
ggml_metal_cv_free(cv);
}
res.smem = 8192;
res.smem = prec_f32 ? 12288 : 8192;
return res;
}
@@ -1399,6 +1431,11 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mv_id(ggml_m
nsg = N_SG_MXFP4;
nr0 = N_R0_MXFP4;
} break;
case GGML_TYPE_NVFP4:
{
nsg = N_SG_NVFP4;
nr0 = N_R0_NVFP4;
} break;
case GGML_TYPE_Q2_K:
{
nsg = N_SG_Q2_K;
+13 -8
View File
@@ -129,6 +129,7 @@ int ggml_metal_pipeline_max_theads_per_threadgroup(struct ggml_metal_pipeline_wi
X(MUL_MV, mul_mv) \
X(MUL_MV_MMA, mul_mv_mma) \
X(MUL_MM, mul_mm) \
X(MUL_MM_TENSOR, mul_mm_tensor) \
X(QUANTIZE, quantize) \
X(SOFTMAX, softmax) \
X(NORM, norm) \
@@ -1510,14 +1511,16 @@ void ggml_metal_device_get_memory(ggml_metal_device_t dev, size_t * free, size_t
}
}
static bool ggml_metal_supports_mul_mat_src1_prec(const struct ggml_tensor * op, bool has_tensor) {
static bool ggml_metal_supports_mul_mat_src1_prec(const struct ggml_tensor * op, bool has_bfloat) {
GGML_ASSERT(op->op == GGML_OP_MUL_MAT || op->op == GGML_OP_MUL_MAT_ID);
const enum ggml_prec prec = ggml_prec_get_src(op, 1);
if (prec == GGML_PREC_F32) {
return false;
return true;
}
if (prec == GGML_PREC_BF16) {
return has_tensor && op->op == GGML_OP_MUL_MAT && op->src[0]->type != GGML_TYPE_F32;
return has_bfloat && op->src[1]->type == GGML_TYPE_F32;
}
return true;
}
@@ -1529,7 +1532,6 @@ static bool ggml_metal_supports_mul_mat_op(
bool mm_path) {
if (!has_simdgroup_reduction ||
op->src[0]->type == GGML_TYPE_F8_E4M3 ||
op->src[0]->type == GGML_TYPE_NVFP4 ||
op->src[0]->type == GGML_TYPE_TQ1_0) {
return false;
}
@@ -1744,6 +1746,9 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te
case GGML_OP_ROLL:
return ggml_is_contiguous(op->src[0]);
case GGML_OP_FLASH_ATTN_EXT:
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
// K/V row lists (ggml_flash_attn_ext_rows): one list of cache rows per q slice
if (op->src[5] != NULL) {
const struct ggml_tensor * kv_rows = op->src[5];
@@ -1907,7 +1912,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te
case GGML_OP_SOLVE_TRI:
return has_simdgroup_reduction && op->src[0]->type == GGML_TYPE_F32;
case GGML_OP_MUL_MAT:
if (!ggml_metal_supports_mul_mat_src1_prec(op, dev->props.has_tensor)) {
if (!ggml_metal_supports_mul_mat_src1_prec(op, dev->props.has_bfloat)) {
return false;
}
// the FWHT kernels read an F16 source directly; every other F16 src1 path
@@ -1920,7 +1925,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te
has_simdgroup_reduction, op, true,
ggml_metal_op_mul_mat_use_mm(op, has_simdgroup_mm));
case GGML_OP_MUL_MAT_ID:
if (!ggml_metal_supports_mul_mat_src1_prec(op, dev->props.has_tensor)) {
if (!ggml_metal_supports_mul_mat_src1_prec(op, dev->props.has_bfloat)) {
return false;
}
return ggml_metal_supports_mul_mat_op(
@@ -1975,6 +1980,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te
case GGML_TYPE_Q5_1:
case GGML_TYPE_Q8_0:
case GGML_TYPE_TQ2_0:
case GGML_TYPE_NVFP4:
switch (op->type) {
case GGML_TYPE_F32:
case GGML_TYPE_F16:
@@ -1989,8 +1995,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te
};
}
case GGML_OP_GET_ROWS:
return op->src[0]->type != GGML_TYPE_NVFP4 &&
op->src[0]->type != GGML_TYPE_TQ1_0 &&
return op->src[0]->type != GGML_TYPE_TQ1_0 &&
op->src[0]->type != GGML_TYPE_F8_E4M3;
case GGML_OP_SET_ROWS:
{
+14
View File
@@ -50,6 +50,9 @@
#define N_R0_MXFP4 2
#define N_SG_MXFP4 2
#define N_R0_NVFP4 2
#define N_SG_NVFP4 2
#define N_R0_Q2_K 4
#define N_SG_Q2_K 2
@@ -1034,6 +1037,17 @@ typedef struct {
uint64_t nb2;
uint64_t nb3;
uint64_t nb_out; // 0 => snapshots are appended after the attn scores (unfused)
int32_t n_pend; // replay: pending tokens per seq in pend_k, pend_v and pend_gb
int32_t keep; // replay: write the state after the replay, not the final one
uint64_t nb61; // pend_k
uint64_t nb62;
uint64_t nb63;
uint64_t nb71; // pend_v
uint64_t nb72;
uint64_t nb73;
uint64_t nb81; // pend_gb
uint64_t nb82;
uint64_t nb83;
} ggml_metal_kargs_gated_delta_net;
typedef struct {
+21
View File
@@ -2104,6 +2104,12 @@ int ggml_metal_op_gated_delta_net(ggml_metal_op_t ctx, int idx) {
}
}
// replay of pending tokens, see ggml_gated_delta_net_ext
const ggml_tensor * pk = op->src[6];
const ggml_tensor * pv = op->src[7];
const ggml_tensor * pgb = op->src[8];
const ggml_tensor * rep = op->src[9];
int ida = 0;
ggml_metal_kargs_gated_delta_net args = {
@@ -2143,6 +2149,17 @@ int ggml_metal_op_gated_delta_net(ggml_metal_op_t ctx, int idx) {
/*.nb2 =*/ nb2,
/*.nb3 =*/ nb3,
/*.nb_out =*/ nb_out,
/*.n_pend =*/ pk ? ggml_get_op_params_i32(op, 1) : 0,
/*.keep =*/ pk ? ggml_get_op_params_i32(op, 2) : 0,
/*.nb61 =*/ pk ? pk->nb[1] : 0,
/*.nb62 =*/ pk ? pk->nb[2] : 0,
/*.nb63 =*/ pk ? pk->nb[3] : 0,
/*.nb71 =*/ pv ? pv->nb[1] : 0,
/*.nb72 =*/ pv ? pv->nb[2] : 0,
/*.nb73 =*/ pv ? pv->nb[3] : 0,
/*.nb81 =*/ pgb ? pgb->nb[1] : 0,
/*.nb82 =*/ pgb ? pgb->nb[2] : 0,
/*.nb83 =*/ pgb ? pgb->nb[3] : 0,
};
ggml_metal_encoder_set_pipeline(enc, pipeline);
@@ -2155,6 +2172,10 @@ int ggml_metal_op_gated_delta_net(ggml_metal_op_t ctx, int idx) {
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op->src[5]), ida++); // state
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op), ida++); // dst (attn)
ggml_metal_encoder_set_buffer (enc, bid_out, ida++); // state_out
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(pk ? pk : op->src[0]), ida++); // pend_k
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(pv ? pv : op->src[0]), ida++); // pend_v
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(pgb ? pgb : op->src[0]), ida++); // pend_gb
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(rep ? rep : op->src[0]), ida++); // n_rep
const int nsg = pipeline.nsg;
+11 -2
View File
@@ -9,6 +9,8 @@
#include "ggml-metal-ops.h"
#include "ggml-metal-tuning.h"
#include <TargetConditionals.h>
#include <mutex>
#include <string>
@@ -653,6 +655,13 @@ static void ggml_backend_metal_graph_optimize(ggml_backend_t backend, ggml_cgrap
ggml_metal_graph_optimize(ctx, cgraph);
}
// iOS can stop a command buffer that runs for more than a few seconds, so split the graph into shorter ones there
#if TARGET_OS_IPHONE
#define GGML_METAL_DEFAULT_N_CB 8
#else
#define GGML_METAL_DEFAULT_N_CB 1
#endif // TARGET_OS_IPHONE
static void ggml_backend_metal_set_n_cb(ggml_backend_t backend, int n_cb) {
GGML_ASSERT(ggml_backend_is_metal(backend));
@@ -704,7 +713,7 @@ ggml_backend_t ggml_backend_metal_init(void) {
/* .context = */ ctx,
};
ggml_backend_metal_set_n_cb(backend, 1);
ggml_backend_metal_set_n_cb(backend, GGML_METAL_DEFAULT_N_CB);
return backend;
}
@@ -799,7 +808,7 @@ static ggml_backend_t ggml_backend_metal_device_init_backend(ggml_backend_dev_t
/* .context = */ ctx,
};
ggml_backend_metal_set_n_cb(backend, 1);
ggml_backend_metal_set_n_cb(backend, GGML_METAL_DEFAULT_N_CB);
return backend;
+56
View File
@@ -41,6 +41,7 @@ constexpr constant static float kvalues_iq4nl_f[16] = {
-127.f, -104.f, -83.f, -65.f, -49.f, -35.f, -22.f, -10.f, 1.f, 13.f, 25.f, 38.f, 53.f, 69.f, 89.f, 113.f
};
// E2M1 values, shared by MXFP4 and NVFP4
constexpr constant static float kvalues_mxfp4_f[16] = {
0, .5f, 1.f, 1.5f, 2.f, 3.f, 4.f, 6.f, -0, -.5f, -1.f, -1.5f, -2.f, -3.f, -4.f, -6.f
};
@@ -68,6 +69,18 @@ static inline float e8m0_to_fp32(uint8_t x) {
return as_type<float>(bits);
}
// UE4M3: unsigned, 4 exponent bits with bias 7, 3 mantissa bits - the NVFP4 sub-block scale
static inline float ue4m3_to_fp32(uint8_t x) {
if (x == 0x7F) {
return 0.0f;
}
const int e = (x >> 3) & 0xF;
const int m = x & 0x7;
return e == 0 ? m*(1.0f/512.0f) : as_type<float>((uint32_t) (((e + 120) << 23) | (m << 20)));
}
static inline float dot(float x, float y) {
return x*y;
}
@@ -124,3 +137,46 @@ template<> inline float4 elu_approx<float4>(float4 x) {
return res;
}
template <typename T> struct value_type;
template <> struct value_type<float4x4> { typedef float type; };
template <> struct value_type<half4x4> { typedef half type; };
#if defined(GGML_METAL_HAS_BF16)
template <> struct value_type<bfloat4x4> { typedef bfloat type; };
#endif
template <typename T> struct value_type_4x4;
template <> struct value_type_4x4<float> { typedef float4x4 type; };
template <> struct value_type_4x4<half> { typedef half4x4 type; };
#if defined(GGML_METAL_HAS_BF16)
template <> struct value_type_4x4<bfloat> { typedef bfloat4x4 type; };
#endif
template <typename T> struct value_type_2x4;
template <> struct value_type_2x4<float> { typedef float2x4 type; };
template <> struct value_type_2x4<half> { typedef half2x4 type; };
#if defined(GGML_METAL_HAS_BF16)
template <> struct value_type_2x4<bfloat> { typedef bfloat2x4 type; };
#endif
template <typename T> struct value_type_8x8;
template <> struct value_type_8x8<float> { typedef simdgroup_float8x8 type; };
template <> struct value_type_8x8<half> { typedef simdgroup_half8x8 type; };
#if defined(GGML_METAL_HAS_BF16)
template <> struct value_type_8x8<bfloat> { typedef simdgroup_bfloat8x8 type; };
#endif
template <typename T> struct value_type_4;
template <> struct value_type_4<float> { typedef float4 type; };
template <> struct value_type_4<half> { typedef half4 type; };
template <> struct value_type_4<int32_t> { typedef int4 type; };
#if defined(GGML_METAL_HAS_BF16)
template <> struct value_type_4<bfloat> { typedef bfloat4 type; };
#endif
template <typename T> struct value_type_2;
template <> struct value_type_2<float> { typedef float2 type; };
template <> struct value_type_2<half> { typedef half2 type; };
#if defined(GGML_METAL_HAS_BF16)
template <> struct value_type_2<bfloat> { typedef bfloat2 type; };
#endif
+77 -38
View File
@@ -378,6 +378,45 @@ void dequantize_mxfp4_t4(device const block_mxfp4 * xb, short il, thread type4 &
reg[3] = d * kvalues_mxfp4_f[(q2[4*il4 + 3] >> shr) & 0x0F];
}
// NVFP4: 64 weights per block split into four 16-weight sub-blocks, each with its own UE4M3 scale.
// the 16 weights of a sub-block are the low nibbles of its 8 bytes followed by the high nibbles
template <typename type4x4>
void dequantize_nvfp4(device const block_nvfp4 * xb, short il, thread type4x4 & reg) {
device const uint8_t * q = (device const uint8_t *)xb->qs + 8*il;
const float d = ue4m3_to_fp32(xb->d[il]);
float4x4 reg_f;
for (int i = 0; i < 4; ++i) {
device const uint8_t * qb = q + 4*(i % 2);
const uint8_t shr = i < 2 ? 0 : 4;
reg_f[i][0] = d * kvalues_mxfp4_f[(qb[0] >> shr) & 0x0F];
reg_f[i][1] = d * kvalues_mxfp4_f[(qb[1] >> shr) & 0x0F];
reg_f[i][2] = d * kvalues_mxfp4_f[(qb[2] >> shr) & 0x0F];
reg_f[i][3] = d * kvalues_mxfp4_f[(qb[3] >> shr) & 0x0F];
}
reg = (type4x4) reg_f;
}
template <typename type4>
void dequantize_nvfp4_t4(device const block_nvfp4 * xb, short il, thread type4 & reg) {
const short s = il/4; // sub-block
const short il4 = il%4; // 4-weight chunk within the sub-block
device const uint8_t * q = (device const uint8_t *)xb->qs + 8*s + 4*(il4 % 2);
const float d = ue4m3_to_fp32(xb->d[s]);
const uint8_t shr = il4 >= 2 ? 4 : 0;
reg[0] = d * kvalues_mxfp4_f[(q[0] >> shr) & 0x0F];
reg[1] = d * kvalues_mxfp4_f[(q[1] >> shr) & 0x0F];
reg[2] = d * kvalues_mxfp4_f[(q[2] >> shr) & 0x0F];
reg[3] = d * kvalues_mxfp4_f[(q[3] >> shr) & 0x0F];
}
template <typename type4x4>
void dequantize_q2_K(device const block_q2_K *xb, short il, thread type4x4 & reg) {
const float d = xb->d;
@@ -393,7 +432,7 @@ void dequantize_q2_K(device const block_q2_K *xb, short il, thread type4x4 & reg
uchar mask = il>1 ? (il>2 ? 192 : 48) : (il>0 ? 12 : 3);
dl = d * (sc & 0xF) * coef, ml = min * (sc >> 4);
for (int i = 0; i < 16; ++i) {
reg[i/4][i%4] = dl * (q[i] & mask) - ml;
reg[i/4][i%4] = (typename value_type<type4x4>::type) (dl * (q[i] & mask) - ml);
}
}
@@ -422,7 +461,7 @@ void dequantize_q3_K(device const block_q3_K *xb, short il, thread type4x4 & reg
dl *= coef;
for (int i = 0; i < 16; ++i) {
reg[i/4][i%4] = dl * (q[i] & mask) - (h[i] & m ? 0 : ml);
reg[i/4][i%4] = (typename value_type<type4x4>::type) (dl * (q[i] & mask) - (h[i] & m ? 0 : ml));
}
}
@@ -446,7 +485,7 @@ void dequantize_q4_K(device const block_q4_K * xb, short il, thread type4x4 & re
const ushort mask = il < 2 ? 0x0F : 0xF0;
for (int i = 0; i < 16; ++i) {
reg[i/4][i%4] = dl * (q[i] & mask) - ml;
reg[i/4][i%4] = (typename value_type<type4x4>::type) (dl * (q[i] & mask) - ml);
}
}
@@ -469,7 +508,7 @@ void dequantize_q5_K(device const block_q5_K *xb, short il, thread type4x4 & reg
const ushort mask = il<2 ? 0x0F : 0xF0;
const float qh_val = il<2 ? 16.f : 256.f;
for (int i = 0; i < 16; ++i) {
reg[i/4][i%4] = dl * ((q[i] & mask) + (qh[i] & ul ? qh_val : 0)) - ml;
reg[i/4][i%4] = (typename value_type<type4x4>::type) (dl * ((q[i] & mask) + (qh[i] & ul ? qh_val : 0)) - ml);
}
}
@@ -499,10 +538,10 @@ void dequantize_q6_K(device const block_q6_K *xb, short il, thread type4x4 & reg
const uint32_t low = (ql[2*i] | (uint32_t)(ql[2*i+1] << 16)) & kmask2;
const uint32_t high = (qh[2*i] | (uint32_t)(qh[2*i+1] << 16)) & kmask1;
const uint32_t q = ((high << shl_h) >> shr_h) | (low >> shr_l);
reg[i][0] = dl0 * ((half)(q & 0xFF)) - ml;
reg[i][1] = dl1 * ((float)(q & 0xFF00)) - ml;
reg[i][2] = dl2 * ((float)(q & 0xFF0000)) - ml;
reg[i][3] = dl3 * ((float)(q & 0xFF000000)) - ml;
reg[i][0] = (typename value_type<type4x4>::type) (dl0 * ((half)(q & 0xFF)) - ml);
reg[i][1] = (typename value_type<type4x4>::type) (dl1 * ((float)(q & 0xFF00)) - ml);
reg[i][2] = (typename value_type<type4x4>::type) (dl2 * ((float)(q & 0xFF0000)) - ml);
reg[i][3] = (typename value_type<type4x4>::type) (dl3 * ((float)(q & 0xFF000000)) - ml);
}
}
@@ -522,12 +561,12 @@ void dequantize_iq2_xxs(device const block_iq2_xxs * xb, short il, thread type4x
constant uint8_t * grid = (constant uint8_t *)(iq2xxs_grid + aux8[2*il+0]);
uint8_t signs = ksigns_iq2xs[(aux32_s >> 14*il) & 127];
for (int i = 0; i < 8; ++i) {
reg[i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f);
reg[i/4][i%4] = (typename value_type<type4x4>::type) (dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f));
}
grid = (constant uint8_t *)(iq2xxs_grid + aux8[2*il+1]);
signs = ksigns_iq2xs[(aux32_s >> (14*il+7)) & 127];
for (int i = 0; i < 8; ++i) {
reg[2+i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f);
reg[2+i/4][i%4] = (typename value_type<type4x4>::type) (dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f));
}
}
@@ -543,12 +582,12 @@ void dequantize_iq2_xs(device const block_iq2_xs * xb, short il, thread type4x4
constant uint8_t * grid = (constant uint8_t *)(iq2xs_grid + (q2[2*il+0] & 511));
uint8_t signs = ksigns_iq2xs[q2[2*il+0] >> 9];
for (int i = 0; i < 8; ++i) {
reg[i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f);
reg[i/4][i%4] = (typename value_type<type4x4>::type) (dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f));
}
grid = (constant uint8_t *)(iq2xs_grid + (q2[2*il+1] & 511));
signs = ksigns_iq2xs[q2[2*il+1] >> 9];
for (int i = 0; i < 8; ++i) {
reg[2+i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f);
reg[2+i/4][i%4] = (typename value_type<type4x4>::type) (dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f));
}
}
@@ -567,15 +606,15 @@ void dequantize_iq3_xxs(device const block_iq3_xxs * xb, short il, thread type4x
constant uint8_t * grid2 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+1]);
uint8_t signs = ksigns_iq2xs[(aux32 >> 14*il) & 127];
for (int i = 0; i < 4; ++i) {
reg[0][i] = dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f);
reg[1][i] = dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f);
reg[0][i] = (typename value_type<type4x4>::type) (dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f));
reg[1][i] = (typename value_type<type4x4>::type) (dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f));
}
grid1 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+2]);
grid2 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+3]);
signs = ksigns_iq2xs[(aux32 >> (14*il+7)) & 127];
for (int i = 0; i < 4; ++i) {
reg[2][i] = dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f);
reg[3][i] = dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f);
reg[2][i] = (typename value_type<type4x4>::type) (dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f));
reg[3][i] = (typename value_type<type4x4>::type) (dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f));
}
}
@@ -593,14 +632,14 @@ void dequantize_iq3_s(device const block_iq3_s * xb, short il, thread type4x4 &
constant uint8_t * grid1 = (constant uint8_t *)(iq3s_grid + (qs[4*il+0] | ((qh << 8) & 256)));
constant uint8_t * grid2 = (constant uint8_t *)(iq3s_grid + (qs[4*il+1] | ((qh << 7) & 256)));
for (int i = 0; i < 4; ++i) {
reg[0][i] = dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i+0]);
reg[1][i] = dl * grid2[i] * select(1, -1, signs[0] & kmask_iq2xs[i+4]);
reg[0][i] = (typename value_type<type4x4>::type) (dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i+0]));
reg[1][i] = (typename value_type<type4x4>::type) (dl * grid2[i] * select(1, -1, signs[0] & kmask_iq2xs[i+4]));
}
grid1 = (constant uint8_t *)(iq3s_grid + (qs[4*il+2] | ((qh << 6) & 256)));
grid2 = (constant uint8_t *)(iq3s_grid + (qs[4*il+3] | ((qh << 5) & 256)));
for (int i = 0; i < 4; ++i) {
reg[2][i] = dl * grid1[i] * select(1, -1, signs[1] & kmask_iq2xs[i+0]);
reg[3][i] = dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i+4]);
reg[2][i] = (typename value_type<type4x4>::type) (dl * grid1[i] * select(1, -1, signs[1] & kmask_iq2xs[i+0]));
reg[3][i] = (typename value_type<type4x4>::type) (dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i+4]));
}
}
@@ -618,8 +657,8 @@ void dequantize_iq2_s(device const block_iq2_s * xb, short il, thread type4x4 &
constant uint8_t * grid1 = (constant uint8_t *)(iq2s_grid + (qs[0] | ((qh << 8) & 0x300)));
constant uint8_t * grid2 = (constant uint8_t *)(iq2s_grid + (qs[1] | ((qh << 6) & 0x300)));
for (int i = 0; i < 8; ++i) {
reg[i/4+0][i%4] = dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i]);
reg[i/4+2][i%4] = dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i]);
reg[i/4+0][i%4] = (typename value_type<type4x4>::type) (dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i]));
reg[i/4+2][i%4] = (typename value_type<type4x4>::type) (dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i]));
}
}
@@ -637,10 +676,10 @@ void dequantize_iq1_s(device const block_iq1_s * xb, short il, thread type4x4 &
constant uint8_t * grid1 = (constant uint8_t *)(iq1s_grid_gpu + (qs[0] | ((h << 8) & 0x700)));
constant uint8_t * grid2 = (constant uint8_t *)(iq1s_grid_gpu + (qs[1] | ((h << 5) & 0x700)));
for (int i = 0; i < 4; ++i) {
reg[0][i] = dl * (grid1[i] & 0xf) + ml;
reg[1][i] = dl * (grid1[i] >> 4) + ml;
reg[2][i] = dl * (grid2[i] & 0xf) + ml;
reg[3][i] = dl * (grid2[i] >> 4) + ml;
reg[0][i] = (typename value_type<type4x4>::type) (dl * (grid1[i] & 0xf) + ml);
reg[1][i] = (typename value_type<type4x4>::type) (dl * (grid1[i] >> 4) + ml);
reg[2][i] = (typename value_type<type4x4>::type) (dl * (grid2[i] & 0xf) + ml);
reg[3][i] = (typename value_type<type4x4>::type) (dl * (grid2[i] >> 4) + ml);
}
}
@@ -664,10 +703,10 @@ void dequantize_iq1_m(device const block_iq1_m * xb, short il, thread type4x4 &
constant uint8_t * grid1 = (constant uint8_t *)(iq1s_grid_gpu + (qs[0] | ((qh[0] << 8) & 0x700)));
constant uint8_t * grid2 = (constant uint8_t *)(iq1s_grid_gpu + (qs[1] | ((qh[0] << 4) & 0x700)));
for (int i = 0; i < 4; ++i) {
reg[0][i] = dl * (grid1[i] & 0xf) + ml1;
reg[1][i] = dl * (grid1[i] >> 4) + ml1;
reg[2][i] = dl * (grid2[i] & 0xf) + ml2;
reg[3][i] = dl * (grid2[i] >> 4) + ml2;
reg[0][i] = (typename value_type<type4x4>::type) (dl * (grid1[i] & 0xf) + ml1);
reg[1][i] = (typename value_type<type4x4>::type) (dl * (grid1[i] >> 4) + ml1);
reg[2][i] = (typename value_type<type4x4>::type) (dl * (grid2[i] & 0xf) + ml2);
reg[3][i] = (typename value_type<type4x4>::type) (dl * (grid2[i] >> 4) + ml2);
}
}
@@ -679,10 +718,10 @@ void dequantize_iq4_nl(device const block_iq4_nl * xb, short il, thread type4x4
thread const uint8_t * q8 = (thread const uint8_t *)&aux32;
for (int i = 0; i < 4; ++i) {
aux32 = ((q4[2*i] | (q4[2*i+1] << 16)) >> 4*il) & 0x0f0f0f0f;
reg[i][0] = d * kvalues_iq4nl_f[q8[0]];
reg[i][1] = d * kvalues_iq4nl_f[q8[1]];
reg[i][2] = d * kvalues_iq4nl_f[q8[2]];
reg[i][3] = d * kvalues_iq4nl_f[q8[3]];
reg[i][0] = (typename value_type<type4x4>::type) (d * kvalues_iq4nl_f[q8[0]]);
reg[i][1] = (typename value_type<type4x4>::type) (d * kvalues_iq4nl_f[q8[1]]);
reg[i][2] = (typename value_type<type4x4>::type) (d * kvalues_iq4nl_f[q8[2]]);
reg[i][3] = (typename value_type<type4x4>::type) (d * kvalues_iq4nl_f[q8[3]]);
}
}
@@ -712,10 +751,10 @@ void dequantize_iq4_xs(device const block_iq4_xs * xb, short il, thread type4x4
thread const uint8_t * q8 = (thread const uint8_t *)&aux32;
for (int i = 0; i < 4; ++i) {
aux32 = (q4[i] >> 4*il) & 0x0f0f0f0f;
reg[i][0] = d * kvalues_iq4nl_f[q8[0]];
reg[i][1] = d * kvalues_iq4nl_f[q8[1]];
reg[i][2] = d * kvalues_iq4nl_f[q8[2]];
reg[i][3] = d * kvalues_iq4nl_f[q8[3]];
reg[i][0] = (typename value_type<type4x4>::type) (d * kvalues_iq4nl_f[q8[0]]);
reg[i][1] = (typename value_type<type4x4>::type) (d * kvalues_iq4nl_f[q8[1]]);
reg[i][2] = (typename value_type<type4x4>::type) (d * kvalues_iq4nl_f[q8[2]]);
reg[i][3] = (typename value_type<type4x4>::type) (d * kvalues_iq4nl_f[q8[3]]);
}
}
+17 -27
View File
@@ -17,28 +17,17 @@ constant int32_t FC_flash_attn_ext_nsg [[function_constant(FC_FLASH_ATTN_EXT +
// ref: https://arxiv.org/pdf/2307.08691.pdf
template<
typename q_t, // query types in shared memory
typename q4_t,
typename q8x8_t,
typename k_t, // key types in shared memory
typename k4x4_t,
typename k8x8_t,
typename v_t, // value types in shared memory
typename v4x4_t,
typename v8x8_t,
typename qk_t, // Q*K types
typename qk8x8_t,
typename s_t, // soft-max types
typename s2_t,
typename s8x8_t,
typename o_t, // attention accumulation types
typename o4_t,
typename o8x8_t,
typename kd4x4_t, // key type in device memory
short nl_k,
void (*deq_k)(device const kd4x4_t *, short, thread k4x4_t &),
void (*deq_k)(device const kd4x4_t *, short, thread typename value_type_4x4<k_t>::type &),
typename vd4x4_t, // value type in device memory
short nl_v,
void (*deq_v)(device const vd4x4_t *, short, thread v4x4_t &),
void (*deq_v)(device const vd4x4_t *, short, thread typename value_type_4x4<v_t>::type &),
short DK, // K head size
short DV, // V head size
short Q, // queries per threadgroup
@@ -58,6 +47,18 @@ void kernel_flash_attn_ext_impl(
uint3 tgpig,
ushort tiisg,
ushort sgitg) {
using q4_t = typename value_type_4 <q_t>::type;
using q8x8_t = typename value_type_8x8 <q_t>::type;
using k4x4_t = typename value_type_4x4 <k_t>::type;
using k8x8_t = typename value_type_8x8 <k_t>::type;
using v4x4_t = typename value_type_4x4 <v_t>::type;
using v8x8_t = typename value_type_8x8 <v_t>::type;
using qk8x8_t = typename value_type_8x8<qk_t>::type;
using s2_t = typename value_type_2 <s_t>::type;
using s8x8_t = typename value_type_8x8 <s_t>::type;
using o4_t = typename value_type_4 <o_t>::type;
using o8x8_t = typename value_type_8x8 <o_t>::type;
const ushort iq3 = tgpig[2];
const ushort iq2 = tgpig[1];
const ushort iq1 = tgpig[0]*Q;
@@ -656,28 +657,17 @@ void kernel_flash_attn_ext_impl(
template<
typename q_t, // query types in shared memory
typename q4_t,
typename q8x8_t,
typename k_t, // key types in shared memory
typename k4x4_t,
typename k8x8_t,
typename v_t, // value types in shared memory
typename v4x4_t,
typename v8x8_t,
typename qk_t, // Q*K types
typename qk8x8_t,
typename s_t, // soft-max types
typename s2_t,
typename s8x8_t,
typename o_t, // attention accumulation types
typename o4_t,
typename o8x8_t,
typename kd4x4_t, // key type in device memory
short nl_k,
void (*deq_k)(device const kd4x4_t *, short, thread k4x4_t &),
void (*deq_k)(device const kd4x4_t *, short, thread typename value_type_4x4<k_t>::type &),
typename vd4x4_t, // value type in device memory
short nl_v,
void (*deq_v)(device const vd4x4_t *, short, thread v4x4_t &),
void (*deq_v)(device const vd4x4_t *, short, thread typename value_type_4x4<v_t>::type &),
short DK, // K head size
short DV, // V head size
short Q = OP_FLASH_ATTN_EXT_NQPSG, // queries per threadgroup
@@ -696,7 +686,7 @@ kernel void kernel_flash_attn_ext(
uint3 tgpig[[threadgroup_position_in_grid]],
ushort tiisg[[thread_index_in_simdgroup]],
ushort sgitg[[simdgroup_index_in_threadgroup]]) {
#define FWD_TMPL q_t, q4_t, q8x8_t, k_t, k4x4_t, k8x8_t, v_t, v4x4_t, v8x8_t, qk_t, qk8x8_t, s_t, s2_t, s8x8_t, o_t, o4_t, o8x8_t, kd4x4_t, nl_k, deq_k, vd4x4_t, nl_v, deq_v, DK, DV, Q, C
#define FWD_TMPL q_t, k_t, v_t, qk_t, s_t, o_t, kd4x4_t, nl_k, deq_k, vd4x4_t, nl_v, deq_v, DK, DV, Q, C
#define FWD_ARGS args, q, k, v, mask, sinks, pad, blk, dst, shmem_f16, tgpig, tiisg, sgitg
switch (FC_flash_attn_ext_nsg) {
// note: disabled cases to reduce library load time
+18 -21
View File
@@ -6,31 +6,28 @@
// template to be able to explore different combinations
#define FA_TYPES \
half, half4, simdgroup_half8x8, \
half, half4x4, simdgroup_half8x8, \
half, half4x4, simdgroup_half8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
float, float4, simdgroup_float8x8
//half, half4, simdgroup_half8x8
half, \
half, \
half, \
float, \
float, \
float
#define FA_TYPES_BF \
bfloat, bfloat4, simdgroup_bfloat8x8, \
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
half, half4, simdgroup_half8x8
//float, float4, simdgroup_float8x8
bfloat, \
bfloat, \
bfloat, \
float, \
float, \
half
#define FA_TYPES_F32 \
half, half4, simdgroup_half8x8, \
float, float4x4, simdgroup_float8x8, \
float, float4x4, simdgroup_float8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
float, float4, simdgroup_float8x8
//half, half4, simdgroup_half8x8
half, \
float, \
float, \
float, \
float, \
float
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
+18 -21
View File
@@ -3,31 +3,28 @@
#include "fa_common.metal"
#define FA_TYPES \
half, half4, simdgroup_half8x8, \
half, half4x4, simdgroup_half8x8, \
half, half4x4, simdgroup_half8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
float, float4, simdgroup_float8x8
//half, half4, simdgroup_half8x8
half, \
half, \
half, \
float, \
float, \
float
#define FA_TYPES_BF \
bfloat, bfloat4, simdgroup_bfloat8x8, \
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
half, half4, simdgroup_half8x8
//float, float4, simdgroup_float8x8
bfloat, \
bfloat, \
bfloat, \
float, \
float, \
half
#define FA_TYPES_F32 \
half, half4, simdgroup_half8x8, \
float, float4x4, simdgroup_float8x8, \
float, float4x4, simdgroup_float8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
float, float4, simdgroup_float8x8
//half, half4, simdgroup_half8x8
half, \
float, \
float, \
float, \
float, \
float
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
+18 -21
View File
@@ -3,31 +3,28 @@
#include "fa_common.metal"
#define FA_TYPES \
half, half4, simdgroup_half8x8, \
half, half4x4, simdgroup_half8x8, \
half, half4x4, simdgroup_half8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
float, float4, simdgroup_float8x8
//half, half4, simdgroup_half8x8
half, \
half, \
half, \
float, \
float, \
float
#define FA_TYPES_BF \
bfloat, bfloat4, simdgroup_bfloat8x8, \
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
half, half4, simdgroup_half8x8
//float, float4, simdgroup_float8x8
bfloat, \
bfloat, \
bfloat, \
float, \
float, \
half
#define FA_TYPES_F32 \
half, half4, simdgroup_half8x8, \
float, float4x4, simdgroup_float8x8, \
float, float4x4, simdgroup_float8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
float, float4, simdgroup_float8x8
//half, half4, simdgroup_half8x8
half, \
float, \
float, \
float, \
float, \
float
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
+18 -21
View File
@@ -3,31 +3,28 @@
#include "fa_common.metal"
#define FA_TYPES \
half, half4, simdgroup_half8x8, \
half, half4x4, simdgroup_half8x8, \
half, half4x4, simdgroup_half8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
float, float4, simdgroup_float8x8
//half, half4, simdgroup_half8x8
half, \
half, \
half, \
float, \
float, \
float
#define FA_TYPES_BF \
bfloat, bfloat4, simdgroup_bfloat8x8, \
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
half, half4, simdgroup_half8x8
//float, float4, simdgroup_float8x8
bfloat, \
bfloat, \
bfloat, \
float, \
float, \
half
#define FA_TYPES_F32 \
half, half4, simdgroup_half8x8, \
float, float4x4, simdgroup_float8x8, \
float, float4x4, simdgroup_float8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
float, float4, simdgroup_float8x8
//half, half4, simdgroup_half8x8
half, \
float, \
float, \
float, \
float, \
float
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
+18 -21
View File
@@ -3,31 +3,28 @@
#include "fa_common.metal"
#define FA_TYPES \
half, half4, simdgroup_half8x8, \
half, half4x4, simdgroup_half8x8, \
half, half4x4, simdgroup_half8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
float, float4, simdgroup_float8x8
//half, half4, simdgroup_half8x8
half, \
half, \
half, \
float, \
float, \
float
#define FA_TYPES_BF \
bfloat, bfloat4, simdgroup_bfloat8x8, \
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
half, half4, simdgroup_half8x8
//float, float4, simdgroup_float8x8
bfloat, \
bfloat, \
bfloat, \
float, \
float, \
half
#define FA_TYPES_F32 \
half, half4, simdgroup_half8x8, \
float, float4x4, simdgroup_float8x8, \
float, float4x4, simdgroup_float8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
float, float4, simdgroup_float8x8
//half, half4, simdgroup_half8x8
half, \
float, \
float, \
float, \
float, \
float
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
+18 -21
View File
@@ -3,31 +3,28 @@
#include "fa_common.metal"
#define FA_TYPES \
half, half4, simdgroup_half8x8, \
half, half4x4, simdgroup_half8x8, \
half, half4x4, simdgroup_half8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
float, float4, simdgroup_float8x8
//half, half4, simdgroup_half8x8
half, \
half, \
half, \
float, \
float, \
float
#define FA_TYPES_BF \
bfloat, bfloat4, simdgroup_bfloat8x8, \
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
half, half4, simdgroup_half8x8
//float, float4, simdgroup_float8x8
bfloat, \
bfloat, \
bfloat, \
float, \
float, \
half
#define FA_TYPES_F32 \
half, half4, simdgroup_half8x8, \
float, float4x4, simdgroup_float8x8, \
float, float4x4, simdgroup_float8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
float, float4, simdgroup_float8x8
//half, half4, simdgroup_half8x8
half, \
float, \
float, \
float, \
float, \
float
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
+18 -21
View File
@@ -3,31 +3,28 @@
#include "fa_common.metal"
#define FA_TYPES \
half, half4, simdgroup_half8x8, \
half, half4x4, simdgroup_half8x8, \
half, half4x4, simdgroup_half8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
float, float4, simdgroup_float8x8
//half, half4, simdgroup_half8x8
half, \
half, \
half, \
float, \
float, \
float
#define FA_TYPES_BF \
bfloat, bfloat4, simdgroup_bfloat8x8, \
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
half, half4, simdgroup_half8x8
//float, float4, simdgroup_float8x8
bfloat, \
bfloat, \
bfloat, \
float, \
float, \
half
#define FA_TYPES_F32 \
half, half4, simdgroup_half8x8, \
float, float4x4, simdgroup_float8x8, \
float, float4x4, simdgroup_float8x8, \
float, simdgroup_float8x8, \
float, float2, simdgroup_float8x8, \
float, float4, simdgroup_float8x8
//half, half4, simdgroup_half8x8
half, \
float, \
float, \
float, \
float, \
float
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
+15 -14
View File
@@ -10,7 +10,6 @@ constant bool FC_flash_attn_ext_tensor_has_scap [[function_constant(FC_FLASH_AT
// ref: https://arxiv.org/pdf/2307.08691.pdf
template<
typename T, // Q, K, V and P types
typename T4,
short DK, // K head size
short DV, // V head size
short Q = OP_FLASH_ATTN_EXT_TENSOR_NQPSG, // queries per threadgroup
@@ -29,6 +28,8 @@ kernel void kernel_flash_attn_ext_tensor(
uint3 tgpig [[threadgroup_position_in_grid]],
ushort tiisg [[thread_index_in_simdgroup]],
ushort sgitg [[simdgroup_index_in_threadgroup]]) {
using T4 = typename value_type_4<T>::type;
constexpr short NW = N_SIMDWIDTH;
constexpr short NT = NW*NSG;
constexpr short NQ = Q/NSG;
@@ -279,20 +280,20 @@ kernel void kernel_flash_attn_ext_tensor(
co.store(td);
}
typedef decltype(kernel_flash_attn_ext_tensor<half, half4, 64, 64>) flash_attn_ext_tensor_t;
typedef decltype(kernel_flash_attn_ext_tensor<half, 64, 64>) flash_attn_ext_tensor_t;
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 64, 64>;
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 128, 128>;
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 192, 128>;
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 256, 256>;
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 512, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 576, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, 64, 64>;
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, 128, 128>;
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, 192, 128>;
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, 256, 256>;
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, 512, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, 576, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 64, 64>;
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 128, 128>;
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 192, 128>;
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 256, 256>;
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 512, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 576, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, 64, 64>;
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, 128, 128>;
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, 192, 128>;
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, 256, 256>;
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, 512, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, 576, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
#endif // GGML_METAL_HAS_TENSOR
@@ -15,19 +15,18 @@ constant int32_t FC_flash_attn_ext_vec_nwg [[function_constant(FC_FLASH_ATTN_EX
constant bool FC_flash_attn_ext_vec_has_sparse [[function_constant(FC_FLASH_ATTN_EXT_VEC + 5)]];
constant bool FC_flash_attn_ext_vec_has_rows [[function_constant(FC_FLASH_ATTN_EXT_VEC + 6)]];
template<
typename q4_t, // query types in shared memory
typename k4_t, // key types in shared memory
typename v4_t, // value types in shared memory
typename q_t, // query types in shared memory
typename k_t, // key types in shared memory
typename v_t, // value types in shared memory
typename qk_t, // Q*K types
typename s_t, // soft-max types
typename s4_t,
typename o4_t, // attention accumulation types
typename o_t, // attention accumulation types
typename kd4_t, // key type in device memory
short nl_k,
void (*deq_k_t4)(device const kd4_t *, short, thread k4_t &),
void (*deq_k_t4)(device const kd4_t *, short, thread typename value_type_4<k_t>::type &),
typename vd4_t, // value type in device memory
short nl_v,
void (*deq_v_t4)(device const vd4_t *, short, thread v4_t &),
void (*deq_v_t4)(device const vd4_t *, short, thread typename value_type_4<v_t>::type &),
short DK, // K head size
short DV, // V head size
short NE = 4, // head elements per thread
@@ -48,6 +47,12 @@ kernel void kernel_flash_attn_ext_vec(
uint3 tgpig[[threadgroup_position_in_grid]],
ushort tiisg[[thread_index_in_simdgroup]],
ushort sgitg[[simdgroup_index_in_threadgroup]]) {
using q4_t = typename value_type_4<q_t>::type;
using k4_t = typename value_type_4<k_t>::type;
using v4_t = typename value_type_4<v_t>::type;
using s4_t = typename value_type_4<s_t>::type;
using o4_t = typename value_type_4<o_t>::type;
static_assert(DK % 32 == 0, "DK must be divisible by 32");
static_assert(DV % 32 == 0, "DV must be divisible by 32");
+12 -12
View File
@@ -3,20 +3,20 @@
#include "fa_vec_common.metal"
#define FA_TYPES \
half4, \
half4, \
half4, \
float, \
float, float4, \
float4
half, \
half, \
half, \
float, \
float, \
float
#define FA_TYPES_F32 \
half4, \
float4, \
float4, \
float, \
float, float4, \
float4
half, \
float, \
float, \
float, \
float, \
float
typedef decltype(kernel_flash_attn_ext_vec<FA_TYPES, half4, 1, dequantize_f16_t4, half4, 1, dequantize_f16_t4, 128, 128, 4>) flash_attn_ext_vec_t;
+12 -12
View File
@@ -3,20 +3,20 @@
#include "fa_vec_common.metal"
#define FA_TYPES \
half4, \
half4, \
half4, \
float, \
float, float4, \
float4
half, \
half, \
half, \
float, \
float, \
float
#define FA_TYPES_F32 \
half4, \
float4, \
float4, \
float, \
float, float4, \
float4
half, \
float, \
float, \
float, \
float, \
float
typedef decltype(kernel_flash_attn_ext_vec<FA_TYPES, half4, 1, dequantize_f16_t4, half4, 1, dequantize_f16_t4, 128, 128, 4>) flash_attn_ext_vec_t;
+12 -12
View File
@@ -3,20 +3,20 @@
#include "fa_vec_common.metal"
#define FA_TYPES \
half4, \
half4, \
half4, \
float, \
float, float4, \
float4
half, \
half, \
half, \
float, \
float, \
float
#define FA_TYPES_F32 \
half4, \
float4, \
float4, \
float, \
float, float4, \
float4
half, \
float, \
float, \
float, \
float, \
float
typedef decltype(kernel_flash_attn_ext_vec<FA_TYPES, half4, 1, dequantize_f16_t4, half4, 1, dequantize_f16_t4, 128, 128, 4>) flash_attn_ext_vec_t;
+12 -12
View File
@@ -3,20 +3,20 @@
#include "fa_vec_common.metal"
#define FA_TYPES \
half4, \
half4, \
half4, \
float, \
float, float4, \
float4
half, \
half, \
half, \
float, \
float, \
float
#define FA_TYPES_F32 \
half4, \
float4, \
float4, \
float, \
float, float4, \
float4
half, \
float, \
float, \
float, \
float, \
float
typedef decltype(kernel_flash_attn_ext_vec<FA_TYPES, half4, 1, dequantize_f16_t4, half4, 1, dequantize_f16_t4, 128, 128, 4>) flash_attn_ext_vec_t;
+12 -12
View File
@@ -3,20 +3,20 @@
#include "fa_vec_common.metal"
#define FA_TYPES \
half4, \
half4, \
half4, \
float, \
float, float4, \
float4
half, \
half, \
half, \
float, \
float, \
float
#define FA_TYPES_F32 \
half4, \
float4, \
float4, \
float, \
float, float4, \
float4
half, \
float, \
float, \
float, \
float, \
float
typedef decltype(kernel_flash_attn_ext_vec<FA_TYPES, half4, 1, dequantize_f16_t4, half4, 1, dequantize_f16_t4, 128, 128, 4>) flash_attn_ext_vec_t;
+12 -12
View File
@@ -3,20 +3,20 @@
#include "fa_vec_common.metal"
#define FA_TYPES \
half4, \
half4, \
half4, \
float, \
float, float4, \
float4
half, \
half, \
half, \
float, \
float, \
float
#define FA_TYPES_F32 \
half4, \
float4, \
float4, \
float, \
float, float4, \
float4
half, \
float, \
float, \
float, \
float, \
float
typedef decltype(kernel_flash_attn_ext_vec<FA_TYPES, half4, 1, dequantize_f16_t4, half4, 1, dequantize_f16_t4, 128, 128, 4>) flash_attn_ext_vec_t;
+12 -12
View File
@@ -3,20 +3,20 @@
#include "fa_vec_common.metal"
#define FA_TYPES \
half4, \
half4, \
half4, \
float, \
float, float4, \
float4
half, \
half, \
half, \
float, \
float, \
float
#define FA_TYPES_F32 \
half4, \
float4, \
float4, \
float, \
float, float4, \
float4
half, \
float, \
float, \
float, \
float, \
float
typedef decltype(kernel_flash_attn_ext_vec<FA_TYPES, half4, 1, dequantize_f16_t4, half4, 1, dequantize_f16_t4, 128, 128, 4>) flash_attn_ext_vec_t;
@@ -3,6 +3,7 @@
constant short FC_gated_delta_net_ne20 [[function_constant(FC_GATED_DELTA_NET + 0)]];
constant short FC_gated_delta_net_ne30 [[function_constant(FC_GATED_DELTA_NET + 1)]];
constant short FC_gated_delta_net_K [[function_constant(FC_GATED_DELTA_NET + 2)]];
constant bool FC_gated_delta_net_rep [[function_constant(FC_GATED_DELTA_NET + 3)]];
#if 1
template<short NSG>
@@ -16,6 +17,10 @@ kernel void kernel_gated_delta_net_impl(
device const char * s,
device char * dst,
device char * dst_fuse,
device const char * pk,
device const char * pv,
device const char * pgb,
device const char * n_rep,
uint3 tgpig[[threadgroup_position_in_grid]],
uint3 tpitg[[thread_position_in_threadgroup]],
uint3 ntg[[threads_per_threadgroup]]) {
@@ -72,6 +77,62 @@ kernel void kernel_gated_delta_net_impl(
const device float * state_out = fused ? (device float *)dst_fuse : (device float *)dst + attn_size;
const uint slot_stride = fused ? (uint)args.nb_out : state_size_per_snap;
// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
if (FC_gated_delta_net_rep) {
const int n_r = ((device const int32_t *) n_rep)[i23];
device const char * pk_ptr = pk + i23*args.nb63 + i11*args.nb61;
device const char * pv_ptr = pv + i23*args.nb73 + i21*args.nb71;
device const char * pgb_ptr = pgb + i23*args.nb83 + i21*args.nb81;
for (int t = 0; t < n_r; t++) {
device const float * k_t = (device const float *) (pk_ptr + t*args.nb62);
device const float * g_t = (device const float *) (pgb_ptr + t*args.nb82);
const float v_t = ((device const float *) (pv_ptr + t*args.nb72))[i20];
const float beta_t = *(device const float *) (pgb_ptr + (args.n_pend + t)*args.nb82);
// same update as below, without the attention output
float s_k = 0.0f;
if (G == 1) {
const float g_exp = exp(g_t[0]);
FOR_UNROLL (short j = 0; j < NSG; j++) {
const short is = tx*NSG + j;
ls[j] *= g_exp;
s_k += ls[j]*k_t[is];
}
} else {
// KDA
FOR_UNROLL (short j = 0; j < NSG; j++) {
const short is = tx*NSG + j;
ls[j] *= exp(g_t[is]);
s_k += ls[j]*k_t[is];
}
}
s_k = simd_sum(s_k);
const float d = (v_t - s_k)*beta_t;
FOR_UNROLL (short j = 0; j < NSG; j++) {
const short is = tx*NSG + j;
ls[j] += k_t[is]*d;
}
}
if (args.keep) {
device float * dst_state = (device float *)state_out + state_out_base;
FOR_UNROLL (short j = 0; j < NSG; j++) {
const short is = tx*NSG + j;
dst_state[is] = ls[j];
}
}
}
for (short t = 0; t < args.ne22; t++) {
float s_k = 0.0f;
@@ -132,7 +193,8 @@ kernel void kernel_gated_delta_net_impl(
}
}
if (K == 1) {
// replay with keep: the state output is the state after the replay
if (K == 1 && !(FC_gated_delta_net_rep && args.keep)) {
device float * dst_state = (device float *)state_out + state_out_base;
FOR_UNROLL (short j = 0; j < NSG; j++) {
const short is = tx*NSG + j;
+16 -10
View File
@@ -465,6 +465,8 @@ kernel void kernel_count_equal(
ushort sgitg[[simdgroup_index_in_threadgroup]],
ushort tiisg[[thread_index_in_simdgroup]],
ushort3 ntg[[threads_per_threadgroup]]) {
using T4 = typename value_type_4<T>::type;
const short NSG = FC_count_equal_nsg;
const int i3 = tgpig.z;
@@ -913,12 +915,14 @@ constant bool FC_top_k_mask_has_extra [[function_constant(FC_TOP_K_MASK + 2)]];
constant bool FC_top_k_mask_vec [[function_constant(FC_TOP_K_MASK + 3)]];
// the fill runs before the scatter, both are fully parallel over the whole dst and over the picks of one row
template <typename T, typename T4>
template <typename T>
kernel void kernel_top_k_mask_fill(
constant ggml_metal_kargs_top_k_mask & args,
device char * dst,
uint tid[[thread_position_in_grid]],
uint ntot[[threads_per_grid]]) {
using T4 = typename value_type_4<T>::type;
const T ninf = T(-INFINITY);
if (FC_top_k_mask_vec) {
@@ -934,14 +938,14 @@ kernel void kernel_top_k_mask_fill(
}
}
typedef decltype(kernel_top_k_mask_fill<half, half4>) kernel_top_k_mask_fill_h_t;
typedef decltype(kernel_top_k_mask_fill<float, float4>) kernel_top_k_mask_fill_f_t;
typedef decltype(kernel_top_k_mask_fill<half>) kernel_top_k_mask_fill_h_t;
typedef decltype(kernel_top_k_mask_fill<float>) kernel_top_k_mask_fill_f_t;
template [[host_name("kernel_top_k_mask_fill_f16")]] kernel kernel_top_k_mask_fill_h_t kernel_top_k_mask_fill<half, half4>;
template [[host_name("kernel_top_k_mask_fill_f32")]] kernel kernel_top_k_mask_fill_f_t kernel_top_k_mask_fill<float, float4>;
template [[host_name("kernel_top_k_mask_fill_f16")]] kernel kernel_top_k_mask_fill_h_t kernel_top_k_mask_fill<half>;
template [[host_name("kernel_top_k_mask_fill_f32")]] kernel kernel_top_k_mask_fill_f_t kernel_top_k_mask_fill<float>;
// one threadgroup per row: copy the mask cells of the live picks and of the extra cells over the fill
template <typename T, typename T4>
template <typename T>
kernel void kernel_top_k_mask(
constant ggml_metal_kargs_top_k_mask & args,
device const char * mask,
@@ -953,6 +957,8 @@ kernel void kernel_top_k_mask(
uint3 tgpig[[threadgroup_position_in_grid]],
uint3 tpitg[[thread_position_in_threadgroup]],
uint3 ntg_max[[threads_per_threadgroup]]) {
using T4 = typename value_type_4<T>::type;
const int i1 = tgpig.x;
const int i2 = tgpig.y;
const int i3 = tgpig.z;
@@ -997,8 +1003,8 @@ kernel void kernel_top_k_mask(
}
}
typedef decltype(kernel_top_k_mask<half, half4>) kernel_top_k_mask_h_t;
typedef decltype(kernel_top_k_mask<float, float4>) kernel_top_k_mask_f_t;
typedef decltype(kernel_top_k_mask<half>) kernel_top_k_mask_h_t;
typedef decltype(kernel_top_k_mask<float>) kernel_top_k_mask_f_t;
template [[host_name("kernel_top_k_mask_f16")]] kernel kernel_top_k_mask_h_t kernel_top_k_mask<half, half4>;
template [[host_name("kernel_top_k_mask_f32")]] kernel kernel_top_k_mask_f_t kernel_top_k_mask<float, float4>;
template [[host_name("kernel_top_k_mask_f16")]] kernel kernel_top_k_mask_h_t kernel_top_k_mask<half>;
template [[host_name("kernel_top_k_mask_f32")]] kernel kernel_top_k_mask_f_t kernel_top_k_mask<float>;
+263 -368
View File
@@ -1,157 +1,20 @@
#include "common.h"
#include "dequantize.h"
constant bool FC_mul_mm_bc_inp [[function_constant(FC_MUL_MM + 0)]];
constant bool FC_mul_mm_bc_out [[function_constant(FC_MUL_MM + 1)]];
constant short FC_mul_mm_ne12 [[function_constant(FC_MUL_MM + 2)]];
constant short FC_mul_mm_ne13 [[function_constant(FC_MUL_MM + 3)]];
constant short FC_mul_mm_r2 [[function_constant(FC_MUL_MM + 4)]];
constant short FC_mul_mm_r3 [[function_constant(FC_MUL_MM + 5)]];
constant bool FC_mul_mm_bc_inp [[function_constant(FC_MUL_MM + 0)]];
constant bool FC_mul_mm_bc_out [[function_constant(FC_MUL_MM + 1)]];
constant short FC_mul_mm_ne12 [[function_constant(FC_MUL_MM + 2)]];
constant short FC_mul_mm_ne13 [[function_constant(FC_MUL_MM + 3)]];
constant short FC_mul_mm_r2 [[function_constant(FC_MUL_MM + 4)]];
constant short FC_mul_mm_r3 [[function_constant(FC_MUL_MM + 5)]];
constant int32_t FC_mul_mm_id_map0_ne02 [[function_constant(FC_MUL_MM + 7)]];
// each block_q contains 16*nl weights
#ifdef GGML_METAL_HAS_TENSOR
template<
typename SA, typename SA_4x4, typename SA_8x8,
typename SB, typename SB_2x4, typename SB_8x8,
typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread SA_4x4 &),
typename T0, typename T0_4x4, typename T1, typename T1_2x4>
kernel void kernel_mul_mm(
constant ggml_metal_kargs_mul_mm & args,
device const char * srcA,
device const char * srcB,
device char * dst,
threadgroup char * shmem [[threadgroup(0)]],
uint3 tgpig [[threadgroup_position_in_grid]],
ushort tiitg [[thread_index_in_threadgroup]],
ushort sgitg [[simdgroup_index_in_threadgroup]]) {
(void) sgitg;
// Matrix dimensions: A(M,K) x B(K,N) -> C(M,N)
const int K = args.ne00;
const int M = args.ne0;
const int N = args.ne1;
// Batch dimension handling
const int im = tgpig.z;
const int i12 = im % FC_mul_mm_ne12;
const int i13 = im / FC_mul_mm_ne12;
// Batch offsets for srcA and srcB
const uint64_t offset0 = (i12/FC_mul_mm_r2)*args.nb02 + (i13/FC_mul_mm_r3)*args.nb03;
// Tile dimensions
constexpr int NRB = SZ_SIMDGROUP * N_MM_BLOCK_X * N_MM_SIMD_GROUP_X;
constexpr int NRA = SZ_SIMDGROUP * N_MM_BLOCK_Y * N_MM_SIMD_GROUP_Y;
// Tile offsets in output matrix
const int ra = tgpig.y * NRA;
const int rb = tgpig.x * NRB;
// Threadgroup memory for dequantized A tile only
threadgroup SA * sa = (threadgroup SA *)(shmem);
// Work-item count for A loading
constexpr int A_WORK_ITEMS = NRA * N_MM_NK;
constexpr int NUM_THREADS = N_SIMDWIDTH * N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y;
// tA wraps threadgroup memory
auto tA = tensor(sa, dextents<int32_t, 2>(N_MM_NK_TOTAL, NRA));
// tB wraps device memory directly
device T1 * ptrB = (device T1 *)(srcB + args.nb12*i12 + args.nb13*i13);
const int strideB = args.nb11 / sizeof(T1);
auto tB = tensor(ptrB, dextents<int32_t, 2>(K, N), array<int, 2>({1, strideB}));
// Configure matmul operation
// note: K is dynamic_extent (clamped to the valid range in PHASE 2), since a static
// N_MM_NK_TOTAL K tile would read src1 out of bounds when K % N_MM_NK_TOTAL != 0
// ref: https://github.com/ggml-org/llama.cpp/pull/27064
mpp::tensor_ops::matmul2d<
mpp::tensor_ops::matmul2d_descriptor(
NRB, NRA, static_cast<int>(dynamic_extent), false, true, true,
mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroups<N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y>> mm;
auto cT = mm.get_destination_cooperative_tensor<decltype(tB), decltype(tA), float>();
// Accumulate partial results over K dimension
for (int loop_k = 0; loop_k < K; loop_k += N_MM_NK_TOTAL) {
// === PHASE 1: Dequantization of A into threadgroup memory ===
for (int work = tiitg; work < A_WORK_ITEMS; work += NUM_THREADS) {
const int row = work / N_MM_NK;
const int k_chunk = work % N_MM_NK;
const int k_pos = loop_k + k_chunk * 16;
const short k_base = k_chunk * 16;
// Bounds check: skip device read if row is out of matrix bounds
if (ra + row < M) {
if (is_same<T0_4x4, block_q>::value && FC_mul_mm_bc_inp) {
// Element-wise reads when K is not aligned (nb01 not aligned for half4x4/float4x4).
// MSL spec Table 2.5: half4x4 requires 8-byte alignment. When K is odd,
// nb01 = K*2 is not 8-byte aligned, so odd-row pointers are misaligned.
// Mirrors the legacy kernel's existing guard.
device const T0 * row_ptr = (device const T0 *)(srcA + args.nb01 * (ra + row) + offset0);
FOR_UNROLL (short i = 0; i < 16; i++) {
sa[row * N_MM_NK_TOTAL + (k_base + i)] = (k_pos + i < K) ? (SA) row_ptr[k_pos + i] : (SA)0;
}
} else {
const int block_idx = k_pos / (16 * nl);
const short il = (k_pos / 16) % nl;
device const block_q * row_ptr = (device const block_q *)(srcA + args.nb01 * (ra + row) + offset0);
SA_4x4 temp_a;
dequantize_func(row_ptr + block_idx, il, temp_a);
FOR_UNROLL (short i = 0; i < 16; i++) {
// Zero-pad A for K positions beyond valid range (handles partial K iterations)
sa[row * N_MM_NK_TOTAL + (k_base + i)] = (k_pos + i < K) ? temp_a[i/4][i%4] : (SA)0;
}
}
} else {
// Zero-pad rows beyond matrix bounds
FOR_UNROLL (short i = 0; i < 16; i++) {
sa[row * N_MM_NK_TOTAL + (k_base + i)] = (SA)0;
}
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
// === PHASE 2: Tensor matmul ===
// Clamp the K extent of both operand tensors to the remaining valid K range so
// the dynamic-K op never reads past the K extent of src1 (or the staged A tile).
const int kExt = min(N_MM_NK_TOTAL, K - loop_k);
auto tAv = tensor(sa, dextents<int32_t, 2>(kExt, NRA), array<int, 2>({1, N_MM_NK_TOTAL}));
auto tBv = tensor(ptrB + loop_k + rb * strideB, dextents<int32_t, 2>(kExt, N - rb), array<int, 2>({1, strideB}));
mm.run(tBv, tAv, cT);
threadgroup_barrier(mem_flags::mem_threadgroup);
}
// Store result tile to output matrix (with batch offset)
// a slice is not used because its byte offset is int32 and wraps at 2 GiB
// ref: https://github.com/ggml-org/llama.cpp/pull/28748
const int tileM = min(NRA, M - ra);
const int tileN = min(NRB, N - rb);
device float * dstTile = (device float *)dst + (uint64_t) im * N * M + (uint64_t) rb * M + ra;
auto tD = tensor(dstTile, dextents<int32_t, 2>(tileM, tileN), array<int, 2>({1, M}));
cT.store(tD);
}
#else
template<
typename S0, typename S0_4x4, typename S0_8x8,
typename S1, typename S1_2x4, typename S1_8x8,
typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread S0_4x4 &),
typename T0, typename T0_4x4, typename T1, typename T1_2x4>
typename S0, typename S1,
typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread typename value_type_4x4<S0>::type &),
typename T0, typename T1>
kernel void kernel_mul_mm(
constant ggml_metal_kargs_mul_mm & args,
device const char * src0,
@@ -162,8 +25,12 @@ kernel void kernel_mul_mm(
ushort tiitg[[thread_index_in_threadgroup]],
ushort sgitg[[simdgroup_index_in_threadgroup]]) {
threadgroup S0 * sa = (threadgroup S0 *)(shmem);
threadgroup S1 * sb = (threadgroup S1 *)(shmem + 4096);
using S0_4x4 = typename value_type_4x4<S0>::type;
using S0_8x8 = typename value_type_8x8<S0>::type;
using S1_2x4 = typename value_type_2x4<S1>::type;
using S1_8x8 = typename value_type_8x8<S1>::type;
using T0_4x4 = typename value_type_4x4<T0>::type;
using T1_2x4 = typename value_type_2x4<T1>::type;
constexpr int NR0 = 64;
constexpr int NR1 = 32;
@@ -172,6 +39,9 @@ kernel void kernel_mul_mm(
constexpr int NL0 = NK/16;
constexpr int NL1 = NK/8;
threadgroup S0 * sa = (threadgroup S0 *)(shmem);
threadgroup S1 * sb = (threadgroup S1 *)(shmem + NR0*NK*sizeof(S0));
const int im = tgpig.z;
const int r0 = tgpig.y*NR0;
const int r1 = tgpig.x*NR1;
@@ -362,7 +232,6 @@ kernel void kernel_mul_mm(
}
}
#endif // GGML_METAL_HAS_TENSOR
template<short ne20> // n_expert_used
kernel void kernel_mul_mm_id_map0(
@@ -544,8 +413,7 @@ template [[host_name("kernel_mul_mm_id_map0_ne20_10")]] kernel kernel_mul_mm_id_
template [[host_name("kernel_mul_mm_id_map0_ne20_16")]] kernel kernel_mul_mm_id_map0_t kernel_mul_mm_id_map0<16>;
template [[host_name("kernel_mul_mm_id_map0_ne20_22")]] kernel kernel_mul_mm_id_map0_t kernel_mul_mm_id_map0<22>;
// TODO: refactor into two seperate functions to avoid ifdef branching: with and without tensor support
template<typename S0, typename S0_4x4, typename S0_8x8, typename S1, typename S1_2x4, typename S1_8x8, typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread S0_4x4 &), typename T0, typename T0_4x4, typename T1, typename T1_2x4>
template<typename S0, typename S1, typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread typename value_type_4x4<S0>::type &), typename T0, typename T1>
kernel void kernel_mul_mm_id(
constant ggml_metal_kargs_mul_mm_id & args,
device const char * src0,
@@ -558,12 +426,12 @@ kernel void kernel_mul_mm_id(
ushort tiitg[[thread_index_in_threadgroup]],
ushort tiisg[[thread_index_in_simdgroup]],
ushort sgitg[[simdgroup_index_in_threadgroup]]) {
threadgroup S0 * sa = (threadgroup S0 *)(shmem);
threadgroup S1 * sb = (threadgroup S1 *)(shmem + 4096);
#ifdef GGML_METAL_HAS_TENSOR
threadgroup float * sc = (threadgroup float *)(shmem);
#endif
using S0_4x4 = typename value_type_4x4<S0>::type;
using S0_8x8 = typename value_type_8x8<S0>::type;
using S1_2x4 = typename value_type_2x4<S1>::type;
using S1_8x8 = typename value_type_8x8<S1>::type;
using T0_4x4 = typename value_type_4x4<T0>::type;
using T1_2x4 = typename value_type_2x4<T1>::type;
constexpr int NR0 = 64;
constexpr int NR1 = 32;
@@ -572,6 +440,10 @@ kernel void kernel_mul_mm_id(
constexpr int NL0 = NK/16;
constexpr int NL1 = NK/8;
threadgroup S0 * sa = (threadgroup S0 *)(shmem);
threadgroup S1 * sb = (threadgroup S1 *)(shmem + NR0*NK*sizeof(S0));
const int tile = tgpig.x; // entry tile, described by the prepass
const int r0 = tgpig.y*NR0;
@@ -608,23 +480,10 @@ kernel void kernel_mul_mm_id(
// skip the upper half of the token tile when the expert did not fill it
constexpr short NR1H = NR1/2;
#ifndef GGML_METAL_HAS_TENSOR
S0_8x8 ma[4];
S1_8x8 mb[2];
simdgroup_float8x8 mc[8];
#else
auto tA = tensor<threadgroup S0, dextents<int32_t, 2>, tensor_inline>(sa, dextents<int32_t, 2>(NK, NR0));
// sb is [NR1][NK] row-major
auto tB0 = tensor<threadgroup S1, dextents<int32_t, 2>, tensor_inline>(sb, dextents<int32_t, 2>(NK, NR1H));
auto tB1 = tensor<threadgroup S1, dextents<int32_t, 2>, tensor_inline>(sb + NR1H*NK, dextents<int32_t, 2>(NK, NR1H));
mpp::tensor_ops::matmul2d<
mpp::tensor_ops::matmul2d_descriptor(NR1H, NR0, NK, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroups<4>> mm;
#endif
const short lr1 = ((short)tiitg/NL1) < nr1 ? ((short)tiitg/NL1) : nr1 - 1; // 0 .. 31
@@ -645,20 +504,14 @@ kernel void kernel_mul_mm_id(
const bool has_hi = nr1 > NR1H;
#ifndef GGML_METAL_HAS_TENSOR
for (short i = 0; i < 8; i++){
mc[i] = make_filled_simdgroup_matrix<float, 8>(0.f);
}
// simdgroups 2,3 own rows NR1H..NR1-1
const bool sg_active = has_hi || sgitg < 2;
#else
auto cT0 = mm.get_destination_cooperative_tensor<decltype(tA), decltype(tB0), float>();
auto cT1 = mm.get_destination_cooperative_tensor<decltype(tA), decltype(tB1), float>();
#endif
for (int loop_k = 0; loop_k < args.ne00; loop_k += NK) {
#ifndef GGML_METAL_HAS_TENSOR
// load data and store to threadgroup memory
if (is_same<T0_4x4, block_q>::value && FC_mul_mm_bc_inp) {
threadgroup_barrier(mem_flags::mem_threadgroup);
@@ -728,66 +581,6 @@ kernel void kernel_mul_mm_id(
*(threadgroup S1_2x4 *)(sb + 64*ib + 8*ly) = (S1_2x4)(*((device T1_2x4 *) y));
}
#else
// load data and store to threadgroup memory
if (is_same<T0_4x4, block_q>::value && FC_mul_mm_bc_inp) {
threadgroup_barrier(mem_flags::mem_threadgroup);
// no need for dequantization
for (short i = 0; i < 16; i++) {
const short sx = 2*il0 + i/8;
const short sy = (tiitg/NL0)/8;
const short lx = i%8;
const short ly = (tiitg/NL0)%8;
//const short lx = (tiitg/NL0)%8;
//const short ly = i%8;
*(sa + NK*(8*sy + ly) + 8*sx + lx) = loop_k + 16*il + i < args.ne00 ? (S0) *((device T0 *) x + i) : 0;
}
} else {
S0_4x4 temp_a;
dequantize_func(x, il, temp_a);
threadgroup_barrier(mem_flags::mem_threadgroup);
FOR_UNROLL (short i = 0; i < 16; i++) {
const short sx = 2*il0 + i/8;
const short sy = (tiitg/NL0)/8;
const short lx = i%8;
const short ly = (tiitg/NL0)%8;
//const short lx = (tiitg/NL0)%8;
//const short ly = i%8;
*(sa + NK*(8*sy + ly) + 8*sx + lx) = temp_a[i/4][i%4];
}
}
if (FC_mul_mm_bc_inp) {
for (short i = 0; i < 8; ++i) {
const short sx = (tiitg%NL1);
const short sy = (tiitg/NL1)/8;
const short lx = i;
const short ly = (tiitg/NL1)%8;
//const short lx = (tiitg/NL1)%8;
//const short ly = i;
*(sb + NK*(8*sy + ly) + 8*sx + lx) = loop_k + iy + i < args.ne00 ? (S1) *((device T1 *) y + i) : 0;
}
} else {
const short sx = (tiitg%NL1);
const short sy = (tiitg/NL1)/8;
//const short lx = i;
const short ly = (tiitg/NL1)%8;
//const short lx = (tiitg/NL1)%8;
//const short ly = i;
*(threadgroup S1_2x4 *)(sb + NK*(8*sy + ly) + 8*sx) = (S1_2x4)(*((device T1_2x4 *) y));
}
#endif
il = (il + 2 < nl) ? il + 2 : il % 2;
x = (il < 2) ? x + (2 + nl - 1)/nl : x;
@@ -796,7 +589,6 @@ kernel void kernel_mul_mm_id(
threadgroup_barrier(mem_flags::mem_threadgroup);
#ifndef GGML_METAL_HAS_TENSOR
if (sg_active) {
// load matrices from threadgroup memory and conduct outer products
threadgroup const S0 * lsma = (sa + 4*64*(sgitg%2));
@@ -825,32 +617,11 @@ kernel void kernel_mul_mm_id(
lsmb += 4*64;
}
}
#else
auto sA = tA.slice(0, 0);
auto sB0 = tB0.slice(0, 0);
mm.run(sB0, sA, cT0);
if (has_hi) {
auto sB1 = tB1.slice(0, 0);
mm.run(sB1, sA, cT1);
}
#endif
}
// block is smaller than 64x32, we should avoid writing data outside of the matrix
threadgroup_barrier(mem_flags::mem_threadgroup);
#ifdef GGML_METAL_HAS_TENSOR
auto tC0 = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sc, dextents<int32_t, 2>(NR0, NR1H));
cT0.store(tC0);
if (has_hi) {
auto tC1 = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sc + NR1H*NR0, dextents<int32_t, 2>(NR0, NR1H));
cT1.store(tC1);
}
#else
if (sg_active) {
threadgroup float * temp_str = ((threadgroup float *) shmem) + 32*(sgitg&1) + (16*(sgitg >> 1))*NR0;
@@ -858,7 +629,6 @@ kernel void kernel_mul_mm_id(
simdgroup_store(mc[i], temp_str + 8*(i%4) + 8*NR0*(i/4), NR0, 0, false);
}
}
#endif
threadgroup_barrier(mem_flags::mem_threadgroup);
@@ -886,133 +656,258 @@ kernel void kernel_mul_mm_id(
}
}
//
// matrix-matrix multiplication
//
typedef decltype(kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, float4x4, 1, dequantize_f32, float, float4x4, float, float2x4>) mul_mm_t;
typedef decltype(kernel_mul_mm<half, half, float4x4, 1, dequantize_f32, float, float>) mul_mm_t;
template [[host_name("kernel_mul_mm_f32_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, float4x4, 1, dequantize_f32, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_f16_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, half4x4, 1, dequantize_f16, half, half4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_f32_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, float4x4, 1, dequantize_f32, float, float>;
template [[host_name("kernel_mul_mm_f16_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, half4x4, 1, dequantize_f16, half, float>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mm_bf16_f32")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat4x4, simdgroup_bfloat8x8, bfloat, bfloat2x4, simdgroup_bfloat8x8, bfloat4x4, 1, dequantize_bf16, bfloat, bfloat4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_bf16_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat4x4, simdgroup_bfloat8x8, bfloat, bfloat2x4, simdgroup_bfloat8x8, bfloat4x4, 1, dequantize_bf16, bfloat, bfloat4x4, bfloat, bfloat2x4>;
template [[host_name("kernel_mul_mm_f32_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, float4x4, 1, dequantize_f32, float, float>;
#endif
template [[host_name("kernel_mul_mm_q1_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q1_0, 8, dequantize_q1_0, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_q2_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q2_0, 4, dequantize_q2_0, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_q4_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_0, 2, dequantize_q4_0, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_q4_1_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_1, 2, dequantize_q4_1, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_q5_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_0, 2, dequantize_q5_0, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_q5_1_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_1, 2, dequantize_q5_1, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_q8_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q8_0, 2, dequantize_q8_0, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_mxfp4_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_mxfp4, 2, dequantize_mxfp4, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_q2_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q2_K, QK_NL, dequantize_q2_K, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_q3_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q3_K, QK_NL, dequantize_q3_K, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_q4_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_K, QK_NL, dequantize_q4_K, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_q5_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_K, QK_NL, dequantize_q5_K, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_q6_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q6_K, QK_NL, dequantize_q6_K, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_iq2_xxs_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_iq2_xs_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_iq3_xxs_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_iq3_s_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq3_s, QK_NL, dequantize_iq3_s, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_iq2_s_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_s, QK_NL, dequantize_iq2_s, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_iq1_s_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq1_s, QK_NL, dequantize_iq1_s, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_iq1_m_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq1_m, QK_NL, dequantize_iq1_m, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_iq4_nl_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq4_nl, 2, dequantize_iq4_nl, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_iq4_xs_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_tq2_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_tq2_0, QK_NL, dequantize_tq2_0, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_f32_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, float4x4, 1, dequantize_f32, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_f16_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, half4x4, 1, dequantize_f16, half, half4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_q1_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q1_0, 8, dequantize_q1_0, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_q2_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q2_0, 4, dequantize_q2_0, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_q4_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_0, 2, dequantize_q4_0, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_q4_1_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_1, 2, dequantize_q4_1, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_q5_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_0, 2, dequantize_q5_0, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_q5_1_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_1, 2, dequantize_q5_1, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_q8_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q8_0, 2, dequantize_q8_0, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_mxfp4_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_mxfp4, 2, dequantize_mxfp4, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_q2_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q2_K, QK_NL, dequantize_q2_K, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_q3_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q3_K, QK_NL, dequantize_q3_K, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_q4_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_K, QK_NL, dequantize_q4_K, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_q5_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_K, QK_NL, dequantize_q5_K, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_q6_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q6_K, QK_NL, dequantize_q6_K, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_iq2_xxs_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_iq2_xs_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_iq3_xxs_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_iq3_s_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq3_s, QK_NL, dequantize_iq3_s, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_iq2_s_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_s, QK_NL, dequantize_iq2_s, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_iq1_s_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq1_s, QK_NL, dequantize_iq1_s, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_iq1_m_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq1_m, QK_NL, dequantize_iq1_m, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_iq4_nl_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq4_nl, 2, dequantize_iq4_nl, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_iq4_xs_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_tq2_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_tq2_0, QK_NL, dequantize_tq2_0, float, float4x4, half, half2x4>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mm_f16_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, half4x4, 1, dequantize_f16, half, float>;
template [[host_name("kernel_mul_mm_q1_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q1_0, 8, dequantize_q1_0, float, float>;
template [[host_name("kernel_mul_mm_q2_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q2_0, 4, dequantize_q2_0, float, float>;
template [[host_name("kernel_mul_mm_q4_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q4_0, 2, dequantize_q4_0, float, float>;
template [[host_name("kernel_mul_mm_q4_1_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q4_1, 2, dequantize_q4_1, float, float>;
template [[host_name("kernel_mul_mm_q5_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q5_0, 2, dequantize_q5_0, float, float>;
template [[host_name("kernel_mul_mm_q5_1_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q5_1, 2, dequantize_q5_1, float, float>;
template [[host_name("kernel_mul_mm_q8_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q8_0, 2, dequantize_q8_0, float, float>;
template [[host_name("kernel_mul_mm_mxfp4_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_mxfp4, 2, dequantize_mxfp4, float, float>;
template [[host_name("kernel_mul_mm_nvfp4_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_nvfp4, 4, dequantize_nvfp4, float, float>;
template [[host_name("kernel_mul_mm_q2_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
template [[host_name("kernel_mul_mm_q3_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
template [[host_name("kernel_mul_mm_q4_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
template [[host_name("kernel_mul_mm_q5_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
template [[host_name("kernel_mul_mm_q6_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
template [[host_name("kernel_mul_mm_iq2_xxs_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
template [[host_name("kernel_mul_mm_iq2_xs_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
template [[host_name("kernel_mul_mm_iq3_xxs_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
template [[host_name("kernel_mul_mm_iq3_s_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
template [[host_name("kernel_mul_mm_iq2_s_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
template [[host_name("kernel_mul_mm_iq1_s_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
template [[host_name("kernel_mul_mm_iq1_m_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
template [[host_name("kernel_mul_mm_iq4_nl_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
template [[host_name("kernel_mul_mm_iq4_xs_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
template [[host_name("kernel_mul_mm_tq2_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
#endif
template [[host_name("kernel_mul_mm_f32_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, float4x4, 1, dequantize_f32, float, float>;
template [[host_name("kernel_mul_mm_f16_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, half4x4, 1, dequantize_f16, half, float>;
template [[host_name("kernel_mul_mm_q1_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q1_0, 8, dequantize_q1_0, float, float>;
template [[host_name("kernel_mul_mm_q2_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q2_0, 4, dequantize_q2_0, float, float>;
template [[host_name("kernel_mul_mm_q4_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q4_0, 2, dequantize_q4_0, float, float>;
template [[host_name("kernel_mul_mm_q4_1_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q4_1, 2, dequantize_q4_1, float, float>;
template [[host_name("kernel_mul_mm_q5_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q5_0, 2, dequantize_q5_0, float, float>;
template [[host_name("kernel_mul_mm_q5_1_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q5_1, 2, dequantize_q5_1, float, float>;
template [[host_name("kernel_mul_mm_q8_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q8_0, 2, dequantize_q8_0, float, float>;
template [[host_name("kernel_mul_mm_mxfp4_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_mxfp4, 2, dequantize_mxfp4, float, float>;
template [[host_name("kernel_mul_mm_nvfp4_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_nvfp4, 4, dequantize_nvfp4, float, float>;
template [[host_name("kernel_mul_mm_q2_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
template [[host_name("kernel_mul_mm_q3_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
template [[host_name("kernel_mul_mm_q4_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
template [[host_name("kernel_mul_mm_q5_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
template [[host_name("kernel_mul_mm_q6_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
template [[host_name("kernel_mul_mm_iq2_xxs_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
template [[host_name("kernel_mul_mm_iq2_xs_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
template [[host_name("kernel_mul_mm_iq3_xxs_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
template [[host_name("kernel_mul_mm_iq3_s_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
template [[host_name("kernel_mul_mm_iq2_s_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
template [[host_name("kernel_mul_mm_iq1_s_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
template [[host_name("kernel_mul_mm_iq1_m_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
template [[host_name("kernel_mul_mm_iq4_nl_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
template [[host_name("kernel_mul_mm_iq4_xs_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
template [[host_name("kernel_mul_mm_tq2_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mm_bf16_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, bfloat4x4, 1, dequantize_bf16, bfloat, float>;
template [[host_name("kernel_mul_mm_bf16_f32")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, bfloat4x4, 1, dequantize_bf16, bfloat, float>;
template [[host_name("kernel_mul_mm_bf16_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, bfloat4x4, 1, dequantize_bf16, bfloat, bfloat>;
#endif
template [[host_name("kernel_mul_mm_q1_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q1_0, 8, dequantize_q1_0, float, float>;
template [[host_name("kernel_mul_mm_q2_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q2_0, 4, dequantize_q2_0, float, float>;
template [[host_name("kernel_mul_mm_q4_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q4_0, 2, dequantize_q4_0, float, float>;
template [[host_name("kernel_mul_mm_q4_1_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q4_1, 2, dequantize_q4_1, float, float>;
template [[host_name("kernel_mul_mm_q5_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q5_0, 2, dequantize_q5_0, float, float>;
template [[host_name("kernel_mul_mm_q5_1_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q5_1, 2, dequantize_q5_1, float, float>;
template [[host_name("kernel_mul_mm_q8_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q8_0, 2, dequantize_q8_0, float, float>;
template [[host_name("kernel_mul_mm_mxfp4_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_mxfp4, 2, dequantize_mxfp4, float, float>;
template [[host_name("kernel_mul_mm_nvfp4_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_nvfp4, 4, dequantize_nvfp4, float, float>;
template [[host_name("kernel_mul_mm_q2_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
template [[host_name("kernel_mul_mm_q3_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
template [[host_name("kernel_mul_mm_q4_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
template [[host_name("kernel_mul_mm_q5_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
template [[host_name("kernel_mul_mm_q6_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
template [[host_name("kernel_mul_mm_iq2_xxs_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
template [[host_name("kernel_mul_mm_iq2_xs_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
template [[host_name("kernel_mul_mm_iq3_xxs_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
template [[host_name("kernel_mul_mm_iq3_s_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
template [[host_name("kernel_mul_mm_iq2_s_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
template [[host_name("kernel_mul_mm_iq1_s_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
template [[host_name("kernel_mul_mm_iq1_m_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
template [[host_name("kernel_mul_mm_iq4_nl_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
template [[host_name("kernel_mul_mm_iq4_xs_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
template [[host_name("kernel_mul_mm_tq2_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
template [[host_name("kernel_mul_mm_f32_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, float4x4, 1, dequantize_f32, float, half>;
template [[host_name("kernel_mul_mm_f16_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, half4x4, 1, dequantize_f16, half, half>;
template [[host_name("kernel_mul_mm_q1_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q1_0, 8, dequantize_q1_0, float, half>;
template [[host_name("kernel_mul_mm_q2_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q2_0, 4, dequantize_q2_0, float, half>;
template [[host_name("kernel_mul_mm_q4_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q4_0, 2, dequantize_q4_0, float, half>;
template [[host_name("kernel_mul_mm_q4_1_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q4_1, 2, dequantize_q4_1, float, half>;
template [[host_name("kernel_mul_mm_q5_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q5_0, 2, dequantize_q5_0, float, half>;
template [[host_name("kernel_mul_mm_q5_1_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q5_1, 2, dequantize_q5_1, float, half>;
template [[host_name("kernel_mul_mm_q8_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q8_0, 2, dequantize_q8_0, float, half>;
template [[host_name("kernel_mul_mm_mxfp4_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_mxfp4, 2, dequantize_mxfp4, float, half>;
template [[host_name("kernel_mul_mm_nvfp4_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_nvfp4, 4, dequantize_nvfp4, float, half>;
template [[host_name("kernel_mul_mm_q2_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q2_K, QK_NL, dequantize_q2_K, float, half>;
template [[host_name("kernel_mul_mm_q3_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q3_K, QK_NL, dequantize_q3_K, float, half>;
template [[host_name("kernel_mul_mm_q4_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q4_K, QK_NL, dequantize_q4_K, float, half>;
template [[host_name("kernel_mul_mm_q5_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q5_K, QK_NL, dequantize_q5_K, float, half>;
template [[host_name("kernel_mul_mm_q6_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q6_K, QK_NL, dequantize_q6_K, float, half>;
template [[host_name("kernel_mul_mm_iq2_xxs_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, half>;
template [[host_name("kernel_mul_mm_iq2_xs_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, half>;
template [[host_name("kernel_mul_mm_iq3_xxs_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, half>;
template [[host_name("kernel_mul_mm_iq3_s_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq3_s, QK_NL, dequantize_iq3_s, float, half>;
template [[host_name("kernel_mul_mm_iq2_s_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq2_s, QK_NL, dequantize_iq2_s, float, half>;
template [[host_name("kernel_mul_mm_iq1_s_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq1_s, QK_NL, dequantize_iq1_s, float, half>;
template [[host_name("kernel_mul_mm_iq1_m_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq1_m, QK_NL, dequantize_iq1_m, float, half>;
template [[host_name("kernel_mul_mm_iq4_nl_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq4_nl, 2, dequantize_iq4_nl, float, half>;
template [[host_name("kernel_mul_mm_iq4_xs_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, half>;
template [[host_name("kernel_mul_mm_tq2_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_tq2_0, QK_NL, dequantize_tq2_0, float, half>;
//
// indirect matrix-matrix multiplication
//
typedef decltype(kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, float4x4, 1, dequantize_f32, float, float4x4, float, float2x4>) mul_mm_id;
typedef decltype(kernel_mul_mm_id<half, half, float4x4, 1, dequantize_f32, float, float>) mul_mm_id;
template [[host_name("kernel_mul_mm_id_f32_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, float4x4, 1, dequantize_f32, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_f16_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, half4x4, 1, dequantize_f16, half, half4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_f32_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, float4x4, 1, dequantize_f32, float, float>;
template [[host_name("kernel_mul_mm_id_f16_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, half4x4, 1, dequantize_f16, half, float>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mm_id_bf16_f32")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat4x4, simdgroup_bfloat8x8, bfloat, bfloat2x4, simdgroup_bfloat8x8, bfloat4x4, 1, dequantize_bf16, bfloat, bfloat4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_bf16_f32")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, bfloat4x4, 1, dequantize_bf16, bfloat, float>;
#endif
template [[host_name("kernel_mul_mm_id_q1_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q1_0, 8, dequantize_q1_0, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_q2_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q2_0, 4, dequantize_q2_0, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_q4_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_0, 2, dequantize_q4_0, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_q4_1_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_1, 2, dequantize_q4_1, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_q5_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_0, 2, dequantize_q5_0, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_q5_1_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_1, 2, dequantize_q5_1, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_q8_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q8_0, 2, dequantize_q8_0, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_q1_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q1_0, 8, dequantize_q1_0, float, float>;
template [[host_name("kernel_mul_mm_id_q2_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q2_0, 4, dequantize_q2_0, float, float>;
template [[host_name("kernel_mul_mm_id_q4_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q4_0, 2, dequantize_q4_0, float, float>;
template [[host_name("kernel_mul_mm_id_q4_1_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q4_1, 2, dequantize_q4_1, float, float>;
template [[host_name("kernel_mul_mm_id_q5_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q5_0, 2, dequantize_q5_0, float, float>;
template [[host_name("kernel_mul_mm_id_q5_1_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q5_1, 2, dequantize_q5_1, float, float>;
template [[host_name("kernel_mul_mm_id_q8_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q8_0, 2, dequantize_q8_0, float, float>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat4x4, simdgroup_bfloat8x8, bfloat, bfloat2x4, simdgroup_bfloat8x8, block_mxfp4, 2, dequantize_mxfp4, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_mxfp4, 2, dequantize_mxfp4, float, float>;
template [[host_name("kernel_mul_mm_id_nvfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_nvfp4, 4, dequantize_nvfp4, float, float>;
#else
template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_mxfp4, 2, dequantize_mxfp4, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_mxfp4, 2, dequantize_mxfp4, float, float>;
template [[host_name("kernel_mul_mm_id_nvfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_nvfp4, 4, dequantize_nvfp4, float, float>;
#endif
template [[host_name("kernel_mul_mm_id_q2_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q2_K, QK_NL, dequantize_q2_K, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_q3_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q3_K, QK_NL, dequantize_q3_K, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_q4_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_K, QK_NL, dequantize_q4_K, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_q5_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_K, QK_NL, dequantize_q5_K, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_q6_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q6_K, QK_NL, dequantize_q6_K, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_iq2_xxs_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_iq2_xs_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_iq3_xxs_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_iq3_s_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq3_s, QK_NL, dequantize_iq3_s, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_iq2_s_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_s, QK_NL, dequantize_iq2_s, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_iq1_s_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq1_s, QK_NL, dequantize_iq1_s, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_iq1_m_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq1_m, QK_NL, dequantize_iq1_m, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_iq4_nl_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq4_nl, 2, dequantize_iq4_nl, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_iq4_xs_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_tq2_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_tq2_0, QK_NL, dequantize_tq2_0, float, float4x4, float, float2x4>;
template [[host_name("kernel_mul_mm_id_q2_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
template [[host_name("kernel_mul_mm_id_q3_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
template [[host_name("kernel_mul_mm_id_q4_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
template [[host_name("kernel_mul_mm_id_q5_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
template [[host_name("kernel_mul_mm_id_q6_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
template [[host_name("kernel_mul_mm_id_iq2_xxs_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
template [[host_name("kernel_mul_mm_id_iq2_xs_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
template [[host_name("kernel_mul_mm_id_iq3_xxs_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
template [[host_name("kernel_mul_mm_id_iq3_s_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
template [[host_name("kernel_mul_mm_id_iq2_s_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
template [[host_name("kernel_mul_mm_id_iq1_s_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
template [[host_name("kernel_mul_mm_id_iq1_m_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
template [[host_name("kernel_mul_mm_id_iq4_nl_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
template [[host_name("kernel_mul_mm_id_iq4_xs_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
template [[host_name("kernel_mul_mm_id_tq2_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
template [[host_name("kernel_mul_mm_id_f32_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, float4x4, 1, dequantize_f32, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_f16_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, half4x4, 1, dequantize_f16, half, half4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_q1_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q1_0, 8, dequantize_q1_0, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_q2_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q2_0, 4, dequantize_q2_0, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_q4_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_0, 2, dequantize_q4_0, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_q4_1_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_1, 2, dequantize_q4_1, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_q5_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_0, 2, dequantize_q5_0, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_q5_1_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_1, 2, dequantize_q5_1, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_q8_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q8_0, 2, dequantize_q8_0, float, float4x4, half, half2x4>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat4x4, simdgroup_bfloat8x8, bfloat, bfloat2x4, simdgroup_bfloat8x8, block_mxfp4, 2, dequantize_mxfp4, float, float4x4, half, half2x4>;
#else
template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_mxfp4, 2, dequantize_mxfp4, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_f32_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, float4x4, 1, dequantize_f32, float, float>;
#endif
template [[host_name("kernel_mul_mm_id_q2_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q2_K, QK_NL, dequantize_q2_K, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_q3_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q3_K, QK_NL, dequantize_q3_K, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_q4_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_K, QK_NL, dequantize_q4_K, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_q5_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_K, QK_NL, dequantize_q5_K, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_q6_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q6_K, QK_NL, dequantize_q6_K, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_iq2_xxs_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_iq2_xs_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_iq3_xxs_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_iq3_s_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq3_s, QK_NL, dequantize_iq3_s, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_iq2_s_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_s, QK_NL, dequantize_iq2_s, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_iq1_s_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq1_s, QK_NL, dequantize_iq1_s, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_iq1_m_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq1_m, QK_NL, dequantize_iq1_m, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_iq4_nl_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq4_nl, 2, dequantize_iq4_nl, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_iq4_xs_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float4x4, half, half2x4>;
template [[host_name("kernel_mul_mm_id_tq2_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_tq2_0, QK_NL, dequantize_tq2_0, float, float4x4, half, half2x4>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mm_id_f16_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, half4x4, 1, dequantize_f16, half, float>;
template [[host_name("kernel_mul_mm_id_q1_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q1_0, 8, dequantize_q1_0, float, float>;
template [[host_name("kernel_mul_mm_id_q2_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q2_0, 4, dequantize_q2_0, float, float>;
template [[host_name("kernel_mul_mm_id_q4_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q4_0, 2, dequantize_q4_0, float, float>;
template [[host_name("kernel_mul_mm_id_q4_1_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q4_1, 2, dequantize_q4_1, float, float>;
template [[host_name("kernel_mul_mm_id_q5_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q5_0, 2, dequantize_q5_0, float, float>;
template [[host_name("kernel_mul_mm_id_q5_1_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q5_1, 2, dequantize_q5_1, float, float>;
template [[host_name("kernel_mul_mm_id_q8_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q8_0, 2, dequantize_q8_0, float, float>;
template [[host_name("kernel_mul_mm_id_q2_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
template [[host_name("kernel_mul_mm_id_q3_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
template [[host_name("kernel_mul_mm_id_q4_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
template [[host_name("kernel_mul_mm_id_q5_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
template [[host_name("kernel_mul_mm_id_q6_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
template [[host_name("kernel_mul_mm_id_iq2_xxs_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
template [[host_name("kernel_mul_mm_id_iq2_xs_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
template [[host_name("kernel_mul_mm_id_iq3_xxs_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
template [[host_name("kernel_mul_mm_id_iq3_s_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
template [[host_name("kernel_mul_mm_id_iq2_s_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
template [[host_name("kernel_mul_mm_id_iq1_s_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
template [[host_name("kernel_mul_mm_id_iq1_m_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
template [[host_name("kernel_mul_mm_id_iq4_nl_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
template [[host_name("kernel_mul_mm_id_iq4_xs_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
template [[host_name("kernel_mul_mm_id_tq2_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
#endif
template [[host_name("kernel_mul_mm_id_f32_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, float4x4, 1, dequantize_f32, float, float>;
template [[host_name("kernel_mul_mm_id_f16_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, half4x4, 1, dequantize_f16, half, float>;
template [[host_name("kernel_mul_mm_id_q1_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q1_0, 8, dequantize_q1_0, float, float>;
template [[host_name("kernel_mul_mm_id_q2_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q2_0, 4, dequantize_q2_0, float, float>;
template [[host_name("kernel_mul_mm_id_q4_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q4_0, 2, dequantize_q4_0, float, float>;
template [[host_name("kernel_mul_mm_id_q4_1_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q4_1, 2, dequantize_q4_1, float, float>;
template [[host_name("kernel_mul_mm_id_q5_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q5_0, 2, dequantize_q5_0, float, float>;
template [[host_name("kernel_mul_mm_id_q5_1_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q5_1, 2, dequantize_q5_1, float, float>;
template [[host_name("kernel_mul_mm_id_q8_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q8_0, 2, dequantize_q8_0, float, float>;
template [[host_name("kernel_mul_mm_id_mxfp4_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_mxfp4, 2, dequantize_mxfp4, float, float>;
template [[host_name("kernel_mul_mm_id_nvfp4_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_nvfp4, 4, dequantize_nvfp4, float, float>;
template [[host_name("kernel_mul_mm_id_q2_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
template [[host_name("kernel_mul_mm_id_q3_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
template [[host_name("kernel_mul_mm_id_q4_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
template [[host_name("kernel_mul_mm_id_q5_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
template [[host_name("kernel_mul_mm_id_q6_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
template [[host_name("kernel_mul_mm_id_iq2_xxs_f32_prec_f32")]]kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
template [[host_name("kernel_mul_mm_id_iq2_xs_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
template [[host_name("kernel_mul_mm_id_iq3_xxs_f32_prec_f32")]]kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
template [[host_name("kernel_mul_mm_id_iq3_s_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
template [[host_name("kernel_mul_mm_id_iq2_s_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
template [[host_name("kernel_mul_mm_id_iq1_s_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
template [[host_name("kernel_mul_mm_id_iq1_m_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
template [[host_name("kernel_mul_mm_id_iq4_nl_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
template [[host_name("kernel_mul_mm_id_iq4_xs_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
template [[host_name("kernel_mul_mm_id_tq2_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mm_id_bf16_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, bfloat4x4, 1, dequantize_bf16, bfloat, float>;
#endif
template [[host_name("kernel_mul_mm_id_f32_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, float4x4, 1, dequantize_f32, float, half>;
template [[host_name("kernel_mul_mm_id_f16_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, half4x4, 1, dequantize_f16, half, half>;
template [[host_name("kernel_mul_mm_id_q1_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q1_0, 8, dequantize_q1_0, float, half>;
template [[host_name("kernel_mul_mm_id_q2_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q2_0, 4, dequantize_q2_0, float, half>;
template [[host_name("kernel_mul_mm_id_q4_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q4_0, 2, dequantize_q4_0, float, half>;
template [[host_name("kernel_mul_mm_id_q4_1_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q4_1, 2, dequantize_q4_1, float, half>;
template [[host_name("kernel_mul_mm_id_q5_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q5_0, 2, dequantize_q5_0, float, half>;
template [[host_name("kernel_mul_mm_id_q5_1_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q5_1, 2, dequantize_q5_1, float, half>;
template [[host_name("kernel_mul_mm_id_q8_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q8_0, 2, dequantize_q8_0, float, half>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_mxfp4, 2, dequantize_mxfp4, float, half>;
template [[host_name("kernel_mul_mm_id_nvfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_nvfp4, 4, dequantize_nvfp4, float, half>;
#else
template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_mxfp4, 2, dequantize_mxfp4, float, half>;
template [[host_name("kernel_mul_mm_id_nvfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_nvfp4, 4, dequantize_nvfp4, float, half>;
#endif
template [[host_name("kernel_mul_mm_id_q2_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q2_K, QK_NL, dequantize_q2_K, float, half>;
template [[host_name("kernel_mul_mm_id_q3_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q3_K, QK_NL, dequantize_q3_K, float, half>;
template [[host_name("kernel_mul_mm_id_q4_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q4_K, QK_NL, dequantize_q4_K, float, half>;
template [[host_name("kernel_mul_mm_id_q5_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q5_K, QK_NL, dequantize_q5_K, float, half>;
template [[host_name("kernel_mul_mm_id_q6_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q6_K, QK_NL, dequantize_q6_K, float, half>;
template [[host_name("kernel_mul_mm_id_iq2_xxs_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, half>;
template [[host_name("kernel_mul_mm_id_iq2_xs_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, half>;
template [[host_name("kernel_mul_mm_id_iq3_xxs_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, half>;
template [[host_name("kernel_mul_mm_id_iq3_s_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq3_s, QK_NL, dequantize_iq3_s, float, half>;
template [[host_name("kernel_mul_mm_id_iq2_s_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq2_s, QK_NL, dequantize_iq2_s, float, half>;
template [[host_name("kernel_mul_mm_id_iq1_s_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq1_s, QK_NL, dequantize_iq1_s, float, half>;
template [[host_name("kernel_mul_mm_id_iq1_m_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq1_m, QK_NL, dequantize_iq1_m, float, half>;
template [[host_name("kernel_mul_mm_id_iq4_nl_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq4_nl, 2, dequantize_iq4_nl, float, half>;
template [[host_name("kernel_mul_mm_id_iq4_xs_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, half>;
template [[host_name("kernel_mul_mm_id_tq2_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_tq2_0, QK_NL, dequantize_tq2_0, float, half>;
@@ -0,0 +1,543 @@
#include "common.h"
#include "dequantize.h"
#ifdef GGML_METAL_HAS_TENSOR
constant bool FC_mul_mm_bc_inp [[function_constant(FC_MUL_MM + 0)]];
constant bool FC_mul_mm_bc_out [[function_constant(FC_MUL_MM + 1)]];
constant short FC_mul_mm_ne12 [[function_constant(FC_MUL_MM + 2)]];
constant short FC_mul_mm_ne13 [[function_constant(FC_MUL_MM + 3)]];
constant short FC_mul_mm_r2 [[function_constant(FC_MUL_MM + 4)]];
constant short FC_mul_mm_r3 [[function_constant(FC_MUL_MM + 5)]];
constant int32_t FC_mul_mm_id_map0_ne02 [[function_constant(FC_MUL_MM + 7)]];
// each block_q contains 16*nl weights
template<
typename SA, typename SB,
typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread typename value_type_4x4<SA>::type &),
typename T0, typename T1>
kernel void kernel_mul_mm_tensor(
constant ggml_metal_kargs_mul_mm & args,
device const char * srcA,
device const char * srcB,
device char * dst,
threadgroup char * shmem [[threadgroup(0)]],
uint3 tgpig [[threadgroup_position_in_grid]],
ushort tiitg [[thread_index_in_threadgroup]],
ushort sgitg [[simdgroup_index_in_threadgroup]]) {
using SA_4x4 = typename value_type_4x4<SA>::type;
using SA_8x8 = typename value_type_8x8<SA>::type;
using SB_2x4 = typename value_type_2x4<SB>::type;
using SB_8x8 = typename value_type_8x8<SB>::type;
using T0_4x4 = typename value_type_4x4<T0>::type;
using T1_2x4 = typename value_type_2x4<T1>::type;
(void) sgitg;
// Matrix dimensions: A(M,K) x B(K,N) -> C(M,N)
const int K = args.ne00;
const int M = args.ne0;
const int N = args.ne1;
// Batch dimension handling
const int im = tgpig.z;
const int i12 = im % FC_mul_mm_ne12;
const int i13 = im / FC_mul_mm_ne12;
// Batch offsets for srcA and srcB
const uint64_t offset0 = (i12/FC_mul_mm_r2)*args.nb02 + (i13/FC_mul_mm_r3)*args.nb03;
// Tile dimensions
constexpr int NRB = SZ_SIMDGROUP * N_MM_BLOCK_X * N_MM_SIMD_GROUP_X;
constexpr int NRA = SZ_SIMDGROUP * N_MM_BLOCK_Y * N_MM_SIMD_GROUP_Y;
// Tile offsets in output matrix
const int ra = tgpig.y * NRA;
const int rb = tgpig.x * NRB;
// Threadgroup memory for dequantized A tile only
threadgroup SA * sa = (threadgroup SA *)(shmem);
// Work-item count for A loading
constexpr int A_WORK_ITEMS = NRA * N_MM_NK;
constexpr int NUM_THREADS = N_SIMDWIDTH * N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y;
// tA wraps threadgroup memory
auto tA = tensor(sa, dextents<int32_t, 2>(N_MM_NK_TOTAL, NRA));
// tB wraps device memory directly
device T1 * ptrB = (device T1 *)(srcB + args.nb12*i12 + args.nb13*i13);
const int strideB = args.nb11 / sizeof(T1);
auto tB = tensor(ptrB, dextents<int32_t, 2>(K, N), array<int, 2>({1, strideB}));
// Configure matmul operation
// note: K is dynamic_extent (clamped to the valid range in PHASE 2), since a static
// N_MM_NK_TOTAL K tile would read src1 out of bounds when K % N_MM_NK_TOTAL != 0
// ref: https://github.com/ggml-org/llama.cpp/pull/27064
mpp::tensor_ops::matmul2d<
mpp::tensor_ops::matmul2d_descriptor(
NRB, NRA, static_cast<int>(dynamic_extent), false, true, true,
mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroups<N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y>> mm;
auto cT = mm.get_destination_cooperative_tensor<decltype(tB), decltype(tA), float>();
// Accumulate partial results over K dimension
for (int loop_k = 0; loop_k < K; loop_k += N_MM_NK_TOTAL) {
// === PHASE 1: Dequantization of A into threadgroup memory ===
for (int work = tiitg; work < A_WORK_ITEMS; work += NUM_THREADS) {
const int row = work / N_MM_NK;
const int k_chunk = work % N_MM_NK;
const int k_pos = loop_k + k_chunk * 16;
const short k_base = k_chunk * 16;
// Bounds check: skip device read if row is out of matrix bounds
if (ra + row < M) {
if (is_same<T0_4x4, block_q>::value && FC_mul_mm_bc_inp) {
// Element-wise reads when K is not aligned (nb01 not aligned for half4x4/float4x4).
// MSL spec Table 2.5: half4x4 requires 8-byte alignment. When K is odd,
// nb01 = K*2 is not 8-byte aligned, so odd-row pointers are misaligned.
// Mirrors the legacy kernel's existing guard.
device const T0 * row_ptr = (device const T0 *)(srcA + args.nb01 * (ra + row) + offset0);
FOR_UNROLL (short i = 0; i < 16; i++) {
sa[row * N_MM_NK_TOTAL + (k_base + i)] = (k_pos + i < K) ? (SA) row_ptr[k_pos + i] : (SA)0;
}
} else {
const int block_idx = k_pos / (16 * nl);
const short il = (k_pos / 16) % nl;
device const block_q * row_ptr = (device const block_q *)(srcA + args.nb01 * (ra + row) + offset0);
SA_4x4 temp_a;
dequantize_func(row_ptr + block_idx, il, temp_a);
FOR_UNROLL (short i = 0; i < 16; i++) {
// Zero-pad A for K positions beyond valid range (handles partial K iterations)
sa[row * N_MM_NK_TOTAL + (k_base + i)] = (k_pos + i < K) ? temp_a[i/4][i%4] : (SA)0;
}
}
} else {
// Zero-pad rows beyond matrix bounds
FOR_UNROLL (short i = 0; i < 16; i++) {
sa[row * N_MM_NK_TOTAL + (k_base + i)] = (SA)0;
}
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
// === PHASE 2: Tensor matmul ===
// Clamp the K extent of both operand tensors to the remaining valid K range so
// the dynamic-K op never reads past the K extent of src1 (or the staged A tile).
const int kExt = min(N_MM_NK_TOTAL, K - loop_k);
auto tAv = tensor(sa, dextents<int32_t, 2>(kExt, NRA), array<int, 2>({1, N_MM_NK_TOTAL}));
auto tBv = tensor(ptrB + loop_k + rb * strideB, dextents<int32_t, 2>(kExt, N - rb), array<int, 2>({1, strideB}));
mm.run(tBv, tAv, cT);
threadgroup_barrier(mem_flags::mem_threadgroup);
}
// Store result tile to output matrix (with batch offset)
// a slice is not used because its byte offset is int32 and wraps at 2 GiB
// ref: https://github.com/ggml-org/llama.cpp/pull/28748
const int tileM = min(NRA, M - ra);
const int tileN = min(NRB, N - rb);
device float * dstTile = (device float *)dst + (uint64_t) im * N * M + (uint64_t) rb * M + ra;
auto tD = tensor(dstTile, dextents<int32_t, 2>(tileM, tileN), array<int, 2>({1, M}));
cT.store(tD);
}
template<typename S0, typename S1, typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread typename value_type_4x4<S0>::type &), typename T0, typename T1>
kernel void kernel_mul_mm_id_tensor(
constant ggml_metal_kargs_mul_mm_id & args,
device const char * src0,
device const char * src1,
device const char * htpe,
device const char * hids,
device char * dst,
threadgroup char * shmem [[threadgroup(0)]],
uint3 tgpig[[threadgroup_position_in_grid]],
ushort tiitg[[thread_index_in_threadgroup]],
ushort tiisg[[thread_index_in_simdgroup]],
ushort sgitg[[simdgroup_index_in_threadgroup]]) {
using S0_4x4 = typename value_type_4x4<S0>::type;
using S0_8x8 = typename value_type_8x8<S0>::type;
using S1_2x4 = typename value_type_2x4<S1>::type;
using S1_8x8 = typename value_type_8x8<S1>::type;
using T0_4x4 = typename value_type_4x4<T0>::type;
using T1_2x4 = typename value_type_2x4<T1>::type;
constexpr int NR0 = 64;
constexpr int NR1 = 32;
constexpr int NK = 32;
constexpr int NL0 = NK/16;
constexpr int NL1 = NK/8;
threadgroup S0 * sa = (threadgroup S0 *)(shmem);
threadgroup S1 * sb = (threadgroup S1 *)(shmem + NR0*NK*sizeof(S0));
threadgroup float * sc = (threadgroup float *)(shmem);
const int tile = tgpig.x; // entry tile, described by the prepass
const int r0 = tgpig.y*NR0;
device const uint32_t * tpe_u32 = (device const uint32_t *) (htpe);
device const int32_t * ids_i32 = (device const int32_t *) (hids);
// the prepass emits one (expert, first entry, valid rows) descriptor per tile that has
// work - the grid is sized by a static upper bound, so the tail early exits
if (tile >= (int) tpe_u32[0]) {
return;
}
const int im = tpe_u32[1 + 3*tile]; // expert
const int idb = tpe_u32[1 + 3*tile + 1]; // first entry of this tile in hids
// number of entries in this tile, always <= NR1
const short nr1 = (short) ((tpe_u32[1 + 3*tile + 2] < NR1) ? tpe_u32[1 + 3*tile + 2] : NR1);
// if this block is of 64x32 shape or smaller
const short nr0 = (args.ne0 - r0 < NR0) ? (args.ne0 - r0) : NR0;
// a thread shouldn't load data outside of the matrix
const short lr0 = ((short)tiitg/NL0) < nr0 ? ((short)tiitg/NL0) : nr0 - 1; // 0 .. 63
const short il0 = (tiitg % NL0);
const short i13 = 0;
const uint64_t offset0 = im*args.nb02 + i13*args.nb03;
const short offset1 = il0/nl;
const short iy = 8*(tiitg % NL1);
// skip the upper half of the token tile when the expert did not fill it
constexpr short NR1H = NR1/2;
auto tA = tensor<threadgroup S0, dextents<int32_t, 2>, tensor_inline>(sa, dextents<int32_t, 2>(NK, NR0));
// sb is [NR1][NK] row-major
auto tB0 = tensor<threadgroup S1, dextents<int32_t, 2>, tensor_inline>(sb, dextents<int32_t, 2>(NK, NR1H));
auto tB1 = tensor<threadgroup S1, dextents<int32_t, 2>, tensor_inline>(sb + NR1H*NK, dextents<int32_t, 2>(NK, NR1H));
mpp::tensor_ops::matmul2d<
mpp::tensor_ops::matmul2d_descriptor(NR1H, NR0, NK, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroups<4>> mm;
const short lr1 = ((short)tiitg/NL1) < nr1 ? ((short)tiitg/NL1) : nr1 - 1; // 0 .. 31
short il = il0;
const int id = ids_i32[idb + lr1];
const short i11 = (id % args.ne20) % args.ne11;
const int i12 = (id / args.ne20);
device const block_q * x = (device const block_q *)(src0 + args.nb01*(r0 + lr0) + offset0) + offset1;
device const T1 * y = (device const T1 *)(src1
+ args.nb13*i13
+ args.nb12*i12
+ args.nb11*i11
+ args.nb10*iy);
const bool has_hi = nr1 > NR1H;
auto cT0 = mm.get_destination_cooperative_tensor<decltype(tB0), decltype(tA), float>();
auto cT1 = mm.get_destination_cooperative_tensor<decltype(tB1), decltype(tA), float>();
for (int loop_k = 0; loop_k < args.ne00; loop_k += NK) {
// load data and store to threadgroup memory
if (is_same<T0_4x4, block_q>::value && FC_mul_mm_bc_inp) {
threadgroup_barrier(mem_flags::mem_threadgroup);
// no need for dequantization
for (short i = 0; i < 16; i++) {
const short sx = 2*il0 + i/8;
const short sy = (tiitg/NL0)/8;
const short lx = i%8;
const short ly = (tiitg/NL0)%8;
//const short lx = (tiitg/NL0)%8;
//const short ly = i%8;
*(sa + NK*(8*sy + ly) + 8*sx + lx) = loop_k + 16*il + i < args.ne00 ? (S0) *((device T0 *) x + i) : 0;
}
} else {
S0_4x4 temp_a;
dequantize_func(x, il, temp_a);
threadgroup_barrier(mem_flags::mem_threadgroup);
FOR_UNROLL (short i = 0; i < 16; i++) {
const short sx = 2*il0 + i/8;
const short sy = (tiitg/NL0)/8;
const short lx = i%8;
const short ly = (tiitg/NL0)%8;
//const short lx = (tiitg/NL0)%8;
//const short ly = i%8;
*(sa + NK*(8*sy + ly) + 8*sx + lx) = temp_a[i/4][i%4];
}
}
if (FC_mul_mm_bc_inp) {
for (short i = 0; i < 8; ++i) {
const short sx = (tiitg%NL1);
const short sy = (tiitg/NL1)/8;
const short lx = i;
const short ly = (tiitg/NL1)%8;
//const short lx = (tiitg/NL1)%8;
//const short ly = i;
*(sb + NK*(8*sy + ly) + 8*sx + lx) = loop_k + iy + i < args.ne00 ? (S1) *((device T1 *) y + i) : 0;
}
} else {
const short sx = (tiitg%NL1);
const short sy = (tiitg/NL1)/8;
//const short lx = i;
const short ly = (tiitg/NL1)%8;
//const short lx = (tiitg/NL1)%8;
//const short ly = i;
*(threadgroup S1_2x4 *)(sb + NK*(8*sy + ly) + 8*sx) = (S1_2x4)(*((device T1_2x4 *) y));
}
il = (il + 2 < nl) ? il + 2 : il % 2;
x = (il < 2) ? x + (2 + nl - 1)/nl : x;
y += NK;
threadgroup_barrier(mem_flags::mem_threadgroup);
auto sA = tA.slice(0, 0);
auto sB0 = tB0.slice(0, 0);
mm.run(sB0, sA, cT0);
if (has_hi) {
auto sB1 = tB1.slice(0, 0);
mm.run(sB1, sA, cT1);
}
}
// block is smaller than 64x32, we should avoid writing data outside of the matrix
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tC0 = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sc, dextents<int32_t, 2>(NR0, NR1H));
cT0.store(tC0);
if (has_hi) {
auto tC1 = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sc + NR1H*NR0, dextents<int32_t, 2>(NR0, NR1H));
cT1.store(tC1);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
for (short j = sgitg; j < nr1; j += 4) {
const int id = ids_i32[idb + j];
const short ide = id % args.ne20;
const int idt = id / args.ne20;
device float * D = (device float *) dst + r0 + (uint64_t) ide*args.ne0 + (uint64_t) idt*args.ne1*args.ne0;
device float4 * D4 = (device float4 *) D;
threadgroup float * C = (threadgroup float *) shmem + j*NR0;
threadgroup float4 * C4 = (threadgroup float4 *) C;
int i = tiisg;
for (; i < nr0/4; i += 32) {
*(D4 + i) = *(C4 + i);
}
i = (4*(nr0/4)) + tiisg;
for (; i < nr0; i += 32) {
*(D + i) = *(C + i);
}
}
}
// matrix-matrix multiplication
//
typedef decltype(kernel_mul_mm_tensor<half, half, float4x4, 1, dequantize_f32, float, float>) mul_mm_tensor_t;
template [[host_name("kernel_mul_mm_tensor_f32_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, float4x4, 1, dequantize_f32, float, float>;
template [[host_name("kernel_mul_mm_tensor_f16_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, half4x4, 1, dequantize_f16, half, float>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mm_tensor_f32_f32_prec_bf16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<bfloat, bfloat, float4x4, 1, dequantize_f32, float, float>;
#endif
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mm_tensor_bf16_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<bfloat, bfloat, bfloat4x4, 1, dequantize_bf16, bfloat, float>;
template [[host_name("kernel_mul_mm_tensor_bf16_bf16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<bfloat, bfloat, bfloat4x4, 1, dequantize_bf16, bfloat, bfloat>;
#endif
template [[host_name("kernel_mul_mm_tensor_q1_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q1_0, 8, dequantize_q1_0, float, float>;
template [[host_name("kernel_mul_mm_tensor_q2_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q2_0, 4, dequantize_q2_0, float, float>;
template [[host_name("kernel_mul_mm_tensor_q4_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q4_0, 2, dequantize_q4_0, float, float>;
template [[host_name("kernel_mul_mm_tensor_q4_1_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q4_1, 2, dequantize_q4_1, float, float>;
template [[host_name("kernel_mul_mm_tensor_q5_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q5_0, 2, dequantize_q5_0, float, float>;
template [[host_name("kernel_mul_mm_tensor_q5_1_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q5_1, 2, dequantize_q5_1, float, float>;
template [[host_name("kernel_mul_mm_tensor_q8_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q8_0, 2, dequantize_q8_0, float, float>;
template [[host_name("kernel_mul_mm_tensor_mxfp4_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_mxfp4, 2, dequantize_mxfp4, float, float>;
template [[host_name("kernel_mul_mm_tensor_nvfp4_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_nvfp4, 4, dequantize_nvfp4, float, float>;
template [[host_name("kernel_mul_mm_tensor_q2_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
template [[host_name("kernel_mul_mm_tensor_q3_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
template [[host_name("kernel_mul_mm_tensor_q4_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
template [[host_name("kernel_mul_mm_tensor_q5_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
template [[host_name("kernel_mul_mm_tensor_q6_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
template [[host_name("kernel_mul_mm_tensor_iq2_xxs_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
template [[host_name("kernel_mul_mm_tensor_iq2_xs_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
template [[host_name("kernel_mul_mm_tensor_iq3_xxs_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
template [[host_name("kernel_mul_mm_tensor_iq3_s_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
template [[host_name("kernel_mul_mm_tensor_iq2_s_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
template [[host_name("kernel_mul_mm_tensor_iq1_s_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
template [[host_name("kernel_mul_mm_tensor_iq1_m_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
template [[host_name("kernel_mul_mm_tensor_iq4_nl_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
template [[host_name("kernel_mul_mm_tensor_iq4_xs_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
template [[host_name("kernel_mul_mm_tensor_tq2_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
template [[host_name("kernel_mul_mm_tensor_f32_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, float4x4, 1, dequantize_f32, float, half>;
template [[host_name("kernel_mul_mm_tensor_f16_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, half4x4, 1, dequantize_f16, half, half>;
template [[host_name("kernel_mul_mm_tensor_q1_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q1_0, 8, dequantize_q1_0, float, half>;
template [[host_name("kernel_mul_mm_tensor_q2_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q2_0, 4, dequantize_q2_0, float, half>;
template [[host_name("kernel_mul_mm_tensor_q4_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q4_0, 2, dequantize_q4_0, float, half>;
template [[host_name("kernel_mul_mm_tensor_q4_1_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q4_1, 2, dequantize_q4_1, float, half>;
template [[host_name("kernel_mul_mm_tensor_q5_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q5_0, 2, dequantize_q5_0, float, half>;
template [[host_name("kernel_mul_mm_tensor_q5_1_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q5_1, 2, dequantize_q5_1, float, half>;
template [[host_name("kernel_mul_mm_tensor_q8_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q8_0, 2, dequantize_q8_0, float, half>;
template [[host_name("kernel_mul_mm_tensor_mxfp4_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_mxfp4, 2, dequantize_mxfp4, float, half>;
template [[host_name("kernel_mul_mm_tensor_nvfp4_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_nvfp4, 4, dequantize_nvfp4, float, half>;
template [[host_name("kernel_mul_mm_tensor_q2_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q2_K, QK_NL, dequantize_q2_K, float, half>;
template [[host_name("kernel_mul_mm_tensor_q3_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q3_K, QK_NL, dequantize_q3_K, float, half>;
template [[host_name("kernel_mul_mm_tensor_q4_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q4_K, QK_NL, dequantize_q4_K, float, half>;
template [[host_name("kernel_mul_mm_tensor_q5_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q5_K, QK_NL, dequantize_q5_K, float, half>;
template [[host_name("kernel_mul_mm_tensor_q6_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q6_K, QK_NL, dequantize_q6_K, float, half>;
template [[host_name("kernel_mul_mm_tensor_iq2_xxs_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, half>;
template [[host_name("kernel_mul_mm_tensor_iq2_xs_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, half>;
template [[host_name("kernel_mul_mm_tensor_iq3_xxs_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, half>;
template [[host_name("kernel_mul_mm_tensor_iq3_s_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq3_s, QK_NL, dequantize_iq3_s, float, half>;
template [[host_name("kernel_mul_mm_tensor_iq2_s_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq2_s, QK_NL, dequantize_iq2_s, float, half>;
template [[host_name("kernel_mul_mm_tensor_iq1_s_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq1_s, QK_NL, dequantize_iq1_s, float, half>;
template [[host_name("kernel_mul_mm_tensor_iq1_m_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq1_m, QK_NL, dequantize_iq1_m, float, half>;
template [[host_name("kernel_mul_mm_tensor_iq4_nl_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq4_nl, 2, dequantize_iq4_nl, float, half>;
template [[host_name("kernel_mul_mm_tensor_iq4_xs_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, half>;
template [[host_name("kernel_mul_mm_tensor_tq2_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_tq2_0, QK_NL, dequantize_tq2_0, float, half>;
//
// indirect matrix-matrix multiplication
//
typedef decltype(kernel_mul_mm_id_tensor<half, half, float4x4, 1, dequantize_f32, float, float>) mul_mm_id_tensor_t;
template [[host_name("kernel_mul_mm_id_tensor_f32_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, float4x4, 1, dequantize_f32, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_f16_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, half4x4, 1, dequantize_f16, half, float>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mm_id_tensor_bf16_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<bfloat, bfloat, bfloat4x4, 1, dequantize_bf16, bfloat, float>;
#endif
template [[host_name("kernel_mul_mm_id_tensor_q1_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q1_0, 8, dequantize_q1_0, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q2_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q2_0, 4, dequantize_q2_0, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q4_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q4_0, 2, dequantize_q4_0, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q4_1_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q4_1, 2, dequantize_q4_1, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q5_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q5_0, 2, dequantize_q5_0, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q5_1_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q5_1, 2, dequantize_q5_1, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q8_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q8_0, 2, dequantize_q8_0, float, float>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<bfloat, bfloat, block_mxfp4, 2, dequantize_mxfp4, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_nvfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<bfloat, bfloat, block_nvfp4, 4, dequantize_nvfp4, float, float>;
#else
template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_mxfp4, 2, dequantize_mxfp4, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_nvfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_nvfp4, 4, dequantize_nvfp4, float, float>;
#endif
template [[host_name("kernel_mul_mm_id_tensor_q2_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q3_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q4_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q5_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q6_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq2_xxs_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq2_xs_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq3_xxs_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq3_s_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq2_s_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq1_s_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq1_m_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq4_nl_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq4_xs_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_tq2_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mm_id_tensor_f32_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<bfloat, bfloat, float4x4, 1, dequantize_f32, float, float>;
#endif
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mm_id_tensor_f16_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, half4x4, 1, dequantize_f16, half, float>;
template [[host_name("kernel_mul_mm_id_tensor_q1_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q1_0, 8, dequantize_q1_0, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q2_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q2_0, 4, dequantize_q2_0, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q4_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q4_0, 2, dequantize_q4_0, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q4_1_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q4_1, 2, dequantize_q4_1, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q5_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q5_0, 2, dequantize_q5_0, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q5_1_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q5_1, 2, dequantize_q5_1, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q8_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q8_0, 2, dequantize_q8_0, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q2_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q3_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q4_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q5_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_q6_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq2_xxs_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq2_xs_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq3_xxs_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq3_s_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq2_s_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq1_s_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq1_m_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq4_nl_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_iq4_xs_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
template [[host_name("kernel_mul_mm_id_tensor_tq2_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
#endif
template [[host_name("kernel_mul_mm_id_tensor_f32_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, float4x4, 1, dequantize_f32, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_f16_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, half4x4, 1, dequantize_f16, half, half>;
template [[host_name("kernel_mul_mm_id_tensor_q1_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q1_0, 8, dequantize_q1_0, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_q2_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q2_0, 4, dequantize_q2_0, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_q4_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q4_0, 2, dequantize_q4_0, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_q4_1_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q4_1, 2, dequantize_q4_1, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_q5_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q5_0, 2, dequantize_q5_0, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_q5_1_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q5_1, 2, dequantize_q5_1, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_q8_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q8_0, 2, dequantize_q8_0, float, half>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<bfloat, bfloat, block_mxfp4, 2, dequantize_mxfp4, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_nvfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<bfloat, bfloat, block_nvfp4, 4, dequantize_nvfp4, float, half>;
#else
template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_mxfp4, 2, dequantize_mxfp4, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_nvfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_nvfp4, 4, dequantize_nvfp4, float, half>;
#endif
template [[host_name("kernel_mul_mm_id_tensor_q2_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q2_K, QK_NL, dequantize_q2_K, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_q3_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q3_K, QK_NL, dequantize_q3_K, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_q4_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q4_K, QK_NL, dequantize_q4_K, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_q5_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q5_K, QK_NL, dequantize_q5_K, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_q6_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q6_K, QK_NL, dequantize_q6_K, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_iq2_xxs_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_iq2_xs_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_iq3_xxs_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_iq3_s_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq3_s, QK_NL, dequantize_iq3_s, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_iq2_s_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq2_s, QK_NL, dequantize_iq2_s, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_iq1_s_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq1_s, QK_NL, dequantize_iq1_s, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_iq1_m_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq1_m, QK_NL, dequantize_iq1_m, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_iq4_nl_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq4_nl, 2, dequantize_iq4_nl, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_iq4_xs_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, half>;
template [[host_name("kernel_mul_mm_id_tensor_tq2_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_tq2_0, QK_NL, dequantize_tq2_0, float, half>;
#endif // GGML_METAL_HAS_TENSOR
+147 -28
View File
@@ -894,6 +894,11 @@ template [[host_name("kernel_mul_mv_ext_mxfp4_f32_r1_3")]] kernel mul_mv_ext_q4
template [[host_name("kernel_mul_mv_ext_mxfp4_f32_r1_4")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<4, block_mxfp4, 32, dequantize_mxfp4_t4>;
template [[host_name("kernel_mul_mv_ext_mxfp4_f32_r1_5")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<5, block_mxfp4, 32, dequantize_mxfp4_t4>;
template [[host_name("kernel_mul_mv_ext_nvfp4_f32_r1_2")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<2, block_nvfp4, 64, dequantize_nvfp4_t4>;
template [[host_name("kernel_mul_mv_ext_nvfp4_f32_r1_3")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<3, block_nvfp4, 64, dequantize_nvfp4_t4>;
template [[host_name("kernel_mul_mv_ext_nvfp4_f32_r1_4")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<4, block_nvfp4, 64, dequantize_nvfp4_t4>;
template [[host_name("kernel_mul_mv_ext_nvfp4_f32_r1_5")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<5, block_nvfp4, 64, dequantize_nvfp4_t4>;
template [[host_name("kernel_mul_mv_ext_iq4_nl_f32_r1_2")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<2, block_iq4_nl, 32, dequantize_iq4_nl_t4>;
template [[host_name("kernel_mul_mv_ext_iq4_nl_f32_r1_3")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<3, block_iq4_nl, 32, dequantize_iq4_nl_t4>;
template [[host_name("kernel_mul_mv_ext_iq4_nl_f32_r1_4")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<4, block_iq4_nl, 32, dequantize_iq4_nl_t4>;
@@ -1046,7 +1051,7 @@ template [[host_name("kernel_mul_mv_bf16_bf16")]] kernel mul_mv_t_t kernel_mul_m
template [[host_name("kernel_mul_mv_f32_bf16")]] kernel mul_mv_t_t kernel_mul_mv_t_t<float, bfloat>;
#endif
template<typename T0, typename T04, typename T1, typename T14, short NR0, typename args_t>
template<typename T0, typename T1, short NR0, typename args_t>
void kernel_mul_mv_t_t_4_impl(
args_t args,
device const char * src0,
@@ -1056,6 +1061,9 @@ void kernel_mul_mv_t_t_4_impl(
uint3 tgpig,
ushort tiisg,
ushort sgitg) {
using T04 = typename value_type_4<T0>::type;
using T14 = typename value_type_4<T1>::type;
const short NSG = FC_mul_mv_nsg;
constexpr short NW = N_SIMDWIDTH;
@@ -1129,7 +1137,7 @@ void kernel_mul_mv_t_t_4_impl(
helper_mv_reduce_and_write<NR0>(dst_f32, sumf, r0, args.ne01, tiisg, sgitg, shmem);
}
template<typename T0, typename T04, typename T1, typename T14, typename args_t>
template<typename T0, typename T1, typename args_t>
void kernel_mul_mv_t_t_4_disp(
args_t args,
device const char * src0,
@@ -1140,14 +1148,14 @@ void kernel_mul_mv_t_t_4_disp(
ushort tiisg,
ushort sgitg) {
switch (args.nr0) {
//case 1: kernel_mul_mv_t_t_4_impl<T0, T04, T1, T14, 1, args_t>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break;
case 2: kernel_mul_mv_t_t_4_impl<T0, T04, T1, T14, 2, args_t>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break;
//case 3: kernel_mul_mv_t_t_4_impl<T0, T04, T1, T14, 3, args_t>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break;
//case 4: kernel_mul_mv_t_t_4_impl<T0, T04, T1, T14, 4, args_t>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break;
//case 1: kernel_mul_mv_t_t_4_impl<T0, T1, 1, args_t>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break;
case 2: kernel_mul_mv_t_t_4_impl<T0, T1, 2, args_t>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break;
//case 3: kernel_mul_mv_t_t_4_impl<T0, T1, 3, args_t>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break;
//case 4: kernel_mul_mv_t_t_4_impl<T0, T1, 4, args_t>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break;
};
}
template<typename T0, typename T04, typename T1, typename T14>
template<typename T0, typename T1>
kernel void kernel_mul_mv_t_t_4(
constant ggml_metal_kargs_mul_mv & args,
device const char * src0,
@@ -1157,18 +1165,18 @@ kernel void kernel_mul_mv_t_t_4(
uint3 tgpig[[threadgroup_position_in_grid]],
ushort tiisg[[thread_index_in_simdgroup]],
ushort sgitg[[simdgroup_index_in_threadgroup]]) {
kernel_mul_mv_t_t_4_disp<T0, T04, T1, T14, constant ggml_metal_kargs_mul_mv &>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg);
kernel_mul_mv_t_t_4_disp<T0, T1, constant ggml_metal_kargs_mul_mv &>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg);
}
typedef decltype(kernel_mul_mv_t_t_4<half, half4, half, half4>) mul_mv_t_t_4;
typedef decltype(kernel_mul_mv_t_t_4<half, half>) mul_mv_t_t_4;
template [[host_name("kernel_mul_mv_f32_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<float, float4, float, float4>;
template [[host_name("kernel_mul_mv_f16_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<half, half4, float, float4>;
template [[host_name("kernel_mul_mv_f16_f16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<half, half4, half, half4>;
template [[host_name("kernel_mul_mv_f32_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<float, float>;
template [[host_name("kernel_mul_mv_f16_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<half, float>;
template [[host_name("kernel_mul_mv_f16_f16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<half, half>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mv_bf16_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<bfloat, bfloat4, float, float4>;
template [[host_name("kernel_mul_mv_bf16_bf16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<bfloat, bfloat4, bfloat, bfloat4>;
template [[host_name("kernel_mul_mv_f32_bf16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<float, float4, bfloat, bfloat4>;
template [[host_name("kernel_mul_mv_bf16_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<bfloat, float>;
template [[host_name("kernel_mul_mv_bf16_bf16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<bfloat, bfloat>;
template [[host_name("kernel_mul_mv_f32_bf16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<float, bfloat>;
#endif
template<typename T0, typename T1, typename args_t>
@@ -3032,18 +3040,18 @@ kernel void kernel_mul_mv_iq4_xs_f32(
// decode the E2M1 value in the low nibble of n, scaled by 2^-14, without a lookup table: the 3 magnitude bits
// land in the fp16 exponent/mantissa (e=0 gives the 0.5 subnormal). same decode as MLX's fp4_e2m1
static inline half mxfp4_dq1(uint32_t n) {
static inline half e2m1_dq1(uint32_t n) {
const half c = as_type<half>(ushort((n & 7) << 9));
return (n & 8) ? -c : c;
}
// low / high nibbles of the 4 bytes of w, in byte order, scaled by 2^-14
static inline float4 mxfp4_lo4(uint32_t w) {
return float4(mxfp4_dq1(w), mxfp4_dq1(w >> 8), mxfp4_dq1(w >> 16), mxfp4_dq1(w >> 24));
static inline float4 e2m1_lo4(uint32_t w) {
return float4(e2m1_dq1(w), e2m1_dq1(w >> 8), e2m1_dq1(w >> 16), e2m1_dq1(w >> 24));
}
static inline float4 mxfp4_hi4(uint32_t w) {
return float4(mxfp4_dq1(w >> 4), mxfp4_dq1(w >> 12), mxfp4_dq1(w >> 20), mxfp4_dq1(w >> 28));
static inline float4 e2m1_hi4(uint32_t w) {
return float4(e2m1_dq1(w >> 4), e2m1_dq1(w >> 12), e2m1_dq1(w >> 20), e2m1_dq1(w >> 28));
}
template<int NR0, typename args_t>
@@ -3108,10 +3116,10 @@ void kernel_mul_mv_mxfp4_f32_impl(
const uint32_t w0 = (a >> sh) | ((b << 1) << (31 - sh));
const uint32_t w1 = (b >> sh) | ((c << 1) << (31 - sh));
float4 acc1 = yl[0]*mxfp4_lo4(w0);
float4 acc2 = yl[1]*mxfp4_hi4(w0);
float4 acc3 = yl[2]*mxfp4_lo4(w1);
float4 acc4 = yl[3]*mxfp4_hi4(w1);
float4 acc1 = yl[0]*e2m1_lo4(w0);
float4 acc2 = yl[1]*e2m1_hi4(w0);
float4 acc3 = yl[2]*e2m1_lo4(w1);
float4 acc4 = yl[3]*e2m1_hi4(w1);
acc1 = (acc1 + acc3) + (acc2 + acc4);
@@ -3146,6 +3154,116 @@ kernel void kernel_mul_mv_mxfp4_f32(
kernel_mul_mv_mxfp4_f32_impl<N_R0_MXFP4, constant ggml_metal_kargs_mul_mv &>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg);
}
// NVFP4: a 64-weight block holds four 16-weight sub-blocks, each scaled by its own UE4M3 value.
// a thread handles the two sub-blocks of one half of the block, so 16 blocks per loop iteration
template<int NR0, typename args_t>
void kernel_mul_mv_nvfp4_f32_impl(
args_t args,
device const char * src0,
device const char * src1,
device char * dst,
threadgroup char * shmem,
uint3 tgpig,
ushort tiisg,
ushort sgitg) {
const short NSG = FC_mul_mv_nsg;
const int r0 = tgpig.x;
const int r1 = tgpig.y;
const int im = tgpig.z;
const int first_row = (r0 * NSG + sgitg) * NR0;
const uint i12 = im%FC_mul_mv_ne12;
const uint i13 = im/FC_mul_mv_ne12;
const uint64_t offset0 = first_row*args.nb01 + (i12/FC_mul_mv_r2)*args.nb02 + (i13/FC_mul_mv_r3)*args.nb03;
const uint64_t offset1 = r1*args.nb11 + (i12 )*args.nb12 + (i13 )*args.nb13;
device const block_nvfp4 * x = (device const block_nvfp4 *) (src0 + offset0);
device const float * y = (device const float *) (src1 + offset1);
const int nb = args.ne00/QK_NVFP4;
const int ns01 = args.nb01/args.nb00; // this can be larger than nb for permuted src0 tensors
const short ix = tiisg/2; // 0...15
const short it = tiisg%2; // 0 or 1
float4 yl[8];
float sumf[NR0]={0.f};
device const float * yb = y + ix*QK_NVFP4 + it*32;
// note: just the check `ib < nb` is enough, but adding the redundant `&& ib < ns01` check makes the kernel a bit faster
// no idea why that is - needs some deeper investigation [TAG_MUL_MV_WEIRD]
for (int ib = ix; ib < nb && ib < ns01; ib += 16) {
device const float4 * y4 = (device const float4 *) yb;
yl[0] = y4[0];
yl[1] = y4[2];
yl[2] = y4[1];
yl[3] = y4[3];
yl[4] = y4[4];
yl[5] = y4[6];
yl[6] = y4[5];
yl[7] = y4[7];
FOR_UNROLL (short row = 0; row < NR0; row++) {
device const block_nvfp4 & xb = x[row*ns01 + ib];
// a block is 36 bytes, so its 16 quant bytes are 4-byte aligned and read as four words
device const uint32_t * pw = (device const uint32_t *)(xb.qs + 16*it);
const uint32_t w0 = pw[0];
const uint32_t w1 = pw[1];
const uint32_t w2 = pw[2];
const uint32_t w3 = pw[3];
float4 acc1 = yl[0]*e2m1_lo4(w0);
float4 acc2 = yl[1]*e2m1_hi4(w0);
float4 acc3 = yl[2]*e2m1_lo4(w1);
float4 acc4 = yl[3]*e2m1_hi4(w1);
float4 acc5 = yl[4]*e2m1_lo4(w2);
float4 acc6 = yl[5]*e2m1_hi4(w2);
float4 acc7 = yl[6]*e2m1_lo4(w3);
float4 acc8 = yl[7]*e2m1_hi4(w3);
acc1 = (acc1 + acc3) + (acc2 + acc4);
acc5 = (acc5 + acc7) + (acc6 + acc8);
// 16384 undoes the 2^-14 of the decode
sumf[row] += ue4m3_to_fp32(xb.d[2*it + 0])*16384.0f*((acc1[0] + acc1[1]) + (acc1[2] + acc1[3])) +
ue4m3_to_fp32(xb.d[2*it + 1])*16384.0f*((acc5[0] + acc5[1]) + (acc5[2] + acc5[3]));
}
yb += 16 * QK_NVFP4;
}
device float * dst_f32 = (device float *) dst + (uint64_t)im*args.ne0*args.ne1 + (uint64_t)r1*args.ne0;
for (int row = 0; row < NR0 && first_row + row < args.ne0; ++row) {
float sum_all = simd_sum(sumf[row]);
if (tiisg == 0) {
dst_f32[first_row + row] = sum_all;
}
}
}
[[host_name("kernel_mul_mv_nvfp4_f32")]]
kernel void kernel_mul_mv_nvfp4_f32(
constant ggml_metal_kargs_mul_mv & args,
device const char * src0,
device const char * src1,
device char * dst,
threadgroup char * shmem [[threadgroup(0)]],
uint3 tgpig[[threadgroup_position_in_grid]],
ushort tiisg[[thread_index_in_simdgroup]],
ushort sgitg[[simdgroup_index_in_threadgroup]]) {
kernel_mul_mv_nvfp4_f32_impl<N_R0_NVFP4, constant ggml_metal_kargs_mul_mv &>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg);
}
template<int nr0, typename args_t>
void kernel_mul_mv_tq2_0_f32_impl(
args_t args,
@@ -3389,17 +3507,17 @@ kernel void kernel_mul_mv_id(
typedef decltype(kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_disp<float, float>>>) kernel_mul_mv_id_t;
typedef decltype(kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_4_disp<float, float4, float, float4>>>) kernel_mul_mv_id_4_t;
typedef decltype(kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_4_disp<float, float>>>) kernel_mul_mv_id_4_t;
template [[host_name("kernel_mul_mv_id_f32_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_disp<float, float>>>;
template [[host_name("kernel_mul_mv_id_f16_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_disp<half, float>>>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mv_id_bf16_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_disp<bfloat, float>>>;
#endif
template [[host_name("kernel_mul_mv_id_f32_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_4_disp<float, float4, float, float4>>>;
template [[host_name("kernel_mul_mv_id_f16_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_4_disp<half, half4, float, float4>>>;
template [[host_name("kernel_mul_mv_id_f32_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_4_disp<float, float>>>;
template [[host_name("kernel_mul_mv_id_f16_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_4_disp<half, float>>>;
#if defined(GGML_METAL_HAS_BF16)
template [[host_name("kernel_mul_mv_id_bf16_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_4_disp<bfloat, bfloat4, float, float4>>>;
template [[host_name("kernel_mul_mv_id_bf16_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_4_disp<bfloat, float>>>;
#endif
template [[host_name("kernel_mul_mv_id_q8_0_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q8_0_f32_impl<N_R0_Q8_0>>>;
@@ -3412,6 +3530,7 @@ template [[host_name("kernel_mul_mv_id_q5_0_f32")]] kernel kernel_mul_mv_id_t
template [[host_name("kernel_mul_mv_id_q5_1_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<mul_vec_q_n_f32_impl<block_q5_1, N_R0_Q5_1>>>;
template [[host_name("kernel_mul_mv_id_mxfp4_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_mxfp4_f32_impl<N_R0_MXFP4>>>;
template [[host_name("kernel_mul_mv_id_nvfp4_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_nvfp4_f32_impl<N_R0_NVFP4>>>;
template [[host_name("kernel_mul_mv_id_q2_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q2_K_f32_impl <N_R0_Q2_K>>>;
template [[host_name("kernel_mul_mv_id_q3_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q3_K_f32_impl <N_R0_Q3_K>>>;
@@ -611,6 +611,7 @@ MUL_MV_MMA_GEN("bf16", bfloat4x4, 1, dequantize_bf16)
MUL_MV_MMA_GEN("q1_0", block_q1_0, 8, dequantize_q1_0)
MUL_MV_MMA_GEN("q2_0", block_q2_0, 4, dequantize_q2_0)
MUL_MV_MMA_GEN("mxfp4", block_mxfp4, 2, dequantize_mxfp4)
MUL_MV_MMA_GEN("nvfp4", block_nvfp4, 4, dequantize_nvfp4)
MUL_MV_MMA_GEN("q2_K", block_q2_K, QK_NL, dequantize_q2_K)
MUL_MV_MMA_GEN("q3_K", block_q3_K, QK_NL, dequantize_q3_K)
MUL_MV_MMA_GEN("iq2_xxs", block_iq2_xxs, QK_NL, dequantize_iq2_xxs)
+73 -8
View File
@@ -146,6 +146,7 @@ template [[host_name("kernel_cpy_q4_1_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32<
template [[host_name("kernel_cpy_q5_0_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32<float4x4, block_q5_0, 2, dequantize_q5_0>;
template [[host_name("kernel_cpy_q5_1_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32<float4x4, block_q5_1, 2, dequantize_q5_1>;
template [[host_name("kernel_cpy_q8_0_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32<float4x4, block_q8_0, 2, dequantize_q8_0>;
template [[host_name("kernel_cpy_nvfp4_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32<float4x4, block_nvfp4, 4, dequantize_nvfp4>;
template [[host_name("kernel_cpy_tq2_0_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32<float4x4, block_tq2_0, QK_NL, dequantize_tq2_0>;
@@ -156,9 +157,51 @@ template [[host_name("kernel_cpy_q4_1_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32<
template [[host_name("kernel_cpy_q5_0_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32<half4x4, block_q5_0, 2, dequantize_q5_0>;
template [[host_name("kernel_cpy_q5_1_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32<half4x4, block_q5_1, 2, dequantize_q5_1>;
template [[host_name("kernel_cpy_q8_0_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32<half4x4, block_q8_0, 2, dequantize_q8_0>;
template [[host_name("kernel_cpy_nvfp4_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32<half4x4, block_nvfp4, 4, dequantize_nvfp4>;
template [[host_name("kernel_cpy_tq2_0_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32<half4x4, block_tq2_0, QK_NL, dequantize_tq2_0>;
template<typename T>
static void concat_copy(device const char * src, device char * dst, const int n, const int tid, const int nth) {
if (n <= 0) {
return;
}
constexpr int N = 16/sizeof(T);
typedef vec<T, N> T16;
device const T * x = (device const T *)src;
device T * y = (device T *)dst;
const size_t rx = (size_t)x % 16;
if (rx != (size_t)y % 16 || rx % sizeof(T) != 0) {
for (int i = tid; i < n; i += nth) {
y[i] = x[i];
}
return;
}
const int np = min((int)(((16 - rx) % 16)/sizeof(T)), n);
const int n16 = (n - np)/N;
for (int i = tid; i < np; i += nth) {
y[i] = x[i];
}
device const T16 * x16 = (device const T16 *)(x + np);
device T16 * y16 = (device T16 *)(y + np);
for (int i = tid; i < n16; i += nth) {
y16[i] = x16[i];
}
for (int i = np + n16*N + tid; i < n; i += nth) {
y[i] = x[i];
}
}
template<typename T>
kernel void kernel_concat(
constant ggml_metal_kargs_concat & args,
@@ -178,20 +221,39 @@ kernel void kernel_concat(
return;
}
int o[4] = {0, 0, 0, 0};
o[args.dim] = args.dim == 0 ? args.ne00 : (args.dim == 1 ? args.ne01 : (args.dim == 2 ? args.ne02 : args.ne03));
const int o0 = args.dim == 0 ? args.ne00 : 0;
const int o1 = args.dim == 1 ? args.ne01 : 0;
const int o2 = args.dim == 2 ? args.ne02 : 0;
const int o3 = args.dim == 3 ? args.ne03 : 0;
// chunk ic of nc0 along the row
const int n0 = (args.ne0 + args.nc0 - 1)/args.nc0;
const int i0e = min(args.ne0, (ic + 1)*n0);
const int i0b = ntg.y == 1 ? ic*n0 : 0;
const int i0e = ntg.y == 1 ? min(args.ne0, (ic + 1)*n0) : args.ne0;
for (int i0 = ic*n0 + tpitg.x; i0 < i0e; i0 += ntg.x) {
if (args.nb0 == sizeof(T) && args.nb00 == sizeof(T) && args.nb10 == sizeof(T)) {
const bool in0 = i1 < args.ne01 && i2 < args.ne02 && i3 < args.ne03;
const int na = in0 ? min(i0e - i0b, max(0, args.ne00 - i0b)) : 0;
const int nb = i0e - i0b - na;
device const char * r0 = src0 + i3*args.nb03 + i2*args.nb02 + i1*args.nb01;
device const char * r1 = src1 + (i3 - o3)*args.nb13 + (i2 - o2)*args.nb12 + (i1 - o1)*args.nb11;
device char * rd = dst + i3*args.nb3 + i2*args.nb2 + i1*args.nb1;
concat_copy<T>(r0 + i0b*sizeof(T), rd + i0b*sizeof(T), na, tpitg.x, ntg.x);
concat_copy<T>(r1 + (i0b + na - o0)*sizeof(T), rd + (i0b + na)*sizeof(T), nb, tpitg.x, ntg.x);
return;
}
for (int i0 = i0b + tpitg.x; i0 < i0e; i0 += ntg.x) {
device const T * x;
if (i0 < args.ne00 && i1 < args.ne01 && i2 < args.ne02 && i3 < args.ne03) {
x = (device const T *)(src0 + (i3 )*args.nb03 + (i2 )*args.nb02 + (i1 )*args.nb01 + (i0 )*args.nb00);
} else {
x = (device const T *)(src1 + (i3 - o[3])*args.nb13 + (i2 - o[2])*args.nb12 + (i1 - o[1])*args.nb11 + (i0 - o[0])*args.nb10);
x = (device const T *)(src1 + (i3 - o3)*args.nb13 + (i2 - o2)*args.nb12 + (i1 - o1)*args.nb11 + (i0 - o0)*args.nb10);
}
device T * y = (device T *)(dst + i3*args.nb3 + i2*args.nb2 + i1*args.nb1 + i0*args.nb0);
@@ -232,8 +294,10 @@ kernel void kernel_concat_q(
return;
}
int o[4] = {0, 0, 0, 0};
o[args.dim] = args.dim == 0 ? args.ne00 : (args.dim == 1 ? args.ne01 : (args.dim == 2 ? args.ne02 : args.ne03));
const int o0 = args.dim == 0 ? args.ne00 : 0;
const int o1 = args.dim == 1 ? args.ne01 : 0;
const int o2 = args.dim == 2 ? args.ne02 : 0;
const int o3 = args.dim == 3 ? args.ne03 : 0;
// chunk ic of nc0 along the row
const int n0 = (args.ne0 + args.nc0 - 1)/args.nc0;
@@ -245,7 +309,7 @@ kernel void kernel_concat_q(
if (i0 < args.ne00 && i1 < args.ne01 && i2 < args.ne02 && i3 < args.ne03) {
x = (device const block_q *)(src0 + (i3 )*args.nb03 + (i2 )*args.nb02 + (i1 )*args.nb01 + (i0 )*args.nb00);
} else {
x = (device const block_q *)(src1 + (i3 - o[3])*args.nb13 + (i2 - o[2])*args.nb12 + (i1 - o[1])*args.nb11 + (i0 - o[0])*args.nb10);
x = (device const block_q *)(src1 + (i3 - o3)*args.nb13 + (i2 - o2)*args.nb12 + (i1 - o1)*args.nb11 + (i0 - o0)*args.nb10);
}
device block_q * y = (device block_q *)(dst + i3*args.nb3 + i2*args.nb2 + i1*args.nb1 + i0*args.nb0);
@@ -341,6 +405,7 @@ template [[host_name("kernel_get_rows_q5_0")]] kernel get_rows_q_t kernel_get
template [[host_name("kernel_get_rows_q5_1")]] kernel get_rows_q_t kernel_get_rows_q<block_q5_1, 2, dequantize_q5_1>;
template [[host_name("kernel_get_rows_q8_0")]] kernel get_rows_q_t kernel_get_rows_q<block_q8_0, 2, dequantize_q8_0>;
template [[host_name("kernel_get_rows_mxfp4")]] kernel get_rows_q_t kernel_get_rows_q<block_mxfp4, 2, dequantize_mxfp4>;
template [[host_name("kernel_get_rows_nvfp4")]] kernel get_rows_q_t kernel_get_rows_q<block_nvfp4, 4, dequantize_nvfp4>;
template [[host_name("kernel_get_rows_q2_K")]] kernel get_rows_q_t kernel_get_rows_q<block_q2_K, QK_NL, dequantize_q2_K>;
template [[host_name("kernel_get_rows_q3_K")]] kernel get_rows_q_t kernel_get_rows_q<block_q3_K, QK_NL, dequantize_q3_K>;
template [[host_name("kernel_get_rows_q4_K")]] kernel get_rows_q_t kernel_get_rows_q<block_q4_K, QK_NL, dequantize_q4_K>;
+20 -1
View File
@@ -21,6 +21,25 @@ inline bfloat4 ggml_metal_unary_cast<bfloat4, float>(float x) {
}
#endif
template <typename T>
inline T ggml_metal_log1p(T x) {
const T y = x / (T(2.0f) + x);
const T y2 = y * y;
T p = T(1.0f / 13.0f);
p = p * y2 + T(1.0f / 11.0f);
p = p * y2 + T(1.0f / 9.0f);
p = p * y2 + T(1.0f / 7.0f);
p = p * y2 + T(1.0f / 5.0f);
p = p * y2 + T(1.0f / 3.0f);
p = p * y2 + T(1.0f);
const T s = T(2.0f) * y * p;
const T l = precise::log(T(1.0f) + x);
const auto in_series = (x >= T(-0.5f)) & (x <= T(1.0f));
const auto tiny = fabs(x) < T(2.5e-38f);
const T r = select(l, s, in_series);
return select(r, x, tiny);
}
template <typename T0, typename T, typename TC>
kernel void kernel_unary_impl(
constant ggml_metal_kargs_unary & args,
@@ -166,7 +185,7 @@ kernel void kernel_unary_impl(
}
if (FC_OP == OP_UNARY_NUM_SOFTPLUS) {
dst_ptr[i0] = ggml_metal_unary_cast<T>(select(log(1 + exp(x)), x, x > 20));
dst_ptr[i0] = ggml_metal_unary_cast<T>(select(ggml_metal_log1p(precise::exp(x)), x, x > TC(20.0f)));
}
if (FC_OP == OP_UNARY_NUM_EXPM1) {
+73
View File
@@ -36,6 +36,78 @@ endif ()
if (GGML_OPENCL_USE_ADRENO_BIN_KERNELS)
message(STATUS "OpenCL will use precompiled binary kernels for Adreno (improved performance on some platforms)")
add_compile_definitions(GGML_OPENCL_USE_ADRENO_BIN_KERNELS)
target_link_libraries(${TARGET_NAME} PRIVATE ${CMAKE_DL_LIBS})
endif ()
# The library is only published for Windows on ARM64. A failed download is not
# fatal: without the library the backend uses its builtin kernels.
string(TOLOWER "${CMAKE_SYSTEM_PROCESSOR}" ADRENO_BIN_KERNELS_SYSTEM_PROCESSOR)
if (GGML_OPENCL_USE_ADRENO_BIN_KERNELS AND GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH AND
WIN32 AND ADRENO_BIN_KERNELS_SYSTEM_PROCESSOR MATCHES "^(aarch64|arm64)$")
# Bump the version and hash together when a new library release is published.
set(ADRENO_BIN_KERNELS_VERSION "0.0.15")
set(ADRENO_BIN_KERNELS_ZIP_SHA256 "325c89a3bce51abe95f40c6bacece005d5ca9cf6166eb5f17d33592cd13ab795")
set(ADRENO_BIN_KERNELS_URL "https://softwarecenter.qualcomm.com/api/download/software/tools/Adreno_Kernel_Library_GGML/Windows/${ADRENO_BIN_KERNELS_VERSION}/adreno-opencl-kernels-${ADRENO_BIN_KERNELS_VERSION}.zip")
set(ADRENO_BIN_KERNELS_ROOT "${CMAKE_BINARY_DIR}/_deps/adreno-opencl-kernels-${ADRENO_BIN_KERNELS_VERSION}")
set(ADRENO_BIN_KERNELS_ZIP "${ADRENO_BIN_KERNELS_ROOT}.zip")
set(ADRENO_BIN_KERNELS_DLL "${ADRENO_BIN_KERNELS_ROOT}/adreno-opencl-kernels.dll")
set(ADRENO_BIN_KERNELS_LICENSE "${ADRENO_BIN_KERNELS_ROOT}/license.txt")
if (NOT EXISTS "${ADRENO_BIN_KERNELS_DLL}" OR NOT EXISTS "${ADRENO_BIN_KERNELS_LICENSE}")
message(STATUS "OpenCL: fetching Adreno binary kernel library ${ADRENO_BIN_KERNELS_VERSION} from Qualcomm; its use is subject to the license in license.txt")
file(DOWNLOAD "${ADRENO_BIN_KERNELS_URL}" "${ADRENO_BIN_KERNELS_ZIP}"
TLS_VERIFY ON
TIMEOUT 120
INACTIVITY_TIMEOUT 30
STATUS ADRENO_BIN_KERNELS_DOWNLOAD_STATUS)
list(GET ADRENO_BIN_KERNELS_DOWNLOAD_STATUS 0 ADRENO_BIN_KERNELS_DOWNLOAD_RESULT)
if (ADRENO_BIN_KERNELS_DOWNLOAD_RESULT EQUAL 0)
file(SHA256 "${ADRENO_BIN_KERNELS_ZIP}" ADRENO_BIN_KERNELS_ZIP_ACTUAL_SHA256)
if (NOT ADRENO_BIN_KERNELS_ZIP_ACTUAL_SHA256 STREQUAL ADRENO_BIN_KERNELS_ZIP_SHA256)
file(REMOVE "${ADRENO_BIN_KERNELS_ZIP}")
message(FATAL_ERROR "Adreno binary kernel library hash mismatch: expected ${ADRENO_BIN_KERNELS_ZIP_SHA256}, got ${ADRENO_BIN_KERNELS_ZIP_ACTUAL_SHA256}")
endif ()
file(MAKE_DIRECTORY "${ADRENO_BIN_KERNELS_ROOT}")
execute_process(
COMMAND ${CMAKE_COMMAND} -E tar xf "${ADRENO_BIN_KERNELS_ZIP}"
WORKING_DIRECTORY "${ADRENO_BIN_KERNELS_ROOT}"
RESULT_VARIABLE ADRENO_BIN_KERNELS_EXTRACT_RESULT)
if (NOT ADRENO_BIN_KERNELS_EXTRACT_RESULT EQUAL 0)
message(WARNING "Failed to extract the Adreno binary kernel library from ${ADRENO_BIN_KERNELS_ZIP}")
endif ()
else ()
list(GET ADRENO_BIN_KERNELS_DOWNLOAD_STATUS 1 ADRENO_BIN_KERNELS_DOWNLOAD_ERROR)
message(WARNING "Failed to download the Adreno binary kernel library (${ADRENO_BIN_KERNELS_DOWNLOAD_ERROR}); "
"the builtin kernels will be used. Set GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=OFF to skip the download.")
endif ()
file(REMOVE "${ADRENO_BIN_KERNELS_ZIP}")
endif ()
if (EXISTS "${ADRENO_BIN_KERNELS_DLL}" AND EXISTS "${ADRENO_BIN_KERNELS_LICENSE}")
if (COMMAND license_add_file)
license_add_file("Adreno OpenCL kernels" "${ADRENO_BIN_KERNELS_LICENSE}")
endif ()
set(ADRENO_BIN_KERNELS_OUTPUT_DIR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}")
if (CMAKE_CONFIGURATION_TYPES AND NOT ADRENO_BIN_KERNELS_OUTPUT_DIR MATCHES "\\$<")
string(APPEND ADRENO_BIN_KERNELS_OUTPUT_DIR "/$<CONFIG>")
endif ()
foreach (CONFIG IN LISTS CMAKE_CONFIGURATION_TYPES CMAKE_BUILD_TYPE)
string(TOUPPER "${CONFIG}" CONFIG_UPPER)
if (DEFINED CMAKE_RUNTIME_OUTPUT_DIRECTORY_${CONFIG_UPPER})
set(ADRENO_BIN_KERNELS_OUTPUT_DIR "$<$<CONFIG:${CONFIG}>:${CMAKE_RUNTIME_OUTPUT_DIRECTORY_${CONFIG_UPPER}}>$<$<NOT:$<CONFIG:${CONFIG}>>:${ADRENO_BIN_KERNELS_OUTPUT_DIR}>")
endif ()
endforeach ()
add_custom_target(ggml-opencl-adreno-bin-kernels ALL
COMMAND ${CMAKE_COMMAND} -E make_directory "${ADRENO_BIN_KERNELS_OUTPUT_DIR}"
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${ADRENO_BIN_KERNELS_DLL}" "${ADRENO_BIN_KERNELS_OUTPUT_DIR}/adreno-opencl-kernels.dll"
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${ADRENO_BIN_KERNELS_LICENSE}" "${ADRENO_BIN_KERNELS_OUTPUT_DIR}/LICENSE-adreno-opencl-kernels.txt")
add_dependencies(${TARGET_NAME} ggml-opencl-adreno-bin-kernels)
install(FILES "${ADRENO_BIN_KERNELS_DLL}" DESTINATION ${CMAKE_INSTALL_BINDIR})
install(FILES "${ADRENO_BIN_KERNELS_LICENSE}" DESTINATION ${CMAKE_INSTALL_BINDIR} RENAME LICENSE-adreno-opencl-kernels.txt)
endif ()
endif ()
function(ggml_opencl_add_kernel KNAME)
@@ -228,6 +300,7 @@ set(GGML_OPENCL_KERNELS
gemm_coopk_q4_k_q8_1_dp4a
gemm_coopk_q4_k_q8_1_dp4a_bin_c8
gemm_coopk_q6_k_q8_1_dp4a
gemm_coopk_q6_k_q8_1_dp4a_bin_c8
pack_b_f16_coopmat
gemm_noshuffle_q4_0_f32_coopmat
gemm_noshuffle_q5_0_f32_coopmat
+217 -12
View File
@@ -1181,9 +1181,9 @@ struct ggml_backend_opencl_context {
cl_kernel kernel_conv_2d_f16_f32;
cl_kernel kernel_conv2d_dw_f32_f32, kernel_conv2d_dwf16_f32;
cl_kernel kernel_ssm_conv_f32_f32, kernel_ssm_conv_f32_f32_4;
// [size_idx][kda][tgpp] where size_idx: 0=S_V=16, 1=32, 2=64, 3=128; kda: 0 or 1.
// [size_idx][kda][tgpp][replay] where size_idx: 0=S_V=16, 1=32, 2=64, 3=128; kda: 0 or 1.
// tgpp 0 = TG variant (COLS_PER_LANE_GROUP=1), tgpp 1 = prefill variant (COLS_PER_LANE_GROUP=4).
cl_kernel kernel_gated_delta_net_f32[4][2][2] = {};
cl_kernel kernel_gated_delta_net_f32[4][2][2][2] = {};
cl_kernel kernel_ssm_scan_f32 = nullptr;
cl_kernel kernel_ssm_scan_f32_mamba2_d128 = nullptr;
cl_kernel kernel_ssm_scan_f32_mamba2_d256 = nullptr;
@@ -1529,13 +1529,18 @@ struct ggml_backend_opencl_context {
cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_c2 = nullptr;
int nsg_coopk_dp4a_q6_k = 8;
int rows_coopk_dp4a_q6_k = 4;
cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 = nullptr;
cl_kernel kernel_quant_a_q8_1_k4h = nullptr;
int nsg_coopk_dp4a_q6_k_bin_c8 = 4;
#endif // GGML_OPENCL_USE_ADRENO_KERNELS
~ggml_backend_opencl_context() {
#ifdef GGML_OPENCL_USE_ADRENO_KERNELS
for (cl_kernel kernel : {
kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8,
kernel_quant_a_q8_1_k4
kernel_quant_a_q8_1_k4,
kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8,
kernel_quant_a_q8_1_k4h
}
) {
if (kernel != nullptr) {
@@ -1949,6 +1954,46 @@ static void load_cl_kernel_coopk_q4_k_bin_c8(ggml_backend_opencl_context * backe
backend_ctx->kernel_quant_a_q8_1_k4 = quant;
}
static void load_cl_kernel_coopk_q6_k_bin_c8(ggml_backend_opencl_context * backend_ctx) {
#ifdef GGML_OPENCL_EMBED_KERNELS
const std::string kernel_src {
#include "gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl.h"
};
#else
const std::string kernel_src = read_file("gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl");
#endif
cl_program program = ggml_cl_build_program_coopk(backend_ctx, kernel_src.c_str(),
"kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8", backend_ctx->kernel_compile_opts,
backend_ctx->nsg_coopk_dp4a_q6_k_bin_c8, false);
if (program == nullptr) {
return;
}
cl_int err;
cl_kernel gemm = clCreateKernel(program, "kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8", &err);
if (err != CL_SUCCESS) {
CL_CHECK(clReleaseProgram(program));
return;
}
cl_kernel quant = clCreateKernel(program, "kernel_quant_a_q8_1_k4h", &err);
CL_CHECK(clReleaseProgram(program));
if (err != CL_SUCCESS) {
CL_CHECK(clReleaseKernel(gemm));
return;
}
if (backend_ctx->get_kernel_workgroup_size(quant) < 64) {
CL_CHECK(clReleaseKernel(gemm));
CL_CHECK(clReleaseKernel(quant));
return;
}
backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 = gemm;
backend_ctx->kernel_quant_a_q8_1_k4h = quant;
}
static void ggml_cl_coopk_build_narrow(ggml_backend_opencl_context * backend_ctx,
const std::string & kernel_src, const char * kernel_name,
int rows, int & nsg, cl_kernel & kernel_c4, cl_kernel & kernel_c2) {
@@ -2065,6 +2110,15 @@ static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx
backend_ctx->rows_coopk_dp4a_q6_k, backend_ctx->nsg_coopk_dp4a_q6_k,
backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_c4,
backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_c2);
static const bool use_coopk_bin = [] {
const char * env = getenv("GGML_OPENCL_COOPK_Q6_K_BIN");
return !env || !*env || atoi(env) != 0;
}();
if (use_adreno_bin_kernels(backend_ctx) && use_coopk_bin) {
load_cl_kernel_coopk_q6_k_bin_c8(backend_ctx);
}
GGML_LOG_CONT(".");
}
}
@@ -5170,7 +5224,7 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
GGML_LOG_CONT(".");
}
// gated_delta_net: one kernel per (S_V, KDA, tgpp) triple.
// gated_delta_net: one kernel per (S_V, KDA, tgpp, replay).
{
#ifdef GGML_OPENCL_EMBED_KERNELS
const std::string kernel_src {
@@ -5238,11 +5292,14 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
// Please remember to implement code to handle it.
opts += " -DSUBGROUPS_PER_WG=" + std::to_string(spw);
cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts);
for (int replay = 0; replay < 2; replay++) {
const std::string opts_rep = opts + " -DREPLAY=" + std::to_string(replay);
cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts_rep);
CL_CHECK((backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp] =
clCreateKernel(prog, "kernel_gated_delta_net", &err), err));
CL_CHECK(clReleaseProgram(prog));
CL_CHECK((backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp][replay] =
clCreateKernel(prog, "kernel_gated_delta_net", &err), err));
CL_CHECK(clReleaseProgram(prog));
}
}
}
}
@@ -12662,8 +12719,8 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te
case GGML_OP_MEAN:
return op->src[0]->type == GGML_TYPE_F32;
case GGML_OP_FLASH_ATTN_EXT: {
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
if (op->src[5] != nullptr) {
// K/V row lists and indexed bias are not supported
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
#ifdef GGML_OPENCL_USE_ADRENO_KERNELS
@@ -29443,6 +29500,93 @@ static void ggml_cl_mul_mat_q6_K_f32_adreno_ila(ggml_backend_t backend, const gg
const int N = ne1;
const int K = ne00;
if (backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 != nullptr &&
N >= 2 && N <= 8 && M > 0 && K > 0 && M % 4 == 0 && K % 256 == 0 &&
src0->ne[0] == K && src0->ne[1] == M && dst->ne[1] == N &&
K <= INT_MAX / 8 && (int64_t) M * K / 8 <= INT_MAX &&
src0->ne[2] == 1 && src0->ne[3] == 1 && src0->view_src == nullptr &&
src1->ne[2] == 1 && src1->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 &&
ggml_is_contiguous(src1) && ggml_is_contiguous(dst)
) {
const int kb = K / 32;
const size_t qa_bytes = (size_t)8 * K;
const size_t ds_bytes = (size_t)24 * kb * sizeof(cl_half);
backend_ctx->prealloc_moe_qa.allocate(context, qa_bytes);
backend_ctx->prealloc_moe_da.allocate(context, ds_bytes);
if (ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_qa, qa_bytes,
backend_ctx->coopk_c8_qa_image, backend_ctx->coopk_c8_qa_buffer, backend_ctx->coopk_c8_qa_image_bytes) &&
ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_da, ds_bytes,
backend_ctx->coopk_c8_ds_image, backend_ctx->coopk_c8_ds_buffer, backend_ctx->coopk_c8_ds_image_bytes)
) {
const int n_blocks = N * kb;
cl_kernel quant = backend_ctx->kernel_quant_a_q8_1_k4h;
CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &extra1->data_device));
CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer));
CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer));
CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_ulong), &offset1));
CL_CHECK(clSetKernelArg(quant, 4, sizeof(int), &n_blocks));
CL_CHECK(clSetKernelArg(quant, 5, sizeof(int), &kb));
size_t quant_local[] = {64};
size_t quant_global[] = {(size_t)8 * kb};
backend_ctx->enqueue_ndrange_kernel(quant, 1, quant_global, quant_local, dst);
int ksplit = ggml_cl_coopk_ksplit(backend_ctx, CEIL_DIV(M / 4, 64), kb);
if (backend_ctx->kernel_gemv_splitk_reduce_f32 == nullptr) {
ksplit = 1;
}
cl_mem out = extrad->data_device;
cl_ulong out_offset = offsetd;
if (ksplit > 1) {
backend_ctx->prealloc_splitk_partial.allocate(context, (size_t)ksplit * M * N * sizeof(float));
out = backend_ctx->prealloc_splitk_partial.buffer;
out_offset = 0;
}
const cl_uchar mask_c0 = 0xC0;
const size_t nsg = backend_ctx->nsg_coopk_dp4a_q6_k_bin_c8;
cl_kernel gemm = backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8;
CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0_q6_K->ql));
CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0_q6_K->qh));
CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0_q6_K->s));
CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0_q6_K->d));
CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->coopk_c8_qa_image));
CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->coopk_c8_ds_image));
CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &out));
CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &out_offset));
CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &M));
CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &K));
CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &N));
CL_CHECK(clSetKernelArg(gemm, 11, sizeof(cl_uchar), &mask_c0));
CL_CHECK(clSetKernelArg(gemm, 12, sizeof(int), &ksplit));
size_t local[] = {64, nsg, 1};
size_t global[] = {(size_t)CEIL_DIV(M / 4, 64) * 64, nsg * ksplit, 1};
backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst);
if (ksplit > 1) {
const int rows = M * N;
cl_kernel reduce = backend_ctx->kernel_gemv_splitk_reduce_f32;
CL_CHECK(clSetKernelArg(reduce, 0, sizeof(cl_mem), &out));
CL_CHECK(clSetKernelArg(reduce, 1, sizeof(cl_mem), &extrad->data_device));
CL_CHECK(clSetKernelArg(reduce, 2, sizeof(cl_ulong), &offsetd));
CL_CHECK(clSetKernelArg(reduce, 3, sizeof(int), &rows));
CL_CHECK(clSetKernelArg(reduce, 4, sizeof(int), &ksplit));
size_t reduce_local[] = {64};
size_t reduce_global[] = {(size_t)CEIL_DIV(rows, 64) * 64};
backend_ctx->enqueue_ndrange_kernel(reduce, 1, reduce_global, reduce_local, dst);
}
return;
}
}
if (ne1 == 1) {
cl_mem b_sub_buf = nullptr;
cl_mem b_img = nullptr;
@@ -40476,6 +40620,9 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) {
const cl_uint n_tokens = (cl_uint) src_v->ne[2];
const cl_uint n_seqs = (cl_uint) src_v->ne[3];
const cl_uint K = (cl_uint) ggml_get_op_params_i32(dst, 0);
const bool replay = dst->src[6] != nullptr;
const cl_uint n_pend = replay ? (cl_uint) ggml_get_op_params_i32(dst, 1) : 0;
const cl_uint keep = replay ? (cl_uint) ggml_get_op_params_i32(dst, 2) : 0;
int si;
switch (S_v) {
@@ -40509,7 +40656,7 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) {
// spw needs adjustment when S_v != 128
const int spw = (tgpp == 0) ? 1 : 1;
cl_kernel kernel = backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp];
cl_kernel kernel = backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp][replay];
GGML_ASSERT(kernel != nullptr);
const cl_uint s_off = S_v * H_v * n_tokens * n_seqs;
@@ -40517,6 +40664,9 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) {
const cl_uint sq1 = (cl_uint)(src_q->nb[1] / sizeof(float));
const cl_uint sq2 = (cl_uint)(src_q->nb[2] / sizeof(float));
const cl_uint sq3 = (cl_uint)(src_q->nb[3] / sizeof(float));
const cl_uint sk1 = (cl_uint)(src_k->nb[1] / sizeof(float));
const cl_uint sk2 = (cl_uint)(src_k->nb[2] / sizeof(float));
const cl_uint sk3 = (cl_uint)(src_k->nb[3] / sizeof(float));
const cl_uint sv1 = (cl_uint)(src_v->nb[1] / sizeof(float));
const cl_uint sv2 = (cl_uint)(src_v->nb[2] / sizeof(float));
const cl_uint sv3 = (cl_uint)(src_v->nb[3] / sizeof(float));
@@ -40567,6 +40717,9 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) {
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq1));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq2));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq3));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk1));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk2));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk3));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv1));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv2));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv3));
@@ -40576,7 +40729,59 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) {
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &H_k));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &rq3));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(float), &scale));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &K));
if (replay) {
const ggml_tensor * src_pk = dst->src[6];
const ggml_tensor * src_pv = dst->src[7];
const ggml_tensor * src_pgb = dst->src[8];
const ggml_tensor * src_rep = dst->src[9];
GGML_ASSERT(src_pk && src_pk->extra);
GGML_ASSERT(src_pv && src_pv->extra);
GGML_ASSERT(src_pgb && src_pgb->extra);
GGML_ASSERT(src_rep && src_rep->extra);
const ggml_tensor_extra_cl * extra_pk = (const ggml_tensor_extra_cl *) src_pk->extra;
const ggml_tensor_extra_cl * extra_pv = (const ggml_tensor_extra_cl *) src_pv->extra;
const ggml_tensor_extra_cl * extra_pgb = (const ggml_tensor_extra_cl *) src_pgb->extra;
const ggml_tensor_extra_cl * extra_rep = (const ggml_tensor_extra_cl *) src_rep->extra;
const cl_ulong off_pk = extra_pk->offset + src_pk->view_offs;
const cl_ulong off_pv = extra_pv->offset + src_pv->view_offs;
const cl_ulong off_pgb = extra_pgb->offset + src_pgb->view_offs;
const cl_ulong off_rep = extra_rep->offset + src_rep->view_offs;
const cl_ulong spk1 = src_pk->nb[1] / sizeof(float);
const cl_ulong spk2 = src_pk->nb[2] / sizeof(float);
const cl_ulong spk3 = src_pk->nb[3] / sizeof(float);
const cl_ulong spv1 = src_pv->nb[1] / sizeof(float);
const cl_ulong spv2 = src_pv->nb[2] / sizeof(float);
const cl_ulong spv3 = src_pv->nb[3] / sizeof(float);
const cl_ulong spg1 = src_pgb->nb[1] / sizeof(float);
const cl_ulong spg2 = src_pgb->nb[2] / sizeof(float);
const cl_ulong spg3 = src_pgb->nb[3] / sizeof(float);
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &n_pend));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &keep));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pk->data_device));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pk));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk1));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk2));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk3));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pv->data_device));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pv));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv1));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv2));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv3));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pgb->data_device));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pgb));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg1));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg2));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg3));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_rep->data_device));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_rep));
}
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &K));
// Subgroup size is 64 for Adreno and 32 for Intel
const int sg_size = backend_ctx->gpu_family == GPU_FAMILY::ADRENO ? 64 : backend_ctx->gpu_family == GPU_FAMILY::INTEL ? 32 : -1;
@@ -18,6 +18,9 @@
#ifndef KDA
#define KDA 0
#endif
#ifndef REPLAY
#define REPLAY 0
#endif
#ifndef SUBGROUP_SIZE
#define SUBGROUP_SIZE 64
#endif
@@ -92,11 +95,19 @@ kernel void kernel_gated_delta_net(
uint n_seqs,
uint s_off,
uint sq1, uint sq2, uint sq3,
uint sk1, uint sk2, uint sk3,
uint sv1, uint sv2, uint sv3,
uint sb1, uint sb2, uint sb3,
uint H_k,
uint rq3,
float scale,
#if REPLAY
uint n_pend, uint keep,
global const char * pk_buf, ulong off_pk, ulong spk1, ulong spk2, ulong spk3,
global const char * pv_buf, ulong off_pv, ulong spv1, ulong spv2, ulong spv3,
global const char * pgb_buf, ulong off_pgb, ulong spg1, ulong spg2, ulong spg3,
global const char * rep_buf, ulong off_rep,
#endif
uint K) {
global const float * data_q = (global const float *)(q_buf + off_q);
@@ -126,6 +137,7 @@ kernel void kernel_gated_delta_net(
// input state holds s0 only [S_v, S_v, H, n_seqs]: per-seq stride is H*D.
const uint state_base = (seq_id * H_v + head_id) * state_size;
const uint q_off_base = iq3 * sq3 + iq1 * sq1;
const uint k_off_base = iq3 * sk3 + iq1 * sk1;
const uint v_off_base = seq_id * sv3 + head_id * sv1;
const uint gb_off_base = seq_id * sb3 + head_id * sb1;
const uint state_out_base = (seq_id * H_v + head_id) * state_size;
@@ -144,13 +156,84 @@ kernel void kernel_gated_delta_net(
}
}
#if REPLAY
global const float * data_pk = (global const float *)(pk_buf + off_pk);
global const float * data_pv = (global const float *)(pv_buf + off_pv);
global const float * data_pgb = (global const float *)(pgb_buf + off_pgb);
global const int * data_n_rep = (global const int *)(rep_buf + off_rep);
const uint n_r = (uint)clamp(data_n_rep[seq_id], 0, (int)n_pend);
for (uint t = 0; t < n_r; t++) {
const ulong k_off = seq_id * spk3 + t * spk2 + iq1 * spk1;
const ulong v_off = seq_id * spv3 + t * spv2 + head_id * spv1;
const ulong g_off = seq_id * spg3 + t * spg2 + head_id * spg1;
const float beta_val = data_pgb[g_off + n_pend * spg2];
float k_reg[ROWS_PER_LANE];
#pragma unroll
for (uint r = 0; r < ROWS_PER_LANE; r++) {
k_reg[r] = data_pk[k_off + r * LANES_PER_COLUMN + lane];
}
#if KDA
float g_exp[ROWS_PER_LANE];
#pragma unroll
for (uint r = 0; r < ROWS_PER_LANE; r++) {
g_exp[r] = exp(data_pgb[g_off + r * LANES_PER_COLUMN + lane]);
}
#else
const float g_val = exp(data_pgb[g_off]);
#endif
// Same state update as the main loop, without the attention output.
#pragma unroll
for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) {
const uint col = sg_col_base + cg * LANE_GROUPS_PER_SG + lane_group;
float kv_shard = 0.0f;
#pragma unroll
for (uint r = 0; r < ROWS_PER_LANE; r++) {
#if KDA
kv_shard += g_exp[r] * s_shard[cg][r] * k_reg[r];
#else
kv_shard += s_shard[cg][r] * k_reg[r];
#endif
}
#if !KDA
kv_shard *= g_val;
#endif
const float kv_col = REDUCE_PARTIAL(kv_shard, temp_ptr, sg_lid);
const float delta_col = (data_pv[v_off + col] - kv_col) * beta_val;
#pragma unroll
for (uint r = 0; r < ROWS_PER_LANE; r++) {
#if KDA
const float gs = g_exp[r] * s_shard[cg][r];
#else
const float gs = g_val * s_shard[cg][r];
#endif
s_shard[cg][r] = gs + k_reg[r] * delta_col;
}
}
}
if (keep) {
#pragma unroll
for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) {
const uint col = sg_col_base + cg * LANE_GROUPS_PER_SG + lane_group;
#pragma unroll
for (uint r = 0; r < ROWS_PER_LANE; r++) {
data_dst[s_off + state_base + col * S_V + r * LANES_PER_COLUMN + lane] = s_shard[cg][r];
}
}
}
#endif
// snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back.
// When n_tokens < K only slots 0..n_tokens-1 are written; older slots are caller-owned.
uint attn_off = (seq_id * n_tokens * H_v + head_id) * S_V;
for (uint t = 0; t < n_tokens; t++) {
const uint q_off = q_off_base + t * sq2;
const uint k_off = q_off;
const uint k_off = k_off_base + t * sk2;
const uint v_off = v_off_base + t * sv2;
const uint gb_off = gb_off_base + t * sb2;
const float beta_val = data_beta[gb_off];
@@ -236,6 +319,11 @@ kernel void kernel_gated_delta_net(
}
}
#if REPLAY
if (keep) {
return;
}
#endif
if (K == 1u) {
#pragma unroll
for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) {
@@ -0,0 +1,214 @@
#pragma OPENCL EXTENSION cl_khr_fp16 : enable
#ifdef cl_khr_integer_dot_product
#pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable
#endif
#ifndef COOPK_NSG
#define COOPK_NSG 4
#endif
#define COK_SG 64
#define COK_ROWS 4
#define COK_PACK4(a, b, c, e) \
( ((uint)(a) & 0xFFu) | (((uint)(b) & 0xFFu) << 8) \
| (((uint)(c) & 0xFFu) << 16) | (((uint)(e) & 0xFFu) << 24) )
// Pack (0, 2, 1, 3) K bytes and store scales plus both 16-value sums at width eight.
kernel void kernel_quant_a_q8_1_k4h(
global const float * src,
global uint * qa,
global half * ds,
ulong offset_src,
int total_blocks,
int k_b
) {
const int blk = get_global_id(0);
if (blk >= 8 * k_b) {
return;
}
const int col = blk / k_b;
const int b = blk % k_b;
if (blk >= total_blocks) {
vstore8((uint8)(0), 0, qa + blk * 8);
ds[(3 * b) * 8 + col] = (half)0;
ds[(3 * b + 1) * 8 + col] = (half)0;
ds[(3 * b + 2) * 8 + col] = (half)0;
return;
}
src = (global const float *)((global const char *)src + offset_src);
const int base = blk * 32;
float v[32];
float amax = 0.0f;
#pragma unroll
for (int i = 0; i < 32; ++i) {
v[i] = src[base + i];
amax = fmax(amax, fabs(v[i]));
}
const float d = amax / 127.0f;
const float id = (amax > 0.0f) ? (127.0f / amax) : 0.0f;
int q[32];
int sum_lo = 0, sum_hi = 0;
#pragma unroll
for (int i = 0; i < 16; ++i) {
q[i] = (int)rint(v[i] * id);
sum_lo += q[i];
}
#pragma unroll
for (int i = 16; i < 32; ++i) {
q[i] = (int)rint(v[i] * id);
sum_hi += q[i];
}
uint8 out;
out.s0 = COK_PACK4(q[ 0], q[ 2], q[ 1], q[ 3]);
out.s1 = COK_PACK4(q[ 4], q[ 6], q[ 5], q[ 7]);
out.s2 = COK_PACK4(q[ 8], q[10], q[ 9], q[11]);
out.s3 = COK_PACK4(q[12], q[14], q[13], q[15]);
out.s4 = COK_PACK4(q[16], q[18], q[17], q[19]);
out.s5 = COK_PACK4(q[20], q[22], q[21], q[23]);
out.s6 = COK_PACK4(q[24], q[26], q[25], q[27]);
out.s7 = COK_PACK4(q[28], q[30], q[29], q[31]);
vstore8(out, 0, qa + blk * 8);
ds[(3 * b) * 8 + col] = (half)d;
ds[(3 * b + 1) * 8 + col] = (half)(d * (float)sum_lo);
ds[(3 * b + 2) * 8 + col] = (half)(d * (float)sum_hi);
}
// Cast before shifting to keep all four K values on Adreno compilers.
#define COK_LO(u) (((uint)(u) | ((uint)(ushort)((u) >> 4) << 16)) & 0x0F0F0F0Fu)
#define COK_HI(h) ((((((uint)(h)) & 0x33u) * 0x110u) & 0x3030u) | (((((uint)(h)) & 0xCCu) * 0x440000u) & 0x30300000u))
#define COK_UNPACK(r) \
const uint w0_##r = COK_LO(bl0.s##r) | COK_HI(bh0.s##r); \
const uint w1_##r = COK_LO(bl1.s##r) | COK_HI(bh1.s##r); \
const uint w2_##r = COK_LO(bl2.s##r) | COK_HI(bh2.s##r); \
const uint w3_##r = COK_LO(bl3.s##r) | COK_HI(bh3.s##r);
#define COK_DOT_RC(r, c) \
d##r.s##c = dot_acc_sat_4x8packed_ss_int(w0_##r, A.s0, d##r.s##c); \
d##r.s##c = dot_acc_sat_4x8packed_ss_int(w1_##r, A.s1, d##r.s##c); \
d##r.s##c = dot_acc_sat_4x8packed_ss_int(w2_##r, A.s2, d##r.s##c); \
d##r.s##c = dot_acc_sat_4x8packed_ss_int(w3_##r, A.s3, d##r.s##c);
#define COK_DOT_COL(c, t) \
{ const uint4 A = read_imageui(src1_qa, (c) * k_t + (t)); \
COK_DOT_RC(0, c) COK_DOT_RC(1, c) COK_DOT_RC(2, c) COK_DOT_RC(3, c) }
kernel void kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8(
global const uint * src0_ql,
global const uint * src0_qh,
global const ushort * src0_s,
global const half * src0_d,
read_only image1d_buffer_t src1_qa,
read_only image1d_buffer_t src1_ds,
global float * dst,
ulong offsetd,
int m,
int k,
int n_no_padding,
uchar mask_c0,
int ksplit
) {
dst = (global float *)((global char *)dst + offsetd);
const int gx = get_global_id(0);
const int sg = get_local_id(1);
const int lane = get_local_id(0);
const int ks = get_group_id(1);
const bool live = gx * COK_ROWS < m;
const int row0 = live ? gx * COK_ROWS : m - COK_ROWS;
const int num_32blk = k / 32;
const int k_t = k >> 4;
const int fence = (int)(mask_c0 >> 6) - 3;
const int nslice = ksplit * COOPK_NSG;
const int b_beg = ks * COOPK_NSG + sg;
float8 acc0 = (float8)(0.0f), acc1 = (float8)(0.0f);
float8 acc2 = (float8)(0.0f), acc3 = (float8)(0.0f);
for (int bg = b_beg; bg * 8 < num_32blk; bg += nslice) {
ushort8 sr0 = vload8(0, src0_s + (row0 + 0) * num_32blk + bg * 8);
ushort8 sr1 = vload8(0, src0_s + (row0 + 1) * num_32blk + bg * 8);
ushort8 sr2 = vload8(0, src0_s + (row0 + 2) * num_32blk + bg * 8);
ushort8 sr3 = vload8(0, src0_s + (row0 + 3) * num_32blk + bg * 8);
for (int jb = 0; jb < 8; ++jb) {
const int blk = bg * 8 + jb;
const ushort4 spk = (ushort4)(sr0.s0, sr1.s0, sr2.s0, sr3.s0);
sr0 = sr0.s12345670; sr1 = sr1.s12345670; sr2 = sr2.s12345670; sr3 = sr3.s12345670;
const half4 scd = vload4(0, src0_d + row0 + (blk >> 3) * m);
const float8 da = convert_float8(as_half8(read_imageui(src1_ds, 3 * blk)));
for (int h = 0; h < 2; ++h) {
const int g0 = (blk << 3) + (h << 2);
const int at = (blk << 1) + h;
const uint4 l01 = vload4(0, src0_ql + row0 + ((g0 >> 1) ) * m);
const uint4 l23 = vload4(0, src0_ql + row0 + ((g0 >> 1) + 1) * m);
const uint4 hq = vload4(0, src0_qh + row0 + (g0 >> 2) * m);
const ushort4 bl0 = (ushort4)((ushort)l01.s0, (ushort)l01.s1, (ushort)l01.s2, (ushort)l01.s3);
const ushort4 bl1 = (ushort4)((ushort)(l01.s0 >> 16), (ushort)(l01.s1 >> 16), (ushort)(l01.s2 >> 16), (ushort)(l01.s3 >> 16));
const ushort4 bl2 = (ushort4)((ushort)l23.s0, (ushort)l23.s1, (ushort)l23.s2, (ushort)l23.s3);
const ushort4 bl3 = (ushort4)((ushort)(l23.s0 >> 16), (ushort)(l23.s1 >> 16), (ushort)(l23.s2 >> 16), (ushort)(l23.s3 >> 16));
const uchar4 bh0 = (uchar4)((uchar)hq.s0, (uchar)hq.s1, (uchar)hq.s2, (uchar)hq.s3);
const uchar4 bh1 = (uchar4)((uchar)(hq.s0 >> 8), (uchar)(hq.s1 >> 8), (uchar)(hq.s2 >> 8), (uchar)(hq.s3 >> 8));
const uchar4 bh2 = (uchar4)((uchar)(hq.s0 >> 16), (uchar)(hq.s1 >> 16), (uchar)(hq.s2 >> 16), (uchar)(hq.s3 >> 16));
const uchar4 bh3 = (uchar4)((uchar)(hq.s0 >> 24), (uchar)(hq.s1 >> 24), (uchar)(hq.s2 >> 24), (uchar)(hq.s3 >> 24));
COK_UNPACK(0) COK_UNPACK(1) COK_UNPACK(2) COK_UNPACK(3)
int8 d0 = (int8)(0), d1 = (int8)(0), d2 = (int8)(0), d3 = (int8)(0);
COK_DOT_COL(0, at) COK_DOT_COL(1, at) COK_DOT_COL(2, at) COK_DOT_COL(3, at)
const int at4 = at + (d0.s0 & fence);
COK_DOT_COL(4, at4) COK_DOT_COL(5, at4) COK_DOT_COL(6, at4) COK_DOT_COL(7, at4)
const float8 sa = convert_float8(as_half8(read_imageui(src1_ds, 3 * blk + 1 + h)));
// Apply the signed-code offset with the sum for this 16-value half.
const float8 sm = sa * -32.0f;
const float s0f = (float)(h ? as_char2(spk.s0).s1 : as_char2(spk.s0).s0) * (float)scd.s0;
const float s1f = (float)(h ? as_char2(spk.s1).s1 : as_char2(spk.s1).s0) * (float)scd.s1;
const float s2f = (float)(h ? as_char2(spk.s2).s1 : as_char2(spk.s2).s0) * (float)scd.s2;
const float s3f = (float)(h ? as_char2(spk.s3).s1 : as_char2(spk.s3).s0) * (float)scd.s3;
acc0 = mad(mad(da, convert_float8(d0), sm), s0f, acc0);
acc1 = mad(mad(da, convert_float8(d1), sm), s1f, acc1);
acc2 = mad(mad(da, convert_float8(d2), sm), s2f, acc2);
acc3 = mad(mad(da, convert_float8(d3), sm), s3f, acc3);
}
}
}
local float8 reduceLM[COK_SG * (COOPK_NSG - 1)];
float8 out0 = (float8)(0.0f), out1 = (float8)(0.0f);
float8 out2 = (float8)(0.0f), out3 = (float8)(0.0f);
#define COK_REDUCE(accv, outv) \
barrier(CLK_LOCAL_MEM_FENCE); \
if (sg > 0) { reduceLM[(sg - 1) * COK_SG + lane] = (accv); } \
barrier(CLK_LOCAL_MEM_FENCE); \
if (sg == 0) { \
float8 sum = (accv); \
for (int s = 0; s < COOPK_NSG - 1; s++) { sum += reduceLM[s * COK_SG + lane]; } \
(outv) = sum; \
}
COK_REDUCE(acc0, out0)
COK_REDUCE(acc1, out1)
COK_REDUCE(acc2, out2)
COK_REDUCE(acc3, out3)
#undef COK_REDUCE
#define COK_STORE_COL(c) \
if ((c) < n_no_padding) { \
vstore4((float4)(out0.s##c, out1.s##c, out2.s##c, out3.s##c), 0, dst + (c) * m + row0); \
}
if (sg == 0 && live) {
dst += (size_t)ks * (size_t)m * (size_t)n_no_padding;
COK_STORE_COL(0) COK_STORE_COL(1) COK_STORE_COL(2) COK_STORE_COL(3)
COK_STORE_COL(4) COK_STORE_COL(5) COK_STORE_COL(6) COK_STORE_COL(7)
}
#undef COK_STORE_COL
}
+46 -6
View File
@@ -4,6 +4,46 @@
// softplus
//------------------------------------------------------------------------------
inline float op_log1p(float x) {
const float y = x / (2.0f + x);
const float y2 = y * y;
float p = 1.0f / 13.0f;
p = p * y2 + 1.0f / 11.0f;
p = p * y2 + 1.0f / 9.0f;
p = p * y2 + 1.0f / 7.0f;
p = p * y2 + 1.0f / 5.0f;
p = p * y2 + 1.0f / 3.0f;
p = p * y2 + 1.0f;
const float s = 2.0f * y * p;
const float l = log(1.0f + x);
const float r = select(l, s, (x >= -0.5f) & (x <= 1.0f));
return select(r, x, fabs(x) < 2.5e-38f);
}
inline float4 op_log1p4(float4 x) {
const float4 y = x / ((float4)(2.0f) + x);
const float4 y2 = y * y;
float4 p = (float4)(1.0f / 13.0f);
p = p * y2 + (float4)(1.0f / 11.0f);
p = p * y2 + (float4)(1.0f / 9.0f);
p = p * y2 + (float4)(1.0f / 7.0f);
p = p * y2 + (float4)(1.0f / 5.0f);
p = p * y2 + (float4)(1.0f / 3.0f);
p = p * y2 + (float4)(1.0f);
const float4 s = (float4)(2.0f) * y * p;
const float4 l = log((float4)(1.0f) + x);
const float4 r = select(l, s, (x >= (float4)(-0.5f)) & (x <= (float4)(1.0f)));
return select(r, x, fabs(x) < (float4)(2.5e-38f));
}
inline float softplus_f32(float x) {
return select(op_log1p(exp(x)), x, x > 20.0f);
}
inline float4 softplus_f32_4(float4 x) {
return select(op_log1p4(exp(x)), x, x > (float4)(20.0f));
}
kernel void kernel_softplus_f32(
global const float * src0,
ulong offset0,
@@ -13,7 +53,7 @@ kernel void kernel_softplus_f32(
src0 = (global float*)((global char*)src0 + offset0);
dst = (global float*)((global char*)dst + offsetd);
dst[get_global_id(0)] = (src0[get_global_id(0)] > 20.0f) ? src0[get_global_id(0)] : log(1.0f + exp(src0[get_global_id(0)]));
dst[get_global_id(0)] = softplus_f32(src0[get_global_id(0)]);
}
kernel void kernel_softplus_f32_4(
@@ -25,7 +65,7 @@ kernel void kernel_softplus_f32_4(
src0 = (global float4*)((global char*)src0 + offset0);
dst = (global float4*)((global char*)dst + offsetd);
dst[get_global_id(0)] = (src0[get_global_id(0)] > 20.0f) ? src0[get_global_id(0)] : log(1.0f + exp(src0[get_global_id(0)]));
dst[get_global_id(0)] = softplus_f32_4(src0[get_global_id(0)]);
}
kernel void kernel_softplus_f16(
@@ -38,7 +78,7 @@ kernel void kernel_softplus_f16(
dst = (global half*)((global char*)dst + offsetd);
const float x = convert_float(src0[get_global_id(0)]);
dst[get_global_id(0)] = convert_half_rte((x > 20.0f) ? x : log(1.0f + exp(x)));
dst[get_global_id(0)] = convert_half_rte(softplus_f32(x));
}
kernel void kernel_softplus_f16_4(
@@ -51,7 +91,7 @@ kernel void kernel_softplus_f16_4(
dst = (global half4*)((global char*)dst + offsetd);
const float4 x = convert_float4(src0[get_global_id(0)]);
dst[get_global_id(0)] = convert_half4_rte((x > 20.0f) ? x : log(1.0f + exp(x)));
dst[get_global_id(0)] = convert_half4_rte(softplus_f32_4(x));
}
kernel void kernel_softplus_f32_nc(
@@ -80,7 +120,7 @@ kernel void kernel_softplus_f32_nc(
global const float * x = (global const float *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
global float * y = (global float *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
*y = (*x > 20.0f) ? *x : log(1.0f + exp(*x));
*y = softplus_f32(*x);
}
}
@@ -111,6 +151,6 @@ kernel void kernel_softplus_f16_nc(
global half * hy = (global half *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
const float x = convert_float(*hx);
*hy = convert_half_rte((x > 20.0f) ? x : log(1.0f + exp(x)));
*hy = convert_half_rte(softplus_f32(x));
}
}
+7
View File
@@ -1929,6 +1929,10 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
return {false, "FLASH_ATTN_EXT gemma3n pattern is not supported"};
}
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
return {false, "FLASH_ATTN_EXT with indexed bias is not supported"};
}
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
if (op->src[5] != nullptr) {
return {false, "FLASH_ATTN_EXT with K/V row lists is not supported"};
@@ -2109,6 +2113,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
}
return {false, reason};
}
if (((const int32_t *) op->op_params)[1] != 0) {
return {false, "GATED_DELTA_NET with replay of pending tokens is not supported"};
}
break;
}
case GGML_OP_SSM_SCAN: {
+35 -98
View File
@@ -1561,6 +1561,13 @@ public:
: backends(std::move(all_backends)), cache_dir(cache_dir) {
stored_graphs.resize(backends.size());
comm_states.resize(backends.size());
ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead()*(1 + GGML_MAX_SRC),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
req_ctx.reset(ggml_init(params));
GGML_ASSERT(req_ctx != nullptr);
}
~rpc_server();
@@ -1593,6 +1600,16 @@ public:
};
private:
// empty context for the tensors of one request, valid until the next call
ggml_context * request_ctx() {
ggml_reset(req_ctx.get());
return req_ctx.get();
}
// nullptr if the buffer was not allocated by this server
ggml_backend_buffer_t find_buffer(uint64_t remote_ptr) const {
ggml_backend_buffer_t buffer = reinterpret_cast<ggml_backend_buffer_t>(remote_ptr);
return buffers.find(buffer) != buffers.end() ? buffer : nullptr;
}
void sync_all_backends();
void comm_free_device(uint32_t dev_id);
static bool comm_allreduce_pairwise(void * comm_ctx_v, ggml_tensor ** tensors);
@@ -1631,6 +1648,7 @@ private:
std::vector<comm_state> comm_states;
// SET_TENSOR data is received in chunks through this buffer
std::vector<uint8_t> set_tensor_buf;
ggml_context_ptr req_ctx;
};
void rpc_server::hello(rpc_msg_hello_rsp & response) {
@@ -1647,15 +1665,7 @@ bool rpc_server::get_alloc_size(const rpc_msg_get_alloc_size_req & request, rpc_
return false;
}
ggml_backend_buffer_type_t buft;
struct ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead()*(1 + GGML_MAX_SRC),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_context * ctx = request_ctx();
ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor);
if (tensor == nullptr) {
@@ -1733,8 +1743,8 @@ bool rpc_server::get_max_size(const rpc_msg_get_max_size_req & request, rpc_msg_
bool rpc_server::buffer_get_base(const rpc_msg_buffer_get_base_req & request, rpc_msg_buffer_get_base_rsp & response) {
LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 "\n", __func__, request.remote_ptr);
ggml_backend_buffer_t buffer = reinterpret_cast<ggml_backend_buffer_t>(request.remote_ptr);
if (buffers.find(buffer) == buffers.end()) {
ggml_backend_buffer_t buffer = find_buffer(request.remote_ptr);
if (buffer == nullptr) {
LOG_ERROR("[%s] buffer not found\n", __func__);
return false;
}
@@ -1746,8 +1756,8 @@ bool rpc_server::buffer_get_base(const rpc_msg_buffer_get_base_req & request, rp
bool rpc_server::free_buffer(const rpc_msg_free_buffer_req & request) {
sync_all_backends();
LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 "\n", __func__, request.remote_ptr);
ggml_backend_buffer_t buffer = reinterpret_cast<ggml_backend_buffer_t>(request.remote_ptr);
if (buffers.find(buffer) == buffers.end()) {
ggml_backend_buffer_t buffer = find_buffer(request.remote_ptr);
if (buffer == nullptr) {
LOG_ERROR("[%s] buffer not found\n", __func__);
return false;
}
@@ -1767,8 +1777,8 @@ bool rpc_server::free_buffer(const rpc_msg_free_buffer_req & request) {
bool rpc_server::buffer_clear(const rpc_msg_buffer_clear_req & request) {
sync_all_backends();
LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 ", value: %u\n", __func__, request.remote_ptr, request.value);
ggml_backend_buffer_t buffer = reinterpret_cast<ggml_backend_buffer_t>(request.remote_ptr);
if (buffers.find(buffer) == buffers.end()) {
ggml_backend_buffer_t buffer = find_buffer(request.remote_ptr);
if (buffer == nullptr) {
LOG_ERROR("[%s] buffer not found\n", __func__);
return false;
}
@@ -1778,15 +1788,7 @@ bool rpc_server::buffer_clear(const rpc_msg_buffer_clear_req & request) {
bool rpc_server::memset_tensor(const rpc_msg_memset_tensor_req & request) {
sync_all_backends();
struct ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor);
ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor);
if (!rpc_check_region(__func__, tensor, request.offset, request.size)) {
return false;
}
@@ -1830,10 +1832,7 @@ ggml_tensor * rpc_server::deserialize_tensor(struct ggml_context * ctx, const rp
return nullptr;
}
ggml_backend_buffer_t buffer = reinterpret_cast<ggml_backend_buffer_t>(tensor->buffer);
if (buffer && buffers.find(buffer) == buffers.end()) {
buffer = nullptr;
}
ggml_backend_buffer_t buffer = find_buffer(tensor->buffer);
if (buffer && nbytes > 0 && !rpc_in_buffer(buffer, tensor->data, nbytes)) {
LOG_ERROR("[%s] tensor '%.*s' (op %s, type %s) data 0x%" PRIx64 " with size %" PRIu64 " out of buffer bounds "
"(base %p, size %zu)\n", __func__, (int) sizeof(tensor->name), tensor->name, ggml_op_name((ggml_op) tensor->op),
@@ -1868,15 +1867,7 @@ bool rpc_server::set_tensor(socket_ptr sock, uint64_t input_size) {
const uint64_t offset = request.offset;
const size_t size = input_size - sizeof(request);
struct ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor);
ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor);
if (!rpc_check_region(__func__, tensor, offset, size)) {
return false;
}
@@ -1927,15 +1918,7 @@ bool rpc_server::set_tensor_2d(const std::vector<uint8_t> & input) {
return false;
}
struct ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor);
ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor);
if (!rpc_check_region(__func__, tensor, request.offset, request.size, request.n_copies, request.stride)) {
return false;
}
@@ -1975,15 +1958,7 @@ bool rpc_server::get_cached_file(uint64_t hash, std::vector<uint8_t> & data) {
bool rpc_server::set_tensor_hash(const rpc_msg_set_tensor_hash_req & request, rpc_msg_set_tensor_hash_rsp & response)
{
sync_all_backends();
struct ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor);
ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor);
if (!rpc_check_region(__func__, tensor, request.offset, 0)) {
return false;
}
@@ -2010,15 +1985,7 @@ bool rpc_server::set_tensor_hash(const rpc_msg_set_tensor_hash_req & request, rp
bool rpc_server::init_tensor(const rpc_msg_init_tensor_req & request) {
sync_all_backends();
struct ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor);
ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor);
if (tensor == nullptr) {
LOG_ERROR("Null tensor pointer passed to server init_tensor function.\n");
return false;
@@ -2047,15 +2014,7 @@ bool rpc_server::init_tensor(const rpc_msg_init_tensor_req & request) {
bool rpc_server::get_tensor(const rpc_msg_get_tensor_req & request, std::vector<uint8_t> & response) {
sync_all_backends();
struct ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor);
ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor);
if (!rpc_check_region(__func__, tensor, request.offset, request.size)) {
return false;
}
@@ -2070,15 +2029,7 @@ bool rpc_server::get_tensor(const rpc_msg_get_tensor_req & request, std::vector<
bool rpc_server::get_tensor_2d(const rpc_msg_tensor_2d_req & request, std::vector<uint8_t> & response) {
sync_all_backends();
struct ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor);
ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor);
if (!rpc_check_region(__func__, tensor, request.offset, request.size, request.n_copies, request.stride)) {
return false;
}
@@ -2093,14 +2044,7 @@ bool rpc_server::get_tensor_2d(const rpc_msg_tensor_2d_req & request, std::vecto
bool rpc_server::copy_tensor(const rpc_msg_copy_tensor_req & request, rpc_msg_copy_tensor_rsp & response) {
sync_all_backends();
struct ggml_init_params params {
/*.mem_size =*/ 2*ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_context * ctx = request_ctx();
ggml_tensor * src = deserialize_tensor(ctx, &request.src);
ggml_tensor * dst = deserialize_tensor(ctx, &request.dst);
@@ -2559,14 +2503,7 @@ bool rpc_server::comm_allreduce(const rpc_msg_comm_allreduce_req & request) {
return false;
}
struct ggml_init_params params = {
/*.mem_size =*/ ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_tensor * t_dst = deserialize_tensor(ctx_ptr.get(), &request.tensor);
ggml_tensor * t_dst = deserialize_tensor(request_ctx(), &request.tensor);
if (t_dst == nullptr || t_dst->buffer == nullptr) {
LOG_ERROR("[%s] error deserializing tensor\n", __func__);
return false;
+5 -3
View File
@@ -7709,10 +7709,12 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons
case GGML_OP_RWKV_WKV6:
case GGML_OP_RWKV_WKV7:
case GGML_OP_GATED_LINEAR_ATTN:
case GGML_OP_GATED_DELTA_NET:
case GGML_OP_OPT_STEP_ADAMW:
case GGML_OP_OPT_STEP_SGD:
return true;
case GGML_OP_GATED_DELTA_NET:
// replay of pending tokens (op param 1) is not implemented
return ggml_get_op_params_i32(op, 1) == 0;
case GGML_OP_SSM_CONV:
return op->type == GGML_TYPE_F32 &&
op->src[0]->type == GGML_TYPE_F32 &&
@@ -7741,8 +7743,8 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons
case GGML_OP_SOLVE_TRI:
return op->src[0]->ne[0] <= SYCL_SOLVE_TRI_MAX_N && op->src[1]->ne[0] <= SYCL_SOLVE_TRI_MAX_K;
case GGML_OP_FLASH_ATTN_EXT:
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
return op->src[5] == nullptr && ggml_sycl_flash_attn_ext_supported(device, op);
// K/V row lists and indexed bias are not supported
return op->src[5] == nullptr && !ggml_flash_attn_ext_has_indexed_bias(op) && ggml_sycl_flash_attn_ext_supported(device, op);
default:
return false;
}
@@ -30,6 +30,10 @@ static void ggml_backend_remoting_device_get_memory(ggml_backend_dev_t dev, size
}
static bool ggml_backend_remoting_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
if ((op->op == GGML_OP_ROPE || op->op == GGML_OP_ROPE_BACK) &&
!ggml_rope_get_truncate(op)) {
return false;
+4 -3
View File
@@ -1370,9 +1370,10 @@ void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph
} else if (tensor->op == GGML_OP_LIGHTNING_INDEXER) {
tensor_clone = ggml_lightning_indexer(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3]);
} else if (tensor->op == GGML_OP_GATED_DELTA_NET) {
tensor_clone = ggml_gated_delta_net(ggml_ctx, src_clone[0], src_clone[1],
src_clone[2], src_clone[3], src_clone[4], src_clone[5],
ggml_get_op_params_i32(tensor, 0));
GGML_ASSERT(ggml_get_op_params_i32(tensor, 0) == 1); // K > 1 comes from the deprecated ggml_gated_delta_net
tensor_clone = ggml_gated_delta_net_ext(ggml_ctx, src_clone[0], src_clone[1],
src_clone[2], src_clone[3], src_clone[4], src_clone[5], src_clone[6], src_clone[7], src_clone[8], src_clone[9],
ggml_get_op_params_i32(tensor, 2) != 0);
} else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
src_clone[0]->flags = tensor->src[0]->flags;
tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
@@ -794,6 +794,10 @@ struct vk_op_gated_delta_net_push_constants {
uint32_t neq1, rq3;
float scale;
uint32_t K;
uint32_t n_pend, keep; // replay: pending tokens per seq, write the state after the replay
uint32_t spk1, spk2, spk3; // replay: pend_k, pend_v and pend_gb strides in floats
uint32_t spv1, spv2, spv3;
uint32_t spg1, spg2, spg3;
};
struct vk_op_ssm_scan_push_constants {
+3 -2
View File
@@ -1013,11 +1013,12 @@ struct vk_device_struct {
vk_pipeline pipeline_rwkv_wkv7_f32;
vk_pipeline pipeline_gated_linear_attn_f32;
vk_pipeline pipeline_lightning_indexer_f32[GGML_TYPE_COUNT];
// [size_idx][kda] where size_idx: 0=d16, 1=d32, 2=d64, 3=d128
vk_pipeline pipeline_gated_delta_net[4][2];
// [size_idx][kda][replay] where size_idx: 0=d16, 1=d32, 2=d64, 3=d128
vk_pipeline pipeline_gated_delta_net[4][2][2];
vk_pipeline pipeline_gated_delta_net_cm;
vk_pipeline pipeline_gated_delta_net_cm_v32;
vk_pipeline pipeline_gated_delta_net_cm_v128;
vk_pipeline pipeline_ssm_scan_f32_d96;
vk_pipeline pipeline_ssm_scan_f32_d128;
vk_pipeline pipeline_ssm_scan_f32_d256;
vk_pipeline pipeline_ssm_conv_f32;
+55 -23
View File
@@ -4212,9 +4212,12 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
const std::array<uint32_t, 3> wg_denoms = {1u, 1u, cols_per_wg};
for (uint32_t kda = 0; kda < 2; kda++) {
ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net[si][kda],
gdn_names[si][kda], gdn_len, gdn_data, "main", 7, sizeof(vk_op_gated_delta_net_push_constants),
wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column, uint32_t(gdn_packed_rows)}, 1, true, use_subgroup_ops, gdn_subgroup_size);
for (uint32_t rep = 0; rep < 2; rep++) {
const std::string name = std::string(gdn_names[si][kda]) + (rep ? "_rep" : "");
ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net[si][kda][rep],
name.c_str(), gdn_len, gdn_data, "main", 11, sizeof(vk_op_gated_delta_net_push_constants),
wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column, uint32_t(gdn_packed_rows), rep}, 1, true, use_subgroup_ops, gdn_subgroup_size);
}
}
}
@@ -4270,12 +4273,15 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
GGML_UNUSED(gdn_shmem);
}
// Pad 96 states to a 128-thread workgroup for 32- and 64-lane subgroups.
if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size}, 1, true, true);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size}, 1, true, true);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d96, "ssm_scan_96_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 96}, 1, true, true);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 128}, 1, true, true);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 256}, 1, true, true);
} else {
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 16}, 1, true, true);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 16}, 1, true, true);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d96, "ssm_scan_96_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 96}, 1, true, true);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 128}, 1, true, true);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 256}, 1, true, true);
}
ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_f32, "ssm_conv_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 0, 0}, 1);
@@ -10235,6 +10241,7 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const
if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
const uint32_t S_v = dst->src[2]->ne[0];
const uint32_t kda = (dst->src[3]->ne[0] == (int64_t)S_v) ? 1 : 0;
const uint32_t rep = dst->src[6] != nullptr ? 1 : 0;
uint32_t si;
switch (S_v) {
case 16: si = 0; break;
@@ -10243,13 +10250,15 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const
case 128: si = 3; break;
default: return nullptr;
}
return ctx->device->pipeline_gated_delta_net[si][kda];
return ctx->device->pipeline_gated_delta_net[si][kda][rep];
}
return nullptr;
case GGML_OP_SSM_SCAN:
if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
const uint32_t d_state = src0->ne[0];
if (d_state == 128) {
if (d_state == 96) {
return ctx->device->pipeline_ssm_scan_f32_d96;
} else if (d_state == 128) {
return ctx->device->pipeline_ssm_scan_f32_d128;
} else if (d_state == 256) {
return ctx->device->pipeline_ssm_scan_f32_d256;
@@ -11357,7 +11366,8 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx,
const bool use_cm = (ctx->device->pipeline_gated_delta_net_cm != nullptr ||
ctx->device->pipeline_gated_delta_net_cm_v32 != nullptr ||
ctx->device->pipeline_gated_delta_net_cm_v128 != nullptr) &&
src_g->ne[0] == 1 && S_v == 128 && dst->src[0]->ne[0] == 128 && K == 1 && n_tokens >= cm_min_tokens;
src_g->ne[0] == 1 && S_v == 128 && dst->src[0]->ne[0] == 128 && K == 1 && n_tokens >= cm_min_tokens &&
dst->src[6] == nullptr; // the chunked kernels do not replay
const bool use_cm2 = use_cm && ctx->device->coopmat2;
const bool have_v64 = ctx->device->pipeline_gated_delta_net_cm != nullptr;
@@ -11389,9 +11399,10 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx,
ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
vk_subbuffer src_buf[6] = {};
for (int i = 0; i < 6; i++) {
src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
vk_subbuffer src_buf[10] = {};
for (int i = 0; i < 10; i++) {
// the replay sources 6..9 bind q when the op has no replay
src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i] ? dst->src[i] : src_q);
}
vk_subbuffer mirror_buf{};
@@ -11409,6 +11420,11 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx,
mirror_buf = vk_subbuffer{ ctx->prealloc_x, 0, ctx->prealloc_x->size };
}
// replay of pending tokens, see ggml_gated_delta_net_ext
const ggml_tensor * src_pk = dst->src[6];
const ggml_tensor * src_pv = dst->src[7];
const ggml_tensor * src_pgb = dst->src[8];
const uint32_t sq1 = (uint32_t)(src_q->nb[1] / sizeof(float));
const uint32_t sq2 = (uint32_t)(src_q->nb[2] / sizeof(float));
const uint32_t sq3 = (uint32_t)(src_q->nb[3] / sizeof(float));
@@ -11434,7 +11450,18 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx,
sb1, sb2, sb3,
neq1, rq3,
scale,
K
K,
src_pk ? (uint32_t)ggml_get_op_params_i32(dst, 1) : 0u,
src_pk ? (uint32_t)ggml_get_op_params_i32(dst, 2) : 0u,
src_pk ? (uint32_t)(src_pk->nb[1] / sizeof(float)) : 0u,
src_pk ? (uint32_t)(src_pk->nb[2] / sizeof(float)) : 0u,
src_pk ? (uint32_t)(src_pk->nb[3] / sizeof(float)) : 0u,
src_pv ? (uint32_t)(src_pv->nb[1] / sizeof(float)) : 0u,
src_pv ? (uint32_t)(src_pv->nb[2] / sizeof(float)) : 0u,
src_pv ? (uint32_t)(src_pv->nb[3] / sizeof(float)) : 0u,
src_pgb ? (uint32_t)(src_pgb->nb[1] / sizeof(float)) : 0u,
src_pgb ? (uint32_t)(src_pgb->nb[2] / sizeof(float)) : 0u,
src_pgb ? (uint32_t)(src_pgb->nb[3] / sizeof(float)) : 0u,
};
if (use_v128) {
@@ -11442,10 +11469,15 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx,
{src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf, mirror_buf},
pc, std::array<uint32_t, 3>{ S_v / cm_V, n_seqs, H });
ctx->prealloc_x_need_sync = true;
} else {
} else if (use_cm) {
ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
{src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf},
pc, use_cm ? std::array<uint32_t, 3>{ S_v / cm_V, n_seqs, H } : std::array<uint32_t, 3>{ H, n_seqs, S_v });
pc, std::array<uint32_t, 3>{ S_v / cm_V, n_seqs, H });
} else {
ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
{src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf,
src_buf[6], src_buf[7], src_buf[8], src_buf[9]},
pc, std::array<uint32_t, 3>{ H, n_seqs, S_v });
}
}
@@ -11496,7 +11528,7 @@ void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_te
std::array<uint32_t, 3> elements;
const uint32_t d_state = src0->ne[0];
uint32_t num_subgroups = d_state / ctx->device->subgroup_size;
uint32_t num_subgroups = (d_state == 96 ? 128 : d_state) / ctx->device->subgroup_size;
const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, num_subgroups);
const uint32_t num_workgroups_y = n_seq;
elements = { num_workgroups_x, num_workgroups_y, 1 };
@@ -11692,9 +11724,10 @@ void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor
const uint64_t n = ggml_nelements(dst);
GGML_ASSERT(n > 0);
// dst can be a view at any offset: bind from the aligned offset below it, the shader skips KY elements
vk_op_push_constants pc = {
(uint32_t)n,
1,
get_misalign_bytes(ctx, dst) / (uint32_t)ggml_type_size(dst->type),
ggml_get_op_params_f32(dst, 0),
0.0f,
0.0f, 0.0f,
@@ -11710,7 +11743,7 @@ void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor
GGML_ASSERT(wg_y <= ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true);
std::array<uint32_t, 3> elements = { wg_x * pipeline->wg_denoms[0], wg_y * pipeline->wg_denoms[1], 1 };
ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
@@ -16774,8 +16807,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
}
case GGML_OP_FLASH_ATTN_EXT:
{
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
if (op->src[5] != nullptr) {
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
bool coopmat2 = device->coopmat2;
@@ -17246,11 +17278,11 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
return false;
}
if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) {
if ((d_state != 96 && d_state != 128 && d_state != 256) || head_dim % 16 != 0) {
return false;
}
size_t shmem_size = d_state * sizeof(float);
size_t shmem_size = (d_state == 96 ? 128 : d_state) * sizeof(float);
if (shmem_size > device->properties.limits.maxComputeSharedMemorySize) {
return false;
@@ -16,6 +16,6 @@ void main() {
return;
}
// p.param1 = fill value
data_d[i] = D_TYPE(p.param1);
// p.param1 = fill value, p.KY = element offset of dst in the bound buffer
data_d[p.KY + i] = D_TYPE(p.param1);
}
@@ -16,6 +16,7 @@ layout(constant_id = 1) const uint KDA = 0;
layout(constant_id = 2) const uint SUBGROUP_SIZE = 32;
layout(constant_id = 3) const uint LANES_PER_COLUMN = 32;
layout(constant_id = 4) const bool PACKED_ROWS = false;
layout(constant_id = 5) const uint REPLAY = 0;
const uint COLS_PER_WG = SUBGROUP_SIZE / LANES_PER_COLUMN;
const uint ROWS_PER_LANE = S_V / LANES_PER_COLUMN;
@@ -42,6 +43,10 @@ layout(push_constant) uniform Parameters {
uint neq1, rq3;
float scale;
uint K;
uint n_pend, keep;
uint spk1, spk2, spk3;
uint spv1, spv2, spv3;
uint spg1, spg2, spg3;
};
layout(binding = 0) readonly buffer QBuf { FLOAT_TYPE data_q[]; };
@@ -52,6 +57,12 @@ layout(binding = 4) readonly buffer BetaBuf { FLOAT_TYPE data_beta[]; };
layout(binding = 5) readonly buffer StateBuf { FLOAT_TYPE data_state[]; };
layout(binding = 6) buffer DstBuf { FLOAT_TYPE data_dst[]; };
// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
layout(binding = 7) readonly buffer PKBuf { FLOAT_TYPE data_pk[]; };
layout(binding = 8) readonly buffer PVBuf { FLOAT_TYPE data_pv[]; };
layout(binding = 9) readonly buffer PGBBuf { FLOAT_TYPE data_pgb[]; };
layout(binding = 10) readonly buffer NRepBuf { int data_n_rep[]; };
#if !USE_SUBGROUP_ADD && !USE_SUBGROUP_CLUSTERED
shared FLOAT_TYPE temp[SUBGROUP_SIZE];
@@ -123,6 +134,55 @@ void main() {
s_shard[r] = FLOAT_TYPE(data_state[state_in_base + col * S_V + row_index(r, lane)]);
}
if (REPLAY != 0) {
const uint n_r = uint(clamp(data_n_rep[seq_id], 0, int(n_pend)));
for (uint t = 0; t < n_r; t++) {
const uint k_off = seq_id * spk3 + t * spk2 + iq1 * spk1;
const uint v_off = seq_id * spv3 + t * spv2 + head_id * spv1;
const uint g_off = seq_id * spg3 + t * spg2 + head_id * spg1;
const FLOAT_TYPE beta_val = FLOAT_TYPE(data_pgb[g_off + n_pend * spg2]);
FLOAT_TYPE k_reg[ROWS_PER_LANE];
[[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
k_reg[r] = FLOAT_TYPE(data_pk[k_off + row_index(r, lane)]);
}
FLOAT_TYPE g_exp[ROWS_PER_LANE];
if (KDA == 0) {
const FLOAT_TYPE g_val = exp(FLOAT_TYPE(data_pgb[g_off]));
[[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
g_exp[r] = g_val;
}
} else {
[[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
g_exp[r] = exp(FLOAT_TYPE(data_pgb[g_off + row_index(r, lane)]));
}
}
const FLOAT_TYPE v_val = FLOAT_TYPE(data_pv[v_off + col]);
// same update as below, without the attention output
FLOAT_TYPE kv_shard = 0.0;
[[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
kv_shard += g_exp[r] * s_shard[r] * k_reg[r];
}
FLOAT_TYPE kv_col = reduce_partial(kv_shard);
FLOAT_TYPE delta_col = (v_val - kv_col) * beta_val;
[[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
s_shard[r] = g_exp[r] * s_shard[r] + k_reg[r] * delta_col;
}
}
if (keep != 0) {
[[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[r];
}
}
}
// snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back.
// When n_tokens < K, only slots 0..n_tokens-1 are written; older slots are caller-owned.
@@ -191,7 +251,8 @@ void main() {
}
}
if (K == 1u) {
// replay with keep: the state output is the state after the replay
if (K == 1u && !(REPLAY != 0 && keep != 0)) {
[[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[r];
}
@@ -8,10 +8,11 @@
#include "types.glsl"
layout(constant_id = 0) const uint D_STATE = 128;
layout(constant_id = 0) const uint BLOCK_SIZE = 128;
layout(constant_id = 1) const uint SUBGROUP_SIZE = 32;
layout(constant_id = 2) const uint D_STATE = 128;
const uint32_t c_factor = D_STATE / SUBGROUP_SIZE;
const uint32_t c_factor = (D_STATE + SUBGROUP_SIZE - 1) / SUBGROUP_SIZE;
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
@@ -46,14 +47,14 @@ float softplus(float x) {
}
#if !USE_SUBGROUP_ADD
shared float temp[D_STATE];
shared float temp[BLOCK_SIZE];
#endif
void main() {
const uint subgroup = gl_SubgroupID;
const uint lane = gl_SubgroupInvocationID;
const uint tid = gl_SubgroupID * SUBGROUP_SIZE + lane;
const uint subgroup_idx = gl_WorkGroupID.x * c_factor + subgroup;
const uint subgroup_idx = gl_WorkGroupID.x * (BLOCK_SIZE / SUBGROUP_SIZE) + subgroup;
const uint head_idx = subgroup_idx / d_head;
const uint head_off = (subgroup_idx % d_head) * 4;
@@ -78,7 +79,8 @@ void main() {
float state[c_factor];
[[unroll]] for (uint j = 0; j < c_factor; j++) {
state[j] = s0[s0_base_idx + SUBGROUP_SIZE * j + lane];
const uint state_idx = SUBGROUP_SIZE * j + lane;
state[j] = D_STATE % SUBGROUP_SIZE == 0 || state_idx < D_STATE ? s0[s0_base_idx + state_idx] : 0.0f;
}
float a = A[A_base_idx];
@@ -91,8 +93,9 @@ void main() {
const float dA = exp(dt_soft_plus * a);
const float x_dt = x[x_base_idx + i * stride_x] * dt_soft_plus;
[[unroll]] for (uint j = 0; j < c_factor; j++) {
float B_val = B[B_base_idx + i * stride_B + SUBGROUP_SIZE * j + lane];
float C_val = C[C_base_idx + i * stride_C + SUBGROUP_SIZE * j + lane];
const uint state_idx = SUBGROUP_SIZE * j + lane;
float B_val = D_STATE % SUBGROUP_SIZE == 0 || state_idx < D_STATE ? B[B_base_idx + i * stride_B + state_idx] : 0.0f;
float C_val = D_STATE % SUBGROUP_SIZE == 0 || state_idx < D_STATE ? C[C_base_idx + i * stride_C + state_idx] : 0.0f;
state[j] = (state[j] * dA) + (B_val * x_dt);
state_sum += state[j] * C_val;
}
@@ -121,7 +124,9 @@ void main() {
if (slot > 0u && slot < K) {
const uint snapshot_base_idx = s_base_idx + slot * n_seq * (nb03 / 4u);
[[unroll]] for (uint j = 0; j < c_factor; j++) {
d[snapshot_base_idx + SUBGROUP_SIZE * j + lane] = state[j];
if (D_STATE % SUBGROUP_SIZE == 0 || SUBGROUP_SIZE * j + lane < D_STATE) {
d[snapshot_base_idx + SUBGROUP_SIZE * j + lane] = state[j];
}
}
}
}
@@ -129,6 +134,8 @@ void main() {
// write back the state
[[unroll]]
for (int j = 0; j < c_factor; j++) {
d[s_base_idx + SUBGROUP_SIZE * j + lane] = state[j];
if (D_STATE % SUBGROUP_SIZE == 0 || SUBGROUP_SIZE * j + lane < D_STATE) {
d[s_base_idx + SUBGROUP_SIZE * j + lane] = state[j];
}
}
}
@@ -1,6 +1,7 @@
#version 450
#include "types.glsl"
#include "utils.glsl"
#if defined(UNARY_MUL_FUSION)
#include "generic_binary_head.glsl"
#else
@@ -116,7 +117,7 @@ float op_expm1(float x) {
}
float op_softplus(float x) {
return (x > 20.0f) ? x : log(1.0f + exp(x));
return (x > 20.0f) ? x : log1p(exp(x));
}
float op_gelu_erf(float a) {
@@ -25,6 +25,26 @@ uint fastdiv_small(uint a, uint b) {
return (a < b) ? 0 : (a / b);
}
// log(1 + x); the atanh series 2*y*(1 + y^2/3 + ... + y^12/13), y = x/(2+x),
// keeps the precision that log(1 + x) loses for x in [-0.5, 1].
float log1p(float x) {
float y = x / (2.0f + x);
float y2 = y * y;
float p = 1.0f / 13.0f;
p = p * y2 + 1.0f / 11.0f;
p = p * y2 + 1.0f / 9.0f;
p = p * y2 + 1.0f / 7.0f;
p = p * y2 + 1.0f / 5.0f;
p = p * y2 + 1.0f / 3.0f;
p = p * y2 + 1.0f;
float s = 2.0f * y * p;
float l = log(1.0f + x);
bool in_series = (x >= -0.5f) && (x <= 1.0f);
bool tiny = abs(x) < 2.5e-38f;
float r = in_series ? s : l;
return tiny ? x : r;
}
void get_indices(uint idx, out uint i00, out uint i01, out uint i02, out uint i03, uint ne00, uint ne01, uint ne02, uint ne03) {
i03 = fastdiv_small(idx, (ne02*ne01*ne00));
const uint i03_offset = i03 * ne02*ne01*ne00;
@@ -450,9 +450,11 @@ struct ggml_webgpu_gated_delta_net_pipeline_key {
int s_v;
int kda;
bool fused_cache;
bool replay;
bool operator==(const ggml_webgpu_gated_delta_net_pipeline_key & other) const {
return type == other.type && s_v == other.s_v && kda == other.kda && fused_cache == other.fused_cache;
return type == other.type && s_v == other.s_v && kda == other.kda && fused_cache == other.fused_cache &&
replay == other.replay;
}
};
@@ -462,6 +464,7 @@ struct ggml_webgpu_gated_delta_net_pipeline_key_hash {
ggml_webgpu_hash_combine(seed, key.type);
ggml_webgpu_hash_combine(seed, key.s_v);
ggml_webgpu_hash_combine(seed, key.kda);
ggml_webgpu_hash_combine(seed, key.replay);
return seed;
}
};
@@ -2015,6 +2018,7 @@ class ggml_webgpu_shader_lib {
key.s_v = (int) context.src2->ne[0];
key.kda = context.src3->ne[0] == context.src2->ne[0];
key.fused_cache = context.dst_fuse != nullptr;
key.replay = context.dst->src[6] != nullptr;
auto it = gated_delta_net_pipelines.find(key);
if (it != gated_delta_net_pipelines.end()) {
@@ -2042,6 +2046,11 @@ class ggml_webgpu_shader_lib {
variant += "_fused_cache";
}
if (key.replay) {
defines.push_back("REPLAY");
variant += "_replay";
}
defines.push_back("S_V=" + std::to_string(key.s_v) + "u");
defines.push_back("WG_SIZE=" + std::to_string(key.s_v) + "u");
+43 -4
View File
@@ -1497,6 +1497,11 @@ static webgpu_encoded_op ggml_webgpu_ssm_scan(webgpu_context & ctx,
return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
}
// storage buffers of the gated delta net shader: q, k, v, g, beta, state and dst, the fused cache, then the replay inputs
static uint32_t ggml_webgpu_gated_delta_net_n_storage_buffers(const ggml_tensor * op, bool fused_cache) {
return 7 + (fused_cache ? 1 : 0) + (op->src[6] != nullptr ? 4 : 0);
}
static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
ggml_tensor * src0,
ggml_tensor * src1,
@@ -1527,6 +1532,12 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
uint32_t scale_u32;
memcpy(&scale_u32, &scale, sizeof(scale_u32));
// replay of pending tokens, see ggml_gated_delta_net_ext
ggml_tensor * pend_k = dst->src[6];
ggml_tensor * pend_v = dst->src[7];
ggml_tensor * pend_gb = dst->src[8];
ggml_tensor * n_rep = dst->src[9];
std::vector<uint32_t> params = {
h,
n_tokens,
@@ -1551,6 +1562,21 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
scale_u32,
dst_fuse ? (uint32_t) (dst_fuse->nb[2] / ggml_type_size(dst_fuse->type)) : 0,
dst_fuse ? (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst_fuse) / ggml_type_size(dst_fuse->type)) : 0,
pend_k ? (uint32_t) ggml_get_op_params_i32(dst, 1) : 0,
pend_k ? (uint32_t) ggml_get_op_params_i32(dst, 2) : 0,
pend_k ? (uint32_t) (pend_k->nb[1] / ggml_type_size(pend_k->type)) : 0,
pend_k ? (uint32_t) (pend_k->nb[2] / ggml_type_size(pend_k->type)) : 0,
pend_k ? (uint32_t) (pend_k->nb[3] / ggml_type_size(pend_k->type)) : 0,
pend_v ? (uint32_t) (pend_v->nb[1] / ggml_type_size(pend_v->type)) : 0,
pend_v ? (uint32_t) (pend_v->nb[2] / ggml_type_size(pend_v->type)) : 0,
pend_v ? (uint32_t) (pend_v->nb[3] / ggml_type_size(pend_v->type)) : 0,
pend_gb ? (uint32_t) (pend_gb->nb[1] / ggml_type_size(pend_gb->type)) : 0,
pend_gb ? (uint32_t) (pend_gb->nb[2] / ggml_type_size(pend_gb->type)) : 0,
pend_gb ? (uint32_t) (pend_gb->nb[3] / ggml_type_size(pend_gb->type)) : 0,
};
std::vector<wgpu::BindGroupEntry> entries = {
@@ -1564,6 +1590,14 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 7, dst_fuse));
}
if (pend_k) {
const uint32_t binding = dst_fuse ? 8 : 7;
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 0, pend_k));
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 1, pend_v));
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 2, pend_gb));
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 3, n_rep));
}
return ggml_backend_webgpu_build(ctx, pipeline, params, entries, h, n_seqs);
}
@@ -3728,7 +3762,9 @@ static std::optional<webgpu_encoded_op> ggml_webgpu_encode(webgpu_context ctx,
return ggml_webgpu_ssm_scan(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5], node->src[6],
node);
case GGML_OP_GATED_DELTA_NET:
if (ggml_webgpu_can_fuse_gdn_cache(cgraph, node_idx, num_encoded_ops)) {
if (ggml_webgpu_gated_delta_net_n_storage_buffers(node, true) <=
ctx->global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage &&
ggml_webgpu_can_fuse_gdn_cache(cgraph, node_idx, num_encoded_ops)) {
ggml_tensor * dst_fuse = cgraph->nodes[node_idx + num_encoded_ops - 1]->src[1];
return ggml_webgpu_gated_delta_net(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5],
node, dst_fuse);
@@ -5086,8 +5122,9 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const
{
// conservative support checks for whether the more resource-intensive shader paths
// can be used, to avoid cases where flash_attn is assigned to the CPU later on
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
supports_op = op->src[5] == nullptr && src0->type == GGML_TYPE_F32 &&
// K/V row lists and indexed bias are not supported
supports_op = op->src[5] == nullptr && !ggml_flash_attn_ext_has_indexed_bias(op) &&
src0->type == GGML_TYPE_F32 &&
(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16 ||
src1->type == GGML_TYPE_Q4_0 || src1->type == GGML_TYPE_Q8_0) &&
(src2->type == GGML_TYPE_F32 || src2->type == GGML_TYPE_F16 ||
@@ -5269,7 +5306,9 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const
src2->type == GGML_TYPE_F32 && op->src[3]->type == GGML_TYPE_F32 &&
op->src[4]->type == GGML_TYPE_F32 && op->src[5]->type == GGML_TYPE_F32 &&
s_v <= ctx->webgpu_global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup &&
ggml_are_same_stride(src0, src1);
ggml_are_same_stride(src0, src1) &&
ggml_webgpu_gated_delta_net_n_storage_buffers(op, false) <=
ctx->webgpu_global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage;
}
break;
case GGML_OP_CLAMP:
@@ -23,10 +23,31 @@ var<storage, read_write> dst: array<f32>;
@group(0) @binding(7)
var<storage, read_write> dst_fuse: array<f32>;
#define DST_SNAP dst_fuse
#define PARAMS_BINDING 8
#define NEXT_BINDING 8
#else
#define DST_SNAP dst
#define PARAMS_BINDING 7
#define NEXT_BINDING 7
#endif
#ifdef REPLAY
// pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
@group(0) @binding(NEXT_BINDING)
var<storage, read_write> pend_k: array<f32>;
@group(0) @binding(NEXT_BINDING + 1)
var<storage, read_write> pend_v: array<f32>;
@group(0) @binding(NEXT_BINDING + 2)
var<storage, read_write> pend_gb: array<f32>;
@group(0) @binding(NEXT_BINDING + 3)
var<storage, read_write> n_rep: array<i32>;
var<workgroup> wg_n_rep: u32;
#define PARAMS_BINDING (NEXT_BINDING + 4)
#else
#define PARAMS_BINDING NEXT_BINDING
#endif
struct Params {
@@ -53,6 +74,21 @@ struct Params {
scale: f32,
dst_fuse_nb2: u32,
dst_fuse_off: u32,
n_pend: u32,
keep: u32,
spk1: u32,
spk2: u32,
spk3: u32,
spv1: u32,
spv2: u32,
spv3: u32,
spg1: u32,
spg2: u32,
spg3: u32,
};
@group(0) @binding(PARAMS_BINDING)
@@ -92,6 +128,66 @@ fn main(
state[i] = src_state[state_in_base + col * S_V + i];
}
#ifdef REPLAY
if (col == 0u) {
wg_n_rep = u32(n_rep[seq_id]);
}
let n_r = workgroupUniformLoad(&wg_n_rep);
for (var t = 0u; t < n_r; t++) {
let k_off = seq_id * params.spk3 + t * params.spk2 + iq1 * params.spk1;
let v_off = seq_id * params.spv3 + t * params.spv2 + head_id * params.spv1;
let g_off = seq_id * params.spg3 + t * params.spg2 + head_id * params.spg1;
sh_k[col] = pend_k[k_off + col];
#ifdef KDA
sh_g[col] = exp(pend_gb[g_off + col]);
#endif
workgroupBarrier();
let v_val = pend_v[v_off + col];
let beta_val = pend_gb[g_off + params.n_pend * params.spg2];
// same update as below, without the attention output
var kv_col = 0.0;
var delta_col = 0.0;
#ifdef KDA
for (var i = 0u; i < S_V; i++) {
kv_col += (sh_g[i] * state[i]) * sh_k[i];
}
delta_col = (v_val - kv_col) * beta_val;
for (var i = 0u; i < S_V; i++) {
state[i] = sh_g[i] * state[i] + sh_k[i] * delta_col;
}
#else
let g_val = exp(pend_gb[g_off]);
for (var i = 0u; i < S_V; i++) {
kv_col += state[i] * sh_k[i];
}
delta_col = (v_val - g_val * kv_col) * beta_val;
for (var i = 0u; i < S_V; i++) {
state[i] = g_val * state[i] + sh_k[i] * delta_col;
}
#endif
workgroupBarrier();
}
if (params.keep != 0u) {
for (var i = 0u; i < S_V; i++) {
DST_SNAP[snap_off + state_out_base + col * S_V + i] = state[i];
}
}
#endif
var attn_off = (seq_id * params.n_tokens * params.h + head_id) * S_V;
for (var t = 0u; t < params.n_tokens; t++) {
@@ -160,7 +256,14 @@ fn main(
workgroupBarrier();
}
if (params.K == 1u) {
#ifdef REPLAY
// replay with keep: the state output is the state after the replay
let write_state = params.K == 1u && params.keep == 0u;
#else
let write_state = params.K == 1u;
#endif
if (write_state) {
for (var i = 0u; i < S_V; i++) {
DST_SNAP[snap_off + state_out_base + col * S_V + i] = state[i];
}
+1 -1
View File
@@ -21,7 +21,7 @@ bool ggml_zdnn_supports_flash_attn_ext(const ggml_backend_zdnn_device_context *
memcpy(&logit_softcap, (const float *) op->op_params + 2, sizeof(float));
// sinks, alibi, softcap, sparse k/v sets and k/v row lists are not implemented
if (op->src[4] != nullptr || op->src[5] != nullptr || max_bias != 0.0f || logit_softcap != 0.0f || ggml_get_op_params_i32(op, 4) != 0) {
if (op->src[4] != nullptr || op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op) || max_bias != 0.0f || logit_softcap != 0.0f || ggml_get_op_params_i32(op, 4) != 0) {
return false;
}
+86 -2
View File
@@ -5545,6 +5545,33 @@ void ggml_flash_attn_ext_add_sinks(
a->src[4] = sinks;
}
bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a) {
return a->op == GGML_OP_FLASH_ATTN_EXT && ggml_get_op_params_i32(a, 5) != 0;
}
void ggml_flash_attn_ext_add_indexed_bias(
struct ggml_tensor * a,
struct ggml_tensor * table,
struct ggml_tensor * indices) {
GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
GGML_ASSERT((table == NULL) == (indices == NULL));
a->src[6] = table;
a->src[7] = indices;
ggml_set_op_params_i32(a, 5, table != NULL);
if (!table) {
return;
}
const struct ggml_tensor * q = a->src[0];
const struct ggml_tensor * mask = a->src[3];
GGML_ASSERT(mask && mask->ne[0] == (a->src[5] ? a->src[5]->ne[0] : a->src[1]->ne[1]) && mask->ne[1] == q->ne[1]);
GGML_ASSERT(mask->ne[2] == 1 && mask->ne[3] == q->ne[3]);
GGML_ASSERT(table->type == GGML_TYPE_F32 && ggml_is_contiguous(table));
GGML_ASSERT(table->ne[1] == q->ne[2] && table->ne[0] > 0 && table->ne[2] == q->ne[1]*q->ne[3] && table->ne[3] == 1);
GGML_ASSERT(indices->type == GGML_TYPE_I32 && ggml_is_contiguous(indices) && ggml_is_matrix(indices));
GGML_ASSERT(indices->ne[0] == mask->ne[0] && indices->ne[1] == table->ne[2]);
}
// ggml_flash_attn_back
struct ggml_tensor * ggml_flash_attn_back(
@@ -6346,7 +6373,7 @@ struct ggml_tensor * ggml_solve_tri(
// ggml_gated_delta_net
struct ggml_tensor * ggml_gated_delta_net(
static struct ggml_tensor * ggml_gated_delta_net_impl(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * k,
@@ -6354,7 +6381,12 @@ struct ggml_tensor * ggml_gated_delta_net(
struct ggml_tensor * g,
struct ggml_tensor * beta,
struct ggml_tensor * state,
int64_t K) {
struct ggml_tensor * pend_k,
struct ggml_tensor * pend_v,
struct ggml_tensor * pend_gb,
struct ggml_tensor * n_rep,
int64_t K,
bool keep) {
GGML_ASSERT(ggml_is_contiguous_rows(q));
GGML_ASSERT(ggml_is_contiguous_rows(k));
GGML_ASSERT(ggml_is_contiguous_rows(v));
@@ -6398,9 +6430,61 @@ struct ggml_tensor * ggml_gated_delta_net(
result->src[4] = beta;
result->src[5] = state;
const bool replay = pend_k != NULL;
GGML_ASSERT((pend_v != NULL) == replay && (pend_gb != NULL) == replay && (n_rep != NULL) == replay);
GGML_ASSERT(replay || !keep);
if (replay) {
const int64_t n_pend = pend_k->ne[2];
GGML_ASSERT(K == 1);
GGML_ASSERT(pend_k->type == GGML_TYPE_F32 && pend_v->type == GGML_TYPE_F32 && pend_gb->type == GGML_TYPE_F32);
GGML_ASSERT(n_rep->type == GGML_TYPE_I32);
GGML_ASSERT(pend_k->nb[0] == sizeof(float) && pend_v->nb[0] == sizeof(float) && pend_gb->nb[0] == sizeof(float));
GGML_ASSERT(pend_k->ne[0] == k->ne[0] && pend_k->ne[1] == k->ne[1] && pend_k->ne[3] == n_seqs);
GGML_ASSERT(pend_v->ne[0] == S_v && pend_v->ne[1] == H && pend_v->ne[2] == n_pend && pend_v->ne[3] == n_seqs);
GGML_ASSERT(pend_gb->ne[0] == g->ne[0] && pend_gb->ne[1] == H && pend_gb->ne[2] == 2*n_pend && pend_gb->ne[3] == n_seqs);
GGML_ASSERT(ggml_is_contiguous(n_rep) && ggml_nelements(n_rep) == n_seqs);
ggml_set_op_params_i32(result, 1, (int32_t) n_pend);
ggml_set_op_params_i32(result, 2, keep ? 1 : 0);
result->src[6] = pend_k;
result->src[7] = pend_v;
result->src[8] = pend_gb;
result->src[9] = n_rep;
}
return result;
}
struct ggml_tensor * ggml_gated_delta_net_ext(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * k,
struct ggml_tensor * v,
struct ggml_tensor * g,
struct ggml_tensor * beta,
struct ggml_tensor * state,
struct ggml_tensor * pend_k,
struct ggml_tensor * pend_v,
struct ggml_tensor * pend_gb,
struct ggml_tensor * n_rep,
bool keep) {
return ggml_gated_delta_net_impl(ctx, q, k, v, g, beta, state, pend_k, pend_v, pend_gb, n_rep, 1, keep);
}
struct ggml_tensor * ggml_gated_delta_net(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * k,
struct ggml_tensor * v,
struct ggml_tensor * g,
struct ggml_tensor * beta,
struct ggml_tensor * state,
int64_t K) {
return ggml_gated_delta_net_impl(ctx, q, k, v, g, beta, state, NULL, NULL, NULL, NULL, K, false);
}
// ggml_lightning_indexer
struct ggml_tensor * ggml_lightning_indexer(
+9
View File
@@ -466,6 +466,15 @@ extern "C" {
const struct llama_model_tensor_override * tt_overrides; // pointer to tensor overrides
const int32_t * prune_layers; // pointer to layer indices to prune
size_t max_buf_size; // max bytes of tensor rows kept in memory at once, 0 = default (8 GiB)
const struct llama_model_imatrix_data * activations; // pointer to activations data
const struct llama_model_imatrix_data * statistics; // pointer to statistics data
const char * const * stats_schema; // pointer to statistics schema names
float target_bpw; // target bits per weight (bpw)
int64_t target_size; // target file size in bytes
const char * state_file; // pointer to bpw state file
const enum ggml_type * target_exclude; // pointer to excluded GGML_TYPEs
ggml_abort_callback abort_callback; // callback to abort quantization
void * abort_callback_data; // pointer to user data for abort_callback
} llama_model_quantize_params;
typedef struct llama_logit_bias {
+12
View File
@@ -1592,6 +1592,18 @@ bool llm_arch_supports_sm_tensor(const llm_arch & arch) {
}
}
bool llm_arch_mmid_down_bf16(const llm_arch & arch) {
switch (arch) {
case LLM_ARCH_MISTRAL4:
case LLM_ARCH_MELLUM:
case LLM_ARCH_FLINT:
case LLM_ARCH_LAGUNA:
return true;
default:
return false;
}
}
bool llama_arch_supports_save(llm_arch arch) {
switch (arch) {
case LLM_ARCH_SENSENOVA_U1:
+1
View File
@@ -1037,3 +1037,4 @@ bool llm_arch_is_diffusion (const llm_arch & arch);
bool llm_arch_supports_sm_tensor(const llm_arch & arch);
bool llm_arch_supports_rs_rollback(const llm_arch & arch);
bool llm_arch_supports_mixed_batch(const llm_arch & arch);
bool llm_arch_mmid_down_bf16(const llm_arch & arch);
+9
View File
@@ -190,6 +190,14 @@ llama_context::llama_context(
cparams.n_rs_seq = 0;
}
// delta-net rollback keeps one state and the inputs of the last ubatch; the gdn op replays the kept tokens before the new ones
cparams.rs_replay = cparams.n_rs_seq > 0 && (
model.arch == LLM_ARCH_QWEN35 || model.arch == LLM_ARCH_QWEN35MOE || model.arch == LLM_ARCH_QWEN4EXP ||
model.arch == LLM_ARCH_CLOVER_MOE ||
// KDA
model.arch == LLM_ARCH_KIMI_K3 || model.arch == LLM_ARCH_KIMI_K31 || model.arch == LLM_ARCH_GLM5_NEXT ||
model.arch == LLM_ARCH_BAILINGMOE3);
cparams.n_threads = params.n_threads;
cparams.n_threads_batch = params.n_threads_batch;
cparams.yarn_ext_factor = params.yarn_ext_factor >= 0.0f ? params.yarn_ext_factor : hparams.yarn_ext_factor;
@@ -435,6 +443,7 @@ llama_context::llama_context(
LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
LLAMA_LOG_INFO("%s: n_rs_seq = %u\n", __func__, cparams.n_rs_seq);
LLAMA_LOG_INFO("%s: rs_replay = %s\n", __func__, cparams.rs_replay ? "true" : "false");
LLAMA_LOG_INFO("%s: n_outputs_max = %u\n", __func__, cparams.n_outputs_max);
LLAMA_LOG_INFO("%s: n_outputs_max_per_seq = %u\n", __func__, cparams.n_outputs_max_per_seq);
+1
View File
@@ -14,6 +14,7 @@ struct llama_cparams {
uint32_t n_ubatch;
uint32_t n_seq_max;
uint32_t n_rs_seq; // number of recurrent-state snapshots per seq for rollback
bool rs_replay; // roll back by replaying kept tokens instead of keeping n_rs_seq snapshots
uint32_t n_outputs_max; // max outputs supported by the context
uint32_t n_outputs_max_per_seq;
int32_t n_threads; // number of threads to use for generation
+1 -1
View File
@@ -51,7 +51,7 @@ LLAMA_API quantize_state_impl * llama_quant_init(
const llama_model * model,
const llama_model_quantize_params * params);
LLAMA_API void llama_quant_free(quantize_state_impl * qs);
LLAMA_API void llama_quant_free(const quantize_state_impl * qs);
// Descriptor for constructing a mock model for quantization testing.
struct llama_quant_model_desc {
+73 -12
View File
@@ -527,8 +527,6 @@ void llm_graph_input_cls::set_input(const llama_ubatch * ubatch) {
}
void llm_graph_input_rs::set_input(const llama_ubatch * ubatch) {
GGML_UNUSED(ubatch);
const int64_t n_rs = mctx->get_n_rs();
if (s_copy) {
@@ -540,6 +538,34 @@ void llm_graph_input_rs::set_input(const llama_ubatch * ubatch) {
data[i] = mctx->s_copy(i);
}
}
set_input_rep(mctx, ubatch);
}
void llm_graph_input_rs::set_input_rep(const llama_memory_recurrent_context * mctx, const llama_ubatch * ubatch) {
if (!has_rep) {
return;
}
const int64_t n_seqs = ubatch->n_seqs;
int32_t * reps = (int32_t *) rep_n->data;
int32_t * cols = (int32_t *) rep_cols->data;
GGML_ASSERT(ggml_backend_buffer_is_host(rep_n->buffer));
GGML_ASSERT(ggml_backend_buffer_is_host(rep_cols->buffer));
for (int64_t s = 0; s < n_seqs; ++s) {
const int64_t n_rep = mctx->get_rs_rep(s);
GGML_ASSERT(n_rep <= n_pend);
reps[s] = n_rep;
// the conv history is [window | pending]: the window after the kept tokens
for (int64_t c = 0; c < n_conv; ++c) {
cols[s*n_conv + c] = n_rep + c;
}
}
}
bool llm_graph_input_rs::can_reuse(const llm_graph_params & params) {
@@ -1261,6 +1287,8 @@ void llm_graph_input_mem_hybrid::set_input(const llama_ubatch * ubatch) {
data[i] = mctx->get_recr()->s_copy(i);
}
}
inp_rs->set_input_rep(mctx->get_recr(), ubatch);
}
bool llm_graph_input_mem_hybrid::can_reuse(const llm_graph_params & params) {
@@ -1307,6 +1335,8 @@ void llm_graph_input_mem_hybrid_k::set_input(const llama_ubatch * ubatch) {
data[i] = mctx->get_recr()->s_copy(i);
}
}
inp_rs->set_input_rep(mctx->get_recr(), ubatch);
}
bool llm_graph_input_mem_hybrid_k::can_reuse(const llm_graph_params & params) {
@@ -1364,6 +1394,8 @@ void llm_graph_input_mem_hybrid_iswa::set_input(const llama_ubatch * ubatch) {
data[i] = mctx->get_recr()->s_copy(i);
}
}
inp_rs->set_input_rep(mctx->get_recr(), ubatch);
}
bool llm_graph_input_mem_hybrid_iswa::can_reuse(const llm_graph_params & params) {
@@ -1443,6 +1475,8 @@ void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch)
data[i] = mctx->get_recr()->s_copy(i);
}
}
inp_rs->set_input_rep(mctx->get_recr(), ubatch);
}
bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & params) {
@@ -1823,7 +1857,7 @@ ggml_tensor * llm_graph_context::build_lora_mm(
}
prec_policy.apply(res);
prec_policy.apply(res, w);
if (w_s) {
res = ggml_mul(ctx0, res, w_s);
@@ -1894,7 +1928,6 @@ ggml_tensor * llm_graph_context::build_lora_mm_id(
ggml_tensor * slots,
bool cached) const {
ggml_tensor * w_s = model.get_w_scale(w);
// as in build_lora_mm: the folded weight reads the transformed input, the LoRA delta reads `cur`
ggml_tensor * cur_mm = build_hadamard_input(w, cur);
// the experts in the MoE cache are selected by their slots
@@ -1907,7 +1940,7 @@ ggml_tensor * llm_graph_context::build_lora_mm_id(
}
// after the NVFP4 default, so that the policy can request a higher precision
prec_policy.apply(res);
prec_policy.apply(res, w);
if (w_s) {
const int64_t n_expert = w_s->ne[0];
@@ -2656,15 +2689,16 @@ ggml_tensor * llm_graph_context::build_moe_ffn(
// ggml_prec_set_src(experts, GGML_PREC_BF16, 1);
// the amax op cannot be split across devices, so these architectures are denied -sm tensor [TAG_MOE_AMAX_SCALE]
// ref: https://github.com/ggml-org/llama.cpp/pull/30656#issuecomment-6269597922
const bool use_amax = llm_arch_mmid_down_bf16(arch) && prec_policy.get_src1(down_exps) != GGML_PREC_BF16;
llm_graph_amax_src1 amax_src1 = { nullptr, nullptr };
if (arch == LLM_ARCH_MISTRAL4 || arch == LLM_ARCH_MELLUM || arch == LLM_ARCH_FLINT || arch == LLM_ARCH_LAGUNA) {
if (use_amax) {
amax_src1 = build_amax_src1_f16(cur);
cur = amax_src1.res;
}
ggml_tensor * experts = build_lora_mm_id(down_exps, cur, ids, mm_ids, cached); // [n_embd, n_expert_used, n_tokens]
//ggml_prec_set_src(experts, GGML_PREC_BF16, 1); // (see TODO above)
cb(experts, "ffn_moe_down", il);
if (amax_src1.scale_s) {
@@ -4136,6 +4170,8 @@ ggml_tensor * llm_graph_context::build_rs(
static std::unique_ptr<llm_graph_input_rs> build_rs_inp_impl(
ggml_context * ctx0,
const llama_ubatch & ubatch,
const llama_hparams & hparams,
const llama_cparams & cparams,
const llama_memory_recurrent_context * mctx_cur) {
auto inp = std::make_unique<llm_graph_input_rs>(mctx_cur);
@@ -4153,13 +4189,38 @@ static std::unique_ptr<llm_graph_input_rs> build_rs_inp_impl(
inp->head = mctx_cur->get_head();
inp->rs_z = mctx_cur->get_rs_z();
inp->has_rep = mctx_cur->get_rs_replay();
if (inp->has_rep) {
// the widest conv window of the model: the delta-net conv, or the PLE n-gram conv (qwen4exp)
const int64_t n_conv_r = hparams.ssm_d_conv - 1;
const int64_t n_conv_p = hparams.ple_conv_state() > 0 ? (int64_t) (hparams.ple_conv_kernel - 1)*hparams.ple_ngram_size : 0;
inp->n_conv = std::max(n_conv_r, n_conv_p);
inp->n_pend = cparams.n_rs_seq + 1;
inp->rep_cols = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, inp->n_conv, n_seqs);
ggml_set_input(inp->rep_cols);
ggml_set_name(inp->rep_cols, "rs_rep_cols");
const auto win = [&](int64_t n) {
return n == inp->n_conv ? inp->rep_cols : ggml_view_2d(ctx0, inp->rep_cols, n, n_seqs, inp->rep_cols->nb[1], 0);
};
inp->rep_cols_r = win(n_conv_r);
inp->rep_cols_p = n_conv_p > 0 ? win(n_conv_p) : nullptr;
inp->rep_n = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_seqs);
ggml_set_input(inp->rep_n);
ggml_set_name(inp->rep_n, "rs_rep_n");
}
return inp;
}
llm_graph_input_rs * llm_graph_context::build_rs_inp() const {
const auto * mctx_cur = static_cast<const llama_memory_recurrent_context *>(mctx);
auto inp = build_rs_inp_impl(ctx0, ubatch, mctx_cur);
auto inp = build_rs_inp_impl(ctx0, ubatch, hparams, cparams, mctx_cur);
return (llm_graph_input_rs *) res->add_input(std::move(inp));
}
@@ -4286,7 +4347,7 @@ ggml_tensor * llm_graph_context::build_rwkv_token_shift_store(
llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid() const {
const auto * mctx_cur = static_cast<const llama_memory_hybrid_context *>(mctx);
auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr());
auto inp_rs = build_rs_inp_impl (ctx0, ubatch, hparams, cparams, mctx_cur->get_recr());
auto inp_attn = build_attn_inp_kv_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn());
auto inp = std::make_unique<llm_graph_input_mem_hybrid>(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur);
@@ -4297,7 +4358,7 @@ llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid() const {
llm_graph_input_mem_hybrid_k * llm_graph_context::build_inp_mem_hybrid_k() const {
const auto * mctx_cur = static_cast<const llama_memory_hybrid_context *>(mctx);
auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr());
auto inp_rs = build_rs_inp_impl (ctx0, ubatch, hparams, cparams, mctx_cur->get_recr());
auto inp_attn = build_attn_inp_k_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn());
auto inp = std::make_unique<llm_graph_input_mem_hybrid_k>(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur);
@@ -4308,7 +4369,7 @@ llm_graph_input_mem_hybrid_k * llm_graph_context::build_inp_mem_hybrid_k() const
llm_graph_input_mem_hybrid_iswa * llm_graph_context::build_inp_mem_hybrid_iswa() const {
const auto * mctx_cur = static_cast<const llama_memory_hybrid_iswa_context *>(mctx);
auto inp_rs = build_rs_inp_impl(ctx0, ubatch, mctx_cur->get_recr());
auto inp_rs = build_rs_inp_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_recr());
// build iswa attention input
const auto * attn_ctx = mctx_cur->get_attn();
@@ -4345,7 +4406,7 @@ llm_graph_input_mem_hybrid_iswa_rel * llm_graph_context::build_inp_mem_hybrid_is
uint32_t extent_swa) const {
const auto * mctx_cur = static_cast<const llama_memory_hybrid_iswa_context *>(mctx);
auto inp_rs = build_rs_inp_impl(ctx0, ubatch, mctx_cur->get_recr());
auto inp_rs = build_rs_inp_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_recr());
const auto * attn_ctx = mctx_cur->get_attn();
+13
View File
@@ -323,6 +323,19 @@ public:
ggml_tensor * s_copy_main; // I32 [n_seqs]
ggml_tensor * s_copy_tail; // I32 [n_rs - 1]
// rs_replay: the ubatch first replays the kept pending tokens of the last ubatch (none is a no-op)
bool has_rep = false;
int64_t n_conv = 0; // conv window columns, the widest conv of the model
int64_t n_pend = 0; // pending slots per seq
ggml_tensor * rep_n = nullptr; // I32 [n_seqs], kept pending tokens
ggml_tensor * rep_cols = nullptr; // I32 [n_conv, n_seqs], conv history columns of the window after the kept tokens
// views of rep_cols for the delta-net conv and the PLE conv windows, computed once per graph and shared across layers
ggml_tensor * rep_cols_r = nullptr;
ggml_tensor * rep_cols_p = nullptr;
void set_input_rep(const llama_memory_recurrent_context * mctx, const llama_ubatch * ubatch);
const llama_memory_recurrent_context * mctx;
// used in view offsets, need to match for valid graph reuse
+2 -1
View File
@@ -33,6 +33,7 @@ llama_memory_hybrid_idx::llama_memory_hybrid_idx(
/* common */
uint32_t n_seq_max,
uint32_t n_rs_seq,
bool rs_replay,
bool offload,
bool unified,
/* layer filters */
@@ -44,7 +45,7 @@ llama_memory_hybrid_idx::llama_memory_hybrid_idx(
no_alloc,
type_k, type_v, v_trans, kv_size, n_swa, swa_type,
type_r, type_s, rs_size,
n_seq_max, n_rs_seq, offload, unified,
n_seq_max, n_rs_seq, rs_replay, offload, unified,
filter_attn, filter_recr),
hparams_idx(model.hparams),
mem_idx(filter_idx == nullptr ? nullptr : [&] {
+1
View File
@@ -33,6 +33,7 @@ public:
/* common */
uint32_t n_seq_max,
uint32_t n_rs_seq,
bool rs_replay,
bool offload,
bool unified,
/* layer filters */
+1
View File
@@ -59,6 +59,7 @@ llama_memory_hybrid_iswa::llama_memory_hybrid_iswa(
rs_size,
n_seq_max,
n_rs_seq,
false,
filter_recr == nullptr ?
[&](int32_t il) { return hparams.is_recr(il); }
: filter_recr
+2
View File
@@ -25,6 +25,7 @@ llama_memory_hybrid::llama_memory_hybrid(
/* common */
uint32_t n_seq_max,
uint32_t n_rs_seq,
bool rs_replay,
bool offload,
bool unified,
/* layer filters */
@@ -60,6 +61,7 @@ llama_memory_hybrid::llama_memory_hybrid(
rs_size,
n_seq_max,
n_rs_seq,
rs_replay,
filter_recr == nullptr ?
[&](int32_t il) { return hparams.is_recr(il); }
: filter_recr
+1
View File
@@ -35,6 +35,7 @@ public:
/* common */
uint32_t n_seq_max,
uint32_t n_rs_seq,
bool rs_replay,
bool offload,
bool unified,
/* layer filters */
+152 -15
View File
@@ -26,6 +26,7 @@ llama_memory_recurrent::llama_memory_recurrent(
uint32_t mem_size,
uint32_t n_seq_max,
uint32_t n_rs_seq,
bool rs_replay,
const layer_filter_cb & filter) : hparams(model.hparams), n_seq_max(n_seq_max), ctxs_bufs(no_alloc) {
const int32_t n_layer = hparams.n_layer();
@@ -33,7 +34,8 @@ llama_memory_recurrent::llama_memory_recurrent(
size = mem_size;
used = 0;
this->n_rs_seq = n_rs_seq;
this->n_rs_seq = n_rs_seq;
this->rs_replay = rs_replay && n_rs_seq > 0;
rs_idx.assign(n_seq_max, 0);
cells.clear();
@@ -53,7 +55,7 @@ llama_memory_recurrent::llama_memory_recurrent(
if (it == ctx_map.end()) {
ggml_init_params params = {
// r and s per layer, plus the separate PLE conv row where the model has one
/*.mem_size =*/ size_t((hparams.ple_conv_state() > 0 ? 3u : 2u)*n_layer*ggml_tensor_overhead()),
/*.mem_size =*/ size_t((hparams.ple_conv_state() > 0 ? 6u : 5u)*n_layer*ggml_tensor_overhead()),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
@@ -74,6 +76,9 @@ llama_memory_recurrent::llama_memory_recurrent(
r_l.resize(n_layer);
s_l.resize(n_layer);
p_l.resize(n_layer);
spk_l.resize(n_layer);
spv_l.resize(n_layer);
spgb_l.resize(n_layer);
for (int i = 0; i < n_layer; i++) {
if (filter && !filter(i)) {
@@ -99,17 +104,45 @@ llama_memory_recurrent::llama_memory_recurrent(
throw std::runtime_error("failed to create ggml context for rs cache");
}
const uint32_t n_rows = mem_size * (1 + n_rs_seq);
ggml_tensor * r = ggml_new_tensor_2d(ctx, type_r, hparams.n_embd_r(), n_rows);
// rs_replay: r is the conv history [channels, d_conv - 1 + n_pend], the window then the pending columns,
// and spk, spv, spgb hold the gdn k, v, gate and beta of up to n_pend pending tokens
const int64_t n_pend = n_rs_seq + 1;
const int64_t n_ch = hparams.n_embd_r() / std::max<int64_t>(1, hparams.ssm_d_conv - 1);
const int64_t n_embd_r = this->rs_replay ? n_ch*(hparams.ssm_d_conv - 1 + n_pend) : hparams.n_embd_r();
const uint32_t n_rows = mem_size * (this->rs_replay ? 1 : 1 + n_rs_seq);
ggml_tensor * r = ggml_new_tensor_2d(ctx, type_r, n_embd_r, n_rows);
ggml_tensor * s = ggml_new_tensor_2d(ctx, type_s, hparams.n_embd_s(), n_rows);
ggml_format_name(r, "cache_r_l%d", i);
ggml_format_name(s, "cache_s_l%d", i);
r_l[i] = r;
s_l[i] = s;
if (this->rs_replay) {
// k [S_k, H_k, n_pend], v [S_v, H_v, n_pend], gb [g0, H_v, 2*n_pend]: separate rows, so that a split by heads
// is one axis of each (-sm tensor). The gate is a scalar per head (g0 = 1), or per key dim for KDA (g0 = S_v)
const bool kda = hparams.n_embd_head_kda != 0;
const int64_t n_k = kda ? (int64_t) hparams.n_embd_head_kda*hparams.n_head() : (int64_t) hparams.ssm_d_state*hparams.ssm_n_group;
const int64_t n_v = kda ? n_k : (int64_t) hparams.ssm_d_inner;
const int64_t n_gb = kda ? n_k : (int64_t) hparams.ssm_dt_rank;
ggml_tensor * spk = ggml_new_tensor_2d(ctx, type_s, n_k*n_pend, mem_size);
ggml_tensor * spv = ggml_new_tensor_2d(ctx, type_s, n_v*n_pend, mem_size);
ggml_tensor * spgb = ggml_new_tensor_2d(ctx, type_s, n_gb*2*n_pend, mem_size);
ggml_format_name(spk, "cache_spk_l%d", i);
ggml_format_name(spv, "cache_spv_l%d", i);
ggml_format_name(spgb, "cache_spgb_l%d", i);
spk_l[i] = spk;
spv_l[i] = spv;
spgb_l[i] = spgb;
}
// the PLE history needs its own row: Meta must mirror it while the delta-net conv state next door stays split
if (hparams.ple_conv_state() > 0 && hparams.is_ple(i)) {
ggml_tensor * p = ggml_new_tensor_2d(ctx, type_r, hparams.ple_conv_state(), n_rows);
// rs_replay: [channels, window + n_pend], like r
const int64_t n_win_p = (int64_t) (hparams.ple_conv_kernel - 1)*hparams.ple_ngram_size;
const int64_t n_embd_p = this->rs_replay ? hparams.ple_conv_state()/n_win_p*(n_win_p + n_pend) : hparams.ple_conv_state();
ggml_tensor * p = ggml_new_tensor_2d(ctx, type_r, n_embd_p, n_rows);
ggml_format_name(p, "cache_ple_r_l%d", i);
p_l[i] = p;
}
@@ -124,7 +157,8 @@ llama_memory_recurrent::llama_memory_recurrent(
if (is_empty()) {
if (n_rs_seq > 0) {
n_rs_seq = 0;
n_rs_seq = 0;
rs_replay = false;
LLAMA_LOG_INFO("%s: disabling rollback snapshots because the memory module is empty\n", __func__);
}
}
@@ -134,8 +168,8 @@ llama_memory_recurrent::llama_memory_recurrent(
const size_t memory_size_s = size_s_bytes();
const size_t memory_size_p = size_p_bytes();
LLAMA_LOG_INFO("%s: size = %7.2f MiB (%6u cells, %3d layers, %2u seqs %2u rs_seq), R (%s): %7.2f MiB, S (%s): %7.2f MiB, P (%s): %7.2f MiB\n", __func__,
(float)(memory_size_r + memory_size_s + memory_size_p) / (1024.0f * 1024.0f), mem_size, n_layer, n_seq_max, n_rs_seq,
LLAMA_LOG_INFO("%s: size = %7.2f MiB (%6u cells, %3d layers, %2u seqs %2u rs_seq%s), R (%s): %7.2f MiB, S (%s): %7.2f MiB, P (%s): %7.2f MiB\n", __func__,
(float)(memory_size_r + memory_size_s + memory_size_p) / (1024.0f * 1024.0f), mem_size, n_layer, n_seq_max, n_rs_seq, rs_replay ? " replay" : "",
ggml_type_name(type_r), (float)memory_size_r / (1024.0f * 1024.0f),
ggml_type_name(type_s), (float)memory_size_s / (1024.0f * 1024.0f),
ggml_type_name(type_r), (float)memory_size_p / (1024.0f * 1024.0f));
@@ -149,6 +183,8 @@ void llama_memory_recurrent::clear(bool data) {
cells[i].src = -1;
cells[i].tail = -1;
cells[i].rs_max = 0;
cells[i].rs_pend = 0;
cells[i].rs_rep = 0;
}
head = 0;
@@ -210,7 +246,13 @@ bool llama_memory_recurrent::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos
// pending rollback is single-use
const bool pending = rs_idx[seq_id] != 0;
if (!pending && rollback >= 1 && rollback <= (llama_pos) cell.rs_max) {
set_rs_idx(seq_id, (uint32_t) rollback);
if (rs_replay) {
// the next ubatch replays only the kept pending tokens
cell.rs_pend -= rollback;
cell.rs_max = 0;
} else {
set_rs_idx(seq_id, (uint32_t) rollback);
}
cell.pos = p0 - 1;
return true;
}
@@ -615,6 +657,7 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) {
auto & orig_cell = cells[seq_meta.tail];
empty_cell.pos = orig_cell.pos;
empty_cell.src = orig_cell.src;
empty_cell.rs_pend = orig_cell.rs_pend;
orig_cell.seq_id.erase(seq_id);
empty_cell.seq_id.insert(seq_id); // will be overwritten
GGML_ASSERT(!orig_cell.is_empty()); // has at least one remaining seq_id
@@ -645,7 +688,13 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) {
std::swap(dst_cell.pos, src_cell.pos);
std::swap(dst_cell.src, src_cell.src);
std::swap(dst_cell.rs_max, src_cell.rs_max);
std::swap(dst_cell.rs_pend, src_cell.rs_pend);
std::swap(dst_cell.seq_id, src_cell.seq_id);
// the cell moved out only gets its final state copied, its rollback snapshots stay behind
if (!rs_replay) {
src_cell.rs_max = 0;
}
// swap tails
for (uint32_t j = 0; j < size; ++j) {
@@ -674,6 +723,11 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) {
}
cell.pos = last_pos;
cell.rs_max = n_seq_tokens <= n_rs_seq + 1 ? n_seq_tokens - 1 : 0;
if (rs_replay) {
// replay what the last ubatch left pending, then keep this ubatch pending if it can be rolled back
cell.rs_rep = cell.src >= 0 ? cell.rs_pend : 0;
cell.rs_pend = cell.rs_max > 0 ? n_seq_tokens : 0;
}
cell.seq_id.clear();
for (int32_t j = 0; j < ubatch.n_seq_id[i]; ++j) {
const llama_seq_id seq_id = ubatch.seq_id[i][j];
@@ -753,6 +807,7 @@ size_t llama_memory_recurrent::size_r_bytes() const {
}
}
return size_r_bytes;
}
@@ -765,6 +820,14 @@ size_t llama_memory_recurrent::size_s_bytes() const {
}
}
for (const auto * sp : { &spk_l, &spv_l, &spgb_l }) {
for (const auto & s : *sp) {
if (s != nullptr) {
size_s_bytes += ggml_nbytes(s);
}
}
}
return size_s_bytes;
}
@@ -907,6 +970,10 @@ void llama_memory_recurrent::state_write_meta(llama_io_write_i & io, const std::
io.write(&seq_id, sizeof(seq_id));
}
}
if (rs_replay) {
io.write(&cell.rs_pend, sizeof(cell.rs_pend));
}
}
}
}
@@ -929,7 +996,7 @@ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std::
io.write(&r_type_i, sizeof(r_type_i));
// Write row size of R tensor
const uint64_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r());
const uint64_t r_size_row = r_l[il]->nb[1];
io.write(&r_size_row, sizeof(r_size_row));
// Write each logical cell row range. With pending recurrent rollback,
@@ -942,7 +1009,7 @@ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std::
// the PLE conv history is a second recurrent row, so it has to travel with the first
if (p_l[il] != nullptr) {
const uint64_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state());
const uint64_t p_size_row = p_l[il]->nb[1];
io.write(&p_size_row, sizeof(p_size_row));
for (const auto & range : cell_ranges) {
@@ -1004,6 +1071,22 @@ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std::
}
}
}
// rs_replay pending inputs travel with their cells
if (rs_replay) {
for (uint32_t il = 0; il < n_layer; ++il) {
for (ggml_tensor * t : { spk_l[il], spv_l[il], spgb_l[il] }) {
if (t == nullptr) continue;
const uint64_t size_row = t->nb[1];
io.write(&size_row, sizeof(size_row));
for (const auto & range : cell_ranges) {
io.write_tensor(t, range.first * size_row, (range.second - range.first) * size_row);
}
}
}
}
}
bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell_count, llama_seq_id dest_seq_id) {
@@ -1024,6 +1107,8 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell
llama_ubatch ubatch = balloc.ubatch_reserve(cell_count, 1);
std::vector<uint32_t> rs_pend(cell_count, 0);
for (uint32_t i = 0; i < cell_count; ++i) {
llama_pos pos;
uint32_t n_seq_id;
@@ -1036,6 +1121,10 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell
return false;
}
if (rs_replay) {
io.read(&rs_pend[i], sizeof(rs_pend[i]));
}
ubatch.pos[i] = pos;
}
ubatch.n_seq_id[0] = 1;
@@ -1053,6 +1142,11 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell
GGML_ASSERT(cells[head + cell_count - 1].pos == ubatch.pos[cell_count - 1]);
GGML_ASSERT(cells[head].has_seq_id(dest_seq_id));
GGML_ASSERT(cells[head + cell_count - 1].has_seq_id(dest_seq_id));
for (uint32_t i = 0; i < cell_count; ++i) {
cells[head + i].rs_pend = rs_pend[i];
cells[head + i].rs_max = 0;
}
} else {
// whole KV cache restore
@@ -1092,6 +1186,10 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell
}
tail = i;
}
if (rs_replay) {
io.read(&cell.rs_pend, sizeof(cell.rs_pend));
}
}
head = 0;
@@ -1143,7 +1241,7 @@ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell
// Read row size of key
uint64_t r_size_row_ref;
io.read(&r_size_row_ref, sizeof(r_size_row_ref));
const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r());
const size_t r_size_row = r_l[il]->nb[1];
if (r_size_row != r_size_row_ref) {
LLAMA_LOG_ERROR("%s: mismatched r row size (%zu != %zu, layer %d)\n", __func__, r_size_row, (size_t) r_size_row_ref, il);
return false;
@@ -1157,7 +1255,7 @@ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell
if (p_l[il] != nullptr) {
uint64_t p_size_row_ref;
io.read(&p_size_row_ref, sizeof(p_size_row_ref));
const size_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state());
const size_t p_size_row = p_l[il]->nb[1];
if (p_size_row != p_size_row_ref) {
LLAMA_LOG_ERROR("%s: mismatched ple row size (%zu != %zu, layer %d)\n", __func__, p_size_row, (size_t) p_size_row_ref, il);
return false;
@@ -1242,6 +1340,25 @@ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell
}
}
if (rs_replay) {
for (uint32_t il = 0; il < n_layer; ++il) {
for (ggml_tensor * t : { spk_l[il], spv_l[il], spgb_l[il] }) {
if (t == nullptr) continue;
uint64_t size_row_ref;
io.read(&size_row_ref, sizeof(size_row_ref));
if (size_row_ref != t->nb[1]) {
LLAMA_LOG_ERROR("%s: mismatched pending row size (%zu != %zu, layer %d)\n", __func__, t->nb[1], (size_t) size_row_ref, il);
return false;
}
if (cell_count) {
io.read_tensor(t, head * t->nb[1], cell_count * t->nb[1]);
}
}
}
}
return true;
}
@@ -1264,7 +1381,7 @@ void llama_memory_recurrent::state_clear(llama_seq_id seq_id, uint32_t cell_head
for (uint32_t il = 0; il < n_layer; ++il) {
if (r_l[il] != nullptr) {
const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r());
const size_t r_size_row = r_l[il]->nb[1];
ggml_backend_tensor_memset(r_l[il], 0, cell_head * r_size_row, cell_count * r_size_row);
}
@@ -1274,7 +1391,7 @@ void llama_memory_recurrent::state_clear(llama_seq_id seq_id, uint32_t cell_head
}
if (p_l[il] != nullptr) {
const size_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state());
const size_t p_size_row = p_l[il]->nb[1];
ggml_backend_tensor_memset(p_l[il], 0, cell_head * p_size_row, cell_count * p_size_row);
}
}
@@ -1360,6 +1477,26 @@ ggml_tensor * llama_memory_recurrent_context::get_p_l(int32_t il) const {
return mem->p_l[il];
}
ggml_tensor * llama_memory_recurrent_context::get_spk_l(int32_t il) const {
return mem->spk_l[il];
}
ggml_tensor * llama_memory_recurrent_context::get_spv_l(int32_t il) const {
return mem->spv_l[il];
}
ggml_tensor * llama_memory_recurrent_context::get_spgb_l(int32_t il) const {
return mem->spgb_l[il];
}
bool llama_memory_recurrent_context::get_rs_replay() const {
return mem->rs_replay;
}
uint32_t llama_memory_recurrent_context::get_rs_rep(int i) const {
return is_full ? 0 : mem->cells[i + mem->head].rs_rep;
}
int32_t llama_memory_recurrent_context::s_copy(int i) const {
const uint32_t cell_idx = i + mem->head;
const int32_t src0 = mem->cells[cell_idx].src0;
+19 -1
View File
@@ -25,6 +25,7 @@ public:
uint32_t mem_size,
uint32_t n_seq_max,
uint32_t n_rs_seq,
bool rs_replay,
const layer_filter_cb & filter);
~llama_memory_recurrent() = default;
@@ -77,6 +78,9 @@ public:
// per-seq rollback index
std::vector<uint32_t> rs_idx;
// deferred commit: keep one state plane plus the inputs of the last ubatch, replay the accepted part in the next ubatch
bool rs_replay = false;
void set_rs_idx(llama_seq_id seq_id, uint32_t idx);
// computed before each graph build
@@ -93,9 +97,13 @@ public:
int32_t tail = -1;
// largest rollback whose snapshot the last ubatch guarantees: a ubatch of n <= n_rs_seq + 1 tokens
// writes snapshots 0..n-1, a longer one only guarantees the final state (ggml_gated_delta_net)
// writes snapshots 0..n-1, a longer one only guarantees the final state (ggml_ssm_scan)
uint32_t rs_max = 0;
// rs_replay: valid tokens in the pending rows, and the pending tokens the current ubatch replays
uint32_t rs_pend = 0;
uint32_t rs_rep = 0;
std::set<llama_seq_id> seq_id;
bool has_seq_id(const llama_seq_id & id) const {
@@ -118,6 +126,10 @@ public:
std::vector<ggml_tensor *> s_l;
// a second conv history that must stay replicated across devices, so it cannot share the r row
std::vector<ggml_tensor *> p_l;
// rs_replay pending gdn inputs: k, v, and the gates then the betas
std::vector<ggml_tensor *> spk_l;
std::vector<ggml_tensor *> spv_l;
std::vector<ggml_tensor *> spgb_l;
private:
//const llama_model & model;
@@ -184,9 +196,15 @@ public:
ggml_tensor * get_r_l(int32_t il) const;
ggml_tensor * get_s_l(int32_t il) const;
ggml_tensor * get_p_l(int32_t il) const;
ggml_tensor * get_spk_l (int32_t il) const;
ggml_tensor * get_spv_l (int32_t il) const;
ggml_tensor * get_spgb_l(int32_t il) const;
int32_t s_copy(int i) const;
bool get_rs_replay() const;
uint32_t get_rs_rep(int i) const; // pending tokens replayed by ubatch seq i
private:
const llama_memory_status status;
-12
View File
@@ -173,18 +173,6 @@ void llama_model_saver::add_kv_from_model() {
// add_kv(LLM_KV_GENERAL_SAMPLING_MIROSTAT_ETA, ???);
add_kv(LLM_KV_GENERAL_NAME, model->name);
if (!model->prec_policy.prec_src1.empty()) {
std::vector<std::string> tensor_names;
std::vector<int8_t> values;
tensor_names.reserve(model->prec_policy.prec_src1.size());
values.reserve(model->prec_policy.prec_src1.size());
for (const auto & [w, prec] : model->prec_policy.prec_src1) {
tensor_names.push_back(ggml_get_name(w));
values.push_back(prec == GGML_PREC_Q8 ? 0 : 1);
}
add_kv(LLM_KV_GENERAL_TENSOR_EXTRA_NAME, tensor_names);
gguf_set_arr_data(gguf_ctx, llm_kv(LLM_KV_GENERAL_TENSOR_EXTRA_PREC_A4).c_str(), GGUF_TYPE_BOOL, values.data(), values.size());
}
// add_kv(LLM_KV_GENERAL_AUTHOR, ???);
// add_kv(LLM_KV_GENERAL_VERSION, ???);
// add_kv(LLM_KV_GENERAL_URL, ???);
+97 -19
View File
@@ -29,6 +29,7 @@
#include <cassert>
#include <cfloat>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <functional>
@@ -467,6 +468,9 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
static const std::regex pattern_r_cache ("cache_r_l\\d*");
static const std::regex pattern_ple_r_cache ("cache_ple_r_l\\d*");
static const std::regex pattern_s_cache ("cache_s_l\\d*");
static const std::regex pattern_spk_cache ("cache_spk_l\\d*");
static const std::regex pattern_spv_cache ("cache_spv_l\\d*");
static const std::regex pattern_spgb_cache ("cache_spgb_l\\d*");
static const std::regex pattern_ssm_conv1d ("blk\\.\\d*\\.ssm_conv1d.weight");
static const std::regex pattern_ssm_out_weight ("blk\\.\\d*\\.ssm_out.weight");
static const std::regex pattern_kda_conv1d ("blk\\.\\d*\\.ssm_conv1d_(q|k|v)\\.weight");
@@ -576,7 +580,9 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_2, "attn_output.weight");
}
if (std::regex_match(tensor_name, pattern_ssm_dt) || std::regex_match(tensor_name, pattern_ssm_a) ||
std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache)) {
std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache) ||
std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) ||
std::regex_match(tensor_name, pattern_spgb_cache)) {
return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_0, "attn_output.weight");
}
}
@@ -641,7 +647,9 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
std::regex_match(tensor_name, pattern_ssm_beta_alpha) || std::regex_match(tensor_name, pattern_ssm_beta_alpha_cat)) {
return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_1, "ssm_out.weight");
}
if (std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache)) {
if (std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache) ||
std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) ||
std::regex_match(tensor_name, pattern_spgb_cache)) {
if (ud->model->arch == LLM_ARCH_LFM2 || ud->model->arch == LLM_ARCH_LFM2MOE || ud->model->arch == LLM_ARCH_LFM3) {
// the LFM2 shortconv block runs fully mirrored, so its conv state must be mirrored too
return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_MIRRORED, "");
@@ -696,10 +704,22 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
auto get_split_segments = [&](int axis, uint32_t il) -> std::vector<std::pair<int64_t, uint32_t>> {
if (is_glm5_next && std::regex_match(tensor_name, pattern_r_cache)) {
// the conv state holds the q, k and v windows one after the other
const int64_t conv_state_size = (hparams.ssm_d_conv - 1) * hparams.n_head(il) * hparams.n_embd_head_kda;
GGML_ASSERT(tensor->ne[axis] == 3*conv_state_size);
const int64_t d_inner = hparams.n_head(il) * hparams.n_embd_head_kda;
const int64_t conv_state_size = (hparams.ssm_d_conv - 1) * d_inner;
if (tensor->ne[axis] != 3*conv_state_size) {
// replay: q, k and v histories [d_inner, window + pending], every column is a block of heads
GGML_ASSERT(tensor->ne[axis] % (3*d_inner) == 0);
return {{d_inner, uint32_t(tensor->ne[axis] / d_inner)}};
}
return {{conv_state_size, 3}};
}
if (is_glm5_next && (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) ||
std::regex_match(tensor_name, pattern_spgb_cache))) {
// replay pending inputs, per token: k [S_k, H], v [S_v, H], then the gates [S_v, H] and the betas (in element 0)
const int64_t d_inner = hparams.n_head(il) * hparams.n_embd_head_kda;
GGML_ASSERT(tensor->ne[axis] % d_inner == 0);
return {{d_inner, uint32_t(tensor->ne[axis] / d_inner)}};
}
// TODO: deduplicate condition [TAG_SPLIT_QGATE_QWEN]
// zonos3 has the qwen35 GDN layout, its attention layers have no fused qkv
if (ud->model->arch == LLM_ARCH_QWEN3NEXT || ud->model->arch == LLM_ARCH_QWEN35 || ud->model->arch == LLM_ARCH_QWEN35MOE || ud->model->arch == LLM_ARCH_CLEF || ud->model->arch == LLM_ARCH_CLOVER_MOE ||
@@ -730,6 +750,8 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
return {{key_dim, 2}, {value_dim, 1}};
}
if (std::regex_match(tensor_name, pattern_r_cache)) {
// the replay layouts need the Qwen 3.5 pattern, llama_context keeps Qwen 3 Next on snapshots
GGML_ASSERT(tensor->ne[axis] == (2*key_dim + value_dim) * (hparams.ssm_d_conv - 1));
return {{key_dim * (hparams.ssm_d_conv - 1), 2}, {value_dim * (hparams.ssm_d_conv - 1), 1}};
}
} else {
@@ -754,11 +776,26 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
return {{n_k_heads, head_ratio}};
}
if (std::regex_match(tensor_name, pattern_r_cache)) {
const int64_t n_conv_ch = 2*key_dim + value_dim;
if (tensor->ne[axis] != n_conv_ch * (hparams.ssm_d_conv - 1)) {
// replay: [channels, window + pending] per cell, every column is a q, k, v block
GGML_ASSERT(tensor->ne[axis] % n_conv_ch == 0);
return {{key_dim, uint32_t((2 + head_ratio) * (tensor->ne[axis] / n_conv_ch))}};
}
return {{key_dim * (hparams.ssm_d_conv - 1), 2 + head_ratio}};
}
if (std::regex_match(tensor_name, pattern_s_cache)) {
return {{n_k_heads * head_v_dim * head_v_dim, head_ratio}};
}
// replay pending inputs, per token: k [S_k, H_k], v [S_v, H_v], then the gates and betas [H_v]
if (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache)) {
GGML_ASSERT(tensor->ne[axis] % key_dim == 0);
return {{key_dim, uint32_t(tensor->ne[axis] / key_dim)}};
}
if (std::regex_match(tensor_name, pattern_spgb_cache)) {
GGML_ASSERT(tensor->ne[axis] % n_k_heads == 0);
return {{n_k_heads, uint32_t(tensor->ne[axis] / n_k_heads)}};
}
}
// the FFN is the same for Qwen 3 Next and Qwen 3.5:
@@ -814,7 +851,14 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
return {granularity_qkv / head_dim};
}
if (std::regex_match(tensor_name, pattern_r_cache)) {
return std::vector<int64_t>(segments.size(), granularity_qkv * (hparams.ssm_d_conv - 1));
// replay: channels first, each segment is a single conv column
const int64_t conv_state_size = (hparams.ssm_d_conv - 1) * hparams.n_head(il) * head_dim;
const bool replay = tensor->ne[0] != 3*conv_state_size;
return std::vector<int64_t>(segments.size(), granularity_qkv * (replay ? 1 : hparams.ssm_d_conv - 1));
}
if (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) ||
std::regex_match(tensor_name, pattern_spgb_cache)) {
return std::vector<int64_t>(segments.size(), granularity_qkv);
}
if (std::regex_match(tensor_name, pattern_s_cache)) {
return {granularity_qkv * head_dim};
@@ -851,11 +895,20 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
return std::vector<int64_t>(segments.size(), 2 * (granularity_qkv / head_dim));
}
if (std::regex_match(tensor_name, pattern_r_cache)) {
return std::vector<int64_t>(segments.size(), granularity_qkv * (hparams.ssm_d_conv - 1));
// replay: [channels, window + pending], each segment is a single conv column
const int64_t n_conv_ch = 2*hparams.ssm_n_group*hparams.ssm_d_state + hparams.ssm_d_inner;
const bool replay = tensor->ne[0] != n_conv_ch * (hparams.ssm_d_conv - 1);
return std::vector<int64_t>(segments.size(), granularity_qkv * (replay ? 1 : hparams.ssm_d_conv - 1));
}
if (std::regex_match(tensor_name, pattern_s_cache)) {
return std::vector<int64_t>(segments.size(), granularity_qkv * head_dim);
}
if (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache)) {
return std::vector<int64_t>(segments.size(), granularity_qkv);
}
if (std::regex_match(tensor_name, pattern_spgb_cache)) {
return std::vector<int64_t>(segments.size(), granularity_qkv / head_dim);
}
} else {
// regular attention
const uint32_t n_gqa = hparams.n_gqa(il);
@@ -1405,19 +1458,24 @@ struct llama_model::impl {
std::vector<float> tensor_split_owned;
};
bool llama_prec_policy::apply(ggml_tensor * res) const {
if (!res || !res->src[0]) {
bool llama_prec_policy::apply(ggml_tensor * res, const ggml_tensor * w) const {
if (!res) {
return false;
}
const ggml_tensor * key = w ? w : res->src[0];
if (!key) {
return false;
}
bool applied = false;
const auto it_acc = prec_acc.find(res->src[0]);
const auto it_acc = prec_acc.find(key);
if (it_acc != prec_acc.end()) {
applied |= ggml_prec_set_acc(res, it_acc->second);
}
const auto it_src1 = prec_src1.find(res->src[0]);
const auto it_src1 = prec_src1.find(key);
if (it_src1 != prec_src1.end()) {
applied |= ggml_prec_set_src(res, it_src1->second, 1);
}
@@ -1724,6 +1782,30 @@ void llama_model_base::load_vocab(llama_model_loader & ml) {
vocab.load(ml, kv);
}
void llama_model_base::load_prec_policy(llama_model_loader & ml) {
// the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/60d8d70770c6776ff598c94bb586a859a38244f1/inference/model.py#L565
if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS || hparams.expert_router_f32) {
for (const auto & layer : layers) {
prec_policy.set_acc(layer.ffn_gate_inp, GGML_PREC_F32);
}
}
if (getenv("LLAMA_MOE_AMAX_SKIP") != nullptr) {
LLAMA_LOG_WARN("LLAMA_MOE_AMAX_SKIP is set - the MoE amax rescaling is disabled\n");
if (llm_arch_mmid_down_bf16(arch)) {
for (const auto & layer : layers) {
if (layer.ffn_down_exps) {
prec_policy.set_src1(layer.ffn_down_exps, GGML_PREC_BF16);
}
}
}
}
// per-tensor activation precision policy
prec_policy.load(ml, *this);
}
bool llama_model_base::load_tensors(llama_model_loader & ml) {
const auto & split_mode = params.split_mode;
const bool use_mlock = params.load_mode == LLAMA_LOAD_MODE_MLOCK || params.load_mode == LLAMA_LOAD_MODE_MMAP_MLOCK;
@@ -2080,15 +2162,7 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
}
}
// the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/60d8d70770c6776ff598c94bb586a859a38244f1/inference/model.py#L565
if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS || hparams.expert_router_f32) {
for (const auto & layer : layers) {
prec_policy.set_acc(layer.ffn_gate_inp, GGML_PREC_F32);
}
}
// per-tensor activation precision policy
prec_policy.load(ml, *this);
load_prec_policy(ml);
ml.init_mappings(true, use_mlock ? &pimpl->mlock_mmaps : nullptr);
pimpl->mappings.reserve(ml.mappings.size());
@@ -3198,6 +3272,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
/* recurrent_rs_size */ std::max((uint32_t) 1, cparams.n_seq_max),
/* n_seq_max */ cparams.n_seq_max,
/* n_rs_seq */ cparams.n_rs_seq,
/* rs_replay */ cparams.rs_replay,
/* offload */ cparams.offload_kqv,
/* unified */ cparams.kv_unified,
/* filter_attn */ std::move(filter_attn),
@@ -3411,6 +3486,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
std::max((uint32_t) 1, cparams.n_seq_max),
cparams.n_seq_max,
cparams.n_rs_seq,
false,
nullptr);
} else if (llm_arch_is_hybrid(arch) && !mtp_on_hybrid_qwen && !mtp_on_hybrid_nemotron) {
// The main difference between hybrid architectures is the
@@ -3505,6 +3581,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
/* recurrent_kv_size */ std::max((uint32_t) 1, cparams.n_seq_max),
/* n_seq_max */ cparams.n_seq_max,
/* n_rs_seq */ cparams.n_rs_seq,
/* rs_replay */ cparams.rs_replay,
/* offload */ cparams.offload_kqv,
/* unified */ cparams.kv_unified,
/* filter_attn */ std::move(filter_attn),
@@ -3525,6 +3602,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
/* recurrent_kv_size */ std::max((uint32_t) 1, cparams.n_seq_max),
/* n_seq_max */ cparams.n_seq_max,
/* n_rs_seq */ cparams.n_rs_seq,
/* rs_replay */ cparams.rs_replay,
/* offload */ cparams.offload_kqv,
/* unified */ cparams.kv_unified,
/* filter_attn */ std::move(filter_attn),
+13 -1
View File
@@ -743,7 +743,7 @@ struct llama_prec_policy {
// the key is the weight tensor `res->src[0]`, stores the recommended activation precision type
std::unordered_map<const ggml_tensor *, ggml_prec> prec_src1;
bool apply(ggml_tensor * res) const;
bool apply(ggml_tensor * res, const ggml_tensor * w = nullptr) const;
void set_acc(const ggml_tensor * w, ggml_prec prec) {
if (w) {
@@ -751,6 +751,17 @@ struct llama_prec_policy {
}
}
void set_src1(const ggml_tensor * w, ggml_prec prec) {
if (w) {
prec_src1[w] = prec;
}
}
ggml_prec get_src1(const ggml_tensor * w) const {
const auto it = prec_src1.find(w);
return it != prec_src1.end() ? it->second : GGML_PREC_UNDEFINED;
}
void load(llama_model_loader & ml, const llama_model & model);
};
@@ -1146,6 +1157,7 @@ struct llama_model_base : public llama_model {
void load_hparams(llama_model_loader & ml) override;
void load_vocab (llama_model_loader & ml) override;
bool load_tensors(llama_model_loader & ml) override;
void load_prec_policy(llama_model_loader & ml);
// model must define these
void load_arch_hparams(llama_model_loader & ml) override = 0;
+2796 -576
View File
File diff suppressed because it is too large Load Diff
+20 -13
View File
@@ -163,22 +163,29 @@ std::unique_ptr<llm_graph_context> llama_model_bailingmoe3::build_arch_graph(con
ggml_tensor * llama_model_bailingmoe3::graph::build_causal_conv1d(
llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs) {
int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs, int il) {
const int64_t d_inner = head_dim * n_head;
const int64_t conv_state_size = (d_conv - 1) * d_inner;
const int64_t total_state_size = 3 * conv_state_size;
ggml_tensor * conv_state = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
(d_conv - 1) * ggml_element_size(conv_state_all),
total_state_size * ggml_element_size(conv_state_all),
qkv * conv_state_size * ggml_element_size(conv_state_all));
ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x);
x_proj = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs);
ggml_tensor * conv_x = ggml_concat(ctx0, conv_state, ggml_transpose(ctx0, x_proj), 0);
build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
ggml_row_size(conv_states_all->type, qkv * conv_state_size));
ggml_tensor * conv_x = nullptr;
if (cparams.rs_replay) {
// the row holds the q, k and v conv histories one after the other
conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_proj, d_conv - 1, d_inner, il, conv_state_all, qkv);
} else {
ggml_tensor * conv_state = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
(d_conv - 1) * ggml_element_size(conv_state_all),
total_state_size * ggml_element_size(conv_state_all),
qkv * conv_state_size * ggml_element_size(conv_state_all));
conv_x = ggml_concat(ctx0, conv_state, ggml_transpose(ctx0, x_proj), 0);
build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
ggml_row_size(conv_states_all->type, qkv * conv_state_size));
}
ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner);
ggml_tensor * out = ggml_ssm_conv(ctx0, conv_x, conv_weight);
@@ -227,17 +234,17 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) :
if (hparams.is_recr(il)) {
const auto * mctx_cur = inp_rs->mctx;
ggml_tensor * conv_states_all = mctx_cur->get_r_l(il);
ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs);
ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs);
ggml_tensor * q = build_causal_conv1d(
inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv,
d_conv, head_dim, n_head, n_seq_tokens, n_seqs);
d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il);
ggml_tensor * k = build_causal_conv1d(
inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv,
d_conv, head_dim, n_head, n_seq_tokens, n_seqs);
d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il);
ggml_tensor * v = build_causal_conv1d(
inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv,
d_conv, head_dim, n_head, n_seq_tokens, n_seqs);
d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il);
ggml_tensor * gate = ggml_mul_mat(ctx0, layer.ssm_f_a, cur);
gate = ggml_add(ctx0, gate, layer.ssm_dt_b);
+179 -57
View File
@@ -32,8 +32,8 @@ std::pair<ggml_tensor *, ggml_tensor *> llm_build_delta_net_base::build_delta_ne
GGML_ASSERT(b->ne[0] == 1 && b->ne[1] == H_v && b->ne[2] == n_tokens && b->ne[3] == n_seqs);
GGML_ASSERT(s->ne[0] == S_v && s->ne[1] == S_v && s->ne[2] == H_v && s->ne[3] == n_seqs);
// K=1: output carries the final state only. state s is 4D [S_v, S_v, H_v, n_seqs].
ggml_tensor * result = ggml_gated_delta_net(ctx0, q, k, v, g, b, s, /*K=*/1);
// output carries the final state. state s is 4D [S_v, S_v, H_v, n_seqs].
ggml_tensor * result = ggml_gated_delta_net_ext(ctx0, q, k, v, g, b, s, nullptr, nullptr, nullptr, nullptr, false);
ggml_tensor * output = ggml_view_4d(ctx0, result,
S_v, H_v, n_tokens, n_seqs,
ggml_row_size(result->type, S_v),
@@ -59,6 +59,10 @@ ggml_tensor * llm_build_delta_net_base::build_conv_state(
int il) {
const int64_t n_seqs = ubatch.n_seqs;
if (cparams.rs_replay) {
return build_conv_state_replay(inp, conv_states_all, qkv_mixed, conv_kernel_size - 1, conv_channels, il);
}
ggml_tensor * conv_states = build_rs(inp, conv_states_all, hparams.n_embd_r(), n_seqs);
cb(conv_states, "conv_states", il);
@@ -76,6 +80,165 @@ ggml_tensor * llm_build_delta_net_base::build_conv_state(
return conv_input;
}
// [TAG_RECURRENT_REPLAY]
// rs_replay keeps one committed state per seq plus the inputs of the last ubatch when it is short enough to be rolled
// back (2 <= n_seq_tokens <= n_rs_seq + 1). The next ubatch first replays the pending tokens that seq_rm kept, commits
// the result and then runs its own tokens. Must match the rule in llama_memory_recurrent::find_slot.
// Every ubatch builds the same nodes, with or without pending tokens, so the allocation planned at reserve time
// stays valid and the scheduler never re-plans.
static bool rs_replay_keep(const llama_cparams & cparams, int64_t n_seq_tokens) {
return n_seq_tokens >= 2 && n_seq_tokens <= (int64_t) cparams.n_rs_seq + 1;
}
ggml_tensor * llm_build_delta_net_base::build_conv_state_replay(
llm_graph_input_rs * inp,
ggml_tensor * conv_states_all,
ggml_tensor * x,
int64_t n_conv,
int64_t channels,
int il,
ggml_tensor * hist_rows,
int64_t blk) {
const auto * mctx_cur = inp->mctx;
const auto kv_head = mctx_cur->get_head();
const int64_t n_hist = n_conv + cparams.n_rs_seq + 1;
const int64_t n_seqs = ubatch.n_seqs;
const int64_t n_seq_tokens = ubatch.n_seq_tokens;
GGML_ASSERT(conv_states_all->ne[0] % (channels*n_hist) == 0);
const int64_t n_blk = conv_states_all->ne[0] / (channels*n_hist);
GGML_ASSERT(blk >= 0 && blk < n_blk);
GGML_ASSERT(x->ne[0] == channels && x->ne[1] == n_seq_tokens && x->ne[2] == n_seqs);
GGML_ASSERT(n_conv <= inp->n_conv);
if (hist_rows == nullptr) {
hist_rows = build_rs(inp, conv_states_all, conv_states_all->ne[0], n_seqs);
}
GGML_ASSERT(hist_rows->ne[0] == conv_states_all->ne[0] && hist_rows->ne[1] == n_seqs);
// channels first: [window | pending], the histories of a row one after the other
ggml_tensor * hist = nullptr;
if (n_blk == 1) {
hist = ggml_reshape_3d(ctx0, hist_rows, channels, n_hist, n_seqs);
} else {
hist = ggml_reshape_4d(ctx0, hist_rows, channels, n_hist, n_blk, n_seqs);
hist = ggml_view_3d(ctx0, hist, channels, n_hist, n_seqs, hist->nb[1], hist->nb[3], blk*hist->nb[2]);
}
cb(hist, "conv_hist", il);
ggml_tensor * win_cols = n_conv == inp->rep_cols_r->ne[0] ? inp->rep_cols_r : inp->rep_cols_p;
GGML_ASSERT(win_cols && win_cols->ne[0] == n_conv);
// [channels, n_conv + n_seq_tokens]: the window after the kept pending tokens, then the new tokens
// (built channels first, a transposed concat is much slower than a concat and a transpose)
ggml_tensor * cols = ggml_concat(ctx0, ggml_get_rows(ctx0, hist, win_cols), x, 1);
ggml_tensor * conv_input = ggml_cont(ctx0, ggml_transpose(ctx0, cols));
cb(conv_input, "conv_input", il);
// keep: the new tokens stay pending behind the committed window, else commit the last n_conv columns
const int64_t n_dst = rs_replay_keep(cparams, n_seq_tokens) ? n_conv + n_seq_tokens : n_conv;
ggml_tensor * tail = ggml_view_3d(ctx0, cols, channels, n_dst, n_seqs, cols->nb[1], cols->nb[2],
(n_conv + n_seq_tokens - n_dst)*cols->nb[1]);
// the rows as [channels, n_blk*n_hist, cells], so that the view of the ubatch cells keeps their strides (-sm tensor)
ggml_tensor * hist_all = ggml_reshape_3d(ctx0, conv_states_all, channels, n_blk*n_hist, conv_states_all->ne[1]);
ggml_tensor * hist_dst = ggml_view_3d(ctx0, hist_all, channels, n_dst, n_seqs, hist_all->nb[1], hist_all->nb[2],
kv_head*hist_all->nb[2] + blk*n_hist*hist_all->nb[1]);
ggml_build_forward_expand(gf, ggml_cpy(ctx0, tail, hist_dst));
return conv_input;
}
ggml_tensor * llm_build_delta_net_base::build_recurrent_attn_replay(
llm_graph_input_rs * inp,
ggml_tensor * ssm_states_all,
ggml_tensor * q,
ggml_tensor * k,
ggml_tensor * v,
ggml_tensor * g,
ggml_tensor * b,
ggml_tensor * s,
int il) {
const auto * mctx_cur = inp->mctx;
const auto kv_head = mctx_cur->get_head();
const int64_t n_pend = cparams.n_rs_seq + 1;
const int64_t n_seqs = ubatch.n_seqs;
const int64_t n_seq_tokens = ubatch.n_seq_tokens;
const int64_t S_k = k->ne[0];
const int64_t H_k = k->ne[1];
const int64_t S_v = v->ne[0];
const int64_t H_v = v->ne[1];
const int64_t g0 = g->ne[0];
const size_t row_size = ggml_row_size(ssm_states_all->type, hparams.n_embd_s());
// the pending inputs of the cells: k [S_k, H_k, n_pend], v [S_v, H_v, n_pend], gb [g0, H_v, 2*n_pend] (the gates,
// then the betas). The views of the ubatch cells keep the strides of these 4D views, so that -sm tensor can split
// them by heads
ggml_tensor * spk = mctx_cur->get_spk_l(il);
ggml_tensor * spv = mctx_cur->get_spv_l(il);
ggml_tensor * spgb = mctx_cur->get_spgb_l(il);
ggml_tensor * ck = ggml_reshape_4d(ctx0, spk, S_k, H_k, n_pend, spk->ne[1]);
ggml_tensor * cv = ggml_reshape_4d(ctx0, spv, S_v, H_v, n_pend, spv->ne[1]);
ggml_tensor * cgb = ggml_reshape_4d(ctx0, spgb, g0, H_v, 2*n_pend, spgb->ne[1]);
const auto gather = [&](ggml_tensor * rows, ggml_tensor * c) {
return ggml_reshape_4d(ctx0, build_rs(inp, rows, rows->ne[0], n_seqs), c->ne[0], c->ne[1], c->ne[2], n_seqs);
};
ggml_tensor * pk = gather(spk, ck);
ggml_tensor * pv = gather(spv, cv);
ggml_tensor * pgb = gather(spgb, cgb);
const bool keep = rs_replay_keep(cparams, n_seq_tokens);
ggml_tensor * state_dst = ggml_view_2d(ctx0, ssm_states_all, hparams.n_embd_s(), n_seqs, ssm_states_all->nb[1], kv_head*row_size);
// store the inputs of the new tokens as pending; only used when keep, a longer ubatch stores its first n_pend tokens
const auto store_inputs = [&]() {
const int64_t n_st = std::min(n_seq_tokens, n_pend);
const auto store = [&](ggml_tensor * x, ggml_tensor * c, int64_t t0) {
ggml_tensor * x_st = ggml_view_4d(ctx0, x, x->ne[0], x->ne[1], n_st, n_seqs, x->nb[1], x->nb[2], x->nb[3], 0);
ggml_tensor * dst = ggml_view_4d(ctx0, c, x->ne[0], x->ne[1], n_st, n_seqs, c->nb[1], c->nb[2], c->nb[3],
kv_head*c->nb[3] + t0*c->nb[2]);
ggml_build_forward_expand(gf, ggml_cpy(ctx0, x_st, dst));
};
store(k, ck, 0);
store(v, cv, 0);
store(g, cgb, 0);
store(b, cgb, n_pend);
};
// the gdn op replays the kept pending tokens, then runs the new tokens
ggml_tensor * result = ggml_gated_delta_net_ext(ctx0, q, k, v, g, b, s, pk, pv, pgb, inp->rep_n, keep);
ggml_tensor * output = ggml_view_4d(ctx0, result, S_v, H_v, n_seq_tokens, n_seqs,
ggml_row_size(result->type, S_v),
ggml_row_size(result->type, S_v*H_v),
ggml_row_size(result->type, S_v*H_v*n_seq_tokens), 0);
cb(output, "attn_output", il);
// keep: the state after the replay, else the final state
ggml_tensor * new_state = ggml_view_2d(ctx0, result, hparams.n_embd_s(), n_seqs,
ggml_row_size(result->type, hparams.n_embd_s()),
ggml_row_size(result->type, S_v*H_v*n_seq_tokens*n_seqs));
ggml_build_forward_expand(gf, ggml_cpy(ctx0, new_state, state_dst));
store_inputs();
return output;
}
ggml_tensor * llm_build_delta_net_base::build_recurrent_attn(
llm_graph_input_rs * inp,
ggml_tensor * ssm_states_all,
@@ -86,67 +249,26 @@ ggml_tensor * llm_build_delta_net_base::build_recurrent_attn(
ggml_tensor * b,
ggml_tensor * s,
int il) {
const auto * mctx_cur = inp->mctx;
const auto kv_head = mctx_cur->get_head();
const uint32_t mem_size = mctx_cur->get_size();
const int64_t S_v = s->ne[0];
const int64_t H_v = s->ne[2];
const int64_t n_seqs = s->ne[3];
const int64_t n_seq_tokens = q->ne[2];
const bool keep = cparams.n_rs_seq > 0;
if (!keep) {
auto attn_out = build_delta_net(q, k, v, g, b, s);
ggml_tensor * output = attn_out.first;
ggml_tensor * new_state = attn_out.second;
cb(output, "attn_output", il);
cb(new_state, "new_state", il);
ggml_build_forward_expand(gf,
ggml_cpy(ctx0, new_state,
ggml_view_2d(ctx0, ssm_states_all, hparams.n_embd_s(), n_seqs, ssm_states_all->nb[1],
kv_head * hparams.n_embd_s() * ggml_element_size(ssm_states_all))));
return output;
if (cparams.rs_replay) {
return build_recurrent_attn_replay(inp, ssm_states_all, q, k, v, g, b, s, il);
}
const int64_t D = S_v * S_v * H_v;
const int64_t K = cparams.n_rs_seq + 1;
// a rollback replays the kept tokens, the gdn op does not write state snapshots
GGML_ASSERT(cparams.n_rs_seq == 0);
// state s is 4D [S_v, S_v, H_v, n_seqs]; K snapshot slots are written into the output.
ggml_tensor * gdn_out = ggml_gated_delta_net(ctx0, q, k, v, g, b, s, K);
const int64_t attn_score_elems = S_v * H_v * n_seq_tokens * n_seqs;
const int64_t state_size_per_snap = S_v * S_v * H_v * n_seqs;
const auto kv_head = inp->mctx->get_head();
const int64_t n_seqs = s->ne[3];
ggml_tensor * output = ggml_view_4d(ctx0, gdn_out,
S_v, H_v, n_seq_tokens, n_seqs,
ggml_row_size(gdn_out->type, S_v),
ggml_row_size(gdn_out->type, S_v * H_v),
ggml_row_size(gdn_out->type, S_v * H_v * n_seq_tokens),
0);
auto attn_out = build_delta_net(q, k, v, g, b, s);
ggml_tensor * output = attn_out.first;
ggml_tensor * new_state = attn_out.second;
cb(output, "attn_output", il);
cb(new_state, "new_state", il);
const size_t row_size = hparams.n_embd_s() * ggml_element_size(ssm_states_all);
// op writes the last min(n_seq_tokens, K) snapshots; trailing slots are left unwritten
const int64_t n_written = std::min<int64_t>(n_seq_tokens, K);
// write the produced snapshots into the recurrent cache (snapshot slot i -> rollback group i)
ggml_tensor * src = ggml_view_3d(ctx0, gdn_out,
D, n_seqs, n_written,
ggml_row_size(gdn_out->type, D),
ggml_row_size(gdn_out->type, state_size_per_snap),
ggml_row_size(gdn_out->type, attn_score_elems));
ggml_tensor * dst = ggml_view_3d(ctx0, ssm_states_all,
D, n_seqs, n_written,
ssm_states_all->nb[1],
(size_t) mem_size * row_size,
(size_t) kv_head * row_size);
ggml_build_forward_expand(gf, ggml_cpy(ctx0, src, dst));
ggml_build_forward_expand(gf,
ggml_cpy(ctx0, new_state,
ggml_view_2d(ctx0, ssm_states_all, hparams.n_embd_s(), n_seqs, ssm_states_all->nb[1],
kv_head * hparams.n_embd_s() * ggml_element_size(ssm_states_all))));
return output;
}

Some files were not shown because too many files have changed in this diff Show More