Compare commits

...
14 Commits
Author SHA1 Message Date
PRANESH S d4adfb478e gguf-py : parse bool values in gguf-set-metadata (#33548)
* gguf-py : parse bool values in gguf-set-metadata

* gguf-py : remove set-metadata test

* gguf-py : accept empty string as false in gguf-set-metadata
2026-12-03 14:36:36 +01:00
Aleksander Grygier debcc4d992 ui: answer a list of CORS origins with the origin that asked (#33602)
* server: answer a list of CORS origins with the one that asked

With more than one origin in --cors-origins, Access-Control-Allow-Origin carried the whole
comma-separated list, which browsers reject. The request's own origin is now sent back
when it is in the list, with Vary: Origin, and none otherwise.

Assisted-by: Claude (Opus 5.5 Medium)

* server: keep "*" in --cors-origins working without credentials

The wildcard fell through to the origin list, so with --no-cors-credentials it matched
no origin and Access-Control-Allow-Origin was dropped. "*" is now handled before the list.
test_cors_options covers a two-origin list and "*" without credentials.

Assisted-by: Claude (Opus 5.5 Medium)
2026-12-03 14:36:16 +01:00
stornic56 4c0ad42e68 models: laguna/afmoe: move inp_out_ids crop before attn_o_proj in last layer (#33557)
* models: laguna/afmoe: move inp_out_ids crop before attn_o_proj in last layer

Advance the ggml_get_rows(..., inp_out_ids) crop of the last layer
(il == n_layer - 1) to run before the attention output projection wo
(attn_o_proj) in laguna.cpp and afmoe.cpp, and before attn_post_norm in
afmoe.cpp.

Since build_lora_mm (wo) and build_norm operate strictly row-wise
without mixing positions or touching the KV cache, advancing the crop is
mathematically equivalent and saves (n_tokens - n_outputs) projections
in the last layer during prefill on all backends.

test-llama-archs: CPU + Vulkan0, laguna/afmoe, all OK.
NMSE laguna 2.38e-07, afmoe 8.83e-08 vs CPU.

AI usage disclosure: assisted

* tests: update MTL.csv fusion counts for afmoe
2026-12-03 14:25:09 +01:00
Jeff Bolz d39c260e6c vulkan: SSM_SCAN optimizations and coopmat2 support (#32916)
* vulkan: SSM_SCAN optimizations and coopmat2 support

Add a prefill shader that does multiple rows at a time, prefetches/stages
through shared memory. The subgroup reduction only runs once per block of tokens.
Doing multiple rows at a time amortizes some of the load overhead and stalls.
Uses larger (vec4) loads. Spreads the "A"/softplus work across threads rather than
repeating on every thread.

Add a coopmat2 shader that implements the chunked matrix form, similar to CUDA
and Metal backends. Each workgroup does 32 rows of a head. Claude verified that
the KLD relative to the fp32 baseline was no worse than CUDA's SSD path relative
to its fp32 baseline.

Add more test coverage for different layouts/views/alignment.

* allow d_state 96 in the fast shaders

* vulkan: SSM_SCAN: address review feedback

- The prefill shader uses chunks of 8 tokens at d_state 128. 16 used
  enough shared memory to lower the occupancy on AMD.
- constexpr constants instead of defines. The ones only the coopmat2
  shader uses, and its shared memory size, are inside its #if, so that
  builds without coopmat2 have no unused constants.
- The prefill shaders no longer need 16-byte aligned binding offsets,
  which AMD and Intel only align to 4 bytes.
- The prefill shader is disabled on Intel, where it spills and is slower
  than the per-token shader.
- Fewer comments.

Assisted-by: Claude Opus 5.5

* vulkan: SSM_SCAN: use log1p in softplus

softplus(dt) computed log(1 + exp(dt)), which loses precision when
exp(dt) is small. The scan shaders now use the log1p helper from
utils.glsl, as the CPU and CUDA backends use log1pf.

Assisted-by: Claude Opus 5.5
2026-12-03 15:21:52 +02:00
ae81d7f090 vulkan: hoist K-quant dequant in mul_mat_vecq (#31022)
* vulkan: hoist K-quant dequant in mul_mat_vecq

Preload each row's weight tile before the column loop so the K-quant block
is unpacked once per row instead of once per column. Small perf win at np=8.

* vulkan: keep legacy MMVQ types on the inline path

The a_tile array is indexed by the NUM_ROWS spec constant. On the Nvidia
Vulkan driver it is not scalarized, so q4_0/q8_0 spill to local memory and
regress (RTX 3090: -12.6%/-21% in test-backend-ops). The legacy unpack is
already cheap; keep those types on the base per-column load+dot. K-quants
and i-quants keep the hoist.

Also store a scalar dm for Q4_0/Q5_0/Q8_0/MXFP4 instead of broadcasting it
to a vec2.

Tested on RX 9070 XT: legacy SPIR-V matches base and perf is within noise;
iq4_xs/iq1_m/q4_K/q6_K/q2_K are unchanged. test-backend-ops passes for
q4_0, q8_0, q4_K, q6_K, iq4_xs, iq1_m and q2_K.

* vulkan: specialize mul_mat_vecq tail for two-row workgroups

---------

Co-authored-by: DrMkdaddy <DrMkdaddy@users.noreply.github.com>
Co-authored-by: Noor Mkdad <37319157+DrMkdaddy@users.noreply.github.com>
2026-12-03 15:20:42 +02:00
yoshi a89559540d ggml : fix view init skipped after buft max_size split (#25584)
* ggml : fix view init skipped after buft max_size split

When ggml_backend_buft_alloc_buffer_n splits allocation on buft
max_size, a view-only tail has size 0 and is left out of the plan.
Persistent views (e.g. KV k_stream / v_stream) were then left without
ggml_backend_view_init.

Do not split on a size-0 tensor. The views stay in the parent range,
and the existing view_init runs.

* ggml : add regression test for view init after max_size split

Cover the buft max_size split path where a view-only tail is left out
of the alloc plan and would skip ggml_backend_view_init.
2026-12-03 15:19:06 +02:00
Aleksander Grygier 05b9db8310 ui: name the MCP server of each tool in /tools, and let MCP servers' icons load (#33598)
* server : name the MCP server of each tool in /tools

A tool of an MCP server llama-server runs from --mcp-servers-config is
listed as <server>_<tool>, so a client could only guess the server from
the name, and guess wrong when the server's name has an underscore.
GET /tools now gives it in `mcp_server` for such tools. Built-in tools
are listed as before.

Assisted-by: Claude (Opus 5.5 Medium)

* server: serve the UI with COEP credentialless

The cross-origin isolation the UI is served with (COEP require-corp) blocked images from
hosts that send no CORP header, such as MCP server icons. With credentialless the page
stays isolated and remote images load without credentials.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: regenerate DESIGN.md with the danger secondary tokens

Assisted-by: Claude (Opus 5.5 Medium)
2026-12-03 13:38:56 +01:00
Aman Gupta c1d374661d CUDA: add internal ops (#33600) 2026-12-03 18:17:44 +08:00
Aleksander Grygier 869790b695 ui: lighten the secondary badge in light mode (#33599)
* ui: lighten the secondary badge in light mode

The secondary badge (GitHub stars on llama.app, plain chips in Llama
Chat) read too dark on light pages. Its fill drops from 15% to 6% of the
text colour, and its hover from 25% to 12%; dark mode is unchanged.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: release Llama UI 0.7.1

Assisted-by: Claude (Opus 5.5 Medium)
2026-12-03 10:29:44 +01:00
Pascal 32da68d077 tests: make local consts static for MSVC (#33587) 2026-12-03 09:33:05 +02:00
Cokodayo ff37ac728e cuda : add flat 1D kernel for small-ne0 non-contiguous CONCAT (#33389)
Assisted-by: Gemini Neon
2026-12-03 08:36:12 +02:00
Wooseok Shin 994cc45e3e CUDA: vectorize Inkling 2 depth_mix with float4 (#33507)
* CUDA: vectorize Inkling 2 depth_mix with float4

Use 16-byte loads and (for Q == 1) stores in depth_mix_f32 when n is a multiple of 4 and the relevant strides and base addresses are 16-byte aligned, keeping the scalar path otherwise. Add DEPTH_MIX tests for boundary shapes and the scalar fallback cases.

Assisted-by: Claude

* CUDA: use 192 threads per block for depth_mix

At n = 2304 the VEC = 4 loops have 576 float4 elements, which 192 threads cover in exactly 3 iterations each, whereas 256 threads left six of eight warps idle in the last iteration. 576 threads were slower on prefill because only one block fits per SM.

Assisted-by: Claude
2026-12-03 08:35:22 +02:00
Alexander Urmuzov 445d5f041c deepseek41 : cut the indexer candidate mask memory (#33495)
Assisted-by: Claude Opus 5.5
2026-12-03 08:31:53 +02:00
Georgi Gerganov 035b8c1745 metal : remove the quantized FA kernels for head sizes that are not multiples of 32 (#33534)
The quantized K/V branches address the cache in whole quantization blocks
relative to the first element of the head, so a quantized KV cache requires
the head size to be divisible by the block size (32 for q4_0/q4_1/q5_0/q5_1/q8_0)

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB)
2026-12-03 08:24:36 +02:00
41 changed files with 1373 additions and 257 deletions
+1 -1
View File
@@ -73,7 +73,7 @@ static ggml_backend_buft_alloc_buffer_n_plan_t ggml_backend_buft_alloc_buffer_n_
}
// flush the current buffer if adding this tensor would exceed max_size
if (cur_buf_size > 0 && (cur_buf_size + this_size) > max_size) {
if (this_size > 0 && cur_buf_size > 0 && (cur_buf_size + this_size) > max_size) {
plan.push_back({ cur_buf_size, first, i });
cur_buf_size = this_size;
first = i;
+137 -30
View File
@@ -79,6 +79,107 @@ static void concat_cont_cuda(const T * x,
concat_cont<T, 2><<<num_blocks, CUDA_CONCAT_BLOCK_SIZE, 0, stream>>>(x, y, dst, ne00, ne01, ne02, ne0, ne1, ne2);
}
template <typename T, int dim>
static __device__ __forceinline__ void concat_non_cont_copy_elem(
const char * __restrict__ src0,
const char * __restrict__ src1,
char * __restrict__ dst,
int64_t ne00,
int64_t ne01,
int64_t ne02,
int64_t ne03,
uint64_t nb00,
uint64_t nb01,
uint64_t nb02,
uint64_t nb03,
uint64_t nb10,
uint64_t nb11,
uint64_t nb12,
uint64_t nb13,
uint64_t nb0,
uint64_t nb1,
uint64_t nb2,
uint64_t nb3,
int64_t i0,
int64_t i1,
int64_t i2,
int64_t i3) {
static_assert(dim >= 0 && dim <= 3, "dim must be in [0, 3]");
bool is_src0 = false;
if constexpr (dim == 0) {
is_src0 = i0 < ne00;
} else if constexpr (dim == 1) {
is_src0 = i1 < ne01;
} else if constexpr (dim == 2) {
is_src0 = i2 < ne02;
} else {
is_src0 = i3 < ne03;
}
const T * x;
if (is_src0) {
x = (const T *) (src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
} else {
if constexpr (dim == 0) {
x = (const T *) (src1 + i3*nb13 + i2*nb12 + i1*nb11 + (i0 - ne00)*nb10);
} else if constexpr (dim == 1) {
x = (const T *) (src1 + i3*nb13 + i2*nb12 + (i1 - ne01)*nb11 + i0*nb10);
} else if constexpr (dim == 2) {
x = (const T *) (src1 + i3*nb13 + (i2 - ne02)*nb12 + i1*nb11 + i0*nb10);
} else {
x = (const T *) (src1 + (i3 - ne03)*nb13 + i2*nb12 + i1*nb11 + i0*nb10);
}
}
T * y = (T *) (dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
*y = *x;
}
// Flat 1D non-contiguous kernel for small dst->ne[0] (<= CUDA_CONCAT_BLOCK_SIZE / 2),
// avoiding mostly-idle thread blocks when rows are much shorter than the block size.
template <typename T, int dim>
static __global__ void __launch_bounds__(CUDA_CONCAT_BLOCK_SIZE)
concat_non_cont_flat(
const char * __restrict__ src0,
const char * __restrict__ src1,
char * __restrict__ dst,
int64_t ne00,
int64_t ne01,
int64_t ne02,
int64_t ne03,
uint64_t nb00,
uint64_t nb01,
uint64_t nb02,
uint64_t nb03,
uint64_t nb10,
uint64_t nb11,
uint64_t nb12,
uint64_t nb13,
uint32_t total,
uint3 ne0_fd,
uint3 ne1_fd,
uint3 ne2_fd,
uint64_t nb0,
uint64_t nb1,
uint64_t nb2,
uint64_t nb3) {
ggml_cuda_pdl_sync();
for (uint32_t idx = (uint32_t) blockIdx.x * blockDim.x + threadIdx.x; idx < total; idx += (uint32_t) blockDim.x * gridDim.x) {
const uint2 dm0 = fast_div_modulo(idx, ne0_fd);
const uint2 dm1 = fast_div_modulo(dm0.x, ne1_fd);
const uint2 dm2 = fast_div_modulo(dm1.x, ne2_fd);
concat_non_cont_copy_elem<T, dim>(
src0, src1, dst,
ne00, ne01, ne02, ne03,
nb00, nb01, nb02, nb03,
nb10, nb11, nb12, nb13,
nb0, nb1, nb2, nb3,
dm0.y, dm1.y, dm2.y, dm2.x);
}
}
// non-contiguous kernel (slow)
template <typename T, int dim>
static __global__ void __launch_bounds__(CUDA_CONCAT_BLOCK_SIZE)
@@ -110,33 +211,19 @@ static __global__ void __launch_bounds__(CUDA_CONCAT_BLOCK_SIZE)
uint64_t nb1,
uint64_t nb2,
uint64_t nb3) {
static_assert(dim >= 0 && dim <= 3, "dim must be in [0, 3]");
const int64_t i1 = blockIdx.x;
const T * x;
// gridDim.y and gridDim.z are capped at 65535, loop over the rest of ne2 and ne3
for (int64_t i3 = blockIdx.z; i3 < ne3; i3 += gridDim.z) {
for (int64_t i2 = blockIdx.y; i2 < ne2; i2 += gridDim.y) {
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) {
x = (const T *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
} else {
if constexpr (dim == 0) {
x = (const T *)(src1 + i3*nb13 + i2*nb12 + i1*nb11 + (i0 - ne00)*nb10);
} else if constexpr (dim == 1) {
x = (const T *)(src1 + i3*nb13 + i2*nb12 + (i1 - ne01)*nb11 + i0*nb10);
} else if constexpr (dim == 2) {
x = (const T *)(src1 + i3*nb13 + (i2 - ne02)*nb12 + i1*nb11 + i0*nb10);
} else if constexpr (dim == 3) {
x = (const T *)(src1 + (i3 - ne03)*nb13 + i2*nb12 + i1*nb11 + i0*nb10);
}
}
T * y = (T *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
*y = *x;
concat_non_cont_copy_elem<T, dim>(
src0, src1, dst,
ne00, ne01, ne02, ne03,
nb00, nb01, nb02, nb03,
nb10, nb11, nb12, nb13,
nb0, nb1, nb2, nb3,
i0, i1, i2, i3);
}
}
}
@@ -166,16 +253,36 @@ static void concat_cuda(const ggml_tensor * src0, const ggml_tensor * src1, ggml
} else {
GGML_ASSERT(!ggml_is_quantized(src0->type));
dim3 grid_dim(dst->ne[1], std::min<int64_t>(dst->ne[2], 65535), std::min<int64_t>(dst->ne[3], 65535));
const int64_t total_elems = ggml_nelements(dst);
const bool use_flat = dst->ne[0] <= CUDA_CONCAT_BLOCK_SIZE / 2
&& total_elems > 0
&& total_elems <= INT32_MAX;
auto launch_kernel = [&](auto dim) {
concat_non_cont<T, dim><<<grid_dim, CUDA_CONCAT_BLOCK_SIZE, 0, stream>>>(
(const char *) src0->data, (const char *) src1->data, (char *) dst->data,
src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3],
src0->nb[0], src0->nb[1], src0->nb[2], src0->nb[3],
src1->ne[0], src1->ne[1], src1->ne[2], src1->ne[3],
src1->nb[0], src1->nb[1], src1->nb[2], src1->nb[3],
dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3],
dst->nb[0], dst->nb[1], dst->nb[2], dst->nb[3]);
if (use_flat) {
const uint3 ne0_fd = init_fastdiv_values((uint64_t) dst->ne[0]);
const uint3 ne1_fd = init_fastdiv_values((uint64_t) dst->ne[1]);
const uint3 ne2_fd = init_fastdiv_values((uint64_t) dst->ne[2]);
const int flat_blocks = (int) std::min<int64_t>(
(total_elems + CUDA_CONCAT_BLOCK_SIZE - 1) / CUDA_CONCAT_BLOCK_SIZE, 65535);
concat_non_cont_flat<T, dim><<<flat_blocks, CUDA_CONCAT_BLOCK_SIZE, 0, stream>>>(
(const char *) src0->data, (const char *) src1->data, (char *) dst->data,
src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3],
src0->nb[0], src0->nb[1], src0->nb[2], src0->nb[3],
src1->nb[0], src1->nb[1], src1->nb[2], src1->nb[3],
(uint32_t) total_elems, ne0_fd, ne1_fd, ne2_fd,
dst->nb[0], dst->nb[1], dst->nb[2], dst->nb[3]);
} else {
dim3 grid_dim(dst->ne[1], std::min<int64_t>(dst->ne[2], 65535), std::min<int64_t>(dst->ne[3], 65535));
concat_non_cont<T, dim><<<grid_dim, CUDA_CONCAT_BLOCK_SIZE, 0, stream>>>(
(const char *) src0->data, (const char *) src1->data, (char *) dst->data,
src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3],
src0->nb[0], src0->nb[1], src0->nb[2], src0->nb[3],
src1->ne[0], src1->ne[1], src1->ne[2], src1->ne[3],
src1->nb[0], src1->nb[1], src1->nb[2], src1->nb[3],
dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3],
dst->nb[0], dst->nb[1], dst->nb[2], dst->nb[3]);
}
};
switch (dim) {
case 0:
+8
View File
@@ -32,6 +32,7 @@
#include "ggml-cuda/fwht.cuh"
#include "ggml-cuda/getrows.cuh"
#include "ggml-cuda/im2col.cuh"
#include "ggml-cuda/internal-ops.cuh"
#include "ggml-cuda/mmf.cuh"
#include "ggml-cuda/mmq.cuh"
#include "ggml-cuda/mmq-few.cuh"
@@ -2939,6 +2940,11 @@ static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct gg
case GGML_OP_TOP_K_MASK:
ggml_cuda_op_top_k_mask(ctx, dst);
break;
case GGML_OP_CUSTOM:
if (!ggml_cuda_op_internal(ctx, dst)) {
return false;
}
break;
default:
return false;
}
@@ -4670,6 +4676,8 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g
return ggml_cuda_lightning_indexer_supported(dev_ctx->device, op);
case GGML_OP_TOP_K_MASK:
return op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_F32;
case GGML_OP_CUSTOM:
return ggml_cuda_internal_op_supported(op);
case GGML_OP_SLEEP:
#if defined(GGML_USE_HIP) || defined(GGML_USE_MUSA)
return false;
+73 -14
View File
@@ -161,9 +161,41 @@ void ggml_cuda_op_short_conv(ggml_backend_cuda_context & ctx, const ggml_cuda_sh
}
}
// ggml_cuda_memcpy_1 is not used here: its __restrict__ pointers give read-only loads, which are not safe with PDL
template <int VEC>
static __device__ __forceinline__ void depth_mix_load(float (&v)[VEC], const float * x) {
static_assert(VEC == 1 || VEC == 4, "depth_mix: VEC must be 1 or 4");
if constexpr (VEC == 4) {
const float4 x4 = *(const float4 *) x;
v[0] = x4.x;
v[1] = x4.y;
v[2] = x4.z;
v[3] = x4.w;
} else {
v[0] = x[0];
}
}
// the VEC elements are stride apart, they take one access only when they are adjacent
template <int VEC>
static __device__ __forceinline__ void depth_mix_store(float * x, const float (&v)[VEC], const int stride) {
static_assert(VEC == 1 || VEC == 4, "depth_mix: VEC must be 1 or 4");
if constexpr (VEC == 4) {
if (stride == 1) {
*(float4 *) x = make_float4(v[0], v[1], v[2], v[3]);
return;
}
}
#pragma unroll
for (int j = 0; j < VEC; ++j) {
x[j*stride] = v[j];
}
}
// one block per (query, token): the dot products of the B stack rows and of cur with the query, the softmax over the
// B + 1 rows and the weighted sum; the norm of cur is a scale of its dot product
template <int block_size>
// a thread takes VEC adjacent elements per access, VEC = 4 needs n % 4 == 0 and 16 byte aligned rows
template <int block_size, int VEC>
static __global__ void depth_mix_f32(
const float * stack, const float * cur, const float * query, float * dst, const int n, const int B, const int Q,
const int64_t stack_s1, const int64_t stack_s2, const int64_t cur_s1, const int64_t query_s1,
@@ -191,17 +223,27 @@ static __global__ void depth_mix_f32(
ggml_cuda_pdl_sync();
for (int i = tid; i < n; i += block_size) {
const float qi = qv[i];
for (int i = tid*VEC; i < n; i += block_size*VEC) {
float qi[VEC];
depth_mix_load(qi, qv + i);
#pragma unroll
for (int r = 0; r < MAX; ++r) {
if (r < B) {
acc[r] += st[r*stack_s1 + i]*qi;
float si[VEC];
depth_mix_load(si, st + r*stack_s1 + i);
#pragma unroll
for (int j = 0; j < VEC; ++j) {
acc[r] += si[j]*qi[j];
}
}
}
const float xi = xc[i];
acc[MAX] += xi*qi;
acc[MAX + 1] += xi*xi;
float xi[VEC];
depth_mix_load(xi, xc + i);
#pragma unroll
for (int j = 0; j < VEC; ++j) {
acc[MAX] += xi[j]*qi[j];
acc[MAX + 1] += xi[j]*xi[j];
}
}
__shared__ float s_acc[NW][MAX + 2];
@@ -255,16 +297,28 @@ static __global__ void depth_mix_f32(
}
p_cur *= inv*sc;
for (int i = tid; i < n; i += block_size) {
float o = 0.0f;
for (int i = tid*VEC; i < n; i += block_size*VEC) {
float o[VEC] = {0.0f};
#pragma unroll
for (int r = 0; r < MAX; ++r) {
if (r < B) {
o += acc[r]*st[r*stack_s1 + i];
float si[VEC];
depth_mix_load(si, st + r*stack_s1 + i);
#pragma unroll
for (int j = 0; j < VEC; ++j) {
o[j] += acc[r]*si[j];
}
}
}
o += p_cur*xc[i];
dst[((int64_t) t*n + i)*Q + q] = o;
float xi[VEC];
depth_mix_load(xi, xc + i);
#pragma unroll
for (int j = 0; j < VEC; ++j) {
o[j] += p_cur*xi[j];
}
// dst is [Q, n, T]
depth_mix_store(dst + ((int64_t) t*n + i)*Q + q, o, Q);
}
}
@@ -280,11 +334,16 @@ void ggml_cuda_op_depth_mix(ggml_backend_cuda_context & ctx, const ggml_tensor *
GGML_ASSERT(ggml_is_contiguous(dst) && dst->ne[0] == Q && dst->ne[1] == n && dst->ne[2] == T);
GGML_ASSERT(T <= 65535 && Q <= 65535);
const int block_size = 256;
const int block_size = 192;
const dim3 grid(Q, T, 1);
// 16 byte accesses: n, the row strides and the base addresses must be multiples of 4 floats
const bool use_vec4 = n % 4 == 0 && (stack->nb[1] | stack->nb[2] | cur->nb[2] | query->nb[1]) % 16 == 0 &&
((uintptr_t) stack->data | (uintptr_t) cur->data | (uintptr_t) query->data | (uintptr_t) dst->data) % 16 == 0;
auto kernel = use_vec4 ? depth_mix_f32<block_size, 4> : depth_mix_f32<block_size, 1>;
const ggml_cuda_kernel_launch_params params(grid, dim3(block_size, 1, 1), 0, ctx.stream());
ggml_cuda_kernel_launch(depth_mix_f32<block_size>, params,
ggml_cuda_kernel_launch(kernel, params,
(const float *) stack->data, (const float *) cur->data, (const float *) query->data, (float *) dst->data,
(int) n, (int) B, (int) Q,
(int64_t) (stack->nb[1]/sizeof(float)), (int64_t) (stack->nb[2]/sizeof(float)),
+73
View File
@@ -0,0 +1,73 @@
#include "internal-ops.cuh"
#define CUDA_SAXPY_BLOCK_SIZE 256
// dst = a*x + y
static __global__ void saxpy_f32(const float * x, const float * y, float * dst, const float a, const int64_t n) {
const int64_t i = (int64_t) blockDim.x*blockIdx.x + threadIdx.x;
if (i >= n) {
return;
}
dst[i] = a*x[i] + y[i];
}
static bool ggml_cuda_internal_saxpy_supported(const ggml_tensor * op) {
const ggml_tensor * x = op->src[0];
const ggml_tensor * y = op->src[1];
return x != nullptr && y != nullptr &&
x->type == GGML_TYPE_F32 && y->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32 &&
ggml_are_same_shape(x, op) && ggml_are_same_shape(y, op) &&
ggml_is_contiguous(x) && ggml_is_contiguous(y) && ggml_is_contiguous(op);
}
static void ggml_cuda_internal_saxpy(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * x = dst->src[0];
const ggml_tensor * y = dst->src[1];
float a;
memcpy(&a, &dst->op_params[GGML_INTERNAL_OP_PARAMS], sizeof(a));
const int64_t n = ggml_nelements(dst);
const int64_t num_blocks = (n + CUDA_SAXPY_BLOCK_SIZE - 1) / CUDA_SAXPY_BLOCK_SIZE;
saxpy_f32<<<num_blocks, CUDA_SAXPY_BLOCK_SIZE, 0, ctx.stream()>>>(
(const float *) x->data, (const float *) y->data, (float *) dst->data, a, n);
}
struct ggml_cuda_internal_op {
const char * id;
bool (*supported)(const ggml_tensor * op);
void (*forward)(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
};
static const ggml_cuda_internal_op ggml_cuda_internal_ops[] = {
{ "ggml_internal_saxpy", ggml_cuda_internal_saxpy_supported, ggml_cuda_internal_saxpy },
};
static const ggml_cuda_internal_op * ggml_cuda_internal_op_find(const ggml_tensor * op) {
const char * id = ggml_internal_op_id(op);
if (id == nullptr) {
return nullptr;
}
for (const ggml_cuda_internal_op & iop : ggml_cuda_internal_ops) {
if (strcmp(iop.id, id) == 0) {
return &iop;
}
}
return nullptr;
}
bool ggml_cuda_internal_op_supported(const ggml_tensor * op) {
const ggml_cuda_internal_op * iop = ggml_cuda_internal_op_find(op);
return iop != nullptr && iop->supported(op);
}
bool ggml_cuda_op_internal(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_cuda_internal_op * iop = ggml_cuda_internal_op_find(dst);
if (iop == nullptr) {
return false;
}
iop->forward(ctx, dst);
return true;
}
+8
View File
@@ -0,0 +1,8 @@
#include "common.cuh"
// internal ops (custom ops without a function, see ggml_custom_4d)
bool ggml_cuda_internal_op_supported(const ggml_tensor * op);
// false if the node is not an internal op of this backend
bool ggml_cuda_op_internal(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
@@ -59,6 +59,10 @@ void kernel_flash_attn_ext_impl(
using o4_t = typename value_type_4 <o_t>::type;
using o8x8_t = typename value_type_8x8 <o_t>::type;
// the quantized branches index the cache in whole blocks relative to the start of the head
static_assert(is_same<kd4x4_t, k4x4_t>::value || DK % 32 == 0, "quantized K cache requires DK divisible by 32");
static_assert(is_same<vd4x4_t, v4x4_t>::value || DV % 32 == 0, "quantized V cache requires DV divisible by 32");
const ushort iq3 = tgpig[2];
const ushort iq2 = tgpig[1];
const ushort iq1 = tgpig[0]*Q;
@@ -29,14 +29,9 @@
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
template [[host_name("kernel_flash_attn_ext_q4_0_dk32_dv32" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_0, 2, dequantize_q4_0, block_q4_0, 2, dequantize_q4_0, 32, 32>;
template [[host_name("kernel_flash_attn_ext_q4_0_dk40_dv40" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_0, 2, dequantize_q4_0, block_q4_0, 2, dequantize_q4_0, 40, 40>;
template [[host_name("kernel_flash_attn_ext_q4_0_dk48_dv48" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_0, 2, dequantize_q4_0, block_q4_0, 2, dequantize_q4_0, 48, 48>;
template [[host_name("kernel_flash_attn_ext_q4_0_dk64_dv64" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_0, 2, dequantize_q4_0, block_q4_0, 2, dequantize_q4_0, 64, 64>;
template [[host_name("kernel_flash_attn_ext_q4_0_dk72_dv72" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_0, 2, dequantize_q4_0, block_q4_0, 2, dequantize_q4_0, 72, 72>;
template [[host_name("kernel_flash_attn_ext_q4_0_dk80_dv80" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_0, 2, dequantize_q4_0, block_q4_0, 2, dequantize_q4_0, 80, 80>;
template [[host_name("kernel_flash_attn_ext_q4_0_dk96_dv96" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_0, 2, dequantize_q4_0, block_q4_0, 2, dequantize_q4_0, 96, 96>;
template [[host_name("kernel_flash_attn_ext_q4_0_dk96_dv64" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_0, 2, dequantize_q4_0, block_q4_0, 2, dequantize_q4_0, 96, 64>;
template [[host_name("kernel_flash_attn_ext_q4_0_dk112_dv112")]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_0, 2, dequantize_q4_0, block_q4_0, 2, dequantize_q4_0, 112, 112>;
template [[host_name("kernel_flash_attn_ext_q4_0_dk128_dv128")]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_0, 2, dequantize_q4_0, block_q4_0, 2, dequantize_q4_0, 128, 128>;
template [[host_name("kernel_flash_attn_ext_q4_0_dk128_dv96" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_0, 2, dequantize_q4_0, block_q4_0, 2, dequantize_q4_0, 128, 96>;
template [[host_name("kernel_flash_attn_ext_q4_0_dk192_dv192")]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_0, 2, dequantize_q4_0, block_q4_0, 2, dequantize_q4_0, 192, 192>;
@@ -29,14 +29,9 @@
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
template [[host_name("kernel_flash_attn_ext_q4_1_dk32_dv32" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_1, 2, dequantize_q4_1, block_q4_1, 2, dequantize_q4_1, 32, 32>;
template [[host_name("kernel_flash_attn_ext_q4_1_dk40_dv40" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_1, 2, dequantize_q4_1, block_q4_1, 2, dequantize_q4_1, 40, 40>;
template [[host_name("kernel_flash_attn_ext_q4_1_dk48_dv48" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_1, 2, dequantize_q4_1, block_q4_1, 2, dequantize_q4_1, 48, 48>;
template [[host_name("kernel_flash_attn_ext_q4_1_dk64_dv64" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_1, 2, dequantize_q4_1, block_q4_1, 2, dequantize_q4_1, 64, 64>;
template [[host_name("kernel_flash_attn_ext_q4_1_dk72_dv72" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_1, 2, dequantize_q4_1, block_q4_1, 2, dequantize_q4_1, 72, 72>;
template [[host_name("kernel_flash_attn_ext_q4_1_dk80_dv80" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_1, 2, dequantize_q4_1, block_q4_1, 2, dequantize_q4_1, 80, 80>;
template [[host_name("kernel_flash_attn_ext_q4_1_dk96_dv96" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_1, 2, dequantize_q4_1, block_q4_1, 2, dequantize_q4_1, 96, 96>;
template [[host_name("kernel_flash_attn_ext_q4_1_dk96_dv64" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_1, 2, dequantize_q4_1, block_q4_1, 2, dequantize_q4_1, 96, 64>;
template [[host_name("kernel_flash_attn_ext_q4_1_dk112_dv112")]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_1, 2, dequantize_q4_1, block_q4_1, 2, dequantize_q4_1, 112, 112>;
template [[host_name("kernel_flash_attn_ext_q4_1_dk128_dv128")]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_1, 2, dequantize_q4_1, block_q4_1, 2, dequantize_q4_1, 128, 128>;
template [[host_name("kernel_flash_attn_ext_q4_1_dk128_dv96" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_1, 2, dequantize_q4_1, block_q4_1, 2, dequantize_q4_1, 128, 96>;
template [[host_name("kernel_flash_attn_ext_q4_1_dk192_dv192")]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q4_1, 2, dequantize_q4_1, block_q4_1, 2, dequantize_q4_1, 192, 192>;
@@ -29,14 +29,9 @@
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
template [[host_name("kernel_flash_attn_ext_q5_0_dk32_dv32" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_0, 2, dequantize_q5_0, block_q5_0, 2, dequantize_q5_0, 32, 32>;
template [[host_name("kernel_flash_attn_ext_q5_0_dk40_dv40" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_0, 2, dequantize_q5_0, block_q5_0, 2, dequantize_q5_0, 40, 40>;
template [[host_name("kernel_flash_attn_ext_q5_0_dk48_dv48" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_0, 2, dequantize_q5_0, block_q5_0, 2, dequantize_q5_0, 48, 48>;
template [[host_name("kernel_flash_attn_ext_q5_0_dk64_dv64" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_0, 2, dequantize_q5_0, block_q5_0, 2, dequantize_q5_0, 64, 64>;
template [[host_name("kernel_flash_attn_ext_q5_0_dk72_dv72" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_0, 2, dequantize_q5_0, block_q5_0, 2, dequantize_q5_0, 72, 72>;
template [[host_name("kernel_flash_attn_ext_q5_0_dk80_dv80" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_0, 2, dequantize_q5_0, block_q5_0, 2, dequantize_q5_0, 80, 80>;
template [[host_name("kernel_flash_attn_ext_q5_0_dk96_dv96" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_0, 2, dequantize_q5_0, block_q5_0, 2, dequantize_q5_0, 96, 96>;
template [[host_name("kernel_flash_attn_ext_q5_0_dk96_dv64" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_0, 2, dequantize_q5_0, block_q5_0, 2, dequantize_q5_0, 96, 64>;
template [[host_name("kernel_flash_attn_ext_q5_0_dk112_dv112")]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_0, 2, dequantize_q5_0, block_q5_0, 2, dequantize_q5_0, 112, 112>;
template [[host_name("kernel_flash_attn_ext_q5_0_dk128_dv128")]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_0, 2, dequantize_q5_0, block_q5_0, 2, dequantize_q5_0, 128, 128>;
template [[host_name("kernel_flash_attn_ext_q5_0_dk128_dv96" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_0, 2, dequantize_q5_0, block_q5_0, 2, dequantize_q5_0, 128, 96>;
template [[host_name("kernel_flash_attn_ext_q5_0_dk192_dv192")]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_0, 2, dequantize_q5_0, block_q5_0, 2, dequantize_q5_0, 192, 192>;
@@ -29,14 +29,9 @@
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
template [[host_name("kernel_flash_attn_ext_q5_1_dk32_dv32" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_1, 2, dequantize_q5_1, block_q5_1, 2, dequantize_q5_1, 32, 32>;
template [[host_name("kernel_flash_attn_ext_q5_1_dk40_dv40" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_1, 2, dequantize_q5_1, block_q5_1, 2, dequantize_q5_1, 40, 40>;
template [[host_name("kernel_flash_attn_ext_q5_1_dk48_dv48" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_1, 2, dequantize_q5_1, block_q5_1, 2, dequantize_q5_1, 48, 48>;
template [[host_name("kernel_flash_attn_ext_q5_1_dk64_dv64" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_1, 2, dequantize_q5_1, block_q5_1, 2, dequantize_q5_1, 64, 64>;
template [[host_name("kernel_flash_attn_ext_q5_1_dk72_dv72" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_1, 2, dequantize_q5_1, block_q5_1, 2, dequantize_q5_1, 72, 72>;
template [[host_name("kernel_flash_attn_ext_q5_1_dk80_dv80" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_1, 2, dequantize_q5_1, block_q5_1, 2, dequantize_q5_1, 80, 80>;
template [[host_name("kernel_flash_attn_ext_q5_1_dk96_dv96" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_1, 2, dequantize_q5_1, block_q5_1, 2, dequantize_q5_1, 96, 96>;
template [[host_name("kernel_flash_attn_ext_q5_1_dk96_dv64" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_1, 2, dequantize_q5_1, block_q5_1, 2, dequantize_q5_1, 96, 64>;
template [[host_name("kernel_flash_attn_ext_q5_1_dk112_dv112")]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_1, 2, dequantize_q5_1, block_q5_1, 2, dequantize_q5_1, 112, 112>;
template [[host_name("kernel_flash_attn_ext_q5_1_dk128_dv128")]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_1, 2, dequantize_q5_1, block_q5_1, 2, dequantize_q5_1, 128, 128>;
template [[host_name("kernel_flash_attn_ext_q5_1_dk128_dv96" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_1, 2, dequantize_q5_1, block_q5_1, 2, dequantize_q5_1, 128, 96>;
template [[host_name("kernel_flash_attn_ext_q5_1_dk192_dv192")]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q5_1, 2, dequantize_q5_1, block_q5_1, 2, dequantize_q5_1, 192, 192>;
@@ -29,14 +29,9 @@
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
template [[host_name("kernel_flash_attn_ext_q8_0_dk32_dv32" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q8_0, 2, dequantize_q8_0, block_q8_0, 2, dequantize_q8_0, 32, 32>;
template [[host_name("kernel_flash_attn_ext_q8_0_dk40_dv40" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q8_0, 2, dequantize_q8_0, block_q8_0, 2, dequantize_q8_0, 40, 40>;
template [[host_name("kernel_flash_attn_ext_q8_0_dk48_dv48" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q8_0, 2, dequantize_q8_0, block_q8_0, 2, dequantize_q8_0, 48, 48>;
template [[host_name("kernel_flash_attn_ext_q8_0_dk64_dv64" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q8_0, 2, dequantize_q8_0, block_q8_0, 2, dequantize_q8_0, 64, 64>;
template [[host_name("kernel_flash_attn_ext_q8_0_dk72_dv72" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q8_0, 2, dequantize_q8_0, block_q8_0, 2, dequantize_q8_0, 72, 72>;
template [[host_name("kernel_flash_attn_ext_q8_0_dk80_dv80" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q8_0, 2, dequantize_q8_0, block_q8_0, 2, dequantize_q8_0, 80, 80>;
template [[host_name("kernel_flash_attn_ext_q8_0_dk96_dv96" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q8_0, 2, dequantize_q8_0, block_q8_0, 2, dequantize_q8_0, 96, 96>;
template [[host_name("kernel_flash_attn_ext_q8_0_dk96_dv64" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q8_0, 2, dequantize_q8_0, block_q8_0, 2, dequantize_q8_0, 96, 64>;
template [[host_name("kernel_flash_attn_ext_q8_0_dk112_dv112")]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q8_0, 2, dequantize_q8_0, block_q8_0, 2, dequantize_q8_0, 112, 112>;
template [[host_name("kernel_flash_attn_ext_q8_0_dk128_dv128")]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q8_0, 2, dequantize_q8_0, block_q8_0, 2, dequantize_q8_0, 128, 128>;
template [[host_name("kernel_flash_attn_ext_q8_0_dk128_dv96" )]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q8_0, 2, dequantize_q8_0, block_q8_0, 2, dequantize_q8_0, 128, 96>;
template [[host_name("kernel_flash_attn_ext_q8_0_dk192_dv192")]] kernel flash_attn_ext_t kernel_flash_attn_ext<FA_TYPES, block_q8_0, 2, dequantize_q8_0, block_q8_0, 2, dequantize_q8_0, 192, 192>;
@@ -825,6 +825,7 @@ struct vk_op_ssm_scan_push_constants {
uint32_t nb02, nb03, nb12, nb13;
uint32_t nb21, nb22, nb31;
uint32_t nb42, nb43, nb52, nb53;
uint32_t off0, off1, off2, off3, off4, off5, off6; // bytes from each source's binding to its data
uint32_t s_off;
uint32_t n_head, d_head, n_group, n_tok;
uint32_t n_seq, K;
+6
View File
@@ -829,6 +829,7 @@ struct vk_device_struct {
bool coopmat2;
bool coopmat2_bf16_support {};
bool coopmat2_gdn_support {};
bool coopmat2_ssm_support {};
bool coopmat2_decode_vector;
uint32_t coopmat2_reserved_shmem {};
@@ -1047,6 +1048,11 @@ struct vk_device_struct {
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_scan_prefill_f32_d96;
vk_pipeline pipeline_ssm_scan_prefill_f32_d128;
vk_pipeline pipeline_ssm_scan_prefill_f32_d256;
vk_pipeline pipeline_ssm_scan_cm2_f32_d96;
vk_pipeline pipeline_ssm_scan_cm2_f32_d128;
vk_pipeline pipeline_ssm_conv_f32;
vk_pipeline pipeline_ssm_conv_silu_f32;
vk_pipeline pipeline_ssm_conv_bias_silu_f32;
+146 -15
View File
@@ -1759,6 +1759,61 @@ static uint32_t ggml_vk_gated_delta_net_shmem_size(uint32_t v, bool coopmat2, bo
return qk + state + p_inv + delta_solved + lower + scan;
}
// Specialization constants of ssm_scan_cm2.comp and ssm_scan_prefill.comp.
static constexpr uint32_t GGML_VK_SSM_CM2_T = 32;
static constexpr uint32_t GGML_VK_SSM_CM2_ROWS = 32;
static constexpr uint32_t GGML_VK_SSM_PREFILL_WG_SIZE = 128;
static constexpr uint32_t GGML_VK_SSM_PREFILL_LPR = 16;
static constexpr uint32_t GGML_VK_SSM_PREFILL_R = 2;
#if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
static constexpr uint32_t GGML_VK_SSM_CM2_WG_SIZE = 128;
static constexpr uint32_t GGML_VK_SSM_CM2_PAD = 8;
static uint32_t ggml_vk_ssm_scan_cm2_shmem_size(uint32_t d_state) {
const uint32_t T = GGML_VK_SSM_CM2_T;
const uint32_t rows = GGML_VK_SSM_CM2_ROWS;
const uint32_t pad = GGML_VK_SSM_CM2_PAD;
const uint32_t f16_size = sizeof(ggml_fp16_t);
const uint32_t c_b = 2 * T * (d_state + pad) * f16_size;
const uint32_t s = rows * (d_state + pad) * f16_size;
const uint32_t x = 3 * T * (rows + pad) * f16_size;
const uint32_t m = T * (T + pad) * f16_size;
const uint32_t scan = 2 * T * sizeof(float);
return c_b + s + x + m + scan;
}
#endif
// d_state must be a multiple of 4 * LPR.
static constexpr uint32_t ggml_vk_ssm_scan_prefill_lpr(uint32_t d_state) {
return d_state % (4 * GGML_VK_SSM_PREFILL_LPR) == 0 ? GGML_VK_SSM_PREFILL_LPR : GGML_VK_SSM_PREFILL_LPR / 2;
}
static constexpr uint32_t ggml_vk_ssm_scan_prefill_rows(uint32_t d_state) {
return GGML_VK_SSM_PREFILL_WG_SIZE / ggml_vk_ssm_scan_prefill_lpr(d_state) * GGML_VK_SSM_PREFILL_R;
}
// Tokens per chunk. 16 at d_state 128 uses enough shared memory to lower the occupancy on AMD.
static constexpr uint32_t ggml_vk_ssm_scan_prefill_tokens(uint32_t d_state) {
return d_state == 96 ? 16 : 8;
}
template <uint32_t d_state>
static constexpr uint32_t ggml_vk_ssm_scan_prefill_shmem_size() {
constexpr uint32_t T = ggml_vk_ssm_scan_prefill_tokens(d_state);
constexpr uint32_t rows = ggml_vk_ssm_scan_prefill_rows(d_state);
constexpr uint32_t wg = GGML_VK_SSM_PREFILL_WG_SIZE;
constexpr uint32_t lpr = ggml_vk_ssm_scan_prefill_lpr(d_state);
static_assert((lpr & (lpr - 1)) == 0 && wg % lpr == 0);
static_assert(d_state % (4 * lpr) == 0);
static_assert((T * d_state / 4) % wg == 0 && rows % 4 == 0 && T * rows / 4 <= wg);
static_assert((T * GGML_VK_SSM_PREFILL_R) % lpr == 0);
return 2 * T * (2 * d_state + rows + 1) * sizeof(float);
}
static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector<uint32_t>& warptile, bool mul_mat_id, ggml_type src0_type) {
uint32_t lut_size = 0;
@@ -4467,6 +4522,35 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
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);
}
// The prefill shader spills and is slower than the per-token shader on Intel.
if (device->vendor_id != VK_VENDOR_ID_INTEL &&
device->subgroup_shuffle && device->subgroup_require_full_support &&
device->subgroup_size >= GGML_VK_SSM_PREFILL_LPR &&
device->properties.limits.maxComputeWorkGroupInvocations >= GGML_VK_SSM_PREFILL_WG_SIZE &&
device->properties.limits.maxComputeWorkGroupSize[0] >= GGML_VK_SSM_PREFILL_WG_SIZE) {
const uint32_t max_shmem = device->properties.limits.maxComputeSharedMemorySize;
if (ggml_vk_ssm_scan_prefill_shmem_size<96>() <= max_shmem) {
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_prefill_f32_d96, "ssm_scan_prefill_d96_f32", ssm_scan_prefill_f32_len, ssm_scan_prefill_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1},
{GGML_VK_SSM_PREFILL_WG_SIZE, 96, ggml_vk_ssm_scan_prefill_tokens(96), ggml_vk_ssm_scan_prefill_lpr(96), GGML_VK_SSM_PREFILL_R}, 1, true, true);
}
if (ggml_vk_ssm_scan_prefill_shmem_size<128>() <= max_shmem) {
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_prefill_f32_d128, "ssm_scan_prefill_d128_f32", ssm_scan_prefill_f32_len, ssm_scan_prefill_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1},
{GGML_VK_SSM_PREFILL_WG_SIZE, 128, ggml_vk_ssm_scan_prefill_tokens(128), ggml_vk_ssm_scan_prefill_lpr(128), GGML_VK_SSM_PREFILL_R}, 1, true, true);
}
if (ggml_vk_ssm_scan_prefill_shmem_size<256>() <= max_shmem) {
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_prefill_f32_d256, "ssm_scan_prefill_d256_f32", ssm_scan_prefill_f32_len, ssm_scan_prefill_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1},
{GGML_VK_SSM_PREFILL_WG_SIZE, 256, ggml_vk_ssm_scan_prefill_tokens(256), ggml_vk_ssm_scan_prefill_lpr(256), GGML_VK_SSM_PREFILL_R}, 1, true, true);
}
}
#if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
if (device->coopmat2 && device->coopmat2_ssm_support) {
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_cm2_f32_d96, "ssm_scan_cm2_d96_f32", ssm_scan_f32_cm2_len, ssm_scan_f32_cm2_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1},
{GGML_VK_SSM_CM2_WG_SIZE, 96, GGML_VK_SSM_CM2_T, GGML_VK_SSM_CM2_ROWS, GGML_VK_SSM_CM2_PAD}, 1, true, true, GGML_VK_SSM_CM2_T);
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_cm2_f32_d128, "ssm_scan_cm2_d128_f32", ssm_scan_f32_cm2_len, ssm_scan_f32_cm2_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1},
{GGML_VK_SSM_CM2_WG_SIZE, 128, GGML_VK_SSM_CM2_T, GGML_VK_SSM_CM2_ROWS, GGML_VK_SSM_CM2_PAD}, 1, true, true, GGML_VK_SSM_CM2_T);
}
#endif
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);
ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_silu_f32, "ssm_conv_silu_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 0, 1}, 1);
ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_bias_silu_f32, "ssm_conv_bias_silu_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 1, 1}, 1);
@@ -5448,6 +5532,16 @@ vk_device ggml_vk_get_device(size_t idx) {
found_fp32_128 = true;
}
}
// The SSM scan's matrix dimensions are d_state (96 or 128), T and ROWS.
const auto ssm_dims_ok = [](uint32_t g) {
return g != 0 && 96 % g == 0 && 128 % g == 0 && GGML_VK_SSM_CM2_T % g == 0 && GGML_VK_SSM_CM2_ROWS % g == 0;
};
if (prop.workgroupInvocations == GGML_VK_SSM_CM2_WG_SIZE &&
prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
ssm_dims_ok(prop.MGranularity) && ssm_dims_ok(prop.NGranularity) && ssm_dims_ok(prop.KGranularity)) {
device->coopmat2_ssm_support = true;
}
if (prop.workgroupInvocations == 256 &&
prop.MGranularity <= 32 &&
prop.NGranularity <= 32 &&
@@ -5493,6 +5587,15 @@ vk_device ggml_vk_get_device(size_t idx) {
#endif
}
}
// The shared memory of d_state 128 also covers 96.
device->coopmat2_ssm_support = device->coopmat2_ssm_support &&
coopmat2_props.cooperativeMatrixWorkgroupScopeMaxWorkgroupSize >= GGML_VK_SSM_CM2_WG_SIZE &&
device->properties.limits.maxComputeWorkGroupInvocations >= GGML_VK_SSM_CM2_WG_SIZE &&
device->properties.limits.maxComputeWorkGroupSize[0] >= GGML_VK_SSM_CM2_WG_SIZE &&
device->subgroup_size_control &&
device->subgroup_min_size <= GGML_VK_SSM_CM2_T && GGML_VK_SSM_CM2_T <= device->subgroup_max_size &&
uint64_t(ggml_vk_ssm_scan_cm2_shmem_size(128)) + coopmat2_props.cooperativeMatrixWorkgroupScopeReservedSharedMemory <=
device->properties.limits.maxComputeSharedMemorySize;
device->coopmat2_gdn_support = device->coopmat2_gdn_support &&
coopmat2_props.cooperativeMatrixWorkgroupScopeMaxWorkgroupSize >= 128 &&
device->properties.limits.maxComputeWorkGroupInvocations >= 128 &&
@@ -12249,7 +12352,40 @@ void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_te
bool is_mamba2 = (src3->nb[1] == sizeof(float));
GGML_ASSERT(is_mamba2);
// The shaders add each source's offset from its aligned binding.
vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
vk_subbuffer src_buf[7] = {};
uint32_t src_off[7] = {};
for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) {
src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i], true);
src_off[i] = get_misalign_bytes(ctx, dst->src[i]);
}
const uint32_t d_state = src0->ne[0];
const uint32_t K = (uint32_t) ggml_get_op_params_i32(dst, 0);
// The prefill shaders read x, B and C as vec4.
auto vec4_aligned = [&](int i) {
const ggml_tensor * t = dst->src[i];
return src_off[i] % 16 == 0 && t->nb[2] % 16 == 0 && t->nb[3] % 16 == 0;
};
const bool vec4 = head_dim % 4 == 0 && vec4_aligned(1) && vec4_aligned(4) && vec4_aligned(5);
vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, dst->op);
uint32_t prefill_rows = 0;
if (vec4 && K <= 1 && n_tok >= 8) {
vk_pipeline cm2 = d_state == 96 ? ctx->device->pipeline_ssm_scan_cm2_f32_d96 :
d_state == 128 ? ctx->device->pipeline_ssm_scan_cm2_f32_d128 : nullptr;
vk_pipeline prefill = d_state == 96 ? ctx->device->pipeline_ssm_scan_prefill_f32_d96 :
d_state == 128 ? ctx->device->pipeline_ssm_scan_prefill_f32_d128 :
d_state == 256 ? ctx->device->pipeline_ssm_scan_prefill_f32_d256 : nullptr;
if (n_tok >= GGML_VK_SSM_CM2_T && cm2) {
pipeline = cm2;
prefill_rows = GGML_VK_SSM_CM2_ROWS;
} else if (prefill) {
pipeline = prefill;
prefill_rows = ggml_vk_ssm_scan_prefill_rows(d_state);
}
}
GGML_ASSERT(pipeline != nullptr);
ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
@@ -12263,24 +12399,19 @@ void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_te
(uint32_t)src3->nb[1],
(uint32_t)src4->nb[2], (uint32_t)src4->nb[3],
(uint32_t)src5->nb[2], (uint32_t)src5->nb[3],
src_off[0], src_off[1], src_off[2], src_off[3], src_off[4], src_off[5], src_off[6],
(uint32_t)s_off,
n_head, head_dim, n_group, n_tok,
n_seq, (uint32_t) ggml_get_op_params_i32(dst, 0)
n_seq, K
};
vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
vk_subbuffer src_buf[7] = {};
for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) {
src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
}
std::array<uint32_t, 3> elements;
const uint32_t d_state = src0->ne[0];
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 };
if (prefill_rows) {
elements = { CEIL_DIV(head_dim, prefill_rows), n_head, n_seq };
} else {
const uint32_t num_subgroups = (d_state == 96 ? 128 : d_state) / ctx->device->subgroup_size;
elements = { CEIL_DIV(n_head * head_dim, num_subgroups), n_seq, 1 };
}
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], src_buf[6], dst_buf},
@@ -18082,14 +18213,14 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
case GGML_OP_SSM_SCAN:
{
for (int i = 0; i < 6; i++) {
if (op->src[i] && ggml_is_quantized(op->src[i]->type)) {
if (op->src[i]->type != GGML_TYPE_F32) {
return false;
}
}
if (op->src[6] && op->src[6]->type != GGML_TYPE_I32) {
return false;
}
if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
if (op->type != GGML_TYPE_F32) {
return false;
}
@@ -22,6 +22,16 @@ layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
#error unimplemented
#endif
// Hoisting pays off when the per-block unpack is expensive (K-quants and
// i-quants). For the legacy 4/8-bit types the unpack is already cheap and the
// indexed a_tile array can spill on some drivers, so keep those on the base
// per-column path.
#if defined(DATA_A_QUANT_LEGACY) || defined(DATA_A_MXFP4)
#define MMVQ_USE_HOIST 0
#else
#define MMVQ_USE_HOIST 1
#endif
uint a_offset, b_offset, d_offset;
int32_t cache_b_qs[K_PER_ITER / 4];
@@ -30,6 +40,17 @@ vec2 cache_b_ds;
#include "mul_mat_vecq_funcs.glsl"
void iter(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint first_row, const uint num_rows, const uint col, const uint b_qs_idx) {
#if MMVQ_USE_HOIST
// Load and unpack the weight block once per row, then reuse it for all columns.
a_tile a_tiles[NUM_ROWS];
uint ibi = first_row*p.ncols;
[[unroll]] for (uint n = 0; n < num_rows; ++n) {
const uint a_block_idx = (ibi + col)/QUANT_K_Q8_1 + a_offset;
ibi += p.ncols;
a_tiles[n] = load_a_tile(a_block_idx, b_qs_idx);
}
#endif
[[unroll]] for (uint j = 0; j < NUM_COLS; ++j) {
// Preload data_b block
const uint b_block_idx = (j*p.batch_stride_b + col) / QUANT_K_Q8_1 + b_offset;
@@ -64,13 +85,18 @@ void iter(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint first_row, const
#endif
#endif
#if MMVQ_USE_HOIST
[[unroll]] for (uint n = 0; n < num_rows; ++n) {
temp[j][n] += dot_a_tile(a_tiles[n]);
}
#else
uint ibi = first_row*p.ncols;
[[unroll]] for (uint n = 0; n < num_rows; ++n) {
const uint a_block_idx = (ibi + col)/QUANT_K_Q8_1 + a_offset;
ibi += p.ncols;
temp[j][n] += mmvq_dot_product(a_block_idx, b_qs_idx);
}
#endif
}
}
@@ -137,6 +163,13 @@ void main() {
if (first_row >= p.stride_d) {
return;
}
#if MMVQ_USE_HOIST
// Pass the known tail size to allow unrolling.
if (NUM_ROWS == 2u) {
compute_outputs(first_row, 1u);
return;
}
#endif
compute_outputs(first_row, p.stride_d - first_row);
}
}
@@ -158,38 +158,63 @@ FLOAT_TYPE mul_q8_1(const int32_t q_sum, const float da, const vec2 dsb, const i
#endif
#if defined(DATA_A_Q2_0)
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
struct a_tile {
i32vec4 qs;
FLOAT_TYPE dm;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
return a_tile(repack4(ib_a, iqs), get_dm(ib_a));
}
FLOAT_TYPE dot_a_tile(const a_tile t) {
int32_t q_sum = 0;
const i32vec4 qs_a = repack4(ib_a, iqs);
q_sum += dotPacked4x8EXT(qs_a.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(qs_a.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(qs_a.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(qs_a.w, cache_b_qs[3]);
q_sum += dotPacked4x8EXT(t.qs.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(t.qs.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(t.qs.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(t.qs.w, cache_b_qs[3]);
// 16 quants per call => divide sums by 32/16 = 2
return mul_q8_1(q_sum, get_dm(ib_a), cache_b_ds, 2);
return mul_q8_1(q_sum, t.dm, cache_b_ds, 2);
}
#elif defined(DATA_A_QUANT_LEGACY) || defined(DATA_A_MXFP4)
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
int32_t q_sum = 0;
#if defined(DATA_A_Q4_1) || defined(DATA_A_Q5_1)
#define A_TILE_DM_TYPE FLOAT_TYPEV2
#else
// Q4_0/Q5_0/Q8_0/MXFP4 only need the scale. Keeping a scalar here avoids
// broadcasting it to a vec2 and carrying the unused component across the
// column loop.
#define A_TILE_DM_TYPE FLOAT_TYPE
#endif
struct a_tile {
int32_t qs0;
int32_t qs1;
A_TILE_DM_TYPE dm;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
a_tile t;
#if QUANT_R == 2
const i32vec2 data_a_qs = repack(ib_a, iqs);
q_sum += dotPacked4x8EXT(data_a_qs.x,
cache_b_qs[0]);
q_sum += dotPacked4x8EXT(data_a_qs.y,
cache_b_qs[1]);
t.qs0 = data_a_qs.x;
t.qs1 = data_a_qs.y;
#else
int32_t data_a_qs = repack(ib_a, iqs * 2);
q_sum += dotPacked4x8EXT(data_a_qs,
cache_b_qs[0]);
data_a_qs = repack(ib_a, iqs * 2 + 1);
q_sum += dotPacked4x8EXT(data_a_qs,
cache_b_qs[1]);
t.qs0 = repack(ib_a, iqs * 2);
t.qs1 = repack(ib_a, iqs * 2 + 1);
#endif
t.dm = get_dm(ib_a);
return t;
}
FLOAT_TYPE dot_a_tile(const a_tile t) {
int32_t q_sum = 0;
q_sum += dotPacked4x8EXT(t.qs0, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(t.qs1, cache_b_qs[1]);
// 2 quants per call => divide sums by 8/2 = 4
return mul_q8_1(q_sum, get_dm(ib_a), cache_b_ds, 4);
return mul_q8_1(q_sum, t.dm, cache_b_ds, 4);
}
#undef A_TILE_DM_TYPE
#endif
#if defined(DATA_A_Q2_K)
@@ -214,28 +239,35 @@ uint8_t get_scale(uint ib, uint iqs) {
return data_a[ib_k].scales[iqs_k / 4];
}
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
struct a_tile {
i32vec4 qs;
int32_t scale;
vec2 dm;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
return a_tile(repack4(ib_a, iqs * 4), int32_t(get_scale(ib_a, iqs * 4)), vec2(get_dm(ib_a)));
}
FLOAT_TYPE dot_a_tile(const a_tile t) {
int32_t sum_d = 0;
int32_t sum_m = 0;
const i32vec4 qs_a = repack4(ib_a, iqs * 4);
const uint8_t scale = get_scale(ib_a, iqs * 4);
const vec2 dm = vec2(get_dm(ib_a));
const int32_t scale_m = int32_t(scale >> 4) * 0x01010101; // Duplicate 8-bit value across 32-bits.
const int32_t scale_m = int32_t(t.scale >> 4) * 0x01010101; // Duplicate 8-bit value across 32-bits.
sum_d += dotPacked4x8EXT(qs_a.x, cache_b_qs[0]) * (scale & 0xF);
sum_d += dotPacked4x8EXT(t.qs.x, cache_b_qs[0]) * (t.scale & 0xF);
sum_m += dotPacked4x8EXT(scale_m, cache_b_qs[0]);
sum_d += dotPacked4x8EXT(qs_a.y, cache_b_qs[1]) * (scale & 0xF);
sum_d += dotPacked4x8EXT(t.qs.y, cache_b_qs[1]) * (t.scale & 0xF);
sum_m += dotPacked4x8EXT(scale_m, cache_b_qs[1]);
sum_d += dotPacked4x8EXT(qs_a.z, cache_b_qs[2]) * (scale & 0xF);
sum_d += dotPacked4x8EXT(t.qs.z, cache_b_qs[2]) * (t.scale & 0xF);
sum_m += dotPacked4x8EXT(scale_m, cache_b_qs[2]);
sum_d += dotPacked4x8EXT(qs_a.w, cache_b_qs[3]) * (scale & 0xF);
sum_d += dotPacked4x8EXT(t.qs.w, cache_b_qs[3]) * (t.scale & 0xF);
sum_m += dotPacked4x8EXT(scale_m, cache_b_qs[3]);
return FLOAT_TYPE(float(cache_b_ds.x) * (float(dm.x) * float(sum_d) - float(dm.y) * float(sum_m)));
return FLOAT_TYPE(float(cache_b_ds.x) * (float(t.dm.x) * float(sum_d) - float(t.dm.y) * float(sum_m)));
}
#endif
@@ -295,18 +327,24 @@ float get_d_scale(uint ib, uint iqs) {
return float(data_a[ib_k].d) * float(scale - 32);
}
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
struct a_tile {
i32vec4 qs;
float d_scale;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
return a_tile(repack4(ib_a, iqs * 4), get_d_scale(ib_a, iqs * 4));
}
FLOAT_TYPE dot_a_tile(const a_tile t) {
int32_t q_sum = 0;
const i32vec4 qs_a = repack4(ib_a, iqs * 4);
const float d_scale = get_d_scale(ib_a, iqs * 4);
q_sum += dotPacked4x8EXT(t.qs.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(t.qs.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(t.qs.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(t.qs.w, cache_b_qs[3]);
q_sum += dotPacked4x8EXT(qs_a.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(qs_a.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(qs_a.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(qs_a.w, cache_b_qs[3]);
return FLOAT_TYPE(float(cache_b_ds.x) * d_scale * float(q_sum));
return FLOAT_TYPE(float(cache_b_ds.x) * t.d_scale * float(q_sum));
}
#endif
@@ -365,18 +403,24 @@ vec2 get_dm_scale(uint ib, uint iqs) {
return FLOAT_TYPEV2(data_a_packed32[ib_k].dm) * FLOAT_TYPEV2(scale_dm);
}
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
struct a_tile {
i32vec4 qs;
vec2 dm_scale;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
return a_tile(repack4(ib_a, iqs * 4), get_dm_scale(ib_a, iqs * 4));
}
FLOAT_TYPE dot_a_tile(const a_tile t) {
int32_t q_sum = 0;
const i32vec4 qs_a = repack4(ib_a, iqs * 4);
const vec2 dm_scale = get_dm_scale(ib_a, iqs * 4);
q_sum += dotPacked4x8EXT(t.qs.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(t.qs.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(t.qs.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(t.qs.w, cache_b_qs[3]);
q_sum += dotPacked4x8EXT(qs_a.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(qs_a.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(qs_a.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(qs_a.w, cache_b_qs[3]);
return FLOAT_TYPE(float(cache_b_ds.x) * float(dm_scale.x) * float(q_sum) - float(dm_scale.y) * float(cache_b_ds.y / 2));
return FLOAT_TYPE(float(cache_b_ds.x) * float(t.dm_scale.x) * float(q_sum) - float(t.dm_scale.y) * float(cache_b_ds.y / 2));
}
#endif
@@ -433,40 +477,67 @@ float get_d_scale(uint ib, uint iqs) {
return float(data_a[ib_k].d) * float(data_a[ib_k].scales[iqs_k / 4]);
}
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
struct a_tile {
i32vec4 qs;
float d_scale;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
return a_tile(repack4(ib_a, iqs * 4), get_d_scale(ib_a, iqs * 4));
}
FLOAT_TYPE dot_a_tile(const a_tile t) {
int32_t q_sum = 0;
const i32vec4 qs_a = repack4(ib_a, iqs * 4);
const float d_scale = get_d_scale(ib_a, iqs * 4);
q_sum += dotPacked4x8EXT(t.qs.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(t.qs.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(t.qs.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(t.qs.w, cache_b_qs[3]);
q_sum += dotPacked4x8EXT(qs_a.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(qs_a.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(qs_a.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(qs_a.w, cache_b_qs[3]);
return FLOAT_TYPE(float(cache_b_ds.x) * float(d_scale) * float(q_sum));
return FLOAT_TYPE(float(cache_b_ds.x) * float(t.d_scale) * float(q_sum));
}
#endif
#if defined(DATA_A_IQ4_XS)
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
struct a_tile {
uvec4 qs;
float d;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
const uint ib = ib_a / 8;
const uint ib32 = ib_a % 8;
int32_t q_sum = 0;
[[unroll]] for (uint j = 0; j < 4; ++j) {
const uint32_t vui = data_a_packed32[ib].qs[4 * ib32 + j];
const i32vec2 qs_a = iq4nl_to_i8x8(vui);
q_sum += dotPacked4x8EXT(qs_a.x, cache_b_qs[j]);
q_sum += dotPacked4x8EXT(qs_a.y, cache_b_qs[j + 4]);
}
a_tile t;
t.qs.x = data_a_packed32[ib].qs[4 * ib32 + 0];
t.qs.y = data_a_packed32[ib].qs[4 * ib32 + 1];
t.qs.z = data_a_packed32[ib].qs[4 * ib32 + 2];
t.qs.w = data_a_packed32[ib].qs[4 * ib32 + 3];
const uint sl = (data_a_packed32[ib].scales_l >> (4 * ib32)) & 0xF;
const uint sh = (data_a_packed32[ib].scales_h >> (2 * ib32)) & 3;
const float d = float(data_a[ib].d) * float(int(sl | (sh << 4)) - 32);
t.d = float(data_a[ib].d) * float(int(sl | (sh << 4)) - 32);
return FLOAT_TYPE(float(cache_b_ds.x) * d * float(q_sum));
return t;
}
FLOAT_TYPE dot_a_tile(const a_tile t) {
int32_t q_sum = 0;
const i32vec2 qs_a0 = iq4nl_to_i8x8(t.qs.x);
const i32vec2 qs_a1 = iq4nl_to_i8x8(t.qs.y);
const i32vec2 qs_a2 = iq4nl_to_i8x8(t.qs.z);
const i32vec2 qs_a3 = iq4nl_to_i8x8(t.qs.w);
q_sum += dotPacked4x8EXT(qs_a0.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(qs_a0.y, cache_b_qs[4]);
q_sum += dotPacked4x8EXT(qs_a1.x, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(qs_a1.y, cache_b_qs[5]);
q_sum += dotPacked4x8EXT(qs_a2.x, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(qs_a2.y, cache_b_qs[6]);
q_sum += dotPacked4x8EXT(qs_a3.x, cache_b_qs[3]);
q_sum += dotPacked4x8EXT(qs_a3.y, cache_b_qs[7]);
return FLOAT_TYPE(float(cache_b_ds.x) * t.d * float(q_sum));
}
#endif
@@ -517,33 +588,50 @@ vec2 get_dm(uint ib, uint iqs) {
return FLOAT_TYPEV2(dl, dl * (delta - 1));
}
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
int32_t q_sum = 0;
struct a_tile {
i32vec4 qs0;
i32vec4 qs1;
vec2 dm;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
const uint ib_k = ib_a / 8;
const uint iqs_k = (ib_a % 8) * 32 + iqs * 32;
i32vec4 qs_a0;
i32vec4 qs_a1;
repack8(ib_k, iqs_k, qs_a0, qs_a1);
a_tile t;
repack8(ib_k, iqs_k, t.qs0, t.qs1);
t.dm = get_dm(ib_k, iqs_k);
return t;
}
const vec2 dm = get_dm(ib_k, iqs_k);
FLOAT_TYPE dot_a_tile(const a_tile t) {
int32_t q_sum = 0;
q_sum += dotPacked4x8EXT(qs_a0.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(qs_a0.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(qs_a0.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(qs_a0.w, cache_b_qs[3]);
q_sum += dotPacked4x8EXT(qs_a1.x, cache_b_qs[4]);
q_sum += dotPacked4x8EXT(qs_a1.y, cache_b_qs[5]);
q_sum += dotPacked4x8EXT(qs_a1.z, cache_b_qs[6]);
q_sum += dotPacked4x8EXT(qs_a1.w, cache_b_qs[7]);
q_sum += dotPacked4x8EXT(t.qs0.x, cache_b_qs[0]);
q_sum += dotPacked4x8EXT(t.qs0.y, cache_b_qs[1]);
q_sum += dotPacked4x8EXT(t.qs0.z, cache_b_qs[2]);
q_sum += dotPacked4x8EXT(t.qs0.w, cache_b_qs[3]);
q_sum += dotPacked4x8EXT(t.qs1.x, cache_b_qs[4]);
q_sum += dotPacked4x8EXT(t.qs1.y, cache_b_qs[5]);
q_sum += dotPacked4x8EXT(t.qs1.z, cache_b_qs[6]);
q_sum += dotPacked4x8EXT(t.qs1.w, cache_b_qs[7]);
return FLOAT_TYPE(float(cache_b_ds.x) * float(dm.x) * float(q_sum) + float(dm.y) * float(cache_b_ds.y));
return FLOAT_TYPE(float(cache_b_ds.x) * float(t.dm.x) * float(q_sum) + float(t.dm.y) * float(cache_b_ds.y));
}
#endif
#if defined(DATA_A_IQ1_M)
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
struct a_tile {
float dl0;
float dl1;
int32_t grid0;
int32_t grid1;
int32_t grid2;
int32_t grid3;
uint qh16;
};
a_tile load_a_tile(const uint ib_a, const uint iqs) {
const uint ib_k = ib_a / 8;
const uint iqs_k = (ib_a % 8) * 32 + iqs * 32;
@@ -556,17 +644,25 @@ FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
const uint qs32 = data_a_packed32[ib_k].qs[ib32];
const uint qh16 = data_a_packed16[ib_k].qh[ib32];
float sum = 0;
const uint sc = data_a[ib_k].scales[ib64];
[[unroll]] for (int l = 0; l < 4; ++l) {
const uint ib16 = 2 * ib32 + l / 2;
const float dl = d * (2 * bitfieldExtract(sc, 3 * int(ib16 & 3), 3) + 1);
const uint qh = qh16 >> (4 * l);
const uint qs = (qs32 >> (8 * l)) & 0xFF;
const float delta = ((qh & 8) != 0) ? -IQ1M_DELTA : IQ1M_DELTA;
const int32_t grid = int32_t(iq1s_grid_gpu[qs | ((qh & 7) << 8)]);
a_tile t;
t.dl0 = d * (2 * bitfieldExtract(sc, 3 * int((2 * ib32) & 3), 3) + 1);
t.dl1 = d * (2 * bitfieldExtract(sc, 3 * int((2 * ib32 + 1) & 3), 3) + 1);
t.qh16 = qh16;
t.grid0 = int32_t(iq1s_grid_gpu[(qs32 & 0xFF) | ((qh16 & 7) << 8)]);
t.grid1 = int32_t(iq1s_grid_gpu[((qs32 >> 8) & 0xFF) | (((qh16 >> 4) & 7) << 8)]);
t.grid2 = int32_t(iq1s_grid_gpu[((qs32 >> 16) & 0xFF) | (((qh16 >> 8) & 7) << 8)]);
t.grid3 = int32_t(iq1s_grid_gpu[((qs32 >> 24) & 0xFF) | (((qh16 >> 12) & 7) << 8)]);
return t;
}
FLOAT_TYPE dot_a_tile(const a_tile t) {
float sum = 0;
[[unroll]] for (int l = 0; l < 4; ++l) {
const float dl = (l < 2) ? t.dl0 : t.dl1;
const int32_t grid = (l == 0) ? t.grid0 : (l == 1) ? t.grid1 : (l == 2) ? t.grid2 : t.grid3;
const float delta = (((t.qh16 >> (4 * l)) & 8) != 0) ? -IQ1M_DELTA : IQ1M_DELTA;
int32_t q_sum = 0;
q_sum += dotPacked4x8EXT((grid >> 0) & 0x0F0F0F0F, cache_b_qs[2 * l + 0]);
@@ -584,3 +680,9 @@ FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
return sum;
}
#endif
// Non-hoisted path (legacy 4/8-bit types): reproduce the base per-column
// load+dot without an indexed a_tile array.
FLOAT_TYPE mmvq_dot_product(const uint ib_a, const uint iqs) {
return dot_a_tile(load_a_tile(ib_a, iqs));
}
@@ -7,6 +7,7 @@
#endif
#include "types.glsl"
#include "utils.glsl"
layout(constant_id = 0) const uint BLOCK_SIZE = 128;
layout(constant_id = 1) const uint SUBGROUP_SIZE = 32;
@@ -25,10 +26,12 @@ layout(binding = 5) readonly buffer Src5 { float C[]; };
layout(binding = 6) readonly buffer Src6 { int ids[]; };
layout(binding = 7) buffer Dst { float d[]; };
// Strides and offsets are in bytes.
layout(push_constant) uniform PushConstants {
uint nb02; uint nb03; uint nb12; uint nb13;
uint nb21; uint nb22; uint nb31;
uint nb42; uint nb43; uint nb52; uint nb53;
uint off0; uint off1; uint off2; uint off3; uint off4; uint off5; uint off6;
uint s_off;
uint n_head;
uint d_head;
@@ -40,7 +43,7 @@ layout(push_constant) uniform PushConstants {
float softplus(float x) {
if (x <= 20.0) {
return log(1.0 + exp(x));
return log1p(exp(x));
} else {
return x;
}
@@ -61,12 +64,12 @@ void main() {
const uint seq_idx = gl_WorkGroupID.y;
const uint group_off = (head_idx / (n_head / n_group)) * D_STATE * 4;
const uint s0_base_idx = (uint(ids[seq_idx]) * nb03 + head_idx * nb02 + head_off * D_STATE) / 4;
const uint x_base_idx = (seq_idx * nb13 + subgroup_idx * 4) / 4;
const uint dt_base_idx = (seq_idx * nb22 + head_idx * 4) / 4;
const uint A_base_idx = (head_idx * nb31) / 4;
const uint B_base_idx = (seq_idx * nb43 + group_off) / 4;
const uint C_base_idx = (seq_idx * nb53 + group_off) / 4;
const uint s0_base_idx = (off0 + uint(ids[off6 / 4 + seq_idx]) * nb03 + head_idx * nb02 + head_off * D_STATE) / 4;
const uint x_base_idx = (off1 + seq_idx * nb13 + subgroup_idx * 4) / 4;
const uint dt_base_idx = (off2 + seq_idx * nb22 + head_idx * 4) / 4;
const uint A_base_idx = (off3 + head_idx * nb31) / 4;
const uint B_base_idx = (off4 + seq_idx * nb43 + group_off) / 4;
const uint C_base_idx = (off5 + seq_idx * nb53 + group_off) / 4;
const uint y_base_idx = seq_idx * n_tok * n_head * d_head + subgroup_idx;
const uint s_base_idx = (s_off + seq_idx * nb03 + head_idx * nb02 + head_off * D_STATE) / 4;
@@ -0,0 +1,231 @@
#version 450
#extension GL_EXT_control_flow_attributes : require
#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require
#extension GL_EXT_shader_explicit_arithmetic_types_int32 : require
#extension GL_KHR_shader_subgroup_basic : require
#extension GL_KHR_shader_subgroup_arithmetic : require
#extension GL_KHR_shader_subgroup_shuffle : require
#extension GL_KHR_memory_scope_semantics : require
#extension GL_KHR_cooperative_matrix : require
#extension GL_NV_cooperative_matrix2 : require
#include "utils.glsl"
// Mamba-2 selective scan in chunks of T tokens (SSD form). A workgroup computes
// ROWS rows of one head, with the state S in an accumulator. Per chunk, with cs
// the cumulative sum of dt * A:
// M = (C * B^T) .* exp(cs_t - cs_s) for s <= t [T x T]
// y = exp(cs_t) * (S * C^T) + X_dt^T * M^T [ROWS x T]
// S = exp(cs_last) * S + X_w^T * B [ROWS x D_STATE]
// where X_dt[s] = dt_s * x_s and X_w[s] = exp(cs_last - cs_s) * X_dt[s].
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
layout(constant_id = 0) const uint WG_SIZE = 128;
layout(constant_id = 1) const uint D_STATE = 128;
layout(constant_id = 2) const uint T = 32; // tokens per chunk, one per subgroup lane
layout(constant_id = 3) const uint ROWS = 32; // rows per workgroup
layout(constant_id = 4) const uint PAD = 8;
// Padded row strides of the shared arrays, in f16vec4.
const uint D_STRIDE = (D_STATE + PAD) / 4;
const uint ROWS_STRIDE = (ROWS + PAD) / 4;
const uint T_STRIDE = (T + PAD) / 4;
layout(binding = 0) readonly buffer Src0 { float s0[]; };
layout(binding = 1) readonly buffer Src1 { vec4 x[]; };
layout(binding = 2) readonly buffer Src2 { float dt[]; };
layout(binding = 3) readonly buffer Src3 { float A[]; };
layout(binding = 4) readonly buffer Src4 { vec4 B[]; };
layout(binding = 5) readonly buffer Src5 { vec4 C[]; };
layout(binding = 6) readonly buffer Src6 { int ids[]; };
layout(binding = 7) writeonly buffer Dst { float d[]; };
// Strides and offsets are in bytes.
layout(push_constant) uniform PushConstants {
uint nb02; uint nb03; uint nb12; uint nb13;
uint nb21; uint nb22; uint nb31;
uint nb42; uint nb43; uint nb52; uint nb53;
uint off0; uint off1; uint off2; uint off3; uint off4; uint off5; uint off6;
uint s_off;
uint n_head;
uint d_head;
uint n_group;
uint n_tok;
uint n_seq;
uint K;
};
// coopMatLoad/Store offsets and strides are in f16vec4.
shared f16vec4 sh_c[T * D_STRIDE]; // C [T x D_STATE]
shared f16vec4 sh_b[T * D_STRIDE]; // B [T x D_STATE]
shared f16vec4 sh_s[ROWS * D_STRIDE]; // S [ROWS x D_STATE]
shared f16vec4 sh_x[2][T * ROWS_STRIDE]; // X_dt [T x ROWS], read after the second barrier
shared f16vec4 sh_w[T * ROWS_STRIDE]; // X_w [T x ROWS]
shared f16vec4 sh_m[T * T_STRIDE]; // M [T x T]
shared float sh_cs[T]; // cs_t
shared float sh_ecs[T]; // exp(cs_t)
#define WG gl_ScopeWorkgroup
#define MUA gl_MatrixUseA
#define MUB gl_MatrixUseB
#define MACC gl_MatrixUseAccumulator
#define ROW gl_CooperativeMatrixLayoutRowMajor
#define COL gl_CooperativeMatrixLayoutColumnMajor
float softplus(float v) {
return v <= 20.0 ? log1p(exp(v)) : v;
}
float DecayMask(const in uint32_t r, const in uint32_t c, const in float cb) {
return c <= r ? cb * exp(sh_cs[r] - sh_cs[c]) : 0.0;
}
float ScaleCol(const in uint32_t r, const in uint32_t c, const in float v) {
return v * sh_ecs[c];
}
const uint NB = T * D_STATE / 4 / WG_SIZE; // vec4 of B (and C) per thread and chunk
const uint NX = T * ROWS / 4 / WG_SIZE; // vec4 of x per thread and chunk
// The next chunk's inputs.
vec4 next_b[NB], next_c[NB], next_x[NX];
float next_dt;
// Reads past the end clamp to the last token and row.
void load_chunk(const uint t0, const uint B_base, const uint C_base, const uint x_base, const uint dt_base, const uint row0) {
const uint tid = gl_LocalInvocationIndex;
[[unroll]] for (uint i = 0; i < NB; ++i) {
const uint e = tid + i * WG_SIZE;
const uint t = min(t0 + e / (D_STATE / 4), n_tok - 1);
next_b[i] = B[B_base + t * (nb42 / 16) + e % (D_STATE / 4)];
next_c[i] = C[C_base + t * (nb52 / 16) + e % (D_STATE / 4)];
}
[[unroll]] for (uint i = 0; i < NX; ++i) {
const uint e = tid + i * WG_SIZE;
const uint t = min(t0 + e / (ROWS / 4), n_tok - 1);
const uint q = min(e % (ROWS / 4), (d_head - row0) / 4 - 1);
next_x[i] = x[x_base + t * (nb12 / 16) + q];
}
next_dt = dt[dt_base + min(t0 + gl_SubgroupInvocationID, n_tok - 1) * (nb21 / 4)];
}
void main() {
const uint tid = gl_LocalInvocationIndex;
const uint lane = gl_SubgroupInvocationID;
const uint head = gl_WorkGroupID.y;
const uint seq = gl_WorkGroupID.z;
const uint row0 = gl_WorkGroupID.x * ROWS;
const uint rows = min(ROWS, d_head - row0);
const uint group = head / (n_head / n_group);
const float a = A[(off3 + head * nb31) / 4];
const uint B_base = (off4 + seq * nb43 + group * D_STATE * 4) / 16;
const uint C_base = (off5 + seq * nb53 + group * D_STATE * 4) / 16;
const uint x_base = (off1 + seq * nb13 + (head * d_head + row0) * 4) / 16;
const uint dt_base = (off2 + seq * nb22) / 4 + head;
const uint stride_y = n_head * d_head;
const uint y_base = seq * n_tok * stride_y + head * d_head + row0;
// Rows past the end load as zero and are not stored.
tensorLayoutNV<2, gl_CooperativeMatrixClampModeConstantNV> layout_s = createTensorLayoutNV(2, gl_CooperativeMatrixClampModeConstantNV);
layout_s = setTensorLayoutDimensionNV(layout_s, rows, D_STATE);
tensorLayoutNV<2, gl_CooperativeMatrixClampModeConstantNV> layout_y = createTensorLayoutNV(2, gl_CooperativeMatrixClampModeConstantNV);
layout_y = setTensorLayoutDimensionNV(layout_y, n_tok, rows);
layout_y = setTensorLayoutStrideNV(layout_y, stride_y, 1);
tensorViewNV<2, false, 1, 0> transpose = createTensorViewNV(2, false, 1, 0);
coopmat<float, WG, ROWS, D_STATE, MACC> S;
coopMatLoadTensorNV(S, s0, (off0 + uint(ids[off6 / 4 + seq]) * nb03 + head * nb02) / 4 + row0 * D_STATE, sliceTensorLayoutNV(layout_s, 0, ROWS, 0, D_STATE));
load_chunk(0, B_base, C_base, x_base, dt_base, row0);
uint buf = 0; // sh_x buffer of the current chunk
for (uint t0 = 0; t0 < n_tok; t0 += T) {
const uint valid = min(T, n_tok - t0);
// One token per lane. Every subgroup computes the scan, so the staging
// below can shuffle dt_t and cs_t without a barrier.
const float dts = lane < valid ? softplus(next_dt) : 0.0;
const float cs = subgroupInclusiveAdd(dts * a);
const float cs_last = subgroupShuffle(cs, T - 1);
if (gl_SubgroupID == 0) {
sh_cs[lane] = cs;
sh_ecs[lane] = exp(cs);
}
// Stage B and C as fp16, row t holding token t.
[[unroll]] for (uint i = 0; i < NB; ++i) {
const uint e = tid + i * WG_SIZE;
const uint o = (e / (D_STATE / 4)) * D_STRIDE + e % (D_STATE / 4);
sh_b[o] = f16vec4(next_b[i]);
sh_c[o] = f16vec4(next_c[i]);
}
// Stage X_dt and X_w. Tokens past the end have dt_t = 0.
[[unroll]] for (uint i = 0; i < NX; ++i) {
const uint e = tid + i * WG_SIZE;
const uint t = e / (ROWS / 4), q = e % (ROWS / 4);
const float dt_t = subgroupShuffle(dts, t);
const float cs_t = subgroupShuffle(cs, t);
sh_x[buf][t * ROWS_STRIDE + q] = f16vec4(next_x[i] * dt_t);
sh_w[t * ROWS_STRIDE + q] = f16vec4(next_x[i] * (exp(cs_last - cs_t) * dt_t));
}
if (t0 + T < n_tok) {
load_chunk(t0 + T, B_base, C_base, x_base, dt_base, row0);
}
coopMatStore(coopmat<float16_t, WG, ROWS, D_STATE, MACC>(S), sh_s, 0, D_STRIDE, ROW);
barrier();
// M = (C * B^T) .* decay [T x T]
{
coopmat<float, WG, T, T, MACC> cb = coopmat<float, WG, T, T, MACC>(0.0);
coopmat<float16_t, WG, T, D_STATE, MUA> c;
coopmat<float16_t, WG, D_STATE, T, MUB> b;
coopMatLoad(c, sh_c, 0, D_STRIDE, ROW);
coopMatLoad(b, sh_b, 0, D_STRIDE, COL);
cb = coopMatMulAdd(c, b, cb);
coopMatPerElementNV(cb, cb, DecayMask);
coopMatStore(coopmat<float16_t, WG, T, T, MACC>(cb), sh_m, 0, T_STRIDE, ROW);
}
// y = exp(cs_t) * (S * C^T) [ROWS x T]
coopmat<float, WG, ROWS, T, MACC> y = coopmat<float, WG, ROWS, T, MACC>(0.0);
{
coopmat<float16_t, WG, ROWS, D_STATE, MUA> s;
coopmat<float16_t, WG, D_STATE, T, MUB> c;
coopMatLoad(s, sh_s, 0, D_STRIDE, ROW);
coopMatLoad(c, sh_c, 0, D_STRIDE, COL);
y = coopMatMulAdd(s, c, y);
}
coopMatPerElementNV(y, y, ScaleCol);
// S = exp(cs_last) * S + X_w^T * B
{
coopmat<float16_t, WG, ROWS, T, MUA> w;
coopmat<float16_t, WG, T, D_STATE, MUB> b;
coopMatLoad(w, sh_w, 0, ROWS_STRIDE, COL);
coopMatLoad(b, sh_b, 0, D_STRIDE, ROW);
S *= exp(cs_last);
S = coopMatMulAdd(w, b, S);
}
barrier();
// y += X_dt^T * M^T
{
coopmat<float16_t, WG, ROWS, T, MUA> xm;
coopmat<float16_t, WG, T, T, MUB> m;
coopMatLoad(xm, sh_x[buf], 0, ROWS_STRIDE, COL);
coopMatLoad(m, sh_m, 0, T_STRIDE, COL);
y = coopMatMulAdd(xm, m, y);
}
coopMatStoreTensorNV(y, d, y_base, sliceTensorLayoutNV(layout_y, t0, T, 0, ROWS), transpose);
buf ^= 1;
}
coopMatStoreTensorNV(S, d, (s_off + seq * nb03 + head * nb02) / 4 + row0 * D_STATE, sliceTensorLayoutNV(layout_s, 0, ROWS, 0, D_STATE));
}
@@ -0,0 +1,203 @@
#version 450
#extension GL_EXT_control_flow_attributes : require
#extension GL_KHR_shader_subgroup_basic : require
#extension GL_KHR_shader_subgroup_shuffle : require
#include "utils.glsl"
// Mamba-2 selective scan over several tokens (fp32). A workgroup computes ROWS
// rows of one head, and the LPR lanes of a row group keep the state of R rows
// in registers. Chunks of T tokens are staged in shared memory, and the sums
// are reduced once per chunk.
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
layout(constant_id = 0) const uint WG_SIZE = 128;
layout(constant_id = 1) const uint D_STATE = 128;
layout(constant_id = 2) const uint T = 16; // tokens per chunk
layout(constant_id = 3) const uint LPR = 16; // lanes per row group
layout(constant_id = 4) const uint R = 2; // rows per thread
const uint S = D_STATE / LPR; // state values per lane and row
const uint ROWS = WG_SIZE / LPR * R; // rows per workgroup
const uint NB = T * D_STATE / 4 / WG_SIZE; // vec4 of B (and C) per thread and chunk
const uint NF = T * R / LPR; // reduced sums per lane per chunk
layout(binding = 0) readonly buffer Src0 { float s0[]; };
layout(binding = 1) readonly buffer Src1 { vec4 x[]; };
layout(binding = 2) readonly buffer Src2 { float dt[]; };
layout(binding = 3) readonly buffer Src3 { float A[]; };
layout(binding = 4) readonly buffer Src4 { vec4 B[]; };
layout(binding = 5) readonly buffer Src5 { vec4 C[]; };
layout(binding = 6) readonly buffer Src6 { int ids[]; };
layout(binding = 7) writeonly buffer Dst { float d[]; };
// Strides and offsets are in bytes.
layout(push_constant) uniform PushConstants {
uint nb02; uint nb03; uint nb12; uint nb13;
uint nb21; uint nb22; uint nb31;
uint nb42; uint nb43; uint nb52; uint nb53;
uint off0; uint off1; uint off2; uint off3; uint off4; uint off5; uint off6;
uint s_off;
uint n_head;
uint d_head;
uint n_group;
uint n_tok;
uint n_seq;
uint K;
};
shared vec4 sh_b[2][T][D_STATE / 4];
shared vec4 sh_c[2][T][D_STATE / 4];
shared float sh_x[2][T][ROWS]; // x * dt
shared float sh_da[2][T]; // exp(dt * A)
float softplus(float v) {
return v <= 20.0 ? log1p(exp(v)) : v;
}
// The next chunk's inputs.
vec4 next_b[NB], next_c[NB], next_x;
float next_dt;
// Reads past the end clamp to the last token and row. store_chunk gives
// tokens past the end dt = 0 and dA = 1.
void load_chunk(const uint t0, const uint B_base, const uint C_base, const uint x_base, const uint dt_base, const uint row0) {
const uint tid = gl_LocalInvocationIndex;
[[unroll]] for (uint i = 0; i < NB; ++i) {
const uint e = tid + i * WG_SIZE;
const uint t = min(t0 + e / (D_STATE / 4), n_tok - 1);
next_b[i] = B[B_base + t * (nb42 / 16) + e % (D_STATE / 4)];
next_c[i] = C[C_base + t * (nb52 / 16) + e % (D_STATE / 4)];
}
// 4 rows of x of one token, and that token's dt.
if (tid < T * ROWS / 4) {
const uint t = min(t0 + tid / (ROWS / 4), n_tok - 1);
const uint q = min(row0 / 4 + tid % (ROWS / 4), d_head / 4 - 1);
next_x = x[x_base + t * (nb12 / 16) + q];
next_dt = dt[dt_base + t * (nb21 / 4)];
}
}
void store_chunk(const uint b, const uint t0, const float a) {
const uint tid = gl_LocalInvocationIndex;
[[unroll]] for (uint i = 0; i < NB; ++i) {
const uint e = tid + i * WG_SIZE;
sh_b[b][e / (D_STATE / 4)][e % (D_STATE / 4)] = next_b[i];
sh_c[b][e / (D_STATE / 4)][e % (D_STATE / 4)] = next_c[i];
}
if (tid < T * ROWS / 4) {
const uint t = tid / (ROWS / 4), q = tid % (ROWS / 4);
const bool valid = t0 + t < n_tok;
const float dts = valid ? softplus(next_dt) : 0.0;
[[unroll]] for (uint k = 0; k < 4; ++k) {
sh_x[b][t][q * 4 + k] = next_x[k] * dts;
}
if (q == 0) {
sh_da[b][t] = valid ? exp(dts * a) : 1.0;
}
}
}
// Lane ln keeps every LPR-th vec4 of a row, so a row group reads contiguous
// vec4s of B and C.
uint state_col(const uint k, const uint ln) {
return ((k / 4) * LPR + ln) * 4 + k % 4;
}
void main() {
// Number row groups in subgroup lane order for the shuffle reduction.
const uint tid = gl_SubgroupID * gl_SubgroupSize + gl_SubgroupInvocationID;
const uint rg = tid / LPR; // row group within the workgroup
const uint ln = tid % LPR; // lane within the row group
const uint head = gl_WorkGroupID.y;
const uint seq = gl_WorkGroupID.z;
const uint row0 = gl_WorkGroupID.x * ROWS;
const uint group = head / (n_head / n_group);
const float a = A[(off3 + head * nb31) / 4];
const uint B_base = (off4 + seq * nb43 + group * D_STATE * 4) / 16;
const uint C_base = (off5 + seq * nb53 + group * D_STATE * 4) / 16;
const uint x_base = (off1 + seq * nb13 + head * d_head * 4) / 16;
const uint dt_base = (off2 + seq * nb22) / 4 + head;
const uint stride_y = n_head * d_head;
const uint y_base = seq * n_tok * stride_y + head * d_head + row0;
// state[j][k] is row row0 + rg * R + j, column state_col(k, ln).
float state[R][S];
const uint s0_base = (off0 + uint(ids[off6 / 4 + seq]) * nb03 + head * nb02) / 4;
const uint s_base = (s_off + seq * nb03 + head * nb02) / 4;
[[unroll]] for (uint j = 0; j < R; ++j) {
const uint row = row0 + rg * R + j;
[[unroll]] for (uint k = 0; k < S; ++k) {
state[j][k] = row < d_head ? s0[s0_base + row * D_STATE + state_col(k, ln)] : 0.0;
}
}
load_chunk(0, B_base, C_base, x_base, dt_base, row0);
store_chunk(0, 0, a);
barrier();
uint buf = 0;
for (uint t0 = 0; t0 < n_tok; t0 += T) {
const bool more = t0 + T < n_tok;
if (more) {
load_chunk(t0 + T, B_base, C_base, x_base, dt_base, row0);
}
float part[T * R];
[[unroll]] for (uint t = 0; t < T; ++t) {
const float dA = sh_da[buf][t];
vec4 bv[S / 4], cv[S / 4];
[[unroll]] for (uint q = 0; q < S / 4; ++q) {
bv[q] = sh_b[buf][t][q * LPR + ln];
cv[q] = sh_c[buf][t][q * LPR + ln];
}
[[unroll]] for (uint j = 0; j < R; ++j) {
const float xdt = sh_x[buf][t][rg * R + j];
float p = 0.0;
[[unroll]] for (uint k = 0; k < S; ++k) {
state[j][k] = fma(state[j][k], dA, bv[k / 4][k % 4] * xdt);
p = fma(state[j][k], cv[k / 4][k % 4], p);
}
part[t * R + j] = p;
}
}
// Butterfly reduction over the row group. Lane ln ends with the sums
// ln * NF .. ln * NF + NF - 1 of part.
[[unroll]] for (uint l = 0; (LPR >> l) > 1; ++l) {
const uint m = LPR >> (l + 1);
const uint h = (T * R) >> (l + 1);
const bool upper = (ln & m) != 0;
[[unroll]] for (uint i = 0; i < h; ++i) {
const float keep = upper ? part[i + h] : part[i];
const float send = upper ? part[i] : part[i + h];
part[i] = keep + subgroupShuffleXor(send, m);
}
}
[[unroll]] for (uint i = 0; i < NF; ++i) {
const uint f = ln * NF + i;
const uint t = f / R, row = rg * R + f % R;
if (t0 + t < n_tok && row0 + row < d_head) {
d[y_base + (t0 + t) * stride_y + row] = part[i];
}
}
if (more) {
store_chunk(buf ^ 1, t0 + T, a);
}
barrier();
buf ^= 1;
}
[[unroll]] for (uint j = 0; j < R; ++j) {
const uint row = row0 + rg * R + j;
if (row < d_head) {
[[unroll]] for (uint k = 0; k < S; ++k) {
d[s_base + row * D_STATE + state_col(k, ln)] = state[j][k];
}
}
}
}
@@ -1267,6 +1267,10 @@ void process_shaders() {
string_to_spv("ssm_scan_f32", "ssm_scan.comp", {{"A_TYPE", "float"}});
string_to_spv("ssm_scan_subgroup_f32", "ssm_scan.comp", {{"A_TYPE", "float"}, {"USE_SUBGROUP_ADD", "1"}});
string_to_spv("ssm_scan_prefill_f32", "ssm_scan_prefill.comp", {});
#if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
string_to_spv("ssm_scan_f32", "ssm_scan_cm2.comp", {}, true, false, true);
#endif
string_to_spv("ssm_conv_f32", "ssm_conv.comp", {{"A_TYPE", "float"}});
+10 -2
View File
@@ -9,7 +9,7 @@ from pathlib import Path
if "NO_LOCAL_GGUF" not in os.environ and (Path(__file__).parent.parent.parent.parent / 'gguf-py').exists():
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
from gguf import GGUFReader # noqa: E402
from gguf import GGUFReader, GGUFValueType # noqa: E402
logger = logging.getLogger("gguf-set-metadata")
@@ -54,7 +54,15 @@ def set_metadata(reader: GGUFReader, args: argparse.Namespace) -> None:
logger.error(f'! This tool only supports changing simple values, {repr(args.key)} has unsupported type {field.types}')
sys.exit(1)
current_value = field.parts[field.data[0]][0]
new_value = handler(args.value)
if field.types[0] == GGUFValueType.BOOL:
# np.bool_ of any non-empty string is True, so "false" must be parsed
value = args.value.lower()
if value not in ('true', 'false', '1', '0', ''):
logger.error(f'! Invalid value {repr(args.value)} for bool field {repr(args.key)}, use true/false or 1/0')
sys.exit(1)
new_value = handler(value in ('true', '1'))
else:
new_value = handler(args.value)
logger.info(f'* Preparing to change field {repr(args.key)} from {current_value} to {new_value}')
if current_value == new_value:
logger.info(f'- Key {repr(args.key)} already set to requested value {current_value}')
+5 -5
View File
@@ -174,6 +174,11 @@ llama_model_afmoe::graph::graph(const llm_graph_params & params) : llm_graph_con
cb(cur, "attn_gated", il);
// now apply output projection
if (il == n_layer - 1 && inp_out_ids) {
cur = ggml_get_rows(ctx0, cur, inp_out_ids);
inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
}
cur = build_lora_mm(model.layers[il].wo, cur);
cb(cur, "attn_o_proj", il);
}
@@ -184,11 +189,6 @@ llama_model_afmoe::graph::graph(const llm_graph_params & params) : llm_graph_con
LLM_NORM_RMS, il);
cb(cur, "attn_post_norm", il);
if (il == n_layer - 1 && inp_out_ids) {
cur = ggml_get_rows(ctx0, cur, inp_out_ids);
inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
}
ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
cb(ffn_inp, "ffn_inp", il);
+20 -6
View File
@@ -600,13 +600,25 @@ ggml_tensor * llama_model_deepseek41::graph::build_attention41(
// own scores, restricted to the source's candidate blocks: 0 inside them, -inf elsewhere
ggml_tensor * bsel = ggml_cont(ctx0, rows(cand_sel));
const int64_t k_b = bsel->ne[0];
ggml_tensor * bm = ggml_fill(ctx0, ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, 1, n_blk, nc*n_stream, 1), -INFINITY);
ggml_tensor * zeros = ggml_fill(ctx0, ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, 1, k_b, nc*n_stream, 1), 0.0f);
bm = ggml_set_rows(ctx0, bm, zeros, ggml_reshape_3d(ctx0, bsel, k_b, nc*n_stream, 1));
bm = ggml_reshape_2d(ctx0, ggml_repeat_4d(ctx0, bm, bs, n_blk, nc*n_stream, 1), bs*n_blk, nc*n_stream);
bm = ggml_reshape_4d(ctx0, ggml_cont(ctx0, ggml_view_2d(ctx0, bm, n_comp, nc*n_stream, bm->nb[1], 0)), n_comp, nc, 1, n_stream);
cb(bm, "cand_mask", il);
score = ggml_add(ctx0, score, bm);
if (n_blk*bs == n_comp && ggml_is_contiguous(score)) {
// add the per-block mask with broadcast, in place: no [n_comp, tokens] mask tensor
// fill a computed node, not a new leaf: a leaf stays allocated for the whole graph
ggml_tensor * bm = ggml_cont(ctx0, ggml_view_3d(ctx0, score, 1, n_blk, nc*n_stream, bs*ggml_element_size(score), score->nb[1], 0));
bm = ggml_fill_inplace(ctx0, bm, -INFINITY);
bm = ggml_set_rows(ctx0, bm, zeros, ggml_reshape_3d(ctx0, bsel, k_b, nc*n_stream, 1));
bm = ggml_reshape_4d(ctx0, bm, 1, n_blk, nc, n_stream);
cb(bm, "cand_mask", il);
score = ggml_add_inplace(ctx0, ggml_reshape_4d(ctx0, score, bs, n_blk, nc, n_stream), bm);
score = ggml_reshape_4d(ctx0, score, n_comp, nc, 1, n_stream);
} else {
ggml_tensor * bm = ggml_fill(ctx0, ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, 1, n_blk, nc*n_stream, 1), -INFINITY);
bm = ggml_set_rows(ctx0, bm, zeros, ggml_reshape_3d(ctx0, bsel, k_b, nc*n_stream, 1));
bm = ggml_reshape_2d(ctx0, ggml_repeat_4d(ctx0, bm, bs, n_blk, nc*n_stream, 1), bs*n_blk, nc*n_stream);
bm = ggml_reshape_4d(ctx0, ggml_cont(ctx0, ggml_view_2d(ctx0, bm, n_comp, nc*n_stream, bm->nb[1], 0)), n_comp, nc, 1, n_stream);
cb(bm, "cand_mask", il);
score = ggml_add(ctx0, score, bm);
}
}
parts_top_k.push_back(ggml_top_k(ctx0, score, std::min<int64_t>(n_comp, hparams.indexer_top_k)));
@@ -625,6 +637,8 @@ ggml_tensor * llama_model_deepseek41::graph::build_attention41(
if (pick_blk) {
cand_sel = join(parts_sel);
cand_n_comp = n_comp;
// compute it here: else the scores of this layer stay allocated until the first consumer layer
ggml_build_forward_expand(gf, cand_sel);
}
top_k = ggml_cont(ctx0, join(parts_top_k));
cb(top_k, "idx_top_k", il);
+5 -5
View File
@@ -251,15 +251,15 @@ llama_model_laguna::graph::graph(const llm_graph_params & params) : llm_graph_co
}
cb(cur, "attn_gated", il);
if (il == n_layer - 1 && inp_out_ids) {
cur = ggml_get_rows(ctx0, cur, inp_out_ids);
inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
}
cur = build_lora_mm(model.layers[il].wo, cur);
cb(cur, "attn_o_proj", il);
}
if (il == n_layer - 1 && inp_out_ids) {
cur = ggml_get_rows(ctx0, cur, inp_out_ids);
inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
}
ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
cb(ffn_inp, "ffn_inp", il);
+2 -2
View File
@@ -1,8 +1,8 @@
# test-fusion baseline for device MTL
# arch ,moe ,mode ,label , count
afmoe ,1 ,any ,MUL+ADD , 2
afmoe ,1 ,any ,RMS_NORM+MUL , 10
afmoe ,1 ,any ,RMS_NORM+MUL+ADD , 3
afmoe ,1 ,any ,RMS_NORM+MUL , 9
afmoe ,1 ,any ,RMS_NORM+MUL+ADD , 4
afmoe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
apertus ,0 ,any ,RMS_NORM+MUL , 9
arcee ,0 ,any ,RMS_NORM+MUL , 5
1 # test-fusion baseline for device MTL
2 # arch ,moe ,mode ,label , count
3 afmoe ,1 ,any ,MUL+ADD , 2
4 afmoe ,1 ,any ,RMS_NORM+MUL , 10 afmoe ,1 ,any ,RMS_NORM+MUL , 9
5 afmoe ,1 ,any ,RMS_NORM+MUL+ADD , 3 afmoe ,1 ,any ,RMS_NORM+MUL+ADD , 4
6 afmoe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
7 apertus ,0 ,any ,RMS_NORM+MUL , 9
8 arcee ,0 ,any ,RMS_NORM+MUL , 5
+25
View File
@@ -1167,6 +1167,30 @@ static void test_buft_get_alloc_size_n_does_not_allocate() {
GGML_ASSERT(x[1]->data == nullptr);
}
// Parent larger than max_size splits off a view-only tail with size 0.
// That tail is not in the alloc plan, so views must be initialized after the split.
static void test_view_init_after_max_size_split() {
const size_t max_size = 16;
dummy_backend backend = dummy_backend_init(max_size);
auto [ctx, graph, ctx_ptr] = make_context();
(void) graph;
ggml_tensor * parent = make_input_with_size(ctx, 24); // 6 x f32, > max_size
ggml_tensor * view0 = ggml_view_1d(ctx, parent, 2, 0);
ggml_tensor * view1 = ggml_view_1d(ctx, parent, 2, 2 * sizeof(float));
assign_names(ctx);
ggml_backend_buffer_ptr buf(ggml_backend_alloc_ctx_tensors_from_buft(ctx, &backend.buffer_type));
GGML_ASSERT(buf);
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t; t = ggml_get_next_tensor(ctx, t)) {
GGML_ASSERT(t->buffer != nullptr);
GGML_ASSERT(t->data != nullptr);
}
GGML_ASSERT(view0->view_src == parent);
GGML_ASSERT(view1->view_src == parent);
}
static void run(const char * name, void (*f)()) {
printf("%s ", name);
fflush(stdout);
@@ -1208,5 +1232,6 @@ int main() {
run("test_buft_get_alloc_size_n_custom_override", test_buft_get_alloc_size_n_custom_override);
run("test_buft_get_alloc_size_n_custom_override_ctx_size", test_buft_get_alloc_size_n_custom_override_ctx_size);
run("test_buft_get_alloc_size_n_does_not_allocate", test_buft_get_alloc_size_n_does_not_allocate);
run("test_view_init_after_max_size_split", test_view_init_after_max_size_split);
return 0;
}
+112 -28
View File
@@ -5053,6 +5053,8 @@ struct test_short_conv : public test_case {
struct test_depth_mix : public test_case {
const int64_t n, B, Q, T;
const bool shared_norm;
const int64_t cur_pad;
const int64_t cur_off;
std::vector<ggml_tensor *> verify;
@@ -5065,11 +5067,12 @@ struct test_depth_mix : public test_case {
std::vector<ggml_tensor *> fusion_test_nodes() override { return verify; }
std::string vars() override {
return VARS_TO_STR5(n, B, Q, T, shared_norm);
return VARS_TO_STR7(n, B, Q, T, shared_norm, cur_pad, cur_off);
}
test_depth_mix(int64_t n = 2304, int64_t B = 8, int64_t Q = 1, int64_t T = 1, bool shared_norm = false)
: n(n), B(B), Q(Q), T(T), shared_norm(shared_norm) {}
test_depth_mix(int64_t n = 2304, int64_t B = 8, int64_t Q = 1, int64_t T = 1, bool shared_norm = false, int64_t cur_pad = 0,
int64_t cur_off = 0)
: n(n), B(B), Q(Q), T(T), shared_norm(shared_norm), cur_pad(cur_pad), cur_off(cur_off) {}
double max_nmse_err() override {
return 5e-4;
@@ -5078,12 +5081,16 @@ struct test_depth_mix : public test_case {
ggml_tensor * build_graph(ggml_context * ctx) override {
verify.clear();
ggml_tensor * stack = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n, B, T);
ggml_tensor * cur = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, T);
ggml_tensor * cur = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n + cur_pad, T);
ggml_tensor * query = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, Q);
ggml_set_name(stack, "stack");
ggml_set_name(cur, "cur");
ggml_tensor * norm = ggml_rms_norm(ctx, ggml_reshape_3d(ctx, cur, n, 1, T), 1e-6f);
// the rows of cur are cur_pad elements apart and start cur_off elements into the row (cur_off <= cur_pad)
ggml_tensor * cur_rows = cur_pad == 0 ? ggml_reshape_3d(ctx, cur, n, 1, T) :
ggml_view_3d(ctx, cur, n, 1, T, cur->nb[1], cur->nb[1], cur_off * sizeof(float));
ggml_tensor * norm = ggml_rms_norm(ctx, cur_rows, 1e-6f);
if (shared_norm) {
ggml_tensor * other = ggml_scale(ctx, norm, 2.0f);
if (gf) {
@@ -5675,6 +5682,8 @@ struct test_ssm_conv_concat_fusion : public test_case {
};
// GGML_OP_SSM_SCAN
// xbc_graph: x, B and C are views of one tensor with rows [xbc_off | x | B | C | pad], as in the Mamba-2 graph.
// off: s, dt, A and ids start off elements into their tensors.
struct test_ssm_scan : public test_case {
const ggml_type type;
@@ -5687,9 +5696,15 @@ struct test_ssm_scan : public test_case {
const bool xbc_overlap;
const int64_t K;
const bool weak_decay;
const bool xbc_graph;
const int64_t off;
const int64_t xbc_off;
const int64_t pad;
const bool seq_major;
std::string vars() override {
return VARS_TO_STR10(type, d_state, head_dim, n_head, n_group, n_seq_tokens, n_seqs, xbc_overlap, K, weak_decay);
return VARS_TO_STR15(type, d_state, head_dim, n_head, n_group, n_seq_tokens, n_seqs, xbc_overlap, K, weak_decay,
xbc_graph, off, xbc_off, pad, seq_major);
}
test_ssm_scan(ggml_type type = GGML_TYPE_F32,
@@ -5701,23 +5716,41 @@ struct test_ssm_scan : public test_case {
int64_t n_seqs = 32,
bool xbc_overlap = false,
int64_t K = 1,
bool weak_decay = false)
: type(type), d_state(d_state), head_dim(head_dim), n_head(n_head), n_group(n_group), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), xbc_overlap(xbc_overlap), K(K), weak_decay(weak_decay) {}
bool weak_decay = false,
bool xbc_graph = false,
int64_t off = 0,
int64_t xbc_off = 0,
int64_t pad = 0,
bool seq_major = false)
: type(type), d_state(d_state), head_dim(head_dim), n_head(n_head), n_group(n_group), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), xbc_overlap(xbc_overlap), K(K), weak_decay(weak_decay),
xbc_graph(xbc_graph), off(off), xbc_off(xbc_off), pad(pad), seq_major(seq_major) {}
double max_nmse_err() override {
// SSD path (head_dim > 1) uses FP16 intermediates (M matrix, X_dt); Mamba-1 is pure FP32.
return (head_dim > 1) ? 2e-7 : 1e-7;
}
int64_t n_slots() const {
return xbc_graph ? n_seqs + 2 : n_seqs;
}
ggml_tensor * build_graph(ggml_context * ctx) override {
ggml_tensor * s = ggml_new_tensor_4d(ctx, type, d_state, head_dim, n_head, n_seqs);
ggml_tensor * dt = ggml_new_tensor_3d(ctx, type, n_head, n_seq_tokens, n_seqs);
ggml_tensor * A = ggml_new_tensor_2d(ctx, type, (head_dim > 1) ? 1 : d_state, n_head);
const size_t f = ggml_type_size(type);
ggml_tensor * x;
ggml_tensor * B;
ggml_tensor * C;
if (xbc_overlap) {
if (xbc_graph) {
const int64_t d_inner = head_dim * n_head;
const int64_t row = xbc_off + d_inner + 2 * n_group * d_state + pad;
ggml_tensor * xbc = seq_major ? ggml_new_tensor_3d(ctx, type, row, n_seqs, n_seq_tokens)
: ggml_new_tensor_3d(ctx, type, row, n_seq_tokens, n_seqs);
const size_t nb_tok = seq_major ? xbc->nb[2] : xbc->nb[1];
const size_t nb_seq = seq_major ? xbc->nb[1] : xbc->nb[2];
x = ggml_view_4d(ctx, xbc, head_dim, n_head, n_seq_tokens, n_seqs, head_dim * f, nb_tok, nb_seq, xbc_off * f);
B = ggml_view_4d(ctx, xbc, d_state, n_group, n_seq_tokens, n_seqs, d_state * f, nb_tok, nb_seq, (xbc_off + d_inner) * f);
C = ggml_view_4d(ctx, xbc, d_state, n_group, n_seq_tokens, n_seqs, d_state * f, nb_tok, nb_seq, (xbc_off + d_inner + n_group * d_state) * f);
} else if (xbc_overlap) {
ggml_tensor * xbc = ggml_new_tensor_4d(ctx, type, d_state, n_head, n_seq_tokens, 2 * n_seqs);
x = ggml_view_4d(ctx, xbc, head_dim, n_head, n_seq_tokens, n_seqs,
xbc->nb[1], xbc->nb[2], xbc->nb[3], xbc->nb[3]);
@@ -5730,7 +5763,19 @@ struct test_ssm_scan : public test_case {
B = ggml_new_tensor_4d(ctx, type, d_state, n_group, n_seq_tokens, n_seqs);
C = ggml_new_tensor_4d(ctx, type, d_state, n_group, n_seq_tokens, n_seqs);
}
ggml_tensor * ids = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_seqs);
const int64_t A_ne0 = (head_dim > 1) ? 1 : d_state;
ggml_tensor * s_all = ggml_new_tensor_1d(ctx, type, off + d_state * head_dim * n_head * n_slots());
ggml_tensor * dt_all = ggml_new_tensor_1d(ctx, type, off + n_head * n_seq_tokens * n_seqs);
ggml_tensor * A_all = ggml_new_tensor_1d(ctx, type, off + A_ne0 * n_head);
ggml_tensor * ids_all = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, off + n_seqs);
ggml_set_name(A_all, "A");
ggml_tensor * s = ggml_view_4d(ctx, s_all, d_state, head_dim, n_head, n_slots(),
d_state * f, d_state * head_dim * f, d_state * head_dim * n_head * f, off * f);
ggml_tensor * dt = ggml_view_3d(ctx, dt_all, n_head, n_seq_tokens, n_seqs, n_head * f, n_head * n_seq_tokens * f, off * f);
ggml_tensor * A = ggml_view_2d(ctx, A_all, A_ne0, n_head, A_ne0 * f, off * f);
ggml_tensor * ids = ggml_view_1d(ctx, ids_all, n_seqs, off * sizeof(int32_t));
ggml_tensor * out = ggml_ssm_scan(ctx, s, x, dt, A, B, C, ids, K);
return out;
}
@@ -5740,21 +5785,23 @@ struct test_ssm_scan : public test_case {
std::random_device rd;
std::default_random_engine rng(rd());
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
if (t->type == GGML_TYPE_I32) {
if (ggml_is_view_op(t->op)) { continue; }
// ids: permutation of [0..n_seqs)
for (int64_t r = 0; r < ggml_nrows(t); r++) {
std::vector<int32_t> data(t->ne[0]);
for (int i = 0; i < t->ne[0]; i++) {
data[i] = i;
}
std::shuffle(data.begin(), data.end(), rng);
ggml_backend_tensor_set(t, data.data(), r * t->nb[1], t->ne[0] * sizeof(int32_t));
}
} else if (ggml_is_view_op(t->op)) {
if (ggml_is_view_op(t->op)) {
continue;
} else if (t->ne[1] == n_head && t->ne[2] == 1) {
// A {1 or d_state, n_head}: negative decay (2-D tensor, ne[2]==1 distinguishes from 3-D/4-D tensors)
}
if (t->type == GGML_TYPE_I32) {
// ids: distinct random state slots
std::vector<int32_t> slots(n_slots());
for (size_t i = 0; i < slots.size(); i++) {
slots[i] = (int32_t) i;
}
std::shuffle(slots.begin(), slots.end(), rng);
std::vector<int32_t> data(ggml_nelements(t), 0);
for (int64_t i = 0; i < n_seqs; i++) {
data[off + i] = slots[i];
}
ggml_backend_tensor_set(t, data.data(), 0, ggml_nbytes(t));
} else if (strcmp(t->name, "A") == 0) {
// negative decay
init_tensor_uniform(t, weak_decay ? -0.02f : -1.0f, weak_decay ? -0.005f : -0.5f);
} else {
init_tensor_uniform(t);
@@ -12359,13 +12406,24 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
}
for (int64_t T : { 1, 3 }) {
for (int64_t Q : { 1, 3, 4 }) {
for (int64_t B : { 1, 3, 12 }) {
for (int64_t B : { 1, 3, 12, 16 }) {
test_cases.emplace_back(new test_depth_mix(2304, B, Q, T));
}
}
test_cases.emplace_back(new test_depth_mix(2304, 5, 3, T, true));
test_cases.emplace_back(new test_depth_mix(100, 2, 2, T));
// around one block of elements, with and without n % 4 == 0
for (int64_t n : { 256, 257, 1001 }) {
test_cases.emplace_back(new test_depth_mix(n, 4, 1, T));
test_cases.emplace_back(new test_depth_mix(n, 4, 3, T));
}
}
test_cases.emplace_back(new test_depth_mix(2304, 4, 1, 1, true));
// rows of cur that are not 16 byte aligned
test_cases.emplace_back(new test_depth_mix(2304, 4, 1, 3, false, 1));
// rows of cur that are 16 byte apart but start 4 bytes off a 16 byte boundary: the scalar fallback on the base address
test_cases.emplace_back(new test_depth_mix(2304, 4, 1, 3, false, 4, 1));
test_cases.emplace_back(new test_depth_mix(2304, 4, 3, 3, false, 4, 1));
for (int64_t T : { 1, 4, 8 }) {
test_cases.emplace_back(new test_loop_ctrl(2304, 64, T));
}
@@ -13630,6 +13688,9 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_ssm_scan_rollback(GGML_TYPE_F32, 96, 64, 16, 8, 8, 2, /*K=*/3)); // d_state=96 rollback snapshots match prefix states
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 32, 4)); // Mamba-2
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 256, 64, 8, 2, 32, 4)); // Falcon-H1
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 8, 2)); // Mamba-2
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 31, 2)); // Mamba-2
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 256, 64, 8, 2, 9, 2)); // Falcon-H1
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 128, 4, 4, 16, 2, true)); // x/B/C overlap
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 80, 128, 1, 256, 1)); // Nemotron-9B SSD path
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 80, 128, 1, 512, 1)); // Nemotron-9B SSD multi-chunk (2 aligned chunks)
@@ -13641,6 +13702,25 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 65, 2)); // SSD one chunk + 1-token sequential tail
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 128, 2)); // SSD multi-chunk, no tail (exercises the chunk-to-chunk state handoff)
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 128, 2, false, /*K=*/1, /*weak_decay=*/true)); // SSD multi-chunk, carried state not numerically negligible
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 2048, 1)); // Mamba-2
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 256, 64, 8, 2, 300, 2)); // Falcon-H1
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 16, 16, 2, 64, 2)); // head_dim 16
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 48, 16, 2, 64, 2)); // head_dim 48
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 64, 16, 8, 16, 2)); // Nemotron-3-Puzzle
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 48, 16, 8, 16, 2)); // head_dim 48
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 48, 16, 8, 64, 2)); // head_dim 48
// Mamba-2 with the inputs laid out like the model graph, then with unaligned offsets and strides.
for (int64_t n_tok : {4, 16, 100}) {
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, n_tok, 2, false, 1, false, /*xbc_graph=*/true));
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, n_tok, 2, false, 1, false, true, /*off=*/1)); // s, dt, A and ids
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, n_tok, 2, false, 1, false, true, 0, /*xbc_off=*/1)); // x, B and C
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, n_tok, 2, false, 1, false, true, 0, 0, /*pad=*/1)); // token stride
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, n_tok, 3, false, 1, false, true, 0, 0, 0, /*seq_major=*/true));
}
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 256, 64, 8, 2, 40, 2, false, 1, false, true, 1)); // Falcon-H1
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 80, 8, 1, 40, 2, false, 1, false, true, 1, 4, 4)); // Nemotron-9B
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 64, 16, 8, 40, 2, false, 1, false, true, 1)); // Nemotron-3-Puzzle
// ssm_scan + cache cpy fusion
test_cases.emplace_back(new test_ssm_scan_cache_fusion(GGML_TYPE_F32, 128, 64, 16, 2, 4, 1, 4));
@@ -15937,6 +16017,10 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_perf() {
}
}
// small-ne0 non-contiguous shapes
test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {3, 8192, 4, 1}, 1, 0, 1));
test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {3, 8192, 1, 1}, 61, 0, 16));
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));
+2 -2
View File
@@ -3088,8 +3088,8 @@ static void test_string_parts(testing & t) {
});
t.test("custom mark bitfield", [](testing & t) {
constexpr uint32_t MARK_A = 1u << 1;
constexpr uint32_t MARK_B = 1u << 2;
static constexpr uint32_t MARK_A = 1u << 1;
static constexpr uint32_t MARK_B = 1u << 2;
static auto render_marked = [](const std::string & tmpl) -> jinja::string {
jinja::lexer lexer;
jinja::program ast = jinja::parse_from_tokens(lexer.tokenize(tmpl));
+1
View File
@@ -190,6 +190,7 @@ Get a list of tools, each tool has these fields:
- `tool` (string): the ID name of the tool, to be used in POST call. Example: `read_file`
- `display_name` (string): the name to be displayed on UI. Example: `Read file`
- `type` (string): `"server"` for a server tool, or `"mcp"` for a tool exposed by an MCP server
- `mcp_server` (string, only when `type` is `"mcp"`): the name of the MCP server the tool comes from, as declared in `--mcp-servers-config`. Example: `imcp`
- `permissions` (object): a mapping string --> boolean that indicates the permission required by this tool. This is useful for the UI to ask the user before calling the tool. For now, the only permission supported is `"write"`
- `definition` (object): the OAI-compat definition of this tool
+1 -1
View File
@@ -393,7 +393,7 @@ The same JSON can be passed inline with `--mcp-servers-json`. Each entry under `
| `cwd` | working directory of the child process |
| `timeout_ms` | per-tool-call timeout (default: 30000) |
Every server is spawned once at startup to list its tools, then stopped, and respawned on demand when one of its tools is called. Tools are exposed as `<server>_<tool>` alongside the built-in ones: they show up in Llama Chat and in `GET /tools`, and the model calls them like any other tool. A name colliding with an already registered tool is skipped. This is independent of `--tools`, MCP servers can be the only tools available.
Every server is spawned once at startup to list its tools, then stopped, and respawned on demand when one of its tools is called. Tools are exposed as `<server>_<tool>` alongside the built-in ones: they show up in Llama Chat, which lists each of these servers on its MCP servers page, and in `GET /tools`, with `"type": "mcp"` and the server's name in `mcp_server`. The model calls them like any other tool. A name colliding with an already registered tool is skipped. This is independent of `--tools`, MCP servers can be the only tools available.
The child process runs with the same privileges as the server, so only declare commands you trust. As with `--tools`, `--cors-origins` then defaults to `localhost`.
+16 -5
View File
@@ -437,13 +437,22 @@ bool server_http_context::init_listener(const common_params & params) {
);
return httplib::Server::HandlerResponse::Handled;
}
if (params.cors_credentials && params.cors_origins == "*") {
// special case: echo back the Origin header to allow any origin to access the server with credentials
res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
if (params.cors_origins == "*") {
// any origin: with credentials the header can't be "*", so the request's own origin is echoed back
res.set_header("Access-Control-Allow-Origin", params.cors_credentials ? req.get_header_value("Origin") : "*");
} else if (params.cors_origins == "localhost") {
// special case: same-origin only, no CORS header needed
} else {
res.set_header("Access-Control-Allow-Origin", params.cors_origins);
// a list of origins: the header takes one origin, never the list, so the request's
// own origin is echoed back when it is one of them, and left out otherwise
const std::string origin = req.get_header_value("Origin");
for (const auto & allowed : string_split<std::string>(params.cors_origins, ',')) {
if (!origin.empty() && string_strip(allowed) == origin) {
res.set_header("Access-Control-Allow-Origin", origin);
res.set_header("Vary", "Origin");
break;
}
}
}
// If this is OPTIONS request, skip validation because browsers don't include Authorization header
if (req.method == "OPTIONS") {
@@ -537,7 +546,9 @@ bool server_http_context::init_listener(const common_params & params) {
return false;
}
if (isolation) {
res.set_header("Cross-Origin-Embedder-Policy", "require-corp");
// credentialless, not require-corp: remote images such as MCP server icons
// load straight from their host, without credentials
res.set_header("Cross-Origin-Embedder-Policy", "credentialless");
res.set_header("Cross-Origin-Opener-Policy", "same-origin");
}
res.set_header("Cache-Control", cache_control);
+7
View File
@@ -2826,6 +2826,13 @@ struct server_mcp_tool : server_tool {
std::string type() const override { return "mcp"; }
// names the server, so a client can group its tools without splitting <server>_<tool>
json to_json() const override {
json res = server_tool::to_json();
res["mcp_server"] = server_name;
return res;
}
json get_definition() const override {
json schema = def.input_schema;
if (schema.is_null() || !schema.is_object()) {
+1 -1
View File
@@ -30,7 +30,7 @@ struct server_tool {
// should_stop: true once the caller stopped waiting, e.g. the client dropped the connection; a null should_stop means "never stop"
virtual json invoke(json params, stream * st = nullptr, const std::function<bool()> & should_stop = nullptr) const = 0;
json to_json() const;
virtual json to_json() const;
};
struct server_tools_runtime; // impl detail, defined in server-tools.cpp
@@ -77,6 +77,9 @@ def test_mcp_tools_listed_in_tools_endpoint():
# Verify tool structure
echo_tool = next(t for t in mcp_tools if get_tool_name(t) == "echo_echo")
assert "description" in echo_tool or "definition" in echo_tool
assert echo_tool["type"] == "mcp"
assert echo_tool["mcp_server"] == "echo"
assert all("mcp_server" not in t for t in tools if t["type"] != "mcp")
finally:
server.stop()
+17 -9
View File
@@ -87,15 +87,21 @@ def test_openai_library_correct_api_key():
assert len(res.choices) == 1
@pytest.mark.parametrize("origin,cors_header,cors_header_value", [
("localhost", "Access-Control-Allow-Origin", "localhost"),
("web.mydomain.fr", "Access-Control-Allow-Origin", "web.mydomain.fr"),
("origin", "Access-Control-Allow-Credentials", "true"),
("web.mydomain.fr", "Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS"),
("web.mydomain.fr", "Access-Control-Allow-Headers", "*"),
@pytest.mark.parametrize("cors_origins,cors_credentials,origin,cors_header,cors_header_value", [
(None, None, "localhost", "Access-Control-Allow-Origin", "localhost"),
(None, None, "web.mydomain.fr", "Access-Control-Allow-Origin", "web.mydomain.fr"),
(None, None, "origin", "Access-Control-Allow-Credentials", "true"),
(None, None, "web.mydomain.fr", "Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS"),
(None, None, "web.mydomain.fr", "Access-Control-Allow-Headers", "*"),
("*", False, "web.mydomain.fr", "Access-Control-Allow-Origin", "*"),
("https://a.example, https://b.example", None, "https://a.example", "Access-Control-Allow-Origin", "https://a.example"),
("https://a.example, https://b.example", None, "https://b.example", "Access-Control-Allow-Origin", "https://b.example"),
("https://a.example, https://b.example", None, "https://c.example", "Access-Control-Allow-Origin", None),
])
def test_cors_options(origin: str, cors_header: str, cors_header_value: str):
def test_cors_options(cors_origins: str | None, cors_credentials: bool | None, origin: str, cors_header: str, cors_header_value: str | None):
global server
server.cors_origins = cors_origins
server.cors_credentials = cors_credentials
server.start()
res = server.make_request("OPTIONS", "/completions", headers={
"Origin": origin,
@@ -103,8 +109,10 @@ def test_cors_options(origin: str, cors_header: str, cors_header_value: str):
"Access-Control-Request-Headers": "Authorization",
})
assert res.status_code == 200
assert cors_header in res.headers
assert res.headers[cors_header] == cors_header_value
if cors_header_value is None:
assert cors_header not in res.headers
else:
assert res.headers[cors_header] == cors_header_value
@pytest.mark.parametrize("origin", [
+3
View File
@@ -141,6 +141,7 @@ class ServerProcess:
mcp_servers_config: str | None = None
mcp_servers_json: str | None = None
cors_origins: str | None = None
cors_credentials: bool | None = None
llama_cache: str | None = None
share_console: bool = False # Windows: console control events only reach a server on the console of the tests
@@ -209,6 +210,8 @@ class ServerProcess:
server_args.extend(["--models-preset", self.models_preset])
if self.cors_origins:
server_args.extend(["--cors-origins", self.cors_origins])
if self.cors_credentials is not None:
server_args.append("--cors-credentials" if self.cors_credentials else "--no-cors-credentials")
if self.n_batch:
server_args.extend(["--batch-size", self.n_batch])
if self.n_ubatch:
+4
View File
@@ -114,6 +114,8 @@ colors:
action-primary-hover: 'color-mix(in oklch, {colors.action-primary} 90%, transparent)'
action-danger: '{colors.fill-danger}'
action-danger-hover: 'color-mix(in oklch, {colors.action-danger} 90%, transparent)'
action-danger-secondary: 'color-mix(in oklch, {colors.fill-danger} 8%, transparent)'
action-danger-secondary-hover: 'color-mix(in oklch, {colors.fill-danger} 16%, transparent)'
action-quiet: 'oklch(0.97 0 0 / 0.3)'
action-quiet-hover: '{colors.neutral-100}'
action-ghost-hover: 'oklch(0.556 0 0 / 0.1)'
@@ -165,6 +167,8 @@ colors:
action-primary-hover-dark: 'color-mix(in oklch, {colors.action-primary-dark} 90%, transparent)'
action-danger-dark: 'color-mix(in oklch, {colors.fill-danger-dark} 58%, transparent)'
action-danger-hover-dark: 'color-mix(in oklch, {colors.fill-danger-dark} 68%, transparent)'
action-danger-secondary-dark: 'color-mix(in oklch, {colors.fill-danger-dark} 12%, transparent)'
action-danger-secondary-hover-dark: 'color-mix(in oklch, {colors.fill-danger-dark} 22%, transparent)'
action-quiet-dark: 'oklch(0.708 0 0 / 0.15)'
action-quiet-hover-dark: 'oklch(0.708 0 0 / 0.25)'
action-ghost-hover-dark: 'oklch(0.708 0 0 / 0.1)'
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@ggml-org/llama-ui",
"version": "0.7.0",
"version": "0.7.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@ggml-org/llama-ui",
"version": "0.7.0",
"version": "0.7.1",
"license": "MIT",
"dependencies": {
"@ggml-org/llama-brand": "0.1.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ggml-org/llama-ui",
"version": "0.7.0",
"version": "0.7.1",
"description": "Shared UI library for llama.cpp frontend apps.",
"license": "MIT",
"repository": {
@@ -68,8 +68,8 @@
--switch-thumb-on: var(--surface-lifted);
/* badges: primary, danger and outline take semantic tokens as they are */
--badge-secondary-background: color-mix(in oklch, var(--fg-default) 15%, transparent);
--badge-secondary-background-hover: color-mix(in oklch, var(--fg-default) 25%, transparent);
--badge-secondary-background: color-mix(in oklch, var(--fg-default) 6%, transparent);
--badge-secondary-background-hover: color-mix(in oklch, var(--fg-default) 12%, transparent);
--badge-danger-background-hover: var(--action-danger-hover);
/* status lamps and orbs read the status tokens through orb-danger and friends */