Compare commits

...
24 Commits
Author SHA1 Message Date
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
51fc2f90e2 ggml-openvino: CI fixes, new model support, fixes and improvements. (#32861)
* ggml-openvino: keep the rope angle in f32 under the f16 inference hint

* ggml-openvino: add a GGML_OP_ARGMAX translator

* ggml-openvino: keep the token dim dynamic for a 2-D activation graph input

* ggml-openvino: tolerate graph inputs and outputs with no backing storage

* ggml-openvino: invalidate a cached graph when its output set changes

* ggml-openvino: bound the compiled-model cache to N shapes instead of 1

* ggml-openvino: add GGML_OPENVINO_LOG_SUPPORTS_OP diagnostic

* ggml-openvino: honour a node's dynamic-dim classification on non-split graphs too

* ggml-openvino: fold consecutive SET_ROWS column writes into one scatter

* ggml-openvino: keep the speculative decoding feature buffers in device memory

* ggml-openvino: keep the fixed token count of static graph inputs for npu
GDN

In a static (NPU) graph that overwrites the fixed token count that
get_graph_input_shape set just before, for example of inp_tokens, so the NPU
graph got a dynamic token dimension. GATED_DELTA_NET models (Qwen3.5, Qwen3.6)
then fail to translate: "GATED_DELTA_NET pad masking requires a static token
dimension". Keep the change for dynamic graphs and the previous behaviour for
static ones.

* ggml-openvino: one output in the decode model of a static NPU pair

The decode model of a static prefill/decode pair copied the compute params of the
prefill graph, including output_len. With llama-perplexity the prefill graph has many
outputs (128 at -c 256), so the decode model gathered 128 rows from its one token in
the last layer. For a MoE model that layer then differs from the others and NPUW fails
to lower its experts ("could not lower the isolated expert partition"). A decode step
outputs one token; the model cache key already assumes it (decode_signature out=1).

* ggml-openvino: fix gated delta net when v is a view with padded heads

The GDN translator assumed v is a view of the fused qkv conv output with
the heads packed in each row, and sliced H_v * S_v elements off that row.
test-backend-ops now has padded_v cases, where v views a wider tensor and
each head row is padded (nb[1] > S_v * nb[0]). The slice then read the
padding, and the results were wrong on CPU and GPU.

Take the packed path only when nb[1] == S_v * nb[0]. Any other view goes
through the generic view resolution, which already returns
[B, T, H_v, S_v], so the reshape of the packed case is skipped too. Model
graphs build v with packed heads and keep the packed path.

* ggml-openvino: make the f32 rope angle opt-in

GGML_OPENVINO_ROPE_F32_ANGLE was on by default. It changes the RoPE of
every model on every device, and it was validated on one model on the
GPU only. On the CPU device, which computes in f32, its f16 round trip
rounds cos and sin, and ROPE cases of test-backend-ops fail against the
CPU backend.

Turn it off by default; GGML_OPENVINO_ROPE_F32_ANGLE=1 turns it on. Fix
the comment that called the round trip a no-op on f32 paths. Document
the variable, and the two diagnostics added with it
(GGML_OPENVINO_LOG_SUPPORTS_OP, GGML_OPENVINO_DIAG_GRAPH_IO), in the
dev_doc.

* docs : add the Muse-Glimmer-30B DFlash memory limit and env var samples

Muse-Glimmer-30B with a DFlash draft peaks at about 45 GB of RAM on an
integrated GPU. Add it to the GPU limitations as a runnable sample, and
add samples for GGML_OPENVINO_LOG_SUPPORTS_OP and
GGML_OPENVINO_DIAG_GRAPH_IO to the dev_doc.

* ggml-openvino: fix weight zero points, buffer extras and cache-key gaps

A code review of ggml/src/ggml-openvino found these bugs:

- Q4_1 weights: `extract_q4_1_data` packs two zero points per byte from a `parallel_for` over blocks, so two threads can write the same byte.
- Zero points out of the u4/u8 range wrap around instead of saturating. gemma-4-E2B has 6 Q4_K sub-blocks with a zero point of 16 or more; 16 wrapped to 0.
- `set_tensor` overwrote the extra that `init_tensor` created for a weight without deleting it.
- The two buffer constructors had separate id counters, and the buffer id is part of the shared graph key.
- A freed weight buffer stayed in the release registry, so a later release could madvise memory it no longer owned.
- `GGML_OPENVINO_ROPE_F32_ANGLE` changes the graph but was not in the compiled-model cache key.
- On NPU, group-128 requantization ignored the row width. A model whose rows are not a multiple of 128 failed to load its weights (SmolLM2-360M).
- The static Split cache held a strong reference to the Split on its own input (a reference cycle) and ignored the output port.
- `rms_norm` took op_case 3 for both a direct and a packed pre-scaled GDN output, so the packed one was not sliced.
- Smaller items: static decode read `out_ids` even when it is empty; the static path aborted where the dynamic path returns an error; a damaged weights `.meta` hash threw from `std::stoull`; `extract_layer_from_name` threw on a non-numeric suffix; `GGML_OP_FILL` was registered twice.

- ggml-quants.cpp: one `parallel_for` iteration per zero point byte for Q4_1; clamp zero points to [0, 15] (u4) and [0, 255] (u8).
- ggml-openvino.cpp: `ggml_openvino_set_extra` replaces and deletes the old extra at every site; one id counter; `ggml_openvino_unregister_weight_buffer` in the buffer destructor; a failed KV re-allocation returns `GGML_STATUS_ALLOC_FAILED`.
- model-cache.cpp: hash `GGML_OPENVINO_ROPE_F32_ANGLE`, cache version 9; `strtoull` for the `.meta` hash.
- npu_quant_policy.cpp: Q4_0_128 falls back to Q4_0_C when `ne[0] % 128 != 0`. ggml-openvino-extra.cpp: the group-64 requant targets fall back to Q8_0_C when `ne[0] % 64 != 0`.
- openvino/utils.cpp: the static Split cache uses a weak reference and the output port in its key, like the dynamic one.
- rms_norm.cpp, ggml-decoder.cpp: op_case 5 for a packed pre-scaled GDN output.
- utils.cpp: static decode writes 0 to `out_ids`; a compile after a weight release returns `GGML_STATUS_FAILED`.
- ggml-decoder.cpp: `extract_layer_from_name` returns nullopt for a non-numeric suffix.
- op_table.cpp/.h: remove the duplicate `GGML_OP_FILL`.

* ggml-openvino: copy the decoder once per graph conversion

`GgmlOvDecoder::visit_subgraph` made a full copy of the decoder for every node it visited. Translators only read the decoder, so one copy per walk is enough. Graph conversion time drops 12-24x (Qwen3.5-0.8B: 4.1 s to 0.17 s over the six graphs of a short run).

- ggml-decoder.cpp: make one decoder copy before the node loop.
- utils.cpp: `get_static_attention_size` takes the decoder by const reference and does not copy the compute params.

* ggml-openvino: remove dead code and fix stale comments

Code that nothing calls or registers, and comments that no longer match the code. No behavior change.

- Remove `translate_gated_delta_net_ref`, `translate_solve_tri` (not registered), the unused `FuseToSDPA` pass, `add_rope_sin_cos`, `checksum`, `save_ggml_tensor_data_to_txt`, `non_cont_dim`, the unused templates in openvino/utils.h and the undefined `getCurrentTime` declaration.
- ggml-decoder.cpp: drop the VIEW op_case tail that only ever set 0.
- utils.cpp: drop a duplicate `entry->ptr` store and the always-false `!model_leafs.empty() == false` term.
- `ggml_openvino_manual_gqa_enabled()` replaces two copies of the GGML_OPENVINO_MANUAL_GQA_ATTN default (flash_attn_ext.cpp and the cache key).
- ggml-openvino.cpp: remove the SSM_CONV case whose comment said it stays on CPU (it runs on OpenVINO); fix the gemma3n reason text (not GPU-only) and two typos.

* ggml-openvino: track dynamic dims through bailingmoe3's GDN views and conv state

bailingmoe3 uses GATED_DELTA_NET views to expose its attention and
state outputs. Preserve their dynamic dimensions in the decoder.

- Assign the dynamic dimensions of the translated attention and state
  outputs to the corresponding GATED_DELTA_NET result VIEWs.
- Count the convolution state slots using the rows spanned by the
  destination view. bailingmoe3 packs the q/k/v convolution states
  into a single row.
- Preserve the tracked dynamic dimension in RESHAPE op case 0 when
  the reshape only adds a trailing size-1 dimension.

* ggml-openvino: translate the per-key gate of GATED_DELTA_NET

Ling-3.0-tiny (bailingmoe3) uses a gate per key dimension (kda),
which the backend previously rejected, causing these layers to
fall back to the CPU.

- Use the fused GatedDeltaNet when the OpenVINO runtime and target
  device support a rank-4 gate.
- Detect support once by compiling a one-node GatedDeltaNet with
  a rank-4 gate and checking the target device with query_model.
  Older runtimes reject this gate, and the CPU plugin does not
  support it.
- Fall back to the reference loop when the fused path is unavailable.
- Support a dynamic token count in the reference loop by using
  dynamic reshapes and deriving the trip count from the input shape.
- Reject unsupported cases with a reason: padded chunks, recurrent
  caches, state snapshots, and the native state layout. The loop
  currently handles one state in the ggml layout.

* ggml-openvino: Fix issue highlighted by tests

* ggml-openvino: reject a padded permuted v in gated delta net

supports_op rejected a permuted v only when src2 was the PERMUTE itself. With padded heads, v is a VIEW of the PERMUTE, so the check missed it and the per-key gate reference loop ran on a v layout it does not handle. Look through the VIEW so this case falls back like the other permuted v inputs.

* ggml-openvino: write back intermediate nodes of op-test graphs

The ADD_RMS_NORM_MUL op test checks the intermediate sum of its graph as
well as the final output. compute_model_outputs() made a node a model
output only when the graph does not consume all of it, so the sum was
never written back and the test read uninitialised memory (28 failures
on GPU and CPU). MUL_MAT_ID_SHARED, which checks its routed and shared
results, failed the same way on CPU.

Op-test graphs (the naive path) can read any node, so make every
non-in-place node a model output there. Model graphs are unchanged.

---------

Co-authored-by: Mustafa Cavus <mustafa.cavus@intel.com>
Co-authored-by: yzhou51 <yaowei.zhou@intel.com>
Co-authored-by: Sabnis, Omkar <omkar.sabnis@intel.com>
2026-11-23 06:29:20 -08:00
Aman Gupta 03813c56e4 rpc : typed request helpers and a single validation step on the server (#32651)
* rpc : typed request helpers and a single validation step on the server

Client and server share one table (rpc_msg_types) that maps each
fixed-size command to its request and response structs. The client sends
them with dispatcher->call<CMD>() and call_async<CMD>(), the server serves
them with rpc_serve<CMD>(), so the per-command code in rpc_serve_client
and at the call sites is gone and a wrong struct for a command does not
compile. SET_TENSOR, SET_TENSOR_2D and GRAPH_COMPUTE get header structs,
written with rpc_writer and parsed with a bounds-checked rpc_reader. The
wire format is unchanged.

Validation of client data is now in one place:
- deserialize_tensor rejects what ggml_new_tensor would assert on (op
  range, ne[0] not a multiple of the block size, element count overflow)
  and computes the tensor size without overflow before the buffer check
- rpc_check_region replaces the per-handler bounds checks and checks the
  request against the tensor size, which ggml_backend_tensor_set/get/memset
  assert on, so an in-buffer but out-of-tensor request no longer aborts
- graph_compute builds the graph in one pass over the tensors, which the
  client sends in topological order: no recursion, and unknown or
  duplicate ids, duplicate nodes, sources sent after their users, compute
  nodes with unallocated operands and views outside their view_src buffer
  are rejected; a tensor may be its own source (ggml_cast)
- GET_ALLOC_SIZE fails if a source tensor is invalid
- a client-sized allocation that fails closes the connection instead of
  terminating the server

* rpc : trim comments
2026-11-23 22:28:40 +08:00
thelittlefireman 46f4da2174 ggml-cuda : handle zero blocks in few-row MMQ quantization (#32566)
Assisted-by: ChatGPT (GPT-6)
2026-11-23 15:17:15 +01:00
Aleksander Grygier 4663f9ca8a ui: smooth height transition for every collapsible (#32873)
* ui: give every collapsible the smooth height transition

Llama UI's Collapsible.Content now force-mounts the bits-ui content and
renders the animated region the chat used to keep as CollapsibleRegion:
height eases open and shut, and the body unmounts once the collapse is
over. The chat's standalone regions use Collapsible.Root/Content, so the
tool groups in settings, the tools menu and drawer and the terminal block
animate like the rest.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: keep collapsible spacing inside the content

Collapsible.Content now stays in the layout while closed, so a margin on
it left a gap under a closed MCP tools list, connection log or server
info. The margin moves onto the content inside, as does the story's
spacing.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 14:12:41 +01:00
255 changed files with 13706 additions and 4107 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
+10
View File
@@ -995,6 +995,16 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.
**GPU-specific**
- Muse-Glimmer-30B with a DFlash draft needs a 64 GB system (peak about 45 GB of RAM):
```bash
export GGML_OPENVINO_DEVICE=GPU
export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill # local disk, not tmpfs
export GGML_OPENVINO_ROPE_F32_ANGLE=1 # long prompts
mkdir -p $GGML_OPENVINO_SPILL_DIR
./build/ReleaseOV/bin/llama-server -m Muse-Glimmer-30B-Q4_K_M.gguf -md <dflash-draft>.gguf \
--spec-type draft-dflash --spec-draft-n-max 4
```
- Multiple GPUs (`GGML_OPENVINO_DEVICE=GPU.0,GPU.1` with `-sm layer`):
- `-sm tensor` is not supported.
- Copies between GPUs go through host memory. There is no asynchronous copy and no peer-to-peer copy.
+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;
}
+2 -2
View File
@@ -607,13 +607,13 @@ static __device__ __forceinline__ void quantize_mmq_few_store(const float4 xi, i
float amax = fmaxf(fmaxf(fabsf(xi.x), fabsf(xi.y)), fmaxf(fabsf(xi.z), fabsf(xi.w)));
amax = warp_reduce_max<8>(amax);
const float d_inv = 127.0f / amax;
const float d_inv = amax == 0.0f ? 0.0f : 127.0f / amax;
char4 q;
q.x = roundf(xi.x*d_inv);
q.y = roundf(xi.y*d_inv);
q.z = roundf(xi.z*d_inv);
q.w = roundf(xi.w*d_inv);
const float d = 1.0f / d_inv;
const float d = amax == 0.0f ? 0.0f : 1.0f / d_inv;
// as in quantize_mmq_q8_1: the sum of the quantized values; the int warp_reduce_sum reduces the whole warp on Ampere+
[[maybe_unused]] float sum = 0.0f;
+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) {
+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>;
+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
+211 -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;
@@ -40576,7 +40723,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
@@ -97,6 +100,13 @@ kernel void kernel_gated_delta_net(
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);
@@ -144,6 +154,77 @@ 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;
@@ -236,6 +317,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
}
@@ -13,6 +13,8 @@ The variables for users, and the rules for values, are in [docs/backend/OPENVINO
| `GGML_OPENVINO_DEBUG_NODE` | all | String | `not set` | Add the named graph nodes as outputs of the compiled model. Separate several names with commas. |
| `GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS` | all | Boolean | `0` | Print the tensor address map once. |
| `GGML_OPENVINO_LOG_UNSUPPORTED_OPS` | all | Boolean | `0` | Log each op that the backend does not support, with the tensor details and the reason. |
| `GGML_OPENVINO_LOG_SUPPORTS_OP` | all | Integer | `0` | Log what `supports_op` accepts and rejects. `1`: summary at exit. `2`: also each call (the first calls are missing). |
| `GGML_OPENVINO_DIAG_GRAPH_IO` | all | Boolean | `0` | When binding a tensor or `infer()` throws, log the graph key and the shapes of the model and the bound tensors. |
| `GGML_OPENVINO_DISABLE_CACHE` | all | Boolean | `0` | Turn the in-process cache of compiled models and decoders off. |
| `GGML_OPENVINO_FULL_GRAPH_KEY` | all | Boolean | `0` | Add the external inputs of a graph to the key of the in-process cache. By default the key is the node count and the names of the first and last nodes. Use it when two different graphs could share that key. |
| `GGML_OPENVINO_LOG_SWA_LAYERS` | all | Boolean | `0` | Log the attention extent of each layer and which layers use sliding-window attention, on an `ov-swa:` line at the WARN level. |
@@ -29,6 +31,12 @@ GGML_OPENVINO_DUMP_CGRAPH=1 GGML_OPENVINO_DUMP_IR=1 \
# Log unsupported ops. The lines have the WARN level, which the default log verbosity shows (-lv 2 or higher).
GGML_OPENVINO_LOG_UNSUPPORTED_OPS=1 ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
# What supports_op accepts and rejects: 1 = summary at exit, 2 = also each call
GGML_OPENVINO_LOG_SUPPORTS_OP=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep ov-supports-op
# Graph key and tensor shapes when an inference throws
GGML_OPENVINO_DIAG_GRAPH_IO=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep DIAG
# NPUW dumps. They need an OpenVINO developer build (NPU_PLUGIN_DEVELOPER_BUILD).
export GGML_OPENVINO_DEVICE=NPU
export GGML_OPENVINO_NPUW_DUMP_SUBS=YES
@@ -74,6 +82,7 @@ These options are off by default. They are not validated for general use: some h
| `GGML_OPENVINO_GDN_NATIVE_STATE` | NPU | Boolean | `0` | Keep the `GATED_DELTA_NET` state in the layout of the OpenVINO op instead of the GGML layout. Every `GATED_DELTA_NET` must then run on the OpenVINO backend; the load aborts if one would run on the CPU backend. Saved states and `GGML_OPENVINO_DEBUG_NODE` dumps hold the OpenVINO layout. `test-backend-ops` fails with it. |
| `GGML_OPENVINO_FORCE_STATIC` | CPU, GPU | Boolean | `0` | Run the static-shape path of the NPU on the CPU or the GPU, to separate translation bugs from NPU plugin or driver problems. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. |
| `GGML_OPENVINO_ENABLE_FALLBACK` | all | Boolean | `0` | Detect graphs that the scheduler splits between OpenVINO and another backend, and translate them as partial graphs, without the compiled model cache. By default every graph is treated as a complete model graph. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. |
| `GGML_OPENVINO_ROPE_F32_ANGLE` | GPU | Boolean | `0` | Keep the RoPE angle in f32 under the f16 hint, for long prompts. Validated on one model. On CPU, `test-backend-ops -o ROPE` fails with it. |
| `GGML_OPENVINO_NATIVE_SOFTPLUS` | all | Boolean | `0` | Translate `SOFTPLUS` to the OpenVINO `SoftPlus` op instead of the default `relu(x) + log(1 + exp(-abs(x)))`. |
| `GGML_OPENVINO_KV_SCATTER_ELEMENTS` | all | Boolean | `0` | Use `ScatterElementsUpdate` instead of `ScatterUpdate` for single-row KV writes in stateless execution. |
| `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | `0` | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]`, so the GPU plugin can update and read it in place. Needs an OpenVINO build newer than 2026.4.1; do not use it with 2026.4.1. |
@@ -45,6 +45,10 @@ std::optional<ExtraQuantType> ggml_openvino_npu_token_embd_requant_type(const gg
}
std::optional<ExtraQuantType> ggml_openvino_npu_weight_requant_type(const ggml_tensor * tensor) {
GGML_UNUSED(tensor);
return ggml_openvino_get_npu_requant_type();
const ExtraQuantType type = ggml_openvino_get_npu_requant_type();
// a group must fit within a row
if (type == ExtraQuantType::Q4_0_128 && tensor->ne[0] % 128 != 0) {
return ExtraQuantType::Q4_0_C;
}
return type;
}
+63 -52
View File
@@ -9,9 +9,11 @@
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <map>
@@ -31,10 +33,27 @@
#include <set>
#include <stdexcept>
#include <string>
#include <cstring>
#include <unordered_map>
#include <vector>
static std::set<std::string> collect_graph_output_names(const ggml_cgraph * cgraph) {
std::set<std::string> outputs;
for (int node_n = 0; node_n < cgraph->n_nodes; node_n++) {
auto * node = cgraph->nodes[node_n];
if (node->flags & GGML_TENSOR_FLAG_OUTPUT) {
outputs.insert(node->name);
}
}
return outputs;
}
bool GgmlOvDecoder::has_same_graph_io(const ggml_cgraph * cgraph) const {
if (m_built_output_names.empty()) {
return true; // no snapshot (naive / test decoders): nothing to compare against
}
return collect_graph_output_names(cgraph) == m_built_output_names;
}
GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph,
ModelParams & model_params,
ComputeParams & compute_params,
@@ -64,6 +83,8 @@ GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph,
validate_cgraph();
m_built_output_names = collect_graph_output_names(cgraph);
set_input_output();
compute_node_dynamic_dims();
compute_model_inputs();
@@ -79,6 +100,7 @@ GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph,
void GgmlOvDecoder::update_io(ggml_cgraph * cgraph) {
m_cgraph = cgraph;
m_built_output_names = collect_graph_output_names(cgraph);
m_model_inputs.clear();
m_model_outputs.clear();
m_node_info_list.clear();
@@ -694,45 +716,6 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
op_case = 1;
break;
}
if (node->src[0]->op == GGML_OP_VIEW) {
auto * src = node->src[0];
if (ggml_nelements(node) != ggml_nelements(src)) {
// throw std::runtime_error("Unsupported VIEW case");
}
op_case = 0;
if (m_model_is_splitted && m_model_inputs.find(get_tensor_ov_name(m_cgraph, src)) != m_model_inputs.end()) {
op_case = 0;
}
}
{
auto * src = node->src[0];
if (ggml_nelements(node) != ggml_nelements(src)) {
// Case 4: select one slice on src dim1 (via view offset), keep src dim2 as output dim1.
// Typical pattern:
// src: ne=[N, M, K, 1], nb=[b0, b1, b2, b3]
// dst: ne=[N, K, 1, 1], nb=[b0, b2, b3, b3]
if (node->ne[0] == src->ne[0] && node->ne[1] == src->ne[2] && node->ne[2] == 1 &&
node->nb[0] == src->nb[0] && node->nb[1] == src->nb[2] && src->ne[1] > 1) {
op_case = 0;
break;
}
// General case 3: shape differs from source (one or more dims) and is handled as VIEW slicing.
int diff_count = 0;
for (int i = 0; i < GGML_MAX_DIMS; i++) {
if (node->ne[i] != src->ne[i]) {
diff_count++;
}
// if node ne[i] > src ne[i], case = 0
if (node->ne[i] > src->ne[i]) {
return 0;
}
}
if (diff_count >= 1) {
op_case = 0;
}
}
}
break;
}
case GGML_OP_RMS_NORM: {
@@ -744,7 +727,8 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
// pre-scaled, and the norm then scales its eps to match; 4: it is not.
op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 3 : 4;
} else if (node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) {
op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 3 : 2;
// packed [attn | state] output, sliced by the norm. 5: pre-scaled, as in 3; 2: not.
op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 5 : 2;
}
}
break;
@@ -897,13 +881,10 @@ std::optional<int> extract_layer_from_name(const std::string & name) {
return std::nullopt;
}
pos1 += 2;
size_t pos2 = name.find(' ', pos1);
if (pos2 == std::string::npos) {
pos2 = name.length();
if (pos1 >= name.size() || !std::isdigit(static_cast<unsigned char>(name[pos1]))) {
return std::nullopt;
}
std::string layer_str = name.substr(pos1, pos2 - pos1);
int layer = std::stoi(layer_str);
return layer;
return std::stoi(name.substr(pos1));
}
// Recover the sliding window width from ggml's own SWA mask. llama.cpp never passes n_swa to a
@@ -1202,7 +1183,11 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
}
ggml_tensor * cache_k = cache_k_view->src[0];
int layer = extract_layer_from_name(cache_k->name).value();
const auto layer_opt = extract_layer_from_name(cache_k->name);
if (!layer_opt) {
continue;
}
const int layer = *layer_opt;
// Classified by the pre-pass above, which groups layers by mask tensor identity. The
// mask NAME cannot be used: build_attn_inp_kq_mask() gives both masks the same name.
@@ -1372,7 +1357,9 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback;
}
if (is_conv || is_gdn) {
compute_params.s_copy_active_slot_len = (int) dest_view->ne[1];
// One cache row per active sequence: [conv_state_size, n_seqs] (qwen35) or, with the q/k/v conv
// states packed in one row, [d_conv - 1, d_inner, n_seqs] (bailingmoe3), so count the rows spanned.
compute_params.s_copy_active_slot_len = (int) ((ggml_nbytes(dest_view) + row_bytes - 1) / row_bytes);
}
}
}
@@ -1573,7 +1560,10 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op,
else {
input_shape = ov::PartialShape{get_shape(input)};
}
if (dynamic_dim_index != -1 && m_model_is_splitted) {
// A static graph (NPU) keeps the fixed token count set above; only a split static graph, whose parts are
// fed by other backends, marks the dimension dynamic. Without this the token dimension of inp_tokens becomes
// dynamic in the NPU graph (and, for example, the GATED_DELTA_NET pad masking fails).
if (dynamic_dim_index != -1 && (!m_is_static || m_model_is_splitted)) {
input_shape[3 - dynamic_dim_index] = -1;
}
if (op->op == GGML_OP_SOFT_MAX && op->src[1] != nullptr && op->src[1]->op == GGML_OP_NONE &&
@@ -1985,7 +1975,9 @@ void GgmlOvDecoder::compute_model_outputs() {
}
}
}
if (input_use_count == cur_node_use_count) {
// op tests (the naive path) can read any node of the graph, e.g. the intermediate sum of a fused
// ADD + RMS_NORM + MUL, so every non-in-place node is a model output there
if (input_use_count == cur_node_use_count && (!m_naive || ::is_inplace_op(cur_node))) {
cur_node = nullptr;
}
}
@@ -2774,11 +2766,14 @@ size_t GgmlOvDecoder::get_output_op_offset(int node_idx) const {
}
void GgmlOvDecoder::visit_subgraph(std::function<void(std::shared_ptr<GgmlDecoder>, int node_idx)> node_visitor) const {
// One copy for the whole walk: translators only read the decoder, and a copy per node costs a full
// copy of the node list for every node.
auto decoder = std::make_shared<GgmlOvDecoder>(*this);
for (int node_idx = 0; node_idx < m_cgraph->n_nodes; node_idx++) {
if (m_cgraph->nodes[node_idx]->op == GGML_OP_NONE) {
continue;
}
node_visitor(std::make_shared<GgmlOvDecoder>(*this), node_idx);
node_visitor(decoder, node_idx);
}
}
@@ -2851,6 +2846,10 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
m_node_dynamic_dims[src] = 1;
continue;
}
if (is_inp_embd_2d(src, node)) {
m_node_dynamic_dims[src] = 1;
continue;
}
self(self, src);
}
}
@@ -2921,10 +2920,22 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
m_node_dynamic_dims[node] = node->view_offs == 0 ? 2 : -1;
break;
}
// A VIEW that does not change the shape is a pass-through for dynamic-dim purposes.
if (is_same_shape(node->src[0], node)) {
m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]];
break;
}
// Use stride-based matching: the stride of a VIEW dimension directly
// encodes which source dimension it indexes into, so it uniquely
// identifies the dynamic dim even when two dims share the same size.
m_node_dynamic_dims[node] = -1;
if (!m_model_params.has_rs_rollback && node->src[0]->op == GGML_OP_GATED_DELTA_NET) {
// The GDN translator publishes attention [S_v, H_v, n_tokens, n_seqs] and state directly under these
// VIEW names (get_output_names), not the packed [attention | state] the strides describe.
m_node_dynamic_dims[node] = node->view_offs == 0 ? 2 : -1;
break;
}
if (m_node_dynamic_dims[node->src[0]] != -1) {
auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
auto dynamic_dim_value = node->src[0]->ne[dynamic_dim_idx];
+17
View File
@@ -458,6 +458,11 @@ public:
void update_io(ggml_cgraph * cgraph);
bool is_bound_to(const ggml_cgraph * cgraph) const;
// Was this decoder built for a graph with the same OUTPUT set as `cgraph`? The cache key is
// only (n_nodes, first/last node name), which cannot see a change in which tensors are marked
// as outputs, and the compiled model's Results are fixed at compile time.
bool has_same_graph_io(const ggml_cgraph * cgraph) const;
static bool is_inp_tok(const ggml_tensor * tensor, const ggml_tensor * op) {
return op->op == GGML_OP_GET_ROWS && tensor == op->src[1] && op->src[0]->op == GGML_OP_NONE;
}
@@ -501,6 +506,16 @@ public:
(tensor->op == GGML_OP_NONE || tensor->op == GGML_OP_CPY);
}
// A 2-D float graph input feeding a matmul as src[1]. Speculative decoding hands the draft the
// target's hidden features this way ([n_embd, n_tokens], with no GET_ROWS lookup, so none of the
// other seeds match it) and the token count differs between the prompt pass and the shorter
// draft blocks, so its token dim must stay dynamic.
static bool is_inp_embd_2d(const ggml_tensor * tensor, const ggml_tensor * op) {
return (tensor->flags & GGML_TENSOR_FLAG_INPUT) && tensor->op == GGML_OP_NONE &&
tensor->type == GGML_TYPE_F32 && tensor->ne[2] == 1 && tensor->ne[3] == 1 &&
op->op == GGML_OP_MUL_MAT && tensor == op->src[1];
}
static bool is_inp_mask(const ggml_tensor * tensor, const ggml_tensor * op) {
return op->op == GGML_OP_CPY || (op->op == GGML_OP_FLASH_ATTN_EXT && tensor == op->src[3]) ||
(op->op == GGML_OP_SOFT_MAX && tensor == op->src[1]);
@@ -759,6 +774,8 @@ private:
std::map<std::string, std::shared_ptr<ov::Node>> m_model_weights;
std::map<std::string, ggml_tensor *> m_model_outputs;
std::set<std::string> m_model_output_names;
// The output set the compiled model was built from, for has_same_graph_io().
std::set<std::string> m_built_output_names;
std::vector<NodeInfo> m_node_info_list;
std::map<ggml_tensor *, int> m_node_dynamic_dims;
std::set<const ggml_tensor *> m_kvcache_4d;
+19 -5
View File
@@ -179,6 +179,9 @@ constexpr env_var env_vars[] = {
{"GGML_OPENVINO_RELEASE_WEIGHTS", env_type::BOOL},
{"GGML_OPENVINO_REDUCE_COMPILE_MEM", env_type::BOOL},
{"GGML_OPENVINO_LOG_UNSUPPORTED_OPS", env_type::BOOL},
{"GGML_OPENVINO_LOG_SUPPORTS_OP", env_type::INT},
{"GGML_OPENVINO_DIAG_GRAPH_IO", env_type::BOOL},
{"GGML_OPENVINO_ROPE_F32_ANGLE", env_type::BOOL},
{"GGML_OPENVINO_LOG_SWA_LAYERS", env_type::BOOL},
{"GGML_OPENVINO_NATIVE_SOFTPLUS", env_type::BOOL},
{"GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS", env_type::BOOL},
@@ -543,6 +546,14 @@ std::string ggml_openvino_config_overrides_in_use() {
return value ? std::string(name) + "=" + value : std::string();
}
bool ggml_openvino_manual_gqa_enabled() {
// set: a positive value enables it, 0 disables it; unset: on GPU only
if (ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN") != nullptr) {
return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0;
}
return ggml_openvino_is_gpu();
}
bool ggml_openvino_gdn_prescale_enabled() {
// float value, so not getenv_int: "64.0" must enable it. Unset means on.
const char * v = ggml_openvino_getenv_str("GGML_OPENVINO_GDN_Q_SCALE", nullptr);
@@ -997,6 +1008,10 @@ std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor *
const bool sym128_all = is_opt("q4_sym128_all");
const bool asym64_all = is_opt("q4_asym64_all");
const bool asym64 = is_opt("q4_asym64");
// A group of 64 must fit within each row; other widths keep channel-wise INT8.
auto group64 = [tensor](ExtraQuantType type) {
return tensor->ne[0] % 64 == 0 ? type : ExtraQuantType::Q8_0_C;
};
// TODO: temporary workaround for slow GPU-plugin GatherMatmul prefill above 16 tokens.
// Q4_1_64 experts let the plugin fuse the MoE into MOECompressed.
@@ -1021,8 +1036,7 @@ std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor *
return tensor->ne[0] % 64 == 0 ? ExtraQuantType::Q4_1_64 : ExtraQuantType::Q8_0_C;
}
if (tensor->type == GGML_TYPE_Q5_0) {
//return ExtraQuantType::Q4_0_128;
return ExtraQuantType::Q4_0_64;
return group64(ExtraQuantType::Q4_0_64);
}
// MoE expert weights (3D, ne[2] = n_expert) stored as Q5_1/Q8_0 are the expert-side
// equivalent of Q6_K/Q5_K: kept at 8 bits by default while the rest of the model is at 4
@@ -1031,10 +1045,10 @@ std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor *
// (704/64 = 11) and 128 does not.
if (tensor->ne[2] > 1 && (tensor->type == GGML_TYPE_Q5_1 || tensor->type == GGML_TYPE_Q8_0)) {
if (sym128 || sym128_all) {
return ExtraQuantType::Q4_0_64;
return group64(ExtraQuantType::Q4_0_64);
}
if (asym64 || asym64_all) {
return ExtraQuantType::Q4_1_64;
return group64(ExtraQuantType::Q4_1_64);
}
// TODO: temporary workaround for a known OpenVINO GPU-plugin bug -- remove once the
// plugin computes grouped 8-bit GatherMatmulCompressed correctly. This costs accuracy
@@ -1049,7 +1063,7 @@ std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor *
// avoids the broken layout and restores correct output.
// Opt out with GGML_OPENVINO_REQUANT_KQUANT=native.
if (ggml_openvino_is_gpu() && !is_opt("native")) {
return ExtraQuantType::Q4_0_64;
return group64(ExtraQuantType::Q4_0_64);
}
}
switch (tensor->type) {
@@ -206,6 +206,9 @@ bool ggml_openvino_is_gpu();
// Read n_seq_active and attention_size(_swa) from the KQ mask shape (off with GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK=1)
bool ggml_openvino_shape_from_mask_enabled();
// Manual GQA attention instead of SDPA (GGML_OPENVINO_MANUAL_GQA_ATTN, on GPU by default)
bool ggml_openvino_manual_gqa_enabled();
// GDN q pre-scale for eligible graphs on the NPU static path. On by default;
// GGML_OPENVINO_GDN_Q_SCALE=0 (or a negative or non-numeric value) turns it off.
bool ggml_openvino_gdn_prescale_enabled();
@@ -242,6 +245,7 @@ size_t ggml_openvino_max_alloc_size(const std::string & device);
// release: madvise(MADV_DONTNEED) all registered buffers, dropping their RSS.
// released: true once release has run (used to fail-fast on post-release recompile).
void ggml_openvino_register_weight_buffer(void * data, size_t size);
void ggml_openvino_unregister_weight_buffer(const void * data);
void ggml_openvino_release_weight_buffers();
bool ggml_openvino_weight_buffers_released();
+198 -75
View File
@@ -18,6 +18,7 @@
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <memory>
#include <mutex>
#include <openvino/core/type/element_type.hpp>
@@ -99,14 +100,20 @@ struct ggml_backend_openvino_buffer_context {
// Used for re-allocation on device for kvcache
void * data_prev = nullptr;
// data is in the weight buffer registry
bool weight_registered = false;
// One counter for both constructors: the id is part of the weight identity in the graph key, so a host-pointer
// buffer and an allocated buffer must never share one.
static size_t next_buffer_id() {
static std::atomic<size_t> next_id{1};
return next_id.fetch_add(1);
}
ggml_backend_openvino_buffer_context(int device, void * external_data, size_t size) :
device(device),
name(std::string(GGML_OPENVINO_NAME) + std::to_string(device)),
id([]() {
static std::atomic<size_t> next_id{1};
return next_id.fetch_add(1);
}()),
id(next_buffer_id()),
data(external_data),
size(size),
is_remote(false),
@@ -117,10 +124,7 @@ struct ggml_backend_openvino_buffer_context {
ggml_backend_openvino_buffer_context(int device, size_t size, bool is_remote = false, bool lazy = false) :
device(device),
name(std::string(GGML_OPENVINO_NAME) + std::to_string(device)),
id([]() {
static std::atomic<size_t> next_id{1};
return next_id.fetch_add(1);
}()),
id(next_buffer_id()),
data(nullptr),
size(size),
is_remote(is_remote) {
@@ -260,6 +264,10 @@ struct ggml_backend_openvino_buffer_context {
delete pair.second;
}
tensor_extras.clear();
// a later release must not madvise memory this buffer no longer owns
if (weight_registered) {
ggml_openvino_unregister_weight_buffer(data);
}
if (kv_on_demand) {
ggml_openvino_kv_storage_unregister(data, size);
}
@@ -321,6 +329,17 @@ void ggml_openvino_register_weight_buffer(void * data, size_t size) {
reg.buffers.emplace_back(data, size);
}
void ggml_openvino_unregister_weight_buffer(const void * data) {
if (data == nullptr) {
return;
}
auto & reg = ov_weight_registry();
std::lock_guard<std::mutex> lock(reg.mutex);
reg.buffers.erase(std::remove_if(reg.buffers.begin(), reg.buffers.end(),
[data](const std::pair<void *, size_t> & b) { return b.first == data; }),
reg.buffers.end());
}
bool ggml_openvino_weight_buffers_released() {
auto & reg = ov_weight_registry();
std::lock_guard<std::mutex> lock(reg.mutex);
@@ -378,21 +397,53 @@ static bool is_self_contained_mmap_enabled() {
ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR");
}
// Stores extra as the tensor's extra, deleting the one it replaces
static void ggml_openvino_set_extra(ggml_backend_openvino_buffer_context * ctx,
ggml_tensor * tensor,
ggml_openvino_extra_base * extra) {
auto it = ctx->tensor_extras.find(tensor);
if (it != ctx->tensor_extras.end() && it->second != extra) {
delete it->second;
}
ctx->tensor_extras[tensor] = extra;
tensor->extra = extra;
}
// Replaces the buffer's context with a new allocation of the same size and moves tensor->data to it. The old
// allocation is freed first, so the two never take memory at the same time. Returns false when the new
// allocation fails.
static bool ggml_openvino_swap_buffer_context(ggml_backend_buffer_t buffer,
ggml_backend_openvino_buffer_context *& ctx,
ggml_tensor * tensor,
bool is_remote,
bool lazy) {
const int device = ctx->device;
const size_t size = ctx->size;
const size_t offset = (char *) tensor->data - (char *) ctx->data;
delete ctx;
ctx = new ggml_backend_openvino_buffer_context(device, size, is_remote, lazy);
buffer->context = ctx;
if (ctx->data == nullptr) {
return false;
}
tensor->data = (char *) ctx->data + offset;
return true;
}
static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
// GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
// Put kvcache on device memory for GPU (NPU memory is too small even for kvcache)
if (strncmp(tensor->name, "cache_", 6) == 0 && !ctx->is_remote && ggml_openvino_is_gpu() &&
!is_stateful_enabled()) {
// Put kvcache on device memory for GPU (NPU memory is too small even for kvcache). Same for the speculative
// decoding feature buffers (llama_context::layer_inp_dev / h_nextn_dev): every graph reads or writes the whole
// buffer, so in host memory the plugin copies it to the device and back on every inference.
const bool is_device_state = strncmp(tensor->name, "cache_", 6) == 0 ||
strcmp(tensor->name, "layer_inp_dev") == 0 || strcmp(tensor->name, "h_nextn_dev") == 0;
if (is_device_state && !ctx->is_remote && ggml_openvino_is_gpu() && !is_stateful_enabled()) {
GGML_ASSERT(ctx->tensor_extras.empty());
auto device = ctx->device;
auto size = ctx->size;
auto * data_prev = ctx->data;
delete ctx;
ctx = new ggml_backend_openvino_buffer_context(device, size, true);
buffer->context = ctx;
tensor->data = (char *) ctx->data + ((char *) tensor->data - (char *) data_prev);
if (!ggml_openvino_swap_buffer_context(buffer, ctx, tensor, true, false)) {
return GGML_STATUS_ALLOC_FAILED;
}
}
// On-demand NPU KV: swap the eagerly committed buffer for demand-zero memory at its first KV tensor
@@ -401,14 +452,10 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu
if (is_kv_tensor && tensor->view_src == nullptr && !ctx->is_remote && ggml_openvino_npu_kv_on_demand_enabled() &&
tensor->ne[2] == 1 && tensor->ne[3] == 1 && tensor->nb[1] == ggml_row_size(tensor->type, tensor->ne[0])) {
if (!ctx->kv_on_demand && ctx->tensor_extras.empty() && tensor->data == ctx->data) {
auto device = ctx->device;
auto size = ctx->size;
auto * data_prev = ctx->data;
delete ctx;
ctx = new ggml_backend_openvino_buffer_context(device, size, false, true);
if (!ggml_openvino_swap_buffer_context(buffer, ctx, tensor, false, true)) {
return GGML_STATUS_ALLOC_FAILED;
}
ctx->kv_on_demand = true;
buffer->context = ctx;
tensor->data = (char *) ctx->data + ((char *) tensor->data - (char *) data_prev);
}
if (ctx->kv_on_demand) {
ggml_openvino_kv_storage_register(tensor->data, tensor->nb[1], tensor->ne[1]);
@@ -431,12 +478,7 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu
if (ggml_openvino_tensor_extra * extra =
ggml_openvino_create_tensor_extra(tensor, ctx->is_remote,
ggml_openvino_get_available_devices()[ctx->device])) {
auto it = ctx->tensor_extras.find(tensor);
if (it != ctx->tensor_extras.end()) {
delete it->second;
}
ctx->tensor_extras[tensor] = extra;
tensor->extra = extra;
ggml_openvino_set_extra(ctx, tensor, extra);
return GGML_STATUS_SUCCESS;
}
}
@@ -451,12 +493,7 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu
ggml_openvino_tensor_extra * extra = ggml_openvino_create_tensor_extra(
tensor, ctx->is_remote, ggml_openvino_get_available_devices()[ctx->device]);
if (extra != nullptr) {
auto it = ctx->tensor_extras.find(tensor);
if (it != ctx->tensor_extras.end()) {
delete it->second;
}
ctx->tensor_extras[tensor] = extra;
tensor->extra = extra;
ggml_openvino_set_extra(ctx, tensor, extra);
}
}
@@ -644,8 +681,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
// }
}
ctx->tensor_extras[tensor] = extra;
tensor->extra = extra;
ggml_openvino_set_extra(ctx, tensor, extra);
// Register the host buffer so its pages can be dropped after the GPU
// plugin has its own device copy (GGML_OPENVINO_RELEASE_WEIGHTS).
@@ -661,6 +697,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
"multi-model runs.");
}
ggml_openvino_register_weight_buffer(ctx->data, ctx->size);
ctx->weight_registered = true;
}
if (!ctx->external_memory) {
@@ -700,12 +737,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
return;
}
auto it = ctx->tensor_extras.find(tensor);
if (it != ctx->tensor_extras.end()) {
delete it->second;
}
ctx->tensor_extras[tensor] = extra;
tensor->extra = extra;
ggml_openvino_set_extra(ctx, tensor, extra);
}
}
@@ -1087,15 +1119,8 @@ void ggml_openvino_buffer_register_extra(ggml_tensor * tensor, ggml_openvino_ext
GGML_ASSERT(tensor->buffer != nullptr);
GGML_ASSERT(ggml_backend_buffer_is_openvino(tensor->buffer));
auto * ctx = static_cast<ggml_backend_openvino_buffer_context *>(tensor->buffer->context);
auto it = ctx->tensor_extras.find(tensor);
if (it != ctx->tensor_extras.end()) {
delete it->second;
}
ctx->tensor_extras[tensor] = extra;
tensor->extra = extra;
ggml_openvino_set_extra(static_cast<ggml_backend_openvino_buffer_context *>(tensor->buffer->context), tensor,
extra);
}
bool ggml_backend_buft_is_openvino(ggml_backend_buffer_type_t buft) {
@@ -1837,7 +1862,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
case GGML_OP_DIV: {
// The GPU plugin can fuse broadcast DIV into the preceding FFN GEMM path
// and produce infs for per-channel scale vectors. Keep those DIVs on CPU
// until the fused GPU kernel is reliable. (falied case llama-arch-test mpt)
// until the fused GPU kernel is reliable (failing case: test-llama-archs, mpt).
// Only a weight divisor is such a scale; at one token an activation divisor has the same shape
// (qwen2moe's shared-expert sigmoid, silu(x) / x).
if (ggml_openvino_is_gpu() && op->src[1]->ne[0] == op->ne[0] &&
@@ -1898,11 +1923,14 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
memcpy(&max_bias, (const float *) op_params + 1, sizeof(float));
memcpy(&logit_softcap, (const float *) op_params + 2, sizeof(float));
// Keep gemma3n flash-attn pattern on CPU for GPU runs to avoid
// accuracy drift in the OpenVINO path. Restrict by scale=1.0 to avoid
// affecting non-gemma3n models such as Llama-3.2.
// Keep gemma3n flash-attn pattern on CPU to avoid accuracy drift in the OpenVINO path.
// Restrict by scale=1.0 to avoid affecting non-gemma3n models such as Llama-3.2.
if (fabsf(scale - 1.0f) < 1e-6f && is_gemma3n_flash_attn_pattern(op)) {
return {false, "FLASH_ATTN_EXT gemma3n pattern on GPU is not supported"};
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
@@ -1948,7 +1976,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
return {false, "CPY with BF16 src[1] type is not supported"};
}
if (ggml_openvino_is_npu() && (op->src[0]->type == GGML_TYPE_BF16 || op->src[1]->type == GGML_TYPE_BF16)) {
return {false, "CPY with BF16 is not supported is not supported on NPU"};
return {false, "CPY with BF16 is not supported on NPU"};
}
// CPY to a quantized destination (e.g. f32 -> q4_0) is numerically unstable with OpenVINO backend.
if (ggml_is_quantized(op->type)) {
@@ -2063,12 +2091,15 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
// return true;
// }
const char * reason = nullptr;
if (op->src[2]->op == GGML_OP_PERMUTE) {
// a VIEW of the PERMUTE (v with padded heads) is still a permuted v
const ggml_tensor * v_src = op->src[2]->op == GGML_OP_VIEW ? op->src[2]->src[0] : op->src[2];
if (v_src->op == GGML_OP_PERMUTE) {
reason = "GATED_DELTA_NET with PERMUTE src2 is not supported";
}
else if (op->src[3]->ne[0] != 1) {
// kda (per-key-dimension gating) not supported by fused GatedDeltaNet op
reason = "GATED_DELTA_NET with kda (per-key-dimension gating) is not supported";
else if (op->src[3]->ne[0] != 1 && (op->op_params[0] > 1 || ggml_openvino_gdn_native_state_enabled()) &&
!ov::frontend::ggml::op::gdn_per_key_gate_supported()) {
reason = "GATED_DELTA_NET with a per-key gate needs an OpenVINO GatedDeltaNet with a rank-4 gate for state "
"snapshots or the native state layout";
}
else if (op->op_params[0] > 1) {
if (ggml_openvino_is_static()) {
@@ -2082,12 +2113,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
}
return {false, reason};
}
break;
}
case GGML_OP_SSM_CONV: {
// qwen3next is numerically unstable with OpenVINO SSM_CONV.
// Keep this op on CPU until the OpenVINO implementation is fixed.
// return true;
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: {
@@ -2292,9 +2320,6 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg
if (!supported) {
return {false, "GLU op " + std::string(ggml_glu_op_name(ggml_get_glu_op(op))) + " has no op translator"};
}
// if (has_view_op_input(op)) {
// return {false, "GLU op " + std::string(ggml_glu_op_name(ggml_get_glu_op(op))) + " with view input is not supported"};
// }
if (op->src[1] == nullptr && op->src[0]->ne[0] % 2 != 0) {
// triggers bug in ov gpu
return {false, "GLU op with odd src0 ne[0] and null src1 is not supported"};
@@ -2347,16 +2372,114 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg
return {true, ""};
}
// Report what supports_op() accepts and rejects, so a graph that silently falls back to another
// backend can be diagnosed. Every op rejected here becomes a graph split; if nothing is rejected,
// the whole graph runs on OpenVINO.
//
// Gated by GGML_OPENVINO_LOG_SUPPORTS_OP:
// 1 one summary at exit listing every distinct op kind and verdict -- start here
// 2 additionally log every individual call, with the tensor name and shape
//
// This wraps the decision function instead of instrumenting it, so all of its return paths are
// covered -- including the several that reject without logging a reason of their own, and any
// added later.
//
// The summary is reported at exit rather than on each op's first occurrence, because the earliest
// calls happen before the log handler emits anything: with level 2 the first line to actually
// appear already reads "call 1244". A first-occurrence line would therefore be silently dropped
// for exactly the ops that are only ever seen early. Counting is unaffected, so the summary is the
// reliable view; treat the level-2 stream as a sample, not a complete trace.
namespace {
struct supports_op_tally {
std::mutex mutex;
// key: "<op>:ok" / "<op>:no" -> number of calls
std::map<std::string, size_t> counts;
// Report totals once, at exit. Registered lazily so a run with the knob off costs nothing.
// atexit runs while the ggml log callback is still valid, which static destruction does not
// guarantee.
void arm_summary() {
static std::once_flag armed;
std::call_once(armed, [] {
std::atexit([] {
auto & self = instance();
std::lock_guard<std::mutex> lock(self.mutex);
size_t n_accept_kinds = 0;
size_t n_reject_kinds = 0;
GGML_LOG_WARN("ov-supports-op: ---- summary (distinct op kinds, with call counts) ----\n");
for (const auto & [key, count] : self.counts) {
const bool ok = key.size() > 3 && key.compare(key.size() - 3, 3, ":ok") == 0;
ok ? ++n_accept_kinds : ++n_reject_kinds;
GGML_LOG_WARN("ov-supports-op: %-8s %-24s %zu call(s)\n", ok ? "ACCEPT" : "REJECT",
key.substr(0, key.size() - 3).c_str(), count);
}
if (n_reject_kinds == 0) {
GGML_LOG_WARN("ov-supports-op: %zu op kind(s) accepted, 0 rejected"
" -- every op was supported, so no split originated here\n",
n_accept_kinds);
} else {
GGML_LOG_WARN("ov-supports-op: %zu op kind(s) accepted, %zu REJECTED"
" -- each rejected kind forces a graph split\n",
n_accept_kinds, n_reject_kinds);
}
});
});
}
static supports_op_tally & instance() {
static supports_op_tally tally;
return tally;
}
};
} // namespace
static bool ggml_backend_openvino_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
auto res = ggml_backend_openvino_device_supports_op_impl(dev, op);
if (!res.is_supported) {
const bool supported = res.is_supported;
if (!supported) {
static const bool log_unsupported = ggml_openvino_getenv_int("GGML_OPENVINO_LOG_UNSUPPORTED_OPS") != 0;
if (log_unsupported) {
GGML_LOG_WARN("OpenVINO op unsupported: op '%s' (%s), type %s: %s\n",
op->name, ggml_op_name(op->op), ggml_type_name(op->type), res.reason.c_str());
}
}
return res.is_supported;
static const int log_level = ggml_openvino_getenv_int("GGML_OPENVINO_LOG_SUPPORTS_OP");
if (log_level <= 0) {
return supported;
}
// Name the op the way ggml does: UNARY and GLU carry their real identity in a sub-enum, so
// logging only "UNARY" would merge SILU with everything else.
std::string op_desc = ggml_op_name(op->op);
if (op->op == GGML_OP_UNARY) {
op_desc += std::string("/") + ggml_unary_op_name(ggml_get_unary_op(op));
} else if (op->op == GGML_OP_GLU) {
op_desc += std::string("/") + ggml_glu_op_name(ggml_get_glu_op(op));
}
// The scheduler calls supports_op() on every graph build and may do so from several threads,
// so the tally needs a lock. Keyed on op identity *and* verdict, because the same op can be
// accepted at one shape and rejected at another (e.g. a quantized 3-D src).
auto & tally = supports_op_tally::instance();
tally.arm_summary();
size_t count;
{
std::lock_guard<std::mutex> lock(tally.mutex);
count = ++tally.counts[op_desc + (supported ? ":ok" : ":no")];
}
if (log_level >= 2) {
GGML_LOG_WARN("ov-supports-op: %-6s %-22s name='%s' type=%s ne=[%ld,%ld,%ld,%ld] (call %zu)\n",
supported ? "ACCEPT" : "REJECT", op_desc.c_str(), op->name, ggml_type_name(op->type),
(long) op->ne[0], (long) op->ne[1], (long) op->ne[2], (long) op->ne[3], count);
}
return supported;
}
static bool ggml_backend_openvino_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
+19 -14
View File
@@ -154,19 +154,22 @@ void extract_q4_1_data(const ggml_tensor * tensor,
});
} else {
auto * zp = static_cast<uint8_t *>(zp_arr.data());
ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
float scale = static_cast<float>(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block))));
float min = static_cast<float>(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block + 2))));
scales[i] = ov::float16(scale);
// zp = -min / scale (bias = min, so zp = -bias/scale)
uint8_t zp_val = (scale != 0.0f) ? (uint8_t) std::round(-min / scale) : 0;
// Pack two 4-bit zero points per byte
if (i % 2 == 0) {
zp[i / 2] = zp_val & 0x0F; // Lower nibble
} else {
zp[i / 2] |= (zp_val << 4); // Upper nibble
const size_t n_blocks = scales_arr.get_size();
// One iteration per zero point byte: the two blocks that share a byte are packed together, so no two
// threads write the same byte.
ov::parallel_for((n_blocks + 1) / 2, [&](size_t pair) {
uint8_t packed = 0;
for (size_t i = 2 * pair; i < std::min(2 * pair + 2, n_blocks); i++) {
float scale = static_cast<float>(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block))));
float min =
static_cast<float>(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block + 2))));
scales[i] = ov::float16(scale);
// zp = -min / scale (bias = min, so zp = -bias/scale), in the u4 range
const uint8_t zp_val = (scale != 0.0f) ? (uint8_t) std::clamp(std::lround(-min / scale), 0L, 15L) : 0;
packed |= (i % 2 == 0) ? zp_val : (uint8_t) (zp_val << 4);
unpack_32_4(data + i * bytes_per_block + 4, weights + i * 16);
}
unpack_32_4(data + i * bytes_per_block + 4, weights + i * 16);
zp[pair] = packed;
});
}
}
@@ -259,7 +262,7 @@ void extract_q5_1_data(const ggml_tensor * tensor,
float min = static_cast<float>(ov::float16::from_bits(read_u16(block + 2)));
scales[i] = ov::float16(scale);
// zp = -min / scale (dequant: (w - zp) * s == w*s + min)
zp[i] = (scale != 0.0f) ? (uint8_t) std::lround(-min / scale) : 0;
zp[i] = (scale != 0.0f) ? (uint8_t) std::clamp(std::lround(-min / scale), 0L, 255L) : 0;
unpack_block(block, weights + i * qk);
});
}
@@ -378,7 +381,9 @@ void extract_q4_k_data(const ggml_tensor * tensor,
bias_f16[i * 8 + j] = ov::float16(-min_vals[j]);
} else {
// zp = min / scale (since bias = -min and zp = -bias/scale)
uint8_t zp_val = (scale_vals[j] != 0.0f) ? (uint8_t) std::round(min_vals[j] / scale_vals[j]) : 0;
uint8_t zp_val = (scale_vals[j] != 0.0f) ?
(uint8_t) std::clamp(std::lround(min_vals[j] / scale_vals[j]), 0L, 15L) :
0;
// Pack two 4-bit zero points per byte
size_t idx = i * 8 + j;
if (idx % 2 == 0) {
+7 -3
View File
@@ -186,6 +186,7 @@ static const char * cache_settings[] = {
"GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK",
"GGML_OPENVINO_KV_SCATTER_ELEMENTS",
"GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN",
"GGML_OPENVINO_ROPE_F32_ANGLE",
};
void ggml_openvino_model_cache_init() {
@@ -368,7 +369,8 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph,
// Version 6 clears recurrent-cache slots with Select, so a NaN in a cleared slot does not survive.
// Version 7 reads ROPE frequency factors named other than rope_freqs.weight as a Constant, not a Parameter.
// Version 8 drops result_norm from the outputs when it has a consumer, and hashes the output flags.
h = fnv1a_u64(h, 8);
// Version 9 hashes GGML_OPENVINO_ROPE_F32_ANGLE, which became opt-in.
h = fnv1a_u64(h, 9);
h = fnv1a(h, graph_signature.data(), graph_signature.size());
for (const char * name : cache_settings) {
const char * value = ggml_openvino_getenv_str(name, "");
@@ -548,8 +550,10 @@ static bool read_weights_hash(const std::string & path, uint64_t & hash) {
std::string key, value;
while (meta >> key >> value) {
if (key == "hash") {
hash = std::stoull(value, nullptr, 16);
return true;
// a damaged record counts as no hash, so the caller rewrites the file
char * end = nullptr;
hash = std::strtoull(value.c_str(), &end, 16);
return end != value.c_str() && *end == '\0';
}
}
return false;
@@ -0,0 +1,51 @@
#include "../node_context.h"
#include "../op_table.h"
#include "../utils.h"
#include "ggml.h"
#include <openvino/frontend/exception.hpp>
#include <openvino/op/concat.hpp>
#include <openvino/op/constant.hpp>
#include <openvino/op/reshape.hpp>
#include <openvino/op/topk.hpp>
namespace ov {
namespace frontend {
namespace ggml {
namespace op {
// GGML_OP_ARGMAX: src0 is a matrix [ne0, ne1]; the result is a 1-D I32 tensor of ne1 entries
// holding, for each row, the index of the maximum along ne0. ggml shapes arrive reversed here, so
// ne0 is the last OV axis and ne1 is axis 2. TopK(k=1, axis=last, MAX) yields exactly that index,
// then reshape to the [1,1,1,ne1] layout the decoder expects for a 1-D ggml output.
//
// Note ggml's argmax returns the FIRST maximum on a tie, while TopK's tie-breaking is not specified
// to match. Ties on real logits are vanishingly rare and none were observed, but the two are not
// proven equivalent.
OutputVector translate_argmax(const NodeContext & context) {
num_inputs_check(context, 1, 1);
auto input = process_view_input_new(context, 0);
auto k = ov::op::v0::Constant::create(ov::element::i64, {}, {1});
auto topk = std::make_shared<ov::op::v11::TopK>(input,
k,
3,
ov::op::v11::TopK::Mode::MAX,
ov::op::v11::TopK::SortType::SORT_VALUES,
context.get_output_type(),
false);
// ne1 is the dynamic row count, so build the target shape at runtime.
auto leading = ov::op::v0::Constant::create(ov::element::i64, {3}, {1, 1, 1});
auto rows = get_dimensions(input.get_node_shared_ptr(), {2});
auto target_shape = std::make_shared<ov::op::v0::Concat>(OutputVector{leading, rows}, 0);
auto res = std::make_shared<ov::op::v1::Reshape>(topk->output(1), target_shape, false);
return rename_outputs_with_suffix({res}, context.get_name());
}
} // namespace op
} // namespace ggml
} // namespace frontend
} // namespace ov
@@ -182,13 +182,7 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
// Manual GQA attention: enabled by default on GPU in stateless mode.
// Set GGML_OPENVINO_MANUAL_GQA_ATTN to a positive value (e.g. 1) to force-enable,
// or to 0 to force-disable. Unset falls back to the device-based default.
static const bool manual_gqa_enabled = []() {
const char * env = ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN");
if (env != nullptr) {
return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0;
}
return ggml_openvino_is_gpu();
}();
static const bool manual_gqa_enabled = ggml_openvino_manual_gqa_enabled();
// The manual path reshapes Q, K, V and the output with one head size; models whose K/V head sizes differ
// from Q's (e.g. MLA) take the SDPA path.
const bool same_head_size = k_shape[3] == q_shape[3] && v_shape[3] == q_shape[3];
@@ -15,6 +15,7 @@
#include <memory>
#include <mutex>
#include <numeric>
#include <openvino/core/model.hpp>
#include <openvino/op/add.hpp>
#include <openvino/op/broadcast.hpp>
#include <openvino/op/concat.hpp>
@@ -29,6 +30,7 @@
#include <openvino/op/maximum.hpp>
#include <openvino/op/minimum.hpp>
#include <openvino/op/multiply.hpp>
#include <openvino/op/parameter.hpp>
#include <openvino/op/range.hpp>
#include <openvino/op/reduce_mean.hpp>
#include <openvino/op/reshape.hpp>
@@ -52,6 +54,31 @@ namespace op {
static OutputVector translate_gated_delta_net_ref(const NodeContext & context);
// Asks the device: OpenVINO releases without the per-key gate reject a rank-4 gate when the node is built, and a plugin
// without a per-key kernel leaves the node out of query_model
bool gdn_per_key_gate_supported() {
static const bool supported = [] {
ov::ParameterVector params;
auto param = [&params](const ov::Shape & shape) {
params.push_back(std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape));
return params.back();
};
std::shared_ptr<ov::Node> gdn;
try {
gdn = std::make_shared<ov::op::internal::GatedDeltaNet>(param({1, 1, 1, 2}), param({1, 1, 1, 2}),
param({1, 1, 1, 2}), param({1, 1, 2, 2}),
param({1, 1, 1, 2}), param({1, 1, 1}));
} catch (const ov::Exception &) {
return false;
}
const auto model = std::make_shared<ov::Model>(gdn->outputs(), params);
return ov_singleton_core()
.query_model(model, ggml_openvino_get_device_name())
.count(gdn->get_friendly_name()) != 0;
}();
return supported;
}
static bool match_gdn_l2_norm(const Output<Node> & normalized, Output<Node> & input, float & eps) {
// Match the RMSNorm decomposition emitted by translate_rms_norm, followed by GGML SCALE.
const auto scale = ov::as_type_ptr<ov::op::v1::Multiply>(normalized.get_node_shared_ptr());
@@ -379,23 +406,36 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
auto v_shape = context.get_input_shape(2).to_shape(); // [B, T, H_v, S_v]
auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k]
// Fused GatedDeltaNet op only supports scalar gate (kda=0).
// Fall back to reference implementation for per-key-dimension gating.
// if (kda) {
// return translate_gated_delta_net_ref(context);
// }
// g [B, T, H_v, 1] gates each head, g [B, T, H_v, S_k] each key dimension (kda); the fused op takes the latter as
// a rank-4 gate
const bool kda = context.get_input_shape(3)[3] != 1;
if (kda && !gdn_per_key_gate_supported()) {
// the reference loop reads and writes the state in the ggml layout, one state per call
FRONT_END_OP_CONVERSION_CHECK(!cache_inputs && context.get_output_op_params()[0] == 1 &&
!ggml_openvino_gdn_native_state_enabled(),
"GATED_DELTA_NET with a per-key gate needs an OpenVINO GatedDeltaNet with a rank-4 "
"gate for recurrent caches, state snapshots or the native state layout");
return translate_gated_delta_net_ref(context);
}
// const int64_t B = v_shape[0];
// const int64_t T = v_shape[1];
const int64_t H_v = v_shape[2];
const int64_t S_v = v_shape[3];
const int64_t H_k = q_shape[2];
const int64_t snapshot_count = context.get_output_op_params()[0];
// const int64_t S_k = q_shape[3];
// v is usually a VIEW of the fused qkv conv output, [S_v, H_v, T, B] over [conv_dim, T, B], with the heads packed
// in each row: a Slice of that row plus the Reshape below. Any other view layout, e.g. heads padded to a wider
// row, goes through the generic view resolution, which already returns [B, T, H_v, S_v].
const bool v_is_view = context.get_view_input_size(2) > 0;
bool v_packed_heads = true;
if (v_is_view) {
const auto v_stride = context.get_view_input_stride(2, 0); // OV order: v_stride[3] = nb[0], v_stride[2] = nb[1]
v_packed_heads = v_stride.size() == 4 && v_stride[2] == (size_t) S_v * v_stride[3];
}
auto q = context.get_input(0);
auto k = context.get_input(1);
auto v = process_view_input(context, 2, H_v * S_v, 3);
auto v = v_packed_heads ? process_view_input(context, 2, H_v * S_v, 3) : process_view_input_new(context, 2);
auto g = context.get_input(3);
auto beta = context.get_input(4);
auto state = context.get_input(5);
@@ -424,7 +464,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
k = std::make_shared<ov::op::v0::Tile>(k, repeats);
}
if (context.get_view_input_size(2)) {
if (v_is_view && v_packed_heads) {
// Same as l2_norm case 1
v = std::make_shared<ov::op::v0::Squeeze>(v, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
auto v_shape = context.get_input_shape(2).to_shape();
@@ -443,7 +483,9 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
state = std::make_shared<ov::op::v1::Transpose>(state, state_perm);
}
g = std::make_shared<ov::op::v0::Squeeze>(g, ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
if (!kda) {
g = std::make_shared<ov::op::v0::Squeeze>(g, ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
}
beta = std::make_shared<ov::op::v0::Squeeze>(beta, ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
if (context.has_input("chunk_valid_len")) {
@@ -453,7 +495,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
// state equal to the state after the last real token. Attention output at those positions
// is garbage but never read.
const auto & g_ps = g.get_partial_shape();
FRONT_END_OP_CONVERSION_CHECK(g_ps.rank().is_static() && g_ps.rank().get_length() == 3 && g_ps[1].is_static(),
FRONT_END_OP_CONVERSION_CHECK(g_ps.rank().is_static() && g_ps[1].is_static(),
"GATED_DELTA_NET pad masking requires a static token dimension");
const int64_t n_tokens = g_ps[1].get_length();
std::vector<int64_t> positions(n_tokens);
@@ -464,8 +506,12 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
auto mask = std::make_shared<ov::op::v0::Unsqueeze>(
std::make_shared<ov::op::v0::Convert>(valid, g.get_element_type()),
ov::op::v0::Constant::create(ov::element::i64, {2}, std::vector<int64_t>{0, 2}));
g = std::make_shared<ov::op::v1::Multiply>(g, mask);
beta = std::make_shared<ov::op::v1::Multiply>(beta, mask);
if (kda) {
mask = std::make_shared<ov::op::v0::Unsqueeze>(mask,
ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
}
g = std::make_shared<ov::op::v1::Multiply>(g, mask);
}
// std::cout << "GatedDeltaNet input shapes: q=" << q.get_partial_shape() << ", k=" << k.get_partial_shape()
@@ -540,6 +586,8 @@ OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, co
static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
num_inputs_check(context, 6, 6);
FRONT_END_OP_CONVERSION_CHECK(!context.has_input("chunk_valid_len"),
"GATED_DELTA_NET reference loop does not support padded prefill chunks");
// Inputs (OV shapes are reversed from ggml):
// ggml: q[S_k, H_k, T, B], k[S_k, H_k, T, B], v[S_v, H_v, T, B]
@@ -559,8 +607,8 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k]
auto g_shape = context.get_input_shape(3).to_shape(); // [B, T, H_v, 1 or S_v]
// The token count T is dynamic: shapes below use -1 for it and the loop runs once per input token.
const int64_t B = v_shape[0];
const int64_t T = v_shape[1];
const int64_t H_v = v_shape[2];
const int64_t S_v = v_shape[3];
const int64_t H_k = q_shape[2];
@@ -599,14 +647,14 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
auto q_transposed = std::make_shared<ov::op::v1::Transpose>(q_bcast, perm_5d);
auto k_transposed = std::make_shared<ov::op::v1::Transpose>(k_bcast, perm_5d);
auto new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, T, S_v});
auto new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, -1, S_v});
q_bh = std::make_shared<ov::op::v1::Reshape>(q_transposed, new_shape, false);
k_bh = std::make_shared<ov::op::v1::Reshape>(k_transposed, new_shape, false);
}
// Merge batch and head dims: [B*H_v, T, S_v]
auto merge_bh = [&](const ov::Output<ov::Node> & x, int64_t last_dim) {
auto shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{B * H_v, T, last_dim});
auto shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{B * H_v, -1, last_dim});
return std::make_shared<ov::op::v1::Reshape>(x, shape, false);
};
@@ -682,7 +730,9 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
ov::OutputVector{body_cond_out, state_updated, attn_out_unsq},
ov::ParameterVector{body_iter, body_state, body_q, body_k, body_v, body_g, body_beta});
auto trip_count = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{T});
auto vm_shape = std::make_shared<ov::op::v3::ShapeOf>(v_m, ov::element::i64);
auto trip_count =
std::make_shared<ov::op::v8::Gather>(vm_shape, axis_1, ov::op::v0::Constant::create(ov::element::i64, {}, {0}));
auto exec_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, std::vector<bool>{true});
auto loop = std::make_shared<ov::op::v5::Loop>(trip_count, exec_cond);
@@ -709,7 +759,7 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
// attn: [B, T, H_v, S_v] row-major, state: [B, H_v, S_v, S_v] row-major
// attn: [B*H_v, T, S_v] -> [B, H_v, T, S_v] -> transpose to [B, T, H_v, S_v] -> flatten
auto attn_4d_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, T, S_v});
auto attn_4d_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, -1, S_v});
auto attn_4d = std::make_shared<ov::op::v1::Reshape>(attn_concat_out, attn_4d_shape, false);
auto attn_perm = std::make_shared<ov::op::v1::Transpose>(attn_4d, perm_0213); // [B, T, H_v, S_v]
@@ -729,7 +779,7 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
// Concat [attn | state] and reshape to final output
auto packed = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{attn_1d, state_1d}, 0);
auto out_shape =
ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, T * B + S_v * B, S_v * H_v});
ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, -1, S_v * H_v});
auto res = std::make_shared<ov::op::v1::Reshape>(packed, out_shape, false);
return rename_outputs_with_suffix({res}, context.get_name());
@@ -30,6 +30,10 @@ OutputVector translate_reshape(const NodeContext & context) {
std::shared_ptr<ov::Node> new_shape_node;
switch (op_case) {
case 0:
// keep the tracked dynamic dim, e.g. the tokens of a reshape that only adds a trailing 1 (see translate_cont)
if (context.get_op_dynamic_dim() != -1) {
shape[3 - context.get_op_dynamic_dim()] = -1;
}
break;
case 1:
case 9:
@@ -34,7 +34,7 @@ OutputVector translate_rms_norm(const NodeContext & context) {
input_node = context.get_input(0);
} else if (op_case == 1) {
input_node = process_view_input_new(context, 0);
} else if (op_case == 2 || op_case == 3) {
} else if (op_case == 2 || op_case == 5) {
auto ssm_state_size = context.get_ssm_state_size();
// The GDN op packs [attn | new_state] along the row axis; the state occupies the last
// ssm_state_size * n_seqs rows. Slice it off (scaling by the active sequence count) to keep
@@ -83,7 +83,7 @@ OutputVector translate_rms_norm(const NodeContext & context) {
float eps;
memcpy(&eps, context.get_output_op_params(), sizeof(float));
if (op_case == 3 && ggml_openvino_gdn_prescale_enabled()) {
if ((op_case == 3 || op_case == 5) && ggml_openvino_gdn_prescale_enabled()) {
// input is the GDN output pre-scaled by ggml_openvino_gdn_q_scale(): rms_norm(s*x, s*s*eps) == rms_norm(x, eps)
const float q_scale = ggml_openvino_gdn_q_scale();
eps *= q_scale * q_scale;
@@ -118,16 +118,41 @@ static OutputVector translate_column_set_rows(const NodeContext & context) {
if (data.get_element_type() != context.get_output_type()) {
data = std::make_shared<v0::Convert>(data, context.get_output_type());
}
Output<Node> rows = std::make_shared<v1::Reshape>(process_view_input_new(context, 1), i64_const({-1}), false);
auto row_ids = process_view_input_new(context, 1);
Output<Node> rows = std::make_shared<v1::Reshape>(row_ids, i64_const({-1}), false);
if (rows.get_element_type() != ov::element::i64) {
rows = std::make_shared<v0::Convert>(rows, ov::element::i64);
}
auto axis = v0::Constant::create(ov::element::i64, {}, {2});
auto buffer = std::make_shared<v1::Reshape>(base, i64_const({1, 1, -1, row_size}), false);
Output<Node> buffer = std::make_shared<v1::Reshape>(base, i64_const({1, 1, -1, row_size}), false);
Output<Node> base_shape_of = std::make_shared<v3::ShapeOf>(base, ov::element::i64);
Output<Node> existing;
// Every write copies the whole buffer, so fold this one into the previous column write when both use the same
// rows (DFlash writes every target layer at the same batch rows): splice into its rows and scatter once
auto rows_source = [](Output<Node> r) {
if (ov::as_type_ptr<v0::Convert>(r.get_node_shared_ptr())) {
r = r.get_node()->input_value(0);
}
return ov::as_type_ptr<v1::Reshape>(r.get_node_shared_ptr()) ? r.get_node()->input_value(0) : Output<Node>();
};
auto prev_res = ov::as_type_ptr<v1::Reshape>(base.get_node_shared_ptr());
auto prev = prev_res ? ov::as_type_ptr<v3::ScatterUpdate>(prev_res->get_input_node_shared_ptr(0)) : nullptr;
if (prev && rows_source(prev->input_value(1)) == row_ids &&
prev->input_value(2).get_partial_shape().rank().is_static() &&
prev->input_value(2).get_partial_shape()[3] == row_size) {
buffer = prev->input_value(0);
rows = prev->input_value(1);
existing = prev->input_value(2);
base_shape_of = prev_res->input_value(1);
}
Output<Node> updates = data;
if (width < row_size) {
auto existing = std::make_shared<v8::Gather>(buffer, rows, axis);
if (!existing.get_node_shared_ptr()) {
existing = std::make_shared<v8::Gather>(buffer, rows, axis);
}
auto col_axis = i64_const({3});
OutputVector parts;
if (col_begin > 0) {
@@ -142,7 +167,7 @@ static OutputVector translate_column_set_rows(const NodeContext & context) {
updates = std::make_shared<v0::Concat>(parts, 3);
}
auto updated = std::make_shared<v3::ScatterUpdate>(buffer, rows, updates, axis);
auto res = std::make_shared<v1::Reshape>(updated, std::make_shared<v3::ShapeOf>(base, ov::element::i64), false);
auto res = std::make_shared<v1::Reshape>(updated, base_shape_of, false);
return rename_outputs_with_suffix({res}, context.get_name());
}
@@ -1,108 +0,0 @@
#include "../node_context.h"
#include "../op_table.h"
#include "../utils.h"
#include <openvino/op/broadcast.hpp>
#include <openvino/op/constant.hpp>
#include <openvino/op/divide.hpp>
#include <openvino/op/gather.hpp>
#include <openvino/op/loop.hpp>
#include <openvino/op/matmul.hpp>
#include <openvino/op/scatter_update.hpp>
#include <openvino/op/shape_of.hpp>
#include <openvino/op/subtract.hpp>
namespace ov {
namespace frontend {
namespace ggml {
namespace op {
// GGML SOLVE_TRI: solve Ax = B for lower-triangular A via forward substitution.
// Currently only lower, right, non-unitriangular variant is implemented.
//
// ggml layout: A [n, n, B1, B2], B [k, n, B1, B2] → X [k, n, B1, B2]
// OV layout: A [B2, B1, n, n], B [B2, B1, n, k] → X [B2, B1, n, k]
//
// Forward substitution row i:
// x[i] = (b[i] - sum_{t<i} A[i,t]*x[t]) / A[i,i]
//
// Implemented as an OV Loop op iterating n times with a carried X accumulator.
// Key insight: A is lower-triangular and X starts as zeros, so the full matmul
// A_row_i @ X_partial = sum_{t<i} A[i,t]*x[t] exactly (upper triangle of A
// is zero; unfilled rows of X are zero).
OutputVector translate_solve_tri(const NodeContext & context) {
num_inputs_check(context, 2, 2);
auto A = context.get_input(0); // [B2, B1, n, n]
auto B = context.get_input(1); // [B2, B1, n, k]
auto A_shape = context.get_input_shape(0).to_shape();
int64_t n = static_cast<int64_t>(A_shape[2]);
// Initial X: zeros with shape of B
auto B_shape_node = std::make_shared<ov::op::v3::ShapeOf>(B, ov::element::i64);
auto zero_f32 = ov::op::v0::Constant::create(ov::element::f32, {}, {0.0f});
auto X_init = std::make_shared<ov::op::v3::Broadcast>(zero_f32, B_shape_node);
// --- Loop body parameters ---
// body_iter: iteration counter injected by the Loop op (i64, shape {1})
auto body_iter = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1});
auto body_X = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
auto body_A = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
auto body_B_p = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
auto c_axis2 = ov::op::v0::Constant::create(ov::element::i64, {1}, {int64_t(2)});
auto c_axis3 = ov::op::v0::Constant::create(ov::element::i64, {1}, {int64_t(3)});
auto c_axis2_scalar = ov::op::v0::Constant::create(ov::element::i64, {}, {int64_t(2)});
// b_i = B[..., i, :] [B2, B1, 1, k]
auto b_i = std::make_shared<ov::op::v8::Gather>(body_B_p, body_iter, c_axis2);
// A_row_i = A[..., i, :] [B2, B1, 1, n]
auto A_row_i = std::make_shared<ov::op::v8::Gather>(body_A, body_iter, c_axis2);
// sum_i = A_row_i @ X [B2, B1, 1, k]
// (lower-tri zeros + unfilled-X zeros make this equal to the partial sum)
auto sum_i = std::make_shared<ov::op::v0::MatMul>(A_row_i, body_X, false, false);
// diag_i = A[..., i, i] [B2, B1, 1, 1]
auto diag_i = std::make_shared<ov::op::v8::Gather>(A_row_i, body_iter, c_axis3);
// x_i = (b_i - sum_i) / diag_i [B2, B1, 1, k]
auto x_i = std::make_shared<ov::op::v1::Divide>(
std::make_shared<ov::op::v1::Subtract>(b_i, sum_i), diag_i);
// X_updated: scatter x_i into body_X at row i along axis 2
auto X_updated = std::make_shared<ov::op::v3::ScatterUpdate>(body_X, body_iter, x_i, c_axis2_scalar);
auto body_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, {true});
auto body = std::make_shared<ov::Model>(
ov::OutputVector{body_cond, X_updated},
ov::ParameterVector{body_iter, body_X, body_A, body_B_p});
// --- Assemble Loop ---
auto trip_count = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{n});
auto exec_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, {true});
auto loop = std::make_shared<ov::op::v5::Loop>(trip_count, exec_cond);
loop->set_function(body);
// iter_counter_body_param_idx=0 (body_iter), exec_condition_body_result_idx=0 (body_cond)
loop->set_special_body_ports(ov::op::v5::Loop::SpecialBodyPorts{0, 0});
// Carried state: X feeds back from X_updated each iteration
loop->set_merged_input(body_X, X_init, X_updated);
// Invariant inputs passed through unchanged
loop->set_invariant_input(body_A, A);
loop->set_invariant_input(body_B_p, B);
// Final output: value of X_updated after the last iteration
auto X_final = loop->get_iter_value(X_updated, -1);
return rename_outputs_with_suffix({X_final}, context.get_name());
}
} // namespace op
} // namespace ggml
} // namespace frontend
} // namespace ov
+1 -3
View File
@@ -57,6 +57,7 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {
{"GGML_OP_SQR", op::translate_sqr },
{"GGML_OP_SQRT", op::translate_sqrt },
{"GGML_OP_SOFT_MAX", op::translate_soft_max },
{"GGML_OP_ARGMAX", op::translate_argmax },
{"GGML_OP_ARGSORT", op::translate_argsort },
{"GGML_OP_SUB", op::translate_1to1_match_2_inputs<v1::Subtract>},
{"GGML_OP_TRANSPOSE", op::translate_transpose },
@@ -102,7 +103,6 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {
{"GGML_OP_GATED_DELTA_NET", op::translate_gated_delta_net },
{"GGML_OP_REPEAT", op::translate_repeat },
{"GGML_OP_CUMSUM", op::translate_cumsum },
{"GGML_OP_FILL", op::translate_fill },
{"GGML_OP_DIAG", op::translate_diag },
{"GGML_OP_TRI", op::translate_tri },
{"GGML_OP_SET", op::translate_set },
@@ -115,8 +115,6 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {
{"GGML_OP_CONV_TRANSPOSE_1D", op::translate_conv_transpose_1d },
{"GGML_OP_CONV_TRANSPOSE_2D", op::translate_conv_transpose_2d },
{"GGML_OP_CONV_3D", op::translate_conv_3d },
// solve_tri has accuracy issues on GPU
// {"GGML_OP_SOLVE_TRI", op::translate_solve_tri },
};
}
+3 -2
View File
@@ -43,6 +43,7 @@ GGML_OP_CONVERTER(translate_glu_geglu);
GGML_OP_CONVERTER(translate_glu_geglu_quick);
GGML_OP_CONVERTER(translate_set_rows);
GGML_OP_CONVERTER(translate_cpy);
GGML_OP_CONVERTER(translate_argmax);
GGML_OP_CONVERTER(translate_argsort);
GGML_OP_CONVERTER(translate_top_k);
GGML_OP_CONVERTER(translate_flash_attn_ext);
@@ -51,16 +52,16 @@ GGML_OP_CONVERTER(translate_pad);
GGML_OP_CONVERTER(translate_ssm_conv);
GGML_OP_CONVERTER(translate_ssm_scan);
GGML_OP_CONVERTER(translate_gated_delta_net);
// The device runs GatedDeltaNet with a gate per key dimension; otherwise the translator falls back to its reference loop
bool gdn_per_key_gate_supported();
#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs);
#endif
GGML_OP_CONVERTER(translate_repeat);
GGML_OP_CONVERTER(translate_cumsum);
GGML_OP_CONVERTER(translate_fill);
GGML_OP_CONVERTER(translate_set);
GGML_OP_CONVERTER(translate_diag);
GGML_OP_CONVERTER(translate_tri);
GGML_OP_CONVERTER(translate_solve_tri);
GGML_OP_CONVERTER(translate_pool_1d);
GGML_OP_CONVERTER(translate_pool_2d);
GGML_OP_CONVERTER(translate_roll);
@@ -1,60 +0,0 @@
#include "fuse_to_sdpa.h"
#include <openvino/core/graph_util.hpp>
#include <openvino/core/rt_info.hpp>
#include <openvino/op/add.hpp>
#include <openvino/op/convert.hpp>
#include <openvino/op/matmul.hpp>
#include <openvino/op/multiply.hpp>
#include <openvino/op/scaled_dot_product_attention.hpp>
#include <openvino/op/softmax.hpp>
#include <openvino/op/transpose.hpp>
#include <openvino/pass/pattern/op/label.hpp>
#include <openvino/pass/pattern/op/pattern.hpp>
#include <openvino/pass/pattern/op/wrap_type.hpp>
namespace ov {
namespace frontend {
namespace ggml {
namespace pass {
FuseToSDPA::FuseToSDPA() {
// Not maintained since FLASH_ATTN_EXT has replaced this pattern
const auto m_k = ov::pass::pattern::any_input();
const auto m_q = ov::pass::pattern::any_input();
const auto m_qk = ov::pass::pattern::wrap_type<ov::op::v0::MatMul>({m_q, m_k});
const auto m_qk_f32 = ov::pass::pattern::wrap_type<ov::op::v0::Convert>({m_qk});
const auto m_scale = ov::pass::pattern::any_input();
const auto m_scaled_qk = ov::pass::pattern::wrap_type<ov::op::v1::Multiply>({m_qk_f32, m_scale});
const auto m_mask = ov::pass::pattern::any_input();
const auto m_masked_qk = ov::pass::pattern::wrap_type<ov::op::v1::Add>({m_scaled_qk, m_mask});
const auto m_softmax_qk = ov::pass::pattern::wrap_type<ov::op::v8::Softmax>({m_masked_qk});
const auto m_softmax_qk_f16 = ov::pass::pattern::wrap_type<ov::op::v0::Convert>({m_softmax_qk});
const auto m_v = ov::pass::pattern::any_input();
const auto m_qkv = ov::pass::pattern::wrap_type<ov::op::v0::MatMul>({m_softmax_qk_f16, m_v});
const auto callback = [=](ov::pass::pattern::Matcher & m) {
auto & pattern_to_output = m.get_pattern_value_map();
auto k = pattern_to_output[m_k];
auto q = pattern_to_output[m_q];
auto v = pattern_to_output[m_v];
auto mask = pattern_to_output[m_mask];
auto scale = pattern_to_output[m_scale];
auto mask_f16 = register_new_node<ov::op::v0::Convert>(mask, ov::element::f16);
auto scale_f16 = register_new_node<ov::op::v0::Convert>(scale, ov::element::f16);
auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q, k, v, mask_f16, scale_f16, false);
ov::replace_node(m.get_match_root(), sdpa);
ov::copy_runtime_info(m.get_matched_nodes(), sdpa);
return true;
};
register_matcher(std::make_shared<ov::pass::pattern::Matcher>(m_qkv, "ov::frontend::ggml::pass::FuseToSDPA"),
callback);
}
} // namespace pass
} // namespace ggml
} // namespace frontend
} // namespace ov
@@ -1,17 +0,0 @@
#include "openvino/pass/matcher_pass.hpp"
namespace ov {
namespace frontend {
namespace ggml {
namespace pass {
class FuseToSDPA : public ov::pass::MatcherPass {
public:
OPENVINO_MATCHER_PASS_RTTI("ov::frontend::ggml::pass::FuseToSDPA")
FuseToSDPA();
};
} // namespace pass
} // namespace ggml
} // namespace frontend
} // namespace ov
@@ -225,42 +225,12 @@ void add_position_mask_stateful_swa(TensorMap & tensor_map) {
tensor_map["KQ_mask_swa_sliced"] = mask->output(0);
}
void add_rope_sin_cos(TensorMap & tensor_map, GgmlDecoder & ggml_model_decoder) {
// When ROPE ops in the graph have divergent op_params (e.g. gemma4's mixed
// SWA/non-SWA layers with different n_dims or freq_base), a shared sin/cos
// precompute cannot broadcast across every ROPE use. Skip it here and let
// translate_rope() build sin/cos per-op from its own op_params.
if (ggml_model_decoder.has_mixed_rope_params()) {
return;
}
int32_t * rope_params = ggml_model_decoder.get_rope_params();
if (tensor_map.find("inp_pos") == tensor_map.end() || rope_params == nullptr) {
return;
}
auto inp_pos = tensor_map.at("inp_pos").get_node_shared_ptr();
std::shared_ptr<ov::Node> rope_freqs_weight;
if (tensor_map.find("rope_freqs.weight") != tensor_map.end()) {
rope_freqs_weight = tensor_map.at("rope_freqs.weight").get_node_shared_ptr();
}
auto sin_cos = make_sin_cos(rope_params, inp_pos, rope_freqs_weight);
auto sin_theta = sin_cos.first;
auto cos_theta = sin_cos.second;
cos_theta.get_node_shared_ptr()->set_friendly_name("rope_cos");
sin_theta.get_node_shared_ptr()->set_friendly_name("rope_sin");
tensor_map.insert({"rope_cos", cos_theta});
tensor_map.insert({"rope_sin", sin_theta});
}
// Create common patterns
void preprocess(TensorMap & tensor_map, GgmlDecoder & ggml_model_decoder) {
if (ggml_model_decoder.is_stateful()) {
add_sliced_mask_stateful(tensor_map, ggml_model_decoder.get_rope_params()[2] == GGML_ROPE_TYPE_IMROPE);
add_position_mask_stateful_swa(tensor_map);
}
// This optimization is error-prone
// add_rope_sin_cos(tensor_map, ggml_model_decoder);
}
} // namespace
+78 -23
View File
@@ -31,6 +31,7 @@
#include <openvino/op/subtract.hpp>
#include <openvino/op/transpose.hpp>
#include <openvino/op/unsqueeze.hpp>
#include <openvino/op/util/precision_sensitive_attribute.hpp>
#include <string>
namespace ov {
@@ -43,18 +44,6 @@ void num_inputs_check(const NodeContext & context, size_t min_inputs, size_t max
FRONT_END_OP_CONVERSION_CHECK(input_size <= max_inputs, "Got more inputs than expected");
}
int non_cont_dim(std::vector<size_t> ne, std::vector<size_t> nb) {
int dim = nb.size() - 1;
size_t bytes = nb[dim];
for (int i = dim; i > 0; i--) {
bytes *= ne[i];
if (bytes != nb[i - 1]) {
return i;
}
}
return 0;
}
std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::op::v3::ShapeOf> & shape,
const std::vector<int> & dims) {
using namespace ov::op;
@@ -311,14 +300,77 @@ std::pair<ov::Output<Node>, ov::Output<Node>> make_sin_cos(int32_t * rope_params
}
}
Output<Node> cos_theta = std::make_shared<ov::op::v0::Cos>(theta);
Output<Node> sin_theta = std::make_shared<ov::op::v0::Sin>(theta);
// Keep the ROPE ANGLE in f32 even under INFERENCE_PRECISION_HINT=f16.
//
// Everything above builds theta = pos * freq_factors with a declared f32 type, but a declared
// element type is not an execution precision: under the f16 hint the GPU plugin compresses these
// subgraphs to f16 anyway. theta's magnitude IS the token position, so at position 6525 it lands
// where f16 spacing is 4 and the value is not even representable. Worse, a model whose freq_base
// and head_dim make factor[0] == 1.0 exactly feeds the raw position in as the top-frequency
// angle, so an absolute error of 1-2 becomes an error of 1-2 RADIANS -- up to a third of a cycle. Sin/Cos of an angle wrong by radians is not approximately
// right, it is arbitrary, and trig amplifies the error without bound.
//
// Measured on a large decoder-only model at inp_pos=6525, same device, f16 vs f32 execution: the
// whole Q/K projection chain is clean at rel ~1e-4, then Cos jumps to rel 0.124 and Sin to 0.155,
// and K right after the rotation carries rel 0.081. The error is depth-dependent because f16
// spacing grows with magnitude: sin rel is 0.006 at position 512 and 0.16 at 6525.
//
// mark_as_precision_sensitive disables fp16 compression of the subgraph feeding an input, which is
// exactly the guarantee needed. Marking Sin/Cos's input covers the whole theta chain back to the
// Convert of inp_pos. The cost is negligible: theta is a few dozen values per token, against the
// matmuls that dominate. The rotation itself and everything downstream stay f16.
//
// Off by default; GGML_OPENVINO_ROPE_F32_ANGLE=1 turns it on. It changes the RoPE of every model,
// it is validated on one model on the GPU only, and on an f32 path the round trip below makes
// cos and sin less accurate.
const bool pin_angle = ggml_openvino_getenv_int("GGML_OPENVINO_ROPE_F32_ANGLE") != 0;
auto cos_op = std::make_shared<ov::op::v0::Cos>(theta);
auto sin_op = std::make_shared<ov::op::v0::Sin>(theta);
if (pin_angle) {
ov::mark_as_precision_sensitive(cos_op->input(0));
ov::mark_as_precision_sensitive(sin_op->input(0));
}
Output<Node> cos_theta = cos_op;
Output<Node> sin_theta = sin_op;
if (mscale != 1.0f) {
auto mscale_node = ov::op::v0::Constant::create(ov::element::f32, Shape{}, {mscale});
cos_theta = std::make_shared<ov::op::v1::Multiply>(cos_theta, mscale_node);
sin_theta = std::make_shared<ov::op::v1::Multiply>(sin_theta, mscale_node);
auto cos_scaled = std::make_shared<ov::op::v1::Multiply>(cos_theta, mscale_node);
auto sin_scaled = std::make_shared<ov::op::v1::Multiply>(sin_theta, mscale_node);
// Mark this Constant's input too. Marking only Sin/Cos keeps those nodes f32 but leaves the
// sibling mscale Constant to be compressed to f16, and the pass does not reconcile the pair,
// so compilation fails with "Arguments do not have the same element type".
if (pin_angle) {
ov::mark_as_precision_sensitive(cos_scaled->input(1));
ov::mark_as_precision_sensitive(sin_scaled->input(1));
}
cos_theta = cos_scaled;
sin_theta = sin_scaled;
}
// Close the f32 island explicitly with an f16 round trip.
//
// ConvertPrecision does not insert the boundary Convert: with only the marking above, the f32
// region propagates forward through the shape-only ops of the cos/sin expansion and then collides
// with f16 data in the rotation, so the type mismatch just moves one step down the graph.
//
// Rounding the RESULT of the trig is harmless -- cos/sin are in [-1,1], where f16 spacing is ~6e-4,
// the ordinary f16 cost accepted everywhere else. What must not be rounded is the ANGLE, which the
// marking above protects. So this spends the cheap rounding to buy a type-consistent graph: the
// chain from inp_pos through Sin/Cos stays f32, everything downstream is f16, and the transition is
// a node we control rather than one the pass has to infer.
//
// Declared types are f32 on both sides at build time, so the frontend sees no type change. On an
// f32 path (the CPU device in test-backend-ops) the two Converts still round cos and sin to f16.
if (pin_angle) {
auto pin_boundary = [](Output<Node> x) -> Output<Node> {
auto down = std::make_shared<ov::op::v0::Convert>(x, ov::element::f16);
return std::make_shared<ov::op::v0::Convert>(down, ov::element::f32);
};
cos_theta = pin_boundary(cos_theta);
sin_theta = pin_boundary(sin_theta);
}
return std::make_pair(sin_theta, cos_theta);
@@ -784,20 +836,23 @@ ov::Output<ov::Node> process_view_input_new(const NodeContext & context, int inp
return split_node->output(static_cast<size_t>(split_index));
}
if (split_index >= 0 && split_index < num_splits && !dynamic_split) {
// as above: a weak reference, and one Split per output port
auto src_node = input.get_node_shared_ptr();
std::string rt_key = "split_dim_" + std::to_string(split_dim);
std::string rt_key =
"split_dim_static_" + std::to_string(split_dim) + "_" + std::to_string(input.get_index());
auto & rt_info = src_node->get_rt_info();
if (rt_info.find(rt_key) == rt_info.end()) {
std::shared_ptr<ov::Node> split_node;
if (rt_info.count(rt_key) != 0) {
split_node = rt_info[rt_key].as<std::weak_ptr<ov::Node>>().lock();
}
if (split_node == nullptr) {
auto axis_const =
ov::op::v0::Constant::create(ov::element::i64, {}, {static_cast<int64_t>(split_dim)});
auto split_node =
split_node =
std::make_shared<ov::op::v1::Split>(input, axis_const, static_cast<size_t>(num_splits));
split_node->set_friendly_name(src_node->get_friendly_name() + "_split");
rt_info[rt_key] = split_node;
rt_info[rt_key] = std::weak_ptr<ov::Node>(split_node);
}
auto split_node = rt_info[rt_key].as<std::shared_ptr<ov::op::v1::Split>>();
return split_node->output(static_cast<size_t>(split_index));
}
}
-34
View File
@@ -13,42 +13,8 @@ namespace ov {
namespace frontend {
namespace ggml {
std::string getCurrentTime();
void num_inputs_check(const NodeContext & context, size_t min_inputs, size_t max_inputs);
int non_cont_dim(std::vector<size_t> ne, std::vector<size_t> nb);
template <typename T> std::vector<int> argsort_descend(const std::vector<T> & v) {
std::vector<int> idx(v.size());
std::iota(idx.begin(), idx.end(), 0);
std::sort(idx.begin(), idx.end(), [&v](int i1, int i2) { return v[i1] > v[i2]; });
return idx;
}
template <typename T> std::vector<T> sorted_descend(std::vector<T> v) {
std::sort(v.begin(), v.end(), [](T a, T b) { return a > b; });
return v;
}
template <typename T> bool is_permuted(const std::vector<T> & strides) {
for (size_t i = 0; i < strides.size() - 1; ++i) {
if (strides[i] < strides[i + 1]) {
return true;
}
}
return false;
}
template <typename T> std::vector<T> permute(const std::vector<T> & x, const std::vector<int> & perm) {
std::vector<T> result;
result.reserve(perm.size());
for (int i : perm) {
result.push_back(x[i]);
}
return result;
}
std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::op::v3::ShapeOf> & shape,
const std::vector<int> & dims);
std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::Node> & node, const std::vector<int> & dims);
+97 -91
View File
@@ -151,6 +151,12 @@ std::optional<ov::Tensor> try_make_kv_sliced_tensor(const std::shared_ptr<GgmlOv
return std::nullopt;
}
if (ggml_tensor->data == nullptr) {
// unallocated input: let the caller build an owning zero tensor rather than slice a null
// pointer
return std::nullopt;
}
ov::Shape sliced_shape = full_shape;
sliced_shape[2] = static_cast<size_t>(n_kv);
@@ -192,10 +198,10 @@ std::optional<ov::Tensor> try_make_kv_4d_tensor(const std::shared_ptr<GgmlOvDeco
}
// Column count of a static KQ mask input; must match GgmlOvDecoder::get_graph_input_shape().
static size_t get_static_attention_size(std::shared_ptr<GgmlOvDecoder> ggml_decoder, const std::string & name) {
static size_t get_static_attention_size(const std::shared_ptr<GgmlOvDecoder> & ggml_decoder, const std::string & name) {
const bool is_swa = ggml_decoder->is_swa_mask(ggml_decoder->get_input_ggml_tensor(name));
if (ggml_decoder->m_is_prefill ? ggml_openvino_kv_slice_enabled() : ggml_openvino_npu_decode_bucket() > 0) {
const auto params = ggml_decoder->get_compute_params();
const auto & params = ggml_decoder->get_compute_params();
const int attention_size = is_swa ? params.attention_size_swa : params.attention_size;
if (attention_size > 0) {
return static_cast<size_t>(attention_size);
@@ -209,10 +215,7 @@ static size_t get_static_attention_size(std::shared_ptr<GgmlOvDecoder> ggml_deco
}
static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurrent) {
const char * manual_gqa_env = ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN");
const bool manual_gqa_enabled = manual_gqa_env != nullptr ?
ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0 :
ggml_openvino_is_gpu();
const bool manual_gqa_enabled = ggml_openvino_manual_gqa_enabled();
uint64_t extra_cfg = 15; // Recurrent caches are writable inputs without cache Results.
#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
@@ -561,6 +564,11 @@ ov::Tensor create_ov_output_tensor(const std::shared_ptr<GgmlOvDecoder> & ggml_d
return context.create_tensor(output_type, output_shape, resolved);
}
// A graph output can also have no backing storage. Give OV an owning tensor so the infer request
// has somewhere to write; nothing downstream reads it.
if (output_data == nullptr) {
return ov::Tensor(output_type, output_shape);
}
ov::Tensor output_tensor(output_type, output_shape, output_data);
return output_tensor;
}
@@ -713,6 +721,20 @@ ov::Tensor convert_ggml_input_to_ov(const std::shared_ptr<GgmlOvDecoder> & ggml_
return make_contiguous_split_input_tensor(ggml_tensor, input_shape);
}
// A graph input may legitimately be left unallocated (data == nullptr, no buffer): llama.cpp
// skips filling the attention mask when a graph only stores K/V without attending, which is what
// a speculative KV-injection pass does. Such an input is never read, but OpenVINO still requires
// a backing tensor for the Parameter and constructing an ov::Tensor over a null pointer asserts.
// Hand OV an owning zero-filled tensor; its contents cannot affect the result because no op
// consumes them.
if (input_data == nullptr) {
GGML_LOG_WARN("ggml-openvino: unallocated INPUT '%s' (ggml name '%s', type %s, ne=[%ld,%ld,%ld,%ld]) "
"-> zero tensor\n",
name.c_str(), ggml_tensor->name, ggml_type_name(ggml_tensor->type),
(long) ggml_tensor->ne[0], (long) ggml_tensor->ne[1], (long) ggml_tensor->ne[2],
(long) ggml_tensor->ne[3]);
return ov::Tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape);
}
auto input_tensor = ov::Tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape, input_data);
return input_tensor;
}
@@ -790,10 +812,8 @@ ov::Tensor get_ov_input_tensor_static_decode(const std::shared_ptr<GgmlOvDecoder
if (GgmlOvDecoder::is_output_idx(ggml_tensor, op)) {
ov::Shape input_shape = {1, 1, 1, 1};
ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape);
int32_t inp_out_id = *((int32_t *) ggml_tensor->data);
assert(ggml_tensor->ne[0] == 1);
assert(inp_out_id == 0);
*input_tensor.data<int32_t>() = inp_out_id;
// The only decode token is row 0. out_ids is empty when the graph has no output, so it is not read.
*input_tensor.data<int32_t>() = 0;
return input_tensor;
}
@@ -1256,13 +1276,15 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
cache_hit = it != r_ctx->decoder_cache.end();
if (cache_hit) {
entry = it->second;
r_ctx->touch_locked(key);
} else {
if (r_ctx->stateful || r_ctx->decoder_cache.size() >= 8) {
if (r_ctx->stateful) {
r_ctx->clear_caches_locked();
}
auto mutex = std::make_shared<std::mutex>();
entry = std::make_shared<decoder_runtime_ctx>(mutex);
r_ctx->decoder_cache[key] = entry;
r_ctx->admit_locked(key);
}
} else {
auto mutex = std::make_shared<std::mutex>();
@@ -1276,10 +1298,21 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
if (cache_hit) {
ggml_decoder = entry->ptr;
// The cache key is only (n_nodes, first/last node name), so it cannot see a change in
// WHICH tensors are graph outputs -- and the compiled model's Results are fixed when it is
// built. A consumer that starts requesting extra outputs later (speculative decoding marks
// the target's per-layer residuals only once the draft is initialised) would otherwise keep
// reusing a model that never produces them, and the host would read unwritten buffers as
// zeros. Recompile when the output set differs.
old_m_params = ggml_decoder->get_model_params();
if (!ggml_decoder->is_splited_model()) {
cache_hit = old_m_params.can_reuse_dynamically(m_params);
}
// Must come AFTER can_reuse_dynamically(), which ASSIGNS to cache_hit rather than
// and-ing into it and would otherwise silently undo this invalidation.
if (cache_hit && !ggml_decoder->has_same_graph_io(cgraph)) {
cache_hit = false;
}
}
std::vector<std::string> ov_input_names;
@@ -1654,8 +1687,6 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
infer_request = std::make_shared<ov::InferRequest>(compiled_model.create_infer_request());
shared_model = compiled_model;
entry->ptr = ggml_decoder;
} // end non-imported (compile) path
entry->ptr = ggml_decoder;
@@ -1725,7 +1756,20 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
id = binding.staging_id;
}
if (needs_bind(binding, input_tensor, id)) {
infer_request->set_input_tensor(i, input_tensor);
try {
infer_request->set_input_tensor(i, input_tensor);
} catch (const std::exception & e) {
if (ggml_openvino_getenv_int("GGML_OPENVINO_DIAG_GRAPH_IO")) {
auto port = infer_request->get_compiled_model().input(i);
GGML_LOG_WARN(
"ggml-openvino: DIAG set_input_tensor[%zu] '%s' threw for n_nodes=%d first=%s last=%s: %s\n"
" model_shape=%s bound_shape=%s\n",
i, param_name.c_str(), key.n_nodes, key.first_node_name.c_str(),
key.last_node_name.c_str(), e.what(), port.get_partial_shape().to_string().c_str(),
input_tensor.get_shape().to_string().c_str());
}
throw;
}
}
if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_INPUT")) {
@@ -1786,12 +1830,40 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
id = binding.staging_id;
}
if (needs_bind(binding, output_tensor, id)) {
infer_request->set_output_tensor(i, output_tensor);
try {
infer_request->set_output_tensor(i, output_tensor);
} catch (const std::exception & e) {
if (ggml_openvino_getenv_int("GGML_OPENVINO_DIAG_GRAPH_IO")) {
auto port = infer_request->get_compiled_model().output(i);
GGML_LOG_WARN(
"ggml-openvino: DIAG set_output_tensor[%zu] '%s' threw for n_nodes=%d first=%s last=%s: %s\n"
" model_shape=%s bound_shape=%s\n",
i, ov_output_names[i].c_str(), key.n_nodes, key.first_node_name.c_str(),
key.last_node_name.c_str(), e.what(), port.get_partial_shape().to_string().c_str(),
output_tensor.get_shape().to_string().c_str());
}
throw;
}
}
}
ov_raw_infer_start = ggml_time_us();
infer_request->infer();
try {
infer_request->infer();
} catch (const std::exception & e) {
if (ggml_openvino_getenv_int("GGML_OPENVINO_DIAG_GRAPH_IO")) {
auto cm = infer_request->get_compiled_model();
GGML_LOG_WARN("ggml-openvino: DIAG infer() threw for n_nodes=%d first=%s last=%s: %s\n", key.n_nodes,
key.first_node_name.c_str(), key.last_node_name.c_str(), e.what());
for (size_t i = 0; i < ov_input_names.size(); i++) {
auto port = cm.input(i);
GGML_LOG_WARN(" param[%zu] name=%s model_shape=%s bound_shape=%s\n", i,
ov_input_names[i].c_str(), port.get_partial_shape().to_string().c_str(),
infer_request->get_input_tensor(i).get_shape().to_string().c_str());
}
}
throw;
}
infer_end_time = ggml_time_us();
for (const auto & out : staged_outputs) {
std::memcpy(out.dst, out.src, out.bytes);
@@ -2190,11 +2262,12 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
cache_hit = it != r_ctx->decoder_cache.end();
if (cache_hit) {
entry = it->second;
r_ctx->touch_locked(key);
} else {
r_ctx->clear_caches_locked();
auto mutex = std::make_shared<std::mutex>();
entry = std::make_shared<decoder_runtime_ctx>(mutex);
r_ctx->decoder_cache[key] = entry;
r_ctx->admit_locked(key);
}
} else {
auto mutex = std::make_shared<std::mutex>();
@@ -2265,10 +2338,8 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
// Same fail-fast as the dynamic path: once the host weight pages have been dropped
// they read as zeros, so a recompile here would bake garbage into the new model.
if (ggml_openvino_weight_buffers_released()) {
GGML_ABORT(
"ggml-openvino: a new graph needs to be compiled but host weight buffers were already "
"released via GGML_OPENVINO_RELEASE_WEIGHTS. This mode requires "
"stable graph shapes; disable host weight release for dynamic workloads.");
GGML_LOG_ERROR("ggml-openvino: cannot compile a new graph after releasing host weights\n");
return GGML_STATUS_FAILED;
}
if (cache_enabled) {
std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
@@ -2318,6 +2389,10 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
}
} else {
auto decode_c_params = c_params;
// A decode step outputs its one token. llama-perplexity asks for many outputs in the prefill graph; the
// decode model of the pair keeps one (decode_signature below), or its last layer would gather more rows
// than the graph has tokens.
decode_c_params.output_len = 1;
if (ggml_openvino_kv_slice_enabled()) {
decode_c_params.attention_size = m_params.ctx_per_seq;
decode_c_params.attention_size_swa = m_params.ctx_per_seq_swa;
@@ -3322,7 +3397,7 @@ bool is_model_splitted(ggml_cgraph * cgraph) {
// the src is also not the model weights, we think the model is splitted.
// the src is also not in model leafs, we think the model is splitted.
if (src != nullptr && model_nodes.find(src) == model_nodes.end() &&
model_weights.find(std::string(src->name)) == model_weights.end() && !model_leafs.empty() == false &&
model_weights.find(std::string(src->name)) == model_weights.end() &&
model_leafs.find(src) == model_leafs.end()) {
if (GgmlOvDecoder::is_inp_tok(src, node)) {
return false;
@@ -3345,75 +3420,6 @@ bool is_naive(ggml_cgraph * cgraph) {
return count < naive_graph_size_threshold;
}
size_t checksum(const void * data, size_t size) {
const uint8_t * bytes = static_cast<const uint8_t *>(data);
size_t sum = 0;
for (size_t i = 0; i < size; ++i) {
sum += (uint8_t) i;
sum += bytes[i];
}
return sum;
}
bool save_ggml_tensor_data_to_txt(const ggml_tensor * tensor, const std::string & file_path) {
if (tensor == nullptr || tensor->data == nullptr) {
return false;
}
std::ofstream out(file_path);
if (!out.is_open()) {
return false;
}
const size_t n = ggml_nelements(tensor);
out << "name: " << tensor->name << ", type: " << ggml_type_name(tensor->type) << ", shape: [" << tensor->ne[0]
<< ", " << tensor->ne[1] << ", " << tensor->ne[2] << ", " << tensor->ne[3] << "]" << ", elements: " << n
<< ", data:" << '\n';
switch (tensor->type) {
case GGML_TYPE_F32: {
const auto * data = static_cast<const float *>(tensor->data);
for (size_t i = 0; i < n; ++i) {
out << data[i] << '\n';
}
break;
}
case GGML_TYPE_F16: {
const auto * data = static_cast<const ggml_fp16_t *>(tensor->data);
for (size_t i = 0; i < n; ++i) {
out << ggml_fp16_to_fp32(data[i]) << '\n';
}
break;
}
case GGML_TYPE_BF16: {
const auto * data = static_cast<const ggml_bf16_t *>(tensor->data);
for (size_t i = 0; i < n; ++i) {
out << ggml_bf16_to_fp32(data[i]) << '\n';
}
break;
}
case GGML_TYPE_I32: {
const auto * data = static_cast<const int32_t *>(tensor->data);
for (size_t i = 0; i < n; ++i) {
out << data[i] << '\n';
}
break;
}
case GGML_TYPE_I64: {
const auto * data = static_cast<const int64_t *>(tensor->data);
for (size_t i = 0; i < n; ++i) {
out << data[i] << '\n';
}
break;
}
default:
out << "unsupported tensor type for text dump" << '\n';
return false;
}
return true;
}
void print_input_tensor_info(const std::string & name, const ov::Tensor & input) {
// GPU inputs can be device (USM) tensors, whose data() throws; print a host copy of those.
const bool is_remote = input.is<ov::RemoteTensor>();
+41 -4
View File
@@ -6,6 +6,7 @@
#include <cstddef>
#include <cstdint>
#include <functional>
#include <list>
#include <map>
#include <memory>
#include <mutex>
@@ -158,6 +159,12 @@ struct ov_runtime_context {
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_output_names_cache;
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_input_names_cache_prefill;
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_output_names_cache_prefill;
// LRU order of decoder_cache's keys, oldest (least recently used) at the front. A pipeline
// that interleaves distinct graph shapes every call -- e.g. DFlash cycling target/draft/
// injection graphs every round -- needs a slot per shape open at once; a single-entry cache
// would evict and recompile all of them, every call, forever.
std::list<graph_key> lru_keys;
static constexpr size_t max_cached_graphs = 8;
size_t stateful_kv_size;
std::map<std::string, std::string> kv_state_input_name_map;
// compute-only copies of graphs that carry unselected ggml_build_forward_select() branches
@@ -169,6 +176,39 @@ struct ov_runtime_context {
ov_runtime_context() : device("CPU"), stateful(false), stateful_kv_size(0) {}
// Mark `key` as the most recently used entry. Call on every cache hit and after inserting a
// new entry, so eviction always picks the graph shape that has gone longest unused.
void touch_locked(const graph_key & key) {
lru_keys.remove(key);
lru_keys.push_back(key);
}
// Drop the least recently used graph shape's compiled model and its associated per-key
// caches. Leaves every other shape's compiled model intact.
void evict_lru_locked() {
if (lru_keys.empty()) {
return;
}
graph_key victim = lru_keys.front();
lru_keys.pop_front();
decoder_cache.erase(victim);
infer_request_cache.erase(victim);
infer_request_cache_prefill.erase(victim);
ov_input_names_cache.erase(victim);
ov_output_names_cache.erase(victim);
ov_input_names_cache_prefill.erase(victim);
ov_output_names_cache_prefill.erase(victim);
}
// Make room for one more graph shape if the cache is at capacity, then mark `key` as most
// recently used. Call right after inserting `key` into decoder_cache.
void admit_locked(const graph_key & key) {
while (decoder_cache.size() > max_cached_graphs) {
evict_lru_locked();
}
touch_locked(key);
}
void clear_caches_locked() {
decoder_cache.clear();
infer_request_cache.clear();
@@ -177,6 +217,7 @@ struct ov_runtime_context {
ov_output_names_cache.clear();
ov_input_names_cache_prefill.clear();
ov_output_names_cache_prefill.clear();
lru_keys.clear();
kv_state_input_name_map.clear();
stateful_kv_size = 0;
}
@@ -192,10 +233,6 @@ enum ggml_status ov_graph_compute(struct ggml_cgraph * cgraph, ggml_backend_t ba
// Releases the cached blobs this process imported (GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR).
void ov_clear_imported_blobs();
size_t checksum(const void * data, size_t size);
bool save_ggml_tensor_data_to_txt(const ggml_tensor * tensor, const std::string & file_path);
void print_input_tensor_info(const std::string & name, const ov::Tensor & tensor);
void print_output_tensor_info(const std::string & name, const ov::Tensor & tensor, const void * output_dst);
File diff suppressed because it is too large Load Diff
+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 {
+2 -2
View File
@@ -1013,8 +1013,8 @@ 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;
+42 -15
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);
}
}
}
@@ -10235,6 +10238,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,7 +10247,7 @@ 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:
@@ -11357,7 +11361,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 +11394,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 +11415,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 +11445,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 +11464,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 });
}
}
@@ -11692,9 +11719,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 +11738,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 +16802,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;
@@ -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];
}
@@ -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 {

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