Compare commits

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

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-24 09:25:04 +01:00
Aman Gupta 4af4bb6d8a rpc : reuse one context for request tensors on the server (#32896) 2026-11-24 09:43:50 +02:00
Georgi GerganovandIsNot-10 b12f22d2f2 ggml : use a range-reduced log1p for softplus (#32655)
* metal : use a range-reduced log1p for softplus

Use the atanh series for x in [-0.5, 1] and precise::log(1 + x) otherwise.
This avoids the cancellation in log(1 + exp(x)) for negative inputs and does
not rely on fast-math folding of (1 + e) - 1.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* tests : add a softplus test for negative inputs

Use inputs in [-16.6, -16.0], where log(1 + exp(x)) has up to ~2x
relative error. This catches both the old form and the fast-math-folded
compensated form.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* ggml : use log1pf in ggml_compute_softplus_f32

Use log1pf(expf(input)) so the host helper keeps the true value for
x < -16.64.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
Co-authored-by: IsNot-10 <209144869@qq.com>

* vulkan : use a range-reduced log1p for softplus

Use the atanh series for x in [-0.5, 1] and log(1 + x) otherwise.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
Co-authored-by: IsNot-10 <209144869@qq.com>

* opencl : use a range-reduced log1p for softplus

Use the atanh series for x in [-0.5, 1] and log(1 + x) otherwise.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
Co-authored-by: IsNot-10 <209144869@qq.com>

* vulkan : move log1p to utils.glsl

Move the range-reduced log1p out of unary.comp into utils.glsl so that
other ops such as topk_moe and ssm_scan can include it.  The body is
unchanged; only the call site in op_softplus is renamed.

Co-authored-by: IsNot-10 <209144869@qq.com>
Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB)

---------

Co-authored-by: IsNot-10 <209144869@qq.com>
2026-11-24 09:30:43 +02:00
losewayy d141011c25 vulkan: support state size 96 in ssm_scan (#32162)
* vulkan: support state size 96 in ssm_scan

Assisted-by: Claude Code

* vulkan: specialize ssm_scan state size

Assisted-by: Codex

* vulkan: clarify ssm_scan constant names

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

Co-authored-by: Hongqiang Wang <wangh@qti.qualcomm.com>
2026-11-23 17:12:33 -08:00
Max Krasnyansky c74c71a6f7 fix editor config in master (#32914) 2026-11-23 15:47:20 -08:00
Aldehir Rojas 38b9cad71d quantize : make local const static for MSVC (#32902) 2026-11-23 17:41:33 -06:00
d35dc4d9e6 GDN: use replay instead of rollback (#31669)
* GDN: use replay instead of rollback [WIP]

* memory : move rs_max with the sequence when find_slot swaps cells

find_slot swapped pos/src/rs_pend/seq_id of the cell it moves out of the
way, but not rs_max, so that sequence inherited the rollback depth of the
cell's previous owner. A smaller value made seq_rm refuse the rollback
(#31656), a larger one made snapshot mode restore the previous owner's
snapshots.

With rs_replay the pending columns are copied along with the state, so
rs_max follows the sequence. Without it only the final state is copied and
the snapshots stay behind, so the moved sequence gets rs_max 0.

* delta_net: drop the graph replay fallback

The graph fallback ran the replay as two gdn ops and copied the
committed state from the replay gdn when keep, from the main gdn
otherwise. Backends whose graph_optimize reorders nodes (Metal,
Vulkan) then give keep and non keep ubatches a different node order
for the same node count, and the scheduler reallocates on every
switch (abort under GGML_SCHED_DEBUG_REALLOC).

The replay now always runs in the gdn op. A device without the replay
in its gdn op leaves the op to the CPU through the scheduler, as for
any unsupported op. This removes LLAMA_RS_REPLAY=2, the replay probe,
rs_replay_fused and the rep_mask input.

* metal: replay the pending gated delta net tokens in the kernel

The gated delta net kernel replays the pending tokens of each seq
before the new ones, with the same state update as the main loop and
no attention output. With keep, it writes the state after the replay
and skips the final state.

The replay is a function constant of the pipeline, keep is a kernel
argument as on CUDA. The pending buffers fall back to src0 when the
op has no replay.

* vulkan: replay the pending gated delta net tokens in the shader

The gated delta net shader replays the pending tokens of each seq
before the new ones, with the same state update as the main loop and
no attention output. With keep, it writes the state after the replay
and skips the final state.

The replay is a specialization constant of the pipeline, keep is a
push constant as on CUDA. The pending buffers bind q when the op has
no replay. The result checker clones the op with its replay sources.

* webgpu: replay the pending gated delta net tokens in the shader

The gated delta net shader replays the pending tokens of each seq
before the new ones, with the same state update as the main loop and
no attention output. With keep, it writes the state after the replay
and skips the final state.

The replay is a define of the pipeline, keep is a param as on CUDA.
The replay count goes through workgroupUniformLoad, so that the loop
around the workgroup barriers stays uniform.

* delta_net: share the replay conv window views across layers

Each replay layer took its own view of the rs_rep_cols input. The
scheduler copies every view of a host input as a separate split input,
so a verify graph uploaded one copy per layer. The views of the delta
net and the PLE conv windows are now built once per graph, like the
s_copy views.

* vulkan: clamp the gated delta net replay count to n_pend

The replay count comes from a buffer, so the shader bounds it to the
pending rows before looping over them. The pipeline array comment now
names the replay index next to the other ones.

Address review from 0cc4m.

* hex-gdn: add support for replay

Enable replay in HVX path
Enable replay in HMX path

* gdn: fix rebase conflicts (missing cparams, etc)

* llama : drop the fused GDN probes brought back by the rebase

il parameter of build_delta_net. The rebase kept them (unused, auto_fgdn
was always false), so restore master's version of that code.

* delta_net : replay for the KDA models and Clover-MoE

Clover-MoE has the Qwen 3.5 layout and only needs the arch gate.

Kimi K3, Kimi K3.1, GLM5-Next and BailingMoE3 keep the q, k and v conv
windows one after the other in a row. With replay the row holds three
channels-first histories [d_inner, window + pending]:
build_conv_state_replay takes the gathered rows of the layer and the
block index. The pending gate rows hold S_v gates per head (KDA).

GLM5-Next gets the -sm tensor split rules for the replay rows.

Tested with test-llama-archs models: logits match snapshots bit for bit
with random rollbacks (CUDA, Vulkan, CPU), no graph re-plans, and
test-llama-context passes in both modes.

* cuda : same KDA update in the gated delta net main and replay loops

The KDA main loop called expf(g) twice inline, the replay loop reads
g from registers. On sm_89 nvcc fused the two loops differently, so a
replayed state was a few ulp off the state of the first pass. Compute
g into registers in the main loop too: replay matches snapshots bit for
bit on sm_89, and the sm_120 output does not change.

* opencl: support replay in GDN

* llama : replay inputs for the hybrid iswa rel memory input

build_inp_mem_hybrid_iswa_rel came in with the rebase: pass hparams and
cparams to build_rs_inp_impl and fill the replay inputs in set_input,
like the other hybrid inputs.

* webgpu: keep the gated delta net replay within the storage buffer limit

* delta_net : add ggml_gated_delta_net_ext, replay is the only rollback

ggml_gated_delta_net_ext takes the optional replay inputs and always
outputs one state. ggml_gated_delta_net(..., K) is back to its master
signature and is deprecated; both build the same op, so the backends
are unchanged.

The delta-net models (qwen35, qwen35moe, qwen4exp, clover-moe and the
KDA models) now always replay the kept tokens when n_rs_seq > 0. The
LLAMA_RS_REPLAY env flag and the snapshot branch of
build_recurrent_attn are removed.

test-backend-ops drops the K > 1 snapshot cases and the K parameter of
the gated delta net tests. The cache fusion test copies the single
state.

* ggml-cpu : spacemit: leave the gdn replay to the generic kernel

The RVV gated delta net kernel does not read the replay inputs. Return
false when op param 1 (n_pend) is set, so that the generic kernel runs
the op.

* vulkan : fill views at any offset

ggml_vk_fill bound dst without allowing a misaligned offset, so a fill
of a view whose offset is not a multiple of
minStorageBufferOffsetAlignment aborted. The recurrent state zeroing in
build_rs hits this with the wider replay conv rows on devices with a
64-byte alignment.

Bind dst from the aligned offset below it and pass the element offset
in KY. test_fill gets an offset to fill a view in place.

---------

Co-authored-by: Pascal <admin@serveurperso.com>
Co-authored-by: Max Krasnyansky <maxk@qti.qualcomm.com>
Co-authored-by: Li He <lih@qti.qualcomm.com>
2026-11-23 15:06:02 -08:00
Evan Huus c212d25ad3 server : preserve a prompt-cache entry until restores succeed (#32828)
Assisted-by: Codex
2026-11-23 21:50:29 +01:00
Hongqiang WangandLi He fd24ee26ad opencl: fetch the Adreno binary kernel library at configure time for Windows on Snapdragon (#31759)
* opencl: fetch the Adreno binary kernel library at configure time

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

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

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

The library is built for Windows on ARM64 only.

* opencl: add download timeout and better handle output dir

Assisted-by: Codex

* opencl: add .txt to license file

Assisted-by: Codex

---------

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

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

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

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

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

* metal : skip the small-batch path for NVFP4

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

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (2x DGX Spark (RDMA, TP=2))
2026-11-23 21:02:30 +02:00
Georgi Gerganov ab789a246c metal : batch concat rows and copy them in vector chunks (#32824)
* metal : batch concat rows and copy them in vector chunks

The concat kernel copied one element per thread, so wide rows with many rows ran at a
fraction of the memory bandwidth. Batch several rows per threadgroup and copy the
contiguous dim-0 elements in 4-element chunks when the row is contiguous.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* test : cover concat vector and misaligned row paths

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)

* metal : hoist the concat src1 row offset into scalars

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)

* metal : peel to align the concat vector copy

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)

* metal : vectorize concat rows along any dimension

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)

* metal : specialize concat with function constants

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)

* metal : drop the concat row-batch dispatch

Batching several rows per threadgroup reduces the number of threads by
the batch factor. On machines with a large GPU this leaves too few
requests in flight and the copy becomes latency bound:

  M5 Ultra (36 CPU)   f16 [1024,8,256,1] d=0   8.1 us -> 17.2 us
                      f32 [4096,8,256,1] d=0  35.4 us -> 118.5 us
                      f16 [4096,8,256,1] d=2  50.9 us -> 102.0 us

An interleaved sweep of the (nth, nrptg) dispatch over the concat perf
cases on an M2 Ultra and an M5 Ultra shows that the base dispatch is
best or tied for every shape once the rows are vectorized, and that the
gains of the previous commit come from the vector copy alone:

  M2 Ultra  f16 [1024,8,256,1] d=0  32.4 us -> 17.0 us
  M5 Ultra  f16 [1024,8,256,1] d=0  13.3 us ->  8.1 us

Keep the vector copy and the function-constant specialization, and
return to the original dispatch.

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)

* metal : revert the concat function constants

Specializing the concat kernel on the concat dimension and on whether a
row is split across threadgroups with function constants makes the
strided scalar path slower. Interleaved over the concat perf cases on an
M5 Ultra, the specialized kernel is not faster than the plain one, and
it costs up to 18% on shapes that are already at the memory bandwidth
limit:

  f32 [2050,8,256,1] b=255 d=0  21.0 us -> 25.1 us
  f32 [2050,8,256,1] b=256 d=2  31.1 us -> 36.7 us
  f16 [4096,8,256,1] b=256 d=2  31.2 us -> 36.7 us

Revert the specialization and keep copying rows with the runtime
arguments. The concat change is now limited to the kernel itself.

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)
2026-11-23 21:01:41 +02:00
Piotr Wilkin (ilintar) 239242322d ggml: compact bias on the existing FLASH_ATTN_EXT (#32740)
* compact bias on the existing FLASH_ATTN_EXT for CUDA, ROCm and Vulkan
* fixup! compact bias on the existing FLASH_ATTN_EXT for CUDA, ROCm and Vulkan
* remove the Vulkan support from this PR
* move the CUDA/HIP and Inkling 2 graph changes out of this PR
* CPU reference implementation of the indexed bias
* move the indexed bias test to test-backend-ops, add the bias in F32 on CPU
* incorporate review remarks
2026-11-23 18:17:11 +01:00
101 changed files with 3238 additions and 660 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:
+15 -8
View File
@@ -83,22 +83,29 @@ Since common quantizations are supported now, it is recommanded to download GGUF
A prebuilt binary kernel library has been introduced for Adreno GPUs.
It currently targets X2 GPUs (X2-90, X2-85 and X2-45) found in Snapdragon X2 SoC.
The library currently contains kernels for MUL_MAT_ID with Q4_0, Q4_1, Q4_K, MXFP4.
The library must be manually downloaded from https://softwarecenter.qualcomm.com/catalog/item/Adreno_Kernel_Library_GGML.
The library is published at https://softwarecenter.qualcomm.com/catalog/item/Adreno_Kernel_Library_GGML.
Its use is subject to the license in the `license.txt` file shipped with it.
To allow using the kernel library, add `-DGGML_OPENCL_USE_ADRENO_BIN_KERNELS=ON` when configuring with CMake.
Then, extract `adreno-opencl-kernels.dll` from the zip file downloaded from the above URL and put it alongside the executables.
The library is enabled by default (`GGML_OPENCL_USE_ADRENO_BIN_KERNELS=ON`).
On Windows on ARM64, CMake downloads the library version pinned in `ggml/src/ggml-opencl/CMakeLists.txt` during configuration (`GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=ON`).
The download is verified against a SHA256 hash, and the build copies `adreno-opencl-kernels.dll` and `LICENSE-adreno-opencl-kernels.txt` alongside the executables.
If the download fails, configuration continues with a warning.
To skip the download, add `-DGGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=OFF`, then extract `adreno-opencl-kernels.dll` from the zip file downloaded from the above URL and put it alongside the executables yourself.
If kernels compatible with the current GPU are found in the library, they will be loaded and used.
If the library is missing, the builtin kernels are used.
Add `-DGGML_OPENCL_USE_ADRENO_BIN_KERNELS=OFF` to disable the library entirely.
## CMake Options
The OpenCL backend has the following CMake options that control the behavior of the backend.
| CMake options | Default value | Description |
|:------------------------------------:|:--------------:|:------------------------------------------|
| `GGML_OPENCL_EMBED_KERNELS` | `ON` | Embed OpenCL kernels into the executable. |
| `GGML_OPENCL_USE_ADRENO_KERNELS` | `ON` | Use kernels optimized for Adreno. |
| `GGML_OPENCL_USE_ADRENO_BIN_KERNELS` | `OFF` | Allow using binary kernel lib for Adreno. |
| CMake options | Default value | Description |
|:--------------------------------------:|:--------------:|:--------------------------------------------------------|
| `GGML_OPENCL_EMBED_KERNELS` | `ON` | Embed OpenCL kernels into the executable. |
| `GGML_OPENCL_USE_ADRENO_KERNELS` | `ON` | Use kernels optimized for Adreno. |
| `GGML_OPENCL_USE_ADRENO_BIN_KERNELS` | `ON` | Allow using binary kernel lib for Adreno. |
| `GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH` | `ON` | Download the binary kernel lib for Adreno (Windows ARM64). |
## Decomposed Flash Attention
+2
View File
@@ -269,6 +269,8 @@ option(GGML_OPENCL "ggml: use OpenCL"
option(GGML_OPENCL_PROFILING "ggml: use OpenCL profiling (increases overhead)" OFF)
option(GGML_OPENCL_EMBED_KERNELS "ggml: embed kernels" ON)
option(GGML_OPENCL_USE_ADRENO_KERNELS "ggml: use optimized kernels for Adreno" ON)
option(GGML_OPENCL_USE_ADRENO_BIN_KERNELS "ggml: load the Adreno binary kernel library" ON)
option(GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH "ggml: fetch the Adreno binary kernel library" ON)
set (GGML_OPENCL_TARGET_VERSION "300" CACHE STRING
"ggml: OpenCL API version to target")
+39 -6
View File
@@ -2292,6 +2292,15 @@ extern "C" {
struct ggml_tensor * a,
struct ggml_tensor * sinks);
GGML_API bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a);
// Add table[indices[key, query], head, query] to the mask, in F32.
// Queries from all streams are flattened in stream order. Indices must be in [0, table->ne[0]).
GGML_API void ggml_flash_attn_ext_add_indexed_bias(
struct ggml_tensor * a,
struct ggml_tensor * table,
struct ggml_tensor * indices);
// TODO: needs to be adapted to ggml_flash_attn_ext
GGML_API struct ggml_tensor * ggml_flash_attn_back(
struct ggml_context * ctx,
@@ -2426,11 +2435,17 @@ extern "C" {
// beta : [1, H_v, n_tokens, n_seqs]
// state : [S_v, S_v, H_v, n_seqs] -- initial recurrent state s0
//
// the output packs the attention scores [S_v, H_v, n_tokens, n_seqs] followed by K state
// snapshots, most-recent first (slot 0 = final state, slot s = state s tokens back). K == 1
// keeps only the final state; when n_tokens < K only slots 0..n_tokens-1 are written.
// when n_tokens > K only slot 0 is guaranteed; backends may leave slots 1..K-1 unwritten.
GGML_API struct ggml_tensor * ggml_gated_delta_net(
// the output packs the attention scores [S_v, H_v, n_tokens, n_seqs] followed by the final state [S_v, S_v, H_v, n_seqs]
//
// replay (optional, set all of pend_k, pend_v, pend_gb and n_rep, or none): first runs the pending tokens of the
// previous ubatch, so that a rollback only drops pending tokens instead of restoring a snapshot
// pend_k : [S_k, H_k, n_pend, n_seqs]
// pend_v : [S_v, H_v, n_pend, n_seqs]
// pend_gb : [g0, H_v, 2*n_pend, n_seqs], the gates of the n_pend tokens, then their betas (in element 0)
// n_rep : I32 [n_seqs], number of pending tokens to replay (<= n_pend)
// the state output is the state after the replay if keep is true, else the final state.
// op param 1 is n_pend (0 without replay): backends that do not implement the replay reject the op when it is set
GGML_API struct ggml_tensor * ggml_gated_delta_net_ext(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * k,
@@ -2438,7 +2453,25 @@ extern "C" {
struct ggml_tensor * g,
struct ggml_tensor * beta,
struct ggml_tensor * state,
int64_t K);
struct ggml_tensor * pend_k,
struct ggml_tensor * pend_v,
struct ggml_tensor * pend_gb,
struct ggml_tensor * n_rep,
bool keep);
// the output packs the attention scores followed by K state snapshots, most-recent first (slot 0 = final state,
// slot s = state s tokens back). when n_tokens < K only slots 0..n_tokens-1 are written. when n_tokens > K only
// slot 0 is guaranteed; backends may leave slots 1..K-1 unwritten.
GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_gated_delta_net(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * k,
struct ggml_tensor * v,
struct ggml_tensor * g,
struct ggml_tensor * beta,
struct ggml_tensor * state,
int64_t K),
"use ggml_gated_delta_net_ext instead");
// DSA lightning indexer
//
+15
View File
@@ -152,6 +152,10 @@ static ggml_backend_buffer_type_t ggml_backend_meta_device_get_buffer_type(ggml_
static ggml_backend_buffer_type_t ggml_backend_meta_device_get_host_buffer_type(ggml_backend_dev_t dev);
static bool ggml_backend_meta_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
GGML_ASSERT(ggml_backend_dev_is_meta(dev));
const ggml_backend_meta_device_context * meta_dev_ctx = (const ggml_backend_meta_device_context *) dev->context;
return std::all_of(meta_dev_ctx->simple_devs.begin(), meta_dev_ctx->simple_devs.end(),
@@ -871,11 +875,22 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(
};
auto handle_gated_delta_net = [&](const std::vector<ggml_backend_meta_split_state> & src_ss) -> ggml_backend_meta_split_state {
// replay (src 6..9): the pending k, v and gates/betas are split by heads like k, v and g, n_rep is per seq
const bool replay = tensor->src[6] != nullptr;
if (src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED &&
src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[3].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED &&
src_ss[4].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[5].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED) {
for (int i = 6; replay && i < 10; i++) {
GGML_ASSERT(src_ss[i].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED);
}
return src_ss[0];
}
if (replay) {
GGML_ASSERT(src_ss[6].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[7].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[8].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[9].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED);
}
GGML_ASSERT(src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_1);
+2 -2
View File
@@ -2679,8 +2679,8 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten
return true;
case GGML_OP_FLASH_ATTN_EXT:
{
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
if (op->src[5] != nullptr) {
// K/V row lists and indexed bias are not supported
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
#ifdef ASCEND_310P
+4 -3
View File
@@ -3068,9 +3068,10 @@ struct ggml_cplan ggml_graph_plan(
} break;
case GGML_OP_GATED_DELTA_NET:
{
const int64_t S_v = node->src[2]->ne[0];
const int64_t K = ggml_get_op_params_i32(node, 0);
const int64_t per_thread = S_v + (K > 1 ? S_v * S_v : 0);
const int64_t S_v = node->src[2]->ne[0];
const int64_t K = ggml_get_op_params_i32(node, 0);
const bool keep = node->src[6] && ggml_get_op_params_i32(node, 2) != 0;
const int64_t per_thread = S_v + (K > 1 || keep ? S_v * S_v : 0);
cur = per_thread * sizeof(float) * n_tasks;
} break;
case GGML_OP_COUNT:
+4
View File
@@ -422,6 +422,10 @@ static ggml_backend_buffer_t ggml_backend_cpu_device_buffer_from_host_ptr(ggml_b
}
static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) {
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
const struct ggml_tensor * src0 = op->src[0];
const struct ggml_tensor * src1 = op->src[1];
+79 -5
View File
@@ -8981,6 +8981,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
const ggml_tensor * mask = dst->src[3];
const ggml_tensor * sinks = dst->src[4];
const ggml_tensor * kv_rows = dst->src[5];
const ggml_tensor * bias_table = dst->src[6];
const ggml_tensor * bias_indices = dst->src[7];
GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
@@ -9022,6 +9024,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
const int64_t rv2 = neq2/nev2;
const int64_t rv3 = neq3/nev3;
const int64_t n_bins = bias_table ? bias_table->ne[0] : 0;
// parallelize by q rows using ggml_vec_dot_f32
float scale = 1.0f;
@@ -9085,12 +9089,21 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
const int32_t * rows = kv_rows ? (const int32_t *) ((const char *) kv_rows->data + iq3*kv_rows->nb[1]) : nullptr;
// bias rows of this query and head, queries of all streams are flattened
const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr;
const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1)*bias_indices->nb[1]) : nullptr;
// online softmax / attention
// loop over n_kv and n_head_kv
// ref: https://arxiv.org/pdf/2112.05682.pdf
for (int64_t ic = ic_start; ic < ic_end; ++ic) {
const float mv = mp ? slope*GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f;
float mv = mp ? GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f;
if (bias) {
GGML_ASSERT(bins[ic] >= 0 && bins[ic] < n_bins);
mv += bias[bins[ic]];
}
mv *= slope;
if (mv == -INFINITY) {
continue;
}
@@ -9268,6 +9281,10 @@ static void ggml_compute_forward_flash_attn_ext_tiled(
const ggml_tensor * kv_rows = dst->src[5];
const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : nek1;
const ggml_tensor * bias_table = dst->src[6];
const ggml_tensor * bias_indices = dst->src[7];
const int64_t n_bins = bias_table ? bias_table->ne[0] : 0;
int ir = ir0;
while (ir < ir1) {
// q indices for the start of this tile
@@ -9346,8 +9363,15 @@ static void ggml_compute_forward_flash_attn_ext_tiled(
bool can_skip = true;
for (int tq = 0; tq < tile_rows; tq++) {
const ggml_fp16_t * mp_row = (const ggml_fp16_t *)((const char *) mask->data + (iq1 + tq)*mask->nb[1] + (iq2%mask->ne[2])*mask->nb[2] + (iq3%mask->ne[3])*mask->nb[3]);
const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1 + tq)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr;
const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1 + tq)*bias_indices->nb[1]) : nullptr;
for (int tk = 0; tk < kv_tile; tk++) {
mask32[tq * KV_TILE_SZ + tk] = slope * GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]);
float m = GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]);
if (bias) {
GGML_ASSERT(bins[ic + tk] >= 0 && bins[ic + tk] < n_bins);
m += bias[bins[ic + tk]];
}
mask32[tq * KV_TILE_SZ + tk] = slope * m;
if (mask32[tq * KV_TILE_SZ + tk] != -INFINITY) {
can_skip = false;
}
@@ -11289,11 +11313,19 @@ static void ggml_compute_forward_gated_delta_net_one_chunk(
// per-seq stride in floats (seq s starts at state + s * seq_stride)
const int64_t state_seq_stride = src_state->nb[3] / sizeof(float);
const int64_t per_thread = S_v + (K > 1 ? S_v * S_v : 0);
// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
const ggml_tensor * src_pk = dst->src[6];
const ggml_tensor * src_pv = dst->src[7];
const ggml_tensor * src_pgb = dst->src[8];
const ggml_tensor * src_n_rep = dst->src[9];
const int64_t n_pend = src_pk ? ggml_get_op_params_i32(dst, 1) : 0;
const bool keep = src_pk && ggml_get_op_params_i32(dst, 2) != 0;
const int64_t per_thread = S_v + (K > 1 || keep ? S_v * S_v : 0);
const int ith = params->ith;
float * delta = (float *)params->wdata + ith * per_thread + CACHE_LINE_SIZE_F32;
float * state_work = K > 1 ? (delta + S_v) : nullptr;
float * state_work = K > 1 || keep ? (delta + S_v) : nullptr;
// output layout: [attn_scores | new_states]
// attn_scores: S_v * H * n_tokens * n_seqs floats
@@ -11327,7 +11359,7 @@ static void ggml_compute_forward_gated_delta_net_one_chunk(
// For K=1, write directly to the single output slot to avoid an extra memcpy at the end.
// For K>1, work in scratch and copy out per-token when the slot is in range.
float * s_out = (K > 1)
float * s_out = (K > 1 || keep)
? state_work
: state_out_base + (iv3 * H + iv1) * S_v * S_v;
@@ -11336,6 +11368,48 @@ static void ggml_compute_forward_gated_delta_net_one_chunk(
const float * s_in = state_in_base + iv3 * state_seq_stride + iv1 * S_v * S_v;
memcpy(s_out, s_in, S_v * S_v * sizeof(float));
if (src_pk) {
const int64_t n_r = ((const int32_t *) src_n_rep->data)[iv3];
GGML_ASSERT(n_r >= 0 && n_r <= n_pend);
const char * pk = (const char *) src_pk->data + iv3*src_pk->nb[3] + ik1*src_pk->nb[1];
const char * pv = (const char *) src_pv->data + iv3*src_pv->nb[3] + iv1*src_pv->nb[1];
const char * pgb = (const char *) src_pgb->data + iv3*src_pgb->nb[3] + iv1*src_pgb->nb[1];
for (int64_t t = 0; t < n_r; t++) {
const float * k_d = (const float *) (pk + t*src_pk->nb[2]);
const float * v_d = (const float *) (pv + t*src_pv->nb[2]);
const float * g_d = (const float *) (pgb + t*src_pgb->nb[2]);
const float beta_val = *(const float *) (pgb + (n_pend + t)*src_pgb->nb[2]);
if (kda) {
for (int64_t i = 0; i < S_v; ++i) {
delta[i] = expf(g_d[i]);
}
for (int64_t j = 0; j < S_v; ++j) {
ggml_vec_mul_f32(S_v, &s_out[j * S_v], &s_out[j * S_v], delta);
}
} else {
ggml_vec_scale_f32(S_v * S_v, s_out, expf(g_d[0]));
}
for (int64_t j = 0; j < S_v; ++j) {
float sum = 0.0f;
ggml_vec_dot_f32(S_v, &sum, 0, &s_out[j * S_v], 0, k_d, 0, 1);
delta[j] = (v_d[j] - sum) * beta_val;
}
for (int64_t j = 0; j < S_v; ++j) {
ggml_vec_mad_f32(S_v, &s_out[j * S_v], k_d, delta[j]);
}
}
// the committed state, the new tokens go on in the scratch
if (keep) {
memcpy(state_out_base + (iv3 * H + iv1) * S_v * S_v, s_out, S_v * S_v * sizeof(float));
}
}
// attn output pointer for first token of this (head, seq)
float * attn_data = attn_out_base + (iv3 * n_tokens * H + iv1) * S_v;
+2 -1
View File
@@ -1156,7 +1156,8 @@ class tensor_traits_common : public tensor_traits_base {
}
return true;
case GGML_OP_GATED_DELTA_NET:
if (params->use_ref) {
// the generic kernel does the replay of pending tokens (op param 1)
if (params->use_ref || ggml_get_op_params_i32(op, 1) != 0) {
return false;
}
switch (op->src[0]->type) {
+4
View File
@@ -582,6 +582,10 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
return BEST_FATTN_KERNEL_NONE;
#endif// FLASH_ATTN_AVAILABLE
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
return BEST_FATTN_KERNEL_NONE;
}
const ggml_tensor * KQV = dst;
const ggml_tensor * Q = dst->src[0];
const ggml_tensor * K = dst->src[1];
@@ -485,6 +485,10 @@ static gdn_path select_gdn_mma_path(int device, const ggml_cuda_gdn_mma_args & a
} // namespace
using namespace ggml_cuda_gated_delta_net_mma;
bool ggml_cuda_gdn_mma_supported(int device, const ggml_cuda_gdn_mma_args & a) {
return a.state_out && select_gdn_mma_path(device, a) != gdn_path::ar;
}
bool ggml_cuda_gdn_mma_launch(int device, const ggml_cuda_gdn_mma_args & a, cudaStream_t stream) {
if (!a.state_out) {
return false;
@@ -32,4 +32,6 @@ struct ggml_cuda_gdn_mma_args {
bool eligible;
};
// true when ggml_cuda_gdn_mma_launch would run the chunked kernel for these args
bool ggml_cuda_gdn_mma_supported(int device, const ggml_cuda_gdn_mma_args & args);
bool ggml_cuda_gdn_mma_launch(int device, const ggml_cuda_gdn_mma_args & args, cudaStream_t stream);
+175 -29
View File
@@ -6,7 +6,25 @@
constexpr int gdn_cols_per_warp = 4;
template <int S_v, bool KDA, bool keep_rs_t, int cols_per_warp = gdn_cols_per_warp>
// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
struct gdn_replay_args {
const float * pk; // [S_v, H_k, n_pend, n_seqs]
const float * pv; // [S_v, H, n_pend, n_seqs]
const float * pgb; // [g0, H, 2*n_pend, n_seqs], gates then betas
const int32_t * n_rep; // [n_seqs]
int64_t sk1, sk2, sk3; // head, token and seq strides in floats
int64_t sv1, sv2, sv3;
int64_t sg1, sg2, sg3;
int n_pend;
bool keep; // write the state after the replay, not the final one
// optional: store the k, v, g, beta inputs of the new tokens (fused cpys)
float * st[4];
int64_t st2[4]; // token stride in floats
int64_t st3[4]; // seq stride in floats
};
template <int S_v, bool KDA, bool keep_rs_t, bool replay = false, int cols_per_warp = gdn_cols_per_warp>
__global__ void __launch_bounds__((ggml_cuda_get_physical_warp_size() < S_v ? ggml_cuda_get_physical_warp_size() : S_v) * 4, 2)
gated_delta_net_cuda(const float * q,
const float * k,
@@ -32,7 +50,8 @@ gated_delta_net_cuda(const float * q,
const uint3 rq3_magic,
float scale,
int64_t state_slot_stride,
int K) {
int K,
const gdn_replay_args rep) {
const uint32_t h_idx = blockIdx.x;
const uint32_t sequence = blockIdx.y;
@@ -72,6 +91,53 @@ gated_delta_net_cuda(const float * q,
s_shard[r] = curr_state[i];
}
if constexpr (replay) {
const int n_r = rep.n_rep[sequence];
const float * pk = rep.pk + sequence * rep.sk3 + iq1 * rep.sk1;
const float * pv = rep.pv + sequence * rep.sv3 + h_idx * rep.sv1;
const float * pgb = rep.pgb + sequence * rep.sg3 + h_idx * rep.sg1;
for (int t = 0; t < n_r; t++) {
const float * k_t = pk + t * rep.sk2;
const float v_col = pv[t * rep.sv2 + col];
const float * g_t = pgb + t * rep.sg2;
const float beta_val = pgb[(rep.n_pend + t) * rep.sg2];
float k_reg[rows_per_lane];
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
k_reg[r] = k_t[r * lanes_per_col + lane_in_col];
}
float g_reg[rows_per_lane];
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
g_reg[r] = expf(KDA ? g_t[r * lanes_per_col + lane_in_col] : g_t[0]);
}
// same update as below, without the attention output
float kv_shard = 0.0f;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
kv_shard += (KDA ? g_reg[r] : 1.0f) * s_shard[r] * k_reg[r];
}
const float kv_col = warp_reduce_sum<lanes_per_col>(kv_shard);
const float delta_col = (v_col - (KDA ? 1.0f : g_reg[0]) * kv_col) * beta_val;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
s_shard[r] = g_reg[r] * s_shard[r] + k_reg[r] * delta_col;
}
}
if (rep.keep) {
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
state[col * S_v + r * lanes_per_col + lane_in_col] = s_shard[r];
}
}
}
for (int t = 0; t < n_tokens; t++) {
const float * q_t = q + iq3 * sq3 + t * sq2 + iq1 * sq1;
const float * k_t = k + iq3 * sq3 + t * sq2 + iq1 * sq1;
@@ -93,6 +159,27 @@ gated_delta_net_cuda(const float * q,
q_reg[r] = q_t[i];
}
if constexpr (replay && !KDA) {
if (rep.st[0] != nullptr) {
// keep the inputs of this token pending: one CTA per k head writes k, each column its v
const bool first = blockIdx.z == 0 && threadIdx.y == 0 && col_in_warp == 0;
if (first && h_idx < neqk1_magic.z) {
float * dk = rep.st[0] + sequence * rep.st3[0] + t * rep.st2[0] + h_idx * S_v;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
dk[r * lanes_per_col + lane_in_col] = k_reg[r];
}
}
if (lane_in_col == 0) {
rep.st[1][sequence * rep.st3[1] + t * rep.st2[1] + h_idx * S_v + col] = v_t[col];
}
if (first && lane_in_col == 0) {
rep.st[2][sequence * rep.st3[2] + t * rep.st2[2] + h_idx] = *g_t;
rep.st[3][sequence * rep.st3[3] + t * rep.st2[3] + h_idx] = beta_val;
}
}
}
if constexpr (!KDA) {
const float g_val = expf(*g_t);
@@ -122,12 +209,18 @@ gated_delta_net_cuda(const float * q,
attn_data[col] = attn_col * scale;
}
} else {
// same arithmetic as the replay loop, so that a replayed state matches bit for bit
float g_reg[rows_per_lane];
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
g_reg[r] = expf(g_t[r * lanes_per_col + lane_in_col]);
}
// kv[col] = sum_i g[i] * S[i][col] * k[i]
float kv_shard = 0.0f;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
const int i = r * lanes_per_col + lane_in_col;
kv_shard += expf(g_t[i]) * s_shard[r] * k_reg[r];
kv_shard += g_reg[r] * s_shard[r] * k_reg[r];
}
float kv_col = warp_reduce_sum<lanes_per_col>(kv_shard);
@@ -140,8 +233,7 @@ gated_delta_net_cuda(const float * q,
float attn_partial = 0.0f;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
const int i = r * lanes_per_col + lane_in_col;
s_shard[r] = expf(g_t[i]) * s_shard[r] + k_reg[r] * delta_col;
s_shard[r] = g_reg[r] * s_shard[r] + k_reg[r] * delta_col;
attn_partial += s_shard[r] * q_reg[r];
}
@@ -170,6 +262,9 @@ gated_delta_net_cuda(const float * q,
}
if constexpr (!keep_rs_t) {
if (replay && rep.keep) {
return;
}
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
const int i = r * lanes_per_col + lane_in_col;
@@ -178,7 +273,7 @@ gated_delta_net_cuda(const float * q,
}
}
template <bool KDA, bool keep_rs_t>
template <bool KDA, bool keep_rs_t, bool replay = false>
static void launch_gated_delta_net(
const float * q_d, const float * k_d, const float * v_d,
const float * g_d, const float * b_d, const float * s_d,
@@ -188,7 +283,7 @@ static void launch_gated_delta_net(
int64_t sv1, int64_t sv2, int64_t sv3,
int64_t sb1, int64_t sb2, int64_t sb3,
int64_t neqk1, int64_t rq3,
float scale, int64_t state_slot_stride, int K, cudaStream_t stream) {
float scale, int64_t state_slot_stride, int K, const gdn_replay_args & rep, cudaStream_t stream) {
//TODO: Add chunked kernel for even faster pre-fill
const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size;
// four columns per warp (see the kernel); shrink the CTA when the wider CTA would leave
@@ -209,29 +304,29 @@ static void launch_gated_delta_net(
const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(grid_dims, block_dims, 0, stream);
switch (S_v) {
case 16:
ggml_cuda_kernel_launch(gated_delta_net_cuda<16, KDA, keep_rs_t>, launch_params,
ggml_cuda_kernel_launch(gated_delta_net_cuda<16, KDA, keep_rs_t, replay>, launch_params,
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H,
n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep);
break;
case 32:
ggml_cuda_kernel_launch(gated_delta_net_cuda<32, KDA, keep_rs_t>, launch_params,
ggml_cuda_kernel_launch(gated_delta_net_cuda<32, KDA, keep_rs_t, replay>, launch_params,
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H,
n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep);
break;
case 64: {
ggml_cuda_kernel_launch(gated_delta_net_cuda<64, KDA, keep_rs_t>, launch_params,
ggml_cuda_kernel_launch(gated_delta_net_cuda<64, KDA, keep_rs_t, replay>, launch_params,
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H,
n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep);
break;
}
case 128: {
ggml_cuda_kernel_launch(gated_delta_net_cuda<128, KDA, keep_rs_t>, launch_params,
ggml_cuda_kernel_launch(gated_delta_net_cuda<128, KDA, keep_rs_t, replay>, launch_params,
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H,
n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep);
break;
}
default:
@@ -353,34 +448,85 @@ static void ggml_cuda_op_gated_delta_net_impl(
state_slot_stride = cache->slot_stride;
}
{
const ggml_tensor * src_pend = dst->src[6];
gdn_replay_args rep = {};
if (src_pend) {
const ggml_tensor * src_pv = dst->src[7];
const ggml_tensor * src_pgb = dst->src[8];
GGML_ASSERT(K == 1);
rep.pk = (const float *) src_pend->data;
rep.pv = (const float *) src_pv->data;
rep.pgb = (const float *) src_pgb->data;
rep.n_rep = (const int32_t *) dst->src[9]->data;
rep.sk1 = src_pend->nb[1] / sizeof(float);
rep.sk2 = src_pend->nb[2] / sizeof(float);
rep.sk3 = src_pend->nb[3] / sizeof(float);
rep.sv1 = src_pv->nb[1] / sizeof(float);
rep.sv2 = src_pv->nb[2] / sizeof(float);
rep.sv3 = src_pv->nb[3] / sizeof(float);
rep.sg1 = src_pgb->nb[1] / sizeof(float);
rep.sg2 = src_pgb->nb[2] / sizeof(float);
rep.sg3 = src_pgb->nb[3] / sizeof(float);
rep.n_pend = ggml_get_op_params_i32(dst, 1);
rep.keep = ggml_get_op_params_i32(dst, 2) != 0;
if (cache != nullptr) {
for (int i = 0; i < 4; ++i) {
rep.st[i] = cache->in_dst[i];
rep.st2[i] = cache->in_nb2[i];
rep.st3[i] = cache->in_nb3[i];
}
}
}
#define GDN_LAUNCH_N(KDA, KEEP, REPLAY, N_TOKENS, REP) \
launch_gated_delta_net<KDA, KEEP, REPLAY>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, \
S_v, H, N_TOKENS, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, \
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, REP, stream)
#define GDN_LAUNCH(KDA, KEEP, REPLAY) GDN_LAUNCH_N(KDA, KEEP, REPLAY, n_tokens, rep)
if (!src_pend) {
ggml_cuda_gdn_mma_args args = ggml_cuda_gdn_mma_args_from_tensor(dst);
args.state_out = state_d;
if (ggml_cuda_gdn_mma_launch(ctx.device, args, stream)) {
return;
}
} else if (!rep.keep && rep.st[0] == nullptr) {
// the chunked kernels (not KDA) do not replay: replay the pending tokens into the state output, then
// run the new tokens from there in place (each thread reads and writes the same state elements)
ggml_cuda_gdn_mma_args args = ggml_cuda_gdn_mma_args_from_tensor(dst);
args.state = state_d;
args.state_out = state_d;
if (ggml_cuda_gdn_mma_supported(ctx.device, args)) {
gdn_replay_args rep_only = rep;
rep_only.keep = true;
GDN_LAUNCH_N(false, false, true, 0, rep_only);
ggml_cuda_gdn_mma_launch(ctx.device, args, stream);
return;
}
}
if (kda) {
if (keep_rs) {
launch_gated_delta_net<true, true>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
GDN_LAUNCH(true, true, false);
} else if (src_pend) {
GDN_LAUNCH(true, false, true);
} else {
launch_gated_delta_net<true, false>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
GDN_LAUNCH(true, false, false);
}
} else {
if (keep_rs) {
launch_gated_delta_net<false, true>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
GDN_LAUNCH(false, true, false);
} else if (src_pend) {
GDN_LAUNCH(false, false, true);
} else {
launch_gated_delta_net<false, false>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
GDN_LAUNCH(false, false, false);
}
}
#undef GDN_LAUNCH
#undef GDN_LAUNCH_N
}
void ggml_cuda_op_gated_delta_net(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
+5
View File
@@ -5,6 +5,11 @@
struct ggml_cuda_gated_delta_net_fused_cache {
float * data; // rollback slot 0
int64_t slot_stride; // between rollback slots (0 when K==1)
// rs_replay: the cpys of the k, v, g, beta inputs into the pending rows, null when not fused
float * in_dst[4] = {};
int64_t in_nb2[4] = {}; // token stride in elements
int64_t in_nb3[4] = {}; // seq stride in elements
};
void ggml_cuda_op_gated_delta_net(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
+41
View File
@@ -3647,6 +3647,47 @@ static int ggml_cuda_try_gdn_cache_fusion(
fused_state_cpy.data = (float *) dst->data; // rollback group 0 (newest)
fused_state_cpy.slot_stride = K > 1 ? (int64_t) (dst->nb[2] / sizeof(float)) : 0;
// rs_replay: the next 4 real nodes may store the k, v, g, beta inputs into the pending rows
if (gdn->src[6] != nullptr && gdn->src[3]->ne[0] == 1) {
int j = node_idx + skip + 1;
int skip_in = skip;
float * in_dst[4];
int64_t in_nb2[4];
int64_t in_nb3[4];
int i = 0;
for (; i < 4 && j < cgraph->n_nodes; ++j) {
const ggml_tensor * n = cgraph->nodes[j];
if (ggml_cuda_is_view_or_noop(n)) {
continue;
}
const ggml_tensor * in = gdn->src[1 + i];
const ggml_tensor * d = n->src[1];
// the cpy reads the whole input, directly or through a view of the same data
const ggml_tensor * s0 = n->src[0];
const bool whole_in = s0 == in || (s0 != nullptr && s0->data == in->data && ggml_are_same_shape(s0, in) &&
ggml_are_same_stride(s0, in));
if (n->op != GGML_OP_CPY || (n->flags & GGML_TENSOR_FLAG_OUTPUT) || !whole_in ||
d->type != GGML_TYPE_F32 || d->data == nullptr || !ggml_are_same_shape(d, in) ||
d->nb[0] != sizeof(float) || d->nb[1] != d->ne[0]*sizeof(float) || d->nb[2] != d->ne[0]*d->ne[1]*sizeof(float)) {
break;
}
in_dst[i] = (float *) d->data;
in_nb2[i] = d->nb[2] / sizeof(float);
in_nb3[i] = d->nb[3] / sizeof(float);
skip_in = j - node_idx;
++i;
}
if (i == 4) {
for (int c = 0; c < 4; ++c) {
fused_state_cpy.in_dst[c] = in_dst[c];
fused_state_cpy.in_nb2[c] = in_nb2[c];
fused_state_cpy.in_nb3[c] = in_nb3[c];
}
skip = skip_in;
}
}
return skip;
}
+3 -1
View File
@@ -1277,6 +1277,7 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm
if (op->type == GGML_TYPE_F32 && op->src[0] && op->src[0]->type == GGML_TYPE_F32 && op->src[1] &&
(op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) && op->src[2] &&
(op->src[2]->type == GGML_TYPE_F32 || op->src[2]->type == GGML_TYPE_F16) && op->src[4] == nullptr && op->src[5] == nullptr &&
!ggml_flash_attn_ext_has_indexed_bias(op) &&
ggml_is_contiguous_rows(op) && ggml_is_contiguous_rows(op->src[0])) {
float max_bias = 0.0f;
float logit_softcap = 0.0f;
@@ -1536,7 +1537,8 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm
op->src[4]->ne[0] == 1 && // beta is scalar per position
et_ggml_is_row_contiguous(op->src[0]) && et_ggml_is_row_contiguous(op->src[1]) &&
et_ggml_is_row_contiguous(op->src[2]) && ggml_is_contiguous(op->src[3]) &&
ggml_is_contiguous(op->src[4]) && ggml_is_contiguous(op->src[5])) {
ggml_is_contiguous(op->src[4]) && ggml_is_contiguous(op->src[5]) &&
ggml_get_op_params_i32(op, 1) == 0) { // no replay of pending tokens
supported = true;
} else {
supported = false;
+23 -2
View File
@@ -355,8 +355,8 @@ static bool htp_kparams_solve_flash_attn(
return false;
}
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
if (op->src[5] != nullptr) {
// K/V row lists and indexed bias are not supported
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
@@ -514,7 +514,12 @@ static bool htp_kparams_solve_gated_delta_net(
const struct ggml_tensor * g = op->src[3];
const struct ggml_tensor * beta = op->src[4];
const struct ggml_tensor * state = op->src[5];
const struct ggml_tensor * pend_k = op->src[6];
const struct ggml_tensor * pend_v = op->src[7];
const struct ggml_tensor * pend_gb = op->src[8];
const struct ggml_tensor * n_rep = op->src[9];
const struct ggml_tensor * dst = op;
const bool replay = pend_k != nullptr;
if (q->type != GGML_TYPE_F32 || k->type != GGML_TYPE_F32 || v->type != GGML_TYPE_F32 ||
g->type != GGML_TYPE_F32 || beta->type != GGML_TYPE_F32 || state->type != GGML_TYPE_F32 ||
@@ -552,6 +557,22 @@ static bool htp_kparams_solve_gated_delta_net(
dst->ne[2] != 1 || dst->ne[3] != 1) {
return false;
}
if ((pend_v != nullptr) != replay || (pend_gb != nullptr) != replay || (n_rep != nullptr) != replay) {
return false;
}
if (replay) {
const int64_t n_pend = ggml_get_op_params_i32(op, 1);
if (K != 1 || n_pend < 0 || pend_k->type != GGML_TYPE_F32 || pend_v->type != GGML_TYPE_F32 ||
pend_gb->type != GGML_TYPE_F32 || n_rep->type != GGML_TYPE_I32 ||
pend_k->nb[0] != sizeof(float) || pend_v->nb[0] != sizeof(float) || pend_gb->nb[0] != sizeof(float) ||
pend_k->ne[0] != k->ne[0] || pend_k->ne[1] != k->ne[1] || pend_k->ne[2] != n_pend || pend_k->ne[3] != n_seqs ||
pend_v->ne[0] != S_v || pend_v->ne[1] != H || pend_v->ne[2] != n_pend || pend_v->ne[3] != n_seqs ||
pend_gb->ne[0] != g->ne[0] || pend_gb->ne[1] != H || pend_gb->ne[2] != 2*n_pend || pend_gb->ne[3] != n_seqs ||
!ggml_is_contiguous(n_rep) || ggml_nelements(n_rep) != n_seqs) {
return false;
}
}
const uint32_t rq3 = (uint32_t) (n_seqs / q->ne[3]);
const uint32_t rk3 = (uint32_t) (n_seqs / k->ne[3]);
+80 -18
View File
@@ -574,7 +574,7 @@ static inline HVX_Vector gdn_add_scaled_dot8_f32(float * restrict dst0, float *
return Q6_V_vmux_QVV(q16, rA, Q6_V_vror_VR(rB, 128 - 16));
}
static inline void gdn_step_kda_f32(
static __attribute__((noinline)) void gdn_step_kda_f32(
float * restrict s_work,
float * restrict attn_out,
const float * restrict q_t,
@@ -662,7 +662,7 @@ static inline void gdn_step_kda_f32(
}
}
static inline void gdn_step_scalar_f32(
static __attribute__((noinline)) void gdn_step_scalar_f32(
float * restrict s_work,
float * restrict attn_out,
const float * restrict q_t,
@@ -748,6 +748,48 @@ static inline void gdn_step_scalar_f32(
}
}
static inline void gdn_replay_f32(
const struct htp_ops_context * octx,
float * restrict s_work,
uint32_t ik1,
uint32_t iv1,
uint32_t iv3,
bool kda,
float scale,
uint32_t S_v
) {
const struct htp_tensor * pend_k = octx->src[6];
const struct htp_tensor * pend_v = octx->src[7];
const struct htp_tensor * pend_gb = octx->src[8];
const struct htp_tensor * n_rep = octx->src[9];
if (!pend_k) {
return;
}
const uint32_t n_pend = (uint32_t) octx->op_params[1];
const int32_t raw_n_rep = ((const int32_t *) (uintptr_t) n_rep->data)[iv3];
const uint32_t n_steps = raw_n_rep <= 0 ? 0 : MIN((uint32_t) raw_n_rep, n_pend);
float unused_attn[128] __attribute__((aligned(128)));
const uint8_t * pk = (const uint8_t *) (uintptr_t) pend_k->data + (uint64_t) iv3 * pend_k->nb[3] + (uint64_t) ik1 * pend_k->nb[1];
const uint8_t * pv = (const uint8_t *) (uintptr_t) pend_v->data + (uint64_t) iv3 * pend_v->nb[3] + (uint64_t) iv1 * pend_v->nb[1];
const uint8_t * pgb = (const uint8_t *) (uintptr_t) pend_gb->data + (uint64_t) iv3 * pend_gb->nb[3] + (uint64_t) iv1 * pend_gb->nb[1];
for (uint32_t t = 0; t < n_steps; ++t) {
const float * k_t = (const float *) (pk + (uint64_t) t * pend_k->nb[2]);
const float * v_t = (const float *) (pv + (uint64_t) t * pend_v->nb[2]);
const float * g_t = (const float *) (pgb + (uint64_t) t * pend_gb->nb[2]);
const float beta_val = *(const float *) (pgb + (uint64_t) (n_pend + t) * pend_gb->nb[2]);
if (kda) {
gdn_step_kda_f32(s_work, unused_attn, k_t, k_t, v_t, g_t, beta_val, scale, S_v);
} else {
gdn_step_scalar_f32(s_work, unused_attn, k_t, k_t, v_t, g_t, beta_val, scale, S_v);
}
}
}
static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
struct htp_gdn_context * gctx = (struct htp_gdn_context *) data;
struct htp_ops_context * octx = gctx->octx;
@@ -792,6 +834,7 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int
const uint32_t state_seq_stride = kparams->state_seq_stride;
const uint64_t state_size_per_snap = (uint64_t) kparams->state_size_per_snap;
const dma_addr_t state_out_dma_base = dst_cache ? dst_cache->data : (dst->data + S_v * H * n_tokens * n_seqs * sizeof(float));
const bool keep = octx->src[6] && octx->op_params[2] != 0;
uint32_t ir_prefetch = gctx->row_start + ith;
int spad_idx = 0;
@@ -838,6 +881,10 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int
float * attn_data = dst_base + ((uint64_t) iv3 * n_tokens * H + iv1) * S_v;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
gdn_replay_f32(octx, s_work_curr, ik1, iv1, iv3, kparams->kda, scale, S_v);
if (keep) {
hvx_copy_f32_uu((uint8_t *) (uintptr_t) s_out, (const uint8_t *) s_work_curr, S_v * S_v);
}
for (uint32_t t = 0; t < n_tokens; ++t) {
const float * q_t = (const float *) ((const uint8_t *) (uintptr_t) q->data +
(uint64_t) iq3 * q->nb[3] + (uint64_t) t * q->nb[2] + (uint64_t) iq1 * q->nb[1]);
@@ -868,10 +915,9 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
// Push real write-back
dma_queue_push(dma_q, dma_make_data(s_out, s_work_curr),
S_v * sizeof(float), S_v * sizeof(float),
S_v * sizeof(float), S_v);
S_v * sizeof(float), keep ? 0 : S_v);
// Prefetch next block (if any)
if (ir_prefetch < row_end) {
@@ -932,6 +978,7 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int
const uint32_t state_seq_stride = kparams->state_seq_stride;
const dma_addr_t state_out_dma_base = dst_cache ? dst_cache->data : (dst->data + S_v * H * n_seqs * sizeof(float));
const bool keep = octx->src[6] && octx->op_params[2] != 0;
uint32_t ir_prefetch = gctx->row_start + ith;
int spad_idx = 0;
@@ -989,6 +1036,10 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int
(uint64_t) iv3 * beta->nb[3] + (uint64_t) iv1 * beta->nb[1]);
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
gdn_replay_f32(octx, s_work_curr, ik1, iv1, iv3, kparams->kda, scale, S_v);
if (keep) {
hvx_copy_f32_uu((uint8_t *) (uintptr_t) s_out, (const uint8_t *) s_work_curr, S_v * S_v);
}
if (kparams->kda) {
gdn_step_kda_f32(s_work_curr, attn_data, q_t, k_t, v_t, g_t, beta_val, scale, S_v);
} else {
@@ -996,10 +1047,9 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
// Push real write-back
dma_queue_push(dma_q, dma_make_data(s_out, s_work_curr),
S_v * sizeof(float), S_v * sizeof(float),
S_v * sizeof(float), S_v);
S_v * sizeof(float), keep ? 0 : S_v);
// Prefetch next block (if any)
if (ir_prefetch < row_end) {
@@ -1654,13 +1704,15 @@ struct htp_gdn_batch_context {
const struct htp_gdn_kernel_params * kparams;
};
static void gdn_hvx_init_state_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
static void gdn_hvx_replay_init_state_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
(void) n;
struct htp_gdn_batch_context * bctx = (struct htp_gdn_batch_context *) data;
struct htp_thread_trace * tr = th->trace;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, 0);
struct htp_gdn_head_ptrs * head = &bctx->heads[i];
gdn_replay_f32(bctx->octx, head->s_state, head->ik1, head->iv1, head->iv3,
bctx->kparams->kda, bctx->scale, bctx->S_v);
gdn_pack_s_col_tiles(head->s_col_tiles, head->s_f16, head->s_state, bctx->S_v);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, 0);
@@ -2038,6 +2090,7 @@ static int gated_delta_net_f32_hmx_chunked(
const uint32_t chunk_size = kparams->chunk_size;
const uint32_t n_chunks = kparams->n_chunks;
const uint32_t n_sv_tiles = S_v / 32;
const bool keep = octx->src[6] && octx->op_params[2] != 0;
struct htp_gdn_hmx_vtcm_layout L;
htp_gdn_hmx_vtcm_layout_build(&L, S_v, chunk_size, kparams->n_heads_batch, kparams->n_hvx, kparams->pipeline != 0);
@@ -2101,7 +2154,17 @@ static int gated_delta_net_f32_hmx_chunked(
}
if (n_chunks > 0) {
work_queue_run(wp, gdn_hvx_init_state_worker, &bctx, n_batch);
work_queue_run(wp, gdn_hvx_replay_init_state_worker, &bctx, n_batch);
if (keep) {
for (uint32_t h = 0; h < n_batch; ++h) {
dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state),
S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v);
}
for (uint32_t h = 0; h < n_batch; ++h) {
dma_queue_pop(dma_q);
}
}
const uint32_t chunk0_tokens = hex_smin(chunk_size, n_tokens);
for (uint32_t h = 0; h < n_batch; ++h) {
@@ -2254,12 +2317,14 @@ static int gated_delta_net_f32_hmx_chunked(
}
}
for (uint32_t h = 0; h < n_batch; ++h) {
dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state),
S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v);
}
for (uint32_t h = 0; h < n_batch; ++h) {
dma_queue_pop(dma_q);
if (!keep) {
for (uint32_t h = 0; h < n_batch; ++h) {
dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state),
S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v);
}
for (uint32_t h = 0; h < n_batch; ++h) {
dma_queue_pop(dma_q);
}
}
}
@@ -2270,7 +2335,7 @@ static int gated_delta_net_f32_hmx_chunked(
int op_gated_delta_net(struct htp_ops_context * octx) {
const struct htp_tensor * dst = octx->dst;
for (int i = 0; i < 6; i++) {
for (int i = 0; i < 10; i++) {
if (htp_tensor_is_extended(octx->src[i])) {
return HTP_STATUS_NO_SUPPORT;
}
@@ -2308,9 +2373,6 @@ int op_gated_delta_net(struct htp_ops_context * octx) {
);
row_start = range.start;
nrows = range.count;
} else if (octx->op_params[1] != 0) {
row_start = octx->op_params[1];
nrows = octx->op_params[2];
}
if (nrows == 0) {
+1 -1
View File
@@ -105,7 +105,7 @@ static inline bool ggml_impl_is_view(const struct ggml_tensor * t) {
}
static inline float ggml_compute_softplus_f32(float input) {
return (input > 20.0f) ? input : logf(1 + expf(input));
return (input > 20.0f) ? input : log1pf(expf(input));
}
// compute correction dims for YaRN RoPE scaling
@@ -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;
+18 -5
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);
@@ -1116,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;
@@ -1321,7 +1329,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm_id(ggml_m
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_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;
@@ -1423,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;
+5 -3
View File
@@ -1532,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;
}
@@ -1747,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];
@@ -1978,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:
@@ -1992,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;
+13
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;
}
+39
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;
@@ -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;
+9
View File
@@ -677,6 +677,7 @@ template [[host_name("kernel_mul_mm_q5_0_f32_prec_bf16")]] kernel mul_mm_t ke
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>;
@@ -703,6 +704,7 @@ template [[host_name("kernel_mul_mm_q5_0_f32_prec_f32")]] kernel mul_mm_t ker
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>;
@@ -732,6 +734,7 @@ template [[host_name("kernel_mul_mm_q5_0_f32")]] kernel mul_mm_t kernel_mul_m
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>;
@@ -758,6 +761,7 @@ template [[host_name("kernel_mul_mm_q5_0_f16")]] kernel mul_mm_t kernel_mul_m
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>;
@@ -794,8 +798,10 @@ template [[host_name("kernel_mul_mm_id_q5_1_f32")]] kernel mul_mm_id kernel_m
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, 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, 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, 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>;
@@ -853,6 +859,7 @@ template [[host_name("kernel_mul_mm_id_q5_0_f32_prec_f32")]] kernel mul_mm_id
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>;
@@ -884,8 +891,10 @@ template [[host_name("kernel_mul_mm_id_q5_1_f16")]] kernel mul_mm_id kernel_m
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>;
@@ -393,6 +393,7 @@ template [[host_name("kernel_mul_mm_tensor_q5_0_f32")]] kernel mul_mm_tensor_
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>;
@@ -419,6 +420,7 @@ template [[host_name("kernel_mul_mm_tensor_q5_0_f16")]] kernel mul_mm_tensor_
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>;
@@ -455,8 +457,10 @@ template [[host_name("kernel_mul_mm_id_tensor_q5_1_f32")]] kernel mul_mm_id_t
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>;
@@ -515,8 +519,10 @@ template [[host_name("kernel_mul_mm_id_tensor_q5_1_f16")]] kernel mul_mm_id_t
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>;
+125 -9
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>;
@@ -3035,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>
@@ -3111,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);
@@ -3149,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,
@@ -3415,6 +3530,7 @@ template [[host_name("kernel_mul_mv_id_q5_0_f32")]] kernel kernel_mul_mv_id_t
template [[host_name("kernel_mul_mv_id_q5_1_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<mul_vec_q_n_f32_impl<block_q5_1, N_R0_Q5_1>>>;
template [[host_name("kernel_mul_mv_id_mxfp4_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_mxfp4_f32_impl<N_R0_MXFP4>>>;
template [[host_name("kernel_mul_mv_id_nvfp4_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_nvfp4_f32_impl<N_R0_NVFP4>>>;
template [[host_name("kernel_mul_mv_id_q2_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q2_K_f32_impl <N_R0_Q2_K>>>;
template [[host_name("kernel_mul_mv_id_q3_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q3_K_f32_impl <N_R0_Q3_K>>>;
@@ -611,6 +611,7 @@ MUL_MV_MMA_GEN("bf16", bfloat4x4, 1, dequantize_bf16)
MUL_MV_MMA_GEN("q1_0", block_q1_0, 8, dequantize_q1_0)
MUL_MV_MMA_GEN("q2_0", block_q2_0, 4, dequantize_q2_0)
MUL_MV_MMA_GEN("mxfp4", block_mxfp4, 2, dequantize_mxfp4)
MUL_MV_MMA_GEN("nvfp4", block_nvfp4, 4, dequantize_nvfp4)
MUL_MV_MMA_GEN("q2_K", block_q2_K, QK_NL, dequantize_q2_K)
MUL_MV_MMA_GEN("q3_K", block_q3_K, QK_NL, dequantize_q3_K)
MUL_MV_MMA_GEN("iq2_xxs", block_iq2_xxs, QK_NL, dequantize_iq2_xxs)
+73 -8
View File
@@ -146,6 +146,7 @@ template [[host_name("kernel_cpy_q4_1_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32<
template [[host_name("kernel_cpy_q5_0_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32<float4x4, block_q5_0, 2, dequantize_q5_0>;
template [[host_name("kernel_cpy_q5_1_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32<float4x4, block_q5_1, 2, dequantize_q5_1>;
template [[host_name("kernel_cpy_q8_0_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32<float4x4, block_q8_0, 2, dequantize_q8_0>;
template [[host_name("kernel_cpy_nvfp4_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32<float4x4, block_nvfp4, 4, dequantize_nvfp4>;
template [[host_name("kernel_cpy_tq2_0_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32<float4x4, block_tq2_0, QK_NL, dequantize_tq2_0>;
@@ -156,9 +157,51 @@ template [[host_name("kernel_cpy_q4_1_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32<
template [[host_name("kernel_cpy_q5_0_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32<half4x4, block_q5_0, 2, dequantize_q5_0>;
template [[host_name("kernel_cpy_q5_1_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32<half4x4, block_q5_1, 2, dequantize_q5_1>;
template [[host_name("kernel_cpy_q8_0_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32<half4x4, block_q8_0, 2, dequantize_q8_0>;
template [[host_name("kernel_cpy_nvfp4_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32<half4x4, block_nvfp4, 4, dequantize_nvfp4>;
template [[host_name("kernel_cpy_tq2_0_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32<half4x4, block_tq2_0, QK_NL, dequantize_tq2_0>;
template<typename T>
static void concat_copy(device const char * src, device char * dst, const int n, const int tid, const int nth) {
if (n <= 0) {
return;
}
constexpr int N = 16/sizeof(T);
typedef vec<T, N> T16;
device const T * x = (device const T *)src;
device T * y = (device T *)dst;
const size_t rx = (size_t)x % 16;
if (rx != (size_t)y % 16 || rx % sizeof(T) != 0) {
for (int i = tid; i < n; i += nth) {
y[i] = x[i];
}
return;
}
const int np = min((int)(((16 - rx) % 16)/sizeof(T)), n);
const int n16 = (n - np)/N;
for (int i = tid; i < np; i += nth) {
y[i] = x[i];
}
device const T16 * x16 = (device const T16 *)(x + np);
device T16 * y16 = (device T16 *)(y + np);
for (int i = tid; i < n16; i += nth) {
y16[i] = x16[i];
}
for (int i = np + n16*N + tid; i < n; i += nth) {
y[i] = x[i];
}
}
template<typename T>
kernel void kernel_concat(
constant ggml_metal_kargs_concat & args,
@@ -178,20 +221,39 @@ kernel void kernel_concat(
return;
}
int o[4] = {0, 0, 0, 0};
o[args.dim] = args.dim == 0 ? args.ne00 : (args.dim == 1 ? args.ne01 : (args.dim == 2 ? args.ne02 : args.ne03));
const int o0 = args.dim == 0 ? args.ne00 : 0;
const int o1 = args.dim == 1 ? args.ne01 : 0;
const int o2 = args.dim == 2 ? args.ne02 : 0;
const int o3 = args.dim == 3 ? args.ne03 : 0;
// chunk ic of nc0 along the row
const int n0 = (args.ne0 + args.nc0 - 1)/args.nc0;
const int i0e = min(args.ne0, (ic + 1)*n0);
const int i0b = ntg.y == 1 ? ic*n0 : 0;
const int i0e = ntg.y == 1 ? min(args.ne0, (ic + 1)*n0) : args.ne0;
for (int i0 = ic*n0 + tpitg.x; i0 < i0e; i0 += ntg.x) {
if (args.nb0 == sizeof(T) && args.nb00 == sizeof(T) && args.nb10 == sizeof(T)) {
const bool in0 = i1 < args.ne01 && i2 < args.ne02 && i3 < args.ne03;
const int na = in0 ? min(i0e - i0b, max(0, args.ne00 - i0b)) : 0;
const int nb = i0e - i0b - na;
device const char * r0 = src0 + i3*args.nb03 + i2*args.nb02 + i1*args.nb01;
device const char * r1 = src1 + (i3 - o3)*args.nb13 + (i2 - o2)*args.nb12 + (i1 - o1)*args.nb11;
device char * rd = dst + i3*args.nb3 + i2*args.nb2 + i1*args.nb1;
concat_copy<T>(r0 + i0b*sizeof(T), rd + i0b*sizeof(T), na, tpitg.x, ntg.x);
concat_copy<T>(r1 + (i0b + na - o0)*sizeof(T), rd + (i0b + na)*sizeof(T), nb, tpitg.x, ntg.x);
return;
}
for (int i0 = i0b + tpitg.x; i0 < i0e; i0 += ntg.x) {
device const T * x;
if (i0 < args.ne00 && i1 < args.ne01 && i2 < args.ne02 && i3 < args.ne03) {
x = (device const T *)(src0 + (i3 )*args.nb03 + (i2 )*args.nb02 + (i1 )*args.nb01 + (i0 )*args.nb00);
} else {
x = (device const T *)(src1 + (i3 - o[3])*args.nb13 + (i2 - o[2])*args.nb12 + (i1 - o[1])*args.nb11 + (i0 - o[0])*args.nb10);
x = (device const T *)(src1 + (i3 - o3)*args.nb13 + (i2 - o2)*args.nb12 + (i1 - o1)*args.nb11 + (i0 - o0)*args.nb10);
}
device T * y = (device T *)(dst + i3*args.nb3 + i2*args.nb2 + i1*args.nb1 + i0*args.nb0);
@@ -232,8 +294,10 @@ kernel void kernel_concat_q(
return;
}
int o[4] = {0, 0, 0, 0};
o[args.dim] = args.dim == 0 ? args.ne00 : (args.dim == 1 ? args.ne01 : (args.dim == 2 ? args.ne02 : args.ne03));
const int o0 = args.dim == 0 ? args.ne00 : 0;
const int o1 = args.dim == 1 ? args.ne01 : 0;
const int o2 = args.dim == 2 ? args.ne02 : 0;
const int o3 = args.dim == 3 ? args.ne03 : 0;
// chunk ic of nc0 along the row
const int n0 = (args.ne0 + args.nc0 - 1)/args.nc0;
@@ -245,7 +309,7 @@ kernel void kernel_concat_q(
if (i0 < args.ne00 && i1 < args.ne01 && i2 < args.ne02 && i3 < args.ne03) {
x = (device const block_q *)(src0 + (i3 )*args.nb03 + (i2 )*args.nb02 + (i1 )*args.nb01 + (i0 )*args.nb00);
} else {
x = (device const block_q *)(src1 + (i3 - o[3])*args.nb13 + (i2 - o[2])*args.nb12 + (i1 - o[1])*args.nb11 + (i0 - o[0])*args.nb10);
x = (device const block_q *)(src1 + (i3 - o3)*args.nb13 + (i2 - o2)*args.nb12 + (i1 - o1)*args.nb11 + (i0 - o0)*args.nb10);
}
device block_q * y = (device block_q *)(dst + i3*args.nb3 + i2*args.nb2 + i1*args.nb1 + i0*args.nb0);
@@ -341,6 +405,7 @@ template [[host_name("kernel_get_rows_q5_0")]] kernel get_rows_q_t kernel_get
template [[host_name("kernel_get_rows_q5_1")]] kernel get_rows_q_t kernel_get_rows_q<block_q5_1, 2, dequantize_q5_1>;
template [[host_name("kernel_get_rows_q8_0")]] kernel get_rows_q_t kernel_get_rows_q<block_q8_0, 2, dequantize_q8_0>;
template [[host_name("kernel_get_rows_mxfp4")]] kernel get_rows_q_t kernel_get_rows_q<block_mxfp4, 2, dequantize_mxfp4>;
template [[host_name("kernel_get_rows_nvfp4")]] kernel get_rows_q_t kernel_get_rows_q<block_nvfp4, 4, dequantize_nvfp4>;
template [[host_name("kernel_get_rows_q2_K")]] kernel get_rows_q_t kernel_get_rows_q<block_q2_K, QK_NL, dequantize_q2_K>;
template [[host_name("kernel_get_rows_q3_K")]] kernel get_rows_q_t kernel_get_rows_q<block_q3_K, QK_NL, dequantize_q3_K>;
template [[host_name("kernel_get_rows_q4_K")]] kernel get_rows_q_t kernel_get_rows_q<block_q4_K, QK_NL, dequantize_q4_K>;
+20 -1
View File
@@ -21,6 +21,25 @@ inline bfloat4 ggml_metal_unary_cast<bfloat4, float>(float x) {
}
#endif
template <typename T>
inline T ggml_metal_log1p(T x) {
const T y = x / (T(2.0f) + x);
const T y2 = y * y;
T p = T(1.0f / 13.0f);
p = p * y2 + T(1.0f / 11.0f);
p = p * y2 + T(1.0f / 9.0f);
p = p * y2 + T(1.0f / 7.0f);
p = p * y2 + T(1.0f / 5.0f);
p = p * y2 + T(1.0f / 3.0f);
p = p * y2 + T(1.0f);
const T s = T(2.0f) * y * p;
const T l = precise::log(T(1.0f) + x);
const auto in_series = (x >= T(-0.5f)) & (x <= T(1.0f));
const auto tiny = fabs(x) < T(2.5e-38f);
const T r = select(l, s, in_series);
return select(r, x, tiny);
}
template <typename T0, typename T, typename TC>
kernel void kernel_unary_impl(
constant ggml_metal_kargs_unary & args,
@@ -166,7 +185,7 @@ kernel void kernel_unary_impl(
}
if (FC_OP == OP_UNARY_NUM_SOFTPLUS) {
dst_ptr[i0] = ggml_metal_unary_cast<T>(select(log(1 + exp(x)), x, x > 20));
dst_ptr[i0] = ggml_metal_unary_cast<T>(select(ggml_metal_log1p(precise::exp(x)), x, x > TC(20.0f)));
}
if (FC_OP == OP_UNARY_NUM_EXPM1) {
+73
View File
@@ -36,6 +36,78 @@ endif ()
if (GGML_OPENCL_USE_ADRENO_BIN_KERNELS)
message(STATUS "OpenCL will use precompiled binary kernels for Adreno (improved performance on some platforms)")
add_compile_definitions(GGML_OPENCL_USE_ADRENO_BIN_KERNELS)
target_link_libraries(${TARGET_NAME} PRIVATE ${CMAKE_DL_LIBS})
endif ()
# The library is only published for Windows on ARM64. A failed download is not
# fatal: without the library the backend uses its builtin kernels.
string(TOLOWER "${CMAKE_SYSTEM_PROCESSOR}" ADRENO_BIN_KERNELS_SYSTEM_PROCESSOR)
if (GGML_OPENCL_USE_ADRENO_BIN_KERNELS AND GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH AND
WIN32 AND ADRENO_BIN_KERNELS_SYSTEM_PROCESSOR MATCHES "^(aarch64|arm64)$")
# Bump the version and hash together when a new library release is published.
set(ADRENO_BIN_KERNELS_VERSION "0.0.15")
set(ADRENO_BIN_KERNELS_ZIP_SHA256 "325c89a3bce51abe95f40c6bacece005d5ca9cf6166eb5f17d33592cd13ab795")
set(ADRENO_BIN_KERNELS_URL "https://softwarecenter.qualcomm.com/api/download/software/tools/Adreno_Kernel_Library_GGML/Windows/${ADRENO_BIN_KERNELS_VERSION}/adreno-opencl-kernels-${ADRENO_BIN_KERNELS_VERSION}.zip")
set(ADRENO_BIN_KERNELS_ROOT "${CMAKE_BINARY_DIR}/_deps/adreno-opencl-kernels-${ADRENO_BIN_KERNELS_VERSION}")
set(ADRENO_BIN_KERNELS_ZIP "${ADRENO_BIN_KERNELS_ROOT}.zip")
set(ADRENO_BIN_KERNELS_DLL "${ADRENO_BIN_KERNELS_ROOT}/adreno-opencl-kernels.dll")
set(ADRENO_BIN_KERNELS_LICENSE "${ADRENO_BIN_KERNELS_ROOT}/license.txt")
if (NOT EXISTS "${ADRENO_BIN_KERNELS_DLL}" OR NOT EXISTS "${ADRENO_BIN_KERNELS_LICENSE}")
message(STATUS "OpenCL: fetching Adreno binary kernel library ${ADRENO_BIN_KERNELS_VERSION} from Qualcomm; its use is subject to the license in license.txt")
file(DOWNLOAD "${ADRENO_BIN_KERNELS_URL}" "${ADRENO_BIN_KERNELS_ZIP}"
TLS_VERIFY ON
TIMEOUT 120
INACTIVITY_TIMEOUT 30
STATUS ADRENO_BIN_KERNELS_DOWNLOAD_STATUS)
list(GET ADRENO_BIN_KERNELS_DOWNLOAD_STATUS 0 ADRENO_BIN_KERNELS_DOWNLOAD_RESULT)
if (ADRENO_BIN_KERNELS_DOWNLOAD_RESULT EQUAL 0)
file(SHA256 "${ADRENO_BIN_KERNELS_ZIP}" ADRENO_BIN_KERNELS_ZIP_ACTUAL_SHA256)
if (NOT ADRENO_BIN_KERNELS_ZIP_ACTUAL_SHA256 STREQUAL ADRENO_BIN_KERNELS_ZIP_SHA256)
file(REMOVE "${ADRENO_BIN_KERNELS_ZIP}")
message(FATAL_ERROR "Adreno binary kernel library hash mismatch: expected ${ADRENO_BIN_KERNELS_ZIP_SHA256}, got ${ADRENO_BIN_KERNELS_ZIP_ACTUAL_SHA256}")
endif ()
file(MAKE_DIRECTORY "${ADRENO_BIN_KERNELS_ROOT}")
execute_process(
COMMAND ${CMAKE_COMMAND} -E tar xf "${ADRENO_BIN_KERNELS_ZIP}"
WORKING_DIRECTORY "${ADRENO_BIN_KERNELS_ROOT}"
RESULT_VARIABLE ADRENO_BIN_KERNELS_EXTRACT_RESULT)
if (NOT ADRENO_BIN_KERNELS_EXTRACT_RESULT EQUAL 0)
message(WARNING "Failed to extract the Adreno binary kernel library from ${ADRENO_BIN_KERNELS_ZIP}")
endif ()
else ()
list(GET ADRENO_BIN_KERNELS_DOWNLOAD_STATUS 1 ADRENO_BIN_KERNELS_DOWNLOAD_ERROR)
message(WARNING "Failed to download the Adreno binary kernel library (${ADRENO_BIN_KERNELS_DOWNLOAD_ERROR}); "
"the builtin kernels will be used. Set GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=OFF to skip the download.")
endif ()
file(REMOVE "${ADRENO_BIN_KERNELS_ZIP}")
endif ()
if (EXISTS "${ADRENO_BIN_KERNELS_DLL}" AND EXISTS "${ADRENO_BIN_KERNELS_LICENSE}")
if (COMMAND license_add_file)
license_add_file("Adreno OpenCL kernels" "${ADRENO_BIN_KERNELS_LICENSE}")
endif ()
set(ADRENO_BIN_KERNELS_OUTPUT_DIR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}")
if (CMAKE_CONFIGURATION_TYPES AND NOT ADRENO_BIN_KERNELS_OUTPUT_DIR MATCHES "\\$<")
string(APPEND ADRENO_BIN_KERNELS_OUTPUT_DIR "/$<CONFIG>")
endif ()
foreach (CONFIG IN LISTS CMAKE_CONFIGURATION_TYPES CMAKE_BUILD_TYPE)
string(TOUPPER "${CONFIG}" CONFIG_UPPER)
if (DEFINED CMAKE_RUNTIME_OUTPUT_DIRECTORY_${CONFIG_UPPER})
set(ADRENO_BIN_KERNELS_OUTPUT_DIR "$<$<CONFIG:${CONFIG}>:${CMAKE_RUNTIME_OUTPUT_DIRECTORY_${CONFIG_UPPER}}>$<$<NOT:$<CONFIG:${CONFIG}>>:${ADRENO_BIN_KERNELS_OUTPUT_DIR}>")
endif ()
endforeach ()
add_custom_target(ggml-opencl-adreno-bin-kernels ALL
COMMAND ${CMAKE_COMMAND} -E make_directory "${ADRENO_BIN_KERNELS_OUTPUT_DIR}"
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${ADRENO_BIN_KERNELS_DLL}" "${ADRENO_BIN_KERNELS_OUTPUT_DIR}/adreno-opencl-kernels.dll"
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${ADRENO_BIN_KERNELS_LICENSE}" "${ADRENO_BIN_KERNELS_OUTPUT_DIR}/LICENSE-adreno-opencl-kernels.txt")
add_dependencies(${TARGET_NAME} ggml-opencl-adreno-bin-kernels)
install(FILES "${ADRENO_BIN_KERNELS_DLL}" DESTINATION ${CMAKE_INSTALL_BINDIR})
install(FILES "${ADRENO_BIN_KERNELS_LICENSE}" DESTINATION ${CMAKE_INSTALL_BINDIR} RENAME LICENSE-adreno-opencl-kernels.txt)
endif ()
endif ()
function(ggml_opencl_add_kernel KNAME)
@@ -228,6 +300,7 @@ set(GGML_OPENCL_KERNELS
gemm_coopk_q4_k_q8_1_dp4a
gemm_coopk_q4_k_q8_1_dp4a_bin_c8
gemm_coopk_q6_k_q8_1_dp4a
gemm_coopk_q6_k_q8_1_dp4a_bin_c8
pack_b_f16_coopmat
gemm_noshuffle_q4_0_f32_coopmat
gemm_noshuffle_q5_0_f32_coopmat
+217 -12
View File
@@ -1181,9 +1181,9 @@ struct ggml_backend_opencl_context {
cl_kernel kernel_conv_2d_f16_f32;
cl_kernel kernel_conv2d_dw_f32_f32, kernel_conv2d_dwf16_f32;
cl_kernel kernel_ssm_conv_f32_f32, kernel_ssm_conv_f32_f32_4;
// [size_idx][kda][tgpp] where size_idx: 0=S_V=16, 1=32, 2=64, 3=128; kda: 0 or 1.
// [size_idx][kda][tgpp][replay] where size_idx: 0=S_V=16, 1=32, 2=64, 3=128; kda: 0 or 1.
// tgpp 0 = TG variant (COLS_PER_LANE_GROUP=1), tgpp 1 = prefill variant (COLS_PER_LANE_GROUP=4).
cl_kernel kernel_gated_delta_net_f32[4][2][2] = {};
cl_kernel kernel_gated_delta_net_f32[4][2][2][2] = {};
cl_kernel kernel_ssm_scan_f32 = nullptr;
cl_kernel kernel_ssm_scan_f32_mamba2_d128 = nullptr;
cl_kernel kernel_ssm_scan_f32_mamba2_d256 = nullptr;
@@ -1529,13 +1529,18 @@ struct ggml_backend_opencl_context {
cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_c2 = nullptr;
int nsg_coopk_dp4a_q6_k = 8;
int rows_coopk_dp4a_q6_k = 4;
cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 = nullptr;
cl_kernel kernel_quant_a_q8_1_k4h = nullptr;
int nsg_coopk_dp4a_q6_k_bin_c8 = 4;
#endif // GGML_OPENCL_USE_ADRENO_KERNELS
~ggml_backend_opencl_context() {
#ifdef GGML_OPENCL_USE_ADRENO_KERNELS
for (cl_kernel kernel : {
kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8,
kernel_quant_a_q8_1_k4
kernel_quant_a_q8_1_k4,
kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8,
kernel_quant_a_q8_1_k4h
}
) {
if (kernel != nullptr) {
@@ -1949,6 +1954,46 @@ static void load_cl_kernel_coopk_q4_k_bin_c8(ggml_backend_opencl_context * backe
backend_ctx->kernel_quant_a_q8_1_k4 = quant;
}
static void load_cl_kernel_coopk_q6_k_bin_c8(ggml_backend_opencl_context * backend_ctx) {
#ifdef GGML_OPENCL_EMBED_KERNELS
const std::string kernel_src {
#include "gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl.h"
};
#else
const std::string kernel_src = read_file("gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl");
#endif
cl_program program = ggml_cl_build_program_coopk(backend_ctx, kernel_src.c_str(),
"kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8", backend_ctx->kernel_compile_opts,
backend_ctx->nsg_coopk_dp4a_q6_k_bin_c8, false);
if (program == nullptr) {
return;
}
cl_int err;
cl_kernel gemm = clCreateKernel(program, "kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8", &err);
if (err != CL_SUCCESS) {
CL_CHECK(clReleaseProgram(program));
return;
}
cl_kernel quant = clCreateKernel(program, "kernel_quant_a_q8_1_k4h", &err);
CL_CHECK(clReleaseProgram(program));
if (err != CL_SUCCESS) {
CL_CHECK(clReleaseKernel(gemm));
return;
}
if (backend_ctx->get_kernel_workgroup_size(quant) < 64) {
CL_CHECK(clReleaseKernel(gemm));
CL_CHECK(clReleaseKernel(quant));
return;
}
backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 = gemm;
backend_ctx->kernel_quant_a_q8_1_k4h = quant;
}
static void ggml_cl_coopk_build_narrow(ggml_backend_opencl_context * backend_ctx,
const std::string & kernel_src, const char * kernel_name,
int rows, int & nsg, cl_kernel & kernel_c4, cl_kernel & kernel_c2) {
@@ -2065,6 +2110,15 @@ static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx
backend_ctx->rows_coopk_dp4a_q6_k, backend_ctx->nsg_coopk_dp4a_q6_k,
backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_c4,
backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_c2);
static const bool use_coopk_bin = [] {
const char * env = getenv("GGML_OPENCL_COOPK_Q6_K_BIN");
return !env || !*env || atoi(env) != 0;
}();
if (use_adreno_bin_kernels(backend_ctx) && use_coopk_bin) {
load_cl_kernel_coopk_q6_k_bin_c8(backend_ctx);
}
GGML_LOG_CONT(".");
}
}
@@ -5170,7 +5224,7 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
GGML_LOG_CONT(".");
}
// gated_delta_net: one kernel per (S_V, KDA, tgpp) triple.
// gated_delta_net: one kernel per (S_V, KDA, tgpp, replay).
{
#ifdef GGML_OPENCL_EMBED_KERNELS
const std::string kernel_src {
@@ -5238,11 +5292,14 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
// Please remember to implement code to handle it.
opts += " -DSUBGROUPS_PER_WG=" + std::to_string(spw);
cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts);
for (int replay = 0; replay < 2; replay++) {
const std::string opts_rep = opts + " -DREPLAY=" + std::to_string(replay);
cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts_rep);
CL_CHECK((backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp] =
clCreateKernel(prog, "kernel_gated_delta_net", &err), err));
CL_CHECK(clReleaseProgram(prog));
CL_CHECK((backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp][replay] =
clCreateKernel(prog, "kernel_gated_delta_net", &err), err));
CL_CHECK(clReleaseProgram(prog));
}
}
}
}
@@ -12662,8 +12719,8 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te
case GGML_OP_MEAN:
return op->src[0]->type == GGML_TYPE_F32;
case GGML_OP_FLASH_ATTN_EXT: {
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
if (op->src[5] != nullptr) {
// K/V row lists and indexed bias are not supported
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
#ifdef GGML_OPENCL_USE_ADRENO_KERNELS
@@ -29443,6 +29500,93 @@ static void ggml_cl_mul_mat_q6_K_f32_adreno_ila(ggml_backend_t backend, const gg
const int N = ne1;
const int K = ne00;
if (backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 != nullptr &&
N >= 2 && N <= 8 && M > 0 && K > 0 && M % 4 == 0 && K % 256 == 0 &&
src0->ne[0] == K && src0->ne[1] == M && dst->ne[1] == N &&
K <= INT_MAX / 8 && (int64_t) M * K / 8 <= INT_MAX &&
src0->ne[2] == 1 && src0->ne[3] == 1 && src0->view_src == nullptr &&
src1->ne[2] == 1 && src1->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 &&
ggml_is_contiguous(src1) && ggml_is_contiguous(dst)
) {
const int kb = K / 32;
const size_t qa_bytes = (size_t)8 * K;
const size_t ds_bytes = (size_t)24 * kb * sizeof(cl_half);
backend_ctx->prealloc_moe_qa.allocate(context, qa_bytes);
backend_ctx->prealloc_moe_da.allocate(context, ds_bytes);
if (ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_qa, qa_bytes,
backend_ctx->coopk_c8_qa_image, backend_ctx->coopk_c8_qa_buffer, backend_ctx->coopk_c8_qa_image_bytes) &&
ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_da, ds_bytes,
backend_ctx->coopk_c8_ds_image, backend_ctx->coopk_c8_ds_buffer, backend_ctx->coopk_c8_ds_image_bytes)
) {
const int n_blocks = N * kb;
cl_kernel quant = backend_ctx->kernel_quant_a_q8_1_k4h;
CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &extra1->data_device));
CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer));
CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer));
CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_ulong), &offset1));
CL_CHECK(clSetKernelArg(quant, 4, sizeof(int), &n_blocks));
CL_CHECK(clSetKernelArg(quant, 5, sizeof(int), &kb));
size_t quant_local[] = {64};
size_t quant_global[] = {(size_t)8 * kb};
backend_ctx->enqueue_ndrange_kernel(quant, 1, quant_global, quant_local, dst);
int ksplit = ggml_cl_coopk_ksplit(backend_ctx, CEIL_DIV(M / 4, 64), kb);
if (backend_ctx->kernel_gemv_splitk_reduce_f32 == nullptr) {
ksplit = 1;
}
cl_mem out = extrad->data_device;
cl_ulong out_offset = offsetd;
if (ksplit > 1) {
backend_ctx->prealloc_splitk_partial.allocate(context, (size_t)ksplit * M * N * sizeof(float));
out = backend_ctx->prealloc_splitk_partial.buffer;
out_offset = 0;
}
const cl_uchar mask_c0 = 0xC0;
const size_t nsg = backend_ctx->nsg_coopk_dp4a_q6_k_bin_c8;
cl_kernel gemm = backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8;
CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0_q6_K->ql));
CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0_q6_K->qh));
CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0_q6_K->s));
CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0_q6_K->d));
CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->coopk_c8_qa_image));
CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->coopk_c8_ds_image));
CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &out));
CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &out_offset));
CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &M));
CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &K));
CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &N));
CL_CHECK(clSetKernelArg(gemm, 11, sizeof(cl_uchar), &mask_c0));
CL_CHECK(clSetKernelArg(gemm, 12, sizeof(int), &ksplit));
size_t local[] = {64, nsg, 1};
size_t global[] = {(size_t)CEIL_DIV(M / 4, 64) * 64, nsg * ksplit, 1};
backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst);
if (ksplit > 1) {
const int rows = M * N;
cl_kernel reduce = backend_ctx->kernel_gemv_splitk_reduce_f32;
CL_CHECK(clSetKernelArg(reduce, 0, sizeof(cl_mem), &out));
CL_CHECK(clSetKernelArg(reduce, 1, sizeof(cl_mem), &extrad->data_device));
CL_CHECK(clSetKernelArg(reduce, 2, sizeof(cl_ulong), &offsetd));
CL_CHECK(clSetKernelArg(reduce, 3, sizeof(int), &rows));
CL_CHECK(clSetKernelArg(reduce, 4, sizeof(int), &ksplit));
size_t reduce_local[] = {64};
size_t reduce_global[] = {(size_t)CEIL_DIV(rows, 64) * 64};
backend_ctx->enqueue_ndrange_kernel(reduce, 1, reduce_global, reduce_local, dst);
}
return;
}
}
if (ne1 == 1) {
cl_mem b_sub_buf = nullptr;
cl_mem b_img = nullptr;
@@ -40476,6 +40620,9 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) {
const cl_uint n_tokens = (cl_uint) src_v->ne[2];
const cl_uint n_seqs = (cl_uint) src_v->ne[3];
const cl_uint K = (cl_uint) ggml_get_op_params_i32(dst, 0);
const bool replay = dst->src[6] != nullptr;
const cl_uint n_pend = replay ? (cl_uint) ggml_get_op_params_i32(dst, 1) : 0;
const cl_uint keep = replay ? (cl_uint) ggml_get_op_params_i32(dst, 2) : 0;
int si;
switch (S_v) {
@@ -40509,7 +40656,7 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) {
// spw needs adjustment when S_v != 128
const int spw = (tgpp == 0) ? 1 : 1;
cl_kernel kernel = backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp];
cl_kernel kernel = backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp][replay];
GGML_ASSERT(kernel != nullptr);
const cl_uint s_off = S_v * H_v * n_tokens * n_seqs;
@@ -40517,6 +40664,9 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) {
const cl_uint sq1 = (cl_uint)(src_q->nb[1] / sizeof(float));
const cl_uint sq2 = (cl_uint)(src_q->nb[2] / sizeof(float));
const cl_uint sq3 = (cl_uint)(src_q->nb[3] / sizeof(float));
const cl_uint sk1 = (cl_uint)(src_k->nb[1] / sizeof(float));
const cl_uint sk2 = (cl_uint)(src_k->nb[2] / sizeof(float));
const cl_uint sk3 = (cl_uint)(src_k->nb[3] / sizeof(float));
const cl_uint sv1 = (cl_uint)(src_v->nb[1] / sizeof(float));
const cl_uint sv2 = (cl_uint)(src_v->nb[2] / sizeof(float));
const cl_uint sv3 = (cl_uint)(src_v->nb[3] / sizeof(float));
@@ -40567,6 +40717,9 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) {
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq1));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq2));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq3));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk1));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk2));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk3));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv1));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv2));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv3));
@@ -40576,7 +40729,59 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) {
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &H_k));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &rq3));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(float), &scale));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &K));
if (replay) {
const ggml_tensor * src_pk = dst->src[6];
const ggml_tensor * src_pv = dst->src[7];
const ggml_tensor * src_pgb = dst->src[8];
const ggml_tensor * src_rep = dst->src[9];
GGML_ASSERT(src_pk && src_pk->extra);
GGML_ASSERT(src_pv && src_pv->extra);
GGML_ASSERT(src_pgb && src_pgb->extra);
GGML_ASSERT(src_rep && src_rep->extra);
const ggml_tensor_extra_cl * extra_pk = (const ggml_tensor_extra_cl *) src_pk->extra;
const ggml_tensor_extra_cl * extra_pv = (const ggml_tensor_extra_cl *) src_pv->extra;
const ggml_tensor_extra_cl * extra_pgb = (const ggml_tensor_extra_cl *) src_pgb->extra;
const ggml_tensor_extra_cl * extra_rep = (const ggml_tensor_extra_cl *) src_rep->extra;
const cl_ulong off_pk = extra_pk->offset + src_pk->view_offs;
const cl_ulong off_pv = extra_pv->offset + src_pv->view_offs;
const cl_ulong off_pgb = extra_pgb->offset + src_pgb->view_offs;
const cl_ulong off_rep = extra_rep->offset + src_rep->view_offs;
const cl_ulong spk1 = src_pk->nb[1] / sizeof(float);
const cl_ulong spk2 = src_pk->nb[2] / sizeof(float);
const cl_ulong spk3 = src_pk->nb[3] / sizeof(float);
const cl_ulong spv1 = src_pv->nb[1] / sizeof(float);
const cl_ulong spv2 = src_pv->nb[2] / sizeof(float);
const cl_ulong spv3 = src_pv->nb[3] / sizeof(float);
const cl_ulong spg1 = src_pgb->nb[1] / sizeof(float);
const cl_ulong spg2 = src_pgb->nb[2] / sizeof(float);
const cl_ulong spg3 = src_pgb->nb[3] / sizeof(float);
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &n_pend));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &keep));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pk->data_device));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pk));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk1));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk2));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk3));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pv->data_device));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pv));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv1));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv2));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv3));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pgb->data_device));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pgb));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg1));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg2));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg3));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_rep->data_device));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_rep));
}
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &K));
// Subgroup size is 64 for Adreno and 32 for Intel
const int sg_size = backend_ctx->gpu_family == GPU_FAMILY::ADRENO ? 64 : backend_ctx->gpu_family == GPU_FAMILY::INTEL ? 32 : -1;
@@ -18,6 +18,9 @@
#ifndef KDA
#define KDA 0
#endif
#ifndef REPLAY
#define REPLAY 0
#endif
#ifndef SUBGROUP_SIZE
#define SUBGROUP_SIZE 64
#endif
@@ -92,11 +95,19 @@ kernel void kernel_gated_delta_net(
uint n_seqs,
uint s_off,
uint sq1, uint sq2, uint sq3,
uint sk1, uint sk2, uint sk3,
uint sv1, uint sv2, uint sv3,
uint sb1, uint sb2, uint sb3,
uint H_k,
uint rq3,
float scale,
#if REPLAY
uint n_pend, uint keep,
global const char * pk_buf, ulong off_pk, ulong spk1, ulong spk2, ulong spk3,
global const char * pv_buf, ulong off_pv, ulong spv1, ulong spv2, ulong spv3,
global const char * pgb_buf, ulong off_pgb, ulong spg1, ulong spg2, ulong spg3,
global const char * rep_buf, ulong off_rep,
#endif
uint K) {
global const float * data_q = (global const float *)(q_buf + off_q);
@@ -126,6 +137,7 @@ kernel void kernel_gated_delta_net(
// input state holds s0 only [S_v, S_v, H, n_seqs]: per-seq stride is H*D.
const uint state_base = (seq_id * H_v + head_id) * state_size;
const uint q_off_base = iq3 * sq3 + iq1 * sq1;
const uint k_off_base = iq3 * sk3 + iq1 * sk1;
const uint v_off_base = seq_id * sv3 + head_id * sv1;
const uint gb_off_base = seq_id * sb3 + head_id * sb1;
const uint state_out_base = (seq_id * H_v + head_id) * state_size;
@@ -144,13 +156,84 @@ kernel void kernel_gated_delta_net(
}
}
#if REPLAY
global const float * data_pk = (global const float *)(pk_buf + off_pk);
global const float * data_pv = (global const float *)(pv_buf + off_pv);
global const float * data_pgb = (global const float *)(pgb_buf + off_pgb);
global const int * data_n_rep = (global const int *)(rep_buf + off_rep);
const uint n_r = (uint)clamp(data_n_rep[seq_id], 0, (int)n_pend);
for (uint t = 0; t < n_r; t++) {
const ulong k_off = seq_id * spk3 + t * spk2 + iq1 * spk1;
const ulong v_off = seq_id * spv3 + t * spv2 + head_id * spv1;
const ulong g_off = seq_id * spg3 + t * spg2 + head_id * spg1;
const float beta_val = data_pgb[g_off + n_pend * spg2];
float k_reg[ROWS_PER_LANE];
#pragma unroll
for (uint r = 0; r < ROWS_PER_LANE; r++) {
k_reg[r] = data_pk[k_off + r * LANES_PER_COLUMN + lane];
}
#if KDA
float g_exp[ROWS_PER_LANE];
#pragma unroll
for (uint r = 0; r < ROWS_PER_LANE; r++) {
g_exp[r] = exp(data_pgb[g_off + r * LANES_PER_COLUMN + lane]);
}
#else
const float g_val = exp(data_pgb[g_off]);
#endif
// Same state update as the main loop, without the attention output.
#pragma unroll
for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) {
const uint col = sg_col_base + cg * LANE_GROUPS_PER_SG + lane_group;
float kv_shard = 0.0f;
#pragma unroll
for (uint r = 0; r < ROWS_PER_LANE; r++) {
#if KDA
kv_shard += g_exp[r] * s_shard[cg][r] * k_reg[r];
#else
kv_shard += s_shard[cg][r] * k_reg[r];
#endif
}
#if !KDA
kv_shard *= g_val;
#endif
const float kv_col = REDUCE_PARTIAL(kv_shard, temp_ptr, sg_lid);
const float delta_col = (data_pv[v_off + col] - kv_col) * beta_val;
#pragma unroll
for (uint r = 0; r < ROWS_PER_LANE; r++) {
#if KDA
const float gs = g_exp[r] * s_shard[cg][r];
#else
const float gs = g_val * s_shard[cg][r];
#endif
s_shard[cg][r] = gs + k_reg[r] * delta_col;
}
}
}
if (keep) {
#pragma unroll
for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) {
const uint col = sg_col_base + cg * LANE_GROUPS_PER_SG + lane_group;
#pragma unroll
for (uint r = 0; r < ROWS_PER_LANE; r++) {
data_dst[s_off + state_base + col * S_V + r * LANES_PER_COLUMN + lane] = s_shard[cg][r];
}
}
}
#endif
// snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back.
// When n_tokens < K only slots 0..n_tokens-1 are written; older slots are caller-owned.
uint attn_off = (seq_id * n_tokens * H_v + head_id) * S_V;
for (uint t = 0; t < n_tokens; t++) {
const uint q_off = q_off_base + t * sq2;
const uint k_off = q_off;
const uint k_off = k_off_base + t * sk2;
const uint v_off = v_off_base + t * sv2;
const uint gb_off = gb_off_base + t * sb2;
const float beta_val = data_beta[gb_off];
@@ -236,6 +319,11 @@ kernel void kernel_gated_delta_net(
}
}
#if REPLAY
if (keep) {
return;
}
#endif
if (K == 1u) {
#pragma unroll
for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) {
@@ -0,0 +1,214 @@
#pragma OPENCL EXTENSION cl_khr_fp16 : enable
#ifdef cl_khr_integer_dot_product
#pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable
#endif
#ifndef COOPK_NSG
#define COOPK_NSG 4
#endif
#define COK_SG 64
#define COK_ROWS 4
#define COK_PACK4(a, b, c, e) \
( ((uint)(a) & 0xFFu) | (((uint)(b) & 0xFFu) << 8) \
| (((uint)(c) & 0xFFu) << 16) | (((uint)(e) & 0xFFu) << 24) )
// Pack (0, 2, 1, 3) K bytes and store scales plus both 16-value sums at width eight.
kernel void kernel_quant_a_q8_1_k4h(
global const float * src,
global uint * qa,
global half * ds,
ulong offset_src,
int total_blocks,
int k_b
) {
const int blk = get_global_id(0);
if (blk >= 8 * k_b) {
return;
}
const int col = blk / k_b;
const int b = blk % k_b;
if (blk >= total_blocks) {
vstore8((uint8)(0), 0, qa + blk * 8);
ds[(3 * b) * 8 + col] = (half)0;
ds[(3 * b + 1) * 8 + col] = (half)0;
ds[(3 * b + 2) * 8 + col] = (half)0;
return;
}
src = (global const float *)((global const char *)src + offset_src);
const int base = blk * 32;
float v[32];
float amax = 0.0f;
#pragma unroll
for (int i = 0; i < 32; ++i) {
v[i] = src[base + i];
amax = fmax(amax, fabs(v[i]));
}
const float d = amax / 127.0f;
const float id = (amax > 0.0f) ? (127.0f / amax) : 0.0f;
int q[32];
int sum_lo = 0, sum_hi = 0;
#pragma unroll
for (int i = 0; i < 16; ++i) {
q[i] = (int)rint(v[i] * id);
sum_lo += q[i];
}
#pragma unroll
for (int i = 16; i < 32; ++i) {
q[i] = (int)rint(v[i] * id);
sum_hi += q[i];
}
uint8 out;
out.s0 = COK_PACK4(q[ 0], q[ 2], q[ 1], q[ 3]);
out.s1 = COK_PACK4(q[ 4], q[ 6], q[ 5], q[ 7]);
out.s2 = COK_PACK4(q[ 8], q[10], q[ 9], q[11]);
out.s3 = COK_PACK4(q[12], q[14], q[13], q[15]);
out.s4 = COK_PACK4(q[16], q[18], q[17], q[19]);
out.s5 = COK_PACK4(q[20], q[22], q[21], q[23]);
out.s6 = COK_PACK4(q[24], q[26], q[25], q[27]);
out.s7 = COK_PACK4(q[28], q[30], q[29], q[31]);
vstore8(out, 0, qa + blk * 8);
ds[(3 * b) * 8 + col] = (half)d;
ds[(3 * b + 1) * 8 + col] = (half)(d * (float)sum_lo);
ds[(3 * b + 2) * 8 + col] = (half)(d * (float)sum_hi);
}
// Cast before shifting to keep all four K values on Adreno compilers.
#define COK_LO(u) (((uint)(u) | ((uint)(ushort)((u) >> 4) << 16)) & 0x0F0F0F0Fu)
#define COK_HI(h) ((((((uint)(h)) & 0x33u) * 0x110u) & 0x3030u) | (((((uint)(h)) & 0xCCu) * 0x440000u) & 0x30300000u))
#define COK_UNPACK(r) \
const uint w0_##r = COK_LO(bl0.s##r) | COK_HI(bh0.s##r); \
const uint w1_##r = COK_LO(bl1.s##r) | COK_HI(bh1.s##r); \
const uint w2_##r = COK_LO(bl2.s##r) | COK_HI(bh2.s##r); \
const uint w3_##r = COK_LO(bl3.s##r) | COK_HI(bh3.s##r);
#define COK_DOT_RC(r, c) \
d##r.s##c = dot_acc_sat_4x8packed_ss_int(w0_##r, A.s0, d##r.s##c); \
d##r.s##c = dot_acc_sat_4x8packed_ss_int(w1_##r, A.s1, d##r.s##c); \
d##r.s##c = dot_acc_sat_4x8packed_ss_int(w2_##r, A.s2, d##r.s##c); \
d##r.s##c = dot_acc_sat_4x8packed_ss_int(w3_##r, A.s3, d##r.s##c);
#define COK_DOT_COL(c, t) \
{ const uint4 A = read_imageui(src1_qa, (c) * k_t + (t)); \
COK_DOT_RC(0, c) COK_DOT_RC(1, c) COK_DOT_RC(2, c) COK_DOT_RC(3, c) }
kernel void kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8(
global const uint * src0_ql,
global const uint * src0_qh,
global const ushort * src0_s,
global const half * src0_d,
read_only image1d_buffer_t src1_qa,
read_only image1d_buffer_t src1_ds,
global float * dst,
ulong offsetd,
int m,
int k,
int n_no_padding,
uchar mask_c0,
int ksplit
) {
dst = (global float *)((global char *)dst + offsetd);
const int gx = get_global_id(0);
const int sg = get_local_id(1);
const int lane = get_local_id(0);
const int ks = get_group_id(1);
const bool live = gx * COK_ROWS < m;
const int row0 = live ? gx * COK_ROWS : m - COK_ROWS;
const int num_32blk = k / 32;
const int k_t = k >> 4;
const int fence = (int)(mask_c0 >> 6) - 3;
const int nslice = ksplit * COOPK_NSG;
const int b_beg = ks * COOPK_NSG + sg;
float8 acc0 = (float8)(0.0f), acc1 = (float8)(0.0f);
float8 acc2 = (float8)(0.0f), acc3 = (float8)(0.0f);
for (int bg = b_beg; bg * 8 < num_32blk; bg += nslice) {
ushort8 sr0 = vload8(0, src0_s + (row0 + 0) * num_32blk + bg * 8);
ushort8 sr1 = vload8(0, src0_s + (row0 + 1) * num_32blk + bg * 8);
ushort8 sr2 = vload8(0, src0_s + (row0 + 2) * num_32blk + bg * 8);
ushort8 sr3 = vload8(0, src0_s + (row0 + 3) * num_32blk + bg * 8);
for (int jb = 0; jb < 8; ++jb) {
const int blk = bg * 8 + jb;
const ushort4 spk = (ushort4)(sr0.s0, sr1.s0, sr2.s0, sr3.s0);
sr0 = sr0.s12345670; sr1 = sr1.s12345670; sr2 = sr2.s12345670; sr3 = sr3.s12345670;
const half4 scd = vload4(0, src0_d + row0 + (blk >> 3) * m);
const float8 da = convert_float8(as_half8(read_imageui(src1_ds, 3 * blk)));
for (int h = 0; h < 2; ++h) {
const int g0 = (blk << 3) + (h << 2);
const int at = (blk << 1) + h;
const uint4 l01 = vload4(0, src0_ql + row0 + ((g0 >> 1) ) * m);
const uint4 l23 = vload4(0, src0_ql + row0 + ((g0 >> 1) + 1) * m);
const uint4 hq = vload4(0, src0_qh + row0 + (g0 >> 2) * m);
const ushort4 bl0 = (ushort4)((ushort)l01.s0, (ushort)l01.s1, (ushort)l01.s2, (ushort)l01.s3);
const ushort4 bl1 = (ushort4)((ushort)(l01.s0 >> 16), (ushort)(l01.s1 >> 16), (ushort)(l01.s2 >> 16), (ushort)(l01.s3 >> 16));
const ushort4 bl2 = (ushort4)((ushort)l23.s0, (ushort)l23.s1, (ushort)l23.s2, (ushort)l23.s3);
const ushort4 bl3 = (ushort4)((ushort)(l23.s0 >> 16), (ushort)(l23.s1 >> 16), (ushort)(l23.s2 >> 16), (ushort)(l23.s3 >> 16));
const uchar4 bh0 = (uchar4)((uchar)hq.s0, (uchar)hq.s1, (uchar)hq.s2, (uchar)hq.s3);
const uchar4 bh1 = (uchar4)((uchar)(hq.s0 >> 8), (uchar)(hq.s1 >> 8), (uchar)(hq.s2 >> 8), (uchar)(hq.s3 >> 8));
const uchar4 bh2 = (uchar4)((uchar)(hq.s0 >> 16), (uchar)(hq.s1 >> 16), (uchar)(hq.s2 >> 16), (uchar)(hq.s3 >> 16));
const uchar4 bh3 = (uchar4)((uchar)(hq.s0 >> 24), (uchar)(hq.s1 >> 24), (uchar)(hq.s2 >> 24), (uchar)(hq.s3 >> 24));
COK_UNPACK(0) COK_UNPACK(1) COK_UNPACK(2) COK_UNPACK(3)
int8 d0 = (int8)(0), d1 = (int8)(0), d2 = (int8)(0), d3 = (int8)(0);
COK_DOT_COL(0, at) COK_DOT_COL(1, at) COK_DOT_COL(2, at) COK_DOT_COL(3, at)
const int at4 = at + (d0.s0 & fence);
COK_DOT_COL(4, at4) COK_DOT_COL(5, at4) COK_DOT_COL(6, at4) COK_DOT_COL(7, at4)
const float8 sa = convert_float8(as_half8(read_imageui(src1_ds, 3 * blk + 1 + h)));
// Apply the signed-code offset with the sum for this 16-value half.
const float8 sm = sa * -32.0f;
const float s0f = (float)(h ? as_char2(spk.s0).s1 : as_char2(spk.s0).s0) * (float)scd.s0;
const float s1f = (float)(h ? as_char2(spk.s1).s1 : as_char2(spk.s1).s0) * (float)scd.s1;
const float s2f = (float)(h ? as_char2(spk.s2).s1 : as_char2(spk.s2).s0) * (float)scd.s2;
const float s3f = (float)(h ? as_char2(spk.s3).s1 : as_char2(spk.s3).s0) * (float)scd.s3;
acc0 = mad(mad(da, convert_float8(d0), sm), s0f, acc0);
acc1 = mad(mad(da, convert_float8(d1), sm), s1f, acc1);
acc2 = mad(mad(da, convert_float8(d2), sm), s2f, acc2);
acc3 = mad(mad(da, convert_float8(d3), sm), s3f, acc3);
}
}
}
local float8 reduceLM[COK_SG * (COOPK_NSG - 1)];
float8 out0 = (float8)(0.0f), out1 = (float8)(0.0f);
float8 out2 = (float8)(0.0f), out3 = (float8)(0.0f);
#define COK_REDUCE(accv, outv) \
barrier(CLK_LOCAL_MEM_FENCE); \
if (sg > 0) { reduceLM[(sg - 1) * COK_SG + lane] = (accv); } \
barrier(CLK_LOCAL_MEM_FENCE); \
if (sg == 0) { \
float8 sum = (accv); \
for (int s = 0; s < COOPK_NSG - 1; s++) { sum += reduceLM[s * COK_SG + lane]; } \
(outv) = sum; \
}
COK_REDUCE(acc0, out0)
COK_REDUCE(acc1, out1)
COK_REDUCE(acc2, out2)
COK_REDUCE(acc3, out3)
#undef COK_REDUCE
#define COK_STORE_COL(c) \
if ((c) < n_no_padding) { \
vstore4((float4)(out0.s##c, out1.s##c, out2.s##c, out3.s##c), 0, dst + (c) * m + row0); \
}
if (sg == 0 && live) {
dst += (size_t)ks * (size_t)m * (size_t)n_no_padding;
COK_STORE_COL(0) COK_STORE_COL(1) COK_STORE_COL(2) COK_STORE_COL(3)
COK_STORE_COL(4) COK_STORE_COL(5) COK_STORE_COL(6) COK_STORE_COL(7)
}
#undef COK_STORE_COL
}
+46 -6
View File
@@ -4,6 +4,46 @@
// softplus
//------------------------------------------------------------------------------
inline float op_log1p(float x) {
const float y = x / (2.0f + x);
const float y2 = y * y;
float p = 1.0f / 13.0f;
p = p * y2 + 1.0f / 11.0f;
p = p * y2 + 1.0f / 9.0f;
p = p * y2 + 1.0f / 7.0f;
p = p * y2 + 1.0f / 5.0f;
p = p * y2 + 1.0f / 3.0f;
p = p * y2 + 1.0f;
const float s = 2.0f * y * p;
const float l = log(1.0f + x);
const float r = select(l, s, (x >= -0.5f) & (x <= 1.0f));
return select(r, x, fabs(x) < 2.5e-38f);
}
inline float4 op_log1p4(float4 x) {
const float4 y = x / ((float4)(2.0f) + x);
const float4 y2 = y * y;
float4 p = (float4)(1.0f / 13.0f);
p = p * y2 + (float4)(1.0f / 11.0f);
p = p * y2 + (float4)(1.0f / 9.0f);
p = p * y2 + (float4)(1.0f / 7.0f);
p = p * y2 + (float4)(1.0f / 5.0f);
p = p * y2 + (float4)(1.0f / 3.0f);
p = p * y2 + (float4)(1.0f);
const float4 s = (float4)(2.0f) * y * p;
const float4 l = log((float4)(1.0f) + x);
const float4 r = select(l, s, (x >= (float4)(-0.5f)) & (x <= (float4)(1.0f)));
return select(r, x, fabs(x) < (float4)(2.5e-38f));
}
inline float softplus_f32(float x) {
return select(op_log1p(exp(x)), x, x > 20.0f);
}
inline float4 softplus_f32_4(float4 x) {
return select(op_log1p4(exp(x)), x, x > (float4)(20.0f));
}
kernel void kernel_softplus_f32(
global const float * src0,
ulong offset0,
@@ -13,7 +53,7 @@ kernel void kernel_softplus_f32(
src0 = (global float*)((global char*)src0 + offset0);
dst = (global float*)((global char*)dst + offsetd);
dst[get_global_id(0)] = (src0[get_global_id(0)] > 20.0f) ? src0[get_global_id(0)] : log(1.0f + exp(src0[get_global_id(0)]));
dst[get_global_id(0)] = softplus_f32(src0[get_global_id(0)]);
}
kernel void kernel_softplus_f32_4(
@@ -25,7 +65,7 @@ kernel void kernel_softplus_f32_4(
src0 = (global float4*)((global char*)src0 + offset0);
dst = (global float4*)((global char*)dst + offsetd);
dst[get_global_id(0)] = (src0[get_global_id(0)] > 20.0f) ? src0[get_global_id(0)] : log(1.0f + exp(src0[get_global_id(0)]));
dst[get_global_id(0)] = softplus_f32_4(src0[get_global_id(0)]);
}
kernel void kernel_softplus_f16(
@@ -38,7 +78,7 @@ kernel void kernel_softplus_f16(
dst = (global half*)((global char*)dst + offsetd);
const float x = convert_float(src0[get_global_id(0)]);
dst[get_global_id(0)] = convert_half_rte((x > 20.0f) ? x : log(1.0f + exp(x)));
dst[get_global_id(0)] = convert_half_rte(softplus_f32(x));
}
kernel void kernel_softplus_f16_4(
@@ -51,7 +91,7 @@ kernel void kernel_softplus_f16_4(
dst = (global half4*)((global char*)dst + offsetd);
const float4 x = convert_float4(src0[get_global_id(0)]);
dst[get_global_id(0)] = convert_half4_rte((x > 20.0f) ? x : log(1.0f + exp(x)));
dst[get_global_id(0)] = convert_half4_rte(softplus_f32_4(x));
}
kernel void kernel_softplus_f32_nc(
@@ -80,7 +120,7 @@ kernel void kernel_softplus_f32_nc(
global const float * x = (global const float *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
global float * y = (global float *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
*y = (*x > 20.0f) ? *x : log(1.0f + exp(*x));
*y = softplus_f32(*x);
}
}
@@ -111,6 +151,6 @@ kernel void kernel_softplus_f16_nc(
global half * hy = (global half *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
const float x = convert_float(*hx);
*hy = convert_half_rte((x > 20.0f) ? x : log(1.0f + exp(x)));
*hy = convert_half_rte(softplus_f32(x));
}
}
+7
View File
@@ -1929,6 +1929,10 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
return {false, "FLASH_ATTN_EXT gemma3n pattern is not supported"};
}
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
return {false, "FLASH_ATTN_EXT with indexed bias is not supported"};
}
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
if (op->src[5] != nullptr) {
return {false, "FLASH_ATTN_EXT with K/V row lists is not supported"};
@@ -2109,6 +2113,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
}
return {false, reason};
}
if (((const int32_t *) op->op_params)[1] != 0) {
return {false, "GATED_DELTA_NET with replay of pending tokens is not supported"};
}
break;
}
case GGML_OP_SSM_SCAN: {
+35 -98
View File
@@ -1561,6 +1561,13 @@ public:
: backends(std::move(all_backends)), cache_dir(cache_dir) {
stored_graphs.resize(backends.size());
comm_states.resize(backends.size());
ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead()*(1 + GGML_MAX_SRC),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
req_ctx.reset(ggml_init(params));
GGML_ASSERT(req_ctx != nullptr);
}
~rpc_server();
@@ -1593,6 +1600,16 @@ public:
};
private:
// empty context for the tensors of one request, valid until the next call
ggml_context * request_ctx() {
ggml_reset(req_ctx.get());
return req_ctx.get();
}
// nullptr if the buffer was not allocated by this server
ggml_backend_buffer_t find_buffer(uint64_t remote_ptr) const {
ggml_backend_buffer_t buffer = reinterpret_cast<ggml_backend_buffer_t>(remote_ptr);
return buffers.find(buffer) != buffers.end() ? buffer : nullptr;
}
void sync_all_backends();
void comm_free_device(uint32_t dev_id);
static bool comm_allreduce_pairwise(void * comm_ctx_v, ggml_tensor ** tensors);
@@ -1631,6 +1648,7 @@ private:
std::vector<comm_state> comm_states;
// SET_TENSOR data is received in chunks through this buffer
std::vector<uint8_t> set_tensor_buf;
ggml_context_ptr req_ctx;
};
void rpc_server::hello(rpc_msg_hello_rsp & response) {
@@ -1647,15 +1665,7 @@ bool rpc_server::get_alloc_size(const rpc_msg_get_alloc_size_req & request, rpc_
return false;
}
ggml_backend_buffer_type_t buft;
struct ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead()*(1 + GGML_MAX_SRC),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_context * ctx = request_ctx();
ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor);
if (tensor == nullptr) {
@@ -1733,8 +1743,8 @@ bool rpc_server::get_max_size(const rpc_msg_get_max_size_req & request, rpc_msg_
bool rpc_server::buffer_get_base(const rpc_msg_buffer_get_base_req & request, rpc_msg_buffer_get_base_rsp & response) {
LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 "\n", __func__, request.remote_ptr);
ggml_backend_buffer_t buffer = reinterpret_cast<ggml_backend_buffer_t>(request.remote_ptr);
if (buffers.find(buffer) == buffers.end()) {
ggml_backend_buffer_t buffer = find_buffer(request.remote_ptr);
if (buffer == nullptr) {
LOG_ERROR("[%s] buffer not found\n", __func__);
return false;
}
@@ -1746,8 +1756,8 @@ bool rpc_server::buffer_get_base(const rpc_msg_buffer_get_base_req & request, rp
bool rpc_server::free_buffer(const rpc_msg_free_buffer_req & request) {
sync_all_backends();
LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 "\n", __func__, request.remote_ptr);
ggml_backend_buffer_t buffer = reinterpret_cast<ggml_backend_buffer_t>(request.remote_ptr);
if (buffers.find(buffer) == buffers.end()) {
ggml_backend_buffer_t buffer = find_buffer(request.remote_ptr);
if (buffer == nullptr) {
LOG_ERROR("[%s] buffer not found\n", __func__);
return false;
}
@@ -1767,8 +1777,8 @@ bool rpc_server::free_buffer(const rpc_msg_free_buffer_req & request) {
bool rpc_server::buffer_clear(const rpc_msg_buffer_clear_req & request) {
sync_all_backends();
LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 ", value: %u\n", __func__, request.remote_ptr, request.value);
ggml_backend_buffer_t buffer = reinterpret_cast<ggml_backend_buffer_t>(request.remote_ptr);
if (buffers.find(buffer) == buffers.end()) {
ggml_backend_buffer_t buffer = find_buffer(request.remote_ptr);
if (buffer == nullptr) {
LOG_ERROR("[%s] buffer not found\n", __func__);
return false;
}
@@ -1778,15 +1788,7 @@ bool rpc_server::buffer_clear(const rpc_msg_buffer_clear_req & request) {
bool rpc_server::memset_tensor(const rpc_msg_memset_tensor_req & request) {
sync_all_backends();
struct ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor);
ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor);
if (!rpc_check_region(__func__, tensor, request.offset, request.size)) {
return false;
}
@@ -1830,10 +1832,7 @@ ggml_tensor * rpc_server::deserialize_tensor(struct ggml_context * ctx, const rp
return nullptr;
}
ggml_backend_buffer_t buffer = reinterpret_cast<ggml_backend_buffer_t>(tensor->buffer);
if (buffer && buffers.find(buffer) == buffers.end()) {
buffer = nullptr;
}
ggml_backend_buffer_t buffer = find_buffer(tensor->buffer);
if (buffer && nbytes > 0 && !rpc_in_buffer(buffer, tensor->data, nbytes)) {
LOG_ERROR("[%s] tensor '%.*s' (op %s, type %s) data 0x%" PRIx64 " with size %" PRIu64 " out of buffer bounds "
"(base %p, size %zu)\n", __func__, (int) sizeof(tensor->name), tensor->name, ggml_op_name((ggml_op) tensor->op),
@@ -1868,15 +1867,7 @@ bool rpc_server::set_tensor(socket_ptr sock, uint64_t input_size) {
const uint64_t offset = request.offset;
const size_t size = input_size - sizeof(request);
struct ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor);
ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor);
if (!rpc_check_region(__func__, tensor, offset, size)) {
return false;
}
@@ -1927,15 +1918,7 @@ bool rpc_server::set_tensor_2d(const std::vector<uint8_t> & input) {
return false;
}
struct ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor);
ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor);
if (!rpc_check_region(__func__, tensor, request.offset, request.size, request.n_copies, request.stride)) {
return false;
}
@@ -1975,15 +1958,7 @@ bool rpc_server::get_cached_file(uint64_t hash, std::vector<uint8_t> & data) {
bool rpc_server::set_tensor_hash(const rpc_msg_set_tensor_hash_req & request, rpc_msg_set_tensor_hash_rsp & response)
{
sync_all_backends();
struct ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor);
ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor);
if (!rpc_check_region(__func__, tensor, request.offset, 0)) {
return false;
}
@@ -2010,15 +1985,7 @@ bool rpc_server::set_tensor_hash(const rpc_msg_set_tensor_hash_req & request, rp
bool rpc_server::init_tensor(const rpc_msg_init_tensor_req & request) {
sync_all_backends();
struct ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor);
ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor);
if (tensor == nullptr) {
LOG_ERROR("Null tensor pointer passed to server init_tensor function.\n");
return false;
@@ -2047,15 +2014,7 @@ bool rpc_server::init_tensor(const rpc_msg_init_tensor_req & request) {
bool rpc_server::get_tensor(const rpc_msg_get_tensor_req & request, std::vector<uint8_t> & response) {
sync_all_backends();
struct ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor);
ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor);
if (!rpc_check_region(__func__, tensor, request.offset, request.size)) {
return false;
}
@@ -2070,15 +2029,7 @@ bool rpc_server::get_tensor(const rpc_msg_get_tensor_req & request, std::vector<
bool rpc_server::get_tensor_2d(const rpc_msg_tensor_2d_req & request, std::vector<uint8_t> & response) {
sync_all_backends();
struct ggml_init_params params {
/*.mem_size =*/ ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor);
ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor);
if (!rpc_check_region(__func__, tensor, request.offset, request.size, request.n_copies, request.stride)) {
return false;
}
@@ -2093,14 +2044,7 @@ bool rpc_server::get_tensor_2d(const rpc_msg_tensor_2d_req & request, std::vecto
bool rpc_server::copy_tensor(const rpc_msg_copy_tensor_req & request, rpc_msg_copy_tensor_rsp & response) {
sync_all_backends();
struct ggml_init_params params {
/*.mem_size =*/ 2*ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_context * ctx = ctx_ptr.get();
ggml_context * ctx = request_ctx();
ggml_tensor * src = deserialize_tensor(ctx, &request.src);
ggml_tensor * dst = deserialize_tensor(ctx, &request.dst);
@@ -2559,14 +2503,7 @@ bool rpc_server::comm_allreduce(const rpc_msg_comm_allreduce_req & request) {
return false;
}
struct ggml_init_params params = {
/*.mem_size =*/ ggml_tensor_overhead(),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
ggml_context_ptr ctx_ptr { ggml_init(params) };
GGML_ASSERT(ctx_ptr != nullptr);
ggml_tensor * t_dst = deserialize_tensor(ctx_ptr.get(), &request.tensor);
ggml_tensor * t_dst = deserialize_tensor(request_ctx(), &request.tensor);
if (t_dst == nullptr || t_dst->buffer == nullptr) {
LOG_ERROR("[%s] error deserializing tensor\n", __func__);
return false;
+5 -3
View File
@@ -7709,10 +7709,12 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons
case GGML_OP_RWKV_WKV6:
case GGML_OP_RWKV_WKV7:
case GGML_OP_GATED_LINEAR_ATTN:
case GGML_OP_GATED_DELTA_NET:
case GGML_OP_OPT_STEP_ADAMW:
case GGML_OP_OPT_STEP_SGD:
return true;
case GGML_OP_GATED_DELTA_NET:
// replay of pending tokens (op param 1) is not implemented
return ggml_get_op_params_i32(op, 1) == 0;
case GGML_OP_SSM_CONV:
return op->type == GGML_TYPE_F32 &&
op->src[0]->type == GGML_TYPE_F32 &&
@@ -7741,8 +7743,8 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons
case GGML_OP_SOLVE_TRI:
return op->src[0]->ne[0] <= SYCL_SOLVE_TRI_MAX_N && op->src[1]->ne[0] <= SYCL_SOLVE_TRI_MAX_K;
case GGML_OP_FLASH_ATTN_EXT:
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
return op->src[5] == nullptr && ggml_sycl_flash_attn_ext_supported(device, op);
// K/V row lists and indexed bias are not supported
return op->src[5] == nullptr && !ggml_flash_attn_ext_has_indexed_bias(op) && ggml_sycl_flash_attn_ext_supported(device, op);
default:
return false;
}
@@ -30,6 +30,10 @@ static void ggml_backend_remoting_device_get_memory(ggml_backend_dev_t dev, size
}
static bool ggml_backend_remoting_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
if ((op->op == GGML_OP_ROPE || op->op == GGML_OP_ROPE_BACK) &&
!ggml_rope_get_truncate(op)) {
return false;
+4 -3
View File
@@ -1370,9 +1370,10 @@ void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph
} else if (tensor->op == GGML_OP_LIGHTNING_INDEXER) {
tensor_clone = ggml_lightning_indexer(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3]);
} else if (tensor->op == GGML_OP_GATED_DELTA_NET) {
tensor_clone = ggml_gated_delta_net(ggml_ctx, src_clone[0], src_clone[1],
src_clone[2], src_clone[3], src_clone[4], src_clone[5],
ggml_get_op_params_i32(tensor, 0));
GGML_ASSERT(ggml_get_op_params_i32(tensor, 0) == 1); // K > 1 comes from the deprecated ggml_gated_delta_net
tensor_clone = ggml_gated_delta_net_ext(ggml_ctx, src_clone[0], src_clone[1],
src_clone[2], src_clone[3], src_clone[4], src_clone[5], src_clone[6], src_clone[7], src_clone[8], src_clone[9],
ggml_get_op_params_i32(tensor, 2) != 0);
} else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
src_clone[0]->flags = tensor->src[0]->flags;
tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
@@ -794,6 +794,10 @@ struct vk_op_gated_delta_net_push_constants {
uint32_t neq1, rq3;
float scale;
uint32_t K;
uint32_t n_pend, keep; // replay: pending tokens per seq, write the state after the replay
uint32_t spk1, spk2, spk3; // replay: pend_k, pend_v and pend_gb strides in floats
uint32_t spv1, spv2, spv3;
uint32_t spg1, spg2, spg3;
};
struct vk_op_ssm_scan_push_constants {
+3 -2
View File
@@ -1013,11 +1013,12 @@ struct vk_device_struct {
vk_pipeline pipeline_rwkv_wkv7_f32;
vk_pipeline pipeline_gated_linear_attn_f32;
vk_pipeline pipeline_lightning_indexer_f32[GGML_TYPE_COUNT];
// [size_idx][kda] where size_idx: 0=d16, 1=d32, 2=d64, 3=d128
vk_pipeline pipeline_gated_delta_net[4][2];
// [size_idx][kda][replay] where size_idx: 0=d16, 1=d32, 2=d64, 3=d128
vk_pipeline pipeline_gated_delta_net[4][2][2];
vk_pipeline pipeline_gated_delta_net_cm;
vk_pipeline pipeline_gated_delta_net_cm_v32;
vk_pipeline pipeline_gated_delta_net_cm_v128;
vk_pipeline pipeline_ssm_scan_f32_d96;
vk_pipeline pipeline_ssm_scan_f32_d128;
vk_pipeline pipeline_ssm_scan_f32_d256;
vk_pipeline pipeline_ssm_conv_f32;
+55 -23
View File
@@ -4212,9 +4212,12 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
const std::array<uint32_t, 3> wg_denoms = {1u, 1u, cols_per_wg};
for (uint32_t kda = 0; kda < 2; kda++) {
ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net[si][kda],
gdn_names[si][kda], gdn_len, gdn_data, "main", 7, sizeof(vk_op_gated_delta_net_push_constants),
wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column, uint32_t(gdn_packed_rows)}, 1, true, use_subgroup_ops, gdn_subgroup_size);
for (uint32_t rep = 0; rep < 2; rep++) {
const std::string name = std::string(gdn_names[si][kda]) + (rep ? "_rep" : "");
ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net[si][kda][rep],
name.c_str(), gdn_len, gdn_data, "main", 11, sizeof(vk_op_gated_delta_net_push_constants),
wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column, uint32_t(gdn_packed_rows), rep}, 1, true, use_subgroup_ops, gdn_subgroup_size);
}
}
}
@@ -4270,12 +4273,15 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
GGML_UNUSED(gdn_shmem);
}
// Pad 96 states to a 128-thread workgroup for 32- and 64-lane subgroups.
if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size}, 1, true, true);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size}, 1, true, true);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d96, "ssm_scan_96_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 96}, 1, true, true);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 128}, 1, true, true);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 256}, 1, true, true);
} else {
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 16}, 1, true, true);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 16}, 1, true, true);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d96, "ssm_scan_96_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 96}, 1, true, true);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 128}, 1, true, true);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 256}, 1, true, true);
}
ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_f32, "ssm_conv_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 0, 0}, 1);
@@ -10235,6 +10241,7 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const
if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
const uint32_t S_v = dst->src[2]->ne[0];
const uint32_t kda = (dst->src[3]->ne[0] == (int64_t)S_v) ? 1 : 0;
const uint32_t rep = dst->src[6] != nullptr ? 1 : 0;
uint32_t si;
switch (S_v) {
case 16: si = 0; break;
@@ -10243,13 +10250,15 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const
case 128: si = 3; break;
default: return nullptr;
}
return ctx->device->pipeline_gated_delta_net[si][kda];
return ctx->device->pipeline_gated_delta_net[si][kda][rep];
}
return nullptr;
case GGML_OP_SSM_SCAN:
if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
const uint32_t d_state = src0->ne[0];
if (d_state == 128) {
if (d_state == 96) {
return ctx->device->pipeline_ssm_scan_f32_d96;
} else if (d_state == 128) {
return ctx->device->pipeline_ssm_scan_f32_d128;
} else if (d_state == 256) {
return ctx->device->pipeline_ssm_scan_f32_d256;
@@ -11357,7 +11366,8 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx,
const bool use_cm = (ctx->device->pipeline_gated_delta_net_cm != nullptr ||
ctx->device->pipeline_gated_delta_net_cm_v32 != nullptr ||
ctx->device->pipeline_gated_delta_net_cm_v128 != nullptr) &&
src_g->ne[0] == 1 && S_v == 128 && dst->src[0]->ne[0] == 128 && K == 1 && n_tokens >= cm_min_tokens;
src_g->ne[0] == 1 && S_v == 128 && dst->src[0]->ne[0] == 128 && K == 1 && n_tokens >= cm_min_tokens &&
dst->src[6] == nullptr; // the chunked kernels do not replay
const bool use_cm2 = use_cm && ctx->device->coopmat2;
const bool have_v64 = ctx->device->pipeline_gated_delta_net_cm != nullptr;
@@ -11389,9 +11399,10 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx,
ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
vk_subbuffer src_buf[6] = {};
for (int i = 0; i < 6; i++) {
src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
vk_subbuffer src_buf[10] = {};
for (int i = 0; i < 10; i++) {
// the replay sources 6..9 bind q when the op has no replay
src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i] ? dst->src[i] : src_q);
}
vk_subbuffer mirror_buf{};
@@ -11409,6 +11420,11 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx,
mirror_buf = vk_subbuffer{ ctx->prealloc_x, 0, ctx->prealloc_x->size };
}
// replay of pending tokens, see ggml_gated_delta_net_ext
const ggml_tensor * src_pk = dst->src[6];
const ggml_tensor * src_pv = dst->src[7];
const ggml_tensor * src_pgb = dst->src[8];
const uint32_t sq1 = (uint32_t)(src_q->nb[1] / sizeof(float));
const uint32_t sq2 = (uint32_t)(src_q->nb[2] / sizeof(float));
const uint32_t sq3 = (uint32_t)(src_q->nb[3] / sizeof(float));
@@ -11434,7 +11450,18 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx,
sb1, sb2, sb3,
neq1, rq3,
scale,
K
K,
src_pk ? (uint32_t)ggml_get_op_params_i32(dst, 1) : 0u,
src_pk ? (uint32_t)ggml_get_op_params_i32(dst, 2) : 0u,
src_pk ? (uint32_t)(src_pk->nb[1] / sizeof(float)) : 0u,
src_pk ? (uint32_t)(src_pk->nb[2] / sizeof(float)) : 0u,
src_pk ? (uint32_t)(src_pk->nb[3] / sizeof(float)) : 0u,
src_pv ? (uint32_t)(src_pv->nb[1] / sizeof(float)) : 0u,
src_pv ? (uint32_t)(src_pv->nb[2] / sizeof(float)) : 0u,
src_pv ? (uint32_t)(src_pv->nb[3] / sizeof(float)) : 0u,
src_pgb ? (uint32_t)(src_pgb->nb[1] / sizeof(float)) : 0u,
src_pgb ? (uint32_t)(src_pgb->nb[2] / sizeof(float)) : 0u,
src_pgb ? (uint32_t)(src_pgb->nb[3] / sizeof(float)) : 0u,
};
if (use_v128) {
@@ -11442,10 +11469,15 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx,
{src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf, mirror_buf},
pc, std::array<uint32_t, 3>{ S_v / cm_V, n_seqs, H });
ctx->prealloc_x_need_sync = true;
} else {
} else if (use_cm) {
ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
{src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf},
pc, use_cm ? std::array<uint32_t, 3>{ S_v / cm_V, n_seqs, H } : std::array<uint32_t, 3>{ H, n_seqs, S_v });
pc, std::array<uint32_t, 3>{ S_v / cm_V, n_seqs, H });
} else {
ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
{src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf,
src_buf[6], src_buf[7], src_buf[8], src_buf[9]},
pc, std::array<uint32_t, 3>{ H, n_seqs, S_v });
}
}
@@ -11496,7 +11528,7 @@ void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_te
std::array<uint32_t, 3> elements;
const uint32_t d_state = src0->ne[0];
uint32_t num_subgroups = d_state / ctx->device->subgroup_size;
uint32_t num_subgroups = (d_state == 96 ? 128 : d_state) / ctx->device->subgroup_size;
const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, num_subgroups);
const uint32_t num_workgroups_y = n_seq;
elements = { num_workgroups_x, num_workgroups_y, 1 };
@@ -11692,9 +11724,10 @@ void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor
const uint64_t n = ggml_nelements(dst);
GGML_ASSERT(n > 0);
// dst can be a view at any offset: bind from the aligned offset below it, the shader skips KY elements
vk_op_push_constants pc = {
(uint32_t)n,
1,
get_misalign_bytes(ctx, dst) / (uint32_t)ggml_type_size(dst->type),
ggml_get_op_params_f32(dst, 0),
0.0f,
0.0f, 0.0f,
@@ -11710,7 +11743,7 @@ void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor
GGML_ASSERT(wg_y <= ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true);
std::array<uint32_t, 3> elements = { wg_x * pipeline->wg_denoms[0], wg_y * pipeline->wg_denoms[1], 1 };
ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
@@ -16774,8 +16807,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
}
case GGML_OP_FLASH_ATTN_EXT:
{
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
if (op->src[5] != nullptr) {
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
bool coopmat2 = device->coopmat2;
@@ -17246,11 +17278,11 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
return false;
}
if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) {
if ((d_state != 96 && d_state != 128 && d_state != 256) || head_dim % 16 != 0) {
return false;
}
size_t shmem_size = d_state * sizeof(float);
size_t shmem_size = (d_state == 96 ? 128 : d_state) * sizeof(float);
if (shmem_size > device->properties.limits.maxComputeSharedMemorySize) {
return false;
@@ -16,6 +16,6 @@ void main() {
return;
}
// p.param1 = fill value
data_d[i] = D_TYPE(p.param1);
// p.param1 = fill value, p.KY = element offset of dst in the bound buffer
data_d[p.KY + i] = D_TYPE(p.param1);
}
@@ -16,6 +16,7 @@ layout(constant_id = 1) const uint KDA = 0;
layout(constant_id = 2) const uint SUBGROUP_SIZE = 32;
layout(constant_id = 3) const uint LANES_PER_COLUMN = 32;
layout(constant_id = 4) const bool PACKED_ROWS = false;
layout(constant_id = 5) const uint REPLAY = 0;
const uint COLS_PER_WG = SUBGROUP_SIZE / LANES_PER_COLUMN;
const uint ROWS_PER_LANE = S_V / LANES_PER_COLUMN;
@@ -42,6 +43,10 @@ layout(push_constant) uniform Parameters {
uint neq1, rq3;
float scale;
uint K;
uint n_pend, keep;
uint spk1, spk2, spk3;
uint spv1, spv2, spv3;
uint spg1, spg2, spg3;
};
layout(binding = 0) readonly buffer QBuf { FLOAT_TYPE data_q[]; };
@@ -52,6 +57,12 @@ layout(binding = 4) readonly buffer BetaBuf { FLOAT_TYPE data_beta[]; };
layout(binding = 5) readonly buffer StateBuf { FLOAT_TYPE data_state[]; };
layout(binding = 6) buffer DstBuf { FLOAT_TYPE data_dst[]; };
// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
layout(binding = 7) readonly buffer PKBuf { FLOAT_TYPE data_pk[]; };
layout(binding = 8) readonly buffer PVBuf { FLOAT_TYPE data_pv[]; };
layout(binding = 9) readonly buffer PGBBuf { FLOAT_TYPE data_pgb[]; };
layout(binding = 10) readonly buffer NRepBuf { int data_n_rep[]; };
#if !USE_SUBGROUP_ADD && !USE_SUBGROUP_CLUSTERED
shared FLOAT_TYPE temp[SUBGROUP_SIZE];
@@ -123,6 +134,55 @@ void main() {
s_shard[r] = FLOAT_TYPE(data_state[state_in_base + col * S_V + row_index(r, lane)]);
}
if (REPLAY != 0) {
const uint n_r = uint(clamp(data_n_rep[seq_id], 0, int(n_pend)));
for (uint t = 0; t < n_r; t++) {
const uint k_off = seq_id * spk3 + t * spk2 + iq1 * spk1;
const uint v_off = seq_id * spv3 + t * spv2 + head_id * spv1;
const uint g_off = seq_id * spg3 + t * spg2 + head_id * spg1;
const FLOAT_TYPE beta_val = FLOAT_TYPE(data_pgb[g_off + n_pend * spg2]);
FLOAT_TYPE k_reg[ROWS_PER_LANE];
[[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
k_reg[r] = FLOAT_TYPE(data_pk[k_off + row_index(r, lane)]);
}
FLOAT_TYPE g_exp[ROWS_PER_LANE];
if (KDA == 0) {
const FLOAT_TYPE g_val = exp(FLOAT_TYPE(data_pgb[g_off]));
[[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
g_exp[r] = g_val;
}
} else {
[[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
g_exp[r] = exp(FLOAT_TYPE(data_pgb[g_off + row_index(r, lane)]));
}
}
const FLOAT_TYPE v_val = FLOAT_TYPE(data_pv[v_off + col]);
// same update as below, without the attention output
FLOAT_TYPE kv_shard = 0.0;
[[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
kv_shard += g_exp[r] * s_shard[r] * k_reg[r];
}
FLOAT_TYPE kv_col = reduce_partial(kv_shard);
FLOAT_TYPE delta_col = (v_val - kv_col) * beta_val;
[[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
s_shard[r] = g_exp[r] * s_shard[r] + k_reg[r] * delta_col;
}
}
if (keep != 0) {
[[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[r];
}
}
}
// snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back.
// When n_tokens < K, only slots 0..n_tokens-1 are written; older slots are caller-owned.
@@ -191,7 +251,8 @@ void main() {
}
}
if (K == 1u) {
// replay with keep: the state output is the state after the replay
if (K == 1u && !(REPLAY != 0 && keep != 0)) {
[[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[r];
}
@@ -8,10 +8,11 @@
#include "types.glsl"
layout(constant_id = 0) const uint D_STATE = 128;
layout(constant_id = 0) const uint BLOCK_SIZE = 128;
layout(constant_id = 1) const uint SUBGROUP_SIZE = 32;
layout(constant_id = 2) const uint D_STATE = 128;
const uint32_t c_factor = D_STATE / SUBGROUP_SIZE;
const uint32_t c_factor = (D_STATE + SUBGROUP_SIZE - 1) / SUBGROUP_SIZE;
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
@@ -46,14 +47,14 @@ float softplus(float x) {
}
#if !USE_SUBGROUP_ADD
shared float temp[D_STATE];
shared float temp[BLOCK_SIZE];
#endif
void main() {
const uint subgroup = gl_SubgroupID;
const uint lane = gl_SubgroupInvocationID;
const uint tid = gl_SubgroupID * SUBGROUP_SIZE + lane;
const uint subgroup_idx = gl_WorkGroupID.x * c_factor + subgroup;
const uint subgroup_idx = gl_WorkGroupID.x * (BLOCK_SIZE / SUBGROUP_SIZE) + subgroup;
const uint head_idx = subgroup_idx / d_head;
const uint head_off = (subgroup_idx % d_head) * 4;
@@ -78,7 +79,8 @@ void main() {
float state[c_factor];
[[unroll]] for (uint j = 0; j < c_factor; j++) {
state[j] = s0[s0_base_idx + SUBGROUP_SIZE * j + lane];
const uint state_idx = SUBGROUP_SIZE * j + lane;
state[j] = D_STATE % SUBGROUP_SIZE == 0 || state_idx < D_STATE ? s0[s0_base_idx + state_idx] : 0.0f;
}
float a = A[A_base_idx];
@@ -91,8 +93,9 @@ void main() {
const float dA = exp(dt_soft_plus * a);
const float x_dt = x[x_base_idx + i * stride_x] * dt_soft_plus;
[[unroll]] for (uint j = 0; j < c_factor; j++) {
float B_val = B[B_base_idx + i * stride_B + SUBGROUP_SIZE * j + lane];
float C_val = C[C_base_idx + i * stride_C + SUBGROUP_SIZE * j + lane];
const uint state_idx = SUBGROUP_SIZE * j + lane;
float B_val = D_STATE % SUBGROUP_SIZE == 0 || state_idx < D_STATE ? B[B_base_idx + i * stride_B + state_idx] : 0.0f;
float C_val = D_STATE % SUBGROUP_SIZE == 0 || state_idx < D_STATE ? C[C_base_idx + i * stride_C + state_idx] : 0.0f;
state[j] = (state[j] * dA) + (B_val * x_dt);
state_sum += state[j] * C_val;
}
@@ -121,7 +124,9 @@ void main() {
if (slot > 0u && slot < K) {
const uint snapshot_base_idx = s_base_idx + slot * n_seq * (nb03 / 4u);
[[unroll]] for (uint j = 0; j < c_factor; j++) {
d[snapshot_base_idx + SUBGROUP_SIZE * j + lane] = state[j];
if (D_STATE % SUBGROUP_SIZE == 0 || SUBGROUP_SIZE * j + lane < D_STATE) {
d[snapshot_base_idx + SUBGROUP_SIZE * j + lane] = state[j];
}
}
}
}
@@ -129,6 +134,8 @@ void main() {
// write back the state
[[unroll]]
for (int j = 0; j < c_factor; j++) {
d[s_base_idx + SUBGROUP_SIZE * j + lane] = state[j];
if (D_STATE % SUBGROUP_SIZE == 0 || SUBGROUP_SIZE * j + lane < D_STATE) {
d[s_base_idx + SUBGROUP_SIZE * j + lane] = state[j];
}
}
}
@@ -1,6 +1,7 @@
#version 450
#include "types.glsl"
#include "utils.glsl"
#if defined(UNARY_MUL_FUSION)
#include "generic_binary_head.glsl"
#else
@@ -116,7 +117,7 @@ float op_expm1(float x) {
}
float op_softplus(float x) {
return (x > 20.0f) ? x : log(1.0f + exp(x));
return (x > 20.0f) ? x : log1p(exp(x));
}
float op_gelu_erf(float a) {
@@ -25,6 +25,26 @@ uint fastdiv_small(uint a, uint b) {
return (a < b) ? 0 : (a / b);
}
// log(1 + x); the atanh series 2*y*(1 + y^2/3 + ... + y^12/13), y = x/(2+x),
// keeps the precision that log(1 + x) loses for x in [-0.5, 1].
float log1p(float x) {
float y = x / (2.0f + x);
float y2 = y * y;
float p = 1.0f / 13.0f;
p = p * y2 + 1.0f / 11.0f;
p = p * y2 + 1.0f / 9.0f;
p = p * y2 + 1.0f / 7.0f;
p = p * y2 + 1.0f / 5.0f;
p = p * y2 + 1.0f / 3.0f;
p = p * y2 + 1.0f;
float s = 2.0f * y * p;
float l = log(1.0f + x);
bool in_series = (x >= -0.5f) && (x <= 1.0f);
bool tiny = abs(x) < 2.5e-38f;
float r = in_series ? s : l;
return tiny ? x : r;
}
void get_indices(uint idx, out uint i00, out uint i01, out uint i02, out uint i03, uint ne00, uint ne01, uint ne02, uint ne03) {
i03 = fastdiv_small(idx, (ne02*ne01*ne00));
const uint i03_offset = i03 * ne02*ne01*ne00;
@@ -450,9 +450,11 @@ struct ggml_webgpu_gated_delta_net_pipeline_key {
int s_v;
int kda;
bool fused_cache;
bool replay;
bool operator==(const ggml_webgpu_gated_delta_net_pipeline_key & other) const {
return type == other.type && s_v == other.s_v && kda == other.kda && fused_cache == other.fused_cache;
return type == other.type && s_v == other.s_v && kda == other.kda && fused_cache == other.fused_cache &&
replay == other.replay;
}
};
@@ -462,6 +464,7 @@ struct ggml_webgpu_gated_delta_net_pipeline_key_hash {
ggml_webgpu_hash_combine(seed, key.type);
ggml_webgpu_hash_combine(seed, key.s_v);
ggml_webgpu_hash_combine(seed, key.kda);
ggml_webgpu_hash_combine(seed, key.replay);
return seed;
}
};
@@ -2015,6 +2018,7 @@ class ggml_webgpu_shader_lib {
key.s_v = (int) context.src2->ne[0];
key.kda = context.src3->ne[0] == context.src2->ne[0];
key.fused_cache = context.dst_fuse != nullptr;
key.replay = context.dst->src[6] != nullptr;
auto it = gated_delta_net_pipelines.find(key);
if (it != gated_delta_net_pipelines.end()) {
@@ -2042,6 +2046,11 @@ class ggml_webgpu_shader_lib {
variant += "_fused_cache";
}
if (key.replay) {
defines.push_back("REPLAY");
variant += "_replay";
}
defines.push_back("S_V=" + std::to_string(key.s_v) + "u");
defines.push_back("WG_SIZE=" + std::to_string(key.s_v) + "u");
+43 -4
View File
@@ -1497,6 +1497,11 @@ static webgpu_encoded_op ggml_webgpu_ssm_scan(webgpu_context & ctx,
return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
}
// storage buffers of the gated delta net shader: q, k, v, g, beta, state and dst, the fused cache, then the replay inputs
static uint32_t ggml_webgpu_gated_delta_net_n_storage_buffers(const ggml_tensor * op, bool fused_cache) {
return 7 + (fused_cache ? 1 : 0) + (op->src[6] != nullptr ? 4 : 0);
}
static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
ggml_tensor * src0,
ggml_tensor * src1,
@@ -1527,6 +1532,12 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
uint32_t scale_u32;
memcpy(&scale_u32, &scale, sizeof(scale_u32));
// replay of pending tokens, see ggml_gated_delta_net_ext
ggml_tensor * pend_k = dst->src[6];
ggml_tensor * pend_v = dst->src[7];
ggml_tensor * pend_gb = dst->src[8];
ggml_tensor * n_rep = dst->src[9];
std::vector<uint32_t> params = {
h,
n_tokens,
@@ -1551,6 +1562,21 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
scale_u32,
dst_fuse ? (uint32_t) (dst_fuse->nb[2] / ggml_type_size(dst_fuse->type)) : 0,
dst_fuse ? (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst_fuse) / ggml_type_size(dst_fuse->type)) : 0,
pend_k ? (uint32_t) ggml_get_op_params_i32(dst, 1) : 0,
pend_k ? (uint32_t) ggml_get_op_params_i32(dst, 2) : 0,
pend_k ? (uint32_t) (pend_k->nb[1] / ggml_type_size(pend_k->type)) : 0,
pend_k ? (uint32_t) (pend_k->nb[2] / ggml_type_size(pend_k->type)) : 0,
pend_k ? (uint32_t) (pend_k->nb[3] / ggml_type_size(pend_k->type)) : 0,
pend_v ? (uint32_t) (pend_v->nb[1] / ggml_type_size(pend_v->type)) : 0,
pend_v ? (uint32_t) (pend_v->nb[2] / ggml_type_size(pend_v->type)) : 0,
pend_v ? (uint32_t) (pend_v->nb[3] / ggml_type_size(pend_v->type)) : 0,
pend_gb ? (uint32_t) (pend_gb->nb[1] / ggml_type_size(pend_gb->type)) : 0,
pend_gb ? (uint32_t) (pend_gb->nb[2] / ggml_type_size(pend_gb->type)) : 0,
pend_gb ? (uint32_t) (pend_gb->nb[3] / ggml_type_size(pend_gb->type)) : 0,
};
std::vector<wgpu::BindGroupEntry> entries = {
@@ -1564,6 +1590,14 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 7, dst_fuse));
}
if (pend_k) {
const uint32_t binding = dst_fuse ? 8 : 7;
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 0, pend_k));
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 1, pend_v));
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 2, pend_gb));
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 3, n_rep));
}
return ggml_backend_webgpu_build(ctx, pipeline, params, entries, h, n_seqs);
}
@@ -3728,7 +3762,9 @@ static std::optional<webgpu_encoded_op> ggml_webgpu_encode(webgpu_context ctx,
return ggml_webgpu_ssm_scan(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5], node->src[6],
node);
case GGML_OP_GATED_DELTA_NET:
if (ggml_webgpu_can_fuse_gdn_cache(cgraph, node_idx, num_encoded_ops)) {
if (ggml_webgpu_gated_delta_net_n_storage_buffers(node, true) <=
ctx->global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage &&
ggml_webgpu_can_fuse_gdn_cache(cgraph, node_idx, num_encoded_ops)) {
ggml_tensor * dst_fuse = cgraph->nodes[node_idx + num_encoded_ops - 1]->src[1];
return ggml_webgpu_gated_delta_net(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5],
node, dst_fuse);
@@ -5086,8 +5122,9 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const
{
// conservative support checks for whether the more resource-intensive shader paths
// can be used, to avoid cases where flash_attn is assigned to the CPU later on
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
supports_op = op->src[5] == nullptr && src0->type == GGML_TYPE_F32 &&
// K/V row lists and indexed bias are not supported
supports_op = op->src[5] == nullptr && !ggml_flash_attn_ext_has_indexed_bias(op) &&
src0->type == GGML_TYPE_F32 &&
(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16 ||
src1->type == GGML_TYPE_Q4_0 || src1->type == GGML_TYPE_Q8_0) &&
(src2->type == GGML_TYPE_F32 || src2->type == GGML_TYPE_F16 ||
@@ -5269,7 +5306,9 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const
src2->type == GGML_TYPE_F32 && op->src[3]->type == GGML_TYPE_F32 &&
op->src[4]->type == GGML_TYPE_F32 && op->src[5]->type == GGML_TYPE_F32 &&
s_v <= ctx->webgpu_global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup &&
ggml_are_same_stride(src0, src1);
ggml_are_same_stride(src0, src1) &&
ggml_webgpu_gated_delta_net_n_storage_buffers(op, false) <=
ctx->webgpu_global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage;
}
break;
case GGML_OP_CLAMP:
@@ -23,10 +23,31 @@ var<storage, read_write> dst: array<f32>;
@group(0) @binding(7)
var<storage, read_write> dst_fuse: array<f32>;
#define DST_SNAP dst_fuse
#define PARAMS_BINDING 8
#define NEXT_BINDING 8
#else
#define DST_SNAP dst
#define PARAMS_BINDING 7
#define NEXT_BINDING 7
#endif
#ifdef REPLAY
// pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
@group(0) @binding(NEXT_BINDING)
var<storage, read_write> pend_k: array<f32>;
@group(0) @binding(NEXT_BINDING + 1)
var<storage, read_write> pend_v: array<f32>;
@group(0) @binding(NEXT_BINDING + 2)
var<storage, read_write> pend_gb: array<f32>;
@group(0) @binding(NEXT_BINDING + 3)
var<storage, read_write> n_rep: array<i32>;
var<workgroup> wg_n_rep: u32;
#define PARAMS_BINDING (NEXT_BINDING + 4)
#else
#define PARAMS_BINDING NEXT_BINDING
#endif
struct Params {
@@ -53,6 +74,21 @@ struct Params {
scale: f32,
dst_fuse_nb2: u32,
dst_fuse_off: u32,
n_pend: u32,
keep: u32,
spk1: u32,
spk2: u32,
spk3: u32,
spv1: u32,
spv2: u32,
spv3: u32,
spg1: u32,
spg2: u32,
spg3: u32,
};
@group(0) @binding(PARAMS_BINDING)
@@ -92,6 +128,66 @@ fn main(
state[i] = src_state[state_in_base + col * S_V + i];
}
#ifdef REPLAY
if (col == 0u) {
wg_n_rep = u32(n_rep[seq_id]);
}
let n_r = workgroupUniformLoad(&wg_n_rep);
for (var t = 0u; t < n_r; t++) {
let k_off = seq_id * params.spk3 + t * params.spk2 + iq1 * params.spk1;
let v_off = seq_id * params.spv3 + t * params.spv2 + head_id * params.spv1;
let g_off = seq_id * params.spg3 + t * params.spg2 + head_id * params.spg1;
sh_k[col] = pend_k[k_off + col];
#ifdef KDA
sh_g[col] = exp(pend_gb[g_off + col]);
#endif
workgroupBarrier();
let v_val = pend_v[v_off + col];
let beta_val = pend_gb[g_off + params.n_pend * params.spg2];
// same update as below, without the attention output
var kv_col = 0.0;
var delta_col = 0.0;
#ifdef KDA
for (var i = 0u; i < S_V; i++) {
kv_col += (sh_g[i] * state[i]) * sh_k[i];
}
delta_col = (v_val - kv_col) * beta_val;
for (var i = 0u; i < S_V; i++) {
state[i] = sh_g[i] * state[i] + sh_k[i] * delta_col;
}
#else
let g_val = exp(pend_gb[g_off]);
for (var i = 0u; i < S_V; i++) {
kv_col += state[i] * sh_k[i];
}
delta_col = (v_val - g_val * kv_col) * beta_val;
for (var i = 0u; i < S_V; i++) {
state[i] = g_val * state[i] + sh_k[i] * delta_col;
}
#endif
workgroupBarrier();
}
if (params.keep != 0u) {
for (var i = 0u; i < S_V; i++) {
DST_SNAP[snap_off + state_out_base + col * S_V + i] = state[i];
}
}
#endif
var attn_off = (seq_id * params.n_tokens * params.h + head_id) * S_V;
for (var t = 0u; t < params.n_tokens; t++) {
@@ -160,7 +256,14 @@ fn main(
workgroupBarrier();
}
if (params.K == 1u) {
#ifdef REPLAY
// replay with keep: the state output is the state after the replay
let write_state = params.K == 1u && params.keep == 0u;
#else
let write_state = params.K == 1u;
#endif
if (write_state) {
for (var i = 0u; i < S_V; i++) {
DST_SNAP[snap_off + state_out_base + col * S_V + i] = state[i];
}
+1 -1
View File
@@ -21,7 +21,7 @@ bool ggml_zdnn_supports_flash_attn_ext(const ggml_backend_zdnn_device_context *
memcpy(&logit_softcap, (const float *) op->op_params + 2, sizeof(float));
// sinks, alibi, softcap, sparse k/v sets and k/v row lists are not implemented
if (op->src[4] != nullptr || op->src[5] != nullptr || max_bias != 0.0f || logit_softcap != 0.0f || ggml_get_op_params_i32(op, 4) != 0) {
if (op->src[4] != nullptr || op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op) || max_bias != 0.0f || logit_softcap != 0.0f || ggml_get_op_params_i32(op, 4) != 0) {
return false;
}
+86 -2
View File
@@ -5545,6 +5545,33 @@ void ggml_flash_attn_ext_add_sinks(
a->src[4] = sinks;
}
bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a) {
return a->op == GGML_OP_FLASH_ATTN_EXT && ggml_get_op_params_i32(a, 5) != 0;
}
void ggml_flash_attn_ext_add_indexed_bias(
struct ggml_tensor * a,
struct ggml_tensor * table,
struct ggml_tensor * indices) {
GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
GGML_ASSERT((table == NULL) == (indices == NULL));
a->src[6] = table;
a->src[7] = indices;
ggml_set_op_params_i32(a, 5, table != NULL);
if (!table) {
return;
}
const struct ggml_tensor * q = a->src[0];
const struct ggml_tensor * mask = a->src[3];
GGML_ASSERT(mask && mask->ne[0] == (a->src[5] ? a->src[5]->ne[0] : a->src[1]->ne[1]) && mask->ne[1] == q->ne[1]);
GGML_ASSERT(mask->ne[2] == 1 && mask->ne[3] == q->ne[3]);
GGML_ASSERT(table->type == GGML_TYPE_F32 && ggml_is_contiguous(table));
GGML_ASSERT(table->ne[1] == q->ne[2] && table->ne[0] > 0 && table->ne[2] == q->ne[1]*q->ne[3] && table->ne[3] == 1);
GGML_ASSERT(indices->type == GGML_TYPE_I32 && ggml_is_contiguous(indices) && ggml_is_matrix(indices));
GGML_ASSERT(indices->ne[0] == mask->ne[0] && indices->ne[1] == table->ne[2]);
}
// ggml_flash_attn_back
struct ggml_tensor * ggml_flash_attn_back(
@@ -6346,7 +6373,7 @@ struct ggml_tensor * ggml_solve_tri(
// ggml_gated_delta_net
struct ggml_tensor * ggml_gated_delta_net(
static struct ggml_tensor * ggml_gated_delta_net_impl(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * k,
@@ -6354,7 +6381,12 @@ struct ggml_tensor * ggml_gated_delta_net(
struct ggml_tensor * g,
struct ggml_tensor * beta,
struct ggml_tensor * state,
int64_t K) {
struct ggml_tensor * pend_k,
struct ggml_tensor * pend_v,
struct ggml_tensor * pend_gb,
struct ggml_tensor * n_rep,
int64_t K,
bool keep) {
GGML_ASSERT(ggml_is_contiguous_rows(q));
GGML_ASSERT(ggml_is_contiguous_rows(k));
GGML_ASSERT(ggml_is_contiguous_rows(v));
@@ -6398,9 +6430,61 @@ struct ggml_tensor * ggml_gated_delta_net(
result->src[4] = beta;
result->src[5] = state;
const bool replay = pend_k != NULL;
GGML_ASSERT((pend_v != NULL) == replay && (pend_gb != NULL) == replay && (n_rep != NULL) == replay);
GGML_ASSERT(replay || !keep);
if (replay) {
const int64_t n_pend = pend_k->ne[2];
GGML_ASSERT(K == 1);
GGML_ASSERT(pend_k->type == GGML_TYPE_F32 && pend_v->type == GGML_TYPE_F32 && pend_gb->type == GGML_TYPE_F32);
GGML_ASSERT(n_rep->type == GGML_TYPE_I32);
GGML_ASSERT(pend_k->nb[0] == sizeof(float) && pend_v->nb[0] == sizeof(float) && pend_gb->nb[0] == sizeof(float));
GGML_ASSERT(pend_k->ne[0] == k->ne[0] && pend_k->ne[1] == k->ne[1] && pend_k->ne[3] == n_seqs);
GGML_ASSERT(pend_v->ne[0] == S_v && pend_v->ne[1] == H && pend_v->ne[2] == n_pend && pend_v->ne[3] == n_seqs);
GGML_ASSERT(pend_gb->ne[0] == g->ne[0] && pend_gb->ne[1] == H && pend_gb->ne[2] == 2*n_pend && pend_gb->ne[3] == n_seqs);
GGML_ASSERT(ggml_is_contiguous(n_rep) && ggml_nelements(n_rep) == n_seqs);
ggml_set_op_params_i32(result, 1, (int32_t) n_pend);
ggml_set_op_params_i32(result, 2, keep ? 1 : 0);
result->src[6] = pend_k;
result->src[7] = pend_v;
result->src[8] = pend_gb;
result->src[9] = n_rep;
}
return result;
}
struct ggml_tensor * ggml_gated_delta_net_ext(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * k,
struct ggml_tensor * v,
struct ggml_tensor * g,
struct ggml_tensor * beta,
struct ggml_tensor * state,
struct ggml_tensor * pend_k,
struct ggml_tensor * pend_v,
struct ggml_tensor * pend_gb,
struct ggml_tensor * n_rep,
bool keep) {
return ggml_gated_delta_net_impl(ctx, q, k, v, g, beta, state, pend_k, pend_v, pend_gb, n_rep, 1, keep);
}
struct ggml_tensor * ggml_gated_delta_net(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * k,
struct ggml_tensor * v,
struct ggml_tensor * g,
struct ggml_tensor * beta,
struct ggml_tensor * state,
int64_t K) {
return ggml_gated_delta_net_impl(ctx, q, k, v, g, beta, state, NULL, NULL, NULL, NULL, K, false);
}
// ggml_lightning_indexer
struct ggml_tensor * ggml_lightning_indexer(
+9
View File
@@ -190,6 +190,14 @@ llama_context::llama_context(
cparams.n_rs_seq = 0;
}
// delta-net rollback keeps one state and the inputs of the last ubatch; the gdn op replays the kept tokens before the new ones
cparams.rs_replay = cparams.n_rs_seq > 0 && (
model.arch == LLM_ARCH_QWEN35 || model.arch == LLM_ARCH_QWEN35MOE || model.arch == LLM_ARCH_QWEN4EXP ||
model.arch == LLM_ARCH_CLOVER_MOE ||
// KDA
model.arch == LLM_ARCH_KIMI_K3 || model.arch == LLM_ARCH_KIMI_K31 || model.arch == LLM_ARCH_GLM5_NEXT ||
model.arch == LLM_ARCH_BAILINGMOE3);
cparams.n_threads = params.n_threads;
cparams.n_threads_batch = params.n_threads_batch;
cparams.yarn_ext_factor = params.yarn_ext_factor >= 0.0f ? params.yarn_ext_factor : hparams.yarn_ext_factor;
@@ -435,6 +443,7 @@ llama_context::llama_context(
LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
LLAMA_LOG_INFO("%s: n_rs_seq = %u\n", __func__, cparams.n_rs_seq);
LLAMA_LOG_INFO("%s: rs_replay = %s\n", __func__, cparams.rs_replay ? "true" : "false");
LLAMA_LOG_INFO("%s: n_outputs_max = %u\n", __func__, cparams.n_outputs_max);
LLAMA_LOG_INFO("%s: n_outputs_max_per_seq = %u\n", __func__, cparams.n_outputs_max_per_seq);
+1
View File
@@ -14,6 +14,7 @@ struct llama_cparams {
uint32_t n_ubatch;
uint32_t n_seq_max;
uint32_t n_rs_seq; // number of recurrent-state snapshots per seq for rollback
bool rs_replay; // roll back by replaying kept tokens instead of keeping n_rs_seq snapshots
uint32_t n_outputs_max; // max outputs supported by the context
uint32_t n_outputs_max_per_seq;
int32_t n_threads; // number of threads to use for generation
+68 -7
View File
@@ -527,8 +527,6 @@ void llm_graph_input_cls::set_input(const llama_ubatch * ubatch) {
}
void llm_graph_input_rs::set_input(const llama_ubatch * ubatch) {
GGML_UNUSED(ubatch);
const int64_t n_rs = mctx->get_n_rs();
if (s_copy) {
@@ -540,6 +538,34 @@ void llm_graph_input_rs::set_input(const llama_ubatch * ubatch) {
data[i] = mctx->s_copy(i);
}
}
set_input_rep(mctx, ubatch);
}
void llm_graph_input_rs::set_input_rep(const llama_memory_recurrent_context * mctx, const llama_ubatch * ubatch) {
if (!has_rep) {
return;
}
const int64_t n_seqs = ubatch->n_seqs;
int32_t * reps = (int32_t *) rep_n->data;
int32_t * cols = (int32_t *) rep_cols->data;
GGML_ASSERT(ggml_backend_buffer_is_host(rep_n->buffer));
GGML_ASSERT(ggml_backend_buffer_is_host(rep_cols->buffer));
for (int64_t s = 0; s < n_seqs; ++s) {
const int64_t n_rep = mctx->get_rs_rep(s);
GGML_ASSERT(n_rep <= n_pend);
reps[s] = n_rep;
// the conv history is [window | pending]: the window after the kept tokens
for (int64_t c = 0; c < n_conv; ++c) {
cols[s*n_conv + c] = n_rep + c;
}
}
}
bool llm_graph_input_rs::can_reuse(const llm_graph_params & params) {
@@ -1261,6 +1287,8 @@ void llm_graph_input_mem_hybrid::set_input(const llama_ubatch * ubatch) {
data[i] = mctx->get_recr()->s_copy(i);
}
}
inp_rs->set_input_rep(mctx->get_recr(), ubatch);
}
bool llm_graph_input_mem_hybrid::can_reuse(const llm_graph_params & params) {
@@ -1307,6 +1335,8 @@ void llm_graph_input_mem_hybrid_k::set_input(const llama_ubatch * ubatch) {
data[i] = mctx->get_recr()->s_copy(i);
}
}
inp_rs->set_input_rep(mctx->get_recr(), ubatch);
}
bool llm_graph_input_mem_hybrid_k::can_reuse(const llm_graph_params & params) {
@@ -1364,6 +1394,8 @@ void llm_graph_input_mem_hybrid_iswa::set_input(const llama_ubatch * ubatch) {
data[i] = mctx->get_recr()->s_copy(i);
}
}
inp_rs->set_input_rep(mctx->get_recr(), ubatch);
}
bool llm_graph_input_mem_hybrid_iswa::can_reuse(const llm_graph_params & params) {
@@ -1443,6 +1475,8 @@ void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch)
data[i] = mctx->get_recr()->s_copy(i);
}
}
inp_rs->set_input_rep(mctx->get_recr(), ubatch);
}
bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & params) {
@@ -4136,6 +4170,8 @@ ggml_tensor * llm_graph_context::build_rs(
static std::unique_ptr<llm_graph_input_rs> build_rs_inp_impl(
ggml_context * ctx0,
const llama_ubatch & ubatch,
const llama_hparams & hparams,
const llama_cparams & cparams,
const llama_memory_recurrent_context * mctx_cur) {
auto inp = std::make_unique<llm_graph_input_rs>(mctx_cur);
@@ -4153,13 +4189,38 @@ static std::unique_ptr<llm_graph_input_rs> build_rs_inp_impl(
inp->head = mctx_cur->get_head();
inp->rs_z = mctx_cur->get_rs_z();
inp->has_rep = mctx_cur->get_rs_replay();
if (inp->has_rep) {
// the widest conv window of the model: the delta-net conv, or the PLE n-gram conv (qwen4exp)
const int64_t n_conv_r = hparams.ssm_d_conv - 1;
const int64_t n_conv_p = hparams.ple_conv_state() > 0 ? (int64_t) (hparams.ple_conv_kernel - 1)*hparams.ple_ngram_size : 0;
inp->n_conv = std::max(n_conv_r, n_conv_p);
inp->n_pend = cparams.n_rs_seq + 1;
inp->rep_cols = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, inp->n_conv, n_seqs);
ggml_set_input(inp->rep_cols);
ggml_set_name(inp->rep_cols, "rs_rep_cols");
const auto win = [&](int64_t n) {
return n == inp->n_conv ? inp->rep_cols : ggml_view_2d(ctx0, inp->rep_cols, n, n_seqs, inp->rep_cols->nb[1], 0);
};
inp->rep_cols_r = win(n_conv_r);
inp->rep_cols_p = n_conv_p > 0 ? win(n_conv_p) : nullptr;
inp->rep_n = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_seqs);
ggml_set_input(inp->rep_n);
ggml_set_name(inp->rep_n, "rs_rep_n");
}
return inp;
}
llm_graph_input_rs * llm_graph_context::build_rs_inp() const {
const auto * mctx_cur = static_cast<const llama_memory_recurrent_context *>(mctx);
auto inp = build_rs_inp_impl(ctx0, ubatch, mctx_cur);
auto inp = build_rs_inp_impl(ctx0, ubatch, hparams, cparams, mctx_cur);
return (llm_graph_input_rs *) res->add_input(std::move(inp));
}
@@ -4286,7 +4347,7 @@ ggml_tensor * llm_graph_context::build_rwkv_token_shift_store(
llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid() const {
const auto * mctx_cur = static_cast<const llama_memory_hybrid_context *>(mctx);
auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr());
auto inp_rs = build_rs_inp_impl (ctx0, ubatch, hparams, cparams, mctx_cur->get_recr());
auto inp_attn = build_attn_inp_kv_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn());
auto inp = std::make_unique<llm_graph_input_mem_hybrid>(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur);
@@ -4297,7 +4358,7 @@ llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid() const {
llm_graph_input_mem_hybrid_k * llm_graph_context::build_inp_mem_hybrid_k() const {
const auto * mctx_cur = static_cast<const llama_memory_hybrid_context *>(mctx);
auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr());
auto inp_rs = build_rs_inp_impl (ctx0, ubatch, hparams, cparams, mctx_cur->get_recr());
auto inp_attn = build_attn_inp_k_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn());
auto inp = std::make_unique<llm_graph_input_mem_hybrid_k>(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur);
@@ -4308,7 +4369,7 @@ llm_graph_input_mem_hybrid_k * llm_graph_context::build_inp_mem_hybrid_k() const
llm_graph_input_mem_hybrid_iswa * llm_graph_context::build_inp_mem_hybrid_iswa() const {
const auto * mctx_cur = static_cast<const llama_memory_hybrid_iswa_context *>(mctx);
auto inp_rs = build_rs_inp_impl(ctx0, ubatch, mctx_cur->get_recr());
auto inp_rs = build_rs_inp_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_recr());
// build iswa attention input
const auto * attn_ctx = mctx_cur->get_attn();
@@ -4345,7 +4406,7 @@ llm_graph_input_mem_hybrid_iswa_rel * llm_graph_context::build_inp_mem_hybrid_is
uint32_t extent_swa) const {
const auto * mctx_cur = static_cast<const llama_memory_hybrid_iswa_context *>(mctx);
auto inp_rs = build_rs_inp_impl(ctx0, ubatch, mctx_cur->get_recr());
auto inp_rs = build_rs_inp_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_recr());
const auto * attn_ctx = mctx_cur->get_attn();
+13
View File
@@ -323,6 +323,19 @@ public:
ggml_tensor * s_copy_main; // I32 [n_seqs]
ggml_tensor * s_copy_tail; // I32 [n_rs - 1]
// rs_replay: the ubatch first replays the kept pending tokens of the last ubatch (none is a no-op)
bool has_rep = false;
int64_t n_conv = 0; // conv window columns, the widest conv of the model
int64_t n_pend = 0; // pending slots per seq
ggml_tensor * rep_n = nullptr; // I32 [n_seqs], kept pending tokens
ggml_tensor * rep_cols = nullptr; // I32 [n_conv, n_seqs], conv history columns of the window after the kept tokens
// views of rep_cols for the delta-net conv and the PLE conv windows, computed once per graph and shared across layers
ggml_tensor * rep_cols_r = nullptr;
ggml_tensor * rep_cols_p = nullptr;
void set_input_rep(const llama_memory_recurrent_context * mctx, const llama_ubatch * ubatch);
const llama_memory_recurrent_context * mctx;
// used in view offsets, need to match for valid graph reuse
+2 -1
View File
@@ -33,6 +33,7 @@ llama_memory_hybrid_idx::llama_memory_hybrid_idx(
/* common */
uint32_t n_seq_max,
uint32_t n_rs_seq,
bool rs_replay,
bool offload,
bool unified,
/* layer filters */
@@ -44,7 +45,7 @@ llama_memory_hybrid_idx::llama_memory_hybrid_idx(
no_alloc,
type_k, type_v, v_trans, kv_size, n_swa, swa_type,
type_r, type_s, rs_size,
n_seq_max, n_rs_seq, offload, unified,
n_seq_max, n_rs_seq, rs_replay, offload, unified,
filter_attn, filter_recr),
hparams_idx(model.hparams),
mem_idx(filter_idx == nullptr ? nullptr : [&] {
+1
View File
@@ -33,6 +33,7 @@ public:
/* common */
uint32_t n_seq_max,
uint32_t n_rs_seq,
bool rs_replay,
bool offload,
bool unified,
/* layer filters */
+1
View File
@@ -59,6 +59,7 @@ llama_memory_hybrid_iswa::llama_memory_hybrid_iswa(
rs_size,
n_seq_max,
n_rs_seq,
false,
filter_recr == nullptr ?
[&](int32_t il) { return hparams.is_recr(il); }
: filter_recr
+2
View File
@@ -25,6 +25,7 @@ llama_memory_hybrid::llama_memory_hybrid(
/* common */
uint32_t n_seq_max,
uint32_t n_rs_seq,
bool rs_replay,
bool offload,
bool unified,
/* layer filters */
@@ -60,6 +61,7 @@ llama_memory_hybrid::llama_memory_hybrid(
rs_size,
n_seq_max,
n_rs_seq,
rs_replay,
filter_recr == nullptr ?
[&](int32_t il) { return hparams.is_recr(il); }
: filter_recr
+1
View File
@@ -35,6 +35,7 @@ public:
/* common */
uint32_t n_seq_max,
uint32_t n_rs_seq,
bool rs_replay,
bool offload,
bool unified,
/* layer filters */
+152 -15
View File
@@ -26,6 +26,7 @@ llama_memory_recurrent::llama_memory_recurrent(
uint32_t mem_size,
uint32_t n_seq_max,
uint32_t n_rs_seq,
bool rs_replay,
const layer_filter_cb & filter) : hparams(model.hparams), n_seq_max(n_seq_max), ctxs_bufs(no_alloc) {
const int32_t n_layer = hparams.n_layer();
@@ -33,7 +34,8 @@ llama_memory_recurrent::llama_memory_recurrent(
size = mem_size;
used = 0;
this->n_rs_seq = n_rs_seq;
this->n_rs_seq = n_rs_seq;
this->rs_replay = rs_replay && n_rs_seq > 0;
rs_idx.assign(n_seq_max, 0);
cells.clear();
@@ -53,7 +55,7 @@ llama_memory_recurrent::llama_memory_recurrent(
if (it == ctx_map.end()) {
ggml_init_params params = {
// r and s per layer, plus the separate PLE conv row where the model has one
/*.mem_size =*/ size_t((hparams.ple_conv_state() > 0 ? 3u : 2u)*n_layer*ggml_tensor_overhead()),
/*.mem_size =*/ size_t((hparams.ple_conv_state() > 0 ? 6u : 5u)*n_layer*ggml_tensor_overhead()),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
@@ -74,6 +76,9 @@ llama_memory_recurrent::llama_memory_recurrent(
r_l.resize(n_layer);
s_l.resize(n_layer);
p_l.resize(n_layer);
spk_l.resize(n_layer);
spv_l.resize(n_layer);
spgb_l.resize(n_layer);
for (int i = 0; i < n_layer; i++) {
if (filter && !filter(i)) {
@@ -99,17 +104,45 @@ llama_memory_recurrent::llama_memory_recurrent(
throw std::runtime_error("failed to create ggml context for rs cache");
}
const uint32_t n_rows = mem_size * (1 + n_rs_seq);
ggml_tensor * r = ggml_new_tensor_2d(ctx, type_r, hparams.n_embd_r(), n_rows);
// rs_replay: r is the conv history [channels, d_conv - 1 + n_pend], the window then the pending columns,
// and spk, spv, spgb hold the gdn k, v, gate and beta of up to n_pend pending tokens
const int64_t n_pend = n_rs_seq + 1;
const int64_t n_ch = hparams.n_embd_r() / std::max<int64_t>(1, hparams.ssm_d_conv - 1);
const int64_t n_embd_r = this->rs_replay ? n_ch*(hparams.ssm_d_conv - 1 + n_pend) : hparams.n_embd_r();
const uint32_t n_rows = mem_size * (this->rs_replay ? 1 : 1 + n_rs_seq);
ggml_tensor * r = ggml_new_tensor_2d(ctx, type_r, n_embd_r, n_rows);
ggml_tensor * s = ggml_new_tensor_2d(ctx, type_s, hparams.n_embd_s(), n_rows);
ggml_format_name(r, "cache_r_l%d", i);
ggml_format_name(s, "cache_s_l%d", i);
r_l[i] = r;
s_l[i] = s;
if (this->rs_replay) {
// k [S_k, H_k, n_pend], v [S_v, H_v, n_pend], gb [g0, H_v, 2*n_pend]: separate rows, so that a split by heads
// is one axis of each (-sm tensor). The gate is a scalar per head (g0 = 1), or per key dim for KDA (g0 = S_v)
const bool kda = hparams.n_embd_head_kda != 0;
const int64_t n_k = kda ? (int64_t) hparams.n_embd_head_kda*hparams.n_head() : (int64_t) hparams.ssm_d_state*hparams.ssm_n_group;
const int64_t n_v = kda ? n_k : (int64_t) hparams.ssm_d_inner;
const int64_t n_gb = kda ? n_k : (int64_t) hparams.ssm_dt_rank;
ggml_tensor * spk = ggml_new_tensor_2d(ctx, type_s, n_k*n_pend, mem_size);
ggml_tensor * spv = ggml_new_tensor_2d(ctx, type_s, n_v*n_pend, mem_size);
ggml_tensor * spgb = ggml_new_tensor_2d(ctx, type_s, n_gb*2*n_pend, mem_size);
ggml_format_name(spk, "cache_spk_l%d", i);
ggml_format_name(spv, "cache_spv_l%d", i);
ggml_format_name(spgb, "cache_spgb_l%d", i);
spk_l[i] = spk;
spv_l[i] = spv;
spgb_l[i] = spgb;
}
// the PLE history needs its own row: Meta must mirror it while the delta-net conv state next door stays split
if (hparams.ple_conv_state() > 0 && hparams.is_ple(i)) {
ggml_tensor * p = ggml_new_tensor_2d(ctx, type_r, hparams.ple_conv_state(), n_rows);
// rs_replay: [channels, window + n_pend], like r
const int64_t n_win_p = (int64_t) (hparams.ple_conv_kernel - 1)*hparams.ple_ngram_size;
const int64_t n_embd_p = this->rs_replay ? hparams.ple_conv_state()/n_win_p*(n_win_p + n_pend) : hparams.ple_conv_state();
ggml_tensor * p = ggml_new_tensor_2d(ctx, type_r, n_embd_p, n_rows);
ggml_format_name(p, "cache_ple_r_l%d", i);
p_l[i] = p;
}
@@ -124,7 +157,8 @@ llama_memory_recurrent::llama_memory_recurrent(
if (is_empty()) {
if (n_rs_seq > 0) {
n_rs_seq = 0;
n_rs_seq = 0;
rs_replay = false;
LLAMA_LOG_INFO("%s: disabling rollback snapshots because the memory module is empty\n", __func__);
}
}
@@ -134,8 +168,8 @@ llama_memory_recurrent::llama_memory_recurrent(
const size_t memory_size_s = size_s_bytes();
const size_t memory_size_p = size_p_bytes();
LLAMA_LOG_INFO("%s: size = %7.2f MiB (%6u cells, %3d layers, %2u seqs %2u rs_seq), R (%s): %7.2f MiB, S (%s): %7.2f MiB, P (%s): %7.2f MiB\n", __func__,
(float)(memory_size_r + memory_size_s + memory_size_p) / (1024.0f * 1024.0f), mem_size, n_layer, n_seq_max, n_rs_seq,
LLAMA_LOG_INFO("%s: size = %7.2f MiB (%6u cells, %3d layers, %2u seqs %2u rs_seq%s), R (%s): %7.2f MiB, S (%s): %7.2f MiB, P (%s): %7.2f MiB\n", __func__,
(float)(memory_size_r + memory_size_s + memory_size_p) / (1024.0f * 1024.0f), mem_size, n_layer, n_seq_max, n_rs_seq, rs_replay ? " replay" : "",
ggml_type_name(type_r), (float)memory_size_r / (1024.0f * 1024.0f),
ggml_type_name(type_s), (float)memory_size_s / (1024.0f * 1024.0f),
ggml_type_name(type_r), (float)memory_size_p / (1024.0f * 1024.0f));
@@ -149,6 +183,8 @@ void llama_memory_recurrent::clear(bool data) {
cells[i].src = -1;
cells[i].tail = -1;
cells[i].rs_max = 0;
cells[i].rs_pend = 0;
cells[i].rs_rep = 0;
}
head = 0;
@@ -210,7 +246,13 @@ bool llama_memory_recurrent::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos
// pending rollback is single-use
const bool pending = rs_idx[seq_id] != 0;
if (!pending && rollback >= 1 && rollback <= (llama_pos) cell.rs_max) {
set_rs_idx(seq_id, (uint32_t) rollback);
if (rs_replay) {
// the next ubatch replays only the kept pending tokens
cell.rs_pend -= rollback;
cell.rs_max = 0;
} else {
set_rs_idx(seq_id, (uint32_t) rollback);
}
cell.pos = p0 - 1;
return true;
}
@@ -615,6 +657,7 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) {
auto & orig_cell = cells[seq_meta.tail];
empty_cell.pos = orig_cell.pos;
empty_cell.src = orig_cell.src;
empty_cell.rs_pend = orig_cell.rs_pend;
orig_cell.seq_id.erase(seq_id);
empty_cell.seq_id.insert(seq_id); // will be overwritten
GGML_ASSERT(!orig_cell.is_empty()); // has at least one remaining seq_id
@@ -645,7 +688,13 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) {
std::swap(dst_cell.pos, src_cell.pos);
std::swap(dst_cell.src, src_cell.src);
std::swap(dst_cell.rs_max, src_cell.rs_max);
std::swap(dst_cell.rs_pend, src_cell.rs_pend);
std::swap(dst_cell.seq_id, src_cell.seq_id);
// the cell moved out only gets its final state copied, its rollback snapshots stay behind
if (!rs_replay) {
src_cell.rs_max = 0;
}
// swap tails
for (uint32_t j = 0; j < size; ++j) {
@@ -674,6 +723,11 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) {
}
cell.pos = last_pos;
cell.rs_max = n_seq_tokens <= n_rs_seq + 1 ? n_seq_tokens - 1 : 0;
if (rs_replay) {
// replay what the last ubatch left pending, then keep this ubatch pending if it can be rolled back
cell.rs_rep = cell.src >= 0 ? cell.rs_pend : 0;
cell.rs_pend = cell.rs_max > 0 ? n_seq_tokens : 0;
}
cell.seq_id.clear();
for (int32_t j = 0; j < ubatch.n_seq_id[i]; ++j) {
const llama_seq_id seq_id = ubatch.seq_id[i][j];
@@ -753,6 +807,7 @@ size_t llama_memory_recurrent::size_r_bytes() const {
}
}
return size_r_bytes;
}
@@ -765,6 +820,14 @@ size_t llama_memory_recurrent::size_s_bytes() const {
}
}
for (const auto * sp : { &spk_l, &spv_l, &spgb_l }) {
for (const auto & s : *sp) {
if (s != nullptr) {
size_s_bytes += ggml_nbytes(s);
}
}
}
return size_s_bytes;
}
@@ -907,6 +970,10 @@ void llama_memory_recurrent::state_write_meta(llama_io_write_i & io, const std::
io.write(&seq_id, sizeof(seq_id));
}
}
if (rs_replay) {
io.write(&cell.rs_pend, sizeof(cell.rs_pend));
}
}
}
}
@@ -929,7 +996,7 @@ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std::
io.write(&r_type_i, sizeof(r_type_i));
// Write row size of R tensor
const uint64_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r());
const uint64_t r_size_row = r_l[il]->nb[1];
io.write(&r_size_row, sizeof(r_size_row));
// Write each logical cell row range. With pending recurrent rollback,
@@ -942,7 +1009,7 @@ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std::
// the PLE conv history is a second recurrent row, so it has to travel with the first
if (p_l[il] != nullptr) {
const uint64_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state());
const uint64_t p_size_row = p_l[il]->nb[1];
io.write(&p_size_row, sizeof(p_size_row));
for (const auto & range : cell_ranges) {
@@ -1004,6 +1071,22 @@ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std::
}
}
}
// rs_replay pending inputs travel with their cells
if (rs_replay) {
for (uint32_t il = 0; il < n_layer; ++il) {
for (ggml_tensor * t : { spk_l[il], spv_l[il], spgb_l[il] }) {
if (t == nullptr) continue;
const uint64_t size_row = t->nb[1];
io.write(&size_row, sizeof(size_row));
for (const auto & range : cell_ranges) {
io.write_tensor(t, range.first * size_row, (range.second - range.first) * size_row);
}
}
}
}
}
bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell_count, llama_seq_id dest_seq_id) {
@@ -1024,6 +1107,8 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell
llama_ubatch ubatch = balloc.ubatch_reserve(cell_count, 1);
std::vector<uint32_t> rs_pend(cell_count, 0);
for (uint32_t i = 0; i < cell_count; ++i) {
llama_pos pos;
uint32_t n_seq_id;
@@ -1036,6 +1121,10 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell
return false;
}
if (rs_replay) {
io.read(&rs_pend[i], sizeof(rs_pend[i]));
}
ubatch.pos[i] = pos;
}
ubatch.n_seq_id[0] = 1;
@@ -1053,6 +1142,11 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell
GGML_ASSERT(cells[head + cell_count - 1].pos == ubatch.pos[cell_count - 1]);
GGML_ASSERT(cells[head].has_seq_id(dest_seq_id));
GGML_ASSERT(cells[head + cell_count - 1].has_seq_id(dest_seq_id));
for (uint32_t i = 0; i < cell_count; ++i) {
cells[head + i].rs_pend = rs_pend[i];
cells[head + i].rs_max = 0;
}
} else {
// whole KV cache restore
@@ -1092,6 +1186,10 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell
}
tail = i;
}
if (rs_replay) {
io.read(&cell.rs_pend, sizeof(cell.rs_pend));
}
}
head = 0;
@@ -1143,7 +1241,7 @@ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell
// Read row size of key
uint64_t r_size_row_ref;
io.read(&r_size_row_ref, sizeof(r_size_row_ref));
const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r());
const size_t r_size_row = r_l[il]->nb[1];
if (r_size_row != r_size_row_ref) {
LLAMA_LOG_ERROR("%s: mismatched r row size (%zu != %zu, layer %d)\n", __func__, r_size_row, (size_t) r_size_row_ref, il);
return false;
@@ -1157,7 +1255,7 @@ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell
if (p_l[il] != nullptr) {
uint64_t p_size_row_ref;
io.read(&p_size_row_ref, sizeof(p_size_row_ref));
const size_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state());
const size_t p_size_row = p_l[il]->nb[1];
if (p_size_row != p_size_row_ref) {
LLAMA_LOG_ERROR("%s: mismatched ple row size (%zu != %zu, layer %d)\n", __func__, p_size_row, (size_t) p_size_row_ref, il);
return false;
@@ -1242,6 +1340,25 @@ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell
}
}
if (rs_replay) {
for (uint32_t il = 0; il < n_layer; ++il) {
for (ggml_tensor * t : { spk_l[il], spv_l[il], spgb_l[il] }) {
if (t == nullptr) continue;
uint64_t size_row_ref;
io.read(&size_row_ref, sizeof(size_row_ref));
if (size_row_ref != t->nb[1]) {
LLAMA_LOG_ERROR("%s: mismatched pending row size (%zu != %zu, layer %d)\n", __func__, t->nb[1], (size_t) size_row_ref, il);
return false;
}
if (cell_count) {
io.read_tensor(t, head * t->nb[1], cell_count * t->nb[1]);
}
}
}
}
return true;
}
@@ -1264,7 +1381,7 @@ void llama_memory_recurrent::state_clear(llama_seq_id seq_id, uint32_t cell_head
for (uint32_t il = 0; il < n_layer; ++il) {
if (r_l[il] != nullptr) {
const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r());
const size_t r_size_row = r_l[il]->nb[1];
ggml_backend_tensor_memset(r_l[il], 0, cell_head * r_size_row, cell_count * r_size_row);
}
@@ -1274,7 +1391,7 @@ void llama_memory_recurrent::state_clear(llama_seq_id seq_id, uint32_t cell_head
}
if (p_l[il] != nullptr) {
const size_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state());
const size_t p_size_row = p_l[il]->nb[1];
ggml_backend_tensor_memset(p_l[il], 0, cell_head * p_size_row, cell_count * p_size_row);
}
}
@@ -1360,6 +1477,26 @@ ggml_tensor * llama_memory_recurrent_context::get_p_l(int32_t il) const {
return mem->p_l[il];
}
ggml_tensor * llama_memory_recurrent_context::get_spk_l(int32_t il) const {
return mem->spk_l[il];
}
ggml_tensor * llama_memory_recurrent_context::get_spv_l(int32_t il) const {
return mem->spv_l[il];
}
ggml_tensor * llama_memory_recurrent_context::get_spgb_l(int32_t il) const {
return mem->spgb_l[il];
}
bool llama_memory_recurrent_context::get_rs_replay() const {
return mem->rs_replay;
}
uint32_t llama_memory_recurrent_context::get_rs_rep(int i) const {
return is_full ? 0 : mem->cells[i + mem->head].rs_rep;
}
int32_t llama_memory_recurrent_context::s_copy(int i) const {
const uint32_t cell_idx = i + mem->head;
const int32_t src0 = mem->cells[cell_idx].src0;
+19 -1
View File
@@ -25,6 +25,7 @@ public:
uint32_t mem_size,
uint32_t n_seq_max,
uint32_t n_rs_seq,
bool rs_replay,
const layer_filter_cb & filter);
~llama_memory_recurrent() = default;
@@ -77,6 +78,9 @@ public:
// per-seq rollback index
std::vector<uint32_t> rs_idx;
// deferred commit: keep one state plane plus the inputs of the last ubatch, replay the accepted part in the next ubatch
bool rs_replay = false;
void set_rs_idx(llama_seq_id seq_id, uint32_t idx);
// computed before each graph build
@@ -93,9 +97,13 @@ public:
int32_t tail = -1;
// largest rollback whose snapshot the last ubatch guarantees: a ubatch of n <= n_rs_seq + 1 tokens
// writes snapshots 0..n-1, a longer one only guarantees the final state (ggml_gated_delta_net)
// writes snapshots 0..n-1, a longer one only guarantees the final state (ggml_ssm_scan)
uint32_t rs_max = 0;
// rs_replay: valid tokens in the pending rows, and the pending tokens the current ubatch replays
uint32_t rs_pend = 0;
uint32_t rs_rep = 0;
std::set<llama_seq_id> seq_id;
bool has_seq_id(const llama_seq_id & id) const {
@@ -118,6 +126,10 @@ public:
std::vector<ggml_tensor *> s_l;
// a second conv history that must stay replicated across devices, so it cannot share the r row
std::vector<ggml_tensor *> p_l;
// rs_replay pending gdn inputs: k, v, and the gates then the betas
std::vector<ggml_tensor *> spk_l;
std::vector<ggml_tensor *> spv_l;
std::vector<ggml_tensor *> spgb_l;
private:
//const llama_model & model;
@@ -184,9 +196,15 @@ public:
ggml_tensor * get_r_l(int32_t il) const;
ggml_tensor * get_s_l(int32_t il) const;
ggml_tensor * get_p_l(int32_t il) const;
ggml_tensor * get_spk_l (int32_t il) const;
ggml_tensor * get_spv_l (int32_t il) const;
ggml_tensor * get_spgb_l(int32_t il) const;
int32_t s_copy(int i) const;
bool get_rs_replay() const;
uint32_t get_rs_rep(int i) const; // pending tokens replayed by ubatch seq i
private:
const llama_memory_status status;
+62 -6
View File
@@ -468,6 +468,9 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
static const std::regex pattern_r_cache ("cache_r_l\\d*");
static const std::regex pattern_ple_r_cache ("cache_ple_r_l\\d*");
static const std::regex pattern_s_cache ("cache_s_l\\d*");
static const std::regex pattern_spk_cache ("cache_spk_l\\d*");
static const std::regex pattern_spv_cache ("cache_spv_l\\d*");
static const std::regex pattern_spgb_cache ("cache_spgb_l\\d*");
static const std::regex pattern_ssm_conv1d ("blk\\.\\d*\\.ssm_conv1d.weight");
static const std::regex pattern_ssm_out_weight ("blk\\.\\d*\\.ssm_out.weight");
static const std::regex pattern_kda_conv1d ("blk\\.\\d*\\.ssm_conv1d_(q|k|v)\\.weight");
@@ -577,7 +580,9 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_2, "attn_output.weight");
}
if (std::regex_match(tensor_name, pattern_ssm_dt) || std::regex_match(tensor_name, pattern_ssm_a) ||
std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache)) {
std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache) ||
std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) ||
std::regex_match(tensor_name, pattern_spgb_cache)) {
return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_0, "attn_output.weight");
}
}
@@ -642,7 +647,9 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
std::regex_match(tensor_name, pattern_ssm_beta_alpha) || std::regex_match(tensor_name, pattern_ssm_beta_alpha_cat)) {
return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_1, "ssm_out.weight");
}
if (std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache)) {
if (std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache) ||
std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) ||
std::regex_match(tensor_name, pattern_spgb_cache)) {
if (ud->model->arch == LLM_ARCH_LFM2 || ud->model->arch == LLM_ARCH_LFM2MOE || ud->model->arch == LLM_ARCH_LFM3) {
// the LFM2 shortconv block runs fully mirrored, so its conv state must be mirrored too
return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_MIRRORED, "");
@@ -697,10 +704,22 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
auto get_split_segments = [&](int axis, uint32_t il) -> std::vector<std::pair<int64_t, uint32_t>> {
if (is_glm5_next && std::regex_match(tensor_name, pattern_r_cache)) {
// the conv state holds the q, k and v windows one after the other
const int64_t conv_state_size = (hparams.ssm_d_conv - 1) * hparams.n_head(il) * hparams.n_embd_head_kda;
GGML_ASSERT(tensor->ne[axis] == 3*conv_state_size);
const int64_t d_inner = hparams.n_head(il) * hparams.n_embd_head_kda;
const int64_t conv_state_size = (hparams.ssm_d_conv - 1) * d_inner;
if (tensor->ne[axis] != 3*conv_state_size) {
// replay: q, k and v histories [d_inner, window + pending], every column is a block of heads
GGML_ASSERT(tensor->ne[axis] % (3*d_inner) == 0);
return {{d_inner, uint32_t(tensor->ne[axis] / d_inner)}};
}
return {{conv_state_size, 3}};
}
if (is_glm5_next && (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) ||
std::regex_match(tensor_name, pattern_spgb_cache))) {
// replay pending inputs, per token: k [S_k, H], v [S_v, H], then the gates [S_v, H] and the betas (in element 0)
const int64_t d_inner = hparams.n_head(il) * hparams.n_embd_head_kda;
GGML_ASSERT(tensor->ne[axis] % d_inner == 0);
return {{d_inner, uint32_t(tensor->ne[axis] / d_inner)}};
}
// TODO: deduplicate condition [TAG_SPLIT_QGATE_QWEN]
// zonos3 has the qwen35 GDN layout, its attention layers have no fused qkv
if (ud->model->arch == LLM_ARCH_QWEN3NEXT || ud->model->arch == LLM_ARCH_QWEN35 || ud->model->arch == LLM_ARCH_QWEN35MOE || ud->model->arch == LLM_ARCH_CLEF || ud->model->arch == LLM_ARCH_CLOVER_MOE ||
@@ -731,6 +750,8 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
return {{key_dim, 2}, {value_dim, 1}};
}
if (std::regex_match(tensor_name, pattern_r_cache)) {
// the replay layouts need the Qwen 3.5 pattern, llama_context keeps Qwen 3 Next on snapshots
GGML_ASSERT(tensor->ne[axis] == (2*key_dim + value_dim) * (hparams.ssm_d_conv - 1));
return {{key_dim * (hparams.ssm_d_conv - 1), 2}, {value_dim * (hparams.ssm_d_conv - 1), 1}};
}
} else {
@@ -755,11 +776,26 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
return {{n_k_heads, head_ratio}};
}
if (std::regex_match(tensor_name, pattern_r_cache)) {
const int64_t n_conv_ch = 2*key_dim + value_dim;
if (tensor->ne[axis] != n_conv_ch * (hparams.ssm_d_conv - 1)) {
// replay: [channels, window + pending] per cell, every column is a q, k, v block
GGML_ASSERT(tensor->ne[axis] % n_conv_ch == 0);
return {{key_dim, uint32_t((2 + head_ratio) * (tensor->ne[axis] / n_conv_ch))}};
}
return {{key_dim * (hparams.ssm_d_conv - 1), 2 + head_ratio}};
}
if (std::regex_match(tensor_name, pattern_s_cache)) {
return {{n_k_heads * head_v_dim * head_v_dim, head_ratio}};
}
// replay pending inputs, per token: k [S_k, H_k], v [S_v, H_v], then the gates and betas [H_v]
if (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache)) {
GGML_ASSERT(tensor->ne[axis] % key_dim == 0);
return {{key_dim, uint32_t(tensor->ne[axis] / key_dim)}};
}
if (std::regex_match(tensor_name, pattern_spgb_cache)) {
GGML_ASSERT(tensor->ne[axis] % n_k_heads == 0);
return {{n_k_heads, uint32_t(tensor->ne[axis] / n_k_heads)}};
}
}
// the FFN is the same for Qwen 3 Next and Qwen 3.5:
@@ -815,7 +851,14 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
return {granularity_qkv / head_dim};
}
if (std::regex_match(tensor_name, pattern_r_cache)) {
return std::vector<int64_t>(segments.size(), granularity_qkv * (hparams.ssm_d_conv - 1));
// replay: channels first, each segment is a single conv column
const int64_t conv_state_size = (hparams.ssm_d_conv - 1) * hparams.n_head(il) * head_dim;
const bool replay = tensor->ne[0] != 3*conv_state_size;
return std::vector<int64_t>(segments.size(), granularity_qkv * (replay ? 1 : hparams.ssm_d_conv - 1));
}
if (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) ||
std::regex_match(tensor_name, pattern_spgb_cache)) {
return std::vector<int64_t>(segments.size(), granularity_qkv);
}
if (std::regex_match(tensor_name, pattern_s_cache)) {
return {granularity_qkv * head_dim};
@@ -852,11 +895,20 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
return std::vector<int64_t>(segments.size(), 2 * (granularity_qkv / head_dim));
}
if (std::regex_match(tensor_name, pattern_r_cache)) {
return std::vector<int64_t>(segments.size(), granularity_qkv * (hparams.ssm_d_conv - 1));
// replay: [channels, window + pending], each segment is a single conv column
const int64_t n_conv_ch = 2*hparams.ssm_n_group*hparams.ssm_d_state + hparams.ssm_d_inner;
const bool replay = tensor->ne[0] != n_conv_ch * (hparams.ssm_d_conv - 1);
return std::vector<int64_t>(segments.size(), granularity_qkv * (replay ? 1 : hparams.ssm_d_conv - 1));
}
if (std::regex_match(tensor_name, pattern_s_cache)) {
return std::vector<int64_t>(segments.size(), granularity_qkv * head_dim);
}
if (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache)) {
return std::vector<int64_t>(segments.size(), granularity_qkv);
}
if (std::regex_match(tensor_name, pattern_spgb_cache)) {
return std::vector<int64_t>(segments.size(), granularity_qkv / head_dim);
}
} else {
// regular attention
const uint32_t n_gqa = hparams.n_gqa(il);
@@ -3220,6 +3272,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
/* recurrent_rs_size */ std::max((uint32_t) 1, cparams.n_seq_max),
/* n_seq_max */ cparams.n_seq_max,
/* n_rs_seq */ cparams.n_rs_seq,
/* rs_replay */ cparams.rs_replay,
/* offload */ cparams.offload_kqv,
/* unified */ cparams.kv_unified,
/* filter_attn */ std::move(filter_attn),
@@ -3433,6 +3486,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
std::max((uint32_t) 1, cparams.n_seq_max),
cparams.n_seq_max,
cparams.n_rs_seq,
false,
nullptr);
} else if (llm_arch_is_hybrid(arch) && !mtp_on_hybrid_qwen && !mtp_on_hybrid_nemotron) {
// The main difference between hybrid architectures is the
@@ -3527,6 +3581,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
/* recurrent_kv_size */ std::max((uint32_t) 1, cparams.n_seq_max),
/* n_seq_max */ cparams.n_seq_max,
/* n_rs_seq */ cparams.n_rs_seq,
/* rs_replay */ cparams.rs_replay,
/* offload */ cparams.offload_kqv,
/* unified */ cparams.kv_unified,
/* filter_attn */ std::move(filter_attn),
@@ -3547,6 +3602,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
/* recurrent_kv_size */ std::max((uint32_t) 1, cparams.n_seq_max),
/* n_seq_max */ cparams.n_seq_max,
/* n_rs_seq */ cparams.n_rs_seq,
/* rs_replay */ cparams.rs_replay,
/* offload */ cparams.offload_kqv,
/* unified */ cparams.kv_unified,
/* filter_attn */ std::move(filter_attn),
+11 -11
View File
@@ -884,7 +884,7 @@ static std::unordered_map<std::string, ggml_type> target_bpw_type(
};
// Quantization types
constexpr ggml_type quant_types[] = {
static constexpr ggml_type quant_types[] = {
GGML_TYPE_IQ1_S,
GGML_TYPE_IQ1_M,
GGML_TYPE_IQ2_XXS,
@@ -908,16 +908,16 @@ static std::unordered_map<std::string, ggml_type> target_bpw_type(
GGML_TYPE_BF16,
};
constexpr double EPSILON = 1e-12;
constexpr double INFINITE = std::numeric_limits<double>::infinity();
constexpr uint64_t STATE_MAGIC = 0x4250572d5632; // "BPW-V2"
constexpr uint64_t HASH_MAGIC = 0xeabada55cafed00d;
constexpr float ffn_down_boost = 6.0f;
constexpr float output_boost = 3.0f;
constexpr float tied_embd_boost = 2.5f;
constexpr float attn_v_boost = 1.25f;
constexpr float boost_taper = 2.2f; // boost starves other tensors below 2.2 bpw
constexpr double downward_threshold = 0.08; // potential gains smaller than 8% are not trusted
static constexpr double EPSILON = 1e-12;
static constexpr double INFINITE = std::numeric_limits<double>::infinity();
static constexpr uint64_t STATE_MAGIC = 0x4250572d5632; // "BPW-V2"
static constexpr uint64_t HASH_MAGIC = 0xeabada55cafed00d;
static constexpr float ffn_down_boost = 6.0f;
static constexpr float output_boost = 3.0f;
static constexpr float tied_embd_boost = 2.5f;
static constexpr float attn_v_boost = 1.25f;
static constexpr float boost_taper = 2.2f; // boost starves other tensors below 2.2 bpw
static constexpr double downward_threshold = 0.08; // potential gains smaller than 8% are not trusted
const char * func = __func__;
// --target-exclude must leave at least one quant type in the pool
+20 -13
View File
@@ -163,22 +163,29 @@ std::unique_ptr<llm_graph_context> llama_model_bailingmoe3::build_arch_graph(con
ggml_tensor * llama_model_bailingmoe3::graph::build_causal_conv1d(
llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs) {
int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs, int il) {
const int64_t d_inner = head_dim * n_head;
const int64_t conv_state_size = (d_conv - 1) * d_inner;
const int64_t total_state_size = 3 * conv_state_size;
ggml_tensor * conv_state = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
(d_conv - 1) * ggml_element_size(conv_state_all),
total_state_size * ggml_element_size(conv_state_all),
qkv * conv_state_size * ggml_element_size(conv_state_all));
ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x);
x_proj = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs);
ggml_tensor * conv_x = ggml_concat(ctx0, conv_state, ggml_transpose(ctx0, x_proj), 0);
build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
ggml_row_size(conv_states_all->type, qkv * conv_state_size));
ggml_tensor * conv_x = nullptr;
if (cparams.rs_replay) {
// the row holds the q, k and v conv histories one after the other
conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_proj, d_conv - 1, d_inner, il, conv_state_all, qkv);
} else {
ggml_tensor * conv_state = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
(d_conv - 1) * ggml_element_size(conv_state_all),
total_state_size * ggml_element_size(conv_state_all),
qkv * conv_state_size * ggml_element_size(conv_state_all));
conv_x = ggml_concat(ctx0, conv_state, ggml_transpose(ctx0, x_proj), 0);
build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
ggml_row_size(conv_states_all->type, qkv * conv_state_size));
}
ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner);
ggml_tensor * out = ggml_ssm_conv(ctx0, conv_x, conv_weight);
@@ -227,17 +234,17 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) :
if (hparams.is_recr(il)) {
const auto * mctx_cur = inp_rs->mctx;
ggml_tensor * conv_states_all = mctx_cur->get_r_l(il);
ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs);
ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs);
ggml_tensor * q = build_causal_conv1d(
inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv,
d_conv, head_dim, n_head, n_seq_tokens, n_seqs);
d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il);
ggml_tensor * k = build_causal_conv1d(
inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv,
d_conv, head_dim, n_head, n_seq_tokens, n_seqs);
d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il);
ggml_tensor * v = build_causal_conv1d(
inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv,
d_conv, head_dim, n_head, n_seq_tokens, n_seqs);
d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il);
ggml_tensor * gate = ggml_mul_mat(ctx0, layer.ssm_f_a, cur);
gate = ggml_add(ctx0, gate, layer.ssm_dt_b);
+179 -57
View File
@@ -32,8 +32,8 @@ std::pair<ggml_tensor *, ggml_tensor *> llm_build_delta_net_base::build_delta_ne
GGML_ASSERT(b->ne[0] == 1 && b->ne[1] == H_v && b->ne[2] == n_tokens && b->ne[3] == n_seqs);
GGML_ASSERT(s->ne[0] == S_v && s->ne[1] == S_v && s->ne[2] == H_v && s->ne[3] == n_seqs);
// K=1: output carries the final state only. state s is 4D [S_v, S_v, H_v, n_seqs].
ggml_tensor * result = ggml_gated_delta_net(ctx0, q, k, v, g, b, s, /*K=*/1);
// output carries the final state. state s is 4D [S_v, S_v, H_v, n_seqs].
ggml_tensor * result = ggml_gated_delta_net_ext(ctx0, q, k, v, g, b, s, nullptr, nullptr, nullptr, nullptr, false);
ggml_tensor * output = ggml_view_4d(ctx0, result,
S_v, H_v, n_tokens, n_seqs,
ggml_row_size(result->type, S_v),
@@ -59,6 +59,10 @@ ggml_tensor * llm_build_delta_net_base::build_conv_state(
int il) {
const int64_t n_seqs = ubatch.n_seqs;
if (cparams.rs_replay) {
return build_conv_state_replay(inp, conv_states_all, qkv_mixed, conv_kernel_size - 1, conv_channels, il);
}
ggml_tensor * conv_states = build_rs(inp, conv_states_all, hparams.n_embd_r(), n_seqs);
cb(conv_states, "conv_states", il);
@@ -76,6 +80,165 @@ ggml_tensor * llm_build_delta_net_base::build_conv_state(
return conv_input;
}
// [TAG_RECURRENT_REPLAY]
// rs_replay keeps one committed state per seq plus the inputs of the last ubatch when it is short enough to be rolled
// back (2 <= n_seq_tokens <= n_rs_seq + 1). The next ubatch first replays the pending tokens that seq_rm kept, commits
// the result and then runs its own tokens. Must match the rule in llama_memory_recurrent::find_slot.
// Every ubatch builds the same nodes, with or without pending tokens, so the allocation planned at reserve time
// stays valid and the scheduler never re-plans.
static bool rs_replay_keep(const llama_cparams & cparams, int64_t n_seq_tokens) {
return n_seq_tokens >= 2 && n_seq_tokens <= (int64_t) cparams.n_rs_seq + 1;
}
ggml_tensor * llm_build_delta_net_base::build_conv_state_replay(
llm_graph_input_rs * inp,
ggml_tensor * conv_states_all,
ggml_tensor * x,
int64_t n_conv,
int64_t channels,
int il,
ggml_tensor * hist_rows,
int64_t blk) {
const auto * mctx_cur = inp->mctx;
const auto kv_head = mctx_cur->get_head();
const int64_t n_hist = n_conv + cparams.n_rs_seq + 1;
const int64_t n_seqs = ubatch.n_seqs;
const int64_t n_seq_tokens = ubatch.n_seq_tokens;
GGML_ASSERT(conv_states_all->ne[0] % (channels*n_hist) == 0);
const int64_t n_blk = conv_states_all->ne[0] / (channels*n_hist);
GGML_ASSERT(blk >= 0 && blk < n_blk);
GGML_ASSERT(x->ne[0] == channels && x->ne[1] == n_seq_tokens && x->ne[2] == n_seqs);
GGML_ASSERT(n_conv <= inp->n_conv);
if (hist_rows == nullptr) {
hist_rows = build_rs(inp, conv_states_all, conv_states_all->ne[0], n_seqs);
}
GGML_ASSERT(hist_rows->ne[0] == conv_states_all->ne[0] && hist_rows->ne[1] == n_seqs);
// channels first: [window | pending], the histories of a row one after the other
ggml_tensor * hist = nullptr;
if (n_blk == 1) {
hist = ggml_reshape_3d(ctx0, hist_rows, channels, n_hist, n_seqs);
} else {
hist = ggml_reshape_4d(ctx0, hist_rows, channels, n_hist, n_blk, n_seqs);
hist = ggml_view_3d(ctx0, hist, channels, n_hist, n_seqs, hist->nb[1], hist->nb[3], blk*hist->nb[2]);
}
cb(hist, "conv_hist", il);
ggml_tensor * win_cols = n_conv == inp->rep_cols_r->ne[0] ? inp->rep_cols_r : inp->rep_cols_p;
GGML_ASSERT(win_cols && win_cols->ne[0] == n_conv);
// [channels, n_conv + n_seq_tokens]: the window after the kept pending tokens, then the new tokens
// (built channels first, a transposed concat is much slower than a concat and a transpose)
ggml_tensor * cols = ggml_concat(ctx0, ggml_get_rows(ctx0, hist, win_cols), x, 1);
ggml_tensor * conv_input = ggml_cont(ctx0, ggml_transpose(ctx0, cols));
cb(conv_input, "conv_input", il);
// keep: the new tokens stay pending behind the committed window, else commit the last n_conv columns
const int64_t n_dst = rs_replay_keep(cparams, n_seq_tokens) ? n_conv + n_seq_tokens : n_conv;
ggml_tensor * tail = ggml_view_3d(ctx0, cols, channels, n_dst, n_seqs, cols->nb[1], cols->nb[2],
(n_conv + n_seq_tokens - n_dst)*cols->nb[1]);
// the rows as [channels, n_blk*n_hist, cells], so that the view of the ubatch cells keeps their strides (-sm tensor)
ggml_tensor * hist_all = ggml_reshape_3d(ctx0, conv_states_all, channels, n_blk*n_hist, conv_states_all->ne[1]);
ggml_tensor * hist_dst = ggml_view_3d(ctx0, hist_all, channels, n_dst, n_seqs, hist_all->nb[1], hist_all->nb[2],
kv_head*hist_all->nb[2] + blk*n_hist*hist_all->nb[1]);
ggml_build_forward_expand(gf, ggml_cpy(ctx0, tail, hist_dst));
return conv_input;
}
ggml_tensor * llm_build_delta_net_base::build_recurrent_attn_replay(
llm_graph_input_rs * inp,
ggml_tensor * ssm_states_all,
ggml_tensor * q,
ggml_tensor * k,
ggml_tensor * v,
ggml_tensor * g,
ggml_tensor * b,
ggml_tensor * s,
int il) {
const auto * mctx_cur = inp->mctx;
const auto kv_head = mctx_cur->get_head();
const int64_t n_pend = cparams.n_rs_seq + 1;
const int64_t n_seqs = ubatch.n_seqs;
const int64_t n_seq_tokens = ubatch.n_seq_tokens;
const int64_t S_k = k->ne[0];
const int64_t H_k = k->ne[1];
const int64_t S_v = v->ne[0];
const int64_t H_v = v->ne[1];
const int64_t g0 = g->ne[0];
const size_t row_size = ggml_row_size(ssm_states_all->type, hparams.n_embd_s());
// the pending inputs of the cells: k [S_k, H_k, n_pend], v [S_v, H_v, n_pend], gb [g0, H_v, 2*n_pend] (the gates,
// then the betas). The views of the ubatch cells keep the strides of these 4D views, so that -sm tensor can split
// them by heads
ggml_tensor * spk = mctx_cur->get_spk_l(il);
ggml_tensor * spv = mctx_cur->get_spv_l(il);
ggml_tensor * spgb = mctx_cur->get_spgb_l(il);
ggml_tensor * ck = ggml_reshape_4d(ctx0, spk, S_k, H_k, n_pend, spk->ne[1]);
ggml_tensor * cv = ggml_reshape_4d(ctx0, spv, S_v, H_v, n_pend, spv->ne[1]);
ggml_tensor * cgb = ggml_reshape_4d(ctx0, spgb, g0, H_v, 2*n_pend, spgb->ne[1]);
const auto gather = [&](ggml_tensor * rows, ggml_tensor * c) {
return ggml_reshape_4d(ctx0, build_rs(inp, rows, rows->ne[0], n_seqs), c->ne[0], c->ne[1], c->ne[2], n_seqs);
};
ggml_tensor * pk = gather(spk, ck);
ggml_tensor * pv = gather(spv, cv);
ggml_tensor * pgb = gather(spgb, cgb);
const bool keep = rs_replay_keep(cparams, n_seq_tokens);
ggml_tensor * state_dst = ggml_view_2d(ctx0, ssm_states_all, hparams.n_embd_s(), n_seqs, ssm_states_all->nb[1], kv_head*row_size);
// store the inputs of the new tokens as pending; only used when keep, a longer ubatch stores its first n_pend tokens
const auto store_inputs = [&]() {
const int64_t n_st = std::min(n_seq_tokens, n_pend);
const auto store = [&](ggml_tensor * x, ggml_tensor * c, int64_t t0) {
ggml_tensor * x_st = ggml_view_4d(ctx0, x, x->ne[0], x->ne[1], n_st, n_seqs, x->nb[1], x->nb[2], x->nb[3], 0);
ggml_tensor * dst = ggml_view_4d(ctx0, c, x->ne[0], x->ne[1], n_st, n_seqs, c->nb[1], c->nb[2], c->nb[3],
kv_head*c->nb[3] + t0*c->nb[2]);
ggml_build_forward_expand(gf, ggml_cpy(ctx0, x_st, dst));
};
store(k, ck, 0);
store(v, cv, 0);
store(g, cgb, 0);
store(b, cgb, n_pend);
};
// the gdn op replays the kept pending tokens, then runs the new tokens
ggml_tensor * result = ggml_gated_delta_net_ext(ctx0, q, k, v, g, b, s, pk, pv, pgb, inp->rep_n, keep);
ggml_tensor * output = ggml_view_4d(ctx0, result, S_v, H_v, n_seq_tokens, n_seqs,
ggml_row_size(result->type, S_v),
ggml_row_size(result->type, S_v*H_v),
ggml_row_size(result->type, S_v*H_v*n_seq_tokens), 0);
cb(output, "attn_output", il);
// keep: the state after the replay, else the final state
ggml_tensor * new_state = ggml_view_2d(ctx0, result, hparams.n_embd_s(), n_seqs,
ggml_row_size(result->type, hparams.n_embd_s()),
ggml_row_size(result->type, S_v*H_v*n_seq_tokens*n_seqs));
ggml_build_forward_expand(gf, ggml_cpy(ctx0, new_state, state_dst));
store_inputs();
return output;
}
ggml_tensor * llm_build_delta_net_base::build_recurrent_attn(
llm_graph_input_rs * inp,
ggml_tensor * ssm_states_all,
@@ -86,67 +249,26 @@ ggml_tensor * llm_build_delta_net_base::build_recurrent_attn(
ggml_tensor * b,
ggml_tensor * s,
int il) {
const auto * mctx_cur = inp->mctx;
const auto kv_head = mctx_cur->get_head();
const uint32_t mem_size = mctx_cur->get_size();
const int64_t S_v = s->ne[0];
const int64_t H_v = s->ne[2];
const int64_t n_seqs = s->ne[3];
const int64_t n_seq_tokens = q->ne[2];
const bool keep = cparams.n_rs_seq > 0;
if (!keep) {
auto attn_out = build_delta_net(q, k, v, g, b, s);
ggml_tensor * output = attn_out.first;
ggml_tensor * new_state = attn_out.second;
cb(output, "attn_output", il);
cb(new_state, "new_state", il);
ggml_build_forward_expand(gf,
ggml_cpy(ctx0, new_state,
ggml_view_2d(ctx0, ssm_states_all, hparams.n_embd_s(), n_seqs, ssm_states_all->nb[1],
kv_head * hparams.n_embd_s() * ggml_element_size(ssm_states_all))));
return output;
if (cparams.rs_replay) {
return build_recurrent_attn_replay(inp, ssm_states_all, q, k, v, g, b, s, il);
}
const int64_t D = S_v * S_v * H_v;
const int64_t K = cparams.n_rs_seq + 1;
// a rollback replays the kept tokens, the gdn op does not write state snapshots
GGML_ASSERT(cparams.n_rs_seq == 0);
// state s is 4D [S_v, S_v, H_v, n_seqs]; K snapshot slots are written into the output.
ggml_tensor * gdn_out = ggml_gated_delta_net(ctx0, q, k, v, g, b, s, K);
const int64_t attn_score_elems = S_v * H_v * n_seq_tokens * n_seqs;
const int64_t state_size_per_snap = S_v * S_v * H_v * n_seqs;
const auto kv_head = inp->mctx->get_head();
const int64_t n_seqs = s->ne[3];
ggml_tensor * output = ggml_view_4d(ctx0, gdn_out,
S_v, H_v, n_seq_tokens, n_seqs,
ggml_row_size(gdn_out->type, S_v),
ggml_row_size(gdn_out->type, S_v * H_v),
ggml_row_size(gdn_out->type, S_v * H_v * n_seq_tokens),
0);
auto attn_out = build_delta_net(q, k, v, g, b, s);
ggml_tensor * output = attn_out.first;
ggml_tensor * new_state = attn_out.second;
cb(output, "attn_output", il);
cb(new_state, "new_state", il);
const size_t row_size = hparams.n_embd_s() * ggml_element_size(ssm_states_all);
// op writes the last min(n_seq_tokens, K) snapshots; trailing slots are left unwritten
const int64_t n_written = std::min<int64_t>(n_seq_tokens, K);
// write the produced snapshots into the recurrent cache (snapshot slot i -> rollback group i)
ggml_tensor * src = ggml_view_3d(ctx0, gdn_out,
D, n_seqs, n_written,
ggml_row_size(gdn_out->type, D),
ggml_row_size(gdn_out->type, state_size_per_snap),
ggml_row_size(gdn_out->type, attn_score_elems));
ggml_tensor * dst = ggml_view_3d(ctx0, ssm_states_all,
D, n_seqs, n_written,
ssm_states_all->nb[1],
(size_t) mem_size * row_size,
(size_t) kv_head * row_size);
ggml_build_forward_expand(gf, ggml_cpy(ctx0, src, dst));
ggml_build_forward_expand(gf,
ggml_cpy(ctx0, new_state,
ggml_view_2d(ctx0, ssm_states_all, hparams.n_embd_s(), n_seqs, ssm_states_all->nb[1],
kv_head * hparams.n_embd_s() * ggml_element_size(ssm_states_all))));
return output;
}
+20 -13
View File
@@ -194,22 +194,29 @@ std::unique_ptr<llm_graph_context> llama_model_glm5_next::build_arch_graph(const
ggml_tensor * llama_model_glm5_next::graph::build_kda_conv1d(
llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs) {
int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il) {
const int64_t d_inner = head_dim * n_head_kda;
const int64_t conv_state_size = (d_conv - 1) * d_inner;
const int64_t n_embd_r_total = 3 * conv_state_size;
ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
(d_conv - 1) * ggml_element_size(conv_state_all),
n_embd_r_total * ggml_element_size(conv_state_all),
qkv * conv_state_size * ggml_element_size(conv_state_all));
ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x);
ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs);
ggml_tensor * conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0);
build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
ggml_row_size(conv_states_all->type, qkv * conv_state_size));
ggml_tensor * conv_x = nullptr;
if (cparams.rs_replay) {
// the row holds the q, k and v conv histories one after the other
conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_state_all, qkv);
} else {
ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
(d_conv - 1) * ggml_element_size(conv_state_all),
n_embd_r_total * ggml_element_size(conv_state_all),
qkv * conv_state_size * ggml_element_size(conv_state_all));
conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0);
build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
ggml_row_size(conv_states_all->type, qkv * conv_state_size));
}
ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner);
ggml_tensor * Xcur = ggml_ssm_conv(ctx0, conv_x, conv_weight);
@@ -796,11 +803,11 @@ ggml_tensor * llama_model_glm5_next::graph::build_kda_layer(
const auto * mctx_cur = inp_rs->mctx;
ggml_tensor * conv_states_all = mctx_cur->get_r_l(il);
ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs);
ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs);
ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
cb(Qcur, "kda_q_conv", il);
cb(Kcur, "kda_k_conv", il);
cb(Vcur, "kda_v_conv", il);
+20 -13
View File
@@ -355,22 +355,29 @@ llama_model_kimi_k3::graph::graph(const llm_graph_params & params) :
ggml_tensor * llama_model_kimi_k3::graph::build_kda_conv1d(
llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs) {
int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il) {
const int64_t d_inner = head_dim * n_head_kda;
const int64_t conv_state_size = (d_conv - 1) * d_inner;
const int64_t n_embd_r_total = 3 * conv_state_size;
ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
(d_conv - 1) * ggml_element_size(conv_state_all),
n_embd_r_total * ggml_element_size(conv_state_all),
qkv * conv_state_size * ggml_element_size(conv_state_all));
ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x);
ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs);
ggml_tensor * conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0);
build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
ggml_row_size(conv_states_all->type, qkv * conv_state_size));
ggml_tensor * conv_x = nullptr;
if (cparams.rs_replay) {
// the row holds the q, k and v conv histories one after the other
conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_state_all, qkv);
} else {
ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
(d_conv - 1) * ggml_element_size(conv_state_all),
n_embd_r_total * ggml_element_size(conv_state_all),
qkv * conv_state_size * ggml_element_size(conv_state_all));
conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0);
build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
ggml_row_size(conv_states_all->type, qkv * conv_state_size));
}
ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner);
ggml_tensor * Xcur = ggml_ssm_conv(ctx0, conv_x, conv_weight);
@@ -388,11 +395,11 @@ ggml_tensor * llama_model_kimi_k3::graph::build_kda_layer(
const auto * mctx_cur = inp_rs->mctx;
ggml_tensor * conv_states_all = mctx_cur->get_r_l(il);
ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs);
ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs);
ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
cb(Qcur, "kda_q_conv", il);
cb(Kcur, "kda_k_conv", il);
cb(Vcur, "kda_v_conv", il);
+20 -13
View File
@@ -391,22 +391,29 @@ llama_model_kimi_k31::graph::graph(const llm_graph_params & params) :
ggml_tensor * llama_model_kimi_k31::graph::build_kda_conv1d(
llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs) {
int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il) {
const int64_t d_inner = head_dim * n_head_kda;
const int64_t conv_state_size = (d_conv - 1) * d_inner;
const int64_t n_embd_r_total = 3 * conv_state_size;
ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
(d_conv - 1) * ggml_element_size(conv_state_all),
n_embd_r_total * ggml_element_size(conv_state_all),
qkv * conv_state_size * ggml_element_size(conv_state_all));
ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x);
ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs);
ggml_tensor * conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0);
build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
ggml_row_size(conv_states_all->type, qkv * conv_state_size));
ggml_tensor * conv_x = nullptr;
if (cparams.rs_replay) {
// the row holds the q, k and v conv histories one after the other
conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_state_all, qkv);
} else {
ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
(d_conv - 1) * ggml_element_size(conv_state_all),
n_embd_r_total * ggml_element_size(conv_state_all),
qkv * conv_state_size * ggml_element_size(conv_state_all));
conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0);
build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
ggml_row_size(conv_states_all->type, qkv * conv_state_size));
}
ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner);
ggml_tensor * Xcur = ggml_ssm_conv(ctx0, conv_x, conv_weight);
@@ -424,11 +431,11 @@ ggml_tensor * llama_model_kimi_k31::graph::build_kda_layer(
const auto * mctx_cur = inp_rs->mctx;
ggml_tensor * conv_states_all = mctx_cur->get_r_l(il);
ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs);
ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs);
ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
cb(Qcur, "kda_q_conv", il);
cb(Kcur, "kda_k_conv", il);
cb(Vcur, "kda_v_conv", il);
+29 -4
View File
@@ -67,6 +67,31 @@ struct llm_build_delta_net_base : public llm_graph_context {
ggml_tensor * b,
ggml_tensor * s,
int il);
// rs_replay variants: replay the kept pending tokens, then keep or commit the new ones [TAG_RECURRENT_REPLAY]
// x: [channels, n_seq_tokens, n_seqs] new conv inputs; returns [n_conv + n_seq_tokens, channels, n_seqs]
// a row of conv_states_all can hold several histories [channels, n_conv + n_pend] one after the other (KDA: q, k, v):
// blk picks one, and hist_rows are the rows of the ubatch cells (build_rs) shared by the blocks, nullptr gathers them
ggml_tensor * build_conv_state_replay(
llm_graph_input_rs * inp,
ggml_tensor * conv_states_all,
ggml_tensor * x,
int64_t n_conv,
int64_t channels,
int il,
ggml_tensor * hist_rows = nullptr,
int64_t blk = 0);
ggml_tensor * build_recurrent_attn_replay(
llm_graph_input_rs * inp,
ggml_tensor * ssm_states_all,
ggml_tensor * q,
ggml_tensor * k,
ggml_tensor * v,
ggml_tensor * g,
ggml_tensor * b,
ggml_tensor * s,
int il);
};
struct llm_build_lfm_base : public llm_graph_context {
@@ -2209,7 +2234,7 @@ struct llama_model_bailingmoe3 : public llama_model_base {
// causal conv1d over one of Q/K/V, qkv selects which third of the conv state row is used
ggml_tensor * build_causal_conv1d(llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs);
int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs, int il);
};
struct graph_mtp : public llm_graph_context {
@@ -3170,7 +3195,7 @@ struct llama_model_kimi_k3 : public llama_model_base {
// causal conv1d over one of Q/K/V, qkv selects which third of the conv state row is used
ggml_tensor * build_kda_conv1d(llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs);
int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il);
ggml_tensor * build_mla_layer(ggml_tensor * cur, const llama_layer & layer,
llm_graph_input_attn_k * inp_attn_k,
@@ -3207,7 +3232,7 @@ struct llama_model_kimi_k31 : public llama_model_base {
ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
int64_t d_conv, int64_t head_dim, int64_t n_head_kda,
int64_t n_seq_tokens, int64_t n_seqs);
int64_t n_seq_tokens, int64_t n_seqs, int il);
ggml_tensor * build_kda_layer(ggml_tensor * cur, const llama_layer & layer,
llm_graph_input_rs * inp_rs,
@@ -3294,7 +3319,7 @@ struct llama_model_glm5_next : public llama_model_base {
// causal conv1d over one of Q/K/V, qkv selects which third of the conv state row is used
ggml_tensor * build_kda_conv1d(llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs);
int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il);
ggml_tensor * build_kpool_select(ggml_tensor * cur, ggml_tensor * qr, const llama_layer & layer,
const llama_memory_hybrid_idx_context * mctx_hyb, llm_graph_input_kpool * inp_kpool, int il);
+4
View File
@@ -1373,6 +1373,10 @@ ggml_tensor * llama_model_qwen4exp::graph::build_conv_state_at(
int64_t state_cols,
int64_t channels,
int il) {
if (cparams.rs_replay) {
return build_conv_state_replay(inp, conv_states_all, x, state_cols, channels, il);
}
const int64_t n_seqs = ubatch.n_seqs;
const int64_t row_total = conv_states_all->ne[0];
+1 -1
View File
@@ -357,7 +357,7 @@ struct case_rollback_bound : ctx_test {
const llm_arch arch = llama_arch_from_string(arch_name);
// the DSV4 cache rebuilds snapshot d from the state before the ubatch, so d <= n is exact;
// the recurrent memory gets snapshots 0..n-1 from ggml_gated_delta_net, only for n <= n_rs_seq + 1
// the recurrent memory gets snapshots 0..n-1 from ggml_ssm_scan, only for n <= n_rs_seq + 1
const bool from_ubatch_start = arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41;
const auto make_ctx = [&]() {
+362 -70
View File
@@ -2258,6 +2258,20 @@ struct test_unary : public test_case {
};
struct test_unary_softplus_neg : public test_unary {
test_unary_softplus_neg() : test_unary(GGML_UNARY_OP_SOFTPLUS) {}
std::string vars() override {
return test_unary::vars() + ",neg";
}
void initialize_tensors(ggml_context * ctx) override {
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
init_tensor_uniform(t, -16.6f, -16.0f);
}
}
};
// GGML_OP_GLU
struct test_glu : public test_case {
const ggml_glu_op op;
@@ -5358,7 +5372,6 @@ struct test_gated_delta_net : public test_case {
const int v_repeat;
const bool permuted;
const bool kda;
const int64_t K; // snapshot slot count: 1 = final-only, >1 = last K states
const bool correlated;
const bool padded_v;
const bool padded_q;
@@ -5366,16 +5379,8 @@ struct test_gated_delta_net : public test_case {
// lower bound of the log-gate; a mild gate keeps the state alive over the whole sequence
const float g_min;
std::string op_desc(ggml_tensor * t) override {
GGML_UNUSED(t);
return "GATED_DELTA_NET";
}
// compare only the view returned by build_graph, not the full op output
bool run_whole_graph() override { return K > 1 && n_seq_tokens > K; }
std::string vars() override {
std::string s = VARS_TO_STR13(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, K, correlated, padded_v, padded_q, permuted_k);
std::string s = VARS_TO_STR12(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, correlated, padded_v, padded_q, permuted_k);
if (g_min != -20.0f) {
s += "," + VAR_TO_STR(g_min);
}
@@ -5384,9 +5389,9 @@ struct test_gated_delta_net : public test_case {
test_gated_delta_net(ggml_type type = GGML_TYPE_F32,
int64_t head_count = 4, int64_t head_size = 16, int64_t n_seq_tokens = 1, int64_t n_seqs = 1,
int v_repeat = 1, bool permuted = false, bool kda = false, int64_t K = 1, bool correlated = false, bool padded_v = false, bool padded_q = false, bool permuted_k = false, float g_min = -20.0f)
int v_repeat = 1, bool permuted = false, bool kda = false, bool correlated = false, bool padded_v = false, bool padded_q = false, bool permuted_k = false, float g_min = -20.0f)
: type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs),
v_repeat(v_repeat), permuted(permuted), kda(kda), K(K), correlated(correlated), padded_v(padded_v), padded_q(padded_q), permuted_k(permuted_k), g_min(g_min) {}
v_repeat(v_repeat), permuted(permuted), kda(kda), correlated(correlated), padded_v(padded_v), padded_q(padded_q), permuted_k(permuted_k), g_min(g_min) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
ggml_tensor * q;
@@ -5430,11 +5435,7 @@ struct test_gated_delta_net : public test_case {
k_permuted = ggml_permute(ctx, k_permuted, 0, 2, 1, 3);
k = ggml_cpy(ctx, k, k_permuted);
}
ggml_tensor * out = ggml_gated_delta_net(ctx, q, k, v, g, beta, state, K);
if (K > 1 && n_seq_tokens > K) {
// n_tokens > K: only slot 0 is guaranteed, so keep the scores and slot 0
out = ggml_view_2d(ctx, out, out->ne[0], out->ne[1] - (K - 1) * head_size * n_seqs, out->nb[1], 0);
}
ggml_tensor * out = ggml_gated_delta_net_ext(ctx, q, k, v, g, beta, state, nullptr, nullptr, nullptr, nullptr, false);
return out;
}
@@ -5462,6 +5463,115 @@ struct test_gated_delta_net : public test_case {
}
};
// GGML_OP_GATED_DELTA_NET with a replay of pending tokens (ggml_gated_delta_net_replay)
struct test_gated_delta_net_replay : public test_case {
const int64_t head_count; // k heads
const int64_t head_size;
const int64_t n_seq_tokens;
const int64_t n_seqs;
const int v_repeat;
const bool kda;
const int64_t n_pend;
const bool keep;
std::string vars() override {
return VARS_TO_STR8(head_count, head_size, n_seq_tokens, n_seqs, v_repeat, kda, n_pend, keep);
}
test_gated_delta_net_replay(int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 4, int64_t n_seqs = 1,
int v_repeat = 1, bool kda = false, int64_t n_pend = 4, bool keep = true)
: head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs),
v_repeat(v_repeat), kda(kda), n_pend(n_pend), keep(keep) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
const int64_t S = head_size;
const int64_t H_k = head_count;
const int64_t H = head_count * v_repeat;
const int64_t g0 = kda ? S : 1;
ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H_k, n_seq_tokens, n_seqs);
ggml_tensor * k = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H_k, n_seq_tokens, n_seqs);
ggml_tensor * v = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H, n_seq_tokens, n_seqs);
ggml_tensor * g = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, g0, H, n_seq_tokens, n_seqs);
ggml_tensor * beta = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, H, n_seq_tokens, n_seqs);
ggml_tensor * state = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, S, H, n_seqs);
// one spare token per seq in pend_k, so that its seq stride is not the dense one
ggml_tensor * pk = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H_k, n_pend + 1, n_seqs);
ggml_tensor * pv = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H, n_pend, n_seqs);
ggml_tensor * pgb = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, g0, H, 2*n_pend, n_seqs);
ggml_tensor * n_rep = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_seqs);
ggml_set_name(g, "g");
ggml_set_name(beta, "beta");
ggml_set_name(v, "v");
ggml_set_name(pk, "pend_k");
ggml_set_name(pv, "pend_v");
ggml_set_name(pgb, "pend_gb");
ggml_set_name(n_rep, "n_rep");
q = ggml_l2_norm(ctx, q, 1e-6f);
k = ggml_l2_norm(ctx, k, 1e-6f);
ggml_tensor * pk_tok = ggml_view_4d(ctx, pk, S, H_k, n_pend, n_seqs, pk->nb[1], pk->nb[2], pk->nb[3], 0);
return ggml_gated_delta_net_ext(ctx, q, k, v, g, beta, state, pk_tok, pv, pgb, n_rep, keep);
}
void initialize_tensors(ggml_context * ctx) override {
std::mt19937 rng(0x6d4e);
const int64_t S = head_size;
const int64_t H = head_count * v_repeat;
const int64_t g0 = kda ? S : 1;
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) {
if (ggml_is_view_op(t->op)) { continue; }
if (strcmp(t->name, "g") == 0) {
init_tensor_uniform(t, -20.0f, -1e-4f);
} else if (strcmp(t->name, "beta") == 0) {
init_tensor_uniform(t, 0.0f, 1.0f);
} else if (strcmp(t->name, "v") == 0) {
init_tensor_uniform(t, -0.3f, 5.0f);
} else if (strcmp(t->name, "n_rep") == 0) {
std::vector<int32_t> data(n_seqs);
for (auto & x : data) {
x = std::uniform_int_distribution<int32_t>(0, n_pend)(rng);
}
ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(int32_t));
} else if (strcmp(t->name, "pend_k") == 0) {
// unit rows, as the l2 norm leaves them
std::vector<float> data(ggml_nelements(t));
std::uniform_real_distribution<float> u(-1.0f, 1.0f);
for (int64_t i = 0; i < ggml_nelements(t)/S; ++i) {
float n2 = 0.0f;
for (int64_t j = 0; j < S; ++j) { data[i*S + j] = u(rng); n2 += data[i*S + j]*data[i*S + j]; }
for (int64_t j = 0; j < S; ++j) { data[i*S + j] /= sqrtf(n2); }
}
ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(float));
} else if (strcmp(t->name, "pend_v") == 0) {
init_tensor_uniform(t, -2.0f, 2.0f);
} else if (strcmp(t->name, "pend_gb") == 0) {
// the gates < 0, then the betas in [0, 1] (element 0 of each gate group)
std::vector<float> data(ggml_nelements(t), 0.0f);
std::uniform_real_distribution<float> u(0.0f, 1.0f);
for (int64_t s = 0; s < n_seqs; ++s) {
for (int64_t r = 0; r < 2*n_pend; ++r) {
float * row = data.data() + (s*2*n_pend + r)*g0*H;
for (int64_t h = 0; h < H; ++h) {
if (r < n_pend) {
for (int64_t j = 0; j < g0; ++j) { row[h*g0 + j] = -20.0f*u(rng) - 1e-4f; }
} else {
row[h*g0] = u(rng);
}
}
}
}
ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(float));
} else {
init_tensor_uniform(t);
}
}
}
};
// GGML_OP_GATED_DELTA_NET + GGML_OP_CPY (recurrent cache fusion)
struct test_gated_delta_net_cache_fusion : public test_case {
const ggml_type type;
@@ -5470,25 +5580,22 @@ struct test_gated_delta_net_cache_fusion : public test_case {
const int64_t head_size;
const int64_t n_seq_tokens;
const int64_t n_seqs;
const int64_t K; // snapshot slot count (>1)
ggml_tensor * cpy_node = nullptr;
std::string vars() override {
return VARS_TO_STR6(type, head_count, head_size, n_seq_tokens, n_seqs, K);
return VARS_TO_STR5(type, head_count, head_size, n_seq_tokens, n_seqs);
}
test_gated_delta_net_cache_fusion(ggml_type type = GGML_TYPE_F32,
int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 2, int64_t n_seqs = 1,
int64_t K = 2)
: type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), K(K) {}
int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 2, int64_t n_seqs = 1)
: type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
const int64_t S_v = head_size;
const int64_t H_v = head_count;
const int64_t H_k = head_count;
const int64_t D = S_v * S_v * H_v;
const int64_t n_written = std::min<int64_t>(n_seq_tokens, K);
ggml_tensor * q = ggml_new_tensor_4d(ctx, type, head_size, H_k, n_seq_tokens, n_seqs);
ggml_tensor * k = ggml_new_tensor_4d(ctx, type, head_size, H_k, n_seq_tokens, n_seqs);
@@ -5506,7 +5613,7 @@ struct test_gated_delta_net_cache_fusion : public test_case {
q = ggml_l2_norm(ctx, q, 1e-6f);
k = ggml_l2_norm(ctx, k, 1e-6f);
ggml_tensor * gdn_out = ggml_gated_delta_net(ctx, q, k, v, g, beta, state, K);
ggml_tensor * gdn_out = ggml_gated_delta_net_ext(ctx, q, k, v, g, beta, state, nullptr, nullptr, nullptr, nullptr, false);
ggml_set_name(gdn_out, "gdn_out");
// attn scores view (first part of the gdn output)
@@ -5517,21 +5624,19 @@ struct test_gated_delta_net_cache_fusion : public test_case {
ggml_row_size(gdn_out->type, S_v * H_v * n_seq_tokens), 0);
ggml_set_name(attn, "attn");
// snapshot tail view [D, n_seqs, n_written]
// state tail view [D, n_seqs]
const int64_t attn_score_elems = S_v * H_v * n_seq_tokens * n_seqs;
ggml_tensor * src = ggml_view_3d(ctx, gdn_out,
D, n_seqs, n_written,
ggml_tensor * src = ggml_view_2d(ctx, gdn_out,
D, n_seqs,
ggml_row_size(gdn_out->type, D),
ggml_row_size(gdn_out->type, D * n_seqs),
ggml_row_size(gdn_out->type, attn_score_elems));
// recurrent cache view [D, n_seqs, n_written]
ggml_tensor * cache = ggml_new_tensor_3d(ctx, type, D, n_seqs, n_written);
// recurrent cache view [D, n_seqs]
ggml_tensor * cache = ggml_new_tensor_2d(ctx, type, D, n_seqs);
ggml_set_name(cache, "cache");
ggml_tensor * dst = ggml_view_3d(ctx, cache,
D, n_seqs, n_written,
ggml_row_size(cache->type, D),
ggml_row_size(cache->type, D * n_seqs), 0);
ggml_tensor * dst = ggml_view_2d(ctx, cache,
D, n_seqs,
ggml_row_size(cache->type, D), 0);
ggml_tensor * cpy = ggml_cpy(ctx, src, dst);
ggml_set_name(cpy, "gdn_cache_cpy");
@@ -9551,6 +9656,124 @@ struct test_flash_attn_ext_kv_rows : public test_case {
}
};
// GGML_OP_FLASH_ATTN_EXT with an indexed bias: mask[key, query] += table[indices[key, query], head, query]
struct test_flash_attn_ext_indexed_bias : public test_case {
const int64_t hs;
const int64_t nh; // K/V heads
const int64_t gqa;
const int64_t kv; // mask columns
const int64_t nb; // queries per stream
const int64_t n_stream;
const int64_t n_bins;
const bool kv_rows; // all streams read one K/V cache of 2*kv rows through kv_rows
const bool sinks;
const ggml_type type_KV;
std::vector<int32_t> rows;
std::string vars() override {
return VARS_TO_STR10(hs, nh, gqa, kv, nb, n_stream, n_bins, kv_rows, sinks, type_KV);
}
double max_nmse_err() override {
return 5e-4;
}
test_flash_attn_ext_indexed_bias(int64_t hs = 128, int64_t nh = 2, int64_t gqa = 3, int64_t kv = 768, int64_t nb = 7, int64_t n_stream = 2,
int64_t n_bins = 17, bool kv_rows = false, bool sinks = true, ggml_type type_KV = GGML_TYPE_F16)
: hs(hs), nh(nh), gqa(gqa), kv(kv), nb(nb), n_stream(n_stream), n_bins(n_bins), kv_rows(kv_rows), sinks(sinks), type_KV(type_KV) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, hs, nb, nh*gqa, n_stream);
ggml_set_name(q, "q");
ggml_tensor * k = ggml_new_tensor_4d(ctx, type_KV, hs, kv_rows ? 2*kv : kv, nh, kv_rows ? 1 : n_stream);
ggml_tensor * v = ggml_new_tensor_4d(ctx, type_KV, hs, kv_rows ? 2*kv : kv, nh, kv_rows ? 1 : n_stream);
ggml_set_name(k, "k");
ggml_set_name(v, "v");
ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, kv, nb, 1, n_stream);
ggml_set_name(m, "m");
ggml_tensor * r = nullptr;
if (kv_rows) {
r = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, kv, n_stream);
ggml_set_name(r, "r");
}
ggml_tensor * table = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_bins, nh*gqa, nb*n_stream);
ggml_set_name(table, "table");
ggml_tensor * indices = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, kv, nb*n_stream);
ggml_set_name(indices, "indices");
ggml_tensor * out = ggml_flash_attn_ext_rows(ctx, q, k, v, m, r, 1.0f/sqrtf(hs), 0.0f, 0.0f);
if (sinks) {
ggml_tensor * s = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nh*gqa);
ggml_set_name(s, "s");
ggml_flash_attn_ext_add_sinks(out, s);
}
ggml_flash_attn_ext_add_indexed_bias(out, table, indices);
ggml_prec_set_acc(out, GGML_PREC_F32);
ggml_set_name(out, "out");
return out;
}
void initialize_tensors(ggml_context * ctx) override {
std::mt19937 gen(0x1B1A);
// distinct random cells per stream, some of them padding
rows.assign(kv*n_stream, -1);
if (kv_rows) {
std::vector<int32_t> order(2*kv);
for (int64_t s = 0; s < n_stream; ++s) {
for (int64_t i = 0; i < 2*kv; ++i) {
order[i] = i;
}
std::shuffle(order.begin(), order.end(), gen);
for (int64_t i = 0; i < kv; ++i) {
rows[s*kv + i] = i % 19 == 7 ? -1 : order[i];
}
}
}
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
if (strcmp(t->name, "r") == 0) {
ggml_backend_tensor_set(t, rows.data(), 0, rows.size()*sizeof(int32_t));
} else if (strcmp(t->name, "m") == 0) {
std::vector<float> f(ggml_nelements(t));
std::uniform_real_distribution<float> dis(-1.0f, 1.0f);
for (int64_t s = 0; s < n_stream; ++s) {
for (int64_t j = 0; j < nb; ++j) {
for (int64_t i = 0; i < kv; ++i) {
const bool pad = kv_rows && rows[s*kv + i] < 0;
const bool drop = (i + 3*j + 5*s) % 11 == 0;
f[(s*nb + j)*kv + i] = pad || drop ? -INFINITY : dis(gen);
}
}
}
std::vector<ggml_fp16_t> h(f.size());
ggml_fp32_to_fp16_row(f.data(), h.data(), f.size());
ggml_backend_tensor_set(t, h.data(), 0, h.size()*sizeof(ggml_fp16_t));
} else if (strcmp(t->name, "indices") == 0) {
std::vector<int32_t> idx(ggml_nelements(t));
std::uniform_int_distribution<int32_t> dis(0, n_bins - 1);
for (auto & i : idx) {
i = dis(gen);
}
ggml_backend_tensor_set(t, idx.data(), 0, idx.size()*sizeof(int32_t));
} else if (strcmp(t->name, "table") == 0) {
init_tensor_uniform(t, -4.0f, 4.0f);
} else if (strcmp(t->name, "s") == 0) {
init_tensor_uniform(t, -10.0f, 10.0f);
} else {
init_tensor_uniform(t);
}
}
}
};
// GGML_OP_CROSS_ENTROPY_LOSS
struct test_cross_entropy_loss : public test_case {
const ggml_type type;
@@ -9886,14 +10109,34 @@ struct test_fill : public test_case {
const ggml_type type;
const std::array<int64_t, 4> ne;
float c;
const int64_t offset; // > 0: fill in place a view that starts offset elements into its buffer
std::string vars() override { return VARS_TO_STR3(type, ne, c); }
std::string vars() override {
std::string s = VARS_TO_STR3(type, ne, c);
if (offset != 0) {
s += "," + VAR_TO_STR(offset);
}
return s;
}
test_fill(float c, ggml_type type = GGML_TYPE_F32,
std::array<int64_t, 4> ne = { 10, 10, 4, 3 })
: type(type), ne(ne), c(c) {}
std::array<int64_t, 4> ne = { 10, 10, 4, 3 }, int64_t offset = 0)
: type(type), ne(ne), c(c), offset(offset) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
if (offset != 0) {
ggml_tensor * a = ggml_new_tensor_1d(ctx, type, offset + ne[0]*ne[1]*ne[2]*ne[3]);
ggml_set_name(a, "a");
ggml_tensor * v = ggml_view_4d(ctx, a, ne[0], ne[1], ne[2], ne[3],
ne[0]*ggml_type_size(type), ne[0]*ne[1]*ggml_type_size(type), ne[0]*ne[1]*ne[2]*ggml_type_size(type),
offset*ggml_type_size(type));
ggml_tensor * out = ggml_fill_inplace(ctx, v, c);
ggml_set_name(out, "out");
return out;
}
ggml_tensor * a = ggml_new_tensor_4d(ctx, type, ne[0], ne[1], ne[2], ne[3]);
ggml_set_param(a);
ggml_set_name(a, "a");
@@ -10901,7 +11144,7 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
std::default_random_engine rng(0);
// unary ops
// TODO: add GGML_UNARY_OP_SOFTPLUS test that is sensitive to using `log1p(exp(x))` vs `log(exp(x) + 1)`
test_cases.emplace_back(new test_unary_softplus_neg());
for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32, GGML_TYPE_BF16}) {
for (int v : {0, 1}) {
for (int op = 0; op < GGML_UNARY_OP_COUNT; op++) {
@@ -13083,6 +13326,21 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_concat(GGML_TYPE_Q8_0, {8192, 2, 1, 1}, dim == 0 ? 4096 : 1, dim, 0));
}
for (ggml_type type : { GGML_TYPE_F32, GGML_TYPE_F16 }) {
test_cases.emplace_back(new test_concat(type, {64, 4, 512, 1}, 512, 2, 0));
test_cases.emplace_back(new test_concat(type, {66, 4, 512, 1}, 512, 2, 0));
test_cases.emplace_back(new test_concat(type, {128, 4, 512, 1}, 512, 2, 1));
for (int dim : { 0, 1, 3 }) {
test_cases.emplace_back(new test_concat(type, {300, 4, 5, 1}, 300, dim, 0));
}
test_cases.emplace_back(new test_concat(type, {1025, 4, 512, 1}, 1025, 0, 0));
test_cases.emplace_back(new test_concat(type, {3, 4, 512, 1}, 5, 0, 0));
}
test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {98306, 8, 1, 1}, 286, 0, 0));
test_cases.emplace_back(new test_concat(GGML_TYPE_F16, {98306, 8, 1, 1}, 286, 0, 0));
// GDN conv_input
for (int64_t ne_b_d : { 31, 32, 33, 64 }) {
test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {3, 10240, 1, 1}, ne_b_d, 0, 16));
@@ -13336,6 +13594,9 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_fill(2.0f, GGML_TYPE_F16, { 303, 207, 11, 3 }));
test_cases.emplace_back(new test_fill(-152.0f, GGML_TYPE_F16, { 800, 600, 4, 4 }));
test_cases.emplace_back(new test_fill(3.5f, GGML_TYPE_F16, { 2048, 512, 2, 2 }));
test_cases.emplace_back(new test_fill(0.0f, GGML_TYPE_F32, { 303, 7, 1, 1 }, 1));
test_cases.emplace_back(new test_fill(2.0f, GGML_TYPE_F32, { 96, 4, 1, 1 }, 37));
test_cases.emplace_back(new test_fill(2.0f, GGML_TYPE_F16, { 303, 7, 1, 1 }, 3));
test_cases.emplace_back(new test_sleep(0));
test_cases.emplace_back(new test_sleep(10, GGML_TYPE_F16, { 128, 4, 2, 2 }));
@@ -13544,6 +13805,21 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
}
}
// flash attention with an indexed bias (Inkling 2 relative-position bias)
for (bool kv_rows : {false, true}) {
for (int64_t nb : {1, 7, 65}) {
for (int64_t n_stream : {1, 2}) {
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, nb, n_stream, 17, kv_rows));
}
}
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias( 64, 2, 3, 768, 7, 2, 17, kv_rows, false));
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 8, 3, 512, 65, 1, 1025, kv_rows));
for (ggml_type type : {GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) {
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, 1, 1, 17, kv_rows, true, type));
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, 7, 2, 17, kv_rows, true, type));
}
}
// sparse mask with large batch size
test_cases.emplace_back(new test_flash_attn_ext(512, 512, 1, { 8, 1}, 4096, 64, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 512));
test_cases.emplace_back(new test_flash_attn_ext(512, 512, 1, { 8, 1}, 4096, 64, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 2048));
@@ -13858,6 +14134,19 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_moe_reduce(2048, 16, 32, false, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 1, 1));
for (bool keep : { true, false }) {
test_cases.emplace_back(new test_gated_delta_net_replay(4, 32, 4, 1, 1, false, 4, keep));
test_cases.emplace_back(new test_gated_delta_net_replay(4, 64, 2, 3, 3, false, 4, keep));
test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 4, 1, 3, false, 4, keep));
test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 8, 2, 3, false, 8, keep));
test_cases.emplace_back(new test_gated_delta_net_replay(4, 32, 1, 2, 2, false, 3, keep));
test_cases.emplace_back(new test_gated_delta_net_replay(4, 64, 3, 2, 1, true, 4, keep));
}
// prefill sized: the replay runs before the chunked kernels (CUDA from 64 tokens, HIP from 2048)
test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 65, 1, 1, false, 4, false));
test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 257, 1, 3, false, 4, false));
test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 513, 2, 2, false, 8, false));
test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 2048, 1, 3, false, 4, false));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 16, 1, 1));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 16, 1, 1, 1, true, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 16, 1, 1, 1, false, true));
@@ -13893,9 +14182,8 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 64, 1, 1, false, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 2, 2, true, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, false, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 1, 1, false, true, 1, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, true, true, 1, true, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4, 2, 2, false, true, 4));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 1, 1, false, true, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, true, true, true, true));
// MMA-eligible GDN shapes: whole heads, value slices, tails, and the HIP prefill threshold.
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 65, 1, 1));
@@ -13916,53 +14204,43 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 512, 2, 2));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 2, 2, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 129, 1, 1, false, false, 1, false, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 129, 1, 1, false, false, false, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4095, 1, 2));
// Correlated keys, high beta, and weak decay stress the chunked triangular solve.
for (int64_t n_tokens : {64, 65, 257}) {
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, n_tokens, 1, 1, false, false, 1, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, n_tokens, 1, 1, false, false, true));
}
// Odd V strides require element loads instead of aligned matrix loads.
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 65, 1, 1, false, false, 1, false, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 65, 1, 1, false, false, false, true));
// Q and K can have different strides in both scalar and chunked paths.
for (int64_t n_tokens : {4, 65}) {
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, 1, false, false, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, 1, false, false, false, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, false, false, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, false, false, false, true));
}
// mild decay keeps the state alive across the sequence; qwen35 prefill layout with K=5 snapshots
// mild decay keeps the state alive across the sequence; qwen35 prefill layout
for (int64_t n : { 5, 300, 2048 }) {
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, n, 1, 3, false, false, /*K=*/5, false, false, false, false, /*g_min=*/-0.05f));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, n, 1, 3, false, false, false, false, false, false, /*g_min=*/-0.05f));
}
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 300, 2, 2, true, false, /*K=*/1, false, false, false, false, /*g_min=*/-0.05f));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 200, 1, 1, false, false, /*K=*/5, false, false, false, false, /*g_min=*/-0.05f));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 300, 2, 2, true, false, false, false, false, false, /*g_min=*/-0.05f));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 200, 1, 1, false, false, false, false, false, false, /*g_min=*/-0.05f));
// a backend may pick its kernel by head count: few and many heads, per head size, plain and KDA
for (int64_t s : { 16, 32, 64, 128 }) {
for (int64_t h : { 4 * 128 / s, 64 * 128 / s }) {
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, false, /*K=*/4, false, false, false, false, /*g_min=*/-0.05f));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, true, /*K=*/1, false, false, false, false, /*g_min=*/-0.05f));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, false, false, false, false, false, /*g_min=*/-0.05f));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, true, false, false, false, false, /*g_min=*/-0.05f));
}
}
// K > 1: output keeps the last min(n_tokens, K) per-token snapshots, ordered most-recent-first
// (slot 0 = final state, slot s = state s tokens back).
// exact-match cases (K == n_seq_tokens):
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 16, 2, 1, 1, false, false, /*K=*/2));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 32, 4, 1, 1, false, false, /*K=*/4));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 4, 2, 1, false, false, /*K=*/4));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 8, 128, 4, 1, 1, false, false, /*K=*/4));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 4, 2, 1, false, true, /*K=*/4));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 8, 32, 4, 2, 2, false, true, /*K=*/4));
// gdn + cache cpy fusion (K > 1)
test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 2, 1, 2));
test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 64, 4, 1, 2));
test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 4, 1, 4));
test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 8, 32, 4, 2, 4));
test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 128, 64, 4, 1, 4));
test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 8, 1, 4));
// gdn + cache cpy fusion
test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 2, 1));
test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 64, 4, 1));
test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 4, 1));
test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 8, 32, 4, 2));
test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 128, 64, 4, 1));
test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 8, 1));
#if 0
// these tests are disabled to save execution time, sbut they can be handy for debugging
@@ -14062,6 +14340,19 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_perf() {
}
}
for (ggml_type type : { GGML_TYPE_F32, GGML_TYPE_F16 }) {
for (int64_t ne0 : { 64, 1024, 4096, 16384 }) {
test_cases.emplace_back(new test_concat(type, {ne0, 8, 256, 1}, 256, 2, 0));
}
test_cases.emplace_back(new test_concat(type, {2050, 8, 256, 1}, 256, 2, 0));
test_cases.emplace_back(new test_concat(type, {1024, 8, 2048, 1}, 2048, 2, 0));
for (int64_t ne0 : { 64, 1024, 4096, 16384 }) {
test_cases.emplace_back(new test_concat(type, {ne0, 8, 256, 1}, 256, 0, 0));
}
test_cases.emplace_back(new test_concat(type, {2050, 8, 256, 1}, 255, 0, 0));
}
// CONT of a 0<->2 permute at DeepSeek-V4 lightning-indexer shapes:
// indexer_kq is [n_kv, n_tokens, n_head=64] and gets ggml_cont(ggml_permute(.., 2,1,0,3)).
for (int64_t n_kv : { 1024, 1280, 2048, 2304 }) {
@@ -14577,6 +14868,8 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_perf() {
test_cases.emplace_back(new test_ssm_conv(GGML_TYPE_F32, {4, 3328, 1, 1}, {4, 3328, 1, 1})); // generate
test_cases.emplace_back(new test_ssm_conv_bias_silu(GGML_TYPE_F32, {515, 3328, 1, 1}, {4, 3328, 1, 1}, true)); // prefill
test_cases.emplace_back(new test_ssm_conv_bias_silu(GGML_TYPE_F32, {4, 3328, 1, 1}, {4, 3328, 1, 1}, true)); // generate
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 64, 128, 8, 512, 1)); // Nemotron-3-Puzzle prefill
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 64, 128, 8, 1, 1)); // Nemotron-3-Puzzle generate
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 48, 1, 512, 1)); // prefill
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 48, 1, 1, 1)); // generate
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 80, 128, 1, 512, 1)); // Nemotron-9B prefill
@@ -14634,7 +14927,6 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_perf() {
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 8192, 1));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 1536, 1));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 2048, 1));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 2048, 1, 3, false, false, 5)); // qwen35 PP-2048, K=5
// lightning_indexer
for (int kv : { 256, 4096, 65536 }) {
+2 -8
View File
@@ -211,7 +211,7 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok
const int64_t t_start = ggml_time_us();
{
auto & data = it_best->data.main;
const auto & data = it_best->data.main;
const size_t size = data.size();
const size_t n = llama_state_seq_set_data_ext(ctx_tgt, data.data(), size, id_slot, 0);
@@ -220,13 +220,10 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok
return false;
}
data.clear();
data.shrink_to_fit();
}
{
auto & data = it_best->data.drft;
const auto & data = it_best->data.drft;
if (!data.empty()) {
GGML_ASSERT(ctx_dft);
@@ -238,9 +235,6 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok
return false;
}
data.clear();
data.shrink_to_fit();
}
}
+1 -22
View File
@@ -1,7 +1,5 @@
import '../src/app.css';
import { MEDIA_QUERIES } from '#lib/constants/pwa.constants.ts';
import { SurfaceTheme } from '#lib/enums/ui.enums.ts';
import { applySurfaceTheme } from '#lib/utils/css.ts';
// the docs pages' styles, shared with the library's Storybook
import '../../../lib/ui/.storybook/docs.css';
import { applyColorScheme } from './color-scheme';
@@ -97,31 +95,12 @@ const preview: Preview = {
],
title: 'Interaction pace'
}
},
// the light surface theme: Paper (white panels on a grey page) or Matte (grey glass on white)
surface: {
description: 'Light surface theme',
toolbar: {
dynamicTitle: true,
icon: 'paintbrush',
items: [
{ title: 'Paper', value: SurfaceTheme.PAPER },
{ title: 'Matte', value: SurfaceTheme.MATTE }
],
title: 'Surface'
}
}
},
initialGlobals: {
interactionPace: 'human',
surface: SurfaceTheme.PAPER
interactionPace: 'human'
},
decorators: [
(story, context) => {
applySurfaceTheme(context.globals.surface);
return story();
},
// `parameters.colorScheme` fixes a story to light or dark, whatever the viewer chose (a scene in a store screenshot)
(story, context) => ({
Component: ModeWatcherDecorator,
+5 -19
View File
@@ -5,8 +5,7 @@ description: >-
Llama UI, the design system and components of Llama Chat, the chat client llama-server
bundles. Neutral and quiet: frosted matte surfaces with faint
blue-grey hairlines, near-flat fills, and status colours for success, warning, error and info. Tokens come in
three tiers: primitives, semantic tokens (with a "-dark" twin where dark mode differs and a
"-matte" twin where the Matte light theme does) and components. The colors, typography and
three tiers: primitives, semantic tokens (with a "-dark" twin where dark mode differs) and components. The colors, typography and
rounded sections are generated from ui/lib/ui/src/lib/styles by `npm run design:tokens` in
ui/apps/chat; spacing, components and the prose are kept in sync with the CSS by hand.
colors:
@@ -123,14 +122,6 @@ colors:
highlight-inverse: '{colors.white-a12}'
sheen-start: '{colors.white-a20}'
elevation-ring: '{colors.black-a5}'
surface-page-matte: '{colors.neutral-0}'
surface-glass-matte: 'oklch(0.97 0 0 / 0.6)'
surface-code-matte: '{colors.neutral-50}'
surface-success-matte: 'color-mix(in oklab, {colors.fill-success} 11%, {colors.surface-page-matte})'
surface-warning-matte: 'color-mix(in oklab, {colors.fill-warning} 11%, {colors.surface-page-matte})'
surface-danger-matte: 'color-mix(in oklab, {colors.fill-danger} 11%, {colors.surface-page-matte})'
surface-info-matte: 'color-mix(in oklab, {colors.fill-info} 11%, {colors.surface-page-matte})'
field-background-matte: '{colors.surface-page-matte}'
surface-page-dark: '{colors.neutral-925}'
surface-muted-dark: '{colors.neutral-800}'
surface-emphasis-dark: '{colors.neutral-750}'
@@ -815,9 +806,8 @@ here. The `spacing` and `components` sections and the prose are written by hand;
disagree with the CSS, the CSS wins and this file is updated to match. Storybook shows every
tier under **Llama UI › Foundations › Colors**.
Paper light mode is the base. A semantic token that resolves differently in dark mode has a
`-dark` twin here, and one that resolves differently in Matte a `-matte` twin; components list
a `-dark` entry wherever their colours change. Translucent component
Light mode is the base. A semantic token that resolves differently in dark mode has a
`-dark` twin here; components list a `-dark` entry wherever their colours change. Translucent component
fills are given as they render over the page, so contrast checks see the real colour.
## Colors
@@ -841,12 +831,8 @@ creative (a shape, a numeral, an illustration). Artwork takes its colours from t
the `art-*` primitives: the day sky and the night sky (llama.app's light and dark hero grounds) and
cinder, the accent orange; never from the status colours, and never red.
Light mode has two surface themes, which share everything else (the palette, buttons, fields,
badges, shadows and dark mode): **Paper**, the default, sets white panels, fields and keys on a
faint grey page (`neutral-25`); **Matte** sets grey glass on a white page. Matte is the
`theme-matte` class on `<html>`, chosen with the Light surfaces setting (Settings → General) or
the Surface switch in Storybook's toolbar, and only its surface tokens differ: `surface-page`,
`surface-glass`, `surface-code`, `field-background` and `float-panel-background-modal`.
Light mode sets white panels, fields and keys on a faint grey page (`neutral-25`). Dark mode shares the
palette, buttons, fields, badges and shadows.
- **Surfaces:** `surface-page` for the page, `surface-muted` for quiet panels,
`surface-emphasis` and `surface-selected` for stronger fills and hover or selected rows,
+1 -4
View File
@@ -28,10 +28,7 @@ const SOURCES = {
theme: fileURLToPath(new URL('theme.css', styles))
};
// the selectors of the themes a semantic token may change in, and the suffix its twin takes here
const THEMES = [
{ selector: '.theme-matte:not(.dark)', suffix: '-matte' },
{ selector: '.dark', suffix: '-dark' }
];
const THEMES = [{ selector: '.dark', suffix: '-dark' }];
// the type roles, by the @theme names Tailwind turns into text-body, text-label-sm, ...: a size with a line height
const TYPE_ROLE = /^--text-([a-z]+(?:-[a-z]+)*)$/;
// body and caption text takes the weight around it, which is regular unless a parent says otherwise
@@ -29,7 +29,7 @@
</script>
<span
class="text-caption font-normal text-muted-foreground tabular-nums"
class="text-body-sm font-normal text-muted-foreground tabular-nums"
title="Time since the task started"
>
{label}
@@ -21,7 +21,6 @@
import { ColorMode } from '#lib/enums/ui.enums.ts';
import { modelsStore, serverStore, settingsStore } from '#lib/stores/index.ts';
import type { SettingsSection, SettingsSectionTitle } from '#lib/types/index.ts';
import { applySurfaceTheme } from '#lib/utils/index.ts';
import { setMode } from 'mode-watcher';
import { fade } from 'svelte/transition';
interface Props {
@@ -91,9 +90,6 @@
function handleConfigChange(key: string, value: string | boolean) {
localConfig[key] = value;
// the surface theme previews at once, like the colour theme
if (key === SETTINGS_KEYS.SURFACE_THEME) applySurfaceTheme(value);
// discover needs the hub metadata reads: checking it turns the hub on,
// unchecking it turns the hub back off, so the checkbox never lies
if (key === SETTINGS_KEYS.ENABLE_DISCOVER_MODELS) {
@@ -108,7 +104,6 @@
function handleReset() {
localConfig = { ...settingsStore.config };
setMode(localConfig.theme as ColorMode);
applySurfaceTheme(localConfig[SETTINGS_KEYS.SURFACE_THEME]);
mobileHeader?.updateCarousel();
}
@@ -73,7 +73,6 @@ export const SETTINGS_KEYS = {
SHOW_THOUGHT_IN_PROGRESS: 'showThoughtInProgress',
SHOW_TOOL_CALL_IN_PROGRESS: 'showToolCallInProgress',
SINGLE_ROW_CHAT_FORM: 'singleRowChatForm',
SURFACE_THEME: 'surfaceTheme',
SYMBOLIC_MATH_ENABLED: 'symbolicMathEnabled',
SYSTEM_MESSAGE: 'systemMessage',
// Sampling
@@ -11,9 +11,7 @@ import { VOICE_MICROPHONE_AUTO } from '@ggml-org/llama-voice';
import AudioLines from '@lucide/svelte/icons/audio-lines';
import Code from '@lucide/svelte/icons/code';
import Database from '@lucide/svelte/icons/database';
import File from '@lucide/svelte/icons/file';
import Funnel from '@lucide/svelte/icons/funnel';
import GlassWater from '@lucide/svelte/icons/glass-water';
import ListRestart from '@lucide/svelte/icons/list-restart';
import Mic from '@lucide/svelte/icons/mic';
import Monitor from '@lucide/svelte/icons/monitor';
@@ -22,7 +20,7 @@ import PencilRuler from '@lucide/svelte/icons/pencil-ruler';
import SlidersVertical from '@lucide/svelte/icons/sliders-vertical';
import Sun from '@lucide/svelte/icons/sun';
import TextCursorInput from '@lucide/svelte/icons/text-cursor-input';
import { SurfaceTheme, SyncableParameterType, VoiceInputMode } from '#lib/enums/index.ts';
import { SyncableParameterType, VoiceInputMode } from '#lib/enums/index.ts';
import { SettingsFieldType } from '#lib/enums/settings.enums.ts';
import { ColorMode } from '#lib/enums/ui.enums.ts';
import type {
@@ -84,17 +82,6 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
],
type: SettingsFieldType.SELECT
},
{
defaultValue: SurfaceTheme.PAPER,
help: 'Choose how the light theme draws its surfaces: Paper puts white panels, fields and buttons on a faint grey page; Matte puts grey glass on a white page. Dark mode is the same for both.',
key: SETTINGS_KEYS.SURFACE_THEME,
label: 'Light surfaces',
options: [
{ icon: File, label: 'Paper', value: SurfaceTheme.PAPER },
{ icon: GlassWater, label: 'Matte', value: SurfaceTheme.MATTE }
],
type: SettingsFieldType.SELECT
},
{
defaultValue: '',
help: `Set the API Key if you are using <code> ${CLI_FLAGS.API_KEY} </code> option for the server.`,
-1
View File
@@ -105,7 +105,6 @@ export {
ScrollCarouselVariant,
SidebarAction,
SidebarSectionKind,
SurfaceTheme,
TooltipSide,
UrlProtocol
} from './ui.enums';
-6
View File
@@ -1,11 +1,5 @@
export { ColorMode, MouseButton, PointerType, TooltipSide } from '@ggml-org/llama-ui/enums';
/** The light surface theme: Paper (white panels on a faint grey page) or Matte (grey glass on white). */
export enum SurfaceTheme {
MATTE = 'matte',
PAPER = 'paper'
}
/**
* ScrollCarousel arrow placement.
*/
@@ -11,6 +11,7 @@
import { conversationsStore, modelsStore, serverStore } from '#lib/stores/index.ts';
import type { DatabaseMessage } from '#lib/types/database.js';
import { getConversationModel } from '#lib/utils/index.ts';
import { getChatFormModelState } from '#lib/utils/model-selection.ts';
export function useChatFormModel() {
const isRouter = $derived(serverStore.isRouterMode);
@@ -82,22 +83,17 @@ export function useChatFormModel() {
return activeModelId ? modelsStore.props.modelSupportsVision(activeModelId) : false;
});
const hasModelSelected = $derived(
!isRouter || !!conversationModel || !!modelsStore.selectedModelId
// the form's selection decides the state; the conversation's model only counts when nothing is selected
const modelState = $derived(
getChatFormModelState({
conversationModel,
isRouter,
models: modelsStore.models,
selectedModelId: modelsStore.selectedModelId
})
);
const isSelectedModelInCache = $derived.by(() => {
if (!isRouter) return true;
if (conversationModel) {
return modelsStore.models.some((option) => option.model === conversationModel);
}
const currentModelId = modelsStore.selectedModelId;
if (!currentModelId) return false;
return modelsStore.models.some((option) => option.id === currentModelId);
});
const hasModelSelected = $derived(modelState.hasModelSelected);
const isSelectedModelInCache = $derived(modelState.isSelectedModelAvailable);
return {
get conversationModel() {
-12
View File
@@ -1,15 +1,3 @@
import { SurfaceTheme } from '#lib/enums/index.ts';
/**
* Applies the light surface theme: Matte sets the theme-matte class on <html>, which the tokens
* read (see tokens/semantic.css); Paper, the default, needs no class.
*/
export function applySurfaceTheme(theme: unknown): void {
if (typeof document === 'undefined') return;
document.documentElement.classList.toggle('theme-matte', theme === SurfaceTheme.MATTE);
}
/**
* Converts a rem CSS value to pixels based on the document root font size.
*/
+1 -1
View File
@@ -390,7 +390,7 @@ export { type GgufMetadata, type GgufValue, readGgufMetadata } from './gguf-meta
export { uuid } from './uuid';
// CSS utilities
export { applySurfaceTheme, remToPx } from './css';
export { remToPx } from './css';
// Audio format helper (used by agentic store and chat service)
export { getAudioInputFormat } from './audio-format';
@@ -0,0 +1,43 @@
import type { ModelOption } from '#lib/types/models.js';
export interface ChatFormModelStateInput {
conversationModel: string | null;
isRouter: boolean;
models: readonly Pick<ModelOption, 'id' | 'model'>[];
selectedModelId: string | null;
}
export interface ChatFormModelState {
hasModelSelected: boolean;
isSelectedModelAvailable: boolean;
}
/**
* Whether the chat form has a model to send with and whether that model is available.
* The form's own selection always wins; the conversation's last model only counts
* when nothing is selected in the form.
*/
export function getChatFormModelState({
conversationModel,
isRouter,
models,
selectedModelId
}: ChatFormModelStateInput): ChatFormModelState {
if (!isRouter) return { hasModelSelected: true, isSelectedModelAvailable: true };
if (selectedModelId) {
return {
hasModelSelected: true,
isSelectedModelAvailable: models.some((option) => option.id === selectedModelId)
};
}
if (conversationModel) {
return {
hasModelSelected: true,
isSelectedModelAvailable: models.some((option) => option.model === conversationModel)
};
}
return { hasModelSelected: false, isSelectedModelAvailable: false };
}
+1 -6
View File
@@ -33,7 +33,7 @@
} from '#lib/stores/index.ts';
import { initStores } from '#lib/stores/init.ts';
import { withBase } from '#lib/utils/base-path.ts';
import { applySurfaceTheme, hapticTap } from '#lib/utils/index.ts';
import { hapticTap } from '#lib/utils/index.ts';
import { browser } from '$app/env';
import { afterNavigate, goto } from '$app/navigation';
import { page } from '$app/state';
@@ -53,11 +53,6 @@
let chatSidebar: { editActiveConversation?: () => void } | undefined = $state();
// the light surface theme (Paper or Matte) follows the saved setting
$effect(() => {
applySurfaceTheme(settingsStore.config[SETTINGS_KEYS.SURFACE_THEME]);
});
let showBuildVersion = $derived(
settingsStore.config[SETTINGS_KEYS.SHOW_BUILD_VERSION] as boolean
);
@@ -0,0 +1,84 @@
// Regression: when the conversation's last assistant message names a model that is no
// longer available, picking an available model in the chat form must clear the submit
// button's error state. The form's selection always decides it.
import ChatFormTestWrapper from './components/ChatFormTestWrapper.svelte';
import { MessageRole, ServerRole } from '#lib/enums/index.ts';
import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts';
import { serverStore } from '#lib/stores/llama-server.svelte.ts';
import { modelsStore } from '#lib/stores/models/index.svelte.ts';
import type { DatabaseMessage, ModelOption } from '#lib/types/index.ts';
import { tick } from 'svelte';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { render } from 'vitest-browser-svelte';
const AVAILABLE: ModelOption = {
capabilities: [],
id: 'org/available:Q4_K_M',
model: 'org/available:Q4_K_M',
name: 'org/available:Q4_K_M'
};
const GONE = 'org/gone:Q4_K_M';
function assistantMessage(model: string): DatabaseMessage {
return {
children: [],
content: 'Hello',
convId: 'c1',
id: 'm1',
model,
parent: null,
role: MessageRole.ASSISTANT,
timestamp: 0,
type: 'text'
} as DatabaseMessage;
}
function sendButton(container: HTMLElement) {
const button = container.querySelector<HTMLButtonElement>('button[type="submit"]');
if (!button) throw new Error('send button not rendered');
return button;
}
const isErrorState = (button: HTMLButtonElement) => button.classList.contains('bg-surface-danger');
beforeEach(() => {
serverStore.role = ServerRole.ROUTER;
modelsStore.models = [AVAILABLE];
modelsStore.clearSelection();
conversationsStore.activeMessages = [assistantMessage(GONE)];
});
afterEach(() => {
conversationsStore.activeMessages = [];
modelsStore.clearSelection();
modelsStore.models = [];
});
describe('ChatForm model availability', () => {
it('shows the error state while the only model is the conversation one that is gone', async () => {
const { container } = render(ChatFormTestWrapper, { initialValue: 'Hi' });
await tick();
const button = sendButton(container);
expect(isErrorState(button)).toBe(true);
expect(button.disabled).toBe(true);
});
it('clears the error state once an available model is selected in the form', async () => {
const { container } = render(ChatFormTestWrapper, { initialValue: 'Hi' });
await tick();
await modelsStore.selectModelById(AVAILABLE.id);
await tick();
const button = sendButton(container);
expect(isErrorState(button)).toBe(false);
expect(button.disabled).toBe(false);
});
});
@@ -0,0 +1,70 @@
// Guards which model decides the chat form's submit state: the form's own selection
// always wins over the model of the conversation's last assistant message.
import { getChatFormModelState } from '#lib/utils/model-selection.ts';
import { describe, expect, it } from 'vitest';
const AVAILABLE = { id: 'org/available:Q4_K_M', model: 'org/available:Q4_K_M' };
const GONE = 'org/gone:Q4_K_M';
describe('getChatFormModelState', () => {
it('reports an available model when the form selects one, even if the conversation used a gone model', () => {
expect(
getChatFormModelState({
conversationModel: GONE,
isRouter: true,
models: [AVAILABLE],
selectedModelId: AVAILABLE.id
})
).toEqual({ hasModelSelected: true, isSelectedModelAvailable: true });
});
it('reports an unavailable model when the form selects one that left the list', () => {
expect(
getChatFormModelState({
conversationModel: AVAILABLE.model,
isRouter: true,
models: [AVAILABLE],
selectedModelId: GONE
})
).toEqual({ hasModelSelected: true, isSelectedModelAvailable: false });
});
it('falls back to the conversation model when nothing is selected in the form', () => {
const state = (conversationModel: string) =>
getChatFormModelState({
conversationModel,
isRouter: true,
models: [AVAILABLE],
selectedModelId: null
});
expect(state(GONE)).toEqual({ hasModelSelected: true, isSelectedModelAvailable: false });
expect(state(AVAILABLE.model)).toEqual({
hasModelSelected: true,
isSelectedModelAvailable: true
});
});
it('has no model selected on a router with neither a selection nor a conversation model', () => {
expect(
getChatFormModelState({
conversationModel: null,
isRouter: true,
models: [AVAILABLE],
selectedModelId: null
})
).toEqual({ hasModelSelected: false, isSelectedModelAvailable: false });
});
it('always has an available model outside router mode', () => {
expect(
getChatFormModelState({
conversationModel: GONE,
isRouter: false,
models: [],
selectedModelId: null
})
).toEqual({ hasModelSelected: true, isSelectedModelAvailable: true });
});
});
-23
View File
@@ -49,30 +49,7 @@ const preview: Preview = {
test: 'todo'
}
},
globalTypes: {
// the light surface theme: Paper (white panels on a grey page) or Matte (grey glass on white)
surface: {
description: 'Light surface theme',
toolbar: {
dynamicTitle: true,
icon: 'paintbrush',
items: [
{ title: 'Paper', value: 'paper' },
{ title: 'Matte', value: 'matte' }
],
title: 'Surface'
}
}
},
initialGlobals: {
surface: 'paper'
},
decorators: [
(story, context) => {
document.documentElement.classList.toggle('theme-matte', context.globals.surface === 'matte');
return story();
},
// `parameters.colorScheme` fixes a story to light or dark, whatever the viewer chose (a scene in a store screenshot)
(story, context) => ({
Component: ModeWatcherDecorator,
+1 -1
View File
@@ -27,7 +27,7 @@ beside the apps built on it in `ui/apps`.
`tw-animate-css` (both peer dependencies) and `@ggml-org/llama-brand`'s `css/colors.css` imported before it.
- `tokens.css`: the three tiers of tokens only, also after `@ggml-org/llama-brand`'s `css/colors.css`. `fonts.css`: Llama Sans and Llama Mono. `surfaces.css`: the matte
surface utilities.
- Dark mode is the `dark` class on `<html>`; the Matte light surfaces are the `theme-matte` class.
- Dark mode is the `dark` class on `<html>`.
## What's in it
+1 -1
View File
@@ -10,7 +10,7 @@
* @import '@ggml-org/llama-brand/css/colors.css';
* @import '@ggml-org/llama-ui/theme.css';
*
* Dark mode is the `dark` class on <html>; the Matte light surfaces are the `theme-matte` class.
* Dark mode is the `dark` class on <html>.
*/
@import './fonts.css';
@@ -71,11 +71,6 @@
/* status lamps and orbs read the status tokens through orb-danger and friends */
}
/* Matte: dialogs on the page colour (white), like the page under them */
.theme-matte:not(.dark) {
--float-panel-background-modal: var(--surface-page);
}
.dark {
/* in dark the keys stay frosted glass and quiet fills, lighter than the page */
--button-secondary-background: var(--surface-glass);

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