From 1fa93f902d02cc6decaf771d9137cf4896b3db7e Mon Sep 17 00:00:00 2001 From: Piotr Wilkin Date: Sat, 21 Nov 2026 16:28:53 +0100 Subject: [PATCH 01/24] compact bias on the existing FLASH_ATTN_EXT for CUDA, ROCm and Vulkan Assisted-by: Codex --- ggml/include/ggml.h | 7 + ggml/src/ggml-backend.cpp | 5 + ggml/src/ggml-cuda/fattn-common.cuh | 27 ++-- ggml/src/ggml-cuda/fattn-mma-f16.cuh | 4 +- ggml/src/ggml-cuda/fattn-tile.cuh | 64 ++++++--- ggml/src/ggml-cuda/fattn-vec.cuh | 4 +- ggml/src/ggml-cuda/fattn.cu | 5 + ggml/src/ggml-cuda/ggml-cuda.cu | 3 + ggml/src/ggml-vulkan/ggml-vulkan.cpp | 69 ++++++--- .../vulkan-shaders/flash_attn.comp | 14 ++ .../vulkan-shaders/flash_attn_base.glsl | 13 ++ .../vulkan-shaders/vulkan-shaders-gen.cpp | 5 + ggml/src/ggml.c | 17 +++ src/llama-graph.cpp | 85 ++++++----- src/llama-graph.h | 11 +- src/llama-kv-cache.cpp | 12 +- src/llama-kv-cache.h | 4 +- src/models/inkling2.cpp | 14 +- src/models/models.h | 1 - tests/CMakeLists.txt | 1 + tests/test-flash-attn-indexed-bias.cpp | 132 ++++++++++++++++++ 21 files changed, 393 insertions(+), 104 deletions(-) create mode 100644 tests/test-flash-attn-indexed-bias.cpp diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 7c5b1e5528c0..9189ed0e41db 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -2283,6 +2283,13 @@ extern "C" { struct ggml_tensor * a, struct ggml_tensor * sinks); + // Add table[head, indices[key, query], query] to the mask before its F16 rounding. + // Queries from all streams are flattened in stream order. Indices must be in [0, table->ne[1]). + GGML_API void ggml_flash_attn_ext_add_indexed_bias( + struct ggml_tensor * a, + struct ggml_tensor * table, + struct ggml_tensor * indices); + // TODO: needs to be adapted to ggml_flash_attn_ext GGML_API struct ggml_tensor * ggml_flash_attn_back( struct ggml_context * ctx, diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp index d598ca3d86d1..6f5ba3b7e5da 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -1030,6 +1030,11 @@ ggml_backend_buffer_t ggml_backend_dev_buffer_from_host_ptr(ggml_backend_dev_t d bool ggml_backend_dev_supports_op(ggml_backend_dev_t device, const struct ggml_tensor * op) { GGML_ASSERT(device); + // Backends predating indexed bias would accept the ordinary FA op and ignore the extra inputs. + if (op->op == GGML_OP_FLASH_ATTN_EXT && op->src[6] && + !ggml_backend_reg_get_proc_address(device->reg, "ggml_backend_flash_attn_ext_indexed_bias")) { + return false; + } return device->iface.supports_op(device, op); } diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh index fc0cc7403910..5dac66f04892 100644 --- a/ggml/src/ggml-cuda/fattn-common.cuh +++ b/ggml/src/ggml-cuda/fattn-common.cuh @@ -18,6 +18,12 @@ // The macro on the following line shifts it by a factor of 2**3=8, as was needed to fix https://github.com/ggml-org/llama.cpp/issues/18606 . #define FATTN_KQ_MAX_OFFSET (3.0f*0.6931f) +struct fattn_indexed_bias { + const float * table; + const int32_t * indices; + int64_t n_bins; +}; + typedef void (* fattn_kernel_t)( const char * __restrict__ Q, const char * __restrict__ K, @@ -40,7 +46,8 @@ typedef void (* fattn_kernel_t)( const int32_t nb11, const int32_t nb12, const int64_t nb13, const int32_t nb21, const int32_t nb22, const int64_t nb23, const int32_t ne31, const int32_t ne32, const int32_t ne33, - const int32_t nb31, const int64_t nb32, const int64_t nb33); + const int32_t nb31, const int64_t nb32, const int64_t nb33, + const fattn_indexed_bias bias); typedef float (*vec_dot_KQ_t)( const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8 , const void * __restrict__ Q_ds); @@ -976,7 +983,7 @@ static __global__ void flash_attn_combine_results( const float * VKQ_parts_ptr, const float2 * VKQ_meta_ptr, float * dst_ptr, - const int parallel_blocks) { + const int parallel_blocks, const float * sinks) { ggml_cuda_pdl_lc(); const float * GGML_CUDA_RESTRICT VKQ_parts = VKQ_parts_ptr; const float2 * GGML_CUDA_RESTRICT VKQ_meta = VKQ_meta_ptr; @@ -1011,13 +1018,13 @@ static __global__ void flash_attn_combine_results( __syncthreads(); - float kqmax = meta[0].x; + float kqmax = sinks ? fmaxf(meta[0].x, sinks[head]) : meta[0].x; for (int l = 1; l < parallel_blocks; ++l) { kqmax = max(kqmax, meta[l].x); } float VKQ_numerator = 0.0f; - float VKQ_denominator = 0.0f; + float VKQ_denominator = sinks ? expf(sinks[head] - kqmax) : 0.0f; for (int l = 0; l < parallel_blocks; ++l) { const float KQ_max_scale = expf(meta[l].x - kqmax); @@ -1170,7 +1177,7 @@ void launch_fattn( // Optional optimization where the mask is scanned to determine whether part of the calculation can be skipped. // Only worth the overhead if there is at lease one FATTN_KQ_STRIDE x FATTN_KQ_STRIDE square to be skipped or // multiple sequences of possibly different lengths, or kv_rows lists that end with padding. - const bool scan_mask = !use_sparse && mask && mask->ne[2] == 1 && n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows); + const bool scan_mask = Q->ne[1] % ncols1 == 0 && !use_sparse && mask && mask->ne[2] == 1 && n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows); if (scan_mask) { const int64_t s31 = mask->nb[1] / sizeof(half2); const int64_t s33 = mask->nb[3] / sizeof(half2); @@ -1310,12 +1317,13 @@ void launch_fattn( GGML_ASSERT(block_dim.x % warp_size == 0); ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num, block_dim, nbytes_shared, main_stream); + const float * combine_sinks = dst->src[6] && sinks && !stream_k && parallel_blocks > 1 ? (const float *) sinks->data : nullptr; ggml_cuda_kernel_launch(fattn_kernel, launch_params, (const char *) Q->data, K_data, V_data, mask ? ((const char *) mask->data) : nullptr, - sinks ? ((const char *) sinks->data) : nullptr, + sinks && !combine_sinks ? (const char *) sinks->data : nullptr, KV_max.ptr, kv_rows ? (const int *) kv_rows->data : nullptr, !stream_k && parallel_blocks > 1 ? dst_tmp.ptr : (float *) KQV->data, dst_tmp_meta.ptr, @@ -1324,7 +1332,10 @@ void launch_fattn( K->ne[0], n_kv, K->ne[2], K->ne[3], nb11, nb12, nb13, nb21, nb22, nb23, mask ? mask->ne[1] : 0, mask ? mask->ne[2] : 0, mask ? mask->ne[3] : 0, - mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0 + mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0, + fattn_indexed_bias{dst->src[6] ? (const float *) dst->src[6]->data : nullptr, + dst->src[7] ? (const int32_t *) dst->src[7]->data : nullptr, + dst->src[6] ? dst->src[6]->ne[1] : 0} ); CUDA_CHECK(cudaGetLastError()); @@ -1371,7 +1382,7 @@ void launch_fattn( const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num_combine, block_dim_combine, nbytes_shared_combine, main_stream); ggml_cuda_kernel_launch(flash_attn_combine_results, launch_params, - dst_tmp.ptr, dst_tmp_meta.ptr, (float *) KQV->data, parallel_blocks); + dst_tmp.ptr, dst_tmp_meta.ptr, (float *) KQV->data, parallel_blocks, combine_sinks); } CUDA_CHECK(cudaGetLastError()); } diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh index dea8d2ad35ec..641cfa3de538 100644 --- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh +++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh @@ -1960,7 +1960,9 @@ static __global__ void flash_attn_ext_f16( const int32_t nb11, const int32_t nb12, const int64_t nb13, const int32_t nb21, const int32_t nb22, const int64_t nb23, const int32_t ne31, const int32_t ne32, const int32_t ne33, - const int32_t nb31, const int64_t nb32, const int64_t nb33) { + const int32_t nb31, const int64_t nb32, const int64_t nb33, + const fattn_indexed_bias bias) { + GGML_UNUSED(bias); ggml_cuda_pdl_sync(); // TODO optimize placement #if defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE)) const char * GGML_CUDA_RESTRICT Q = Q_ptr; diff --git a/ggml/src/ggml-cuda/fattn-tile.cuh b/ggml/src/ggml-cuda/fattn-tile.cuh index 177b2f0653bf..4e0cb52f2511 100644 --- a/ggml/src/ggml-cuda/fattn-tile.cuh +++ b/ggml/src/ggml-cuda/fattn-tile.cuh @@ -376,7 +376,7 @@ static constexpr __device__ int ggml_cuda_fattn_tile_get_nbatch_K(const int DKQ, // TODO: deduplicate with mma-f16 template static __device__ __forceinline__ void flash_attn_tile_load_tile( - const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int stride_KV, const int i_sup) { + const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int stride_KV, const int i_sup, const int first, const int * rows) { constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); constexpr int cpy_ne = cpy_nb / 4; @@ -400,6 +400,7 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( const int i = i0 + threadIdx.y*stride_i + (stride_j == warp_size ? 0 : threadIdx.x / stride_j); if (i0 + nwarps*stride_i <= I || i < I) { + const int row = (oob_check && i >= i_sup) ? -1 : (rows ? rows[first + i] : first + i); #pragma unroll for (int j0 = j0_start; j0 < j0_stop; j0 += stride_j) { const int j = j0*cpy_ne + (stride_j == warp_size ? threadIdx.x : threadIdx.x % stride_j)*cpy_ne; @@ -407,7 +408,7 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( const __align__(16) half2 zero[cpy_ne] = {{0.0f, 0.0f}}; ggml_cuda_memcpy_1( tile_KV + i*(J/2 + J_padding) + j, - !oob_check || i < i_sup ? KV + i*stride_KV + j : zero); + row >= 0 ? KV + (int64_t) row*stride_KV + j : zero); } } } @@ -426,7 +427,7 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( template static __device__ __forceinline__ void flash_attn_tile_load_tile( - const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int stride_KV, const int i_sup) { + const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int stride_KV, const int i_sup, const int first, const int * rows) { constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); constexpr int cpy_ne = cpy_nb / 4; @@ -450,6 +451,7 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( const int i = i0 + threadIdx.y*stride_i + (stride_j == warp_size ? 0 : threadIdx.x / stride_j); if (i0 + nwarps*stride_i <= I || i < I) { + const int row = (oob_check && i >= i_sup) ? -1 : (rows ? rows[first + i] : first + i); #pragma unroll for (int j0 = j0_start; j0 < j0_stop; j0 += stride_j) { const int j = j0*(cpy_ne/2) + (stride_j == warp_size ? threadIdx.x : threadIdx.x % stride_j)*(cpy_ne/2); @@ -457,7 +459,7 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( const half2 zero[cpy_ne/2] = {{0.0f, 0.0f}}; __align__(16) half2 tmp_h2[cpy_ne/2]; ggml_cuda_memcpy_1( - tmp_h2, !oob_check || i < i_sup ? KV + i*stride_KV + j : zero); + tmp_h2, row >= 0 ? KV + (int64_t) row*stride_KV + j : zero); __align__(16) float2 tmp_f2[cpy_ne/2]; #pragma unroll @@ -490,7 +492,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ( const int k_VKQ_0, const int k_VKQ_sup, const int k_KQ_0, - float * KQ_acc) { + float * KQ_acc, const int * rows) { constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); constexpr int cpy_ne = cpy_nb / 4; @@ -499,7 +501,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ( constexpr int np = nwarps > ncols ? nwarps/ncols : 1; // number of parallel warps per Q column flash_attn_tile_load_tile - (K_h2 + int64_t(k_VKQ_0)*stride_K2 + k_KQ_0/2, KV_tmp, stride_K2, k_VKQ_sup); + (K_h2 + k_KQ_0/2, KV_tmp, stride_K2, k_VKQ_sup, k_VKQ_0, rows); __syncthreads(); #ifdef FAST_FP16_AVAILABLE @@ -575,7 +577,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter( T_acc * const VKQ, const int k_VKQ_0, const int k_VKQ_max, - const int col_Q_0) { + const int col_Q_0, + const fattn_indexed_bias bias, const int head, const int n_heads, const int sequence, const int * rows) { constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); constexpr int cpy_ne = cpy_nb / 4; @@ -608,12 +611,12 @@ static __device__ __forceinline__ void flash_attn_tile_iter( #pragma unroll for (int k_KQ_0 = 0; k_KQ_0 < DKQ - nbatch_K_last; k_KQ_0 += nbatch_K) { flash_attn_tile_iter_KQ( - Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc); + Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc, rows); } if (nbatch_K_last > 0) { constexpr int k_KQ_0 = DKQ - nbatch_K_last; flash_attn_tile_iter_KQ( - Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc); + Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc, rows); } // Apply logit softcap + mask, update KQ_max: @@ -636,8 +639,18 @@ static __device__ __forceinline__ void flash_attn_tile_iter( } if (!oob_check || i_KQ < k_VKQ_sup) { - KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] += (ncols2 > 1 || mask) ? - slope*__half2float(mask[j*stride_mask + k_VKQ_0 + i_KQ]) : 0.0f; + const int k = k_VKQ_0 + i_KQ; + float m = (ncols2 > 1 || mask) ? __half2float(mask[(int64_t) j*stride_mask + k]) : 0.0f; + if constexpr (ncols2 == 1 && (DKQ == 64 || DKQ == 128)) { + if (bias.table) { + const int64_t query = (int64_t) sequence*ne01.z + j; + const int bin = bias.indices[query*stride_mask + k]; + if ((uint32_t) bin < bias.n_bins) { + m = __half2float(__float2half(m + bias.table[(query*bias.n_bins + bin)*n_heads + head])); + } + } + } + KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] += slope*m; KQ_max_new[jc0] = fmaxf(KQ_max_new[jc0], KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] + FATTN_KQ_MAX_OFFSET); } @@ -719,7 +732,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter( #pragma unroll for (int k0 = 0; k0 < nbatch_fa; k0 += nbatch_V) { flash_attn_tile_load_tile - (V_h2 + int64_t(k_VKQ_0 + k0)*stride_V2, KV_tmp, stride_V2, k_VKQ_sup - k0); + (V_h2, KV_tmp, stride_V2, k_VKQ_sup - k0, k_VKQ_0 + k0, rows); __syncthreads(); #ifdef FAST_FP16_AVAILABLE @@ -812,7 +825,8 @@ static __global__ void flash_attn_tile( const int32_t nb11, const int32_t nb12, const int64_t nb13, const int32_t nb21, const int32_t nb22, const int64_t nb23, const int32_t ne31, const int32_t ne32, const int32_t ne33, - const int32_t nb31, const int64_t nb32, const int64_t nb33) { + const int32_t nb31, const int64_t nb32, const int64_t nb33, + const fattn_indexed_bias bias) { #ifdef FLASH_ATTN_AVAILABLE const char * GGML_CUDA_RESTRICT Q = Q_ptr; const char * GGML_CUDA_RESTRICT K = K_ptr; @@ -822,7 +836,6 @@ static __global__ void flash_attn_tile( const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; float * GGML_CUDA_RESTRICT dst = dst_ptr; float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; - GGML_UNUSED(KV_rows_ptr); // Skip unused kernel variants for faster compilation: @@ -853,6 +866,7 @@ static __global__ void flash_attn_tile( const int col_Q_0 = blockIdx.x * ncols1; // Index of the first Q column for this CUDA block to work on. const int sequence = blockIdx.z / (ne02/ncols2); + const int * rows = KV_rows_ptr ? KV_rows_ptr + (int64_t) sequence*ne11 : nullptr; const int head0 = blockIdx.z*ncols2 - sequence*ne02; // == blockIdx.z % (ne02/ncols2) const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix. const float * Q_f = (const float *) (Q + nb03*sequence + nb02* head0); @@ -961,14 +975,14 @@ static __global__ void flash_attn_tile( constexpr bool oob_check = false; flash_attn_tile_iter (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, - stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0); + stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, bias, head0, ne02, sequence, rows); k_VKQ_0 += gridDim.y*nbatch_fa; } if (k_VKQ_0 < k_VKQ_max) { constexpr bool oob_check = true; flash_attn_tile_iter (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, - stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0); + stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, bias, head0, ne02, sequence, rows); } } else { // Branch without out-of-bounds checks. @@ -976,7 +990,7 @@ static __global__ void flash_attn_tile( constexpr bool oob_check = false; flash_attn_tile_iter (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, - stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0); + stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, bias, head0, ne02, sequence, rows); } } @@ -1052,7 +1066,7 @@ static __global__ void flash_attn_tile( } // Attention sink: adjust KQ max and sum only for the first of all parallel blocks: - if (sinks && blockIdx.y == 0) { + if (sinks && !bias.table && blockIdx.y == 0) { #pragma unroll for (int jc0 = 0; jc0 < cpw; ++jc0) { const int jc = jc0 + (threadIdx.y/np)*cpw; @@ -1093,7 +1107,17 @@ static __global__ void flash_attn_tile( return; } - const float scale = gridDim.y == 1 ? 1.0f/KQ_sum[jc0] : 1.0f; + float scale = 1.0f; + if (gridDim.y == 1) { + if (bias.table && sinks) { + const float sink = ((const float *) sinks)[head0 + c]; + const float kq_max = fmaxf(KQ_max[jc0], sink); + const float kq_scale = expf(KQ_max[jc0] - kq_max); + scale = kq_scale/(KQ_sum[jc0]*kq_scale + expf(sink - kq_max)); + } else { + scale = 1.0f/KQ_sum[jc0]; + } + } const int j_dst_unrolled = ((sequence*int(ne01.z) + col_Q_0 + j)*ne02 + head0 + c)*gridDim.y + blockIdx.y; @@ -1253,7 +1277,7 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm const bool nvidia = GGML_CUDA_CC_IS_NVIDIA(ggml_cuda_info().devices[ggml_cuda_get_device()].cc); const int gqa_limit = nvidia && gqa_ratio <= 4 && DV <= 256 ? 16 : INT_MAX; // a mask with a head dimension is not shared by the Q heads of a K/V head - const bool use_gqa_opt = mask && mask->ne[2] == 1 && max_bias == 0.0f && Q->ne[1] <= gqa_limit && K->ne[1] % FATTN_KQ_STRIDE == 0; + const bool use_gqa_opt = !dst->src[6] && mask && mask->ne[2] == 1 && max_bias == 0.0f && Q->ne[1] <= gqa_limit && K->ne[1] % FATTN_KQ_STRIDE == 0; if constexpr (DKQ == 320) { // This branch is only used for Mistral Small 4 which has a GQA ratio of 32. diff --git a/ggml/src/ggml-cuda/fattn-vec.cuh b/ggml/src/ggml-cuda/fattn-vec.cuh index 09a46187d105..88c0b32ad9d1 100644 --- a/ggml/src/ggml-cuda/fattn-vec.cuh +++ b/ggml/src/ggml-cuda/fattn-vec.cuh @@ -40,7 +40,9 @@ static __global__ void flash_attn_ext_vec( const int32_t nb11, const int32_t nb12, const int64_t nb13, const int32_t nb21, const int32_t nb22, const int64_t nb23, const int32_t ne31, const int32_t ne32, const int32_t ne33, - const int32_t nb31, const int64_t nb32, const int64_t nb33) { + const int32_t nb31, const int64_t nb32, const int64_t nb33, + const fattn_indexed_bias bias) { + GGML_UNUSED(bias); ggml_cuda_pdl_lc(); #ifdef FLASH_ATTN_AVAILABLE const char * GGML_CUDA_RESTRICT Q = Q_ptr; diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 10aa5af15863..f63cde69569e 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -669,6 +669,11 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const return BEST_FATTN_KERNEL_NONE; } + if (dst->src[6]) { + const float softcap = ggml_get_op_params_f32(dst, 2); + return (Q->ne[0] == 128 || (Q->ne[0] == 64 && softcap == 0.0f)) ? BEST_FATTN_KERNEL_TILE : BEST_FATTN_KERNEL_NONE; + } + if (mask && mask->ne[2] != 1) { // the kv_rows mask is compacted per sequence, it has no head dimension if (kv_rows) { diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 3e1f167e9936..f0d226f17ceb 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -7004,6 +7004,9 @@ static ggml_backend_feature * ggml_backend_cuda_get_features(ggml_backend_reg_t } static void * ggml_backend_cuda_reg_get_proc_address(ggml_backend_reg_t reg, const char * name) { + if (strcmp(name, "ggml_backend_flash_attn_ext_indexed_bias") == 0) { + return (void *) ggml_backend_cuda_device_supports_op; + } GGML_UNUSED(reg); if (strcmp(name, "ggml_backend_comm_init") == 0) { return (void *)ggml_backend_cuda_comm_init; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index ae5a05c72e38..6bab65cff5e5 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -2333,7 +2333,12 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { const void * spv_data = nullptr; size_t spv_size = 0; const char *name = nullptr; - if (bf16_kv) { + const bool kv_rows = (fa.first.flags & (1u << 31)) != 0; + if (kv_rows) { + spv_data = device->fp16 ? flash_attn_f32_f16_rows_data : flash_attn_f32_f16_rows_fp32_data; + spv_size = device->fp16 ? flash_attn_f32_f16_rows_len : flash_attn_f32_f16_rows_fp32_len; + name = "flash_attn_f32_f16_rows"; + } else if (bf16_kv) { spv_data = flash_attn_f32_f16_fp32_data; spv_size = flash_attn_f32_f16_fp32_len; name = aligned ? "flash_attn_f32_bf16_aligned" : "flash_attn_f32_bf16"; @@ -2363,7 +2368,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { } name = aligned ? "flash_attn_f32_f16_aligned" : "flash_attn_f32_f16"; } - ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 8, + ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", kv_rows ? 9 : 8, sizeof(vk_flash_attn_push_constants), {Br, 1, 1}, get_fa_spec_constants(fa.first), aligned ? Bc : 1, true, !fa_ds, !fa_ds ? fa_sgs : 0); @@ -9025,10 +9030,12 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const const uint32_t nem2 = mask ? mask->ne[2] : 0; const uint32_t nem3 = mask ? mask->ne[3] : 0; + const ggml_tensor * bias = dst->src[6]; const uint32_t HSK = nek0; const uint32_t HSV = nev0; uint32_t N = neq1; - const uint32_t KV = nek1; + const ggml_tensor * rows = dst->src[5]; + const uint32_t KV = rows ? rows->ne[0] : nek1; GGML_ASSERT(ne0 == HSV); GGML_ASSERT(ne2 == N); @@ -9085,7 +9092,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const const uint32_t cm2_min_reuse = KV >= 8192 ? 4096 : 8192; // Query reuse must cover the conversion and synchronization cost. const bool cm2_dequant_kv = KV >= 4096 && neq1 >= cm2_min_queries && (uint64_t) neq1 * qk_ratio >= cm2_min_reuse; - const bool use_dequant_kv = ((k_quant && v_quant) || kv_raw_strided) && neq1 >= 64 && + const bool use_dequant_kv = !rows && ((k_quant && v_quant) || kv_raw_strided) && neq1 >= 64 && is_dense_kv_cache(k) && is_dense_kv_cache(v) && (uint64_t)ggml_nelements(k) * kv_scratch_ts <= ctx->device->properties.limits.maxStorageBufferRange && (uint64_t)ggml_nelements(v) * kv_scratch_ts <= ctx->device->properties.limits.maxStorageBufferRange && @@ -9105,7 +9112,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const vk_fa_tuning_params tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, 32, KV, k_type_eff, v_type_eff, f32acc, qk_ratio); const uint32_t max_gqa = std::min(tuning_params.block_rows, 32u); - if (N <= 8 && qk_ratio > 1 && qk_ratio <= max_gqa && + if (!bias && N <= 8 && qk_ratio > 1 && qk_ratio <= max_gqa && qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) { // grouped query attention - make the N dimension equal to gqa_ratio, reduce // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1 @@ -9115,7 +9122,8 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const workgroups_y /= gqa_ratio; } - tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, N, KV, k_type_eff, v_type_eff, f32acc, qk_ratio); + tuning_params = bias ? get_fa_tuning_params_scalar(ctx->device, HSK, HSV, N, KV, k_type_eff, v_type_eff, f32acc) + : get_fa_tuning_params(ctx->device, HSK, HSV, N, KV, k_type_eff, v_type_eff, f32acc, qk_ratio); float scale = 1.0f; float max_bias = 0.0f; @@ -9141,7 +9149,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const return (t->type != GGML_TYPE_F16 && t->type != GGML_TYPE_BF16) || (t->nb[1] | t->nb[2] | t->nb[3]) % (4 * sizeof(ggml_fp16_t)) == 0; }; - const bool use_sparse = !disable_sparse && n_kv_max > 0 && mask && + const bool use_sparse = !bias && !disable_sparse && n_kv_max > 0 && mask && max_bias == 0.0f && logit_softcap == 0.0f && (tuning_params.path != FA_COOPMAT2 || (sparse_gather_aligned(k) && sparse_gather_aligned(v))) && nem0 == KV && @@ -9200,11 +9208,18 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const } // Only use mask opt when the mask is fairly large. This hasn't been tuned extensively. - bool use_mask_opt = mask && !use_sparse && nem1 >= 32 && nem0 * nem1 > 32768 && nem0 >= tuning_params.block_cols * 16 + bool use_mask_opt = !bias && mask && !use_sparse && nem1 >= 32 && nem0 * nem1 > 32768 && nem0 >= tuning_params.block_cols * 16 && (ctx->device->architecture != vk_device_architecture::AMD_GCN || HSK > 256 || HSV > 256); vk_fa_pipeline_state fa_pipeline_state = get_fa_pipeline_state(ctx->device, tuning_params, HSK, HSV, aligned, f32acc, mask != nullptr, use_mask_opt, logit_softcap != 0, use_sparse, k_type_eff, v_type_eff); + if (bias) { + // Bind the table and indices in the two unused mask optimization slots. + fa_pipeline_state.flags |= (uint32_t) bias->ne[1] << 8; + if (rows) { + fa_pipeline_state.flags |= 1u << 31; + } + } vk_pipeline pipeline = nullptr; auto tensor_aligned_with = [&](const ggml_tensor * t, uint32_t in) { @@ -9219,7 +9234,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const tensor_aligned_with(k, 16u) && tensor_aligned_with(v, 16u); bool xe_fa_supported_dtype = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16 && mask != nullptr && mask->type == GGML_TYPE_F16; - xe_fa_opt = xe_fa_supported_platform && xe_fa_supported_usage && xe_fa_supported_dtype; + xe_fa_opt = !bias && xe_fa_supported_platform && xe_fa_supported_usage && xe_fa_supported_dtype; std::pair xe_fa_pipeline_dual_phases = { nullptr , nullptr }; vk_pipeline xe_fa_pipeline = nullptr; size_t size_q_staging = 0; @@ -9433,6 +9448,10 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const vk_subbuffer sinks_buf = sinks ? ggml_vk_tensor_subbuffer(ctx, sinks) : q_buf; vk_subbuffer mask_opt_buf = use_mask_opt ? ggml_vk_subbuffer(ctx, ctx->prealloc_y, 0) : q_buf; vk_subbuffer sparse_buf = use_sparse ? ggml_vk_subbuffer(ctx, ctx->prealloc_y, 0) : q_buf; + if (bias) { + mask_opt_buf = ggml_vk_tensor_subbuffer(ctx, bias); + sparse_buf = ggml_vk_tensor_subbuffer(ctx, dst->src[7]); + } if (use_mask_opt || use_sparse) { // the mask opt bits and the sparse index list overwrite a matmul input converted into prealloc_y ctx->prealloc_y_last_pipeline_used = nullptr; @@ -9548,6 +9567,16 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const mask_n_head_log2, m0, m1, gqa_ratio, split_kv, split_k }; + auto dispatch_fa = [&](const vk_subbuffer & out, std::array groups) { + if (rows) { + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + {q_buf, k_buf, v_buf, mask_buf, sinks_buf, out, mask_opt_buf, sparse_buf, ggml_vk_tensor_subbuffer(ctx, rows)}, pc, groups); + } else { + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + {q_buf, k_buf, v_buf, mask_buf, sinks_buf, out, mask_opt_buf, sparse_buf}, pc, groups); + } + }; + if (xe_fa_opt) { uint32_t head_stride_q = uint32_t(nbq2 / ggml_type_size(q->type)); uint32_t head_stride_k = uint32_t(nbk2 / ggml_type_size(k->type)); @@ -9619,9 +9648,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const } vk_subbuffer split_k_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0); - ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, - {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf, mask_opt_buf, sparse_buf}, - pc, { dispatch_x, workgroups_y, workgroups_z }); + dispatch_fa(split_k_buf, { dispatch_x, workgroups_y, workgroups_z }); ggml_vk_sync_buffers(ctx, subctx); const vk_op_flash_attn_split_k_reduce_push_constants pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3, split_k, (sinks != nullptr) }; @@ -9634,9 +9661,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const // When using gqa, we want one actual workgroup per batch, so cancel out wg_denoms workgroups_x *= pipeline->wg_denoms[0]; } - ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, - {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf, mask_opt_buf, sparse_buf}, - pc, { workgroups_x, workgroups_y, workgroups_z }); + dispatch_fa(dst_buf, { workgroups_x, workgroups_y, workgroups_z }); } if (use_dequant_kv) { @@ -16772,8 +16797,15 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm } case GGML_OP_FLASH_ATTN_EXT: { - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - if (op->src[5] != nullptr) { + // Only the indexed-bias scalar kernel reads row lists. + if (op->src[5] && (!op->src[6] || device->properties.limits.maxPerStageDescriptorStorageBuffers < 9 || + device->properties.limits.maxDescriptorSetStorageBuffers < 9)) { + return false; + } + if (op->src[6] && (op->src[6]->ne[1] > 0x7fffff || !device->subgroup_shuffle || !device->subgroup_vote || + ggml_nelements(op->src[6]) > UINT32_MAX || ggml_nelements(op->src[7]) > UINT32_MAX || + op->src[1]->type != GGML_TYPE_F16 || op->src[2]->type != GGML_TYPE_F16 || + (op->src[1]->ne[0] != 64 && op->src[1]->ne[0] != 128) || op->src[1]->ne[0] != op->src[2]->ne[0])) { return false; } bool coopmat2 = device->coopmat2; @@ -17478,6 +17510,9 @@ static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, } static void * ggml_backend_vk_reg_get_proc_address(ggml_backend_reg_t reg, const char * name) { + if (strcmp(name, "ggml_backend_flash_attn_ext_indexed_bias") == 0) { + return (void *) ggml_backend_vk_device_supports_op; + } UNUSED(reg); #if !defined(_WIN32) if (strcmp(name, "ggml_backend_comm_init") == 0) { diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp index c1e4606cd916..ef69134c8616 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp @@ -212,9 +212,23 @@ void main() { uint32_t r = (idx + tid) / Bc; if (idx + tid < Bc * Br) { uint32_t kcol; +#ifdef KV_ROWS + kcol = j * Bc + c; + bool kv_active = kcol < KV; +#else bool kv_active = fa_kv_index(j * Bc + c, kcol); +#endif if (kv_active && (!nem1_bounds_check || i * Br + r < p.nem1)) { FLOAT_TYPE m = FLOAT_TYPE(data_m[m_offset + (i * Br + r) * m_stride + kcol]); + const uint n_bins = (Flags & 0x7fffffffu) >> 8; + if (n_bins != 0) { + uint query = iq3 * p.N + i * Br + r; + uint bin = uint(data_sparse[query * KV + kcol]); + if (bin < n_bins) { + float bias = uintBitsToFloat(data_mask_opt[(query * n_bins + bin) * p.neq2 + iq2]); + m = FLOAT_TYPE(unpackHalf2x16(packHalf2x16(vec2(float(m) + bias, 0))).x); + } + } masksh[c * masksh_stride + r] = m; max_mask = max(max_mask, float(m)); } else { diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl index 072edfa68cc7..b6941af8be74 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl @@ -88,6 +88,10 @@ layout (binding = 5) writeonly buffer OV4 {D_TYPEV4 data_ov4[];}; layout (binding = 6) readonly buffer MO {uint32_t data_mask_opt[];}; +#ifdef KV_ROWS +layout (binding = 8) readonly buffer KR {int32_t data_kv_rows[];}; +#endif + layout (binding = 7) readonly buffer SP {int32_t data_sparse[];}; // Use -FLT_MAX/2 rather than -inf to reduce the possibility of NaNs, e.g. when computing Mold-M. @@ -237,6 +241,15 @@ void init_indices() // Resolve a linear KV slot to a real column; false for inactive (sparse padding/-1, or dense OOB). bool fa_kv_index(uint lin, out uint kv_col) { +#ifdef KV_ROWS + if (lin >= KV) { + kv_col = 0; + return false; + } + int row = data_kv_rows[iq3 * KV + lin]; + kv_col = uint(max(row, 0)); + return row >= 0; +#endif if (USE_SPARSE) { if (lin >= p.split_kv) { kv_col = 0; diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp index e20c94758900..718e4e849184 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp @@ -749,6 +749,11 @@ void process_shaders() { #endif } + if (!f16acc) { + string_to_spv("flash_attn_f32_f16_rows", "flash_attn.comp", + merge_maps(fa_base_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}, {"KV_ROWS", "1"}}), fp16, false, false, false); + } + string_to_spv("flash_attn_f32_f16", "flash_attn.comp", merge_maps(fa_base_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}}), fp16, false, false, f16acc); diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index b47c5addf6c5..9da7699b4859 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -5526,6 +5526,23 @@ void ggml_flash_attn_ext_add_sinks( a->src[4] = sinks; } +void ggml_flash_attn_ext_add_indexed_bias( + struct ggml_tensor * a, + struct ggml_tensor * table, + struct ggml_tensor * indices) { + GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT); + const struct ggml_tensor * q = a->src[0]; + const struct ggml_tensor * mask = a->src[3]; + GGML_ASSERT(mask && mask->ne[0] == (a->src[5] ? a->src[5]->ne[0] : a->src[1]->ne[1]) && mask->ne[1] == q->ne[1]); + GGML_ASSERT(mask->ne[2] == 1 && mask->ne[3] == q->ne[3]); + GGML_ASSERT(table->type == GGML_TYPE_F32 && ggml_is_contiguous(table)); + GGML_ASSERT(table->ne[0] == q->ne[2] && table->ne[1] > 0 && table->ne[2] == q->ne[1]*q->ne[3] && table->ne[3] == 1); + GGML_ASSERT(indices->type == GGML_TYPE_I32 && ggml_is_contiguous(indices) && ggml_is_matrix(indices)); + GGML_ASSERT(indices->ne[0] == mask->ne[0] && indices->ne[1] == table->ne[2]); + a->src[6] = table; + a->src[7] = indices; +} + // ggml_flash_attn_back struct ggml_tensor * ggml_flash_attn_back( diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index c5c9ddf014b9..07ba2c855cad 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1415,7 +1415,7 @@ void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch) } if (self_rel_pos->buffer) { - attn_ctx->get_base()->set_input_relative_pos(self_rel_pos, ubatch, extent); + attn_ctx->get_base()->set_input_relative_pos(self_rel_pos, inp_attn->self_attn_mask.rows, ubatch, extent); } // swa tensors may not be allocated if there are no SWA attention layers @@ -1429,7 +1429,7 @@ void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch) } if (self_rel_pos_swa->buffer) { - attn_ctx->get_swa()->set_input_relative_pos(self_rel_pos_swa, ubatch, extent_swa); + attn_ctx->get_swa()->set_input_relative_pos(self_rel_pos_swa, inp_attn->self_attn_mask_swa.rows, ubatch, extent_swa); } const int64_t n_rs = mctx->get_recr()->get_n_rs(); @@ -1454,16 +1454,13 @@ bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & par const auto * attn_ctx = mctx->get_attn(); - // the masks are always dense, see build_inp_mem_hybrid_iswa_rel() - // base tensors may not be allocated if there are no non-SWA attention layers if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; } - res &= can_reuse_kq_mask(inp_attn->self_attn_mask.raw, attn_ctx->get_base(), params.ubatch, params.cparams); + res &= can_reuse_attn_mask(inp_attn->self_attn_mask, attn_ctx->get_base(), params.ubatch, params.cparams); - res &= self_rel_pos->ne[0] == attn_ctx->get_base()->get_n_kv(); res &= self_rel_pos->ne[1] == params.ubatch.n_tokens; // swa tensors may not be allocated if there are no SWA attention layers @@ -1471,9 +1468,8 @@ bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & par res &= inp_attn->self_k_idxs_swa->ne[0] == params.ubatch.n_tokens; } - res &= can_reuse_kq_mask(inp_attn->self_attn_mask_swa.raw, attn_ctx->get_swa(), params.ubatch, params.cparams); + res &= can_reuse_attn_mask(inp_attn->self_attn_mask_swa, attn_ctx->get_swa(), params.ubatch, params.cparams); - res &= self_rel_pos_swa->ne[0] == attn_ctx->get_swa()->get_n_kv(); res &= self_rel_pos_swa->ne[1] == params.ubatch.n_tokens; res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); @@ -3182,7 +3178,9 @@ ggml_tensor * llm_graph_context::build_attn_mha( ggml_tensor * v_mla, int64_t n_kv_max, float kq_scale, - int il) const { + int il, + ggml_tensor * bias_table, + ggml_tensor * bias_indices) const { const bool v_trans = v->nb[1] > v->nb[2]; // split the batch into streams if needed @@ -3197,6 +3195,20 @@ ggml_tensor * llm_graph_context::build_attn_mha( k = ggml_permute(ctx0, k, 0, 2, 1, 3); v = ggml_permute(ctx0, v, 0, 2, 1, 3); + auto dense_bias_mask = [&]() { + ggml_tensor * bias = ggml_get_rows(ctx0, bias_table, bias_indices); + bias = ggml_reshape_4d(ctx0, bias, q->ne[2], bias_indices->ne[0], q->ne[1], n_stream); + bias = ggml_cont(ctx0, ggml_permute(ctx0, bias, 2, 0, 1, 3)); + cb(bias, "kq_b", il); + ggml_tensor * mask = kq_mask->type == GGML_TYPE_F32 ? kq_mask : ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); + mask = ggml_add(ctx0, bias, mask); + if (cparams.flash_attn) { + mask = ggml_cast(ctx0, mask, GGML_TYPE_F16); + } + cb(mask, "kq_mask_rel_pos", il); + return mask; + }; + ggml_tensor * cur; const bool use_flash_attn = cparams.flash_attn && kq_b == nullptr; @@ -3230,6 +3242,23 @@ ggml_tensor * llm_graph_context::build_attn_mha( GGML_ASSERT(n_kv_max >= 0 && n_kv_max <= INT32_MAX); ggml_flash_attn_ext_set_n_kv_max(cur, static_cast(n_kv_max)); ggml_prec_set_acc(cur, GGML_PREC_F32); + if (bias_table) { + ggml_flash_attn_ext_add_indexed_bias(cur, bias_table, bias_indices); + const auto dev = model.dev_layer(il); + if (!cparams.offload_kqv || !dev || !ggml_backend_dev_supports_op(dev, cur)) { + cur->src[6] = cur->src[7] = nullptr; + cur->src[3] = dense_bias_mask(); + } else if (kv_rows) { + // Looped layers can project Q and the bias on a different device from their KV cache. + for (int i = 0; i < ggml_backend_sched_get_n_backends(sched); ++i) { + auto backend = ggml_backend_sched_get_backend(sched, i); + if (ggml_backend_get_device(backend) == dev) { + ggml_backend_sched_set_tensor_backend(sched, cur, backend); + break; + } + } + } + } if (v_mla) { #if 0 @@ -3250,6 +3279,9 @@ ggml_tensor * llm_graph_context::build_attn_mha( cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]); } else { + if (bias_table) { + kq_mask = dense_bias_mask(); + } ggml_tensor * kq = ggml_mul_mat(ctx0, k, q); cb(kq, "kq", il); @@ -3781,7 +3813,9 @@ static ggml_tensor * build_attn_iswa_impl( ggml_tensor * sinks, ggml_tensor * v_mla, float kq_scale, - int il) { + int il, + ggml_tensor * bias_table = nullptr, + ggml_tensor * bias_indices = nullptr) { ggml_context * ctx0 = gctx.ctx0; ggml_cgraph * gf = gctx.gf; @@ -3847,7 +3881,7 @@ static ggml_tensor * build_attn_iswa_impl( ggml_tensor * k = use_kv_cur ? k_cur : mctx_cur->get_k(ctx0, il); ggml_tensor * v = use_kv_cur ? v_cur : mctx_cur->get_v(ctx0, il); - ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il); + ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il, bias_table, bias_indices); cur = build_attn_scale_kv_output(ctx0, mctx_cur, cur, il); gctx.cb(cur, "kqv_out", il); @@ -4441,19 +4475,18 @@ llm_graph_input_mem_hybrid_iswa_rel * llm_graph_context::build_inp_mem_hybrid_is auto inp_attn = std::make_unique(hparams, cparams, attn_ctx); - // dense masks: the bias is gathered by the distance to each cell of the K/V view { inp_attn->self_k_idxs = attn_ctx->get_base()->build_input_k_idxs(ctx0, ubatch); inp_attn->self_v_idxs = attn_ctx->get_base()->build_input_v_idxs(ctx0, ubatch); - inp_attn->self_attn_mask.raw = build_attn_inp_kq_mask(ctx0, attn_ctx->get_base(), ubatch, cparams); + inp_attn->self_attn_mask = build_attn_inp_attn_mask(ctx0, attn_ctx->get_base(), ubatch, cparams); } { inp_attn->self_k_idxs_swa = attn_ctx->get_swa()->build_input_k_idxs(ctx0, ubatch); inp_attn->self_v_idxs_swa = attn_ctx->get_swa()->build_input_v_idxs(ctx0, ubatch); - inp_attn->self_attn_mask_swa.raw = build_attn_inp_kq_mask(ctx0, attn_ctx->get_swa(), ubatch, cparams); + inp_attn->self_attn_mask_swa = build_attn_inp_attn_mask(ctx0, attn_ctx->get_swa(), ubatch, cparams); } inp_attn->self_k_rot = attn_ctx->get_base()->get_k_rot(); @@ -4464,11 +4497,11 @@ llm_graph_input_mem_hybrid_iswa_rel * llm_graph_context::build_inp_mem_hybrid_is auto inp = std::make_unique(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur, extent, extent_swa); - inp->self_rel_pos = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, attn_ctx->get_base()->get_n_kv(), ubatch.n_tokens); + inp->self_rel_pos = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, inp->get_attn()->self_attn_mask.raw->ne[0], ubatch.n_tokens); ggml_set_input(inp->self_rel_pos); ggml_set_name(inp->self_rel_pos, "attn_inp_rel_pos"); - inp->self_rel_pos_swa = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, attn_ctx->get_swa()->get_n_kv(), ubatch.n_tokens); + inp->self_rel_pos_swa = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, inp->get_attn()->self_attn_mask_swa.raw->ne[0], ubatch.n_tokens); ggml_set_input(inp->self_rel_pos_swa); ggml_set_name(inp->self_rel_pos_swa, "attn_inp_rel_pos_swa"); @@ -4483,7 +4516,7 @@ ggml_tensor * llm_graph_context::build_attn( ggml_tensor * q_cur, ggml_tensor * k_cur, ggml_tensor * v_cur, - ggml_tensor * kq_b, + ggml_tensor * bias_table, ggml_tensor * sinks, float kq_scale, int il) const { @@ -4493,22 +4526,10 @@ ggml_tensor * llm_graph_context::build_attn( const auto & attn_mask = is_swa ? inp_attn->self_attn_mask_swa : inp_attn->self_attn_mask; - // TODO: support kv_rows - fill the distances over the kv_rows cell lists and pass the rows to build_attn_mha, - // needs a kv_rows flash attention with a per-head mask (CUDA has none) - GGML_ASSERT(attn_mask.rows == nullptr); - - // a mask per head, in the dense layout of the input mask, which flash attention takes in F16 - ggml_tensor * kq_mask = attn_mask.raw; - if (kq_mask->type != GGML_TYPE_F32) { - kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); - } - kq_mask = ggml_add(ctx0, kq_b, kq_mask); - if (cparams.flash_attn) { - kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F16); - } - cb(kq_mask, "kq_mask_rel_pos", il); + ggml_tensor * indices = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; - return build_attn_iswa_impl(*this, inp_attn, wo, wo_b, wo_s, q_cur, k_cur, v_cur, nullptr, kq_mask, nullptr, sinks, nullptr, kq_scale, il); + return build_attn_iswa_impl(*this, inp_attn, wo, wo_b, wo_s, q_cur, k_cur, v_cur, nullptr, attn_mask.raw, attn_mask.rows, + sinks, nullptr, kq_scale, il, bias_table, indices); } void llm_graph_context::build_dense_out( diff --git a/src/llama-graph.h b/src/llama-graph.h index a9f8e5ce0068..b3de174c8b54 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -774,8 +774,7 @@ class llm_graph_input_mem_hybrid_iswa : public llm_graph_input_i { }; // hybrid iswa memory with a per-head attention bias that depends on the distance from the query to the cell (Inkling) -// the KQ masks are always dense (rows == nullptr) and are filled from the same cells as the distances, so that the bias -// gathered by distance lines up with the mask +// The visibility mask and distances use the same cache cell order. class llm_graph_input_mem_hybrid_iswa_rel : public llm_graph_input_i { public: llm_graph_input_mem_hybrid_iswa_rel( @@ -1342,7 +1341,9 @@ struct llm_graph_context { ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v] int64_t n_kv_max, float kq_scale, - int il) const; + int il, + ggml_tensor * bias_table = nullptr, + ggml_tensor * bias_indices = nullptr) const; llm_graph_input_attn_no_cache * build_attn_inp_no_cache() const; @@ -1540,7 +1541,7 @@ struct llm_graph_context { uint32_t extent, uint32_t extent_swa) const; - // kq_b is added to the KQ mask, after the KQ scale + // Gather the per-head bias by distance and add it to the visibility mask. ggml_tensor * build_attn( llm_graph_input_mem_hybrid_iswa_rel * inp, ggml_tensor * wo, @@ -1549,7 +1550,7 @@ struct llm_graph_context { ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens] ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] - ggml_tensor * kq_b, // [n_kv, n_tokens/n_stream, n_head_q, n_stream] + ggml_tensor * bias_table, // [n_head_q, n_bins, n_tokens] ggml_tensor * sinks, // [n_head_q] float kq_scale, int il) const; diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index fbe422a2717a..06b4a8a484e4 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -2007,14 +2007,18 @@ bool llama_kv_cache::has_cell_ext() const { return hparams.n_pos_per_embd() > 1 || hparams.ple_n_heads > 0; } -void llama_kv_cache::set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const { +void llama_kv_cache::set_input_relative_pos(ggml_tensor * dst, const ggml_tensor * rows, const llama_ubatch * ubatch, uint32_t extent) const { GGML_ASSERT(dst->type == GGML_TYPE_I32); const int64_t n_kv = dst->ne[0]; + GGML_ASSERT(!rows || (rows->ne[0] == n_kv && ggml_backend_buffer_is_host(rows->buffer))); + const int64_t n_tps = ubatch->n_tokens / (rows ? rows->ne[1] : 1); std::vector data(n_kv * ubatch->n_tokens); for (uint32_t i = 0; i < ubatch->n_tokens; ++i) { const auto & cells = v_cells.at(seq_to_stream.at(ubatch->seq_id[i][0])); + const int32_t * list = rows ? (const int32_t *) rows->data + (i/n_tps)*n_kv : nullptr; for (int64_t j = 0; j < n_kv; ++j) { - const int64_t distance = cells.is_empty(j) ? -1 : int64_t(ubatch->pos[i]) - cells.pos_get(j); + const int64_t cell = list ? list[j] : j; + const int64_t distance = cell < 0 || cells.is_empty(cell) ? -1 : int64_t(ubatch->pos[i]) - cells.pos_get(cell); data[i*n_kv + j] = distance >= 0 && distance < extent ? distance : extent; } } @@ -3124,8 +3128,8 @@ void llama_kv_cache_context::set_input_pos_bucket(ggml_tensor * dst, const llama kv->set_input_pos_bucket(dst, ubatch); } -void llama_kv_cache_context::set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const { - kv->set_input_relative_pos(dst, ubatch, extent); +void llama_kv_cache_context::set_input_relative_pos(ggml_tensor * dst, const ggml_tensor * rows, const llama_ubatch * ubatch, uint32_t extent) const { + kv->set_input_relative_pos(dst, rows, ubatch, extent); } void llama_kv_cache_context::get_prev_tokens(const llama_ubatch & ubatch, uint32_t n, std::vector & res) const { diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index 1b40f6fc41d5..1bfccf6aa3c5 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -249,7 +249,7 @@ class llama_kv_cache : public llama_memory_i { void set_input_attn_mask (const llm_attn_mask & attn_mask, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; - void set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; + void set_input_relative_pos(ggml_tensor * dst, const ggml_tensor * rows, const llama_ubatch * ubatch, uint32_t extent) const; // true if llama_kv_cell_ext holds information that has to survive a state save/restore bool has_cell_ext() const; @@ -454,7 +454,7 @@ class llama_kv_cache_context : public llama_memory_context_i { void set_input_k_shift (ggml_tensor * dst) const; void set_input_attn_mask (const llm_attn_mask & attn_mask, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; - void set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; + void set_input_relative_pos(ggml_tensor * dst, const ggml_tensor * rows, const llama_ubatch * ubatch, uint32_t extent) const; // see llama_kv_cache::get_prev_tokens() void get_prev_tokens(const llama_ubatch & ubatch, uint32_t n, std::vector & res) const; diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 3e43ef4184ea..8f6a6e41a363 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -249,7 +249,6 @@ ggml_tensor * llama_model_inkling2::graph::control(ggml_tensor * cur, ggml_tenso ggml_tensor * llama_model_inkling2::graph::build_inputs() { inp = build_inp_mem_hybrid_iswa_rel(hparams.n_relative_extent, hparams.n_swa); - attn = inp->get_attn(); recr = inp->get_recr(); ggml_tensor * inp_pos = build_inp_pos(); @@ -346,30 +345,19 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens cb(Vcur, "Vcur", il); cb(Rcur, "Rcur", il); - ggml_tensor * rel_pos = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; - - const int64_t n_stream = (is_swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw)->ne[3]; - const int64_t n_kv = rel_pos->ne[0]; - ggml_tensor * sinks = build_lora_mm(layer.attn_sink_proj, inputs[0]); - // project r on the bias table first, then gather by distance: only the gathered bias is n_kv x n_tokens x n_head ggml_tensor * table = ggml_mul_mat(ctx0, ggml_pad(ctx0, layer.attn_rel_bias, 0, 1, 0, 0), Rcur); // the sink logit t is per query: exp(s - t)/(1 + sum(exp(s - t))) = exp(s)/(exp(t) + sum(exp(s))), with a zero sink table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks, 1, n_head, n_tokens)); table = ggml_cont(ctx0, ggml_permute(ctx0, table, 1, 0, 2, 3)); - ggml_tensor * kq_b = ggml_get_rows(ctx0, table, rel_pos); - kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, n_tokens/n_stream, n_stream); - kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); - cb(kq_b, "kq_b", il); - sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); cur = build_attn(inp, nullptr, nullptr, nullptr, - Qcur, Kcur, Vcur, kq_b, sinks, 1.0f/sqrtf(n_embd_head), il); + Qcur, Kcur, Vcur, table, sinks, 1.0f/sqrtf(n_embd_head), il); cur = ggml_mul(ctx0, cur, ggml_sigmoid(ctx0, build_lora_mm(layer.wqkv_gate, inputs[0]))); cur = convolve(build_lora_mm(layer.wo, cur), layer.attn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa); diff --git a/src/models/models.h b/src/models/models.h index 8d2a5882772e..822a728e4f50 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2532,7 +2532,6 @@ struct llama_model_inkling2 : public llama_model_base { void build_output(ggml_tensor * cur, const std::vector & blocks); llm_graph_input_mem_hybrid_iswa_rel * inp = nullptr; - llm_graph_input_attn_kv_iswa * attn = nullptr; llm_graph_input_rs * recr = nullptr; ggml_tensor * inp_out_ids = nullptr; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5b997e91bbcf..f9dff8bf8ccd 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -367,6 +367,7 @@ endif() llama_build(test-backend-ops.cpp LINK ggml Threads::Threads) llama_build_and_test(test-backend-tensor.cpp LINK ggml) +llama_build_and_test(test-flash-attn-indexed-bias.cpp LINK ggml) llama_build_and_test(test-sleep.cpp LINK ggml) llama_build_and_test(test-backend-sched.cpp LINK ggml) diff --git a/tests/test-flash-attn-indexed-bias.cpp b/tests/test-flash-attn-indexed-bias.cpp new file mode 100644 index 000000000000..2eaa3079feba --- /dev/null +++ b/tests/test-flash-attn-indexed-bias.cpp @@ -0,0 +1,132 @@ +#include "ggml-alloc.h" +#include "ggml-backend.h" +#include "ggml.h" + +#include +#include +#include +#include + +static void test_indexed_bias(ggml_backend_t backend, int width, bool use_rows, int n_query, int cells = 768) { + constexpr int heads = 6, kv_heads = 2, streams = 2, bins = 17; + const int cols = use_rows ? std::min(512, cells) : cells; + + ggml_context * ctx = ggml_init({32*ggml_tensor_overhead() + ggml_graph_overhead(), nullptr, true}); + auto * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, width, n_query, heads, streams); + auto * k = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, width, cells, kv_heads, use_rows ? 1 : streams); + auto * v = ggml_dup_tensor(ctx, k); + auto * mask = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, cols, n_query, 1, streams); + auto * rows = use_rows ? ggml_new_tensor_2d(ctx, GGML_TYPE_I32, cols, streams) : nullptr; + auto * table = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, heads, bins, n_query*streams); + auto * indices = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, cols, n_query*streams); + auto * sinks = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, heads); + auto * out = ggml_flash_attn_ext_rows(ctx, q, k, v, mask, rows, 1.0f/sqrtf(width), 0, 0); + ggml_flash_attn_ext_add_sinks(out, sinks); + ggml_flash_attn_ext_add_indexed_bias(out, table, indices); + ggml_prec_set_acc(out, GGML_PREC_F32); + + if (!ggml_backend_supports_op(backend, out)) { + ggml_free(ctx); + return; + } + + auto * graph = ggml_new_graph(ctx); + ggml_build_forward_expand(graph, out); + auto * buf = ggml_backend_alloc_ctx_tensors(ctx, backend); + GGML_ASSERT(buf); + ggml_backend_buffer_clear(buf, 0); + + std::vector row(cols*streams), idx(ggml_nelements(indices)); + std::vector visibility(idx.size()), values(ggml_nelements(v)); + std::vector keys(ggml_nelements(k)); + std::vector queries(ggml_nelements(q)); + float sink_logits[heads]; + for (int h = 0; h < heads; ++h) { + sink_logits[h] = float(2*h - 3); + } + for (size_t i = 0; i < queries.size(); i += width) { + queries[i] = 4.0f; + } + std::vector biases(ggml_nelements(table)), expected(n_query*streams*heads), output(ggml_nelements(out)); + for (int s = 0; s < v->ne[3]; ++s) { + for (int h = 0; h < kv_heads; ++h) { + for (int c = 0; c < cells; ++c) { + const float x = float((c + 3*h + 5*s) % 23 - 11)/16; + const int offset = ((s*kv_heads + h)*cells + c)*width; + std::fill_n(values.data() + offset, width, ggml_fp32_to_fp16(x)); + keys[offset] = ggml_fp32_to_fp16(float((7*c + 2*h + 3*s) % 29 - 14)/4); + } + } + } + for (int s = 0; s < streams; ++s) { + for (int c = 0; c < cols; ++c) { + row[s*cols + c] = use_rows ? (c % 19 == 0 ? -1 : (13*c + 73*s) % cells) : c; + } + for (int j = 0; j < n_query; ++j) { + const int query = s*n_query + j; + for (int h = 0; h < heads; ++h) { + for (int b = 0; b < bins; ++b) { + biases[(query*bins + b)*heads + h] = float((b*(3 + h) + query) % 13 - 6)/2; + } + double sum = exp(double(sink_logits[h])), weighted = 0.0; + for (int c = 0; c < cols; ++c) { + const int cell = row[s*cols + c]; + const int i = query*cols + c; + idx[i] = (c + 3*query) % bins; + const bool visible = (s != 1 || j != 0) && cell >= 0 && (c + j) % 7 != 0; + visibility[i] = ggml_fp32_to_fp16(visible ? 0.25f : -INFINITY); + if (visible) { + const int vk = (use_rows ? 0 : s)*kv_heads + h/(heads/kv_heads); + const double qk = 4.0*ggml_fp16_to_fp32(keys[(vk*cells + cell)*width])/sqrt(width); + const double weight = exp(qk + 0.25 + biases[(query*bins + idx[i])*heads + h]); + weighted += weight*ggml_fp16_to_fp32(values[(vk*cells + cell)*width]); + sum += weight; + } + } + expected[query*heads + h] = weighted/sum; + } + } + } + ggml_backend_tensor_set(q, queries.data(), 0, ggml_nbytes(q)); + ggml_backend_tensor_set(k, keys.data(), 0, ggml_nbytes(k)); + ggml_backend_tensor_set(v, values.data(), 0, ggml_nbytes(v)); + ggml_backend_tensor_set(mask, visibility.data(), 0, ggml_nbytes(mask)); + ggml_backend_tensor_set(table, biases.data(), 0, ggml_nbytes(table)); + ggml_backend_tensor_set(sinks, sink_logits, 0, sizeof(sink_logits)); + ggml_backend_tensor_set(indices, idx.data(), 0, ggml_nbytes(indices)); + if (rows) { + ggml_backend_tensor_set(rows, row.data(), 0, ggml_nbytes(rows)); + } + GGML_ASSERT(ggml_backend_graph_compute(backend, graph) == GGML_STATUS_SUCCESS); + ggml_backend_tensor_get(out, output.data(), 0, ggml_nbytes(out)); + float max_error = 0.0f; + for (size_t i = 0; i < output.size(); ++i) { + GGML_ASSERT(std::isfinite(output[i])); + max_error = std::max(max_error, fabsf(output[i] - expected[i/width])); + } + printf("%s: width=%d, rows=%d, queries=%d, cells=%d, max error=%g\n", ggml_backend_name(backend), width, use_rows, n_query, cells, max_error); + GGML_ASSERT(max_error < 0.001f); + ggml_backend_buffer_free(buf); + ggml_free(ctx); +} + +int main() { + ggml_backend_load_all(); + for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { + auto dev = ggml_backend_dev_get(i); + if (!ggml_backend_reg_get_proc_address(ggml_backend_dev_backend_reg(dev), "ggml_backend_flash_attn_ext_indexed_bias")) { + continue; + } + auto backend = ggml_backend_dev_init(dev, nullptr); + GGML_ASSERT(backend); + for (int width : {64, 128}) { + test_indexed_bias(backend, width, false, 7, 16); + test_indexed_bias(backend, width, true, 7, 16); + for (int n_query : {1, 7, 65}) { + test_indexed_bias(backend, width, false, n_query); + test_indexed_bias(backend, width, true, n_query); + } + } + ggml_backend_free(backend); + } +} From d29f9d4898d02b028e7755c654db3e281f307d9a Mon Sep 17 00:00:00 2001 From: Piotr Wilkin Date: Sat, 21 Nov 2026 18:51:25 +0100 Subject: [PATCH 02/24] fixup! compact bias on the existing FLASH_ATTN_EXT for CUDA, ROCm and Vulkan Assisted-by: Codex --- ggml/include/ggml.h | 2 ++ ggml/src/ggml-backend-meta.cpp | 4 ++++ ggml/src/ggml-backend.cpp | 5 ----- ggml/src/ggml-cann/ggml-cann.cpp | 4 ++-- ggml/src/ggml-cpu/ggml-cpu.cpp | 4 ++++ ggml/src/ggml-cuda/fattn.cu | 2 +- ggml/src/ggml-cuda/ggml-cuda.cu | 3 --- ggml/src/ggml-et/ggml-et.cpp | 1 + ggml/src/ggml-hexagon/htp-kparams.cpp | 4 ++-- ggml/src/ggml-metal/ggml-metal-device.m | 3 +++ ggml/src/ggml-opencl/ggml-opencl.cpp | 4 ++-- ggml/src/ggml-openvino/ggml-openvino.cpp | 4 ++++ ggml/src/ggml-rpc/ggml-rpc.cpp | 3 +-- ggml/src/ggml-sycl/ggml-sycl.cpp | 4 ++-- ggml/src/ggml-virtgpu/ggml-backend-device.cpp | 4 ++++ ggml/src/ggml-vulkan/ggml-vulkan.cpp | 8 +++----- .../ggml-vulkan/vulkan-shaders/flash_attn.comp | 2 +- ggml/src/ggml-webgpu/ggml-webgpu.cpp | 4 ++-- ggml/src/ggml-zdnn/fattn.cpp | 2 +- ggml/src/ggml.c | 15 +++++++++++++-- src/llama-graph.cpp | 2 +- tests/test-flash-attn-indexed-bias.cpp | 14 +++++++++----- 22 files changed, 62 insertions(+), 36 deletions(-) diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 9189ed0e41db..c20ab6f64216 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -2283,6 +2283,8 @@ extern "C" { struct ggml_tensor * a, struct ggml_tensor * sinks); + GGML_API bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a); + // Add table[head, indices[key, query], query] to the mask before its F16 rounding. // Queries from all streams are flattened in stream order. Indices must be in [0, table->ne[1]). GGML_API void ggml_flash_attn_ext_add_indexed_bias( diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index 595a5824aafe..d80b458906b4 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -152,6 +152,10 @@ static ggml_backend_buffer_type_t ggml_backend_meta_device_get_buffer_type(ggml_ static ggml_backend_buffer_type_t ggml_backend_meta_device_get_host_buffer_type(ggml_backend_dev_t dev); static bool ggml_backend_meta_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) { + if (op->op == GGML_OP_FLASH_ATTN_EXT && ggml_flash_attn_ext_has_indexed_bias(op)) { + return false; + } + GGML_ASSERT(ggml_backend_dev_is_meta(dev)); const ggml_backend_meta_device_context * meta_dev_ctx = (const ggml_backend_meta_device_context *) dev->context; return std::all_of(meta_dev_ctx->simple_devs.begin(), meta_dev_ctx->simple_devs.end(), diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp index 6f5ba3b7e5da..d598ca3d86d1 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -1030,11 +1030,6 @@ ggml_backend_buffer_t ggml_backend_dev_buffer_from_host_ptr(ggml_backend_dev_t d bool ggml_backend_dev_supports_op(ggml_backend_dev_t device, const struct ggml_tensor * op) { GGML_ASSERT(device); - // Backends predating indexed bias would accept the ordinary FA op and ignore the extra inputs. - if (op->op == GGML_OP_FLASH_ATTN_EXT && op->src[6] && - !ggml_backend_reg_get_proc_address(device->reg, "ggml_backend_flash_attn_ext_indexed_bias")) { - return false; - } return device->iface.supports_op(device, op); } diff --git a/ggml/src/ggml-cann/ggml-cann.cpp b/ggml/src/ggml-cann/ggml-cann.cpp index 0adc8680f5a4..4ea2f216d066 100644 --- a/ggml/src/ggml-cann/ggml-cann.cpp +++ b/ggml/src/ggml-cann/ggml-cann.cpp @@ -2679,8 +2679,8 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten return true; case GGML_OP_FLASH_ATTN_EXT: { - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - if (op->src[5] != nullptr) { + // K/V row lists and indexed bias are not supported + if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) { return false; } #ifdef ASCEND_310P diff --git a/ggml/src/ggml-cpu/ggml-cpu.cpp b/ggml/src/ggml-cpu/ggml-cpu.cpp index 29783400186d..23f05e28e94b 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.cpp +++ b/ggml/src/ggml-cpu/ggml-cpu.cpp @@ -422,6 +422,10 @@ static ggml_backend_buffer_t ggml_backend_cpu_device_buffer_from_host_ptr(ggml_b } static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) { + if (op->op == GGML_OP_FLASH_ATTN_EXT && ggml_flash_attn_ext_has_indexed_bias(op)) { + return false; + } + const struct ggml_tensor * src0 = op->src[0]; const struct ggml_tensor * src1 = op->src[1]; diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index f63cde69569e..2aee8856ccbd 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -669,7 +669,7 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const return BEST_FATTN_KERNEL_NONE; } - if (dst->src[6]) { + if (ggml_flash_attn_ext_has_indexed_bias(dst)) { const float softcap = ggml_get_op_params_f32(dst, 2); return (Q->ne[0] == 128 || (Q->ne[0] == 64 && softcap == 0.0f)) ? BEST_FATTN_KERNEL_TILE : BEST_FATTN_KERNEL_NONE; } diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index f0d226f17ceb..3e1f167e9936 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -7004,9 +7004,6 @@ static ggml_backend_feature * ggml_backend_cuda_get_features(ggml_backend_reg_t } static void * ggml_backend_cuda_reg_get_proc_address(ggml_backend_reg_t reg, const char * name) { - if (strcmp(name, "ggml_backend_flash_attn_ext_indexed_bias") == 0) { - return (void *) ggml_backend_cuda_device_supports_op; - } GGML_UNUSED(reg); if (strcmp(name, "ggml_backend_comm_init") == 0) { return (void *)ggml_backend_cuda_comm_init; diff --git a/ggml/src/ggml-et/ggml-et.cpp b/ggml/src/ggml-et/ggml-et.cpp index 53e64b323e5a..e575ee78b45c 100644 --- a/ggml/src/ggml-et/ggml-et.cpp +++ b/ggml/src/ggml-et/ggml-et.cpp @@ -1277,6 +1277,7 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm if (op->type == GGML_TYPE_F32 && op->src[0] && op->src[0]->type == GGML_TYPE_F32 && op->src[1] && (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) && op->src[2] && (op->src[2]->type == GGML_TYPE_F32 || op->src[2]->type == GGML_TYPE_F16) && op->src[4] == nullptr && op->src[5] == nullptr && + !ggml_flash_attn_ext_has_indexed_bias(op) && ggml_is_contiguous_rows(op) && ggml_is_contiguous_rows(op->src[0])) { float max_bias = 0.0f; float logit_softcap = 0.0f; diff --git a/ggml/src/ggml-hexagon/htp-kparams.cpp b/ggml/src/ggml-hexagon/htp-kparams.cpp index 6d365b8119c7..4e3c5cb8d3df 100644 --- a/ggml/src/ggml-hexagon/htp-kparams.cpp +++ b/ggml/src/ggml-hexagon/htp-kparams.cpp @@ -355,8 +355,8 @@ static bool htp_kparams_solve_flash_attn( return false; } - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - if (op->src[5] != nullptr) { + // K/V row lists and indexed bias are not supported + if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) { return false; } diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 2e085453adb9..4de1c2d28fed 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1744,6 +1744,9 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te case GGML_OP_ROLL: return ggml_is_contiguous(op->src[0]); case GGML_OP_FLASH_ATTN_EXT: + if (ggml_flash_attn_ext_has_indexed_bias(op)) { + return false; + } // K/V row lists (ggml_flash_attn_ext_rows): one list of cache rows per q slice if (op->src[5] != NULL) { const struct ggml_tensor * kv_rows = op->src[5]; diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 894f8235e9a0..0638cf155ab8 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -12426,8 +12426,8 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te case GGML_OP_MEAN: return op->src[0]->type == GGML_TYPE_F32; case GGML_OP_FLASH_ATTN_EXT: { - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - if (op->src[5] != nullptr) { + // K/V row lists and indexed bias are not supported + if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) { return false; } #ifdef GGML_OPENCL_USE_ADRENO_KERNELS diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index bd49560d8e1e..8325e638ada7 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1905,6 +1905,10 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { return {false, "FLASH_ATTN_EXT gemma3n pattern on GPU is not supported"}; } + if (ggml_flash_attn_ext_has_indexed_bias(op)) { + return {false, "FLASH_ATTN_EXT with indexed bias is not supported"}; + } + // K/V row lists (ggml_flash_attn_ext_rows) are not supported if (op->src[5] != nullptr) { return {false, "FLASH_ATTN_EXT with K/V row lists is not supported"}; diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp index e4a84cb0caf0..3ccfa8b9bb24 100644 --- a/ggml/src/ggml-rpc/ggml-rpc.cpp +++ b/ggml/src/ggml-rpc/ggml-rpc.cpp @@ -3113,9 +3113,8 @@ static ggml_backend_buffer_type_t ggml_backend_rpc_device_get_buffer_type(ggml_b static bool ggml_backend_rpc_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) { GGML_UNUSED(dev); - GGML_UNUSED(op); //TODO: call the remote backend and cache the results - return true; + return op->op != GGML_OP_FLASH_ATTN_EXT || !ggml_flash_attn_ext_has_indexed_bias(op); } static bool ggml_backend_rpc_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) { diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp index 3de5f1bd5888..702c3ae28f83 100644 --- a/ggml/src/ggml-sycl/ggml-sycl.cpp +++ b/ggml/src/ggml-sycl/ggml-sycl.cpp @@ -7719,8 +7719,8 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons case GGML_OP_SOLVE_TRI: return op->src[0]->ne[0] <= SYCL_SOLVE_TRI_MAX_N && op->src[1]->ne[0] <= SYCL_SOLVE_TRI_MAX_K; case GGML_OP_FLASH_ATTN_EXT: - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - return op->src[5] == nullptr && ggml_sycl_flash_attn_ext_supported(device, op); + // K/V row lists and indexed bias are not supported + return op->src[5] == nullptr && !ggml_flash_attn_ext_has_indexed_bias(op) && ggml_sycl_flash_attn_ext_supported(device, op); default: return false; } diff --git a/ggml/src/ggml-virtgpu/ggml-backend-device.cpp b/ggml/src/ggml-virtgpu/ggml-backend-device.cpp index 86df4cc5f3b2..a9e9e1b8640b 100644 --- a/ggml/src/ggml-virtgpu/ggml-backend-device.cpp +++ b/ggml/src/ggml-virtgpu/ggml-backend-device.cpp @@ -30,6 +30,10 @@ static void ggml_backend_remoting_device_get_memory(ggml_backend_dev_t dev, size } static bool ggml_backend_remoting_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) { + if (op->op == GGML_OP_FLASH_ATTN_EXT && ggml_flash_attn_ext_has_indexed_bias(op)) { + return false; + } + if ((op->op == GGML_OP_ROPE || op->op == GGML_OP_ROPE_BACK) && !ggml_rope_get_truncate(op)) { return false; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 6bab65cff5e5..aa2ba47d0208 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -16798,11 +16798,12 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm case GGML_OP_FLASH_ATTN_EXT: { // Only the indexed-bias scalar kernel reads row lists. - if (op->src[5] && (!op->src[6] || device->properties.limits.maxPerStageDescriptorStorageBuffers < 9 || + const bool indexed_bias = ggml_flash_attn_ext_has_indexed_bias(op); + if (op->src[5] && (!indexed_bias || device->properties.limits.maxPerStageDescriptorStorageBuffers < 9 || device->properties.limits.maxDescriptorSetStorageBuffers < 9)) { return false; } - if (op->src[6] && (op->src[6]->ne[1] > 0x7fffff || !device->subgroup_shuffle || !device->subgroup_vote || + if (indexed_bias && (op->src[6]->ne[1] > 0x7fffff || !device->subgroup_shuffle || !device->subgroup_vote || ggml_nelements(op->src[6]) > UINT32_MAX || ggml_nelements(op->src[7]) > UINT32_MAX || op->src[1]->type != GGML_TYPE_F16 || op->src[2]->type != GGML_TYPE_F16 || (op->src[1]->ne[0] != 64 && op->src[1]->ne[0] != 128) || op->src[1]->ne[0] != op->src[2]->ne[0])) { @@ -17510,9 +17511,6 @@ static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, } static void * ggml_backend_vk_reg_get_proc_address(ggml_backend_reg_t reg, const char * name) { - if (strcmp(name, "ggml_backend_flash_attn_ext_indexed_bias") == 0) { - return (void *) ggml_backend_vk_device_supports_op; - } UNUSED(reg); #if !defined(_WIN32) if (strcmp(name, "ggml_backend_comm_init") == 0) { diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp index ef69134c8616..5cfd6b8ae7b9 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp @@ -226,7 +226,7 @@ void main() { uint bin = uint(data_sparse[query * KV + kcol]); if (bin < n_bins) { float bias = uintBitsToFloat(data_mask_opt[(query * n_bins + bin) * p.neq2 + iq2]); - m = FLOAT_TYPE(unpackHalf2x16(packHalf2x16(vec2(float(m) + bias, 0))).x); + m = FLOAT_TYPE(float16_t(float(m) + bias)); } } masksh[c * masksh_stride + r] = m; diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index 75527b111f6a..cba6d291e18a 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -5080,8 +5080,8 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const { // conservative support checks for whether the more resource-intensive shader paths // can be used, to avoid cases where flash_attn is assigned to the CPU later on - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - supports_op = op->src[5] == nullptr && src0->type == GGML_TYPE_F32 && + // K/V row lists and indexed bias are not supported + supports_op = op->src[5] == nullptr && !ggml_flash_attn_ext_has_indexed_bias(op) && src0->type == GGML_TYPE_F32 && (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_Q4_0 || src1->type == GGML_TYPE_Q8_0) && (src2->type == GGML_TYPE_F32 || src2->type == GGML_TYPE_F16 || diff --git a/ggml/src/ggml-zdnn/fattn.cpp b/ggml/src/ggml-zdnn/fattn.cpp index e6a0c24cadaf..5e74e67a4936 100644 --- a/ggml/src/ggml-zdnn/fattn.cpp +++ b/ggml/src/ggml-zdnn/fattn.cpp @@ -21,7 +21,7 @@ bool ggml_zdnn_supports_flash_attn_ext(const ggml_backend_zdnn_device_context * memcpy(&logit_softcap, (const float *) op->op_params + 2, sizeof(float)); // sinks, alibi, softcap, sparse k/v sets and k/v row lists are not implemented - if (op->src[4] != nullptr || op->src[5] != nullptr || max_bias != 0.0f || logit_softcap != 0.0f || ggml_get_op_params_i32(op, 4) != 0) { + if (op->src[4] != nullptr || op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op) || max_bias != 0.0f || logit_softcap != 0.0f || ggml_get_op_params_i32(op, 4) != 0) { return false; } diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 9da7699b4859..21a4b8720f12 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -5526,11 +5526,24 @@ void ggml_flash_attn_ext_add_sinks( a->src[4] = sinks; } +bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a) { + GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT); + return ggml_get_op_params_i32(a, 5) != 0; +} + void ggml_flash_attn_ext_add_indexed_bias( struct ggml_tensor * a, struct ggml_tensor * table, struct ggml_tensor * indices) { GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT); + GGML_ASSERT((table == NULL) == (indices == NULL)); + a->src[6] = table; + a->src[7] = indices; + ggml_set_op_params_i32(a, 5, table != NULL); + if (!table) { + return; + } + const struct ggml_tensor * q = a->src[0]; const struct ggml_tensor * mask = a->src[3]; GGML_ASSERT(mask && mask->ne[0] == (a->src[5] ? a->src[5]->ne[0] : a->src[1]->ne[1]) && mask->ne[1] == q->ne[1]); @@ -5539,8 +5552,6 @@ void ggml_flash_attn_ext_add_indexed_bias( GGML_ASSERT(table->ne[0] == q->ne[2] && table->ne[1] > 0 && table->ne[2] == q->ne[1]*q->ne[3] && table->ne[3] == 1); GGML_ASSERT(indices->type == GGML_TYPE_I32 && ggml_is_contiguous(indices) && ggml_is_matrix(indices)); GGML_ASSERT(indices->ne[0] == mask->ne[0] && indices->ne[1] == table->ne[2]); - a->src[6] = table; - a->src[7] = indices; } // ggml_flash_attn_back diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 07ba2c855cad..4829780ec56a 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -3246,7 +3246,7 @@ ggml_tensor * llm_graph_context::build_attn_mha( ggml_flash_attn_ext_add_indexed_bias(cur, bias_table, bias_indices); const auto dev = model.dev_layer(il); if (!cparams.offload_kqv || !dev || !ggml_backend_dev_supports_op(dev, cur)) { - cur->src[6] = cur->src[7] = nullptr; + ggml_flash_attn_ext_add_indexed_bias(cur, nullptr, nullptr); cur->src[3] = dense_bias_mask(); } else if (kv_rows) { // Looped layers can project Q and the bias on a different device from their KV cache. diff --git a/tests/test-flash-attn-indexed-bias.cpp b/tests/test-flash-attn-indexed-bias.cpp index 2eaa3079feba..011c1a8f10a3 100644 --- a/tests/test-flash-attn-indexed-bias.cpp +++ b/tests/test-flash-attn-indexed-bias.cpp @@ -22,6 +22,12 @@ static void test_indexed_bias(ggml_backend_t backend, int width, bool use_rows, auto * sinks = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, heads); auto * out = ggml_flash_attn_ext_rows(ctx, q, k, v, mask, rows, 1.0f/sqrtf(width), 0, 0); ggml_flash_attn_ext_add_sinks(out, sinks); + const bool supports_plain = ggml_backend_supports_op(backend, out); + ggml_flash_attn_ext_add_indexed_bias(out, table, indices); + GGML_ASSERT(ggml_flash_attn_ext_has_indexed_bias(out)); + ggml_flash_attn_ext_add_indexed_bias(out, nullptr, nullptr); + GGML_ASSERT(!ggml_flash_attn_ext_has_indexed_bias(out) && !out->src[6] && !out->src[7]); + GGML_ASSERT(ggml_backend_supports_op(backend, out) == supports_plain); ggml_flash_attn_ext_add_indexed_bias(out, table, indices); ggml_prec_set_acc(out, GGML_PREC_F32); @@ -66,7 +72,7 @@ static void test_indexed_bias(ggml_backend_t backend, int width, bool use_rows, const int query = s*n_query + j; for (int h = 0; h < heads; ++h) { for (int b = 0; b < bins; ++b) { - biases[(query*bins + b)*heads + h] = float((b*(3 + h) + query) % 13 - 6)/2; + biases[(query*bins + b)*heads + h] = float((b*(3 + h) + query) % 13 - 6)/2.9f; } double sum = exp(double(sink_logits[h])), weighted = 0.0; for (int c = 0; c < cols; ++c) { @@ -78,7 +84,8 @@ static void test_indexed_bias(ggml_backend_t backend, int width, bool use_rows, if (visible) { const int vk = (use_rows ? 0 : s)*kv_heads + h/(heads/kv_heads); const double qk = 4.0*ggml_fp16_to_fp32(keys[(vk*cells + cell)*width])/sqrt(width); - const double weight = exp(qk + 0.25 + biases[(query*bins + idx[i])*heads + h]); + const float m = 0.25f + biases[(query*bins + idx[i])*heads + h]; + const double weight = exp(qk + ggml_fp16_to_fp32(ggml_fp32_to_fp16(m))); weighted += weight*ggml_fp16_to_fp32(values[(vk*cells + cell)*width]); sum += weight; } @@ -114,9 +121,6 @@ int main() { ggml_backend_load_all(); for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { auto dev = ggml_backend_dev_get(i); - if (!ggml_backend_reg_get_proc_address(ggml_backend_dev_backend_reg(dev), "ggml_backend_flash_attn_ext_indexed_bias")) { - continue; - } auto backend = ggml_backend_dev_init(dev, nullptr); GGML_ASSERT(backend); for (int width : {64, 128}) { From 37608cd0377ff226cde1765ee67a4eee46dbb419 Mon Sep 17 00:00:00 2001 From: Pedro Cuenca Date: Sat, 21 Nov 2026 18:57:20 +0100 Subject: [PATCH 03/24] Build mask in chunks --- src/llama-graph.cpp | 75 ++++++++++++++++++++++++++++++++++++----- src/llama-graph.h | 16 +++++---- src/models/inkling2.cpp | 16 +++------ 3 files changed, 80 insertions(+), 27 deletions(-) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 1bd3f8d0f85e..42cdb4e10358 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1432,6 +1432,12 @@ void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch) attn_ctx->get_swa()->set_input_relative_pos(self_rel_pos_swa, ubatch, extent_swa); } + if (self_rows->buffer) { + std::vector rows(self_rows->ne[0]); + std::iota(rows.begin(), rows.end(), 0); + ggml_backend_tensor_set(self_rows, rows.data(), 0, ggml_nbytes(self_rows)); + } + const int64_t n_rs = mctx->get_recr()->get_n_rs(); if (inp_rs->s_copy) { @@ -1476,6 +1482,8 @@ bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & par res &= self_rel_pos_swa->ne[0] == attn_ctx->get_swa()->get_n_kv(); res &= self_rel_pos_swa->ne[1] == params.ubatch.n_tokens; + res &= self_rows->ne[0] == params.ubatch.n_tokens; + res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; @@ -4382,6 +4390,10 @@ llm_graph_input_mem_hybrid_iswa_rel * llm_graph_context::build_inp_mem_hybrid_is ggml_set_input(inp->self_rel_pos_swa); ggml_set_name(inp->self_rel_pos_swa, "attn_inp_rel_pos_swa"); + inp->self_rows = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, ubatch.n_tokens); + ggml_set_input(inp->self_rows); + ggml_set_name(inp->self_rows, "attn_inp_rows"); + return (llm_graph_input_mem_hybrid_iswa_rel *) res->add_input(std::move(inp)); } @@ -4393,7 +4405,7 @@ ggml_tensor * llm_graph_context::build_attn( ggml_tensor * q_cur, ggml_tensor * k_cur, ggml_tensor * v_cur, - ggml_tensor * kq_b, + ggml_tensor * rel_bias, ggml_tensor * sinks, float kq_scale, int il) const { @@ -4407,14 +4419,59 @@ ggml_tensor * llm_graph_context::build_attn( // needs a kv_rows flash attention with a per-head mask (CUDA has none) GGML_ASSERT(attn_mask.rows == nullptr); - // a mask per head, in the dense layout of the input mask, which flash attention takes in F16 - ggml_tensor * kq_mask = attn_mask.raw; - if (kq_mask->type != GGML_TYPE_F32) { - kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); - } - kq_mask = ggml_add(ctx0, kq_b, kq_mask); - if (cparams.flash_attn) { - kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F16); + ggml_tensor * mask = attn_mask.raw; // [n_kv, n_tps, 1, n_stream] + ggml_tensor * rel_pos = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; // [n_kv, n_tokens] + + const int64_t n_kv = mask->ne[0]; + const int64_t n_tps = mask->ne[1]; + const int64_t n_stream = mask->ne[3]; + const int64_t n_head = rel_bias->ne[0]; + const int64_t n_bucket = rel_bias->ne[1]; + + // a mask per head, in the dense layout of the input mask and of its type (F16 for flash attention) + ggml_tensor * kq_mask = nullptr; + + // the bias of all rows at once is n_kv x n_tokens x n_head in F32, which does not fit at long context: + // the full-attention layers write the mask a few query rows at a time, at most 32 chunks + const int64_t n_rows = is_swa ? n_tps : std::max(32, (n_tps + 31)/32); + + if (n_rows >= n_tps) { + // [n_head, n_kv, n_tokens] -> [n_kv, n_tps, n_head, n_stream] + ggml_tensor * kq_b = ggml_get_rows(ctx0, rel_bias, rel_pos); + kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, n_tps, n_stream); + kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); + + kq_mask = ggml_add(ctx0, kq_b, mask->type == GGML_TYPE_F32 ? mask : ggml_cast(ctx0, mask, GGML_TYPE_F32)); + if (mask->type != GGML_TYPE_F32) { + kq_mask = ggml_cast(ctx0, kq_mask, mask->type); + } + } else { + // the scheduler copies each view of an input to the device on its own, copy the whole input once instead + rel_pos = ggml_cont(ctx0, rel_pos); + + kq_mask = ggml_repeat_4d(ctx0, mask, n_kv, n_tps, n_head, n_stream); + + for (int64_t i0 = 0; i0 < n_tps; i0 += n_rows) { + const int64_t n = std::min(n_rows, n_tps - i0); + + ggml_tensor * bias = ggml_view_4d(ctx0, rel_bias, n_head, n_bucket, n, n_stream, + rel_bias->nb[1], rel_bias->nb[2], n_tps*rel_bias->nb[2], i0*rel_bias->nb[2]); + ggml_tensor * pos = ggml_view_3d(ctx0, rel_pos, n_kv, n, n_stream, + rel_pos->nb[1], n_tps*rel_pos->nb[1], i0*rel_pos->nb[1]); + // the KQ mask of these rows, already repeated over the heads + ggml_tensor * rows = ggml_view_4d(ctx0, kq_mask, n_kv, n, n_head, n_stream, + kq_mask->nb[1], kq_mask->nb[2], kq_mask->nb[3], i0*kq_mask->nb[1]); + + // [n_head, n_kv, n, n_stream] -> [n_kv, n, n_head, n_stream] + ggml_tensor * cur = ggml_get_rows(ctx0, bias, pos); + cur = ggml_cont(ctx0, ggml_permute(ctx0, cur, 2, 0, 1, 3)); + cur = ggml_add(ctx0, cur, rows->type == GGML_TYPE_F32 ? rows : ggml_cast(ctx0, rows, GGML_TYPE_F32)); + + kq_mask = ggml_set_rows(ctx0, kq_mask, cur, ggml_view_1d(ctx0, inp->self_rows, n, i0*ggml_element_size(inp->self_rows))); + + // add the chunks in order, otherwise the graph computes all of them before the first write + ggml_build_forward_expand(gf, kq_mask); + } } cb(kq_mask, "kq_mask_rel_pos", il); diff --git a/src/llama-graph.h b/src/llama-graph.h index 116b7132a53e..57e604dc8470 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -807,6 +807,9 @@ class llm_graph_input_mem_hybrid_iswa_rel : public llm_graph_input_i { ggml_tensor * self_rel_pos = nullptr; // I32 [n_kv, n_batch] ggml_tensor * self_rel_pos_swa = nullptr; // I32 [n_kv_swa, n_batch] + // 0, 1, ..., the query rows that the per-head KQ mask is written to + ggml_tensor * self_rows = nullptr; // I32 [n_batch] + const uint32_t extent; const uint32_t extent_swa; @@ -1534,17 +1537,18 @@ struct llm_graph_context { uint32_t extent, uint32_t extent_swa) const; - // kq_b is added to the KQ mask, after the KQ scale + // rel_bias holds the bias of each query and head by distance bucket, it is gathered by the distance to + // each cell and added to the KQ mask, after the KQ scale ggml_tensor * build_attn( llm_graph_input_mem_hybrid_iswa_rel * inp, ggml_tensor * wo, ggml_tensor * wo_b, ggml_tensor * wo_s, - ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens] - ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] - ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] - ggml_tensor * kq_b, // [n_kv, n_tokens/n_stream, n_head_q, n_stream] - ggml_tensor * sinks, // [n_head_q] + ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens] + ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] + ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] + ggml_tensor * rel_bias, // [n_head_q, extent + 1, n_tokens] + ggml_tensor * sinks, // [n_head_q] float kq_scale, int il) const; diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 45477a69e35e..b27577786811 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -347,30 +347,22 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens cb(Vcur, "Vcur", il); cb(Rcur, "Rcur", il); - ggml_tensor * rel_pos = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; - - const int64_t n_stream = (is_swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw)->ne[3]; - const int64_t n_kv = rel_pos->ne[0]; - ggml_tensor * sinks = build_lora_mm(layer.attn_sink_proj, inputs[0]); - // project r on the bias table first, then gather by distance: only the gathered bias is n_kv x n_tokens x n_head + // project r on the bias table, the attention gathers it by distance: [n_head, extent + 1, n_tokens] + // the last bucket is a zero pad, for the cells that are farther than the extent ggml_tensor * table = ggml_mul_mat(ctx0, ggml_pad(ctx0, layer.attn_rel_bias, 0, 1, 0, 0), Rcur); // the sink logit t is per query: exp(s - t)/(1 + sum(exp(s - t))) = exp(s)/(exp(t) + sum(exp(s))), with a zero sink table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks, 1, n_head, n_tokens)); table = ggml_cont(ctx0, ggml_permute(ctx0, table, 1, 0, 2, 3)); - - ggml_tensor * kq_b = ggml_get_rows(ctx0, table, rel_pos); - kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, n_tokens/n_stream, n_stream); - kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); - cb(kq_b, "kq_b", il); + cb(table, "rel_bias", il); sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); cur = build_attn(inp, nullptr, nullptr, nullptr, - Qcur, Kcur, Vcur, kq_b, sinks, 1.0f/sqrtf(n_embd_head), il); + Qcur, Kcur, Vcur, table, sinks, 1.0f/sqrtf(n_embd_head), il); cur = ggml_mul(ctx0, cur, ggml_sigmoid(ctx0, build_lora_mm(layer.wqkv_gate, inputs[0]))); cur = convolve(build_lora_mm(layer.wo, cur), layer.attn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa); From ff91e4f84de442a954e2c73178b78630997df9f0 Mon Sep 17 00:00:00 2001 From: Piotr Wilkin Date: Sat, 21 Nov 2026 18:58:59 +0100 Subject: [PATCH 04/24] fixup! compact bias on the existing FLASH_ATTN_EXT for CUDA, ROCm and Vulkan Assisted-by: Codex --- ggml/src/ggml-webgpu/ggml-webgpu.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index cba6d291e18a..a63fa26eabb3 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -5081,7 +5081,8 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const // conservative support checks for whether the more resource-intensive shader paths // can be used, to avoid cases where flash_attn is assigned to the CPU later on // K/V row lists and indexed bias are not supported - supports_op = op->src[5] == nullptr && !ggml_flash_attn_ext_has_indexed_bias(op) && src0->type == GGML_TYPE_F32 && + supports_op = op->src[5] == nullptr && !ggml_flash_attn_ext_has_indexed_bias(op) && + src0->type == GGML_TYPE_F32 && (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_Q4_0 || src1->type == GGML_TYPE_Q8_0) && (src2->type == GGML_TYPE_F32 || src2->type == GGML_TYPE_F16 || From 56a4ac9eec559c295e84eb4af8730e7a1a889199 Mon Sep 17 00:00:00 2001 From: Pedro Cuenca Date: Sat, 21 Nov 2026 20:07:02 +0100 Subject: [PATCH 05/24] Copy one head mask and broadcast rather than 24 copies --- src/llama-graph.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 42cdb4e10358..a42088035740 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -4458,8 +4458,8 @@ ggml_tensor * llm_graph_context::build_attn( rel_bias->nb[1], rel_bias->nb[2], n_tps*rel_bias->nb[2], i0*rel_bias->nb[2]); ggml_tensor * pos = ggml_view_3d(ctx0, rel_pos, n_kv, n, n_stream, rel_pos->nb[1], n_tps*rel_pos->nb[1], i0*rel_pos->nb[1]); - // the KQ mask of these rows, already repeated over the heads - ggml_tensor * rows = ggml_view_4d(ctx0, kq_mask, n_kv, n, n_head, n_stream, + // the KQ mask of these rows from the first head, not written yet, broadcast over the heads + ggml_tensor * rows = ggml_view_4d(ctx0, kq_mask, n_kv, n, 1, n_stream, kq_mask->nb[1], kq_mask->nb[2], kq_mask->nb[3], i0*kq_mask->nb[1]); // [n_head, n_kv, n, n_stream] -> [n_kv, n, n_head, n_stream] From 808fd1c4e18352eeefcbf1b40fc890fb5cda5e80 Mon Sep 17 00:00:00 2001 From: Piotr Wilkin Date: Sun, 22 Nov 2026 02:02:29 +0100 Subject: [PATCH 06/24] fixup! compact bias on the existing FLASH_ATTN_EXT for CUDA, ROCm and Vulkan Assisted-by: Codex --- ggml/include/ggml.h | 4 +- ggml/src/ggml-cuda/fattn-common.cuh | 28 +++-- ggml/src/ggml-cuda/fattn-tile.cuh | 114 +++++++++--------- ggml/src/ggml-cuda/fattn-vec.cuh | 49 +++++--- ggml/src/ggml-cuda/fattn.cu | 9 +- ggml/src/ggml-vulkan/ggml-vulkan.cpp | 4 +- .../vulkan-shaders/flash_attn.comp | 2 +- ggml/src/ggml.c | 2 +- src/llama-graph.cpp | 3 +- src/llama-graph.h | 2 +- src/models/inkling2.cpp | 1 - tests/test-flash-attn-indexed-bias.cpp | 36 +++--- 12 files changed, 149 insertions(+), 105 deletions(-) diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index c20ab6f64216..496fadbc30a9 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -2285,8 +2285,8 @@ extern "C" { GGML_API bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a); - // Add table[head, indices[key, query], query] to the mask before its F16 rounding. - // Queries from all streams are flattened in stream order. Indices must be in [0, table->ne[1]). + // Add table[indices[key, query], head, query] to the mask before its F16 rounding. + // Queries from all streams are flattened in stream order. Indices must be in [0, table->ne[0]). GGML_API void ggml_flash_attn_ext_add_indexed_bias( struct ggml_tensor * a, struct ggml_tensor * table, diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh index 5dac66f04892..9ed4e7ce2665 100644 --- a/ggml/src/ggml-cuda/fattn-common.cuh +++ b/ggml/src/ggml-cuda/fattn-common.cuh @@ -22,6 +22,17 @@ struct fattn_indexed_bias { const float * table; const int32_t * indices; int64_t n_bins; + int64_t n_keys; + int64_t query_stride; + + __device__ fattn_indexed_bias for_head(int64_t first_query, int head) const { + return {table + first_query*query_stride + head*n_bins, indices + first_query*n_keys, n_bins, n_keys, query_stride}; + } + + __device__ half add(half mask, int query, int key) const { + const int bin = indices[query*n_keys + key]; + return uint32_t(bin) < n_bins ? __float2half(__half2float(mask) + table[query*query_stride + bin]) : mask; + } }; typedef void (* fattn_kernel_t)( @@ -983,7 +994,7 @@ static __global__ void flash_attn_combine_results( const float * VKQ_parts_ptr, const float2 * VKQ_meta_ptr, float * dst_ptr, - const int parallel_blocks, const float * sinks) { + const int parallel_blocks) { ggml_cuda_pdl_lc(); const float * GGML_CUDA_RESTRICT VKQ_parts = VKQ_parts_ptr; const float2 * GGML_CUDA_RESTRICT VKQ_meta = VKQ_meta_ptr; @@ -1018,13 +1029,13 @@ static __global__ void flash_attn_combine_results( __syncthreads(); - float kqmax = sinks ? fmaxf(meta[0].x, sinks[head]) : meta[0].x; + float kqmax = meta[0].x; for (int l = 1; l < parallel_blocks; ++l) { kqmax = max(kqmax, meta[l].x); } float VKQ_numerator = 0.0f; - float VKQ_denominator = sinks ? expf(sinks[head] - kqmax) : 0.0f; + float VKQ_denominator = 0.0f; for (int l = 0; l < parallel_blocks; ++l) { const float KQ_max_scale = expf(meta[l].x - kqmax); @@ -1177,7 +1188,7 @@ void launch_fattn( // Optional optimization where the mask is scanned to determine whether part of the calculation can be skipped. // Only worth the overhead if there is at lease one FATTN_KQ_STRIDE x FATTN_KQ_STRIDE square to be skipped or // multiple sequences of possibly different lengths, or kv_rows lists that end with padding. - const bool scan_mask = Q->ne[1] % ncols1 == 0 && !use_sparse && mask && mask->ne[2] == 1 && n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows); + const bool scan_mask = !dst->src[6] && !use_sparse && mask && mask->ne[2] == 1 && n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows); if (scan_mask) { const int64_t s31 = mask->nb[1] / sizeof(half2); const int64_t s33 = mask->nb[3] / sizeof(half2); @@ -1317,13 +1328,12 @@ void launch_fattn( GGML_ASSERT(block_dim.x % warp_size == 0); ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num, block_dim, nbytes_shared, main_stream); - const float * combine_sinks = dst->src[6] && sinks && !stream_k && parallel_blocks > 1 ? (const float *) sinks->data : nullptr; ggml_cuda_kernel_launch(fattn_kernel, launch_params, (const char *) Q->data, K_data, V_data, mask ? ((const char *) mask->data) : nullptr, - sinks && !combine_sinks ? (const char *) sinks->data : nullptr, + sinks ? ((const char *) sinks->data) : nullptr, KV_max.ptr, kv_rows ? (const int *) kv_rows->data : nullptr, !stream_k && parallel_blocks > 1 ? dst_tmp.ptr : (float *) KQV->data, dst_tmp_meta.ptr, @@ -1335,7 +1345,9 @@ void launch_fattn( mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0, fattn_indexed_bias{dst->src[6] ? (const float *) dst->src[6]->data : nullptr, dst->src[7] ? (const int32_t *) dst->src[7]->data : nullptr, - dst->src[6] ? dst->src[6]->ne[1] : 0} + dst->src[6] ? dst->src[6]->ne[0] : 0, + dst->src[7] ? dst->src[7]->ne[0] : 0, + dst->src[6] ? dst->src[6]->ne[0]*dst->src[6]->ne[1] : 0} ); CUDA_CHECK(cudaGetLastError()); @@ -1382,7 +1394,7 @@ void launch_fattn( const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num_combine, block_dim_combine, nbytes_shared_combine, main_stream); ggml_cuda_kernel_launch(flash_attn_combine_results, launch_params, - dst_tmp.ptr, dst_tmp_meta.ptr, (float *) KQV->data, parallel_blocks, combine_sinks); + dst_tmp.ptr, dst_tmp_meta.ptr, (float *) KQV->data, parallel_blocks); } CUDA_CHECK(cudaGetLastError()); } diff --git a/ggml/src/ggml-cuda/fattn-tile.cuh b/ggml/src/ggml-cuda/fattn-tile.cuh index 4e0cb52f2511..8987cf9b522d 100644 --- a/ggml/src/ggml-cuda/fattn-tile.cuh +++ b/ggml/src/ggml-cuda/fattn-tile.cuh @@ -374,9 +374,9 @@ static constexpr __device__ int ggml_cuda_fattn_tile_get_nbatch_K(const int DKQ, } // TODO: deduplicate with mma-f16 -template +template static __device__ __forceinline__ void flash_attn_tile_load_tile( - const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int stride_KV, const int i_sup, const int first, const int * rows) { + const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int stride_KV, const int i_sup, const int * rows) { constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); constexpr int cpy_ne = cpy_nb / 4; @@ -400,7 +400,7 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( const int i = i0 + threadIdx.y*stride_i + (stride_j == warp_size ? 0 : threadIdx.x / stride_j); if (i0 + nwarps*stride_i <= I || i < I) { - const int row = (oob_check && i >= i_sup) ? -1 : (rows ? rows[first + i] : first + i); + const int row = use_rows && (!oob_check || i < i_sup) ? rows[i] : i; #pragma unroll for (int j0 = j0_start; j0 < j0_stop; j0 += stride_j) { const int j = j0*cpy_ne + (stride_j == warp_size ? threadIdx.x : threadIdx.x % stride_j)*cpy_ne; @@ -408,7 +408,7 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( const __align__(16) half2 zero[cpy_ne] = {{0.0f, 0.0f}}; ggml_cuda_memcpy_1( tile_KV + i*(J/2 + J_padding) + j, - row >= 0 ? KV + (int64_t) row*stride_KV + j : zero); + (!oob_check || i < i_sup) && (!use_rows || row >= 0) ? KV + int64_t(row)*stride_KV + j : zero); } } } @@ -425,9 +425,9 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( ggml_cuda_unroll<7>{}(load); } -template +template static __device__ __forceinline__ void flash_attn_tile_load_tile( - const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int stride_KV, const int i_sup, const int first, const int * rows) { + const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int stride_KV, const int i_sup, const int * rows) { constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); constexpr int cpy_ne = cpy_nb / 4; @@ -451,7 +451,7 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( const int i = i0 + threadIdx.y*stride_i + (stride_j == warp_size ? 0 : threadIdx.x / stride_j); if (i0 + nwarps*stride_i <= I || i < I) { - const int row = (oob_check && i >= i_sup) ? -1 : (rows ? rows[first + i] : first + i); + const int row = use_rows && (!oob_check || i < i_sup) ? rows[i] : i; #pragma unroll for (int j0 = j0_start; j0 < j0_stop; j0 += stride_j) { const int j = j0*(cpy_ne/2) + (stride_j == warp_size ? threadIdx.x : threadIdx.x % stride_j)*(cpy_ne/2); @@ -459,7 +459,7 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( const half2 zero[cpy_ne/2] = {{0.0f, 0.0f}}; __align__(16) half2 tmp_h2[cpy_ne/2]; ggml_cuda_memcpy_1( - tmp_h2, row >= 0 ? KV + (int64_t) row*stride_KV + j : zero); + tmp_h2, (!oob_check || i < i_sup) && (!use_rows || row >= 0) ? KV + int64_t(row)*stride_KV + j : zero); __align__(16) float2 tmp_f2[cpy_ne/2]; #pragma unroll @@ -483,13 +483,12 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( // Function that performs a single iteration in for the KQ matrix multiplication: template + bool use_logit_softcap, bool oob_check, bool use_rows, typename T_vec_dot> static __device__ __forceinline__ void flash_attn_tile_iter_KQ( T_vec_dot * const Q_tmp, const half2 * const __restrict__ K_h2, T_vec_dot * const KV_tmp, const int stride_K2, - const int k_VKQ_0, const int k_VKQ_sup, const int k_KQ_0, float * KQ_acc, const int * rows) { @@ -500,8 +499,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ( constexpr int cpw = ncols > nwarps ? ncols/nwarps : 1; // Q columns per warp constexpr int np = nwarps > ncols ? nwarps/ncols : 1; // number of parallel warps per Q column - flash_attn_tile_load_tile - (K_h2 + k_KQ_0/2, KV_tmp, stride_K2, k_VKQ_sup, k_VKQ_0, rows); + flash_attn_tile_load_tile + (K_h2 + k_KQ_0/2, KV_tmp, stride_K2, k_VKQ_sup, rows); __syncthreads(); #ifdef FAST_FP16_AVAILABLE @@ -558,7 +557,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ( // Function that performs a single iteration of the main loop over up to nbatch_fa tokens. template + bool use_logit_softcap, bool oob_check, bool use_rows, bool indexed_bias, typename T_vec_dot, typename T_KQ, typename T_acc> static __device__ __forceinline__ void flash_attn_tile_iter( T_vec_dot * const Q_tmp, const half2 * const __restrict__ K_h2, @@ -578,7 +577,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter( const int k_VKQ_0, const int k_VKQ_max, const int col_Q_0, - const fattn_indexed_bias bias, const int head, const int n_heads, const int sequence, const int * rows) { + const fattn_indexed_bias bias, const int * rows) { constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); constexpr int cpy_ne = cpy_nb / 4; @@ -597,6 +596,9 @@ static __device__ __forceinline__ void flash_attn_tile_iter( #endif // FAST_FP16_AVAILABLE static_assert(cpw % KQ_cs == 0, "bad KQ_cs"); const int k_VKQ_sup = k_VKQ_max - k_VKQ_0; // k supremum, only smaller k values have valid KV data + const half2 * K_tile = use_rows ? K_h2 : K_h2 + int64_t(k_VKQ_0)*stride_K2; + const half2 * V_tile = use_rows ? V_h2 : V_h2 + int64_t(k_VKQ_0)*stride_V2; + const int * tile_rows = use_rows ? rows + k_VKQ_0 : nullptr; float KQ_max_new[cpw]; #pragma unroll @@ -610,13 +612,13 @@ static __device__ __forceinline__ void flash_attn_tile_iter( constexpr int nbatch_K_last = DKQ % nbatch_K; #pragma unroll for (int k_KQ_0 = 0; k_KQ_0 < DKQ - nbatch_K_last; k_KQ_0 += nbatch_K) { - flash_attn_tile_iter_KQ( - Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc, rows); + flash_attn_tile_iter_KQ( + Q_tmp, K_tile, KV_tmp, stride_K2, k_VKQ_sup, k_KQ_0, KQ_acc, tile_rows); } if (nbatch_K_last > 0) { constexpr int k_KQ_0 = DKQ - nbatch_K_last; - flash_attn_tile_iter_KQ( - Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc, rows); + flash_attn_tile_iter_KQ( + Q_tmp, K_tile, KV_tmp, stride_K2, k_VKQ_sup, k_KQ_0, KQ_acc, tile_rows); } // Apply logit softcap + mask, update KQ_max: @@ -640,17 +642,13 @@ static __device__ __forceinline__ void flash_attn_tile_iter( if (!oob_check || i_KQ < k_VKQ_sup) { const int k = k_VKQ_0 + i_KQ; - float m = (ncols2 > 1 || mask) ? __half2float(mask[(int64_t) j*stride_mask + k]) : 0.0f; - if constexpr (ncols2 == 1 && (DKQ == 64 || DKQ == 128)) { - if (bias.table) { - const int64_t query = (int64_t) sequence*ne01.z + j; - const int bin = bias.indices[query*stride_mask + k]; - if ((uint32_t) bin < bias.n_bins) { - m = __half2float(__float2half(m + bias.table[(query*bias.n_bins + bin)*n_heads + head])); - } + if (ncols2 > 1 || mask) { + half m = mask[int64_t(j)*stride_mask + k]; + if constexpr (indexed_bias) { + m = bias.add(m, j, k); } + KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] += slope*__half2float(m); } - KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] += slope*m; KQ_max_new[jc0] = fmaxf(KQ_max_new[jc0], KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] + FATTN_KQ_MAX_OFFSET); } @@ -731,8 +729,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter( static_assert(nbatch_V % np == 0, "bad nbatch_V"); #pragma unroll for (int k0 = 0; k0 < nbatch_fa; k0 += nbatch_V) { - flash_attn_tile_load_tile - (V_h2, KV_tmp, stride_V2, k_VKQ_sup - k0, k_VKQ_0 + k0, rows); + flash_attn_tile_load_tile + (use_rows ? V_tile : V_tile + int64_t(k0)*stride_V2, KV_tmp, stride_V2, k_VKQ_sup - k0, use_rows ? tile_rows + k0 : nullptr); __syncthreads(); #ifdef FAST_FP16_AVAILABLE @@ -801,7 +799,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter( } } -template // D == head size +template // D == head size __launch_bounds__(ggml_cuda_fattn_tile_get_nthreads(DKQ, DV, ncols1*ncols2), ggml_cuda_fattn_tile_get_occupancy(DKQ, DV, ncols1*ncols2)) static __global__ void flash_attn_tile( const char * Q_ptr, @@ -866,8 +864,9 @@ static __global__ void flash_attn_tile( const int col_Q_0 = blockIdx.x * ncols1; // Index of the first Q column for this CUDA block to work on. const int sequence = blockIdx.z / (ne02/ncols2); - const int * rows = KV_rows_ptr ? KV_rows_ptr + (int64_t) sequence*ne11 : nullptr; + const int * rows = use_rows ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr; const int head0 = blockIdx.z*ncols2 - sequence*ne02; // == blockIdx.z % (ne02/ncols2) + const auto head_bias = indexed_bias ? bias.for_head(int64_t(sequence)*ne01.z, head0) : bias; const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix. const float * Q_f = (const float *) (Q + nb03*sequence + nb02* head0); const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*(head0 / gqa_ratio)); @@ -973,24 +972,24 @@ static __global__ void flash_attn_tile( int k_VKQ_0 = blockIdx.y*nbatch_fa; while (k_VKQ_0 <= k_VKQ_max - nbatch_fa) { constexpr bool oob_check = false; - flash_attn_tile_iter + flash_attn_tile_iter (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, - stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, bias, head0, ne02, sequence, rows); + stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows); k_VKQ_0 += gridDim.y*nbatch_fa; } if (k_VKQ_0 < k_VKQ_max) { constexpr bool oob_check = true; - flash_attn_tile_iter + flash_attn_tile_iter (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, - stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, bias, head0, ne02, sequence, rows); + stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows); } } else { // Branch without out-of-bounds checks. for (int k_VKQ_0 = blockIdx.y*nbatch_fa; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nbatch_fa) { constexpr bool oob_check = false; - flash_attn_tile_iter + flash_attn_tile_iter (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, - stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, bias, head0, ne02, sequence, rows); + stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows); } } @@ -1066,7 +1065,7 @@ static __global__ void flash_attn_tile( } // Attention sink: adjust KQ max and sum only for the first of all parallel blocks: - if (sinks && !bias.table && blockIdx.y == 0) { + if (sinks && blockIdx.y == 0) { #pragma unroll for (int jc0 = 0; jc0 < cpw; ++jc0) { const int jc = jc0 + (threadIdx.y/np)*cpw; @@ -1107,17 +1106,7 @@ static __global__ void flash_attn_tile( return; } - float scale = 1.0f; - if (gridDim.y == 1) { - if (bias.table && sinks) { - const float sink = ((const float *) sinks)[head0 + c]; - const float kq_max = fmaxf(KQ_max[jc0], sink); - const float kq_scale = expf(KQ_max[jc0] - kq_max); - scale = kq_scale/(KQ_sum[jc0]*kq_scale + expf(sink - kq_max)); - } else { - scale = 1.0f/KQ_sum[jc0]; - } - } + const float scale = gridDim.y == 1 ? 1.0f/KQ_sum[jc0] : 1.0f; const int j_dst_unrolled = ((sequence*int(ne01.z) + col_Q_0 + j)*ne02 + head0 + c)*gridDim.y + blockIdx.y; @@ -1171,7 +1160,7 @@ static __global__ void flash_attn_tile( #endif // FLASH_ATTN_AVAILABLE } -template +template static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const ggml_tensor * Q = dst->src[0]; @@ -1187,7 +1176,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 64; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; + fattn_kernel_t fattn_kernel = flash_attn_tile; launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; @@ -1203,7 +1192,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 32; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; + fattn_kernel_t fattn_kernel = flash_attn_tile; launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; @@ -1215,7 +1204,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 16; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; + fattn_kernel_t fattn_kernel = flash_attn_tile; launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; @@ -1227,7 +1216,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 8; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; + fattn_kernel_t fattn_kernel = flash_attn_tile; launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; @@ -1239,7 +1228,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 4; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; + fattn_kernel_t fattn_kernel = flash_attn_tile; launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; @@ -1250,7 +1239,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 2; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; + fattn_kernel_t fattn_kernel = flash_attn_tile; launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; @@ -1277,7 +1266,18 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm const bool nvidia = GGML_CUDA_CC_IS_NVIDIA(ggml_cuda_info().devices[ggml_cuda_get_device()].cc); const int gqa_limit = nvidia && gqa_ratio <= 4 && DV <= 256 ? 16 : INT_MAX; // a mask with a head dimension is not shared by the Q heads of a K/V head - const bool use_gqa_opt = !dst->src[6] && mask && mask->ne[2] == 1 && max_bias == 0.0f && Q->ne[1] <= gqa_limit && K->ne[1] % FATTN_KQ_STRIDE == 0; + const bool use_gqa_opt = mask && mask->ne[2] == 1 && max_bias == 0.0f && Q->ne[1] <= gqa_limit && K->ne[1] % FATTN_KQ_STRIDE == 0; + + if constexpr (DKQ == 64 || DKQ == 128) { + if (dst->src[6]) { + if (dst->src[5]) { + launch_fattn_tile_switch_ncols1(ctx, dst); + } else { + launch_fattn_tile_switch_ncols1(ctx, dst); + } + return; + } + } if constexpr (DKQ == 320) { // This branch is only used for Mistral Small 4 which has a GQA ratio of 32. diff --git a/ggml/src/ggml-cuda/fattn-vec.cuh b/ggml/src/ggml-cuda/fattn-vec.cuh index 88c0b32ad9d1..42c0ef1c40e1 100644 --- a/ggml/src/ggml-cuda/fattn-vec.cuh +++ b/ggml/src/ggml-cuda/fattn-vec.cuh @@ -16,7 +16,7 @@ static constexpr __device__ int ggml_cuda_fattn_vec_get_nthreads_device() { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpass-failed" #endif // __clang__ -template // D == head size +template // D == head size __launch_bounds__(ggml_cuda_fattn_vec_get_nthreads_device(), 1) static __global__ void flash_attn_ext_vec( const char * Q_ptr, @@ -42,7 +42,6 @@ static __global__ void flash_attn_ext_vec( const int32_t ne31, const int32_t ne32, const int32_t ne33, const int32_t nb31, const int64_t nb32, const int64_t nb33, const fattn_indexed_bias bias) { - GGML_UNUSED(bias); ggml_cuda_pdl_lc(); #ifdef FLASH_ATTN_AVAILABLE const char * GGML_CUDA_RESTRICT Q = Q_ptr; @@ -53,7 +52,6 @@ static __global__ void flash_attn_ext_vec( const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; float * GGML_CUDA_RESTRICT dst = dst_ptr; float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; - GGML_UNUSED(KV_rows_ptr); // Skip unused kernel variants for faster compilation: if (use_logit_softcap && !(D == 128 || D == 256)) { @@ -109,6 +107,7 @@ static __global__ void flash_attn_ext_vec( const int sequence = blockIdx.z / ne02; const int head = blockIdx.z - sequence*ne02; + const auto head_bias = indexed_bias ? bias.for_head(int64_t(sequence)*ne01.z, head) : bias; const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix. Q += nb03*sequence + nb02* head + nb01*ic0; K += nb13*sequence + nb12*(head / gqa_ratio); @@ -273,12 +272,15 @@ static __global__ void flash_attn_ext_vec( } const int k_VKQ_max = KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11; - K += blockIdx.y*nthreads * nb11; - V += blockIdx.y*nthreads * nb21; + const int * rows = use_rows ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr; + if constexpr (!use_rows) { + K += blockIdx.y*nthreads * nb11; + V += blockIdx.y*nthreads * nb21; + } maskh += blockIdx.y*nthreads; for (int k_VKQ_0 = blockIdx.y*nthreads; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nthreads, // Increment pointers after each loop: - K += gridDim.y*nthreads*nb11, V += gridDim.y*nthreads*nb21, maskh += gridDim.y*nthreads) { + K += use_rows ? 0 : gridDim.y*nthreads*nb11, V += use_rows ? 0 : gridDim.y*nthreads*nb21, maskh += gridDim.y*nthreads) { // Calculate KQ tile and keep track of new maximum KQ values: float KQ_reg[ncols]; // KQ in registers. @@ -292,22 +294,24 @@ static __global__ void flash_attn_ext_vec( #pragma unroll for (int i_KQ_0 = 0; i_KQ_0 < nthreads_KQ; ++i_KQ_0) { const int i_KQ = threadIdx.y*WARP_SIZE + (nthreads_KQ == WARP_SIZE ? 0 : (threadIdx.x & ~(nthreads_KQ-1))) + i_KQ_0; + const int row = use_rows ? rows[k_VKQ_0 + i_KQ] : i_KQ; #pragma unroll for (int j = 0; j < ncols; ++j) { - float sum = vec_dot_KQ(K + i_KQ*nb11, Q_reg[j], Q_i32[j], Q_ds[j]); + float sum = vec_dot_KQ(K + (use_rows ? int64_t(max(row, 0))*nb11 : i_KQ*nb11), Q_reg[j], Q_i32[j], Q_ds[j]); sum = warp_reduce_sum(sum); if (use_logit_softcap) { sum = logit_softcap*tanhf(sum); } - if (mask && (ncols == 1 || ic0 + j < int(ne01.z))) { - sum += slope*__half2float(maskh[j*ne11 + i_KQ]); + if constexpr (!indexed_bias) { + if (mask && (ncols == 1 || ic0 + j < int(ne01.z))) { + sum += slope*__half2float(maskh[j*ne11 + i_KQ]); + } + KQ_max_new[j] = fmaxf(KQ_max_new[j], sum + FATTN_KQ_MAX_OFFSET); } - KQ_max_new[j] = fmaxf(KQ_max_new[j], sum + FATTN_KQ_MAX_OFFSET); - if ((nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ) == uint32_t(i_KQ_0)) { KQ_reg[j] = sum; } @@ -316,8 +320,14 @@ static __global__ void flash_attn_ext_vec( #pragma unroll for (int j = 0; j < ncols; ++j) { + if constexpr (indexed_bias) { + const int k = k_VKQ_0 + tid; + const half m = use_rows && rows[k] < 0 ? half(-INFINITY) : head_bias.add(maskh[j*ne11 + tid], ic0 + j, k); + KQ_reg[j] += slope*__half2float(m); + KQ_max_new[j] = fmaxf(KQ_max[j], KQ_reg[j] + FATTN_KQ_MAX_OFFSET); + } #pragma unroll - for (int offset = nthreads_KQ; offset < WARP_SIZE; offset <<= 1) { + for (int offset = indexed_bias ? 1 : nthreads_KQ; offset < WARP_SIZE; offset <<= 1) { KQ_max_new[j] = fmaxf(KQ_max_new[j], ggml_cuda_shfl_xor(KQ_max_new[j], offset, WARP_SIZE)); } const float KQ_max_scale = expf(KQ_max[j] - KQ_max_new[j]); @@ -347,6 +357,7 @@ static __global__ void flash_attn_ext_vec( #pragma unroll for (int k0 = 0; k0 < WARP_SIZE; k0 += V_cols_per_iter) { const int k = threadIdx.y*WARP_SIZE + k0 + (nthreads_V == WARP_SIZE ? 0 : threadIdx.x / nthreads_V); + const char * V_row = V + (use_rows ? int64_t(max(rows[k_VKQ_0 + k], 0))*nb21 : k*nb21); #ifdef V_DOT2_F32_F16_AVAILABLE half2 KQ_k[ncols]; @@ -359,14 +370,14 @@ static __global__ void flash_attn_ext_vec( half2 tmp[V_rows_per_thread/2]; if constexpr (type_V == GGML_TYPE_BF16) { float2 tmp_f[V_rows_per_thread/2]; - dequantize_V(V + k*nb21, tmp_f, + dequantize_V(V_row, tmp_f, 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); #pragma unroll for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { tmp[i_VKQ_1] = __float22half2_rn(tmp_f[i_VKQ_1]); } } else { - dequantize_V(V + k*nb21, tmp, + dequantize_V(V_row, tmp, 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); } #pragma unroll @@ -386,7 +397,7 @@ static __global__ void flash_attn_ext_vec( #pragma unroll for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { float2 tmp[V_rows_per_thread/2]; - dequantize_V(V + k*nb21, tmp, + dequantize_V(V_row, tmp, 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); #pragma unroll for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { @@ -547,7 +558,7 @@ static __global__ void flash_attn_ext_vec( nb11, nb12, nb13, nb21, nb22, nb23, ne31, ne32, ne33, - nb31, nb32, nb33); + nb31, nb32, nb33, bias); NO_DEVICE_CODE; #endif // FLASH_ATTN_AVAILABLE } @@ -562,6 +573,12 @@ void ggml_cuda_flash_attn_ext_vec_case_impl(ggml_backend_cuda_context & ctx, ggm const int nthreads = ggml_cuda_fattn_vec_get_nthreads_host(cc); const int nwarps = nthreads / WARP_SIZE; fattn_kernel_t fattn_kernel = flash_attn_ext_vec; + if constexpr (cols_per_block == 1 && (D == 64 || D == 128) && !use_logit_softcap) { + if (dst->src[6]) { + fattn_kernel = dst->src[5] ? flash_attn_ext_vec : + flash_attn_ext_vec; + } + } const bool need_f16_K = type_K == GGML_TYPE_F16; const bool need_f16_V = type_V == GGML_TYPE_F16; constexpr size_t nbytes_shared = 0; diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 2aee8856ccbd..11b8a3e891f5 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -671,7 +671,14 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const if (ggml_flash_attn_ext_has_indexed_bias(dst)) { const float softcap = ggml_get_op_params_f32(dst, 2); - return (Q->ne[0] == 128 || (Q->ne[0] == 64 && softcap == 0.0f)) ? BEST_FATTN_KERNEL_TILE : BEST_FATTN_KERNEL_NONE; + if (Q->ne[0] != 128 && !(Q->ne[0] == 64 && softcap == 0.0f)) { + return BEST_FATTN_KERNEL_NONE; + } + if (softcap == 0.0f && Q->ne[1] == 1 && n_kv % FATTN_KQ_STRIDE == 0 && + ggml_cuda_get_fattn_vec_case(Q->ne[0], K->type, V->type)) { + return BEST_FATTN_KERNEL_VEC; + } + return BEST_FATTN_KERNEL_TILE; } if (mask && mask->ne[2] != 1) { diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index aa2ba47d0208..5e79e47e6e43 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -9215,7 +9215,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const if (bias) { // Bind the table and indices in the two unused mask optimization slots. - fa_pipeline_state.flags |= (uint32_t) bias->ne[1] << 8; + fa_pipeline_state.flags |= (uint32_t) bias->ne[0] << 8; if (rows) { fa_pipeline_state.flags |= 1u << 31; } @@ -16803,7 +16803,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm device->properties.limits.maxDescriptorSetStorageBuffers < 9)) { return false; } - if (indexed_bias && (op->src[6]->ne[1] > 0x7fffff || !device->subgroup_shuffle || !device->subgroup_vote || + if (indexed_bias && (op->src[6]->ne[0] > 0x7fffff || !device->subgroup_shuffle || !device->subgroup_vote || ggml_nelements(op->src[6]) > UINT32_MAX || ggml_nelements(op->src[7]) > UINT32_MAX || op->src[1]->type != GGML_TYPE_F16 || op->src[2]->type != GGML_TYPE_F16 || (op->src[1]->ne[0] != 64 && op->src[1]->ne[0] != 128) || op->src[1]->ne[0] != op->src[2]->ne[0])) { diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp index 5cfd6b8ae7b9..fe14ad570e1c 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp @@ -225,7 +225,7 @@ void main() { uint query = iq3 * p.N + i * Br + r; uint bin = uint(data_sparse[query * KV + kcol]); if (bin < n_bins) { - float bias = uintBitsToFloat(data_mask_opt[(query * n_bins + bin) * p.neq2 + iq2]); + float bias = uintBitsToFloat(data_mask_opt[(query * p.neq2 + iq2) * n_bins + bin]); m = FLOAT_TYPE(float16_t(float(m) + bias)); } } diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 21a4b8720f12..89a9d9dfdc39 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -5549,7 +5549,7 @@ void ggml_flash_attn_ext_add_indexed_bias( GGML_ASSERT(mask && mask->ne[0] == (a->src[5] ? a->src[5]->ne[0] : a->src[1]->ne[1]) && mask->ne[1] == q->ne[1]); GGML_ASSERT(mask->ne[2] == 1 && mask->ne[3] == q->ne[3]); GGML_ASSERT(table->type == GGML_TYPE_F32 && ggml_is_contiguous(table)); - GGML_ASSERT(table->ne[0] == q->ne[2] && table->ne[1] > 0 && table->ne[2] == q->ne[1]*q->ne[3] && table->ne[3] == 1); + GGML_ASSERT(table->ne[1] == q->ne[2] && table->ne[0] > 0 && table->ne[2] == q->ne[1]*q->ne[3] && table->ne[3] == 1); GGML_ASSERT(indices->type == GGML_TYPE_I32 && ggml_is_contiguous(indices) && ggml_is_matrix(indices)); GGML_ASSERT(indices->ne[0] == mask->ne[0] && indices->ne[1] == table->ne[2]); } diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 4829780ec56a..b37ddd1aa4d5 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -3196,7 +3196,8 @@ ggml_tensor * llm_graph_context::build_attn_mha( v = ggml_permute(ctx0, v, 0, 2, 1, 3); auto dense_bias_mask = [&]() { - ggml_tensor * bias = ggml_get_rows(ctx0, bias_table, bias_indices); + ggml_tensor * table = ggml_cont(ctx0, ggml_permute(ctx0, bias_table, 1, 0, 2, 3)); + ggml_tensor * bias = ggml_get_rows(ctx0, table, bias_indices); bias = ggml_reshape_4d(ctx0, bias, q->ne[2], bias_indices->ne[0], q->ne[1], n_stream); bias = ggml_cont(ctx0, ggml_permute(ctx0, bias, 2, 0, 1, 3)); cb(bias, "kq_b", il); diff --git a/src/llama-graph.h b/src/llama-graph.h index b3de174c8b54..cfcbc248c72d 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -1550,7 +1550,7 @@ struct llm_graph_context { ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens] ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] - ggml_tensor * bias_table, // [n_head_q, n_bins, n_tokens] + ggml_tensor * bias_table, // [n_bins, n_head_q, n_tokens] ggml_tensor * sinks, // [n_head_q] float kq_scale, int il) const; diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 8f6a6e41a363..5d8bc7a4e09a 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -351,7 +351,6 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens // the sink logit t is per query: exp(s - t)/(1 + sum(exp(s - t))) = exp(s)/(exp(t) + sum(exp(s))), with a zero sink table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks, 1, n_head, n_tokens)); - table = ggml_cont(ctx0, ggml_permute(ctx0, table, 1, 0, 2, 3)); sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); diff --git a/tests/test-flash-attn-indexed-bias.cpp b/tests/test-flash-attn-indexed-bias.cpp index 011c1a8f10a3..048ea0264433 100644 --- a/tests/test-flash-attn-indexed-bias.cpp +++ b/tests/test-flash-attn-indexed-bias.cpp @@ -7,17 +7,23 @@ #include #include -static void test_indexed_bias(ggml_backend_t backend, int width, bool use_rows, int n_query, int cells = 768) { +static void set_kv(ggml_tensor * t, const std::vector & data) { + std::vector bytes(ggml_nbytes(t)); + ggml_quantize_chunk(t->type, data.data(), bytes.data(), 0, ggml_nrows(t), t->ne[0], nullptr); + ggml_backend_tensor_set(t, bytes.data(), 0, bytes.size()); +} + +static void test_indexed_bias(ggml_backend_t backend, int width, bool use_rows, int n_query, int cells = 768, ggml_type kv_type = GGML_TYPE_F16) { constexpr int heads = 6, kv_heads = 2, streams = 2, bins = 17; const int cols = use_rows ? std::min(512, cells) : cells; ggml_context * ctx = ggml_init({32*ggml_tensor_overhead() + ggml_graph_overhead(), nullptr, true}); auto * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, width, n_query, heads, streams); - auto * k = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, width, cells, kv_heads, use_rows ? 1 : streams); + auto * k = ggml_new_tensor_4d(ctx, kv_type, width, cells, kv_heads, use_rows ? 1 : streams); auto * v = ggml_dup_tensor(ctx, k); auto * mask = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, cols, n_query, 1, streams); auto * rows = use_rows ? ggml_new_tensor_2d(ctx, GGML_TYPE_I32, cols, streams) : nullptr; - auto * table = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, heads, bins, n_query*streams); + auto * table = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, bins, heads, n_query*streams); auto * indices = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, cols, n_query*streams); auto * sinks = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, heads); auto * out = ggml_flash_attn_ext_rows(ctx, q, k, v, mask, rows, 1.0f/sqrtf(width), 0, 0); @@ -43,8 +49,8 @@ static void test_indexed_bias(ggml_backend_t backend, int width, bool use_rows, ggml_backend_buffer_clear(buf, 0); std::vector row(cols*streams), idx(ggml_nelements(indices)); - std::vector visibility(idx.size()), values(ggml_nelements(v)); - std::vector keys(ggml_nelements(k)); + std::vector visibility(idx.size()); + std::vector keys(ggml_nelements(k)), values(ggml_nelements(v)); std::vector queries(ggml_nelements(q)); float sink_logits[heads]; for (int h = 0; h < heads; ++h) { @@ -59,8 +65,8 @@ static void test_indexed_bias(ggml_backend_t backend, int width, bool use_rows, for (int c = 0; c < cells; ++c) { const float x = float((c + 3*h + 5*s) % 23 - 11)/16; const int offset = ((s*kv_heads + h)*cells + c)*width; - std::fill_n(values.data() + offset, width, ggml_fp32_to_fp16(x)); - keys[offset] = ggml_fp32_to_fp16(float((7*c + 2*h + 3*s) % 29 - 14)/4); + std::fill_n(values.data() + offset, width, x); + keys[offset] = float((7*c + 2*h + 3*s) % 29 - 14)/4; } } } @@ -72,7 +78,7 @@ static void test_indexed_bias(ggml_backend_t backend, int width, bool use_rows, const int query = s*n_query + j; for (int h = 0; h < heads; ++h) { for (int b = 0; b < bins; ++b) { - biases[(query*bins + b)*heads + h] = float((b*(3 + h) + query) % 13 - 6)/2.9f; + biases[(query*heads + h)*bins + b] = float((b*(3 + h) + query) % 13 - 6)/2.9f; } double sum = exp(double(sink_logits[h])), weighted = 0.0; for (int c = 0; c < cols; ++c) { @@ -83,10 +89,10 @@ static void test_indexed_bias(ggml_backend_t backend, int width, bool use_rows, visibility[i] = ggml_fp32_to_fp16(visible ? 0.25f : -INFINITY); if (visible) { const int vk = (use_rows ? 0 : s)*kv_heads + h/(heads/kv_heads); - const double qk = 4.0*ggml_fp16_to_fp32(keys[(vk*cells + cell)*width])/sqrt(width); - const float m = 0.25f + biases[(query*bins + idx[i])*heads + h]; + const double qk = 4.0*keys[(vk*cells + cell)*width]/sqrt(width); + const float m = 0.25f + biases[(query*heads + h)*bins + idx[i]]; const double weight = exp(qk + ggml_fp16_to_fp32(ggml_fp32_to_fp16(m))); - weighted += weight*ggml_fp16_to_fp32(values[(vk*cells + cell)*width]); + weighted += weight*values[(vk*cells + cell)*width]; sum += weight; } } @@ -95,8 +101,8 @@ static void test_indexed_bias(ggml_backend_t backend, int width, bool use_rows, } } ggml_backend_tensor_set(q, queries.data(), 0, ggml_nbytes(q)); - ggml_backend_tensor_set(k, keys.data(), 0, ggml_nbytes(k)); - ggml_backend_tensor_set(v, values.data(), 0, ggml_nbytes(v)); + set_kv(k, keys); + set_kv(v, values); ggml_backend_tensor_set(mask, visibility.data(), 0, ggml_nbytes(mask)); ggml_backend_tensor_set(table, biases.data(), 0, ggml_nbytes(table)); ggml_backend_tensor_set(sinks, sink_logits, 0, sizeof(sink_logits)); @@ -111,7 +117,7 @@ static void test_indexed_bias(ggml_backend_t backend, int width, bool use_rows, GGML_ASSERT(std::isfinite(output[i])); max_error = std::max(max_error, fabsf(output[i] - expected[i/width])); } - printf("%s: width=%d, rows=%d, queries=%d, cells=%d, max error=%g\n", ggml_backend_name(backend), width, use_rows, n_query, cells, max_error); + printf("%s: width=%d, kv=%s, rows=%d, queries=%d, cells=%d, max error=%g\n", ggml_backend_name(backend), width, ggml_type_name(kv_type), use_rows, n_query, cells, max_error); GGML_ASSERT(max_error < 0.001f); ggml_backend_buffer_free(buf); ggml_free(ctx); @@ -126,6 +132,8 @@ int main() { for (int width : {64, 128}) { test_indexed_bias(backend, width, false, 7, 16); test_indexed_bias(backend, width, true, 7, 16); + test_indexed_bias(backend, width, false, 1, 768, GGML_TYPE_Q4_0); + test_indexed_bias(backend, width, true, 1, 768, GGML_TYPE_Q4_0); for (int n_query : {1, 7, 65}) { test_indexed_bias(backend, width, false, n_query); test_indexed_bias(backend, width, true, n_query); From be0bf1fbdf6b99cf029f856cce946c198dfd1ea5 Mon Sep 17 00:00:00 2001 From: Piotr Wilkin Date: Sun, 22 Nov 2026 11:37:33 +0100 Subject: [PATCH 07/24] remove the Vulkan support from this PR Assisted-by: Codex --- ggml/src/ggml-vulkan/ggml-vulkan.cpp | 66 +++++-------------- .../vulkan-shaders/flash_attn.comp | 14 ---- .../vulkan-shaders/flash_attn_base.glsl | 13 ---- .../vulkan-shaders/vulkan-shaders-gen.cpp | 5 -- 4 files changed, 16 insertions(+), 82 deletions(-) diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 5e79e47e6e43..2bba15356547 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -2333,12 +2333,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { const void * spv_data = nullptr; size_t spv_size = 0; const char *name = nullptr; - const bool kv_rows = (fa.first.flags & (1u << 31)) != 0; - if (kv_rows) { - spv_data = device->fp16 ? flash_attn_f32_f16_rows_data : flash_attn_f32_f16_rows_fp32_data; - spv_size = device->fp16 ? flash_attn_f32_f16_rows_len : flash_attn_f32_f16_rows_fp32_len; - name = "flash_attn_f32_f16_rows"; - } else if (bf16_kv) { + if (bf16_kv) { spv_data = flash_attn_f32_f16_fp32_data; spv_size = flash_attn_f32_f16_fp32_len; name = aligned ? "flash_attn_f32_bf16_aligned" : "flash_attn_f32_bf16"; @@ -2368,7 +2363,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { } name = aligned ? "flash_attn_f32_f16_aligned" : "flash_attn_f32_f16"; } - ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", kv_rows ? 9 : 8, + ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 8, sizeof(vk_flash_attn_push_constants), {Br, 1, 1}, get_fa_spec_constants(fa.first), aligned ? Bc : 1, true, !fa_ds, !fa_ds ? fa_sgs : 0); @@ -9030,12 +9025,10 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const const uint32_t nem2 = mask ? mask->ne[2] : 0; const uint32_t nem3 = mask ? mask->ne[3] : 0; - const ggml_tensor * bias = dst->src[6]; const uint32_t HSK = nek0; const uint32_t HSV = nev0; uint32_t N = neq1; - const ggml_tensor * rows = dst->src[5]; - const uint32_t KV = rows ? rows->ne[0] : nek1; + const uint32_t KV = nek1; GGML_ASSERT(ne0 == HSV); GGML_ASSERT(ne2 == N); @@ -9092,7 +9085,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const const uint32_t cm2_min_reuse = KV >= 8192 ? 4096 : 8192; // Query reuse must cover the conversion and synchronization cost. const bool cm2_dequant_kv = KV >= 4096 && neq1 >= cm2_min_queries && (uint64_t) neq1 * qk_ratio >= cm2_min_reuse; - const bool use_dequant_kv = !rows && ((k_quant && v_quant) || kv_raw_strided) && neq1 >= 64 && + const bool use_dequant_kv = ((k_quant && v_quant) || kv_raw_strided) && neq1 >= 64 && is_dense_kv_cache(k) && is_dense_kv_cache(v) && (uint64_t)ggml_nelements(k) * kv_scratch_ts <= ctx->device->properties.limits.maxStorageBufferRange && (uint64_t)ggml_nelements(v) * kv_scratch_ts <= ctx->device->properties.limits.maxStorageBufferRange && @@ -9112,7 +9105,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const vk_fa_tuning_params tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, 32, KV, k_type_eff, v_type_eff, f32acc, qk_ratio); const uint32_t max_gqa = std::min(tuning_params.block_rows, 32u); - if (!bias && N <= 8 && qk_ratio > 1 && qk_ratio <= max_gqa && + if (N <= 8 && qk_ratio > 1 && qk_ratio <= max_gqa && qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) { // grouped query attention - make the N dimension equal to gqa_ratio, reduce // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1 @@ -9122,8 +9115,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const workgroups_y /= gqa_ratio; } - tuning_params = bias ? get_fa_tuning_params_scalar(ctx->device, HSK, HSV, N, KV, k_type_eff, v_type_eff, f32acc) - : get_fa_tuning_params(ctx->device, HSK, HSV, N, KV, k_type_eff, v_type_eff, f32acc, qk_ratio); + tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, N, KV, k_type_eff, v_type_eff, f32acc, qk_ratio); float scale = 1.0f; float max_bias = 0.0f; @@ -9149,7 +9141,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const return (t->type != GGML_TYPE_F16 && t->type != GGML_TYPE_BF16) || (t->nb[1] | t->nb[2] | t->nb[3]) % (4 * sizeof(ggml_fp16_t)) == 0; }; - const bool use_sparse = !bias && !disable_sparse && n_kv_max > 0 && mask && + const bool use_sparse = !disable_sparse && n_kv_max > 0 && mask && max_bias == 0.0f && logit_softcap == 0.0f && (tuning_params.path != FA_COOPMAT2 || (sparse_gather_aligned(k) && sparse_gather_aligned(v))) && nem0 == KV && @@ -9208,18 +9200,11 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const } // Only use mask opt when the mask is fairly large. This hasn't been tuned extensively. - bool use_mask_opt = !bias && mask && !use_sparse && nem1 >= 32 && nem0 * nem1 > 32768 && nem0 >= tuning_params.block_cols * 16 + bool use_mask_opt = mask && !use_sparse && nem1 >= 32 && nem0 * nem1 > 32768 && nem0 >= tuning_params.block_cols * 16 && (ctx->device->architecture != vk_device_architecture::AMD_GCN || HSK > 256 || HSV > 256); vk_fa_pipeline_state fa_pipeline_state = get_fa_pipeline_state(ctx->device, tuning_params, HSK, HSV, aligned, f32acc, mask != nullptr, use_mask_opt, logit_softcap != 0, use_sparse, k_type_eff, v_type_eff); - if (bias) { - // Bind the table and indices in the two unused mask optimization slots. - fa_pipeline_state.flags |= (uint32_t) bias->ne[0] << 8; - if (rows) { - fa_pipeline_state.flags |= 1u << 31; - } - } vk_pipeline pipeline = nullptr; auto tensor_aligned_with = [&](const ggml_tensor * t, uint32_t in) { @@ -9234,7 +9219,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const tensor_aligned_with(k, 16u) && tensor_aligned_with(v, 16u); bool xe_fa_supported_dtype = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16 && mask != nullptr && mask->type == GGML_TYPE_F16; - xe_fa_opt = !bias && xe_fa_supported_platform && xe_fa_supported_usage && xe_fa_supported_dtype; + xe_fa_opt = xe_fa_supported_platform && xe_fa_supported_usage && xe_fa_supported_dtype; std::pair xe_fa_pipeline_dual_phases = { nullptr , nullptr }; vk_pipeline xe_fa_pipeline = nullptr; size_t size_q_staging = 0; @@ -9448,10 +9433,6 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const vk_subbuffer sinks_buf = sinks ? ggml_vk_tensor_subbuffer(ctx, sinks) : q_buf; vk_subbuffer mask_opt_buf = use_mask_opt ? ggml_vk_subbuffer(ctx, ctx->prealloc_y, 0) : q_buf; vk_subbuffer sparse_buf = use_sparse ? ggml_vk_subbuffer(ctx, ctx->prealloc_y, 0) : q_buf; - if (bias) { - mask_opt_buf = ggml_vk_tensor_subbuffer(ctx, bias); - sparse_buf = ggml_vk_tensor_subbuffer(ctx, dst->src[7]); - } if (use_mask_opt || use_sparse) { // the mask opt bits and the sparse index list overwrite a matmul input converted into prealloc_y ctx->prealloc_y_last_pipeline_used = nullptr; @@ -9567,16 +9548,6 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const mask_n_head_log2, m0, m1, gqa_ratio, split_kv, split_k }; - auto dispatch_fa = [&](const vk_subbuffer & out, std::array groups) { - if (rows) { - ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, - {q_buf, k_buf, v_buf, mask_buf, sinks_buf, out, mask_opt_buf, sparse_buf, ggml_vk_tensor_subbuffer(ctx, rows)}, pc, groups); - } else { - ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, - {q_buf, k_buf, v_buf, mask_buf, sinks_buf, out, mask_opt_buf, sparse_buf}, pc, groups); - } - }; - if (xe_fa_opt) { uint32_t head_stride_q = uint32_t(nbq2 / ggml_type_size(q->type)); uint32_t head_stride_k = uint32_t(nbk2 / ggml_type_size(k->type)); @@ -9648,7 +9619,9 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const } vk_subbuffer split_k_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0); - dispatch_fa(split_k_buf, { dispatch_x, workgroups_y, workgroups_z }); + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf, mask_opt_buf, sparse_buf}, + pc, { dispatch_x, workgroups_y, workgroups_z }); ggml_vk_sync_buffers(ctx, subctx); const vk_op_flash_attn_split_k_reduce_push_constants pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3, split_k, (sinks != nullptr) }; @@ -9661,7 +9634,9 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const // When using gqa, we want one actual workgroup per batch, so cancel out wg_denoms workgroups_x *= pipeline->wg_denoms[0]; } - dispatch_fa(dst_buf, { workgroups_x, workgroups_y, workgroups_z }); + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf, mask_opt_buf, sparse_buf}, + pc, { workgroups_x, workgroups_y, workgroups_z }); } if (use_dequant_kv) { @@ -16797,16 +16772,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm } case GGML_OP_FLASH_ATTN_EXT: { - // Only the indexed-bias scalar kernel reads row lists. - const bool indexed_bias = ggml_flash_attn_ext_has_indexed_bias(op); - if (op->src[5] && (!indexed_bias || device->properties.limits.maxPerStageDescriptorStorageBuffers < 9 || - device->properties.limits.maxDescriptorSetStorageBuffers < 9)) { - return false; - } - if (indexed_bias && (op->src[6]->ne[0] > 0x7fffff || !device->subgroup_shuffle || !device->subgroup_vote || - ggml_nelements(op->src[6]) > UINT32_MAX || ggml_nelements(op->src[7]) > UINT32_MAX || - op->src[1]->type != GGML_TYPE_F16 || op->src[2]->type != GGML_TYPE_F16 || - (op->src[1]->ne[0] != 64 && op->src[1]->ne[0] != 128) || op->src[1]->ne[0] != op->src[2]->ne[0])) { + if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) { return false; } bool coopmat2 = device->coopmat2; diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp index fe14ad570e1c..c1e4606cd916 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn.comp @@ -212,23 +212,9 @@ void main() { uint32_t r = (idx + tid) / Bc; if (idx + tid < Bc * Br) { uint32_t kcol; -#ifdef KV_ROWS - kcol = j * Bc + c; - bool kv_active = kcol < KV; -#else bool kv_active = fa_kv_index(j * Bc + c, kcol); -#endif if (kv_active && (!nem1_bounds_check || i * Br + r < p.nem1)) { FLOAT_TYPE m = FLOAT_TYPE(data_m[m_offset + (i * Br + r) * m_stride + kcol]); - const uint n_bins = (Flags & 0x7fffffffu) >> 8; - if (n_bins != 0) { - uint query = iq3 * p.N + i * Br + r; - uint bin = uint(data_sparse[query * KV + kcol]); - if (bin < n_bins) { - float bias = uintBitsToFloat(data_mask_opt[(query * p.neq2 + iq2) * n_bins + bin]); - m = FLOAT_TYPE(float16_t(float(m) + bias)); - } - } masksh[c * masksh_stride + r] = m; max_mask = max(max_mask, float(m)); } else { diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl index b6941af8be74..072edfa68cc7 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_base.glsl @@ -88,10 +88,6 @@ layout (binding = 5) writeonly buffer OV4 {D_TYPEV4 data_ov4[];}; layout (binding = 6) readonly buffer MO {uint32_t data_mask_opt[];}; -#ifdef KV_ROWS -layout (binding = 8) readonly buffer KR {int32_t data_kv_rows[];}; -#endif - layout (binding = 7) readonly buffer SP {int32_t data_sparse[];}; // Use -FLT_MAX/2 rather than -inf to reduce the possibility of NaNs, e.g. when computing Mold-M. @@ -241,15 +237,6 @@ void init_indices() // Resolve a linear KV slot to a real column; false for inactive (sparse padding/-1, or dense OOB). bool fa_kv_index(uint lin, out uint kv_col) { -#ifdef KV_ROWS - if (lin >= KV) { - kv_col = 0; - return false; - } - int row = data_kv_rows[iq3 * KV + lin]; - kv_col = uint(max(row, 0)); - return row >= 0; -#endif if (USE_SPARSE) { if (lin >= p.split_kv) { kv_col = 0; diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp index 718e4e849184..e20c94758900 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp @@ -749,11 +749,6 @@ void process_shaders() { #endif } - if (!f16acc) { - string_to_spv("flash_attn_f32_f16_rows", "flash_attn.comp", - merge_maps(fa_base_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}, {"KV_ROWS", "1"}}), fp16, false, false, false); - } - string_to_spv("flash_attn_f32_f16", "flash_attn.comp", merge_maps(fa_base_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}}), fp16, false, false, f16acc); From 6ed422257aa6f3af12331e340b343a3f69ec52db Mon Sep 17 00:00:00 2001 From: Xuan Son Nguyen Date: Sun, 22 Nov 2026 01:24:14 +0100 Subject: [PATCH 08/24] conversion --- conversion/inkling2.py | 163 ++++++++++++++++++++++++++++++++++++++ convert_hf_to_gguf.py | 7 +- gguf-py/gguf/constants.py | 22 +++++ 3 files changed, 190 insertions(+), 2 deletions(-) diff --git a/conversion/inkling2.py b/conversion/inkling2.py index 63e73a6d527f..0d64f8f8890f 100644 --- a/conversion/inkling2.py +++ b/conversion/inkling2.py @@ -329,6 +329,169 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter yield self.format_tensor_name(gguf.MODEL_TENSOR.LOOP_MSG_QUERY, start + i, ".weight"), query +def _fold_markov_chunk(unembed: Callable[[], Tensor], weight: Tensor | None, bias: Tensor | None, rows: slice) -> np.ndarray: + head = LazyTorchTensor.to_eager(unembed()[rows]).double() + out = head @ weight if weight is not None else head @ bias + return out.float().numpy() + + +class Inkling2DSparkModel(Inkling2Model): + """Inkling2 DSpark draft (mtp.safetensors) as a DFLASH GGUF, export with --dspark""" + model_arch = gguf.MODEL_ARCH.DFLASH + + _TARGET = { + "model.llm.unembed.weight": "target.unembed", + "model.language_model.unembed.weight": "target.unembed", + "lm_head.weight": "target.unembed", + "model.llm.embed_norm.weight": "target.embed_norm", + "model.language_model.embed_norm.weight": "target.embed_norm", + "model.language_model.embed_tokens.embed_norm.weight": "target.embed_norm", + } + + _LAYER = { + "self_attn.k_proj_ctx.weight": gguf.MODEL_TENSOR.DFLASH_ATTN_K_CTX, + "self_attn.v_proj_ctx.weight": gguf.MODEL_TENSOR.DFLASH_ATTN_V_CTX, + "self_attn.k_norm_ctx.weight": gguf.MODEL_TENSOR.DFLASH_ATTN_K_CTX_NORM, + "dflare_norm.weight": gguf.MODEL_TENSOR.DFLASH_CTX_NORM, + } + + _ROOT = { + "target.embed_norm": gguf.MODEL_TENSOR.TOKEN_EMBD_NORM, + "mtp.norm.weight": gguf.MODEL_TENSOR.OUTPUT_NORM, + "mtp.markov_head.markov_w1.weight": gguf.MODEL_TENSOR.DSPARK_MARKOV_W1, + "mtp.markov_head.rnn_proj.weight": gguf.MODEL_TENSOR.DSPARK_JOINT_PROJ, + "mtp.markov_head.rnn_proj.bias": gguf.MODEL_TENSOR.DSPARK_JOINT_PROJ, + "mtp.markov_head.dflare_norm.weight": gguf.MODEL_TENSOR.DSPARK_MARKOV_CTX_NORM, + } + + def __init__(self, *args, **kwargs): + self._folded: dict[str, gguf.LazyChunkedTensor] = {} + super().__init__(*args, **kwargs) + hp = self.hparams + mtp = hp.get("mtp_config") + if not mtp: + raise ValueError("Inkling2 DSpark export needs the mtp_config") + if mtp.get("markov_head_type") != "rnn_hidden" or mtp.get("q_bias") or mtp.get("o_bias") or mtp["hidden_size"] != hp["hidden_size"]: + raise ValueError(f"Inkling2 DSpark: unsupported mtp_config {mtp}") + # ids count loop passes, the last id is the final norm output + n_visits = self.block_count + if (loop := hp.get("loop_config")) is not None: + n_visits += (loop["num_passes"] - 1) * (loop["core_end"] - loop["core_start"]) + targets = mtp["target_layer_ids"] + if len(targets) < 2 or targets != sorted(set(targets)) or targets[-1] != n_visits: + raise ValueError(f"Inkling2 DSpark: target_layer_ids {targets} must be sorted and end at {n_visits}") + self.mtp = mtp + self.block_count = mtp["num_hidden_layers"] + self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count) + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + if remote_hf_model_id is not None: + raise NotImplementedError("Inkling2 DSpark export needs a local checkpoint") + # mtp.safetensors is not in the weight map, unembed and embed_norm come from the target + tensors = self.index_local_tensors("mtp") + tensors.update(self.index_local_tensors("model")) + return tensors + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + name, gen = item + if name in cls._TARGET: + return cls._TARGET[name], gen + if name.startswith(("model.", "lm_head.")): + return None + if name.startswith("layers."): + return f"model.{name}", gen + return f"mtp.{name}", gen + + def dequant_model(self): + super().dequant_model() + if "target.unembed" not in self.model_tensors: + raise ValueError("Inkling2 DSpark: missing the target unembed") + unembed = self.model_tensors.pop("target.unembed") + weight = LazyTorchTensor.to_eager(self.model_tensors.pop("mtp.markov_head.hidden_out.weight")()).double() + bias = LazyTorchTensor.to_eager(self.model_tensors.pop("mtp.markov_head.hidden_out.bias")()).double() + n_vocab, n_embd = unembed().shape + if weight.shape[0] != n_embd or bias.shape != (n_embd,): + raise ValueError(f"Inkling2 DSpark: hidden_out {tuple(weight.shape)} does not match unembed {(n_vocab, n_embd)}") + # markov_w2 = unembed @ hidden_out, fp64 like vLLM, one row chunk at a time + row_chunks = [slice(i, min(i + 4096, n_vocab)) for i in range(0, n_vocab, 4096)] + for name, w, b, shape in ( + ("mtp.markov_head.fold.weight", weight, None, (n_vocab, weight.shape[1])), + ("mtp.markov_head.fold.bias", None, bias, (n_vocab,)), + ): + self._folded[name] = gguf.LazyChunkedTensor([partial(_fold_markov_chunk, unembed, w, b, r) for r in row_chunks], shape, np.float32) + self.model_tensors[name] = lambda shape=shape: torch.empty(shape, dtype=torch.float32, device="meta") + + def prepare_metadata(self, vocab_only: bool): + from_dir = self.fname_out.is_dir() + super().prepare_metadata(vocab_only=vocab_only) + if from_dir: + self.fname_out = self.fname_out.parent / f"dspark-{self.fname_out.name}" + + def set_vocab(self): + super().set_vocab() + # block uses mask_embd, mask token id is not used + self.gguf_writer.add_mask_token_id(0) + + def set_gguf_parameters(self): + hp, mtp = self.hparams, self.mtp + n = self.block_count + w = self.gguf_writer + w.add_block_count(n) + w.add_vocab_size(hp["vocab_size"]) + w.add_vocab_size_unpadded(hp["unpadded_vocab_size"]) + w.add_context_length(mtp["max_position_embeddings"]) + w.add_embedding_length(mtp["hidden_size"]) + w.add_feed_forward_length(mtp["intermediate_size"]) + w.add_head_count(mtp["num_attention_heads"]) + w.add_head_count_kv(mtp["num_key_value_heads"]) + w.add_key_length(mtp["head_dim"]) + w.add_value_length(mtp["head_dim"]) + w.add_rope_dimension_count(mtp["head_dim"]) + w.add_rope_freq_base(float(mtp["rope_theta"])) + w.add_layer_norm_rms_eps(mtp["rms_norm_eps"]) + w.add_sliding_window(mtp["sliding_window_size"]) + w.add_sliding_window_pattern([i in mtp["local_layer_ids"] for i in range(n)]) + w.add_final_logit_softcapping(hp["final_logit_softcapping"]) + w.add_block_size(mtp["block_size"]) + w.add_target_layers(mtp["target_layer_ids"]) + # slot 0 is the anchor, it does not predict a token + w.add_sample_from_anchor(False) + w.add_has_confidence_head(False) + w.add_file_type(self.ftype) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + if name in self._folded: + suffix = ".bias" if name.endswith(".bias") else ".weight" + yield self.format_tensor_name(gguf.MODEL_TENSOR.DSPARK_MARKOV_W2, None, suffix), cast("Tensor", self._folded[name]) + return + if name in self._ROOT: + suffix = ".bias" if name.endswith(".bias") else ".weight" + yield self.format_tensor_name(self._ROOT[name], None, suffix), data_torch + return + if name == "mtp.fuse_weight": + if tuple(data_torch.shape) != (self.block_count + 1, len(self.mtp["target_layer_ids"])): + raise ValueError(f"Inkling2 DSpark: unexpected fuse_weight shape {tuple(data_torch.shape)}") + # one row per draft layer, the last row is for the markov head + alpha = torch.softmax(data_torch.float(), dim=-1) + for i in range(self.block_count): + yield self.format_tensor_name(gguf.MODEL_TENSOR.DFLASH_CTX_MIX, i), alpha[i] + yield self.format_tensor_name(gguf.MODEL_TENSOR.DSPARK_MARKOV_CTX_MIX), alpha[-1] + return + if name == "mtp.mask_embed": + # copy the one mask embedding to each mask slot + yield self.format_tensor_name(gguf.MODEL_TENSOR.DSPARK_MASK_EMBD), data_torch.unsqueeze(0).expand(self.mtp["block_size"] - 1, -1).contiguous() + return + if name.startswith("mtp."): + raise ValueError(f"Inkling2 DSpark: unexpected tensor {name!r}") + assert bid is not None + key = name.removeprefix(f"model.layers.{bid}.") + if key in self._LAYER: + yield self.format_tensor_name(self._LAYER[key], bid), data_torch + return + yield from TextModel.modify_tensors(self, data_torch, name, bid) + + @ModelBase.register("Inkling2ForConditionalGeneration", "Inkling2LoopForConditionalGeneration") class Inkling2VisionModel(MmprojModel): def get_vision_config(self): diff --git a/convert_hf_to_gguf.py b/convert_hf_to_gguf.py index 8cee1f8646e1..11fa4a353cd8 100755 --- a/convert_hf_to_gguf.py +++ b/convert_hf_to_gguf.py @@ -136,7 +136,7 @@ def parse_args() -> argparse.Namespace: ) parser.add_argument( "--dspark", action="store_true", - help="Export only the DeepSeek-V4 or Mistral Large 4 DSpark draft tensors as a separate GGUF.", + help="Export only the DeepSeek-V4, Mistral Large 4 or Inkling 2 DSpark draft tensors as a separate GGUF.", ) parser.add_argument( "--mistral-format", action="store_true", @@ -289,8 +289,11 @@ def main() -> None: sys.exit(1) from conversion.mistral4 import MistralLarge4DSparkModel model_class = MistralLarge4DSparkModel + elif model_architecture in ("Inkling2ForConditionalGeneration", "Inkling2ForCausalLM", "Inkling2LoopForConditionalGeneration", "Inkling2LoopForCausalLM"): + from conversion.inkling2 import Inkling2DSparkModel + model_class = Inkling2DSparkModel elif model_architecture not in ("DeepseekV4ForCausalLM", "DeepseekV41ForCausalLM"): - logger.error("--dspark is only supported for DeepseekV4ForCausalLM, DeepseekV41ForCausalLM and Mistral Large 4") + logger.error("--dspark is only supported for DeepseekV4ForCausalLM, DeepseekV41ForCausalLM, Mistral Large 4 and Inkling 2") sys.exit(1) elif model_architecture == "DeepseekV41ForCausalLM": from conversion.deepseek41 import DeepseekV41DSparkModel diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index 0592f5e016f5..d8cdac689467 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -1536,6 +1536,8 @@ class MODEL_TENSOR(IntEnum): DSPARK_CONF_PROJ = auto() # confidence head DSPARK_JOINT_PROJ = auto() # rnn markov head DSPARK_MASK_EMBD = auto() # per-slot mask embeddings + DSPARK_MARKOV_CTX_MIX = auto() # rnn markov head: target feature mix + DSPARK_MARKOV_CTX_NORM = auto() # rnn markov head: target feature norm ENGRAM_KV = auto() ENGRAM_GATE = auto() DFLASH_ATTN_CONV_BASE = auto() @@ -1545,6 +1547,11 @@ class MODEL_TENSOR(IntEnum): DFLASH_SELECTOR_PREV = auto() DFLASH_SELECTOR_NEXT = auto() DFLASH_SELECTOR_HIDDEN = auto() + DFLASH_CTX_MIX = auto() # per-layer target feature mix + DFLASH_CTX_NORM = auto() # per-layer target feature norm + DFLASH_ATTN_K_CTX = auto() # per-layer context K projection + DFLASH_ATTN_V_CTX = auto() # per-layer context V projection + DFLASH_ATTN_K_CTX_NORM = auto() LILICORR_TOKEN_PROJ = auto() LILICORR_PASS_HIDDEN_PROJ = auto() LILICORR_SLOT_EMBD = auto() @@ -2590,6 +2597,8 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.DSPARK_CONF_PROJ: "conf_proj", MODEL_TENSOR.DSPARK_JOINT_PROJ: "joint_proj", MODEL_TENSOR.DSPARK_MASK_EMBD: "mask_embd", + MODEL_TENSOR.DSPARK_MARKOV_CTX_MIX: "markov_ctx_mix", + MODEL_TENSOR.DSPARK_MARKOV_CTX_NORM: "markov_ctx_norm", MODEL_TENSOR.ENGRAM_KV: "blk.{bid}.engram_kv", MODEL_TENSOR.ENGRAM_GATE: "blk.{bid}.engram_gate", MODEL_TENSOR.DFLASH_ATTN_CONV_BASE: "blk.{bid}.attn_conv_base", @@ -2599,6 +2608,11 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.DFLASH_SELECTOR_PREV: "selector_predecessor", MODEL_TENSOR.DFLASH_SELECTOR_NEXT: "selector_successor", MODEL_TENSOR.DFLASH_SELECTOR_HIDDEN: "selector_hidden", + MODEL_TENSOR.DFLASH_CTX_MIX: "blk.{bid}.ctx_mix", + MODEL_TENSOR.DFLASH_CTX_NORM: "blk.{bid}.ctx_norm", + MODEL_TENSOR.DFLASH_ATTN_K_CTX: "blk.{bid}.attn_k_ctx", + MODEL_TENSOR.DFLASH_ATTN_V_CTX: "blk.{bid}.attn_v_ctx", + MODEL_TENSOR.DFLASH_ATTN_K_CTX_NORM: "blk.{bid}.attn_k_ctx_norm", MODEL_TENSOR.LILICORR_TOKEN_PROJ: "lilicorr.token_proj", MODEL_TENSOR.LILICORR_PASS_HIDDEN_PROJ: "lilicorr.pass_hidden_proj", MODEL_TENSOR.LILICORR_SLOT_EMBD: "lilicorr.slot_embedding", @@ -6461,6 +6475,7 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.LAYER_OUT_SCALE, MODEL_TENSOR.ROPE_FREQS, MODEL_TENSOR.TOKEN_EMBD, + MODEL_TENSOR.TOKEN_EMBD_NORM, MODEL_TENSOR.OUTPUT, MODEL_TENSOR.OUTPUT_NORM, MODEL_TENSOR.ATTN_NORM, @@ -6512,6 +6527,8 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.DSPARK_CONF_PROJ, MODEL_TENSOR.DSPARK_JOINT_PROJ, MODEL_TENSOR.DSPARK_MASK_EMBD, + MODEL_TENSOR.DSPARK_MARKOV_CTX_MIX, + MODEL_TENSOR.DSPARK_MARKOV_CTX_NORM, MODEL_TENSOR.DFLASH_ATTN_CONV_BASE, MODEL_TENSOR.DFLASH_ATTN_CONV_PROJ, MODEL_TENSOR.DFLASH_FFN_CONV_BASE, @@ -6519,6 +6536,11 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.DFLASH_SELECTOR_PREV, MODEL_TENSOR.DFLASH_SELECTOR_NEXT, MODEL_TENSOR.DFLASH_SELECTOR_HIDDEN, + MODEL_TENSOR.DFLASH_CTX_MIX, + MODEL_TENSOR.DFLASH_CTX_NORM, + MODEL_TENSOR.DFLASH_ATTN_K_CTX, + MODEL_TENSOR.DFLASH_ATTN_V_CTX, + MODEL_TENSOR.DFLASH_ATTN_K_CTX_NORM, MODEL_TENSOR.LILICORR_TOKEN_PROJ, MODEL_TENSOR.LILICORR_PASS_HIDDEN_PROJ, MODEL_TENSOR.LILICORR_SLOT_EMBD, From 8ccecab8b621db69c8adb891a06b4d8f5078aeeb Mon Sep 17 00:00:00 2001 From: Xuan Son Nguyen Date: Sun, 22 Nov 2026 03:21:26 +0100 Subject: [PATCH 09/24] init cpp side --- common/speculative.cpp | 89 ++++++++++++++++-- conversion/inkling2.py | 10 ++- gguf-py/gguf/constants.py | 1 + gguf-py/gguf/gguf_writer.py | 3 + src/llama-arch.cpp | 14 +++ src/llama-arch.h | 7 ++ src/llama-batch.cpp | 3 + src/llama-hparams.h | 1 + src/llama-model.h | 10 +++ src/models/dflash.cpp | 169 ++++++++++++++++++++++++++++------- src/models/dspark.cpp | 68 ++++++++++++-- src/models/inkling2-loop.cpp | 8 ++ src/models/inkling2.cpp | 5 ++ src/models/models.h | 3 + 14 files changed, 345 insertions(+), 46 deletions(-) diff --git a/common/speculative.cpp b/common/speculative.cpp index b40eb5535f73..1f5fe72a3340 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -1140,8 +1140,8 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { llama_set_causal_attn(ctx_dft, causal_attn); // DFlash needs non-causal attention unless the model says otherwise } - // only LiliCorr uses this, to keep the context features for its scorer; the other heads only need the KV cache - // called after the host copy injection of a chunk, while h_nextn still holds the context features of batch_inject + // LiliCorr and the Inkling2 DSpark keep context features from h_nextn; the other heads only need the KV cache + // called after the injection of a chunk, while h_nextn still holds the context features of batch_inject virtual void store_context_features(llama_seq_id /*seq_id*/, int32_t /*n_chunk*/) {} public: @@ -1245,6 +1245,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { __func__, rc, (int) n_chunk, (int) offset); return false; } + store_context_features(seq_id, n_chunk); continue; } @@ -1374,6 +1375,13 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im // bonus anchor (SpecForge exports) when false: slot 0 is a bonus token, not a prediction slot bool sample_from_anchor = true; + // the Markov head reads the context state of the last committed token (Inkling2 f_rnn) + // it comes back from the injection as h_nextn, kept for the last ctx_rows positions of each sequence + bool has_markov_context = false; + size_t ctx_rows = 0; + std::vector ctx_embd; + std::vector ctx_pos; + common_speculative_impl_draft_dspark(const common_params_speculative & params, uint32_t n_seq) : common_speculative_impl_draft_dflash(params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK) { @@ -1384,6 +1392,15 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im if (llama_model_meta_val_str(model_dft, "dflash.sample_from_anchor", buf, sizeof(buf)) >= 0) { sample_from_anchor = std::strcmp(buf, "true") == 0; } + if (llama_model_meta_val_str(model_dft, "dflash.has_markov_context", buf, sizeof(buf)) >= 0) { + has_markov_context = std::strcmp(buf, "true") == 0; + } + } + + if (has_markov_context) { + ctx_rows = (size_t) block_size + 1; + ctx_embd.resize((size_t) n_seq * ctx_rows * (size_t) n_embd_dec); + ctx_pos.assign((size_t) n_seq * ctx_rows, -1); } if (this->params.p_min > 0.0f) { @@ -1396,17 +1413,51 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im } } - LOG_INF("%s: - sample_from_anchor=%s\n", __func__, sample_from_anchor ? "true" : "false"); + LOG_INF("%s: - sample_from_anchor=%s, has_markov_context=%s\n", __func__, + sample_from_anchor ? "true" : "false", has_markov_context ? "true" : "false"); // anchor-first DSpark yields a full block_size draft tokens + // the context state is read back from h_nextn at every injected row init({ /* .n_draft_max = */ sample_from_anchor ? block_size : block_size - 1, /* .backend_sampling = */ true, /* .dev_features = */ true, - /* .nextn_masked = */ true, + /* .nextn_masked = */ !has_markov_context, }); } +protected: + void store_context_features(llama_seq_id seq_id, int32_t n_chunk) override { + if (!has_markov_context) { + return; + } + const float * state = llama_get_embeddings_nextn(params.ctx_dft); + if (!state) { + return; + } + const llama_pos pos_min = std::max(0, batch_inject.tokens.back().pos[0] - block_size); + for (int32_t i = 0; i < n_chunk; ++i) { + const llama_pos pos = batch_inject.tokens[i].pos[0]; + if (pos < pos_min) { + continue; + } + const size_t slot = (size_t) seq_id * ctx_rows + (size_t) pos % ctx_rows; + std::memcpy(ctx_embd.data() + slot * (size_t) n_embd_dec, state + (size_t) i * n_embd_dec, (size_t) n_embd_dec * sizeof(float)); + ctx_pos[slot] = pos; + } + } + + // context state of the token before the block, nullptr if it was not injected + const float * get_context_state(llama_seq_id seq_id, llama_pos pos) const { + if (pos < 0) { + return nullptr; + } + const size_t slot = (size_t) seq_id * ctx_rows + (size_t) pos % ctx_rows; + return ctx_pos[slot] == pos ? ctx_embd.data() + slot * (size_t) n_embd_dec : nullptr; + } + +public: + void draft(common_speculative_draft_params_vec & dparams) override { auto & ctx_dft = params.ctx_dft; @@ -1423,16 +1474,26 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im continue; } + // the Markov head reads the context state of the token before the block, no draft without it + const float * state = has_markov_context ? get_context_state(seq_id, dp.pos0 - 1) : nullptr; + if (has_markov_context && !state) { + continue; + } + common_sampler_reset(smpls[seq_id].get()); const int32_t n = (int32_t) dp.pos0; + // the block attention is non-causal: a draft with a markov context decodes the full trained block, then reads n_max of it const int32_t n_draft = params.n_max; - const int32_t n_block_tokens = n_draft + (sample_from_anchor ? 0 : 1); + const int32_t n_block_tokens = has_markov_context ? block_size : n_draft + (sample_from_anchor ? 0 : 1); i_block_beg[seq_id] = batch.size(); n_block [seq_id] = n_block_tokens; for (int32_t i = 0; i < n_block_tokens; ++i) { - batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, true); + const int32_t idx = batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, true); + if (state) { + batch.set_embd_state(idx, { state, 1, (size_t) n_embd_dec }); + } } } @@ -1464,7 +1525,8 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im const float * conf = params.p_min > 0.0f ? llama_get_embeddings_nextn(ctx_dft) : nullptr; // bonus-anchor drafts read the mask positions only, like DFlash const int32_t i_draft_beg = sample_from_anchor ? 0 : 1; - for (int32_t i = i_draft_beg; i < n_block_tokens; ++i) { + const int32_t i_draft_end = std::min(n_block_tokens, i_draft_beg + params.n_max); + for (int32_t i = i_draft_beg; i < i_draft_end; ++i) { const int32_t idx = beg + i; if (conf && conf[(size_t) idx * n_embd_dec] < params.p_min) { @@ -3136,6 +3198,19 @@ common_speculative_init_result::common_speculative_init_result( pimpl->model.reset(model_dft); + // a draft with a markov context decodes its full trained block, whatever n_max is + { + char buf[32] = {}; + if (llama_model_meta_val_str(model_dft, "dflash.has_markov_context", buf, sizeof(buf)) >= 0 && std::strcmp(buf, "true") == 0 && + llama_model_meta_val_str(model_dft, "dflash.block_size", buf, sizeof(buf)) >= 0) { + const uint32_t block_size = (uint32_t) std::max(1, std::atoi(buf)); + cparams.n_outputs_max = std::max(cparams.n_outputs_max, cparams.n_seq_max * block_size); + if (cparams.n_outputs_max_per_seq > 1) { + cparams.n_outputs_max_per_seq = std::max(cparams.n_outputs_max_per_seq, block_size); + } + } + } + llama_context * ctx_dft = llama_init_from_model(model_dft, cparams); if (ctx_dft == nullptr) { LOG_ERR("%s: failed to create MTP context\n", __func__); diff --git a/conversion/inkling2.py b/conversion/inkling2.py index 0d64f8f8890f..ce92459181df 100644 --- a/conversion/inkling2.py +++ b/conversion/inkling2.py @@ -414,6 +414,8 @@ def dequant_model(self): if weight.shape[0] != n_embd or bias.shape != (n_embd,): raise ValueError(f"Inkling2 DSpark: hidden_out {tuple(weight.shape)} does not match unembed {(n_vocab, n_embd)}") # markov_w2 = unembed @ hidden_out, fp64 like vLLM, one row chunk at a time + # padded tokens are never sampled, so keep only the tokenizer rows + n_vocab = self.hparams["unpadded_vocab_size"] row_chunks = [slice(i, min(i + 4096, n_vocab)) for i in range(0, n_vocab, 4096)] for name, w, b, shape in ( ("mtp.markov_head.fold.weight", weight, None, (n_vocab, weight.shape[1])), @@ -438,8 +440,6 @@ def set_gguf_parameters(self): n = self.block_count w = self.gguf_writer w.add_block_count(n) - w.add_vocab_size(hp["vocab_size"]) - w.add_vocab_size_unpadded(hp["unpadded_vocab_size"]) w.add_context_length(mtp["max_position_embeddings"]) w.add_embedding_length(mtp["hidden_size"]) w.add_feed_forward_length(mtp["intermediate_size"]) @@ -450,7 +450,8 @@ def set_gguf_parameters(self): w.add_rope_dimension_count(mtp["head_dim"]) w.add_rope_freq_base(float(mtp["rope_theta"])) w.add_layer_norm_rms_eps(mtp["rms_norm_eps"]) - w.add_sliding_window(mtp["sliding_window_size"]) + # the block sees W positions before the anchor, llama.cpp SWA sees n_swa - 1 + w.add_sliding_window(mtp["sliding_window_size"] + 1) w.add_sliding_window_pattern([i in mtp["local_layer_ids"] for i in range(n)]) w.add_final_logit_softcapping(hp["final_logit_softcapping"]) w.add_block_size(mtp["block_size"]) @@ -458,6 +459,7 @@ def set_gguf_parameters(self): # slot 0 is the anchor, it does not predict a token w.add_sample_from_anchor(False) w.add_has_confidence_head(False) + w.add_has_markov_context(True) w.add_file_type(self.ftype) def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: @@ -465,6 +467,8 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter suffix = ".bias" if name.endswith(".bias") else ".weight" yield self.format_tensor_name(gguf.MODEL_TENSOR.DSPARK_MARKOV_W2, None, suffix), cast("Tensor", self._folded[name]) return + if name == "mtp.markov_head.markov_w1.weight": + data_torch = data_torch[:self.hparams["unpadded_vocab_size"]] if name in self._ROOT: suffix = ".bias" if name.endswith(".bias") else ".weight" yield self.format_tensor_name(self._ROOT[name], None, suffix), data_torch diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index d8cdac689467..57852fad6bcf 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -177,6 +177,7 @@ class LLM: SELECTOR_TOP_K = "{arch}.selector_top_k" SAMPLE_FROM_ANCHOR = "{arch}.sample_from_anchor" HAS_CONFIDENCE_HEAD = "{arch}.has_confidence_head" + HAS_MARKOV_CONTEXT = "{arch}.has_markov_context" NORM_BEFORE_RESIDUAL = "{arch}.norm_before_residual" NORM_BEFORE_FC = "{arch}.norm_before_fc" REALTIME_DELAY_TOKENS = "{arch}.realtime_delay_tokens" diff --git a/gguf-py/gguf/gguf_writer.py b/gguf-py/gguf/gguf_writer.py index 08c8d2f33c15..900aef6141a3 100644 --- a/gguf-py/gguf/gguf_writer.py +++ b/gguf-py/gguf/gguf_writer.py @@ -1110,6 +1110,9 @@ def add_sample_from_anchor(self, value: bool) -> None: def add_has_confidence_head(self, value: bool) -> None: self.add_bool(Keys.LLM.HAS_CONFIDENCE_HEAD.format(arch=self.arch), value) + def add_has_markov_context(self, value: bool) -> None: + self.add_bool(Keys.LLM.HAS_MARKOV_CONTEXT.format(arch=self.arch), value) + def add_target_layers(self, value: Sequence[int]) -> None: self.add_array(Keys.LLM.TARGET_LAYERS.format(arch=self.arch), value) diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index cdb1f3794fe1..b8eb39fb2f8e 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -913,6 +913,8 @@ static const std::map LLM_TENSOR_NAMES = { { LLM_TENSOR_DSPARK_CONF_PROJ, "conf_proj" }, { LLM_TENSOR_DSPARK_JOINT_PROJ, "joint_proj" }, { LLM_TENSOR_DSPARK_MASK_EMBD, "mask_embd" }, + { LLM_TENSOR_DSPARK_MARKOV_CTX_MIX, "markov_ctx_mix" }, + { LLM_TENSOR_DSPARK_MARKOV_CTX_NORM, "markov_ctx_norm" }, { LLM_TENSOR_ENGRAM_KV, "blk.%d.engram_kv" }, { LLM_TENSOR_ENGRAM_GATE, "blk.%d.engram_gate" }, { LLM_TENSOR_DFLASH_ATTN_CONV_BASE, "blk.%d.attn_conv_base" }, @@ -922,6 +924,11 @@ static const std::map LLM_TENSOR_NAMES = { { LLM_TENSOR_DFLASH_SELECTOR_PREV, "selector_predecessor" }, { LLM_TENSOR_DFLASH_SELECTOR_NEXT, "selector_successor" }, { LLM_TENSOR_DFLASH_SELECTOR_HIDDEN, "selector_hidden" }, + { LLM_TENSOR_DFLASH_CTX_MIX, "blk.%d.ctx_mix" }, + { LLM_TENSOR_DFLASH_CTX_NORM, "blk.%d.ctx_norm" }, + { LLM_TENSOR_DFLASH_ATTN_K_CTX, "blk.%d.attn_k_ctx" }, + { LLM_TENSOR_DFLASH_ATTN_V_CTX, "blk.%d.attn_v_ctx" }, + { LLM_TENSOR_DFLASH_ATTN_K_CTX_NORM, "blk.%d.attn_k_ctx_norm" }, { LLM_TENSOR_LILICORR_TOKEN_PROJ, "lilicorr.token_proj" }, { LLM_TENSOR_LILICORR_PASS_HIDDEN_PROJ, "lilicorr.pass_hidden_proj" }, { LLM_TENSOR_LILICORR_SLOT_EMBD, "lilicorr.slot_embedding" }, @@ -1340,6 +1347,8 @@ static const std::map LLM_TENSOR_INFOS = { {LLM_TENSOR_DSPARK_CONF_PROJ, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, {LLM_TENSOR_DSPARK_JOINT_PROJ, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, {LLM_TENSOR_DSPARK_MASK_EMBD, {LLM_TENSOR_LAYER_INPUT, GGML_OP_GET_ROWS}}, + {LLM_TENSOR_DSPARK_MARKOV_CTX_MIX, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_DSPARK_MARKOV_CTX_NORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}}, {LLM_TENSOR_ENGRAM_KV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_ENGRAM_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, {LLM_TENSOR_DFLASH_ATTN_CONV_BASE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, @@ -1349,6 +1358,11 @@ static const std::map LLM_TENSOR_INFOS = { {LLM_TENSOR_DFLASH_SELECTOR_PREV, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_GET_ROWS}}, {LLM_TENSOR_DFLASH_SELECTOR_NEXT, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_GET_ROWS}}, {LLM_TENSOR_DFLASH_SELECTOR_HIDDEN, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_DFLASH_CTX_MIX, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_DFLASH_CTX_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, + {LLM_TENSOR_DFLASH_ATTN_K_CTX, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_DFLASH_ATTN_V_CTX, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_DFLASH_ATTN_K_CTX_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, {LLM_TENSOR_LILICORR_TOKEN_PROJ, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, {LLM_TENSOR_LILICORR_PASS_HIDDEN_PROJ, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, {LLM_TENSOR_LILICORR_SLOT_EMBD, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_ADD}}, diff --git a/src/llama-arch.h b/src/llama-arch.h index 6517a3ea7ea9..54c2c8f8251a 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -918,6 +918,8 @@ enum llm_tensor { LLM_TENSOR_DSPARK_CONF_PROJ, LLM_TENSOR_DSPARK_JOINT_PROJ, LLM_TENSOR_DSPARK_MASK_EMBD, + LLM_TENSOR_DSPARK_MARKOV_CTX_MIX, + LLM_TENSOR_DSPARK_MARKOV_CTX_NORM, LLM_TENSOR_ENGRAM_KV, LLM_TENSOR_ENGRAM_GATE, LLM_TENSOR_DFLASH_ATTN_CONV_BASE, @@ -927,6 +929,11 @@ enum llm_tensor { LLM_TENSOR_DFLASH_SELECTOR_PREV, LLM_TENSOR_DFLASH_SELECTOR_NEXT, LLM_TENSOR_DFLASH_SELECTOR_HIDDEN, + LLM_TENSOR_DFLASH_CTX_MIX, + LLM_TENSOR_DFLASH_CTX_NORM, + LLM_TENSOR_DFLASH_ATTN_K_CTX, + LLM_TENSOR_DFLASH_ATTN_V_CTX, + LLM_TENSOR_DFLASH_ATTN_K_CTX_NORM, LLM_TENSOR_LILICORR_TOKEN_PROJ, LLM_TENSOR_LILICORR_PASS_HIDDEN_PROJ, LLM_TENSOR_LILICORR_SLOT_EMBD, diff --git a/src/llama-batch.cpp b/src/llama-batch.cpp index ca3e308f4e90..13efac363ccc 100644 --- a/src/llama-batch.cpp +++ b/src/llama-batch.cpp @@ -1219,6 +1219,9 @@ size_t llama_batch_ext_select_n_embd_state(llama_context_type ctx_type, const ll if (hparams.lilicorr_candidate_topk > 0) { return hparams.n_embd_inp(); } + if (hparams.dspark_f_rnn) { + return hparams.n_embd; + } return 0; } diff --git a/src/llama-hparams.h b/src/llama-hparams.h index 642f901186ba..b6a373bfe5cf 100644 --- a/src/llama-hparams.h +++ b/src/llama-hparams.h @@ -304,6 +304,7 @@ struct llama_hparams { uint32_t dflash_conv_group_size = 0; uint32_t dflash_selector_rank = 0; uint32_t dflash_selector_top_k = 0; + bool dspark_f_rnn = false; // rnn markov head reads f_rnn from embd_state uint32_t lilicorr_hidden_size = 0; uint32_t lilicorr_candidate_topk = 0; uint32_t lilicorr_num_heads = 0; diff --git a/src/llama-model.h b/src/llama-model.h index eae5c68486ab..c4ac3331c5ec 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -424,6 +424,13 @@ struct llama_layer { struct ggml_tensor * dflash_ffn_conv_base = nullptr; struct ggml_tensor * dflash_ffn_conv_proj = nullptr; + // per-layer context K/V from mixed target features (Inkling2 DSpark) + struct ggml_tensor * dflash_ctx_mix = nullptr; + struct ggml_tensor * dflash_ctx_norm = nullptr; + struct ggml_tensor * dflash_wk_ctx = nullptr; + struct ggml_tensor * dflash_wv_ctx = nullptr; + struct ggml_tensor * dflash_attn_k_ctx_norm = nullptr; + struct ggml_tensor * lilicorr_attn_norm = nullptr; struct ggml_tensor * lilicorr_mlp_norm = nullptr; struct ggml_tensor * lilicorr_attn_in_proj = nullptr; @@ -939,6 +946,9 @@ struct llama_model { struct ggml_tensor * dspark_joint_proj = nullptr; // rnn markov head struct ggml_tensor * dspark_joint_proj_b = nullptr; struct ggml_tensor * dspark_mask_embd = nullptr; // per-slot mask embeddings + struct ggml_tensor * dspark_markov_w2_b = nullptr; + struct ggml_tensor * dspark_markov_ctx_mix = nullptr; // rnn markov head: f_rnn from target features + struct ggml_tensor * dspark_markov_ctx_norm = nullptr; // zaya1 struct ggml_tensor * res_scale_in = nullptr; diff --git a/src/models/dflash.cpp b/src/models/dflash.cpp index 98a8d1d9acec..fbc0a63b69fd 100644 --- a/src/models/dflash.cpp +++ b/src/models/dflash.cpp @@ -41,6 +41,7 @@ void llama_model_dflash::load_arch_hparams(llama_model_loader & ml) { const bool has_lilicorr = ml.get_key(LLM_KV_LILICORR_HIDDEN_SIZE, hparams.lilicorr_hidden_size, false); if (has_markov) { variant = VARIANT_DSPARK; + hparams.dspark_f_rnn = ml.get_tensor_meta("markov_ctx_norm.weight") != nullptr; } else if (has_selector) { variant = VARIANT_DFLASH2; } else if (has_lilicorr) { @@ -107,12 +108,18 @@ void llama_model_dflash::load_arch_tensors(llama_model_loader &) { case VARIANT_DFLASH: break; } - fc = create_tensor(tn(LLM_TENSOR_FC, "weight"), { n_embd_inp, n_embd }, 0); + // drafts with per-layer context K/V (ctx_mix) have no shared fc + const int fc_flags = ml->get_tensor_meta("blk.0.ctx_mix.weight") ? TENSOR_NOT_REQUIRED : 0; + + fc = create_tensor(tn(LLM_TENSOR_FC, "weight"), { n_embd_inp, n_embd }, fc_flags); fc_s = create_tensor(tn(LLM_TENSOR_FC, "scale"), { 1 }, TENSOR_NOT_REQUIRED); fc_in_s = create_tensor(tn(LLM_TENSOR_FC, "input_scale"), { 1 }, TENSOR_NOT_REQUIRED); - output_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), { n_embd }, 0); // encoder hidden_norm (after fc) + output_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), { n_embd }, fc_flags); // encoder hidden_norm (after fc) output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd }, 0); // decoder final norm + // optional: norm of the anchor embedding + tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight", 0), { n_embd }, TENSOR_NOT_REQUIRED); + // optional: reduced-vocab drafts ship their own lm head, full-vocab drafts can share the target's via ctx_other // a draft with its own embeddings + head references no target tensors and can run on devices the target does not use (e.g. -devd with a tensor-split target) output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab_draft }, TENSOR_NOT_REQUIRED); @@ -167,6 +174,15 @@ void llama_model_dflash::load_tensors_layers_base() { layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), { n_embd, n_ff }, 0); layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd }, 0); layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), { n_embd, n_ff }, 0); + + // optional: context K/V from this layer's own mix of the target features + layer.dflash_ctx_mix = create_tensor(tn(LLM_TENSOR_DFLASH_CTX_MIX, "weight", i), { (int64_t) target_layer_ids.size() }, TENSOR_NOT_REQUIRED); + if (layer.dflash_ctx_mix) { + layer.dflash_ctx_norm = create_tensor(tn(LLM_TENSOR_DFLASH_CTX_NORM, "weight", i), { n_embd }, 0); + layer.dflash_wk_ctx = create_tensor(tn(LLM_TENSOR_DFLASH_ATTN_K_CTX, "weight", i), { n_embd, n_embd_k_gqa }, 0); + layer.dflash_wv_ctx = create_tensor(tn(LLM_TENSOR_DFLASH_ATTN_V_CTX, "weight", i), { n_embd, n_embd_v_gqa }, 0); + layer.dflash_attn_k_ctx_norm = create_tensor(tn(LLM_TENSOR_DFLASH_ATTN_K_CTX_NORM, "weight", i), { n_embd_head_k }, 0); + } } } @@ -295,8 +311,46 @@ ggml_tensor * llama_model_dflash::graph_base::build_rope(ggml_tensor * cur, ggml ext_factor, attn_factor, beta_fast, beta_slow); } +// write one layer's injected K/V to its (sub-)cache +void llama_model_dflash::graph_base::store_inject_kv(ggml_tensor * Kcur, ggml_tensor * Vcur, int il) { + if (use_iswa) { + // route each layer's K/V to its sub-cache: SWA layers -> sliding cache, full -> dense + const bool is_swa = hparams.is_swa(il); + const auto * kv = is_swa ? inp_attn_iswa->mctx->get_swa() : inp_attn_iswa->mctx->get_base(); + ggml_tensor * k_idxs = is_swa ? inp_attn_iswa->get_k_idxs_swa() : inp_attn_iswa->get_k_idxs(); + ggml_tensor * v_idxs = is_swa ? inp_attn_iswa->get_v_idxs_swa() : inp_attn_iswa->get_v_idxs(); + // rotate K/V into the cache's rotated space + ggml_tensor * k_rot = is_swa ? inp_attn_iswa->self_k_rot_swa[il] : inp_attn_iswa->self_k_rot[il]; + ggml_tensor * v_rot = is_swa ? inp_attn_iswa->self_v_rot_swa[il] : inp_attn_iswa->self_v_rot[il]; + if (k_rot) { + Kcur = llama_mul_mat_hadamard(ctx0, Kcur, k_rot); + } + if (v_rot) { + Vcur = llama_mul_mat_hadamard(ctx0, Vcur, v_rot); + } + ggml_build_forward_expand(gf, kv->cpy_k(ctx0, Kcur, k_idxs, il)); + ggml_build_forward_expand(gf, kv->cpy_v(ctx0, Vcur, v_idxs, il)); + } else { + // rotate K/V into the cache's rotated space + if (inp_attn->self_k_rot[il]) { + Kcur = llama_mul_mat_hadamard(ctx0, Kcur, inp_attn->self_k_rot[il]); + } + if (inp_attn->self_v_rot[il]) { + Vcur = llama_mul_mat_hadamard(ctx0, Vcur, inp_attn->self_v_rot[il]); + } + ggml_build_forward_expand(gf, inp_attn->mctx->cpy_k(ctx0, Kcur, inp_attn->get_k_idxs(), il)); + ggml_build_forward_expand(gf, inp_attn->mctx->cpy_v(ctx0, Vcur, inp_attn->get_v_idxs(), il)); + } +} + // KV cache injection ggml_tensor * llama_model_dflash::graph_base::build_inject() { + // drafts without fc: each layer mixes the raw target features itself + if (!model.fc) { + build_inject_ctx_mix(); + return nullptr; + } + ggml_tensor * inp_g = build_inject_inp(*this, model); cb(inp_g, "inp_g_embeddings", -1); @@ -318,34 +372,7 @@ ggml_tensor * llama_model_dflash::graph_base::build_inject() { cb(Kcur, "Kcur_injected", il); cb(Vcur, "Vcur_injected", il); - if (use_iswa) { - // route each layer's K/V to its sub-cache: SWA layers -> sliding cache, full -> dense - const bool is_swa = hparams.is_swa(il); - const auto * kv = is_swa ? inp_attn_iswa->mctx->get_swa() : inp_attn_iswa->mctx->get_base(); - ggml_tensor * k_idxs = is_swa ? inp_attn_iswa->get_k_idxs_swa() : inp_attn_iswa->get_k_idxs(); - ggml_tensor * v_idxs = is_swa ? inp_attn_iswa->get_v_idxs_swa() : inp_attn_iswa->get_v_idxs(); - // rotate K/V into the cache's rotated space - ggml_tensor * k_rot = is_swa ? inp_attn_iswa->self_k_rot_swa[il] : inp_attn_iswa->self_k_rot[il]; - ggml_tensor * v_rot = is_swa ? inp_attn_iswa->self_v_rot_swa[il] : inp_attn_iswa->self_v_rot[il]; - if (k_rot) { - Kcur = llama_mul_mat_hadamard(ctx0, Kcur, k_rot); - } - if (v_rot) { - Vcur = llama_mul_mat_hadamard(ctx0, Vcur, v_rot); - } - ggml_build_forward_expand(gf, kv->cpy_k(ctx0, Kcur, k_idxs, il)); - ggml_build_forward_expand(gf, kv->cpy_v(ctx0, Vcur, v_idxs, il)); - } else { - // rotate K/V into the cache's rotated space - if (inp_attn->self_k_rot[il]) { - Kcur = llama_mul_mat_hadamard(ctx0, Kcur, inp_attn->self_k_rot[il]); - } - if (inp_attn->self_v_rot[il]) { - Vcur = llama_mul_mat_hadamard(ctx0, Vcur, inp_attn->self_v_rot[il]); - } - ggml_build_forward_expand(gf, inp_attn->mctx->cpy_k(ctx0, Kcur, inp_attn->get_k_idxs(), il)); - ggml_build_forward_expand(gf, inp_attn->mctx->cpy_v(ctx0, Vcur, inp_attn->get_v_idxs(), il)); - } + store_inject_kv(Kcur, Vcur, il); } res->t_embd = inp_g; @@ -355,6 +382,50 @@ ggml_tensor * llama_model_dflash::graph_base::build_inject() { return inp_g; } +// KV cache injection with per-layer context K/V (Inkling2 DSpark): rms_norm(sum_i ctx_mix[i] * target_i) * ctx_norm -> k_ctx / v_ctx +// also outputs f_rnn (the same mix for the markov head) as h_nextn +void llama_model_dflash::graph_base::build_inject_ctx_mix() { + const int64_t n_embd_inp = hparams.n_embd_inp_enc(); + const int64_t n_target = n_embd_inp / n_embd; + + auto inp = std::make_unique(n_embd_inp); + ggml_tensor * feats = build_inp_target_features(*this, *inp, n_embd_inp); + res->add_input(std::move(inp)); + + // [n_target, n_embd, n_tokens]: the mix is a matmul over the target taps + feats = ggml_cont(ctx0, ggml_permute(ctx0, ggml_reshape_3d(ctx0, feats, n_embd, n_target, n_tokens), 1, 0, 2, 3)); + cb(feats, "inp_target_features", -1); + + const auto build_mix = [&](ggml_tensor * mix, ggml_tensor * norm, int il) { + ggml_tensor * cur = ggml_reshape_2d(ctx0, ggml_mul_mat(ctx0, mix, feats), n_embd, n_tokens); + return build_norm(cur, norm, nullptr, LLM_NORM_RMS, il); + }; + + // the driver keeps the f_rnn rows of the context positions + if (model.dspark_markov_ctx_mix) { + res->t_h_nextn = build_mix(model.dspark_markov_ctx_mix, model.dspark_markov_ctx_norm, -1); + cb(res->t_h_nextn, "f_rnn", -1); + ggml_build_forward_expand(gf, res->t_h_nextn); + } + + for (int il = 0; il < n_layer; ++il) { + const auto & layer = model.layers[il]; + GGML_ASSERT(layer.dflash_ctx_mix && "DFlash draft without fc requires per-layer ctx_mix"); + + ggml_tensor * cur = build_mix(layer.dflash_ctx_mix, layer.dflash_ctx_norm, il); + + ggml_tensor * Kcur = ggml_reshape_3d(ctx0, build_lora_mm(layer.dflash_wk_ctx, cur), n_embd_head, n_head_kv, n_tokens); + ggml_tensor * Vcur = ggml_reshape_3d(ctx0, build_lora_mm(layer.dflash_wv_ctx, cur), n_embd_head, n_head_kv, n_tokens); + + Kcur = build_norm(Kcur, layer.dflash_attn_k_ctx_norm, NULL, LLM_NORM_RMS, il); + Kcur = build_rope(Kcur, inp_pos, il); + cb(Kcur, "Kcur_injected", il); + cb(Vcur, "Vcur_injected", il); + + store_inject_kv(Kcur, Vcur, il); + } +} + ggml_tensor * llama_model_dflash::graph_base::build_inp_tokens() { ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens); ggml_set_input(inp_tokens); @@ -367,10 +438,41 @@ ggml_tensor * llama_model_dflash::graph_base::build_inp_tokens() { return inp_tokens; } +// DSpark block [anchor, mask_1, ..., mask_k] per sequence: slot k > 0 uses mask row k - 1, the anchor uses its (normed) token embedding +ggml_tensor * llama_model_dflash::graph_base::build_inp_block(ggml_tensor * inp_tokens) { + ggml_tensor * tok_embd = get_tok_embd(*this, model); + + const int64_t n_blocks = ubatch.n_seqs_unq; + const int64_t block_drafts = n_blocks > 0 ? n_tokens / n_blocks : 0; + + if (block_drafts == 0 || n_tokens % n_blocks != 0 || block_drafts > (int64_t) hparams.dflash_block_size) { + // not a draft block (e.g. graph reserve) + return ggml_get_rows(ctx0, tok_embd, inp_tokens); + } + + ggml_tensor * anchors = ggml_view_2d(ctx0, inp_tokens, 1, n_blocks, (size_t) block_drafts * inp_tokens->nb[0], 0); + anchors = ggml_get_rows(ctx0, tok_embd, ggml_cont_1d(ctx0, anchors, n_blocks)); + if (model.tok_norm) { + anchors = build_norm(anchors, model.tok_norm, nullptr, LLM_NORM_RMS, -1); + } + + ggml_tensor * cur = ggml_reshape_3d(ctx0, anchors, n_embd, 1, n_blocks); + if (block_drafts > 1) { + ggml_tensor * masks = ggml_view_3d(ctx0, model.dspark_mask_embd, n_embd, block_drafts - 1, 1, + model.dspark_mask_embd->nb[1], model.dspark_mask_embd->nb[2], 0); + masks = ggml_repeat_4d(ctx0, ggml_cast(ctx0, masks, GGML_TYPE_F32), n_embd, block_drafts - 1, n_blocks, 1); + cur = ggml_concat(ctx0, cur, masks, 1); + } + + return ggml_reshape_2d(ctx0, cur, n_embd, n_tokens); +} + ggml_tensor * llama_model_dflash::graph_base::build_layers(ggml_tensor * inp_tokens) { const float kq_scale = hparams.f_attention_scale != 0.0f ? hparams.f_attention_scale : 1.0f/sqrtf(float(n_embd_head)); - ggml_tensor * inpL = ggml_get_rows(ctx0, get_tok_embd(*this, model), inp_tokens); + ggml_tensor * inpL = model.dspark_mask_embd + ? build_inp_block(inp_tokens) + : ggml_get_rows(ctx0, get_tok_embd(*this, model), inp_tokens); if (hparams.f_embedding_scale != 0.0f) { inpL = ggml_scale(ctx0, inpL, hparams.f_embedding_scale); } @@ -482,6 +584,11 @@ ggml_tensor * llama_model_dflash::graph_base::build_logits(ggml_tensor * cur) { const auto [output, output_s] = get_lm_head(*this, model); cur = build_lora_mm(output, cur, output_s); + // a padded lm head (e.g. shared from the target): drop the rows past the vocabulary + if (!model.d2t && cur->ne[0] > (int64_t) model.vocab.n_tokens()) { + cur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, model.vocab.n_tokens(), cur->ne[1], cur->nb[1], 0)); + } + // DFlash2 feeds these logits to the selector, so they need the target's output // transforms; DFlash1 and DSpark read them through the sampler instead if (model.dflash_selector_hidden) { diff --git a/src/models/dspark.cpp b/src/models/dspark.cpp index b92c8976108e..b561708f227b 100644 --- a/src/models/dspark.cpp +++ b/src/models/dspark.cpp @@ -84,13 +84,27 @@ void llama_model_dflash::load_tensors_dspark(int64_t n_vocab_draft) { dspark_markov_w1 = create_tensor(tn(LLM_TENSOR_DSPARK_MARKOV_W1, "weight"), { dspark_markov_rank, n_vocab }, 0); dspark_markov_w2 = create_tensor(tn(LLM_TENSOR_DSPARK_MARKOV_W2, "weight"), { dspark_markov_rank, n_vocab_draft }, 0); dspark_markov_w2_s = create_tensor(tn(LLM_TENSOR_DSPARK_MARKOV_W2, "scale"), { 1 }, TENSOR_NOT_REQUIRED); + dspark_markov_w2_b = create_tensor(tn(LLM_TENSOR_DSPARK_MARKOV_W2, "bias"), { n_vocab_draft }, TENSOR_NOT_REQUIRED); dspark_conf_proj = create_tensor(tn(LLM_TENSOR_DSPARK_CONF_PROJ, "weight"), { n_embd + dspark_markov_rank, 1 }, TENSOR_NOT_REQUIRED); dspark_conf_proj_b = create_tensor(tn(LLM_TENSOR_DSPARK_CONF_PROJ, "bias"), { 1 }, TENSOR_NOT_REQUIRED); - dspark_joint_proj = create_tensor(tn(LLM_TENSOR_DSPARK_JOINT_PROJ, "weight"), { n_embd + 2*dspark_markov_rank, 3*dspark_markov_rank }, TENSOR_NOT_REQUIRED); + // f_rnn: the rnn head also reads a mix of the target features of the last committed token + const int64_t n_joint = (hparams.dspark_f_rnn ? 2*n_embd : n_embd) + 2*dspark_markov_rank; + + dspark_joint_proj = create_tensor(tn(LLM_TENSOR_DSPARK_JOINT_PROJ, "weight"), { n_joint, 3*dspark_markov_rank }, TENSOR_NOT_REQUIRED); dspark_joint_proj_b = create_tensor(tn(LLM_TENSOR_DSPARK_JOINT_PROJ, "bias"), { 3*dspark_markov_rank }, dspark_joint_proj ? 0 : TENSOR_NOT_REQUIRED); + if (hparams.dspark_f_rnn) { + dspark_markov_ctx_mix = create_tensor(tn(LLM_TENSOR_DSPARK_MARKOV_CTX_MIX, "weight"), { (int64_t) target_layer_ids.size() }, 0); + dspark_markov_ctx_norm = create_tensor(tn(LLM_TENSOR_DSPARK_MARKOV_CTX_NORM, "weight"), { n_embd }, 0); + } + + // the ML4 backbone loads its own mask_embd + if (backbone == BACKBONE_BASE) { + dspark_mask_embd = create_tensor(tn(LLM_TENSOR_DSPARK_MASK_EMBD, "weight"), { n_embd, hparams.dflash_block_size - 1 }, TENSOR_NOT_REQUIRED); + } + LLAMA_LOG_INFO("%s: DFlash with DSpark markov head (rank = %lld)\n", __func__, (long long) dspark_markov_rank); } @@ -177,7 +191,10 @@ void llama_model_dflash::load_tensors_layers_mistral_large4() { } // DSpark (DFlash + Markov & Confidence head): Markov bias on the draft logits, chained per block position -static void build_dspark_markov_head(llm_graph_context & g, const llama_model & model, ggml_tensor * tokens, ggml_tensor * hidden = nullptr) { +// f_rnn: [n_embd, n_tokens] extra rnn input, read at the anchor of each block +// softcap_after_bias: softcap(base + bias) instead of leaving the logits uncapped +static void build_dspark_markov_head(llm_graph_context & g, const llama_model & model, ggml_tensor * tokens, ggml_tensor * hidden = nullptr, + ggml_tensor * f_rnn = nullptr, bool softcap_after_bias = false) { ggml_context * ctx0 = g.ctx0; auto & res = g.res; @@ -221,6 +238,12 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & ggml_tensor * prev = ggml_view_2d(ctx0, tokens, 1, n_blocks, token_stride, 0); prev = ggml_cont_1d(ctx0, prev, n_blocks); + if (f_rnn) { + f_rnn = ggml_cont(ctx0, ggml_view_2d(ctx0, f_rnn, f_rnn->ne[0], n_blocks, (size_t) block_drafts * f_rnn->nb[1], 0)); // [n_embd, n_blocks] + } + + const float softcap = softcap_after_bias ? g.hparams.f_final_logit_softcapping : 0.0f; + ggml_tensor * cat = nullptr; ggml_tensor * cat_conf = nullptr; @@ -249,6 +272,9 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & ggml_tensor * hidden_i = ggml_view_2d(ctx0, hidden, hidden->ne[0], n_blocks, (size_t) block_drafts * hidden->nb[1], i*hidden->nb[1]); ggml_tensor * joint = ggml_concat(ctx0, ggml_concat(ctx0, state, w1_prev, 0), ggml_cont(ctx0, hidden_i), 0); + if (f_rnn) { + joint = ggml_concat(ctx0, joint, f_rnn, 0); + } joint = ggml_add(ctx0, ggml_mul_mat(ctx0, model.dspark_joint_proj, joint), model.dspark_joint_proj_b); // [3R, n_blocks] const auto chunk = [&](int64_t k) { @@ -263,6 +289,9 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & } ggml_tensor * bias = g.build_lora_mm(w2, markov, model.dspark_markov_w2_s); // [n_vocab_draft, n_blocks] + if (model.dspark_markov_w2_b) { + bias = ggml_add(ctx0, bias, model.dspark_markov_w2_b); + } if (model.d2t) { // reduced draft vocab: scatter the bias to the target rows (base is -inf on the others) const int64_t n_draft_vocab = bias->ne[0]; @@ -276,6 +305,9 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & // position i of every block: strided view [n_vocab, n_blocks] ggml_tensor * base_i = ggml_view_2d(ctx0, base, n_vocab, n_blocks, base_stride, i*base->nb[1]); ggml_tensor * col = ggml_add(ctx0, base_i, bias); + if (softcap > 0.0f) { + col = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, col, 1.0f/softcap)), softcap); + } cat = cat ? ggml_concat(ctx0, cat, col, 1) : col; @@ -327,13 +359,39 @@ llama_model_dflash::graph_dspark::graph_dspark(const llm_graph_params & params) return; } - ggml_tensor * inp_tokens = build_inp_tokens(); - ggml_tensor * cur = build_layers(inp_tokens); + // f_rnn arrives as the state embedding of the block tokens + ggml_tensor * inp_tokens = nullptr; + ggml_tensor * f_rnn = nullptr; + if (hparams.dspark_f_rnn && ubatch.embd_state) { + inp_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens); + ggml_set_input(inp_tokens); + res->t_inp_tokens = inp_tokens; + + auto inp = std::make_unique(n_embd, n_embd); + inp->tokens = inp_tokens; + inp->h = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_tokens); + ggml_set_input(inp->h); + f_rnn = inp->h; + res->add_input(std::move(inp)); + } else { + inp_tokens = build_inp_tokens(); + } + + // the whole block shares the mask row of its first query (the anchor) + if (model.dspark_mask_embd && use_iswa) { + inp_attn_iswa->self_attn_mask_swa.block_uniform = true; + } + + ggml_tensor * cur = build_layers(inp_tokens); build_logits(cur); // bias the draft logits with the Markov head - build_dspark_markov_head(*this, model, inp_tokens); + if (!hparams.dspark_f_rnn) { + build_dspark_markov_head(*this, model, inp_tokens); + } else if (f_rnn) { + build_dspark_markov_head(*this, model, inp_tokens, cur, f_rnn, true); + } } // DSV4 DSpark decoder, dual-mode by batch type (see graph_base): diff --git a/src/models/inkling2-loop.cpp b/src/models/inkling2-loop.cpp index 8366a1191f25..1b9455b52229 100644 --- a/src/models/inkling2-loop.cpp +++ b/src/models/inkling2-loop.cpp @@ -80,7 +80,12 @@ llama_model_inkling2_loop::graph::graph(const llm_graph_params & params) : llama auto * cur = build_inputs(); std::vector blocks; + + // DSpark target features are indexed by layer visit, not by cache slot + int visit = 0; + for (int il = 0; il < start; ++il) { + res->t_layer_inp[visit++] = cur; cur = build_layer(il, il, cur, blocks); } @@ -99,6 +104,7 @@ llama_model_inkling2_loop::graph::graph(const llm_graph_params & params) : llama } for (int ip = start; ip < end; ++ip) { const int il = pass == 0 ? ip : m.n_phys + (pass - 1)*(end - start) + (ip - start); + res->t_layer_inp[visit++] = cur; if (pass == 0) { cur = build_layer(il, ip, cur, blocks); continue; @@ -109,7 +115,9 @@ llama_model_inkling2_loop::graph::graph(const llm_graph_params & params) : llama } for (int il = end; il < m.n_phys; ++il) { + res->t_layer_inp[visit++] = cur; cur = build_layer(il, il, cur, blocks); } + GGML_ASSERT(visit == n_layer); build_output(cur, blocks); } diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 45477a69e35e..1e8d15c55874 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -422,6 +422,9 @@ void llama_model_inkling2::graph::build_output(ggml_tensor * cur, const std::vec cur = ggml_reshape_2d(ctx0, mix(blocks, cur, model.output_res_query), n_embd, n_tokens); cur = build_norm(cur, model.output_norm, nullptr, LLM_NORM_RMS, -1); + // DSpark target features: the last one is the final norm output of every token + res->t_layer_inp[n_layer] = cur; + if (inp_out_ids) { cur = ggml_get_rows(ctx0, cur, inp_out_ids); } @@ -450,6 +453,8 @@ llama_model_inkling2::graph::graph(const llm_graph_params & params) : llm_graph_ std::vector blocks; for (int il = 0; il < n_layer; ++il) { + // DSpark target features: the partial block at the layer input + res->t_layer_inp[il] = cur; cur = build_layer(il, il, cur, blocks); } diff --git a/src/models/models.h b/src/models/models.h index b12642fb9a70..045b57f46975 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -1643,7 +1643,10 @@ struct llama_model_dflash : public llama_model_base { graph_base(const llm_graph_params & params); ggml_tensor * build_inject(); + void build_inject_ctx_mix(); + void store_inject_kv(ggml_tensor * Kcur, ggml_tensor * Vcur, int il); ggml_tensor * build_inp_tokens(); + ggml_tensor * build_inp_block(ggml_tensor * inp_tokens); ggml_tensor * build_layers(ggml_tensor * inp_tokens); ggml_tensor * build_logits(ggml_tensor * cur); ggml_tensor * build_rope(ggml_tensor * cur, ggml_tensor * pos, int il); From eacd398fcacfe06142cf7a0f3f6e88c2fc5c5553 Mon Sep 17 00:00:00 2001 From: Xuan Son Nguyen Date: Sun, 22 Nov 2026 03:36:41 +0100 Subject: [PATCH 10/24] handle temp > 0 --- common/speculative.cpp | 56 +++++++++++++++++++++++++-- src/llama-batch.cpp | 3 +- src/models/dspark.cpp | 86 +++++++++++++++++++++++++++++++++++------- 3 files changed, 127 insertions(+), 18 deletions(-) diff --git a/common/speculative.cpp b/common/speculative.cpp index 1f5fe72a3340..3c579f5f6b5c 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -1382,6 +1382,12 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im std::vector ctx_embd; std::vector ctx_pos; + // per-token state of the block tokens: [context state | uniform | 1/temp], see llama_batch_ext_select_n_embd_state + // with probabilistic drafting the graph draws each block token from it and returns [token, k, ids, probs] in h_nextn + std::vector block_state; + std::vector draw_rng; + std::vector draw_seed; // the seed each generator was last seeded with (-1: reseed) + common_speculative_impl_draft_dspark(const common_params_speculative & params, uint32_t n_seq) : common_speculative_impl_draft_dflash(params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK) { @@ -1401,6 +1407,9 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im ctx_rows = (size_t) block_size + 1; ctx_embd.resize((size_t) n_seq * ctx_rows * (size_t) n_embd_dec); ctx_pos.assign((size_t) n_seq * ctx_rows, -1); + block_state.reserve((size_t) n_seq * block_size * (n_embd_dec + 2)); + draw_rng.resize(n_seq); + draw_seed.assign(n_seq, -1); } if (this->params.p_min > 0.0f) { @@ -1467,6 +1476,9 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im // record where each block starts and its size std::vector i_block_beg(n_seq, -1); std::vector n_block (n_seq, 0); + std::vector sampled (n_seq, false); + + block_state.clear(); for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { auto & dp = dparams[seq_id]; @@ -1480,6 +1492,14 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im continue; } + // the graph draws the block at the target's temperature, the verifier then does rejection sampling with q + sampled[seq_id] = has_markov_context && params.probabilistic && dp.result_q && dp.temp > 0.0f; + if (sampled[seq_id] && draw_seed[seq_id] != dp.seed) { + draw_seed[seq_id] = dp.seed; + // the default seed means random; mixed so it differs from the target's, as in spec_retune + draw_rng[seq_id].seed(dp.seed == LLAMA_DEFAULT_SEED ? std::random_device{}() : dp.seed ^ 0x85ebca6bu); + } + common_sampler_reset(smpls[seq_id].get()); const int32_t n = (int32_t) dp.pos0; @@ -1492,7 +1512,13 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im for (int32_t i = 0; i < n_block_tokens; ++i) { const int32_t idx = batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, true); if (state) { - batch.set_embd_state(idx, { state, 1, (size_t) n_embd_dec }); + // reserved up front, so the views of the earlier tokens stay valid + GGML_ASSERT(block_state.size() + n_embd_dec + 2 <= block_state.capacity()); + float * row = block_state.data() + block_state.size(); + block_state.insert(block_state.end(), state, state + n_embd_dec); + block_state.push_back(sampled[seq_id] ? (float) std::uniform_real_distribution(0.0, 1.0)(draw_rng[seq_id]) : 0.5f); + block_state.push_back(sampled[seq_id] ? 1.0f / dp.temp : 0.0f); + batch.set_embd_state(idx, { row, 1, (size_t) n_embd_dec + 2 }); } } } @@ -1521,11 +1547,35 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im auto & result = *dp.result; - // DSpark: read from the first draft slot, truncate below the confidence threshold - const float * conf = params.p_min > 0.0f ? llama_get_embeddings_nextn(ctx_dft) : nullptr; // bonus-anchor drafts read the mask positions only, like DFlash const int32_t i_draft_beg = sample_from_anchor ? 0 : 1; const int32_t i_draft_end = std::min(n_block_tokens, i_draft_beg + params.n_max); + + if (sampled[seq_id]) { + // the tokens the graph drew, and the distribution q each one was drawn from + const float * draws = llama_get_embeddings_nextn(ctx_dft); + GGML_ASSERT(draws && "DSpark draws missing from h_nextn"); + for (int32_t i = i_draft_beg; i < i_draft_end; ++i) { + const float * row = draws + (size_t) (beg + i) * n_embd_dec; + const int32_t n_cand = (int32_t) row[1]; + + auto & q = dp.result_q->emplace_back(); + q.reserve(n_cand); + for (int32_t k = 0; k < n_cand; ++k) { + const float p = row[2 + n_cand + k]; + q.push_back({ (llama_token) row[2 + k], std::log(p), p }); + } + result.push_back((llama_token) row[0]); + } + if (result.size() < (size_t) params.n_min) { + result.clear(); + dp.result_q->clear(); + } + continue; + } + + // DSpark: read from the first draft slot, truncate below the confidence threshold + const float * conf = params.p_min > 0.0f ? llama_get_embeddings_nextn(ctx_dft) : nullptr; for (int32_t i = i_draft_beg; i < i_draft_end; ++i) { const int32_t idx = beg + i; diff --git a/src/llama-batch.cpp b/src/llama-batch.cpp index 13efac363ccc..2dc25ad0061d 100644 --- a/src/llama-batch.cpp +++ b/src/llama-batch.cpp @@ -1220,7 +1220,8 @@ size_t llama_batch_ext_select_n_embd_state(llama_context_type ctx_type, const ll return hparams.n_embd_inp(); } if (hparams.dspark_f_rnn) { - return hparams.n_embd; + // Inkling2 DSpark rnn head: [f_rnn | uniform | 1/temp] + return hparams.n_embd + 2; } return 0; } diff --git a/src/models/dspark.cpp b/src/models/dspark.cpp index b561708f227b..7b2113f33f0e 100644 --- a/src/models/dspark.cpp +++ b/src/models/dspark.cpp @@ -191,10 +191,11 @@ void llama_model_dflash::load_tensors_layers_mistral_large4() { } // DSpark (DFlash + Markov & Confidence head): Markov bias on the draft logits, chained per block position -// f_rnn: [n_embd, n_tokens] extra rnn input, read at the anchor of each block +// rnn_state: [n_embd + 2, n_tokens] per-token state of the Inkling2 rnn head, [f_rnn | uniform | 1/temp] (see llama_batch_ext_select_n_embd_state) +// f_rnn is an extra rnn input read at the anchor; each step draws its token at 1/temp (0: argmax) and packs [token, k, ids, probs] into h_nextn // softcap_after_bias: softcap(base + bias) instead of leaving the logits uncapped static void build_dspark_markov_head(llm_graph_context & g, const llama_model & model, ggml_tensor * tokens, ggml_tensor * hidden = nullptr, - ggml_tensor * f_rnn = nullptr, bool softcap_after_bias = false) { + ggml_tensor * rnn_state = nullptr, bool softcap_after_bias = false) { ggml_context * ctx0 = g.ctx0; auto & res = g.res; @@ -238,14 +239,57 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & ggml_tensor * prev = ggml_view_2d(ctx0, tokens, 1, n_blocks, token_stride, 0); prev = ggml_cont_1d(ctx0, prev, n_blocks); - if (f_rnn) { - f_rnn = ggml_cont(ctx0, ggml_view_2d(ctx0, f_rnn, f_rnn->ne[0], n_blocks, (size_t) block_drafts * f_rnn->nb[1], 0)); // [n_embd, n_blocks] - } + const int64_t n_embd = g.hparams.n_embd; + + // n_rows values from offset off of the state at block position i, [n_rows, n_blocks] + const auto state_rows = [&](int64_t n_rows, int64_t off, int64_t i) { + return ggml_cont(ctx0, ggml_view_2d(ctx0, rnn_state, n_rows, n_blocks, (size_t) block_drafts * rnn_state->nb[1], + i*rnn_state->nb[1] + off*ggml_element_size(rnn_state))); + }; + + ggml_tensor * f_rnn = nullptr; // [n_embd, n_blocks] + ggml_tensor * inv_temp = nullptr; // [1, n_blocks] + ggml_tensor * is_greedy = nullptr; // [1, n_blocks], 1 when inv_temp is 0 + if (rnn_state) { + GGML_ASSERT(!has_conf && rnn_state->ne[0] == n_embd + 2); + f_rnn = state_rows(n_embd, 0, 0); + inv_temp = state_rows(1, n_embd + 1, 0); + is_greedy = ggml_scale_bias(ctx0, ggml_step(ctx0, inv_temp), -1.0f, 1.0f); + } + + // the draws keep the top n_cand candidates, q of the verifier is their distribution + const int64_t n_cand = std::min(64, n_vocab); + GGML_ASSERT(!rnn_state || 2 + 2*n_cand <= n_embd); + + // draw the token of block position i from softmax(top_k(col) * inv_temp), like the backend dist sampler + // returns [n_embd, n_blocks] packed rows [token, n_cand, ids, probs] and sets the next prev + const auto draw = [&](ggml_tensor * col, int64_t i, ggml_tensor *& next) { + ggml_tensor * ids = ggml_top_k(ctx0, col, n_cand); // [n_cand, n_blocks], unordered + ggml_tensor * vals = ggml_reshape_2d(ctx0, ggml_get_rows(ctx0, ggml_reshape_3d(ctx0, col, 1, n_vocab, n_blocks), ids), n_cand, n_blocks); + ggml_tensor * probs = ggml_soft_max(ctx0, ggml_mul(ctx0, vals, inv_temp)); + + // index of the first candidate whose cumulative probability passes the uniform + ggml_tensor * n_over = ggml_sum_rows(ctx0, ggml_step(ctx0, ggml_sub(ctx0, ggml_cumsum(ctx0, probs), state_rows(1, n_embd, i)))); + ggml_tensor * idx = ggml_cast(ctx0, ggml_scale_bias(ctx0, ggml_clamp(ctx0, n_over, 1.0f, (float) n_cand), -1.0f, (float) n_cand), GGML_TYPE_I32); + + ggml_tensor * ids_f = ggml_cast(ctx0, ids, GGML_TYPE_F32); + ggml_tensor * drawn = ggml_reshape_2d(ctx0, ggml_get_rows(ctx0, ggml_reshape_3d(ctx0, ids_f, 1, n_cand, n_blocks), idx), 1, n_blocks); + ggml_tensor * argmax = ggml_reshape_2d(ctx0, ggml_cast(ctx0, ggml_argmax(ctx0, col), GGML_TYPE_F32), 1, n_blocks); + + // greedy keeps the exact argmax + ggml_tensor * tok = ggml_add(ctx0, drawn, ggml_mul(ctx0, is_greedy, ggml_sub(ctx0, argmax, drawn))); + next = ggml_cast(ctx0, ggml_reshape_1d(ctx0, tok, n_blocks), GGML_TYPE_I32); + + ggml_tensor * k_col = ggml_fill(ctx0, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_blocks), (float) n_cand); + ggml_tensor * row = ggml_concat(ctx0, ggml_concat(ctx0, ggml_concat(ctx0, tok, k_col, 0), ids_f, 0), probs, 0); + return ggml_pad(ctx0, row, n_embd - row->ne[0], 0, 0, 0); + }; const float softcap = softcap_after_bias ? g.hparams.f_final_logit_softcapping : 0.0f; ggml_tensor * cat = nullptr; ggml_tensor * cat_conf = nullptr; + ggml_tensor * cat_draw = nullptr; if (!sample_from_anchor) { // bonus anchor slot: pass the logits through unbiased, pad the (unread) confidence column @@ -253,11 +297,14 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & if (has_conf) { cat_conf = ggml_sigmoid(ctx0, ggml_view_2d(ctx0, base, 1, n_blocks, base_stride, 0)); } + if (rnn_state) { + cat_draw = ggml_fill(ctx0, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_blocks), 0.0f); + } } ggml_tensor * state = nullptr; // [R, n_blocks] - // TODO: the in-graph chain is greedy (argmax); sampling params affect only the final + // TODO: without rnn_state the in-graph chain is greedy (argmax); sampling params affect only the final // token pick, not the Markov conditioning path for (int64_t i = i_draft_beg; i < block_drafts; ++i) { ggml_tensor * w1_prev = ggml_get_rows(ctx0, w1, prev); // [R, n_blocks] @@ -327,11 +374,22 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & cat_conf = cat_conf ? ggml_concat(ctx0, cat_conf, conf, 1) : conf; } - if (i + 1 < block_drafts) { + if (rnn_state) { + ggml_tensor * packed = draw(col, i, prev); + cat_draw = cat_draw ? ggml_concat(ctx0, cat_draw, packed, 1) : packed; + } else if (i + 1 < block_drafts) { prev = ggml_argmax(ctx0, col); } } + if (cat_draw) { + // position-major like cat; restore ubatch block-major order + ggml_tensor * draws = ggml_reshape_3d(ctx0, cat_draw, n_embd, n_blocks, block_drafts); + draws = ggml_cont(ctx0, ggml_permute(ctx0, draws, 0, 2, 1, 3)); + res->t_h_nextn = ggml_reshape_2d(ctx0, draws, n_embd, n_tok); + ggml_build_forward_expand(g.gf, res->t_h_nextn); + } + // cat is position-major; restore ubatch block-major order ggml_tensor * out = ggml_reshape_3d(ctx0, cat, n_vocab, n_blocks, block_drafts); out = ggml_cont(ctx0, ggml_permute(ctx0, out, 0, 2, 1, 3)); // [n_vocab, block_drafts, n_blocks] @@ -359,19 +417,19 @@ llama_model_dflash::graph_dspark::graph_dspark(const llm_graph_params & params) return; } - // f_rnn arrives as the state embedding of the block tokens + // the Inkling2 rnn head state arrives as the state embedding of the block tokens ggml_tensor * inp_tokens = nullptr; - ggml_tensor * f_rnn = nullptr; + ggml_tensor * rnn_state = nullptr; if (hparams.dspark_f_rnn && ubatch.embd_state) { inp_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens); ggml_set_input(inp_tokens); res->t_inp_tokens = inp_tokens; - auto inp = std::make_unique(n_embd, n_embd); + auto inp = std::make_unique(n_embd, n_embd + 2); inp->tokens = inp_tokens; - inp->h = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_tokens); + inp->h = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd + 2, n_tokens); ggml_set_input(inp->h); - f_rnn = inp->h; + rnn_state = inp->h; res->add_input(std::move(inp)); } else { inp_tokens = build_inp_tokens(); @@ -389,8 +447,8 @@ llama_model_dflash::graph_dspark::graph_dspark(const llm_graph_params & params) // bias the draft logits with the Markov head if (!hparams.dspark_f_rnn) { build_dspark_markov_head(*this, model, inp_tokens); - } else if (f_rnn) { - build_dspark_markov_head(*this, model, inp_tokens, cur, f_rnn, true); + } else if (rnn_state) { + build_dspark_markov_head(*this, model, inp_tokens, cur, rnn_state, true); } } From e4b1cb5318f1ac55d148be228c6347c6a94cc4c6 Mon Sep 17 00:00:00 2001 From: Piotr Wilkin Date: Sun, 22 Nov 2026 13:19:34 +0100 Subject: [PATCH 11/24] dspark : fix Inkling2 draft state width, reseeding and draw order Assisted-by: Claude Opus 5.5 --- common/speculative.cpp | 35 ++++++++++++++++++++++++++++------- docs/speculative.md | 14 ++++++++++++++ src/llama-batch.cpp | 4 ++-- src/models/dspark.cpp | 28 +++++++++++++++++++--------- 4 files changed, 63 insertions(+), 18 deletions(-) diff --git a/common/speculative.cpp b/common/speculative.cpp index 3c579f5f6b5c..8db83f65b326 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -1382,7 +1382,7 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im std::vector ctx_embd; std::vector ctx_pos; - // per-token state of the block tokens: [context state | uniform | 1/temp], see llama_batch_ext_select_n_embd_state + // per-token state of the block tokens, n_embd_dec wide: the context state on the anchor row, [uniform | 1/temp] on the draft rows, see llama_batch_ext_select_n_embd_state // with probabilistic drafting the graph draws each block token from it and returns [token, k, ids, probs] in h_nextn std::vector block_state; std::vector draw_rng; @@ -1407,7 +1407,7 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im ctx_rows = (size_t) block_size + 1; ctx_embd.resize((size_t) n_seq * ctx_rows * (size_t) n_embd_dec); ctx_pos.assign((size_t) n_seq * ctx_rows, -1); - block_state.reserve((size_t) n_seq * block_size * (n_embd_dec + 2)); + block_state.reserve((size_t) n_seq * block_size * n_embd_dec); draw_rng.resize(n_seq); draw_seed.assign(n_seq, -1); } @@ -1466,6 +1466,14 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im } public: + void begin(llama_seq_id seq_id, const llama_tokens & prompt) override { + // the markov context draws: reseed per request rather than per round, or two identical requests differ + if (has_markov_context && seq_id >= 0 && seq_id < (llama_seq_id) n_seq) { + draw_seed[seq_id] = -1; + } + + common_speculative_impl_draft_dflash::begin(seq_id, prompt); + } void draft(common_speculative_draft_params_vec & dparams) override { auto & ctx_dft = params.ctx_dft; @@ -1492,6 +1500,11 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im continue; } + // the full block of a markov context draft has to fit in the draft context + if (has_markov_context && (uint64_t) dp.pos0 + block_size > llama_n_ctx_seq(ctx_dft)) { + continue; + } + // the graph draws the block at the target's temperature, the verifier then does rejection sampling with q sampled[seq_id] = has_markov_context && params.probabilistic && dp.result_q && dp.temp > 0.0f; if (sampled[seq_id] && draw_seed[seq_id] != dp.seed) { @@ -1513,12 +1526,20 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im const int32_t idx = batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, true); if (state) { // reserved up front, so the views of the earlier tokens stay valid - GGML_ASSERT(block_state.size() + n_embd_dec + 2 <= block_state.capacity()); + GGML_ASSERT(block_state.size() + n_embd_dec <= block_state.capacity()); float * row = block_state.data() + block_state.size(); - block_state.insert(block_state.end(), state, state + n_embd_dec); - block_state.push_back(sampled[seq_id] ? (float) std::uniform_real_distribution(0.0, 1.0)(draw_rng[seq_id]) : 0.5f); - block_state.push_back(sampled[seq_id] ? 1.0f / dp.temp : 0.0f); - batch.set_embd_state(idx, { row, 1, (size_t) n_embd_dec + 2 }); + if (i == 0) { + block_state.insert(block_state.end(), state, state + n_embd_dec); + } else { + block_state.resize(block_state.size() + n_embd_dec, 0.0f); + if (sampled[seq_id]) { + // u in [0, 1): a draw in double can round up to 1 in float + const float u = (float) std::uniform_real_distribution(0.0, 1.0)(draw_rng[seq_id]); + row[0] = std::min(u, std::nextafter(1.0f, 0.0f)); + row[1] = 1.0f / dp.temp; + } + } + batch.set_embd_state(idx, { row, 1, (size_t) n_embd_dec }); } } } diff --git a/docs/speculative.md b/docs/speculative.md index 48e9d757ee3c..c3107cd0bafb 100644 --- a/docs/speculative.md +++ b/docs/speculative.md @@ -132,6 +132,20 @@ llama-server -m Qwen3-4B.gguf -md Qwen3-4B-DSpark.gguf \ acceptance (from the draft's confidence head) falls below `P` (default 0 = disabled). Values above 0 require a draft with a confidence head. +Inkling 2 ships its DSpark drafter as `mtp.safetensors` in the model directory. Export it from a local +checkpoint with `--dspark`; the converter also reads the target's lm head and embedding norm from there: + +```bash +python convert_hf_to_gguf.py /path/to/Inkling-2-Mini --dspark --outtype bf16 --outfile Inkling-2-Mini-DSpark.gguf + +llama-server -m Inkling-2-Mini.gguf -md Inkling-2-Mini-DSpark.gguf \ + --spec-type draft-dspark --spec-draft-n-max 3 -fa on --jinja +``` + +The Inkling 2 drafter always decodes its full trained block. It also supports `--spec-draft-sampling probabilistic`: +at a positive request temperature, each drawn token conditions the next one, and the target verifies the draft by +rejection sampling. + Currently only drafts with a Qwen3 backbone are supported; support for other backbones (e.g. Gemma4) is planned. diff --git a/src/llama-batch.cpp b/src/llama-batch.cpp index 2dc25ad0061d..3391cb49e858 100644 --- a/src/llama-batch.cpp +++ b/src/llama-batch.cpp @@ -1220,8 +1220,8 @@ size_t llama_batch_ext_select_n_embd_state(llama_context_type ctx_type, const ll return hparams.n_embd_inp(); } if (hparams.dspark_f_rnn) { - // Inkling2 DSpark rnn head: [f_rnn | uniform | 1/temp] - return hparams.n_embd + 2; + // Inkling2 DSpark rnn head: f_rnn on the anchor row, [uniform | 1/temp] on the draft rows + return hparams.n_embd; } return 0; } diff --git a/src/models/dspark.cpp b/src/models/dspark.cpp index 7b2113f33f0e..0538e220535f 100644 --- a/src/models/dspark.cpp +++ b/src/models/dspark.cpp @@ -191,8 +191,9 @@ void llama_model_dflash::load_tensors_layers_mistral_large4() { } // DSpark (DFlash + Markov & Confidence head): Markov bias on the draft logits, chained per block position -// rnn_state: [n_embd + 2, n_tokens] per-token state of the Inkling2 rnn head, [f_rnn | uniform | 1/temp] (see llama_batch_ext_select_n_embd_state) -// f_rnn is an extra rnn input read at the anchor; each step draws its token at 1/temp (0: argmax) and packs [token, k, ids, probs] into h_nextn +// rnn_state: [n_embd, n_tokens] per-token state of the Inkling2 rnn head (see llama_batch_ext_select_n_embd_state) +// anchor row: f_rnn, an extra rnn input; draft row i: [uniform | 1/temp | 0...] of its draw +// each step draws its token at 1/temp (0: argmax) and packs [token, k, ids, probs] into h_nextn // softcap_after_bias: softcap(base + bias) instead of leaving the logits uncapped static void build_dspark_markov_head(llm_graph_context & g, const llama_model & model, ggml_tensor * tokens, ggml_tensor * hidden = nullptr, ggml_tensor * rnn_state = nullptr, bool softcap_after_bias = false) { @@ -251,10 +252,13 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & ggml_tensor * inv_temp = nullptr; // [1, n_blocks] ggml_tensor * is_greedy = nullptr; // [1, n_blocks], 1 when inv_temp is 0 if (rnn_state) { - GGML_ASSERT(!has_conf && rnn_state->ne[0] == n_embd + 2); - f_rnn = state_rows(n_embd, 0, 0); - inv_temp = state_rows(1, n_embd + 1, 0); - is_greedy = ggml_scale_bias(ctx0, ggml_step(ctx0, inv_temp), -1.0f, 1.0f); + // the anchor row holds f_rnn, so it cannot be a draft row + GGML_ASSERT(!has_conf && !sample_from_anchor && rnn_state->ne[0] == n_embd); + f_rnn = state_rows(n_embd, 0, 0); + if (block_drafts > i_draft_beg) { + inv_temp = state_rows(1, 1, i_draft_beg); + is_greedy = ggml_scale_bias(ctx0, ggml_step(ctx0, inv_temp), -1.0f, 1.0f); + } } // the draws keep the top n_cand candidates, q of the verifier is their distribution @@ -266,10 +270,16 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model & const auto draw = [&](ggml_tensor * col, int64_t i, ggml_tensor *& next) { ggml_tensor * ids = ggml_top_k(ctx0, col, n_cand); // [n_cand, n_blocks], unordered ggml_tensor * vals = ggml_reshape_2d(ctx0, ggml_get_rows(ctx0, ggml_reshape_3d(ctx0, col, 1, n_vocab, n_blocks), ids), n_cand, n_blocks); + + // the top-k order can change between runs, sort by logit so a seed draws the same tokens + ggml_tensor * order = ggml_argsort(ctx0, vals, GGML_SORT_ORDER_DESC); + ids = ggml_reshape_2d(ctx0, ggml_get_rows(ctx0, ggml_reshape_3d(ctx0, ids, 1, n_cand, n_blocks), order), n_cand, n_blocks); + vals = ggml_reshape_2d(ctx0, ggml_get_rows(ctx0, ggml_reshape_3d(ctx0, vals, 1, n_cand, n_blocks), order), n_cand, n_blocks); + ggml_tensor * probs = ggml_soft_max(ctx0, ggml_mul(ctx0, vals, inv_temp)); // index of the first candidate whose cumulative probability passes the uniform - ggml_tensor * n_over = ggml_sum_rows(ctx0, ggml_step(ctx0, ggml_sub(ctx0, ggml_cumsum(ctx0, probs), state_rows(1, n_embd, i)))); + ggml_tensor * n_over = ggml_sum_rows(ctx0, ggml_step(ctx0, ggml_sub(ctx0, ggml_cumsum(ctx0, probs), state_rows(1, 0, i)))); ggml_tensor * idx = ggml_cast(ctx0, ggml_scale_bias(ctx0, ggml_clamp(ctx0, n_over, 1.0f, (float) n_cand), -1.0f, (float) n_cand), GGML_TYPE_I32); ggml_tensor * ids_f = ggml_cast(ctx0, ids, GGML_TYPE_F32); @@ -425,9 +435,9 @@ llama_model_dflash::graph_dspark::graph_dspark(const llm_graph_params & params) ggml_set_input(inp_tokens); res->t_inp_tokens = inp_tokens; - auto inp = std::make_unique(n_embd, n_embd + 2); + auto inp = std::make_unique(n_embd, n_embd); inp->tokens = inp_tokens; - inp->h = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd + 2, n_tokens); + inp->h = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_tokens); ggml_set_input(inp->h); rnn_state = inp->h; res->add_input(std::move(inp)); From 9cd1953046e6f5f54b339924d5dbd8733ce5411f Mon Sep 17 00:00:00 2001 From: Piotr Wilkin Date: Sun, 22 Nov 2026 14:50:15 +0100 Subject: [PATCH 12/24] move the CUDA/HIP and Inkling 2 graph changes out of this PR Assisted-by: Claude Opus 5.5 --- ggml/src/ggml-cuda/fattn-common.cuh | 29 +------- ggml/src/ggml-cuda/fattn-mma-f16.cuh | 4 +- ggml/src/ggml-cuda/fattn-tile.cuh | 98 +++++++++++----------------- ggml/src/ggml-cuda/fattn-vec.cuh | 51 +++++---------- ggml/src/ggml-cuda/fattn.cu | 16 ++--- src/llama-graph.cpp | 86 +++++++++--------------- src/llama-graph.h | 11 ++-- src/llama-kv-cache.cpp | 12 ++-- src/llama-kv-cache.h | 4 +- src/models/inkling2.cpp | 15 ++++- src/models/models.h | 1 + 11 files changed, 119 insertions(+), 208 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh index 9ed4e7ce2665..fc0cc7403910 100644 --- a/ggml/src/ggml-cuda/fattn-common.cuh +++ b/ggml/src/ggml-cuda/fattn-common.cuh @@ -18,23 +18,6 @@ // The macro on the following line shifts it by a factor of 2**3=8, as was needed to fix https://github.com/ggml-org/llama.cpp/issues/18606 . #define FATTN_KQ_MAX_OFFSET (3.0f*0.6931f) -struct fattn_indexed_bias { - const float * table; - const int32_t * indices; - int64_t n_bins; - int64_t n_keys; - int64_t query_stride; - - __device__ fattn_indexed_bias for_head(int64_t first_query, int head) const { - return {table + first_query*query_stride + head*n_bins, indices + first_query*n_keys, n_bins, n_keys, query_stride}; - } - - __device__ half add(half mask, int query, int key) const { - const int bin = indices[query*n_keys + key]; - return uint32_t(bin) < n_bins ? __float2half(__half2float(mask) + table[query*query_stride + bin]) : mask; - } -}; - typedef void (* fattn_kernel_t)( const char * __restrict__ Q, const char * __restrict__ K, @@ -57,8 +40,7 @@ typedef void (* fattn_kernel_t)( const int32_t nb11, const int32_t nb12, const int64_t nb13, const int32_t nb21, const int32_t nb22, const int64_t nb23, const int32_t ne31, const int32_t ne32, const int32_t ne33, - const int32_t nb31, const int64_t nb32, const int64_t nb33, - const fattn_indexed_bias bias); + const int32_t nb31, const int64_t nb32, const int64_t nb33); typedef float (*vec_dot_KQ_t)( const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8 , const void * __restrict__ Q_ds); @@ -1188,7 +1170,7 @@ void launch_fattn( // Optional optimization where the mask is scanned to determine whether part of the calculation can be skipped. // Only worth the overhead if there is at lease one FATTN_KQ_STRIDE x FATTN_KQ_STRIDE square to be skipped or // multiple sequences of possibly different lengths, or kv_rows lists that end with padding. - const bool scan_mask = !dst->src[6] && !use_sparse && mask && mask->ne[2] == 1 && n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows); + const bool scan_mask = !use_sparse && mask && mask->ne[2] == 1 && n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows); if (scan_mask) { const int64_t s31 = mask->nb[1] / sizeof(half2); const int64_t s33 = mask->nb[3] / sizeof(half2); @@ -1342,12 +1324,7 @@ void launch_fattn( K->ne[0], n_kv, K->ne[2], K->ne[3], nb11, nb12, nb13, nb21, nb22, nb23, mask ? mask->ne[1] : 0, mask ? mask->ne[2] : 0, mask ? mask->ne[3] : 0, - mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0, - fattn_indexed_bias{dst->src[6] ? (const float *) dst->src[6]->data : nullptr, - dst->src[7] ? (const int32_t *) dst->src[7]->data : nullptr, - dst->src[6] ? dst->src[6]->ne[0] : 0, - dst->src[7] ? dst->src[7]->ne[0] : 0, - dst->src[6] ? dst->src[6]->ne[0]*dst->src[6]->ne[1] : 0} + mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0 ); CUDA_CHECK(cudaGetLastError()); diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh index 641cfa3de538..dea8d2ad35ec 100644 --- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh +++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh @@ -1960,9 +1960,7 @@ static __global__ void flash_attn_ext_f16( const int32_t nb11, const int32_t nb12, const int64_t nb13, const int32_t nb21, const int32_t nb22, const int64_t nb23, const int32_t ne31, const int32_t ne32, const int32_t ne33, - const int32_t nb31, const int64_t nb32, const int64_t nb33, - const fattn_indexed_bias bias) { - GGML_UNUSED(bias); + const int32_t nb31, const int64_t nb32, const int64_t nb33) { ggml_cuda_pdl_sync(); // TODO optimize placement #if defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE)) const char * GGML_CUDA_RESTRICT Q = Q_ptr; diff --git a/ggml/src/ggml-cuda/fattn-tile.cuh b/ggml/src/ggml-cuda/fattn-tile.cuh index 8987cf9b522d..177b2f0653bf 100644 --- a/ggml/src/ggml-cuda/fattn-tile.cuh +++ b/ggml/src/ggml-cuda/fattn-tile.cuh @@ -374,9 +374,9 @@ static constexpr __device__ int ggml_cuda_fattn_tile_get_nbatch_K(const int DKQ, } // TODO: deduplicate with mma-f16 -template +template static __device__ __forceinline__ void flash_attn_tile_load_tile( - const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int stride_KV, const int i_sup, const int * rows) { + const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int stride_KV, const int i_sup) { constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); constexpr int cpy_ne = cpy_nb / 4; @@ -400,7 +400,6 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( const int i = i0 + threadIdx.y*stride_i + (stride_j == warp_size ? 0 : threadIdx.x / stride_j); if (i0 + nwarps*stride_i <= I || i < I) { - const int row = use_rows && (!oob_check || i < i_sup) ? rows[i] : i; #pragma unroll for (int j0 = j0_start; j0 < j0_stop; j0 += stride_j) { const int j = j0*cpy_ne + (stride_j == warp_size ? threadIdx.x : threadIdx.x % stride_j)*cpy_ne; @@ -408,7 +407,7 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( const __align__(16) half2 zero[cpy_ne] = {{0.0f, 0.0f}}; ggml_cuda_memcpy_1( tile_KV + i*(J/2 + J_padding) + j, - (!oob_check || i < i_sup) && (!use_rows || row >= 0) ? KV + int64_t(row)*stride_KV + j : zero); + !oob_check || i < i_sup ? KV + i*stride_KV + j : zero); } } } @@ -425,9 +424,9 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( ggml_cuda_unroll<7>{}(load); } -template +template static __device__ __forceinline__ void flash_attn_tile_load_tile( - const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int stride_KV, const int i_sup, const int * rows) { + const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int stride_KV, const int i_sup) { constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); constexpr int cpy_ne = cpy_nb / 4; @@ -451,7 +450,6 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( const int i = i0 + threadIdx.y*stride_i + (stride_j == warp_size ? 0 : threadIdx.x / stride_j); if (i0 + nwarps*stride_i <= I || i < I) { - const int row = use_rows && (!oob_check || i < i_sup) ? rows[i] : i; #pragma unroll for (int j0 = j0_start; j0 < j0_stop; j0 += stride_j) { const int j = j0*(cpy_ne/2) + (stride_j == warp_size ? threadIdx.x : threadIdx.x % stride_j)*(cpy_ne/2); @@ -459,7 +457,7 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( const half2 zero[cpy_ne/2] = {{0.0f, 0.0f}}; __align__(16) half2 tmp_h2[cpy_ne/2]; ggml_cuda_memcpy_1( - tmp_h2, (!oob_check || i < i_sup) && (!use_rows || row >= 0) ? KV + int64_t(row)*stride_KV + j : zero); + tmp_h2, !oob_check || i < i_sup ? KV + i*stride_KV + j : zero); __align__(16) float2 tmp_f2[cpy_ne/2]; #pragma unroll @@ -483,15 +481,16 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( // Function that performs a single iteration in for the KQ matrix multiplication: template + bool use_logit_softcap, bool oob_check, typename T_vec_dot> static __device__ __forceinline__ void flash_attn_tile_iter_KQ( T_vec_dot * const Q_tmp, const half2 * const __restrict__ K_h2, T_vec_dot * const KV_tmp, const int stride_K2, + const int k_VKQ_0, const int k_VKQ_sup, const int k_KQ_0, - float * KQ_acc, const int * rows) { + float * KQ_acc) { constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); constexpr int cpy_ne = cpy_nb / 4; @@ -499,8 +498,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ( constexpr int cpw = ncols > nwarps ? ncols/nwarps : 1; // Q columns per warp constexpr int np = nwarps > ncols ? nwarps/ncols : 1; // number of parallel warps per Q column - flash_attn_tile_load_tile - (K_h2 + k_KQ_0/2, KV_tmp, stride_K2, k_VKQ_sup, rows); + flash_attn_tile_load_tile + (K_h2 + int64_t(k_VKQ_0)*stride_K2 + k_KQ_0/2, KV_tmp, stride_K2, k_VKQ_sup); __syncthreads(); #ifdef FAST_FP16_AVAILABLE @@ -557,7 +556,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ( // Function that performs a single iteration of the main loop over up to nbatch_fa tokens. template + bool use_logit_softcap, bool oob_check, typename T_vec_dot, typename T_KQ, typename T_acc> static __device__ __forceinline__ void flash_attn_tile_iter( T_vec_dot * const Q_tmp, const half2 * const __restrict__ K_h2, @@ -576,8 +575,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter( T_acc * const VKQ, const int k_VKQ_0, const int k_VKQ_max, - const int col_Q_0, - const fattn_indexed_bias bias, const int * rows) { + const int col_Q_0) { constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); constexpr int cpy_ne = cpy_nb / 4; @@ -596,9 +594,6 @@ static __device__ __forceinline__ void flash_attn_tile_iter( #endif // FAST_FP16_AVAILABLE static_assert(cpw % KQ_cs == 0, "bad KQ_cs"); const int k_VKQ_sup = k_VKQ_max - k_VKQ_0; // k supremum, only smaller k values have valid KV data - const half2 * K_tile = use_rows ? K_h2 : K_h2 + int64_t(k_VKQ_0)*stride_K2; - const half2 * V_tile = use_rows ? V_h2 : V_h2 + int64_t(k_VKQ_0)*stride_V2; - const int * tile_rows = use_rows ? rows + k_VKQ_0 : nullptr; float KQ_max_new[cpw]; #pragma unroll @@ -612,13 +607,13 @@ static __device__ __forceinline__ void flash_attn_tile_iter( constexpr int nbatch_K_last = DKQ % nbatch_K; #pragma unroll for (int k_KQ_0 = 0; k_KQ_0 < DKQ - nbatch_K_last; k_KQ_0 += nbatch_K) { - flash_attn_tile_iter_KQ( - Q_tmp, K_tile, KV_tmp, stride_K2, k_VKQ_sup, k_KQ_0, KQ_acc, tile_rows); + flash_attn_tile_iter_KQ( + Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc); } if (nbatch_K_last > 0) { constexpr int k_KQ_0 = DKQ - nbatch_K_last; - flash_attn_tile_iter_KQ( - Q_tmp, K_tile, KV_tmp, stride_K2, k_VKQ_sup, k_KQ_0, KQ_acc, tile_rows); + flash_attn_tile_iter_KQ( + Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc); } // Apply logit softcap + mask, update KQ_max: @@ -641,14 +636,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter( } if (!oob_check || i_KQ < k_VKQ_sup) { - const int k = k_VKQ_0 + i_KQ; - if (ncols2 > 1 || mask) { - half m = mask[int64_t(j)*stride_mask + k]; - if constexpr (indexed_bias) { - m = bias.add(m, j, k); - } - KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] += slope*__half2float(m); - } + KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] += (ncols2 > 1 || mask) ? + slope*__half2float(mask[j*stride_mask + k_VKQ_0 + i_KQ]) : 0.0f; KQ_max_new[jc0] = fmaxf(KQ_max_new[jc0], KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] + FATTN_KQ_MAX_OFFSET); } @@ -729,8 +718,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter( static_assert(nbatch_V % np == 0, "bad nbatch_V"); #pragma unroll for (int k0 = 0; k0 < nbatch_fa; k0 += nbatch_V) { - flash_attn_tile_load_tile - (use_rows ? V_tile : V_tile + int64_t(k0)*stride_V2, KV_tmp, stride_V2, k_VKQ_sup - k0, use_rows ? tile_rows + k0 : nullptr); + flash_attn_tile_load_tile + (V_h2 + int64_t(k_VKQ_0 + k0)*stride_V2, KV_tmp, stride_V2, k_VKQ_sup - k0); __syncthreads(); #ifdef FAST_FP16_AVAILABLE @@ -799,7 +788,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter( } } -template // D == head size +template // D == head size __launch_bounds__(ggml_cuda_fattn_tile_get_nthreads(DKQ, DV, ncols1*ncols2), ggml_cuda_fattn_tile_get_occupancy(DKQ, DV, ncols1*ncols2)) static __global__ void flash_attn_tile( const char * Q_ptr, @@ -823,8 +812,7 @@ static __global__ void flash_attn_tile( const int32_t nb11, const int32_t nb12, const int64_t nb13, const int32_t nb21, const int32_t nb22, const int64_t nb23, const int32_t ne31, const int32_t ne32, const int32_t ne33, - const int32_t nb31, const int64_t nb32, const int64_t nb33, - const fattn_indexed_bias bias) { + const int32_t nb31, const int64_t nb32, const int64_t nb33) { #ifdef FLASH_ATTN_AVAILABLE const char * GGML_CUDA_RESTRICT Q = Q_ptr; const char * GGML_CUDA_RESTRICT K = K_ptr; @@ -834,6 +822,7 @@ static __global__ void flash_attn_tile( const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; float * GGML_CUDA_RESTRICT dst = dst_ptr; float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; + GGML_UNUSED(KV_rows_ptr); // Skip unused kernel variants for faster compilation: @@ -864,9 +853,7 @@ static __global__ void flash_attn_tile( const int col_Q_0 = blockIdx.x * ncols1; // Index of the first Q column for this CUDA block to work on. const int sequence = blockIdx.z / (ne02/ncols2); - const int * rows = use_rows ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr; const int head0 = blockIdx.z*ncols2 - sequence*ne02; // == blockIdx.z % (ne02/ncols2) - const auto head_bias = indexed_bias ? bias.for_head(int64_t(sequence)*ne01.z, head0) : bias; const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix. const float * Q_f = (const float *) (Q + nb03*sequence + nb02* head0); const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*(head0 / gqa_ratio)); @@ -972,24 +959,24 @@ static __global__ void flash_attn_tile( int k_VKQ_0 = blockIdx.y*nbatch_fa; while (k_VKQ_0 <= k_VKQ_max - nbatch_fa) { constexpr bool oob_check = false; - flash_attn_tile_iter + flash_attn_tile_iter (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, - stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows); + stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0); k_VKQ_0 += gridDim.y*nbatch_fa; } if (k_VKQ_0 < k_VKQ_max) { constexpr bool oob_check = true; - flash_attn_tile_iter + flash_attn_tile_iter (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, - stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows); + stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0); } } else { // Branch without out-of-bounds checks. for (int k_VKQ_0 = blockIdx.y*nbatch_fa; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nbatch_fa) { constexpr bool oob_check = false; - flash_attn_tile_iter + flash_attn_tile_iter (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, - stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows); + stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0); } } @@ -1160,7 +1147,7 @@ static __global__ void flash_attn_tile( #endif // FLASH_ATTN_AVAILABLE } -template +template static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const ggml_tensor * Q = dst->src[0]; @@ -1176,7 +1163,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 64; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; + fattn_kernel_t fattn_kernel = flash_attn_tile; launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; @@ -1192,7 +1179,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 32; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; + fattn_kernel_t fattn_kernel = flash_attn_tile; launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; @@ -1204,7 +1191,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 16; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; + fattn_kernel_t fattn_kernel = flash_attn_tile; launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; @@ -1216,7 +1203,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 8; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; + fattn_kernel_t fattn_kernel = flash_attn_tile; launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; @@ -1228,7 +1215,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 4; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; + fattn_kernel_t fattn_kernel = flash_attn_tile; launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; @@ -1239,7 +1226,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 2; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; + fattn_kernel_t fattn_kernel = flash_attn_tile; launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; @@ -1268,17 +1255,6 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm // a mask with a head dimension is not shared by the Q heads of a K/V head const bool use_gqa_opt = mask && mask->ne[2] == 1 && max_bias == 0.0f && Q->ne[1] <= gqa_limit && K->ne[1] % FATTN_KQ_STRIDE == 0; - if constexpr (DKQ == 64 || DKQ == 128) { - if (dst->src[6]) { - if (dst->src[5]) { - launch_fattn_tile_switch_ncols1(ctx, dst); - } else { - launch_fattn_tile_switch_ncols1(ctx, dst); - } - return; - } - } - if constexpr (DKQ == 320) { // This branch is only used for Mistral Small 4 which has a GQA ratio of 32. // On AMD, simply use that GQA ratio with 32 columns / block since we always have enough SRAM. diff --git a/ggml/src/ggml-cuda/fattn-vec.cuh b/ggml/src/ggml-cuda/fattn-vec.cuh index 42c0ef1c40e1..09a46187d105 100644 --- a/ggml/src/ggml-cuda/fattn-vec.cuh +++ b/ggml/src/ggml-cuda/fattn-vec.cuh @@ -16,7 +16,7 @@ static constexpr __device__ int ggml_cuda_fattn_vec_get_nthreads_device() { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpass-failed" #endif // __clang__ -template // D == head size +template // D == head size __launch_bounds__(ggml_cuda_fattn_vec_get_nthreads_device(), 1) static __global__ void flash_attn_ext_vec( const char * Q_ptr, @@ -40,8 +40,7 @@ static __global__ void flash_attn_ext_vec( const int32_t nb11, const int32_t nb12, const int64_t nb13, const int32_t nb21, const int32_t nb22, const int64_t nb23, const int32_t ne31, const int32_t ne32, const int32_t ne33, - const int32_t nb31, const int64_t nb32, const int64_t nb33, - const fattn_indexed_bias bias) { + const int32_t nb31, const int64_t nb32, const int64_t nb33) { ggml_cuda_pdl_lc(); #ifdef FLASH_ATTN_AVAILABLE const char * GGML_CUDA_RESTRICT Q = Q_ptr; @@ -52,6 +51,7 @@ static __global__ void flash_attn_ext_vec( const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; float * GGML_CUDA_RESTRICT dst = dst_ptr; float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; + GGML_UNUSED(KV_rows_ptr); // Skip unused kernel variants for faster compilation: if (use_logit_softcap && !(D == 128 || D == 256)) { @@ -107,7 +107,6 @@ static __global__ void flash_attn_ext_vec( const int sequence = blockIdx.z / ne02; const int head = blockIdx.z - sequence*ne02; - const auto head_bias = indexed_bias ? bias.for_head(int64_t(sequence)*ne01.z, head) : bias; const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix. Q += nb03*sequence + nb02* head + nb01*ic0; K += nb13*sequence + nb12*(head / gqa_ratio); @@ -272,15 +271,12 @@ static __global__ void flash_attn_ext_vec( } const int k_VKQ_max = KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11; - const int * rows = use_rows ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr; - if constexpr (!use_rows) { - K += blockIdx.y*nthreads * nb11; - V += blockIdx.y*nthreads * nb21; - } + K += blockIdx.y*nthreads * nb11; + V += blockIdx.y*nthreads * nb21; maskh += blockIdx.y*nthreads; for (int k_VKQ_0 = blockIdx.y*nthreads; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nthreads, // Increment pointers after each loop: - K += use_rows ? 0 : gridDim.y*nthreads*nb11, V += use_rows ? 0 : gridDim.y*nthreads*nb21, maskh += gridDim.y*nthreads) { + K += gridDim.y*nthreads*nb11, V += gridDim.y*nthreads*nb21, maskh += gridDim.y*nthreads) { // Calculate KQ tile and keep track of new maximum KQ values: float KQ_reg[ncols]; // KQ in registers. @@ -294,24 +290,22 @@ static __global__ void flash_attn_ext_vec( #pragma unroll for (int i_KQ_0 = 0; i_KQ_0 < nthreads_KQ; ++i_KQ_0) { const int i_KQ = threadIdx.y*WARP_SIZE + (nthreads_KQ == WARP_SIZE ? 0 : (threadIdx.x & ~(nthreads_KQ-1))) + i_KQ_0; - const int row = use_rows ? rows[k_VKQ_0 + i_KQ] : i_KQ; #pragma unroll for (int j = 0; j < ncols; ++j) { - float sum = vec_dot_KQ(K + (use_rows ? int64_t(max(row, 0))*nb11 : i_KQ*nb11), Q_reg[j], Q_i32[j], Q_ds[j]); + float sum = vec_dot_KQ(K + i_KQ*nb11, Q_reg[j], Q_i32[j], Q_ds[j]); sum = warp_reduce_sum(sum); if (use_logit_softcap) { sum = logit_softcap*tanhf(sum); } - if constexpr (!indexed_bias) { - if (mask && (ncols == 1 || ic0 + j < int(ne01.z))) { - sum += slope*__half2float(maskh[j*ne11 + i_KQ]); - } - KQ_max_new[j] = fmaxf(KQ_max_new[j], sum + FATTN_KQ_MAX_OFFSET); + if (mask && (ncols == 1 || ic0 + j < int(ne01.z))) { + sum += slope*__half2float(maskh[j*ne11 + i_KQ]); } + KQ_max_new[j] = fmaxf(KQ_max_new[j], sum + FATTN_KQ_MAX_OFFSET); + if ((nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ) == uint32_t(i_KQ_0)) { KQ_reg[j] = sum; } @@ -320,14 +314,8 @@ static __global__ void flash_attn_ext_vec( #pragma unroll for (int j = 0; j < ncols; ++j) { - if constexpr (indexed_bias) { - const int k = k_VKQ_0 + tid; - const half m = use_rows && rows[k] < 0 ? half(-INFINITY) : head_bias.add(maskh[j*ne11 + tid], ic0 + j, k); - KQ_reg[j] += slope*__half2float(m); - KQ_max_new[j] = fmaxf(KQ_max[j], KQ_reg[j] + FATTN_KQ_MAX_OFFSET); - } #pragma unroll - for (int offset = indexed_bias ? 1 : nthreads_KQ; offset < WARP_SIZE; offset <<= 1) { + for (int offset = nthreads_KQ; offset < WARP_SIZE; offset <<= 1) { KQ_max_new[j] = fmaxf(KQ_max_new[j], ggml_cuda_shfl_xor(KQ_max_new[j], offset, WARP_SIZE)); } const float KQ_max_scale = expf(KQ_max[j] - KQ_max_new[j]); @@ -357,7 +345,6 @@ static __global__ void flash_attn_ext_vec( #pragma unroll for (int k0 = 0; k0 < WARP_SIZE; k0 += V_cols_per_iter) { const int k = threadIdx.y*WARP_SIZE + k0 + (nthreads_V == WARP_SIZE ? 0 : threadIdx.x / nthreads_V); - const char * V_row = V + (use_rows ? int64_t(max(rows[k_VKQ_0 + k], 0))*nb21 : k*nb21); #ifdef V_DOT2_F32_F16_AVAILABLE half2 KQ_k[ncols]; @@ -370,14 +357,14 @@ static __global__ void flash_attn_ext_vec( half2 tmp[V_rows_per_thread/2]; if constexpr (type_V == GGML_TYPE_BF16) { float2 tmp_f[V_rows_per_thread/2]; - dequantize_V(V_row, tmp_f, + dequantize_V(V + k*nb21, tmp_f, 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); #pragma unroll for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { tmp[i_VKQ_1] = __float22half2_rn(tmp_f[i_VKQ_1]); } } else { - dequantize_V(V_row, tmp, + dequantize_V(V + k*nb21, tmp, 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); } #pragma unroll @@ -397,7 +384,7 @@ static __global__ void flash_attn_ext_vec( #pragma unroll for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { float2 tmp[V_rows_per_thread/2]; - dequantize_V(V_row, tmp, + dequantize_V(V + k*nb21, tmp, 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); #pragma unroll for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { @@ -558,7 +545,7 @@ static __global__ void flash_attn_ext_vec( nb11, nb12, nb13, nb21, nb22, nb23, ne31, ne32, ne33, - nb31, nb32, nb33, bias); + nb31, nb32, nb33); NO_DEVICE_CODE; #endif // FLASH_ATTN_AVAILABLE } @@ -573,12 +560,6 @@ void ggml_cuda_flash_attn_ext_vec_case_impl(ggml_backend_cuda_context & ctx, ggm const int nthreads = ggml_cuda_fattn_vec_get_nthreads_host(cc); const int nwarps = nthreads / WARP_SIZE; fattn_kernel_t fattn_kernel = flash_attn_ext_vec; - if constexpr (cols_per_block == 1 && (D == 64 || D == 128) && !use_logit_softcap) { - if (dst->src[6]) { - fattn_kernel = dst->src[5] ? flash_attn_ext_vec : - flash_attn_ext_vec; - } - } const bool need_f16_K = type_K == GGML_TYPE_F16; const bool need_f16_V = type_V == GGML_TYPE_F16; constexpr size_t nbytes_shared = 0; diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 11b8a3e891f5..b37065c31dfb 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -582,6 +582,10 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const return BEST_FATTN_KERNEL_NONE; #endif// FLASH_ATTN_AVAILABLE + if (ggml_flash_attn_ext_has_indexed_bias(dst)) { + return BEST_FATTN_KERNEL_NONE; + } + const ggml_tensor * KQV = dst; const ggml_tensor * Q = dst->src[0]; const ggml_tensor * K = dst->src[1]; @@ -669,18 +673,6 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const return BEST_FATTN_KERNEL_NONE; } - if (ggml_flash_attn_ext_has_indexed_bias(dst)) { - const float softcap = ggml_get_op_params_f32(dst, 2); - if (Q->ne[0] != 128 && !(Q->ne[0] == 64 && softcap == 0.0f)) { - return BEST_FATTN_KERNEL_NONE; - } - if (softcap == 0.0f && Q->ne[1] == 1 && n_kv % FATTN_KQ_STRIDE == 0 && - ggml_cuda_get_fattn_vec_case(Q->ne[0], K->type, V->type)) { - return BEST_FATTN_KERNEL_VEC; - } - return BEST_FATTN_KERNEL_TILE; - } - if (mask && mask->ne[2] != 1) { // the kv_rows mask is compacted per sequence, it has no head dimension if (kv_rows) { diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index b37ddd1aa4d5..c5c9ddf014b9 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1415,7 +1415,7 @@ void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch) } if (self_rel_pos->buffer) { - attn_ctx->get_base()->set_input_relative_pos(self_rel_pos, inp_attn->self_attn_mask.rows, ubatch, extent); + attn_ctx->get_base()->set_input_relative_pos(self_rel_pos, ubatch, extent); } // swa tensors may not be allocated if there are no SWA attention layers @@ -1429,7 +1429,7 @@ void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch) } if (self_rel_pos_swa->buffer) { - attn_ctx->get_swa()->set_input_relative_pos(self_rel_pos_swa, inp_attn->self_attn_mask_swa.rows, ubatch, extent_swa); + attn_ctx->get_swa()->set_input_relative_pos(self_rel_pos_swa, ubatch, extent_swa); } const int64_t n_rs = mctx->get_recr()->get_n_rs(); @@ -1454,13 +1454,16 @@ bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & par const auto * attn_ctx = mctx->get_attn(); + // the masks are always dense, see build_inp_mem_hybrid_iswa_rel() + // base tensors may not be allocated if there are no non-SWA attention layers if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; } - res &= can_reuse_attn_mask(inp_attn->self_attn_mask, attn_ctx->get_base(), params.ubatch, params.cparams); + res &= can_reuse_kq_mask(inp_attn->self_attn_mask.raw, attn_ctx->get_base(), params.ubatch, params.cparams); + res &= self_rel_pos->ne[0] == attn_ctx->get_base()->get_n_kv(); res &= self_rel_pos->ne[1] == params.ubatch.n_tokens; // swa tensors may not be allocated if there are no SWA attention layers @@ -1468,8 +1471,9 @@ bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & par res &= inp_attn->self_k_idxs_swa->ne[0] == params.ubatch.n_tokens; } - res &= can_reuse_attn_mask(inp_attn->self_attn_mask_swa, attn_ctx->get_swa(), params.ubatch, params.cparams); + res &= can_reuse_kq_mask(inp_attn->self_attn_mask_swa.raw, attn_ctx->get_swa(), params.ubatch, params.cparams); + res &= self_rel_pos_swa->ne[0] == attn_ctx->get_swa()->get_n_kv(); res &= self_rel_pos_swa->ne[1] == params.ubatch.n_tokens; res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); @@ -3178,9 +3182,7 @@ ggml_tensor * llm_graph_context::build_attn_mha( ggml_tensor * v_mla, int64_t n_kv_max, float kq_scale, - int il, - ggml_tensor * bias_table, - ggml_tensor * bias_indices) const { + int il) const { const bool v_trans = v->nb[1] > v->nb[2]; // split the batch into streams if needed @@ -3195,21 +3197,6 @@ ggml_tensor * llm_graph_context::build_attn_mha( k = ggml_permute(ctx0, k, 0, 2, 1, 3); v = ggml_permute(ctx0, v, 0, 2, 1, 3); - auto dense_bias_mask = [&]() { - ggml_tensor * table = ggml_cont(ctx0, ggml_permute(ctx0, bias_table, 1, 0, 2, 3)); - ggml_tensor * bias = ggml_get_rows(ctx0, table, bias_indices); - bias = ggml_reshape_4d(ctx0, bias, q->ne[2], bias_indices->ne[0], q->ne[1], n_stream); - bias = ggml_cont(ctx0, ggml_permute(ctx0, bias, 2, 0, 1, 3)); - cb(bias, "kq_b", il); - ggml_tensor * mask = kq_mask->type == GGML_TYPE_F32 ? kq_mask : ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); - mask = ggml_add(ctx0, bias, mask); - if (cparams.flash_attn) { - mask = ggml_cast(ctx0, mask, GGML_TYPE_F16); - } - cb(mask, "kq_mask_rel_pos", il); - return mask; - }; - ggml_tensor * cur; const bool use_flash_attn = cparams.flash_attn && kq_b == nullptr; @@ -3243,23 +3230,6 @@ ggml_tensor * llm_graph_context::build_attn_mha( GGML_ASSERT(n_kv_max >= 0 && n_kv_max <= INT32_MAX); ggml_flash_attn_ext_set_n_kv_max(cur, static_cast(n_kv_max)); ggml_prec_set_acc(cur, GGML_PREC_F32); - if (bias_table) { - ggml_flash_attn_ext_add_indexed_bias(cur, bias_table, bias_indices); - const auto dev = model.dev_layer(il); - if (!cparams.offload_kqv || !dev || !ggml_backend_dev_supports_op(dev, cur)) { - ggml_flash_attn_ext_add_indexed_bias(cur, nullptr, nullptr); - cur->src[3] = dense_bias_mask(); - } else if (kv_rows) { - // Looped layers can project Q and the bias on a different device from their KV cache. - for (int i = 0; i < ggml_backend_sched_get_n_backends(sched); ++i) { - auto backend = ggml_backend_sched_get_backend(sched, i); - if (ggml_backend_get_device(backend) == dev) { - ggml_backend_sched_set_tensor_backend(sched, cur, backend); - break; - } - } - } - } if (v_mla) { #if 0 @@ -3280,9 +3250,6 @@ ggml_tensor * llm_graph_context::build_attn_mha( cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]); } else { - if (bias_table) { - kq_mask = dense_bias_mask(); - } ggml_tensor * kq = ggml_mul_mat(ctx0, k, q); cb(kq, "kq", il); @@ -3814,9 +3781,7 @@ static ggml_tensor * build_attn_iswa_impl( ggml_tensor * sinks, ggml_tensor * v_mla, float kq_scale, - int il, - ggml_tensor * bias_table = nullptr, - ggml_tensor * bias_indices = nullptr) { + int il) { ggml_context * ctx0 = gctx.ctx0; ggml_cgraph * gf = gctx.gf; @@ -3882,7 +3847,7 @@ static ggml_tensor * build_attn_iswa_impl( ggml_tensor * k = use_kv_cur ? k_cur : mctx_cur->get_k(ctx0, il); ggml_tensor * v = use_kv_cur ? v_cur : mctx_cur->get_v(ctx0, il); - ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il, bias_table, bias_indices); + ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il); cur = build_attn_scale_kv_output(ctx0, mctx_cur, cur, il); gctx.cb(cur, "kqv_out", il); @@ -4476,18 +4441,19 @@ llm_graph_input_mem_hybrid_iswa_rel * llm_graph_context::build_inp_mem_hybrid_is auto inp_attn = std::make_unique(hparams, cparams, attn_ctx); + // dense masks: the bias is gathered by the distance to each cell of the K/V view { inp_attn->self_k_idxs = attn_ctx->get_base()->build_input_k_idxs(ctx0, ubatch); inp_attn->self_v_idxs = attn_ctx->get_base()->build_input_v_idxs(ctx0, ubatch); - inp_attn->self_attn_mask = build_attn_inp_attn_mask(ctx0, attn_ctx->get_base(), ubatch, cparams); + inp_attn->self_attn_mask.raw = build_attn_inp_kq_mask(ctx0, attn_ctx->get_base(), ubatch, cparams); } { inp_attn->self_k_idxs_swa = attn_ctx->get_swa()->build_input_k_idxs(ctx0, ubatch); inp_attn->self_v_idxs_swa = attn_ctx->get_swa()->build_input_v_idxs(ctx0, ubatch); - inp_attn->self_attn_mask_swa = build_attn_inp_attn_mask(ctx0, attn_ctx->get_swa(), ubatch, cparams); + inp_attn->self_attn_mask_swa.raw = build_attn_inp_kq_mask(ctx0, attn_ctx->get_swa(), ubatch, cparams); } inp_attn->self_k_rot = attn_ctx->get_base()->get_k_rot(); @@ -4498,11 +4464,11 @@ llm_graph_input_mem_hybrid_iswa_rel * llm_graph_context::build_inp_mem_hybrid_is auto inp = std::make_unique(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur, extent, extent_swa); - inp->self_rel_pos = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, inp->get_attn()->self_attn_mask.raw->ne[0], ubatch.n_tokens); + inp->self_rel_pos = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, attn_ctx->get_base()->get_n_kv(), ubatch.n_tokens); ggml_set_input(inp->self_rel_pos); ggml_set_name(inp->self_rel_pos, "attn_inp_rel_pos"); - inp->self_rel_pos_swa = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, inp->get_attn()->self_attn_mask_swa.raw->ne[0], ubatch.n_tokens); + inp->self_rel_pos_swa = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, attn_ctx->get_swa()->get_n_kv(), ubatch.n_tokens); ggml_set_input(inp->self_rel_pos_swa); ggml_set_name(inp->self_rel_pos_swa, "attn_inp_rel_pos_swa"); @@ -4517,7 +4483,7 @@ ggml_tensor * llm_graph_context::build_attn( ggml_tensor * q_cur, ggml_tensor * k_cur, ggml_tensor * v_cur, - ggml_tensor * bias_table, + ggml_tensor * kq_b, ggml_tensor * sinks, float kq_scale, int il) const { @@ -4527,10 +4493,22 @@ ggml_tensor * llm_graph_context::build_attn( const auto & attn_mask = is_swa ? inp_attn->self_attn_mask_swa : inp_attn->self_attn_mask; - ggml_tensor * indices = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; + // TODO: support kv_rows - fill the distances over the kv_rows cell lists and pass the rows to build_attn_mha, + // needs a kv_rows flash attention with a per-head mask (CUDA has none) + GGML_ASSERT(attn_mask.rows == nullptr); + + // a mask per head, in the dense layout of the input mask, which flash attention takes in F16 + ggml_tensor * kq_mask = attn_mask.raw; + if (kq_mask->type != GGML_TYPE_F32) { + kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); + } + kq_mask = ggml_add(ctx0, kq_b, kq_mask); + if (cparams.flash_attn) { + kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F16); + } + cb(kq_mask, "kq_mask_rel_pos", il); - return build_attn_iswa_impl(*this, inp_attn, wo, wo_b, wo_s, q_cur, k_cur, v_cur, nullptr, attn_mask.raw, attn_mask.rows, - sinks, nullptr, kq_scale, il, bias_table, indices); + return build_attn_iswa_impl(*this, inp_attn, wo, wo_b, wo_s, q_cur, k_cur, v_cur, nullptr, kq_mask, nullptr, sinks, nullptr, kq_scale, il); } void llm_graph_context::build_dense_out( diff --git a/src/llama-graph.h b/src/llama-graph.h index cfcbc248c72d..a9f8e5ce0068 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -774,7 +774,8 @@ class llm_graph_input_mem_hybrid_iswa : public llm_graph_input_i { }; // hybrid iswa memory with a per-head attention bias that depends on the distance from the query to the cell (Inkling) -// The visibility mask and distances use the same cache cell order. +// the KQ masks are always dense (rows == nullptr) and are filled from the same cells as the distances, so that the bias +// gathered by distance lines up with the mask class llm_graph_input_mem_hybrid_iswa_rel : public llm_graph_input_i { public: llm_graph_input_mem_hybrid_iswa_rel( @@ -1341,9 +1342,7 @@ struct llm_graph_context { ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v] int64_t n_kv_max, float kq_scale, - int il, - ggml_tensor * bias_table = nullptr, - ggml_tensor * bias_indices = nullptr) const; + int il) const; llm_graph_input_attn_no_cache * build_attn_inp_no_cache() const; @@ -1541,7 +1540,7 @@ struct llm_graph_context { uint32_t extent, uint32_t extent_swa) const; - // Gather the per-head bias by distance and add it to the visibility mask. + // kq_b is added to the KQ mask, after the KQ scale ggml_tensor * build_attn( llm_graph_input_mem_hybrid_iswa_rel * inp, ggml_tensor * wo, @@ -1550,7 +1549,7 @@ struct llm_graph_context { ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens] ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] - ggml_tensor * bias_table, // [n_bins, n_head_q, n_tokens] + ggml_tensor * kq_b, // [n_kv, n_tokens/n_stream, n_head_q, n_stream] ggml_tensor * sinks, // [n_head_q] float kq_scale, int il) const; diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 06b4a8a484e4..fbe422a2717a 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -2007,18 +2007,14 @@ bool llama_kv_cache::has_cell_ext() const { return hparams.n_pos_per_embd() > 1 || hparams.ple_n_heads > 0; } -void llama_kv_cache::set_input_relative_pos(ggml_tensor * dst, const ggml_tensor * rows, const llama_ubatch * ubatch, uint32_t extent) const { +void llama_kv_cache::set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const { GGML_ASSERT(dst->type == GGML_TYPE_I32); const int64_t n_kv = dst->ne[0]; - GGML_ASSERT(!rows || (rows->ne[0] == n_kv && ggml_backend_buffer_is_host(rows->buffer))); - const int64_t n_tps = ubatch->n_tokens / (rows ? rows->ne[1] : 1); std::vector data(n_kv * ubatch->n_tokens); for (uint32_t i = 0; i < ubatch->n_tokens; ++i) { const auto & cells = v_cells.at(seq_to_stream.at(ubatch->seq_id[i][0])); - const int32_t * list = rows ? (const int32_t *) rows->data + (i/n_tps)*n_kv : nullptr; for (int64_t j = 0; j < n_kv; ++j) { - const int64_t cell = list ? list[j] : j; - const int64_t distance = cell < 0 || cells.is_empty(cell) ? -1 : int64_t(ubatch->pos[i]) - cells.pos_get(cell); + const int64_t distance = cells.is_empty(j) ? -1 : int64_t(ubatch->pos[i]) - cells.pos_get(j); data[i*n_kv + j] = distance >= 0 && distance < extent ? distance : extent; } } @@ -3128,8 +3124,8 @@ void llama_kv_cache_context::set_input_pos_bucket(ggml_tensor * dst, const llama kv->set_input_pos_bucket(dst, ubatch); } -void llama_kv_cache_context::set_input_relative_pos(ggml_tensor * dst, const ggml_tensor * rows, const llama_ubatch * ubatch, uint32_t extent) const { - kv->set_input_relative_pos(dst, rows, ubatch, extent); +void llama_kv_cache_context::set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const { + kv->set_input_relative_pos(dst, ubatch, extent); } void llama_kv_cache_context::get_prev_tokens(const llama_ubatch & ubatch, uint32_t n, std::vector & res) const { diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index 1bfccf6aa3c5..1b40f6fc41d5 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -249,7 +249,7 @@ class llama_kv_cache : public llama_memory_i { void set_input_attn_mask (const llm_attn_mask & attn_mask, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; - void set_input_relative_pos(ggml_tensor * dst, const ggml_tensor * rows, const llama_ubatch * ubatch, uint32_t extent) const; + void set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; // true if llama_kv_cell_ext holds information that has to survive a state save/restore bool has_cell_ext() const; @@ -454,7 +454,7 @@ class llama_kv_cache_context : public llama_memory_context_i { void set_input_k_shift (ggml_tensor * dst) const; void set_input_attn_mask (const llm_attn_mask & attn_mask, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; - void set_input_relative_pos(ggml_tensor * dst, const ggml_tensor * rows, const llama_ubatch * ubatch, uint32_t extent) const; + void set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; // see llama_kv_cache::get_prev_tokens() void get_prev_tokens(const llama_ubatch & ubatch, uint32_t n, std::vector & res) const; diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 5d8bc7a4e09a..3e43ef4184ea 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -249,6 +249,7 @@ ggml_tensor * llama_model_inkling2::graph::control(ggml_tensor * cur, ggml_tenso ggml_tensor * llama_model_inkling2::graph::build_inputs() { inp = build_inp_mem_hybrid_iswa_rel(hparams.n_relative_extent, hparams.n_swa); + attn = inp->get_attn(); recr = inp->get_recr(); ggml_tensor * inp_pos = build_inp_pos(); @@ -345,18 +346,30 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens cb(Vcur, "Vcur", il); cb(Rcur, "Rcur", il); + ggml_tensor * rel_pos = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; + + const int64_t n_stream = (is_swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw)->ne[3]; + const int64_t n_kv = rel_pos->ne[0]; + ggml_tensor * sinks = build_lora_mm(layer.attn_sink_proj, inputs[0]); + // project r on the bias table first, then gather by distance: only the gathered bias is n_kv x n_tokens x n_head ggml_tensor * table = ggml_mul_mat(ctx0, ggml_pad(ctx0, layer.attn_rel_bias, 0, 1, 0, 0), Rcur); // the sink logit t is per query: exp(s - t)/(1 + sum(exp(s - t))) = exp(s)/(exp(t) + sum(exp(s))), with a zero sink table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks, 1, n_head, n_tokens)); + table = ggml_cont(ctx0, ggml_permute(ctx0, table, 1, 0, 2, 3)); + + ggml_tensor * kq_b = ggml_get_rows(ctx0, table, rel_pos); + kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, n_tokens/n_stream, n_stream); + kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); + cb(kq_b, "kq_b", il); sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); cur = build_attn(inp, nullptr, nullptr, nullptr, - Qcur, Kcur, Vcur, table, sinks, 1.0f/sqrtf(n_embd_head), il); + Qcur, Kcur, Vcur, kq_b, sinks, 1.0f/sqrtf(n_embd_head), il); cur = ggml_mul(ctx0, cur, ggml_sigmoid(ctx0, build_lora_mm(layer.wqkv_gate, inputs[0]))); cur = convolve(build_lora_mm(layer.wo, cur), layer.attn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa); diff --git a/src/models/models.h b/src/models/models.h index 822a728e4f50..8d2a5882772e 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2532,6 +2532,7 @@ struct llama_model_inkling2 : public llama_model_base { void build_output(ggml_tensor * cur, const std::vector & blocks); llm_graph_input_mem_hybrid_iswa_rel * inp = nullptr; + llm_graph_input_attn_kv_iswa * attn = nullptr; llm_graph_input_rs * recr = nullptr; ggml_tensor * inp_out_ids = nullptr; From 79980c5dfb7ce6b6cae4d0f8b4276aa72138e993 Mon Sep 17 00:00:00 2001 From: Piotr Wilkin Date: Sun, 22 Nov 2026 14:53:26 +0100 Subject: [PATCH 13/24] CPU reference implementation of the indexed bias Assisted-by: Claude Opus 5.5 --- ggml/src/ggml-cpu/ggml-cpu.cpp | 4 ---- ggml/src/ggml-cpu/ops.cpp | 28 ++++++++++++++++++++++++++-- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/ggml/src/ggml-cpu/ggml-cpu.cpp b/ggml/src/ggml-cpu/ggml-cpu.cpp index 23f05e28e94b..29783400186d 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.cpp +++ b/ggml/src/ggml-cpu/ggml-cpu.cpp @@ -422,10 +422,6 @@ static ggml_backend_buffer_t ggml_backend_cpu_device_buffer_from_host_ptr(ggml_b } static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) { - if (op->op == GGML_OP_FLASH_ATTN_EXT && ggml_flash_attn_ext_has_indexed_bias(op)) { - return false; - } - const struct ggml_tensor * src0 = op->src[0]; const struct ggml_tensor * src1 = op->src[1]; diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index cd8134740e19..0a286adcb9ce 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -8869,6 +8869,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( const ggml_tensor * mask = dst->src[3]; const ggml_tensor * sinks = dst->src[4]; const ggml_tensor * kv_rows = dst->src[5]; + const ggml_tensor * bias_table = dst->src[6]; + const ggml_tensor * bias_indices = dst->src[7]; GGML_TENSOR_LOCALS(int64_t, neq, q, ne) GGML_TENSOR_LOCALS(size_t, nbq, q, nb) @@ -8910,6 +8912,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( const int64_t rv2 = neq2/nev2; const int64_t rv3 = neq3/nev3; + const int64_t n_bins = bias_table ? bias_table->ne[0] : 0; + // parallelize by q rows using ggml_vec_dot_f32 float scale = 1.0f; @@ -8973,12 +8977,21 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( const int32_t * rows = kv_rows ? (const int32_t *) ((const char *) kv_rows->data + iq3*kv_rows->nb[1]) : nullptr; + // bias rows of this query and head, queries of all streams are flattened + const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr; + const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1)*bias_indices->nb[1]) : nullptr; + // online softmax / attention // loop over n_kv and n_head_kv // ref: https://arxiv.org/pdf/2112.05682.pdf for (int64_t ic = ic_start; ic < ic_end; ++ic) { - const float mv = mp ? slope*GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f; + float mv = mp ? GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f; + if (bias) { + GGML_ASSERT(bins[ic] >= 0 && bins[ic] < n_bins); + mv = GGML_CPU_FP16_TO_FP32(GGML_CPU_FP32_TO_FP16(mv + bias[bins[ic]])); + } + mv *= slope; if (mv == -INFINITY) { continue; } @@ -9156,6 +9169,10 @@ static void ggml_compute_forward_flash_attn_ext_tiled( const ggml_tensor * kv_rows = dst->src[5]; const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : nek1; + const ggml_tensor * bias_table = dst->src[6]; + const ggml_tensor * bias_indices = dst->src[7]; + const int64_t n_bins = bias_table ? bias_table->ne[0] : 0; + int ir = ir0; while (ir < ir1) { // q indices for the start of this tile @@ -9234,8 +9251,15 @@ static void ggml_compute_forward_flash_attn_ext_tiled( bool can_skip = true; for (int tq = 0; tq < tile_rows; tq++) { const ggml_fp16_t * mp_row = (const ggml_fp16_t *)((const char *) mask->data + (iq1 + tq)*mask->nb[1] + (iq2%mask->ne[2])*mask->nb[2] + (iq3%mask->ne[3])*mask->nb[3]); + const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1 + tq)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr; + const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1 + tq)*bias_indices->nb[1]) : nullptr; for (int tk = 0; tk < kv_tile; tk++) { - mask32[tq * KV_TILE_SZ + tk] = slope * GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]); + float m = GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]); + if (bias) { + GGML_ASSERT(bins[ic + tk] >= 0 && bins[ic + tk] < n_bins); + m = GGML_CPU_FP16_TO_FP32(GGML_CPU_FP32_TO_FP16(m + bias[bins[ic + tk]])); + } + mask32[tq * KV_TILE_SZ + tk] = slope * m; if (mask32[tq * KV_TILE_SZ + tk] != -INFINITY) { can_skip = false; } From 0b51bb2fed322bc884f96f98db340e2b0f6ea176 Mon Sep 17 00:00:00 2001 From: Xuan-Son Nguyen Date: Sun, 22 Nov 2026 17:52:56 +0100 Subject: [PATCH 14/24] server: support /models/sse on single-model mode (#32398) * server: support /models/sse on single-model mode * nits * nits --- common/arg.cpp | 10 +- common/arg.h | 3 + common/download.cpp | 26 +++- tools/server/README.md | 2 + tools/server/server-common.cpp | 17 +++ tools/server/server-common.h | 3 + tools/server/server-context.cpp | 11 +- tools/server/server-http.cpp | 3 + tools/server/server-models.cpp | 88 ++++++++---- tools/server/server-models.h | 21 ++- tools/server/server.cpp | 186 +++++++++++++++++--------- tools/server/tests/unit/test_basic.py | 16 +++ 12 files changed, 273 insertions(+), 113 deletions(-) diff --git a/common/arg.cpp b/common/arg.cpp index a638237672bd..e99b48c5b4d8 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -326,7 +326,7 @@ static bool parse_bool_value(const std::string & value) { // common_models_handler // -static std::string get_default_local_path(const std::string & url) { +std::string common_get_default_local_path(const std::string & url) { auto f = string_split(url, '#').front(); f = string_split(f, '?').front(); return fs_get_cache_file(string_split(f, '/').back()).string(); @@ -436,7 +436,7 @@ static std::vector build_url_tasks(const common_params_mod if (parts.size() == 1) { common_download_task task; task.url = parts[0]; - task.local_path = model.path.empty() ? get_default_local_path(parts[0]) : model.path; + task.local_path = model.path.empty() ? common_get_default_local_path(parts[0]) : model.path; task.opts = opts; tasks.push_back(std::move(task)); return tasks; @@ -454,7 +454,7 @@ static std::vector build_url_tasks(const common_params_mod task.url = part; task.opts = opts; - std::string local = get_default_local_path(part); + std::string local = common_get_default_local_path(part); if (!base_dir.empty()) { auto pos = local.rfind('/'); std::string name = pos == std::string::npos ? local : local.substr(pos + 1); @@ -487,7 +487,7 @@ void common_models_handler_apply(common_models_handler & handler, common_params auto handle_url = [&](common_params_model & model) { if (!model.url.empty()) { if (model.path.empty()) { - model.path = get_default_local_path(model.url); + model.path = common_get_default_local_path(model.url); } } }; @@ -498,7 +498,7 @@ void common_models_handler_apply(common_models_handler & handler, common_params // optionally, if docker repo is set, resolve it if (!params.model.docker_repo.empty()) { params.model.url = common_docker_resolve_model(params.model.docker_repo); - params.model.path = get_default_local_path(params.model.url); + params.model.path = common_get_default_local_path(params.model.url); } // handle plain "url" tasks (non-hf) diff --git a/common/arg.h b/common/arg.h index 203d1b4e11b8..a7cf30be4052 100644 --- a/common/arg.h +++ b/common/arg.h @@ -149,6 +149,9 @@ common_models_handler common_models_handler_init(const common_params & params, l // check if the model is a preset repo (i.e. has a preset file) bool common_models_handler_is_preset_repo(const common_models_handler & handler); +// the cache path a model downloaded from a plain url is stored at +std::string common_get_default_local_path(const std::string & url); + // download and update params with the downloaded model path void common_models_handler_apply(common_models_handler & handler, common_params & params, common_download_callback * callback = nullptr); diff --git a/common/download.cpp b/common/download.cpp index 682fd6e3ef7a..4dabaedb5466 100644 --- a/common/download.cpp +++ b/common/download.cpp @@ -98,6 +98,9 @@ class ProgressBar : public common_download_callback { std::string filename; size_t len = 0; + // the caller's callback, if any, still receives every event + common_download_callback * next; + static void cleanup(const ProgressBar * line) { lines.erase(line); if (lines.empty()) { @@ -110,9 +113,12 @@ class ProgressBar : public common_download_callback { } public: - ProgressBar() = default; + ProgressBar(common_download_callback * next) : next(next) {} void on_start(const common_download_progress & p) override { + if (next) { + next->on_start(p); + } filename = url_get_filename(p.url); for (size_t i = 0; i < filename.size(); ++i) { @@ -126,12 +132,22 @@ class ProgressBar : public common_download_callback { } } - void on_done(const common_download_progress &, bool) override { + void on_done(const common_download_progress & p, bool ok) override { + if (next) { + next->on_done(p, ok); + } std::lock_guard lock(mutex); cleanup(this); } + bool is_cancelled() const override { + return next && next->is_cancelled(); + } + void on_update(const common_download_progress & p) override { + if (next) { + next->on_update(p); + } if (!p.total || !is_output_a_tty()) { return; } @@ -519,11 +535,9 @@ int common_download_file_single(const std::string & url, const std::string & lock_path, const std::string & alt_path) { if (!opts.offline) { - ProgressBar tty_cb; + ProgressBar tty_cb(opts.callback); common_download_opts online_opts = opts; - if (!online_opts.callback) { - online_opts.callback = &tty_cb; - } + online_opts.callback = &tty_cb; return common_download_file_single_online(url, path, online_opts, skip_etag, lock_path, alt_path); } diff --git a/tools/server/README.md b/tools/server/README.md index b0168b6d14dc..b995e740304b 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -2435,6 +2435,8 @@ Response: ### GET `/models/sse`: Real-time events +This endpoint is also available in single-model mode (`-m`, `-hf`, ...), where it is served before the model is loaded, to follow the download and loading progress. As `GET /models` is unavailable until the model is loaded, each new client first receives the last event sent. If the download or the loading fails, a `status_change` event with status `unloaded` is sent before the server exits. + Example events: ```js diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp index 8d4c022e975d..95c57f877bee 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -1,3 +1,4 @@ +#include "arg.h" #include "common.h" #include "download.h" #include "log.h" @@ -2386,6 +2387,22 @@ server_role::~server_role() { } } +std::string server_get_model_name(const common_params & params) { + if (!params.model_alias.empty()) { + // backward compat: use first alias as model name + return *params.model_alias.begin(); + } + if (!params.model.get_name().empty()) { + return params.model.get_name(); + } + if (!params.model.url.empty()) { + // -mu before the download: the path the model will be stored at + return common_get_default_local_path(params.model.url); + } + // fallback: derive model name from file name + return std::filesystem::path(params.model.path).filename().string(); +} + bool server_role::is_managed_by_router() { return std::getenv(SERVER_ENV_ROUTER_PORT) != nullptr; } diff --git a/tools/server/server-common.h b/tools/server/server-common.h index 911bb31d709f..c1a0f4dcabe9 100644 --- a/tools/server/server-common.h +++ b/tools/server/server-common.h @@ -837,6 +837,9 @@ static inline server_state server_state_from_str(const std::string & str) { GGML_ASSERT(false && "invalid server_state string"); } +// the model name reported by the server: the first alias, else the model's repo or path +std::string server_get_model_name(const common_params & params); + // the role of this process and, when it is a child of a router, its side of the protocol struct server_role { // serializes the notify_to_router writes diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index b458a17c42fa..89f884e6548c 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1642,16 +1642,7 @@ struct server_context_impl { SRV_TRC("%s", "context checkpoints disabled\n"); } - if (!params_base.model_alias.empty()) { - // backward compat: use first alias as model name - model_name = *params_base.model_alias.begin(); - } else if (!params_base.model.get_name().empty()) { - model_name = params_base.model.get_name(); - } else { - // fallback: derive model name from file name - auto model_path = std::filesystem::path(params_base.model.path); - model_name = model_path.filename().string(); - } + model_name = server_get_model_name(params_base); model_aliases = params_base.model_alias; model_tags = params_base.model_tags; diff --git a/tools/server/server-http.cpp b/tools/server/server-http.cpp index 0244d4a72f75..d1f31e3ae22c 100644 --- a/tools/server/server-http.cpp +++ b/tools/server/server-http.cpp @@ -396,6 +396,9 @@ bool server_http_context::init_listener(const common_params & params) { if (frontend_paths.count(req.path)) { return true; // frontend asset, allow it to load and show "loading" } + if (req.path == "/models/sse") { + return true; // reports the download and loading progress + } // no endpoints are allowed to be accessed when the server is not ready // this is to prevent any data races or inconsistent states res.status = 503; diff --git a/tools/server/server-models.cpp b/tools/server/server-models.cpp index 5d5992c08d3a..8e3bb4982627 100644 --- a/tools/server/server-models.cpp +++ b/tools/server/server-models.cpp @@ -734,16 +734,7 @@ bool server_models::remove_sidecar(const std::string & name, const std::string & } void server_models::notify_sse(const std::string & event, const std::string & model_id, const json & data) { - std::unique_ptr result = std::make_unique(); - result->data = { - {"model", model_id}, - {"event", event}, - }; - if (!data.is_null()) { - result->data["data"] = data; - } - SRV_DBG("notifying SSE clients about event '%s' for model '%s': %s\n", event.c_str(), model_id.c_str(), safe_json_to_str(result->data).c_str()); - sse.broadcast(std::move(result)); + sse.notify(event, model_id, data); } void server_models::load_models() { @@ -1931,7 +1922,7 @@ void server_models::handle_child_state(const std::string & name, const std::stri } // -// server_models_routes +// server_models_sse // // RAII wrapper similar to server_response_reader, but doesn't use server_queue @@ -1970,6 +1961,61 @@ struct server_models_sse_client { } }; +void server_models_sse::notify(const std::string & event, const std::string & model_id, const json & data) { + std::unique_ptr result = std::make_unique(); + result->data = { + {"model", model_id}, + {"event", event}, + }; + if (!data.is_null()) { + result->data["data"] = data; + } + SRV_DBG("notifying SSE clients about event '%s' for model '%s': %s\n", event.c_str(), model_id.c_str(), safe_json_to_str(result->data).c_str()); + // under the lock, so that a client connecting meanwhile gets this event either replayed or queued, not both + std::lock_guard lk(mutex); + if (replay_last) { + last_event = result->data; + } + queue.broadcast(std::move(result)); +} + +server_http_context::handler_t server_models_sse::make_handler(std::function should_stop) { + return [this, should_stop = std::move(should_stop)](const server_http_req & req) { + auto res = std::make_unique(); + res->status = 200; + res->content_type = "text/event-stream"; + std::shared_ptr sse_client; + std::string pending; // the replayed event, sent first + { + std::lock_guard lk(mutex); + sse_client = std::make_shared(queue); + if (replay_last && !last_event.is_null()) { + pending = "data: " + safe_json_to_str(last_event) + "\n\n"; + } + } + res->next = [should_stop, sse_client, pending = std::move(pending), &req](std::string & output) mutable -> bool { + if (!pending.empty()) { + output = std::move(pending); + pending.clear(); + return true; + } + auto result = sse_client->next([&]() { + return should_stop() || req.should_stop(); + }); + if (result == nullptr) { + return false; // client disconnected or should_stop + } + output = "data: " + safe_json_to_str(result->to_json()) + "\n\n"; + return true; // listen for the next event + }; + return res; + }; +} + +// +// server_models_routes +// + static void res_ok(std::unique_ptr & res, const json & response_data) { res->status = 200; res->data = safe_json_to_str(response_data); @@ -2312,23 +2358,9 @@ void server_models_routes::init_routes() { return res; }; - this->get_router_models_sse = [this](const server_http_req & req) { - auto res = std::make_unique(); - res->status = 200; - res->content_type = "text/event-stream"; - auto sse_client = std::make_shared(models.sse); - res->next = [this, sse_client, &req](std::string & output) -> bool { - auto result = sse_client->next([&]() { - return stopping.load(std::memory_order_relaxed) || req.should_stop(); - }); - if (result == nullptr) { - return false; // client disconnected or should_stop - } - output = "data: " + safe_json_to_str(result->to_json()) + "\n\n"; - return true; // listen for the next event - }; - return res; - }; + this->get_router_models_sse = models.sse.make_handler([this]() { + return stopping.load(std::memory_order_relaxed); + }); this->post_router_models = [this](const server_http_req & req) { auto res = std::make_unique(); diff --git a/tools/server/server-models.h b/tools/server/server-models.h index e18ae3a31f43..fa5322ad8c28 100644 --- a/tools/server/server-models.h +++ b/tools/server/server-models.h @@ -157,6 +157,25 @@ struct server_unfinished_downloads { void delete_partials(const std::vector & parts); }; +// broadcasts model events to the clients of GET /models/sse, used by both router and single-model mode +struct server_models_sse { + // send the last event to each new client, for single-model mode where GET /models is unavailable while loading + const bool replay_last; + + server_models_sse(bool replay_last = false) : replay_last(replay_last) {} + + // thread-safe + void notify(const std::string & event, const std::string & model_id, const json & data = nullptr); + + // handler for GET /models/sse, a client is disconnected once should_stop() returns true + server_http_context::handler_t make_handler(std::function should_stop); + +private: + std::mutex mutex; + json last_event; + server_response queue; +}; + struct server_models_routes; struct server_monitor; // defined in server-models.cpp @@ -289,7 +308,7 @@ struct server_models { server_models(const common_params & params, int argc, char ** argv); ~server_models(); - server_response sse; // for real-time updates via SSE endpoint + server_models_sse sse; // for real-time updates via SSE endpoint // (re-)load the list of models from various sources and prepare the metadata mapping // - if this is called the first time, simply populate the metadata diff --git a/tools/server/server.cpp b/tools/server/server.cpp index fabf0a0413c8..e022355dca80 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -109,6 +109,7 @@ static server_role_type server_role_detect(const common_params & params, server_ } // a server given no model is a router const bool has_model = !params.model.path.empty() + || !params.model.url.empty() || !params.model.hf_repo.empty() || !params.model.docker_repo.empty(); return has_model ? SERVER_ROLE_INSTANCE : SERVER_ROLE_ROUTER; @@ -363,66 +364,45 @@ static bool server_on_listening(server_http_context & ctx_http, const common_par return true; } -// -// download worker: a child of the router that pulls a model into the cache and reports the progress -// - -struct server_download_state : public common_download_callback { - server_role * role; +// throttled download progress, shared by the download worker and single-model mode +struct server_download_progress : public common_download_callback { + // called under the lock, the files are downloaded in parallel threads + std::function on_progress; std::function should_stop; - // files download in parallel threads: throttle each file on its own, a shared - // timer lets a small, fast file (e.g. a draft) starve the updates of the others - std::mutex progress_mutex; + // throttle each file on its own, a shared timer lets a small, fast file (e.g. a draft) starve the updates of the others + std::mutex mutex; std::unordered_map last_progress_time; - bool is_ok = false; - server_download_state(server_role * r) : role(r) {} - - bool run(common_params & params) { - try { - common_models_handler handler = common_models_handler_init(params, LLAMA_EXAMPLE_SERVER); - common_models_handler_apply(handler, params, this); - is_ok = true; - } catch (const std::exception & e) { - auto model_name = params.model.get_name(); - SRV_ERR("download failed for model name=%s: %s\n", model_name.c_str(), e.what()); - is_ok = false; - } - return is_ok; - } - void on_progress(const common_download_progress & p) { - json data = { - {"url", p.url}, - {"downloaded", p.downloaded}, - {"total", p.total}, - }; - role->notify_to_router(server_state_to_str(SERVER_STATE_DOWNLOADING), data); + void notify(const common_download_progress & p) { + std::lock_guard lk(mutex); + on_progress(p); } void on_start(const common_download_progress & p) override { - on_progress(p); + notify(p); } void on_update(const common_download_progress & p) override { int64_t now = ggml_time_ms(); - // throttle progress updates to avoid flooding logs; the first update of a file - // always passes, it carries the file's total size - { - std::lock_guard lk(progress_mutex); - auto it = last_progress_time.find(p.url); - if (it != last_progress_time.end() && now - it->second < 100) { - return; - } - last_progress_time[p.url] = now; + // the first update of a file always passes, it carries the file's total size + std::lock_guard lk(mutex); + auto it = last_progress_time.find(p.url); + if (it != last_progress_time.end() && now - it->second < 100) { + return; } + last_progress_time[p.url] = now; on_progress(p); } void on_done(const common_download_progress & p, bool) override { - on_progress(p); + notify(p); } bool is_cancelled() const override { return should_stop ? should_stop() : false; } }; +// +// download worker: a child of the router that pulls a model into the cache and reports the progress +// + static int server_run_download(common_params & params, server_role & role) { auto cancelled = std::make_shared>(false); @@ -431,12 +411,27 @@ static int server_run_download(common_params & params, server_role & role) { cancelled->store(true, std::memory_order_relaxed); }); - server_download_state dl(&role); + server_download_progress dl; + dl.on_progress = [&role](const common_download_progress & p) { + role.notify_to_router(server_state_to_str(SERVER_STATE_DOWNLOADING), { + {"url", p.url}, + {"downloaded", p.downloaded}, + {"total", p.total}, + }); + }; dl.should_stop = [cancelled]() { return cancelled->load(std::memory_order_relaxed); }; - bool ok = dl.run(params); + bool ok = true; + try { + common_models_handler handler = common_models_handler_init(params, LLAMA_EXAMPLE_SERVER); + common_models_handler_apply(handler, params, &dl); + } catch (const std::exception & e) { + auto model_name = params.model.get_name(); + SRV_ERR("download failed for model name=%s: %s\n", model_name.c_str(), e.what()); + ok = false; + } role.notify_to_router(server_state_to_str(SERVER_STATE_DOWNLOADING), { {"result", ok ? "download_finished" : "download_failed"}, @@ -638,15 +633,21 @@ static int server_run_router(common_params & params, int argc, char ** argv, con // static int server_run_instance(common_params & params, server_role & role, common_models_handler & models_handler, const server_run_opts & opts) { - // -hf / docker: download if needed and resolve the local path. a child resolves what the router downloaded - if (opts.resolve_model) { - try { - common_models_handler_apply(models_handler, params); - } catch (const std::exception & e) { - SRV_ERR("failed to download model: %s\n", e.what()); - return 1; + // a router child reports its state to the router, a single-model server to its own /models/sse clients + const bool managed = role.is_managed_by_router(); + const std::string model_name = server_get_model_name(params); + server_models_sse sse(/* replay_last */ true); + std::atomic sse_stopping = false; + + auto notify = [&](const std::string & event, const json & data = nullptr) { + if (!managed) { + sse.notify(event, model_name, data); } - } + }; + auto notify_status = [&](server_model_status status, json data = json::object()) { + data["status"] = server_model_status_to_string(status); + notify("status_change", data); + }; // note: this is guaranteed to out-live ctx_http and tools server_mcp mcp_mgr; @@ -667,37 +668,82 @@ static int server_run_instance(common_params & params, server_role & role, commo server_stream_make_get_handler(), server_stream_make_lookup_handler(), server_stream_make_delete_handler()); + if (!managed) { + ctx_http.get("/models/sse", ex_wrapper(sse.make_handler([&sse_stopping]() { + return sse_stopping.load(std::memory_order_relaxed); + }))); + } if (!server_setup_features(ctx_http, params, mcp_mgr, tools, SERVER_ROLE_INSTANCE)) { return 1; } // setup clean up function, to be called before exit - auto clean_up = [&ctx_http, &ctx_server, &mcp_mgr]() { + auto clean_up = [&ctx_http, &ctx_server, &mcp_mgr, &sse_stopping]() { SRV_INF("%s: cleaning up before exit...\n", __func__); // stop the session GC first, it finalizes live sessions and wakes pending readers server_stream_session_manager_stop(); + sse_stopping.store(true); // disconnect the SSE clients ctx_http.stop(); ctx_server.terminate(); mcp_mgr.shutdown(); llama_backend_free(); }; - // start the HTTP server before loading the model to be able to serve /health requests + // start the HTTP server before downloading and loading the model to be able to serve /health and /models/sse requests if (!ctx_http.start()) { clean_up(); SRV_ERR("%s", "exiting due to HTTP server error\n"); return 1; } - // setup communication child --> router if necessary - if (role.is_managed_by_router()) { - ctx_server.set_state_callback([&](server_state state, json payload) { - role.notify_to_router(server_state_to_str(state), payload); - }); + // -hf / docker: download if needed and resolve the local path. a child resolves what the router downloaded + if (opts.resolve_model) { + json progress = json::object(); // url -> {done, total}, the same shape as the router sends + server_download_progress dl; + dl.on_progress = [&](const common_download_progress & p) { + if (p.total == 0) { + return; // not started yet, or found in the cache + } + progress[p.url] = { + {"done", p.downloaded}, + {"total", p.total}, + }; + notify("download_progress", {{"progress", progress}}); + }; + try { + common_models_handler_apply(models_handler, params, managed ? nullptr : &dl); + if (!progress.empty()) { + notify("download_finished"); + } + } catch (const std::exception & e) { + SRV_ERR("failed to download model: %s\n", e.what()); + notify("download_failed"); + notify_status(SERVER_MODEL_STATUS_UNLOADED, {{"exit_code", 1}}); + clean_up(); + ctx_http.join(); + return 1; + } } + // setup communication child --> router, or to the SSE clients + ctx_server.set_state_callback([&](server_state state, json payload) { + if (managed) { + role.notify_to_router(server_state_to_str(state), payload); + return; + } + switch (state) { + case SERVER_STATE_LOADING: notify_status(SERVER_MODEL_STATUS_LOADING, {{"progress", payload}}); break; + case SERVER_STATE_READY: notify_status(SERVER_MODEL_STATUS_LOADED); break; // wakeup from sleeping + case SERVER_STATE_SLEEPING: notify_status(SERVER_MODEL_STATUS_SLEEPING); break; + default: break; + } + }); + + notify_status(SERVER_MODEL_STATUS_LOADING); + if (!ctx_server.load_model(params)) { + notify_status(SERVER_MODEL_STATUS_UNLOADED, {{"exit_code", 1}}); clean_up(); ctx_http.join(); SRV_ERR("%s", "exiting due to model loading error\n"); @@ -709,7 +755,22 @@ static int server_run_instance(common_params & params, server_role & role, commo SRV_INF("%s", "model loaded\n"); + json info = routes.get_model_info(); + json memory; + if (const auto * ll_ctx = ctx_server.get_llama_context()) { + memory = server_model_memory(llama_n_ctx(ll_ctx), common_memory_breakdown_rows(ll_ctx)).to_json(); + } + + { + json data = {{"info", info}}; + if (!memory.is_null()) { + data["memory"] = memory; + } + notify_status(SERVER_MODEL_STATUS_LOADED, data); + } + shutdown_handler = [&](int) { + sse_stopping.store(true); mcp_mgr.shutdown(); // this will unblock start_loop() ctx_server.terminate(); @@ -729,12 +790,11 @@ static int server_run_instance(common_params & params, server_role & role, commo // optionally, notify router server that this instance is ready std::thread monitor_thread; - if (role.is_managed_by_router()) { + if (managed) { monitor_thread = role.setup(shutdown_handler); - json info = routes.get_model_info(); // the router tracks device memory from these reports - if (const auto * ll_ctx = ctx_server.get_llama_context()) { - info["memory"] = server_model_memory(llama_n_ctx(ll_ctx), common_memory_breakdown_rows(ll_ctx)).to_json(); + if (!memory.is_null()) { + info["memory"] = memory; } role.notify_to_router(server_state_to_str(SERVER_STATE_READY), info); } diff --git a/tools/server/tests/unit/test_basic.py b/tools/server/tests/unit/test_basic.py index 423a7c326cfa..ad3cea679ee2 100644 --- a/tools/server/tests/unit/test_basic.py +++ b/tools/server/tests/unit/test_basic.py @@ -143,3 +143,19 @@ def test_server_model_aliases_and_tags(): assert set(model["tags"]) == {"chat", "fim", "small"} # id is derived from first alias (alphabetical order from std::set) assert model["id"] == "code" + + +def test_server_models_sse_single_model(): + global server + server.start() + # a client connecting after the load gets the last status replayed + with requests.get(server.make_url("/models/sse"), stream=True, timeout=10) as res: + assert res.status_code == 200 + assert res.headers["Content-Type"].startswith("text/event-stream") + line = next(x for x in res.iter_lines() if x) + event = json.loads(line.decode("utf-8").removeprefix("data: ")) + model_id = server.make_request("GET", "/models").body["data"][0]["id"] + assert event["model"] == model_id + assert event["event"] == "status_change" + assert event["data"]["status"] == "loaded" + assert event["data"]["info"]["id"] == model_id From 1014775c8a10e52d2cc3189a13d3b9437fa0213c Mon Sep 17 00:00:00 2001 From: Aldehir Rojas Date: Sun, 22 Nov 2026 11:36:03 -0600 Subject: [PATCH 15/24] chat : implement token aware parsing (#29307) --- common/chat-auto-parser-generator.cpp | 10 +- common/chat-auto-parser.h | 1 + common/chat-peg-parser.h | 11 + common/chat.cpp | 20 +- common/chat.h | 6 + common/json-schema-to-grammar.cpp | 4 +- common/parsers/gemma4.cpp | 55 +- common/parsers/gpt-oss.cpp | 61 +- common/parsers/harmony-xml.cpp | 7 +- common/parsers/k2-horizon.cpp | 4 +- common/parsers/minicpm5.cpp | 4 +- common/parsers/minimax-m3.cpp | 6 +- common/parsers/muse-glimmer.cpp | 54 +- common/parsers/muse-spark.cpp | 5 +- common/parsers/qwen3-coder.cpp | 79 +-- common/peg-parser.cpp | 660 ++++++++++++++++++---- common/peg-parser.h | 94 ++- common/reasoning-budget.cpp | 8 +- common/trie.cpp | 74 ++- common/trie.h | 61 +- docs/development/parsing.md | 131 +++++ grammars/README.md | 6 +- src/llama-grammar.cpp | 216 +++++-- src/llama-grammar.h | 20 +- tests/peg-parser/test-basic.cpp | 43 ++ tests/peg-parser/test-gbnf-generation.cpp | 362 +++++++++--- tests/test-chat.cpp | 273 +++++++-- tests/test-grammar-integration.cpp | 189 ++++++- tests/test-grammar-parser.cpp | 24 + tests/test-llama-grammar.cpp | 2 +- 30 files changed, 1988 insertions(+), 502 deletions(-) diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp index e59a556ad08c..220889367754 100644 --- a/common/chat-auto-parser-generator.cpp +++ b/common/chat-auto-parser-generator.cpp @@ -373,7 +373,9 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte auto & p = ctx.p; const auto & inputs = ctx.inputs; - auto until_suffix = p.rule("until-suffix", p.until(arguments.value_suffix)); + // A raw string value needs a suffix to end on, without one it is parsed as JSON + bool raw_strings = !arguments.value_suffix.empty(); + auto until_suffix = raw_strings ? p.rule("until-suffix", p.until(arguments.value_suffix)) : p.eps(); common_peg_parser tool_choice = p.choice(); @@ -389,9 +391,9 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte p.tool_arg(p.tool_arg_open(arguments.name_prefix + p.tool_arg_name(p.literal(param.name)) + arguments.name_suffix) + arguments.value_prefix + - (param.schema->may_be_string() ? - p.ac(p.tool_arg_string_value(until_suffix) + - p.tool_arg_close(p.literal(arguments.value_suffix)), arguments.value_suffix) : + (raw_strings && param.schema->may_be_string() ? + p.through(p.tool_arg_string_value(until_suffix), + p.tool_arg_close(p.literal(arguments.value_suffix))) : (p.tool_arg_json_value(p.schema( p.json(), "tool-" + std::to_string(tool_index) + "-arg-" + std::to_string(param_index) + "-schema", doc, *param.schema)) + p.tool_arg_close(p.literal(arguments.value_suffix))))); diff --git a/common/chat-auto-parser.h b/common/chat-auto-parser.h index 8ae15c91e1e5..696b9e5e66b5 100644 --- a/common/chat-auto-parser.h +++ b/common/chat-auto-parser.h @@ -71,6 +71,7 @@ struct generation_params { bool is_inference = true; bool add_inference = false; bool mark_input = true; // whether to mark input strings in the jinja context + common_peg_tokens specials; bool has_continuation() const { return continue_final_message != COMMON_CHAT_CONTINUATION_NONE && !continue_msg.empty(); diff --git a/common/chat-peg-parser.h b/common/chat-peg-parser.h index c77ec117b5aa..b39607e5cd88 100644 --- a/common/chat-peg-parser.h +++ b/common/chat-peg-parser.h @@ -71,6 +71,9 @@ constexpr size_t COMMON_CHAT_MAX_PERMUTE = 6; class common_chat_peg_builder : public common_peg_parser_builder { public: + common_chat_peg_builder() = default; + explicit common_chat_peg_builder(common_peg_tokens tokens) : common_peg_parser_builder(std::move(tokens)) {} + // Tag constants (from former common_chat_peg_base_builder) static constexpr const char * REASONING_BLOCK = "reasoning-block"; static constexpr const char * REASONING = "reasoning"; @@ -200,6 +203,14 @@ inline common_peg_arena build_chat_peg_parser( return builder.build(); } +inline common_peg_arena build_chat_peg_parser( + const common_peg_tokens & specials, + const std::function & fn) { + common_chat_peg_builder builder(specials); + builder.set_root(fn(builder)); + return builder.build(); +} + class tag_based_peg_mapper { public: std::map tags; diff --git a/common/chat.cpp b/common/chat.cpp index de5f1c490303..3cff920cf16b 100644 --- a/common/chat.cpp +++ b/common/chat.cpp @@ -315,6 +315,7 @@ struct common_chat_templates { bool add_bos; bool add_eos; bool has_explicit_template; // Model had builtin template or template overridden was specified. + common_peg_tokens specials; std::unique_ptr template_default; // always set (defaults to chatml) std::unique_ptr template_tool_use; std::unique_ptr template_tts; // the prompt of a text to speak @@ -802,6 +803,10 @@ void common_chat_templates_free(struct common_chat_templates * tmpls) { delete tmpls; } +void common_chat_templates_set_specials(struct common_chat_templates * tmpls, common_peg_tokens specials) { + tmpls->specials = std::move(specials); +} + bool common_chat_templates_was_explicit(const struct common_chat_templates * tmpls) { return tmpls->has_explicit_template; } @@ -978,6 +983,7 @@ common_chat_templates_ptr common_chat_templates_init(const struct llama_model * std::string token_eos = eos_token_override; bool add_bos = false; bool add_eos = false; + common_peg_tokens specials; if (model) { const auto * vocab = llama_model_get_vocab(model); const auto get_token = [&](llama_token token, const char * name, const char * jinja_variable_name) { @@ -997,11 +1003,13 @@ common_chat_templates_ptr common_chat_templates_init(const struct llama_model * token_eos = get_token(llama_vocab_eos(vocab), "EOS", "eos_token"); add_bos = llama_vocab_get_add_bos(vocab); add_eos = llama_vocab_get_add_eos(vocab); + specials = common_peg_tokens(vocab); } common_chat_templates_ptr tmpls(new common_chat_templates()); tmpls->has_explicit_template = has_explicit_template; tmpls->add_bos = add_bos; tmpls->add_eos = add_eos; + tmpls->specials = std::move(specials); try { tmpls->template_default = std::make_unique(default_template_src, token_bos, token_eos); } catch (const std::exception & e) { @@ -1543,6 +1551,7 @@ static common_chat_params common_chat_templates_apply_jinja(const struct common_ params.add_generation_prompt = inputs.add_generation_prompt; params.add_bos = tmpls->add_bos; params.add_eos = tmpls->add_eos; + params.specials = tmpls->specials; params.continue_final_message = inputs.continue_final_message; if (params.continue_final_message != COMMON_CHAT_CONTINUATION_NONE) { @@ -1825,6 +1834,7 @@ common_chat_input common_chat_input_tokenize(const llama_vocab * vocab, const st } if (input.text != text) { // the pieces do not give back the same text, keep the text without tokens + LOG_WRN("%s: token pieces do not match the text, parsing without token ids\n", __func__); return common_chat_input(text); } return input; @@ -1935,11 +1945,17 @@ common_chat_session::common_chat_session(const common_chat_templates * tm thinking_ends = std::move(applied.thinking_end_tags); parser_params.format = applied.format; - parser_params.generation_prompt = vocab ? common_chat_input_tokenize(vocab, applied.generation_prompt) - : common_chat_input(applied.generation_prompt); parser_params.debug = params.debug; parser_params.parser = std::move(applied.parser); + if (vocab) { + parser_params.generation_prompt = common_chat_input_tokenize(vocab, applied.generation_prompt); + } else if (params.tokenize) { + parser_params.generation_prompt = params.tokenize(applied.generation_prompt); + } else { + parser_params.generation_prompt = common_chat_input(applied.generation_prompt); + } + delimiters = std::move(applied.message_delimiters); if (vocab) { diff --git a/common/chat.h b/common/chat.h index 43331b16d4a0..ca324d8121c6 100644 --- a/common/chat.h +++ b/common/chat.h @@ -372,6 +372,9 @@ common_chat_templates_ptr common_chat_templates_init(const struct llama_model * const std::string & bos_token_override = "", const std::string & eos_token_override = ""); +// override special tokens for testing +void common_chat_templates_set_specials(struct common_chat_templates * tmpls, common_peg_tokens specials); + bool common_chat_templates_was_explicit(const struct common_chat_templates * tmpls); std::string common_chat_templates_source(const struct common_chat_templates * tmpls, const std::string & variant = ""); @@ -397,6 +400,9 @@ common_chat_msg common_chat_peg_parse(const common_peg_arena & src_parser, const struct common_chat_session_params { bool echo = false; // include the assistant prefill in the output when continuing a message bool debug = false; // enable debug output for the PEG parser + + // tokenize the generation prompt when there is no vocab for testing + std::function tokenize; }; class common_chat_session { diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp index b6ea61fc3870..4690a57fa4ca 100644 --- a/common/json-schema-to-grammar.cpp +++ b/common/json-schema-to-grammar.cpp @@ -676,8 +676,8 @@ class common_chat_schema_converter { const auto & node = trie.nodes[idx]; std::string rejects; auto first = true; - for (const auto & [cpt, child] : node.children) { - std::string c = common_unicode_cpt_to_utf8(cpt); + for (const auto & [sym, child] : node.children) { + std::string c = common_unicode_cpt_to_utf8(sym.value); rejects += c; if (first) { first = false; diff --git a/common/parsers/gemma4.cpp b/common/parsers/gemma4.cpp index 2a2e929e19a3..ff4dfad6789e 100644 --- a/common/parsers/gemma4.cpp +++ b/common/parsers/gemma4.cpp @@ -24,7 +24,9 @@ struct depth_guard { // Gemma 4 value parsers void gemma4_value_rules(common_chat_peg_builder & p) { // The tags are what gemma4_to_json() in the mapper reads, the rules may wrap them freely. - p.rule("gemma4-string", p.tag(gemma4::STRING, p.literal("<|\"|>") + p.tag(gemma4::STRING_CONTENT, p.until("<|\"|>")) + p.literal("<|\"|>"))); + auto string_delim = p.token("<|\"|>"); + + p.rule("gemma4-string", p.tag(gemma4::STRING, string_delim + p.tag(gemma4::STRING_CONTENT, p.until(string_delim)) + string_delim)); p.rule("gemma4-bool", p.tag(gemma4::BOOL, p.json_bool())); @@ -34,7 +36,7 @@ void gemma4_value_rules(common_chat_peg_builder & p) { // Keys are bare in the template, but Gemma 4 occasionally wraps them in quotes p.rule("gemma4-dict-key", p.tag(gemma4::DICT_KEY, p.choice({ - p.literal("<|\"|>") + p.tag(gemma4::DICT_KEY_NAME, p.until("<|\"|>")) + p.literal("<|\"|>"), + string_delim + p.tag(gemma4::DICT_KEY_NAME, p.until(string_delim)) + string_delim, p.literal("\"") + p.tag(gemma4::DICT_KEY_NAME, p.chars("[^\"]", 1, -1)) + p.literal("\""), p.literal("'") + p.tag(gemma4::DICT_KEY_NAME, p.chars("[^']", 1, -1)) + p.literal("'"), p.tag(gemma4::DICT_KEY_NAME, p.chars("[^:}]", 1, -1)), @@ -144,7 +146,7 @@ class gemma4_schema_parser { alts |= name(); } // Gemma 4 may emit keys in its string delimiters or quotes - alts |= p_.literal("<|\"|>") + name() + p_.literal("<|\"|>"); + alts |= p_.token("<|\"|>") + name() + p_.token("<|\"|>"); if (key.find('\'') == std::string::npos) { alts |= p_.literal("'") + name() + p_.literal("'"); } @@ -331,18 +333,23 @@ common_chat_params common_chat_params_init_gemma4(const common_chat_template & auto include_grammar = has_response_format || (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE); auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE; - data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) { - auto start = p.rule("start", p.optional(p.literal("<|turn>model\n"))); + data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) { + auto start = p.rule("start", p.optional(p.token("<|turn>") + p.literal("model\n"))); + auto channel_start = p.token("<|channel>"); + auto channel_end = p.token(""); + auto think_start = channel_start + p.literal("thought"); + auto tool_call_start = p.token("<|tool_call>"); + // the model may start a tool call before closing the thought channel + auto think_end = channel_end | p.peek(tool_call_start); if (extract_reasoning) { - // the model may start a tool call before closing the thought channel - p.rule("thought", p.literal("<|channel>thought") + p.space() + p.reasoning(p.until_one_of({"", "<|tool_call>"})) + (p.literal("") | p.peek(p.literal("<|tool_call>")))); + p.rule("thought", think_start + p.space() + p.reasoning(p.until(channel_end | tool_call_start)) + think_end); } else { - p.rule("thought", p.content(p.literal("<|channel>thought") + p.space() + p.until_one_of({"", "<|tool_call>"}) + (p.literal("") | p.peek(p.literal("<|tool_call>"))))); + p.rule("thought", p.content(think_start + p.space() + p.until(channel_end | tool_call_start) + think_end)); } - auto consume_empty_channels = p.gbnf(p.zero_or_more(p.literal("<|channel>") + p.negate(p.literal("thought"))), ""); - auto thought = (p.peek(p.literal("<|channel>")) + consume_empty_channels + p.ref("thought")) | p.negate(p.literal("<|channel>")); + auto consume_empty_channels = p.gbnf(p.zero_or_more(channel_start + p.negate(p.literal("thought"))), ""); + auto thought = (p.peek(channel_start) + consume_empty_channels + p.ref("thought")) | p.negate(channel_start); if (has_response_format) { auto response_format = p.literal("```json") << @@ -378,39 +385,35 @@ common_chat_params common_chat_params_init_gemma4(const common_chat_template & }))); }); - auto tool_call = p.trigger_rule("tool-call", p.repeat( - "<|tool_call>call:" + tool_choice + "", - /* min = */ inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0, - /* max = */ inputs.parallel_tool_calls ? -1 : 1 - )); + auto tool_call_rest = p.literal("call:") + tool_choice + p.token(""); + auto tool_call = p.rule("tool-call", tool_call_start + tool_call_rest); + auto more = inputs.parallel_tool_calls ? p.zero_or_more(tool_call) : p.eps(); + + auto tool_calls = p.trigger_rule("tool-calls", tool_call_start, tool_call_rest + more); if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) { - return start + thought + tool_call; + return start + thought + tool_calls; } - auto scan_to_toolcall = p.rule("scan-to-toolcall", p.until("<|tool_call>")); - auto content = p.rule("content", p.content(p.until_one_of({"<|channel>", "", "<|tool_call>"}))); + auto scan_to_toolcall = p.rule("scan-to-toolcall", p.until(tool_call_start)); + auto content = p.rule("content", p.content(p.until(channel_start | channel_end | tool_call_start))); auto message = p.rule("message", thought + content); - return start + p.zero_or_more(message) + scan_to_toolcall + tool_call; + return start + p.zero_or_more(message) + scan_to_toolcall + p.optional(tool_calls); } // Gemma 4 may emit an extra <|channel>thought\n at the end of the content. It may // also emit a single trailing token. Consume all complete reasoning blocks and // then stop at the first unmatched token. - auto content = p.rule("content", p.content(p.until_one_of({"<|channel>", ""}))); + auto content = p.rule("content", p.content(p.until(channel_start | channel_end))); auto message = p.rule("message", thought + content); return start + p.one_or_more(message); }); if (include_grammar) { - data.grammar_lazy = !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED)); + data.grammar_lazy = false; data.grammar = build_grammar([&](const common_grammar_builder & builder) { - data.parser.build_grammar(builder, data.grammar_lazy); + data.parser.build_grammar(builder, !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED))); }); - - data.grammar_triggers = { - { COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "<|tool_call>" }, - }; } return data; diff --git a/common/parsers/gpt-oss.cpp b/common/parsers/gpt-oss.cpp index 4cbf929f9bfd..fbc388c97c2d 100644 --- a/common/parsers/gpt-oss.cpp +++ b/common/parsers/gpt-oss.cpp @@ -65,17 +65,18 @@ common_chat_params common_chat_params_init_gpt_oss(const common_chat_template & auto include_grammar = has_response_format || (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE); auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE; - data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) { - auto start = p.rule("start", p.literal("<|start|>assistant")); - auto end = p.rule("end", p.literal("<|end|>")); - auto content = p.rule("message-content", p.until("<|end|>")); - auto channel = p.literal("<|channel|>") + (p.literal("commentary") | p.literal("analysis")); + data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) { + auto start_assistant = p.token("<|start|>") + p.literal("assistant"); + auto start = p.rule("start", start_assistant); + auto end = p.rule("end", p.token("<|end|>")); + auto content = p.rule("message-content", p.until(p.token("<|end|>"))); + auto channel = p.token("<|channel|>") + (p.literal("commentary") | p.literal("analysis")); auto constrain_type = p.chars("[A-Za-z0-9_-]", 1, -1); - auto constraint = p.optional(p.space() + p.optional(p.literal("<|constrain|>")) + constrain_type); + auto constraint = p.optional(p.chars("[ ]", 1, -1) + p.optional(p.token("<|constrain|>")) + constrain_type); // Occasionally, gpt-oss-20b will prefix channels with this commentary - auto stray_commentary = p.optional(p.literal("<|channel|>commentary") + p.optional(p.literal(" to=assistant"))); - auto start_analysis = stray_commentary + p.literal("<|channel|>analysis<|message|>"); + auto stray_commentary = p.optional(p.token("<|channel|>") + p.literal("commentary") + p.optional(p.literal(" to=assistant"))); + auto start_analysis = stray_commentary + p.token("<|channel|>") + p.literal("analysis") + p.token("<|message|>"); if (extract_reasoning) { p.rule("analysis", start_analysis + p.reasoning(content) + end); @@ -84,8 +85,8 @@ common_chat_params common_chat_params_init_gpt_oss(const common_chat_template & } auto analysis = p.ref("analysis"); - auto preamble = p.rule("preamble", p.literal("<|channel|>commentary<|message|>") + p.content(content) + end); - auto final_msg = p.rule("final", stray_commentary + p.literal("<|channel|>final") + constraint + p.literal("<|message|>") + p.content(content)); + auto preamble = p.rule("preamble", p.token("<|channel|>") + p.literal("commentary") + p.token("<|message|>") + p.content(content) + end); + auto final_msg = p.rule("final", stray_commentary + p.token("<|channel|>") + p.literal("final") + constraint + p.token("<|message|>") + p.content(content)); // Consume any unsolicited tool calls, e.g. builtin functions auto unsolicited = p.rule("unsolicited", p.atomic(p.optional(channel) + p.literal(" to=") + content + end)); @@ -94,58 +95,58 @@ common_chat_params common_chat_params_init_gpt_oss(const common_chat_template & if (has_response_format) { auto response_format = p.rule("response-format", - p.literal("<|channel|>final") + constraint + p.literal("<|message|>") + + p.token("<|channel|>") + p.literal("final") + constraint + p.token("<|message|>") + p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema))); return p.zero_or_more(start + analysis) + start + response_format; } if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) { - auto tool_choice = p.choice(); + auto in_role = p.choice(); + auto in_channel = p.choice(); foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) { const auto & function = tool.at("function"); std::string name = function.at("name"); const auto params = common_chat_tool_parameters(function); - auto func_name = p.literal(" to=functions.") + p.tool_name(p.literal(name)); + auto func_name = p.tool_name(p.literal(name)); auto args = p.tool_args(p.schema(p.json(), "tool-" + std::to_string(tool_index) + "-schema", params)); // recipient in role header // <|start|>assistant to=functions.NAME<|channel|>(commentary|analysis)[constraint]<|message|>ARGS - auto tool_in_role = p.tool(p.tool_open(func_name + channel + constraint + p.literal("<|message|>")) + args); + in_role |= p.rule("tool-" + std::to_string(tool_index) + "-in-role", + p.atomic(func_name + channel + constraint + p.token("<|message|>")) + args); // recipient in channel header - // <|channel|>(commentary|analysis) to=functions.NAME[constraint]<|message|>ARGS - auto tool_in_channel = p.tool(p.tool_open(channel + func_name + constraint + p.literal("<|message|>")) + args); - - tool_choice |= p.rule("tool-" + std::to_string(tool_index), tool_in_role | tool_in_channel); + // <|start|>assistant<|channel|>(commentary|analysis) to=functions.NAME[constraint]<|message|>ARGS + in_channel |= p.rule("tool-" + std::to_string(tool_index) + "-in-channel", + p.atomic(func_name + constraint + p.token("<|message|>")) + args); }); - auto tool_call = p.trigger_rule("tool-call", tool_choice); + // The recipient prefix is the trigger, so the grammar constrains the name that follows it + auto to_functions = p.tool_open(p.literal(" to=functions.")); + auto tool_call = p.choice({ + p.trigger_rule("tool-call-in-role", start_assistant + to_functions, in_role), + p.trigger_rule("tool-call-in-channel", start_assistant + channel + to_functions, in_channel) + }); if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) { - return p.zero_or_more(start + any) + start + tool_call; + return p.zero_or_more(start + any) + tool_call; } - return p.zero_or_more(start + any) + start + (tool_call | final_msg); + return p.zero_or_more(start + any) + (tool_call | (start + final_msg)); } return p.zero_or_more(start + any) + start + (final_msg | unsolicited); }); if (include_grammar) { - data.grammar_lazy = !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED)); + // The grammar scans for the triggers itself, so the sampler runs it from the first token + data.grammar_lazy = false; data.grammar = build_grammar([&](const common_grammar_builder & builder) { - data.parser.build_grammar(builder, data.grammar_lazy); + data.parser.build_grammar(builder, !has_response_format && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO); }); - - data.grammar_triggers = { - { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "^\\s+to$" }, - { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "^<\\|channel\\|>(?:commentary|analysis)\\s+to=functions$" }, - { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|start\\|>assistant(\\s+to)" }, - { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|start\\|>assistant(<\\|channel\\|>(?:commentary|analysis)\\s+to)" } - }; } return data; diff --git a/common/parsers/harmony-xml.cpp b/common/parsers/harmony-xml.cpp index bf05fac5d680..1a7e3cb82a55 100644 --- a/common/parsers/harmony-xml.cpp +++ b/common/parsers/harmony-xml.cpp @@ -99,8 +99,11 @@ common_chat_params common_chat_params_init_harmony_xml(const common_chat_templat auto arg_close = p.tool_arg_close(p.gbnf( p.literal(PARAM_CLOSE) | (p.literal("\n") + p.peek(p.optional(p.literal("\n")) + next_open)), gbnf_format_literal("\n") + " " + gbnf_format_literal(PARAM_CLOSE.substr(1)) + "?")); - auto arg_string = p.rule("rfl-arg-string", - p.ac(p.tool_arg_string_value(p.until_one_of(string_ends)) + arg_close, PARAM_CLOSE)); + auto string_value = p.tool_arg_string_value(p.until_one_of(string_ends)); + auto arg_string = p.rule("rfl-arg-string", p.through(string_value, p.tool_arg_close(p.literal(PARAM_CLOSE)))); + // the parser also accepts a value with no closing tag, the grammar still requires the closing tag + auto missing_close = string_value + p.tool_arg_close(p.literal("\n") + p.peek(p.optional(p.literal("\n")) + next_open)); + arg_string = p.gbnf(arg_string | missing_close, "rfl-arg-string"); auto arg_sep = p.optional(p.literal("\n")); std::string call_close_gbnf = gbnf_format_literal("<|end|>"); diff --git a/common/parsers/k2-horizon.cpp b/common/parsers/k2-horizon.cpp index e688cd919382..b02330d2dc95 100644 --- a/common/parsers/k2-horizon.cpp +++ b/common/parsers/k2-horizon.cpp @@ -91,7 +91,7 @@ common_chat_params common_chat_params_init_k2_horizon(const common_chat_template } auto think_body = p.until_one_of(data.thinking_end_tags); auto think_block = [&](const common_peg_parser & body) { - return p.optional(THINK_START + p.space() + p.ac(body + think_end, data.thinking_end_tags)); + return p.optional(THINK_START + p.space() + p.through(body, think_end)); }; auto reasoning = extract_reasoning ? think_block(p.reasoning(think_body)) : p.eps(); @@ -110,7 +110,7 @@ common_chat_params common_chat_params_init_k2_horizon(const common_chat_template tool_choice = p.standard_json_tools(CALL_START, CALL_END, inputs.tools, false, true); } else { auto arg_close = p.tool_arg_close(p.literal(ARG_VAL_END)); - auto arg_string = p.rule("xml-arg-string", p.ac(p.tool_arg_string_value(p.until(ARG_VAL_END)) + arg_close, ARG_VAL_END)); + auto arg_string = p.rule("xml-arg-string", p.through(p.tool_arg_string_value(p.until(ARG_VAL_END)), arg_close)); // The models leave out even when asked for xml_typed auto arg_type = call_format == "xml_typed" ? p.optional(ARG_TYPE + p.until(ARG_TYPE_END) + ARG_TYPE_END + p.space()) : p.eps(); diff --git a/common/parsers/minicpm5.cpp b/common/parsers/minicpm5.cpp index 7609865e08c9..ef0fed7fcda5 100644 --- a/common/parsers/minicpm5.cpp +++ b/common/parsers/minicpm5.cpp @@ -63,8 +63,8 @@ common_chat_params common_chat_params_init_minicpm5(const common_chat_template & // CDATA lets a value carry characters that would otherwise close the tag (e.g. // ); capture the inner text only, excluding the CDATA markers. auto string_value = p.choice({ - p.literal("")) + p.literal("]]>"), "]]>") + p.tool_arg_close(p.literal("")), - p.negate(p.literal("")) + p.tool_arg_close(p.literal("")), "") + p.literal("")), "]]>") + p.tool_arg_close(p.literal("")), + p.negate(p.literal("")), p.tool_arg_close(p.literal(""))) }); auto tool_choice = p.choice(); diff --git a/common/parsers/minimax-m3.cpp b/common/parsers/minimax-m3.cpp index 6080bfb00a98..dba02b238ef7 100644 --- a/common/parsers/minimax-m3.cpp +++ b/common/parsers/minimax-m3.cpp @@ -64,8 +64,8 @@ common_chat_params common_chat_params_init_minimax_m3(const common_chat_template if (extract_reasoning) { auto block = inputs.enable_thinking ? p.literal(THINK_START) + p.space() + - p.ac(p.reasoning(p.until(THINK_END)) + p.literal(THINK_END), THINK_END) - : p.literal(THINK_START) + p.ac(p.until(THINK_END) + p.literal(THINK_END), THINK_END); + p.through(p.reasoning(p.until(THINK_END)), THINK_END) + : p.literal(THINK_START) + p.through(p.until(THINK_END), THINK_END); // A turn without reasoning is prefixed with a bare , written either by the // generation prompt (thinking_mode = "disabled") or by the model itself. @@ -113,7 +113,7 @@ common_chat_params common_chat_params_init_minimax_m3(const common_chat_template // A string accepts anything, so a union with a string alternative is a string if (schema.may_be_string()) { - return p.ac(p.tool_arg_string_value(p.until(close)) + close_tag, close); + return p.through(p.tool_arg_string_value(p.until(close)), close_tag); } if (schema.kind() == common_chat_schema::KIND_ANY_OF) { diff --git a/common/parsers/muse-glimmer.cpp b/common/parsers/muse-glimmer.cpp index 78ff50727aa2..a1ee40f498cb 100644 --- a/common/parsers/muse-glimmer.cpp +++ b/common/parsers/muse-glimmer.cpp @@ -17,7 +17,7 @@ common_chat_params common_chat_params_init_muse_glimmer(const common_chat_templa data.supports_thinking = true; data.preserved_tokens = { - "<|start|>", "<|message|>", "<|eom|>", "<|eot|>", + "<|start|>", "<|message|>", "<|eom|>", // ATEM tool-call markup emitted on " to=" turns. "", "", "", "", @@ -48,37 +48,38 @@ common_chat_params common_chat_params_init_muse_glimmer(const common_chat_templa // Constrained grammar whenever tools are offered or a response format is requested. auto include_grammar = has_response_format || (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE); - data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) { - auto start = p.rule("start", p.literal("<|start|>assistant")); + data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) { + auto start_token = p.token("<|start|>"); + auto message = p.token("<|message|>"); + auto eom = p.token("<|eom|>"); + auto start = p.rule("start", start_token + p.literal("assistant")); if (!extract_reasoning && !include_grammar) { return start + p.content(p.rest()); } if (extract_reasoning) { - p.rule("analysis", p.literal(" to=self<|message|>") + p.reasoning(p.until("<|eom|>")) + p.literal("<|eom|>")); + p.rule("analysis", p.literal(" to=self") + message + p.reasoning(p.until(eom)) + eom); } else { - p.rule("analysis", p.literal(" to=self<|message|>") + p.content(p.until("<|eom|>")) + p.literal("<|eom|>")); + p.rule("analysis", p.literal(" to=self") + message + p.content(p.until(eom)) + eom); } auto analysis = p.ref("analysis"); auto recipient = p.optional(p.literal(" to=user")); - auto final_msg = p.rule("final", recipient + p.literal("<|message|>") + - p.content(p.until_one_of({ "<|eot|>", "<|eom|>" }))); + auto final_msg = p.rule("final", recipient + message + p.content(p.until(eom))); if (has_response_format) { auto response_json = p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema)); auto response_format = p.rule("response-format", - recipient + p.literal("<|message|>") + + recipient + message + ((p.literal("```json") + p.space() + response_json + p.space() + p.literal("```")) | response_json)); return p.zero_or_more(start + analysis) + start + response_format; } if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) { - auto string_value = p.ac( - p.tool_arg_string_value(p.until("")) + p.tool_arg_close(p.literal("")), - ""); + auto string_value = p.through(p.tool_arg_string_value(p.until("")), + p.tool_arg_close(p.literal(""))); auto tool_choice = p.choice(); foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) { @@ -106,40 +107,35 @@ common_chat_params common_chat_params_init_muse_glimmer(const common_chat_templa args = p.zero_or_more(p.choice(arg_rules) + p.space()); } - auto tool_parser = p.tool( - p.tool_open(p.literal(" to=") + p.until("<|message|>") + - p.literal("<|message|>") + p.space() + - p.literal("") + p.space()) + auto open = p.tool_open(start_token + p.literal("assistant to=") + p.tool_name(p.literal(name)) + message); + auto body = p.rule("tool-" + std::to_string(tool_index), + p.literal("") + p.space() + p.literal("") + p.space() << p.tool_args(args) << p.tool_close(p.literal("") + p.space() + p.literal(""))); - tool_choice |= p.rule("tool-" + std::to_string(tool_index), tool_parser); + tool_choice |= open + body; }); - auto tool_calls = inputs.parallel_tool_calls - ? p.trigger_rule("tool-call", tool_choice + p.zero_or_more(p.literal("<|eom|>") + start + tool_choice)) - : p.trigger_rule("tool-call", tool_choice); - + auto more = inputs.parallel_tool_calls ? p.zero_or_more(eom + tool_choice) : p.eps(); + auto tool_calls = p.rule("tool-calls", tool_choice + more); if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) { - return p.zero_or_more(start + analysis) + start + tool_calls; + return p.zero_or_more(start + analysis) + tool_calls; } - auto trailing_calls = p.optional(p.literal("<|eom|>") + start + tool_calls); - return p.zero_or_more(start + analysis) + start + (tool_calls | (final_msg + trailing_calls)); + auto trailing_calls = p.optional(eom + tool_calls); + return p.zero_or_more(start + analysis) + (tool_calls | (start + final_msg + trailing_calls)); } return p.zero_or_more(start + analysis) + start + final_msg; }); if (include_grammar) { - data.grammar_lazy = !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED)); + // Every message starts with a recipient header, so the grammar is not lazy. + // The model cannot generate a recipient that is not self, user, or a tool. + data.grammar_lazy = false; data.grammar = build_grammar([&](const common_grammar_builder & builder) { - data.parser.build_grammar(builder, data.grammar_lazy); + data.parser.build_grammar(builder); }); - data.grammar_triggers = { - { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, - "(?:^|<\\|start\\|>assistant)( to=(?!self<\\|message\\|>)(?!user<\\|message\\|>)[^<]*?<\\|message\\|>)" }, - }; } return data; diff --git a/common/parsers/muse-spark.cpp b/common/parsers/muse-spark.cpp index 945ee2aaf7ba..74a393f4e08c 100644 --- a/common/parsers/muse-spark.cpp +++ b/common/parsers/muse-spark.cpp @@ -86,9 +86,8 @@ common_chat_params common_chat_params_init_muse_spark(const common_chat_template } if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) { - auto string_value = p.ac( - p.tool_arg_string_value(p.until("")) + p.tool_arg_close(p.literal("")), - ""); + auto string_value = p.through(p.tool_arg_string_value(p.until("")), + p.tool_arg_close(p.literal(""))); auto tool_choice = p.choice(); foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) { diff --git a/common/parsers/qwen3-coder.cpp b/common/parsers/qwen3-coder.cpp index b8dc0226722b..c943b93f3be2 100644 --- a/common/parsers/qwen3-coder.cpp +++ b/common/parsers/qwen3-coder.cpp @@ -59,27 +59,16 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat data.prompt.append(data.generation_prompt); } - std::vector tool_call_starts = { "" }; - - if (is_qwen3_coder) { - // Match complete opener for Qwen3-Coder models that occasionally omit the - // starting . The model may hallucinate a tool name, but it is preferable over - // constraining on - foreach_function(inputs.tools, [&](size_t, const json & tool) { - const std::string name = tool.at("function").at("name"); - tool_call_starts.push_back(""); - }); - } - - data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) { + data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) { auto generation_prompt = p.literal(GEN_PREFIX); // The template strips the newline before , so leave it out of the reasoning - auto think_body = p.until_one_of({ "\n", "", "" }); - auto think_close = p.literal("\n") | p.literal("") | p.peek(p.literal("")); + auto think_end = (p.literal("\n") + p.token("")) | p.token(""); + auto think_body = p.until(think_end | p.token("")); + auto think_close = think_end | p.peek(p.token("")); - auto reasoning_extracted = p.optional("" + p.space() + p.reasoning(think_body) + think_close); - auto reasoning_skipped = p.optional("" + p.space() + think_body + think_close); + auto reasoning_extracted = p.optional(p.token("") + p.space() + p.reasoning(think_body) + think_close); + auto reasoning_skipped = p.optional(p.token("") + p.space() + think_body + think_close); auto reasoning = p.eps(); if (supports_reasoning && extract_reasoning) { @@ -99,7 +88,13 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) { auto arg_close = p.tool_arg_close(p.literal("\n\n")); auto arg_string = p.rule("xml-arg-string", - p.ac(p.tool_arg_string_value(p.until("\n\n")) + arg_close, "\n\n")); + p.through(p.tool_arg_string_value(p.until("\n\n")), arg_close)); + + auto min_calls = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0; + + auto more = inputs.parallel_tool_calls ? p.zero_or_more(p.ref("tool-call")) : p.eps(); + auto starts = p.token(""); + auto tool_calls = p.choice(); auto tool_choice = p.choice(); foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) { @@ -155,35 +150,29 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat args = args + p.zero_or_more(p.choice(optional_args)); } - auto func = p.tool(p.tool_open("\n") + - p.tool_args(args) + - p.tool_close(p.literal("\n"))); - - tool_choice |= p.rule("tool-" + std::to_string(tool_index), func); - }); + auto opener = p.tool_open(""); + auto body = p.literal("\n") + p.tool_args(args) + p.tool_close(p.literal("\n")); - auto min_calls = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0; + tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(opener + body)); - auto tool_call_body = tool_choice + "" + p.space(); - auto tool_call = p.rule("tool-call", "\n" + tool_call_body); + if (is_qwen3_coder) { + // Qwen3-Coder models sometimes omit , so the full opener is also a trigger. + // Do not trigger on . + tool_calls |= p.trigger_rule("tool-calls-" + std::to_string(tool_index), opener, body + p.token("") + p.space() + more); + starts |= opener; + } + }); - // Qwen3-Coder models may occasionally omit the token. - auto tool_call_first = is_qwen3_coder ? - p.rule("tool-call-first", p.optional(p.literal("\n")) + tool_call_body) : - tool_call; + auto tool_call_body = tool_choice + p.token("") + p.space(); + p.rule("tool-call", p.token("") + p.literal("\n") + tool_call_body); - auto calls = inputs.parallel_tool_calls ? tool_call_first + p.zero_or_more(tool_call) : tool_call_first; - auto tool_calls = p.trigger_rule("tool-call-root", p.repeat(calls, min_calls, 1)); + tool_calls |= p.trigger_rule("tool-calls", p.token(""), p.literal("\n") + tool_call_body + more); // The templates separate content from the tool calls with one or two newlines, // stop the content before them - std::vector content_ends; - for (const auto & start : tool_call_starts) { - content_ends.insert(content_ends.end(), { "\n\n" + start, "\n" + start, start }); - } + auto content_end = (p.literal("\n\n") + starts) | (p.literal("\n") + starts) | starts; - return generation_prompt + - (reasoning << p.content(p.until_one_of(content_ends)) << tool_calls); + return generation_prompt + (reasoning << p.content(p.until(content_end)) << p.repeat(tool_calls, min_calls, 1)); } // Content only parser @@ -191,17 +180,11 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat }); if (include_grammar) { - data.grammar_lazy = !has_response_format && has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO; - + // The grammar scans for the triggers itself, so the sampler runs it from the first token + data.grammar_lazy = false; data.grammar = build_grammar([&](const common_grammar_builder & builder) { - data.parser.build_grammar(builder, data.grammar_lazy); + data.parser.build_grammar(builder, !has_response_format && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO); }); - - if (data.grammar_lazy) { - for (const auto & start : tool_call_starts) { - data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_WORD, start }); - } - } } return data; diff --git a/common/peg-parser.cpp b/common/peg-parser.cpp index d980cfc76dca..924289097752 100644 --- a/common/peg-parser.cpp +++ b/common/peg-parser.cpp @@ -208,6 +208,89 @@ void common_peg_ast_arena::visit(const common_peg_parse_result & result, const c } } +common_peg_tokens::common_peg_tokens(const llama_vocab * vocab) { + const llama_token n_tokens = llama_vocab_n_tokens(vocab); + for (llama_token id = 0; id < n_tokens; ++id) { + const auto attr = llama_vocab_get_attr(vocab, id); + if (attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED)) { + std::string text = llama_vocab_get_text(vocab, id); + ids.emplace(text, id); + tokens.emplace(id, common_peg_token{ std::move(text), attr }); + } + } +} + +llama_token common_peg_tokens::token_id(const std::string & text) const { + auto it = ids.find(text); + return it != ids.end() ? it->second : LLAMA_TOKEN_NULL; +} + +// Insert every delimiter the parser matches into the trie, starting from each node in from. Returns the end nodes. +// A choice adds the delimiters of each branch. A sequence joins every combination of its children. +static std::set insert_delimiter(common_trie & trie, const common_peg_arena & arena, common_peg_parser_id id, + std::set from = { 0 }) { + return std::visit([&](const auto & p) -> std::set { + using T = std::decay_t; + if constexpr (std::is_same_v || std::is_same_v) { + return insert_delimiter(trie, arena, p.child, std::move(from)); + } else if constexpr (std::is_same_v) { + std::set ends; + for (size_t node : from) { + size_t pos = 0; + while (pos < p.literal.size()) { + auto result = common_parse_utf8_codepoint(p.literal, pos); + if (result.status != utf8_parse_result::SUCCESS) { + break; + } + node = trie.extend(node, common_trie::symbol::codepoint(result.codepoint)); + pos += result.bytes_consumed; + } + ends.insert(node); + } + return ends; + } else if constexpr (std::is_same_v) { + std::set ends; + for (size_t node : from) { + ends.insert(trie.extend(node, common_trie::symbol::token(p.token))); + } + return ends; + } else if constexpr (std::is_same_v) { + std::set ends; + for (auto child : p.children) { + ends.merge(insert_delimiter(trie, arena, child, from)); + } + return ends; + } else if constexpr (std::is_same_v) { + for (auto child : p.children) { + from = insert_delimiter(trie, arena, child, std::move(from)); + } + return from; + } else { + throw std::invalid_argument("a delimiter may only be a sequence of literals, tokens, and choices of them, possibly wrapped in tags and atomics"); + } + }, arena.get(id)); +} + +// Build the matcher of an until parser, each pattern valued by the branch it belongs to +static common_trie build_until_matcher(const common_peg_arena & arena, + const std::vector & branches, + bool include) { + common_trie matcher; + for (size_t b = 0; b < branches.size(); b++) { + for (size_t end : insert_delimiter(matcher, arena, branches[b].delimiter)) { + if (end == 0) { + throw std::invalid_argument("delimiter must not match the empty string"); + } + // nothing follows a delimiter without include, so the first branch to claim it wins + auto owner = matcher.mark(end, (int32_t) b); + if (owner != (int32_t) b && include) { + throw std::invalid_argument("until branches " + std::to_string(owner) + " and " + std::to_string(b) + " must not share a delimiter"); + } + } + } + return matcher; +} + struct parser_executor; common_peg_parser_id common_peg_arena::add_parser(common_peg_parser_variant parser) { @@ -298,6 +381,49 @@ struct parser_executor { return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos); } + common_peg_parse_result operator()(const common_peg_token_parser & p) { + if (start_pos >= ctx.input.size()) { + if (!ctx.is_lenient()) { + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos); + } + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos); + } + + if (start_pos >= ctx.tokens.size() || ctx.tokens[start_pos] != p.token) { + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos); + } + + // Skip the rest of the piece, up to the next token or the end of the input + auto pos = start_pos + 1; + while (pos < ctx.input.size() && ctx.tokens[pos] == LLAMA_TOKEN_NULL) { + ++pos; + } + + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos); + } + + common_peg_parse_result operator()(const common_peg_token_not_parser & p) { + if (start_pos >= ctx.input.size()) { + if (!ctx.is_lenient()) { + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos); + } + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos); + } + + if (start_pos >= ctx.tokens.size() || ctx.tokens[start_pos] == LLAMA_TOKEN_NULL || + std::find(p.tokens.begin(), p.tokens.end(), ctx.tokens[start_pos]) != p.tokens.end()) { + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos); + } + + // Skip the rest of the piece, up to the next token or the end of the input + auto pos = start_pos + 1; + while (pos < ctx.input.size() && ctx.tokens[pos] == LLAMA_TOKEN_NULL) { + ++pos; + } + + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos); + } + common_peg_parse_result operator()(const common_peg_sequence_parser & p) { if (ctx.is_debug()) { LOG_DBG("%sSEQ start at %zu '%s' (%zu children)\n", debug_indent().c_str(), start_pos, @@ -689,7 +815,11 @@ struct parser_executor { } common_peg_parse_result operator()(const common_peg_until_parser & p) const { - common_trie matcher(p.delimiters); + if (p.include) { + return parse_through(p); + } + + const auto & matcher = p.matcher; // Scan input and check for delimiters size_t pos = start_pos; @@ -697,24 +827,24 @@ struct parser_executor { std::vector invalid_utf8; while (pos < ctx.input.size()) { - auto utf8_result = common_parse_utf8_codepoint(ctx.input, pos); + auto step = matcher.next(ctx.input, ctx.tokens, pos); - if (utf8_result.status == utf8_parse_result::INCOMPLETE && ctx.is_lenient()) { + if (step.status == utf8_parse_result::INCOMPLETE && ctx.is_lenient()) { // The rest of the sequence may still arrive, return what we have so far return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, last_valid_pos, {}, std::move(invalid_utf8)); } - if (utf8_result.status != utf8_parse_result::SUCCESS) { + if (step.status != utf8_parse_result::SUCCESS) { // Malformed UTF-8, or a sequence truncated by the end of a complete input. // A delimiter cannot start inside bytes that fail to decode, so consume them and move on - invalid_utf8.push_back({pos, utf8_result.bytes_consumed}); - pos += utf8_result.bytes_consumed; + invalid_utf8.push_back({pos, step.bytes_consumed}); + pos += step.bytes_consumed; last_valid_pos = pos; continue; } // Check if a delimiter starts at this position - auto match = matcher.check_at(ctx.input, pos); + auto match = matcher.check_at(ctx.input, ctx.tokens, pos); if (match == common_trie::COMPLETE_MATCH) { // Found a complete delimiter, return everything before it @@ -727,7 +857,7 @@ struct parser_executor { return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos, {}, std::move(invalid_utf8)); } - pos += utf8_result.bytes_consumed; + pos += step.bytes_consumed; last_valid_pos = pos; } @@ -738,6 +868,48 @@ struct parser_executor { return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, last_valid_pos, {}, std::move(invalid_utf8)); } + // Parse content, then the first branch whose delimiter and rest follow it, like C (D1 R1 | D2 R2 | ...) + common_peg_parse_result parse_through(const common_peg_until_parser & p) const { + auto content = arena.parse(p.content, ctx, start_pos); + if (content.fail() || content.need_more_input()) { + return content; + } + + auto pos = content.end; + for (const auto & branch : p.branches) { + auto nodes = content.nodes; + auto invalid_utf8 = content.invalid_utf8; + auto end = pos; + bool matched = true; + + for (auto id : { branch.delimiter, branch.rest }) { + if (id == COMMON_PEG_INVALID_PARSER_ID) { + continue; + } + auto result = arena.parse(id, ctx, end); + if (result.fail()) { + matched = false; + break; + } + nodes.insert(nodes.end(), result.nodes.begin(), result.nodes.end()); + invalid_utf8.insert(invalid_utf8.end(), result.invalid_utf8.begin(), result.invalid_utf8.end()); + end = result.end; + if (result.need_more_input()) { + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, end, std::move(nodes), std::move(invalid_utf8)); + } + } + if (matched) { + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, end, std::move(nodes), std::move(invalid_utf8)); + } + } + + if (p.optional && pos == ctx.input.size()) { + auto type = ctx.is_lenient() ? COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT : COMMON_PEG_PARSE_RESULT_SUCCESS; + return common_peg_parse_result(type, start_pos, pos, std::move(content.nodes), std::move(content.invalid_utf8)); + } + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos, pos); + } + common_peg_parse_result operator()(const common_peg_schema_parser & p) { return arena.parse(p.child, ctx, start_pos); } @@ -823,10 +995,6 @@ struct parser_executor { common_peg_parse_result operator()(const common_peg_gbnf_parser & p) { return arena.parse(p.child, ctx, start_pos); } - - common_peg_parse_result operator()(const common_peg_ac_parser & p) { - return arena.parse(p.child, ctx, start_pos); - } }; common_peg_parse_result common_peg_arena::parse(common_peg_parse_context & ctx, size_t start) const { @@ -899,19 +1067,33 @@ void common_peg_arena::resolve_refs() { std::is_same_v || std::is_same_v || std::is_same_v || - std::is_same_v || - std::is_same_v) { + std::is_same_v) { p.child = resolve_ref(p.child); + } else if constexpr (std::is_same_v) { + if (p.content != COMMON_PEG_INVALID_PARSER_ID) { + p.content = resolve_ref(p.content); + } + for (auto & branch : p.branches) { + branch.delimiter = resolve_ref(branch.delimiter); + if (branch.rest != COMMON_PEG_INVALID_PARSER_ID) { + branch.rest = resolve_ref(branch.rest); + } + } } else if constexpr (std::is_same_v) { p.child = resolve_ref(p.child); + if (p.start != COMMON_PEG_INVALID_PARSER_ID) { + p.start = resolve_ref(p.start); + p.rest = resolve_ref(p.rest); + } } else if constexpr (std::is_same_v) { p.child = resolve_ref(p.child); } else if constexpr (std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || - std::is_same_v || std::is_same_v || + std::is_same_v || + std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || @@ -955,6 +1137,14 @@ std::string common_peg_arena::dump_impl(common_peg_parser_id return "End"; } else if constexpr (std::is_same_v) { return "Literal(" + p.literal + ")"; + } else if constexpr (std::is_same_v) { + return "Token(" + p.piece + ", " + std::to_string(p.token) + ")"; + } else if constexpr (std::is_same_v) { + std::vector parts; + for (auto token : p.tokens) { + parts.push_back(std::to_string(token)); + } + return "TokenNot(" + string_join(parts, ", ") + ")"; } else if constexpr (std::is_same_v) { std::vector parts; for (const auto & child : p.children) { @@ -981,8 +1171,6 @@ std::string common_peg_arena::dump_impl(common_peg_parser_id return "Atomic(" + dump_impl(p.child, visited) + ")"; } else if constexpr (std::is_same_v) { return "Gbnf(" + p.grammar + ", " + dump_impl(p.child, visited) + ")"; - } else if constexpr (std::is_same_v) { - return "Ac(" + string_join(p.delimiters, " | ") + ", " + dump_impl(p.child, visited) + ")"; } else if constexpr (std::is_same_v) { return "Any"; } else if constexpr (std::is_same_v) { @@ -995,7 +1183,18 @@ std::string common_peg_arena::dump_impl(common_peg_parser_id } else if constexpr (std::is_same_v) { return "String(" + std::string(1, p.delimiter) + ")"; } else if constexpr (std::is_same_v) { - return "Until(" + string_join(p.delimiters, " | ") + ")"; + std::vector branches; + for (const auto & branch : p.branches) { + auto text = dump_impl(branch.delimiter, visited); + if (branch.rest != COMMON_PEG_INVALID_PARSER_ID) { + text += " " + dump_impl(branch.rest, visited); + } + branches.push_back(std::move(text)); + } + if (p.include) { + return "Until(" + dump_impl(p.content, visited) + ", " + string_join(branches, " | ") + (p.optional ? ", optional" : "") + ")"; + } + return "Until(" + string_join(branches, " | ") + ")"; } else if constexpr (std::is_same_v) { return "Schema(" + dump_impl(p.child, visited) + ", " + (p.node ? common_chat_schema::kind_name(p.node->kind()) : "null") + ")"; } else if constexpr (std::is_same_v) { @@ -1089,6 +1288,67 @@ common_peg_parser operator|(const std::string & str, const common_peg_parser & p common_peg_parser_builder::common_peg_parser_builder() {} +common_peg_parser_builder::common_peg_parser_builder(common_peg_tokens tokens) { + arena_.tokens_ = std::move(tokens); +} + +common_peg_parser common_peg_parser_builder::until_one_of(const std::vector & delimiters) { + common_peg_until_parser p; + for (const auto & d : delimiters) { + p.branches.push_back({ literal(d).id() }); + } + p.matcher = build_until_matcher(arena_, p.branches, p.include); + return add(std::move(p)); +} + +common_peg_parser common_peg_parser_builder::until(const common_peg_parser & delimiter) { + common_peg_until_parser p; + p.branches = { { delimiter.id() } }; + p.matcher = build_until_matcher(arena_, p.branches, p.include); + return add(std::move(p)); +} + +common_peg_parser common_peg_parser_builder::through(const common_peg_parser & content, const std::vector & branches, bool optional) { + if (branches.empty()) { + throw std::runtime_error("through requires at least one branch"); + } + common_peg_until_parser p; + p.branches = branches; + p.include = true; + p.optional = optional; + p.content = content.id(); + p.matcher = build_until_matcher(arena_, p.branches, p.include); + return add(std::move(p)); +} + +common_peg_parser common_peg_parser_builder::token(const std::string & piece) { + auto token = arena_.tokens_.token_id(piece); + if (token == LLAMA_TOKEN_NULL) { + return literal(piece); + } + return add(common_peg_token_parser{token, piece}); +} + +common_peg_parser common_peg_parser_builder::token(const std::vector & pieces, bool negate) { + if (!negate) { + std::vector alts; + for (const auto & piece : pieces) { + alts.push_back(token(piece)); + } + return choice(alts); + } + + common_peg_token_not_parser p; + for (const auto & piece : pieces) { + auto token = arena_.tokens_.token_id(piece); + if (token == LLAMA_TOKEN_NULL) { + throw std::invalid_argument("token is not registered with the builder: " + piece); + } + p.tokens.push_back(token); + } + return add(p); +} + common_peg_parser common_peg_parser_builder::sequence(const std::vector & parsers) { // Flatten nested sequences std::vector flattened; @@ -1195,6 +1455,17 @@ common_peg_parser common_peg_parser_builder::rule(const std::string & name, cons return ref(clean_name); } +common_peg_parser common_peg_parser_builder::trigger_rule(const std::string & name, const common_peg_parser & start, const common_peg_parser & rest) { + common_trie scratch; + if (insert_delimiter(scratch, arena_, start.id()).count(0)) { + throw std::invalid_argument("trigger start must not match the empty string"); + } + auto clean_name = gbnf_format_rule_name(name); + auto rule_id = arena_.add_parser(common_peg_rule_parser{clean_name, (start + rest).id(), true, start.id(), rest.id()}); + arena_.add_rule(clean_name, rule_id); + return ref(clean_name); +} + void common_peg_parser_builder::set_root(const common_peg_parser & p) { arena_.set_root(p.id()); } @@ -1392,13 +1663,6 @@ common_peg_parser common_peg_parser_builder::json_member(const std::string & key }); } -common_peg_parser common_peg_parser_builder::ac(const common_peg_parser & p, const std::vector & delimiters) { - if (delimiters.empty()) { - throw std::runtime_error("ac parser requires at least one delimiter"); - } - return add(common_peg_ac_parser{p, delimiters}); -} - static std::string gbnf_escape_char_class(uint32_t c) { if (c == '-' || c == ']' || c == '[' || c == '\\') { return "\\" + std::string(1, (char) c); @@ -1457,15 +1721,63 @@ static std::string gbnf_char_class(const std::vector & chars, bool neg return s + "]"; } +// Token set such as <[1,5-9]>, with consecutive ids collapsed into ranges +static std::string gbnf_token_set(const std::vector & tokens, bool negate) { + std::string s = negate ? "!<[" : "<["; + for (size_t i = 0; i < tokens.size();) { + size_t j = i; + while (j + 1 < tokens.size() && tokens[j + 1] == tokens[j] + 1) { + j++; + } + s += (i == 0 ? "" : ",") + std::to_string(tokens[i]); + if (j > i) { + s += "-" + std::to_string(tokens[j]); + } + i = j + 1; + } + return s + "]>"; +} + +// Symbols on the transitions out of an automaton state, codepoints and tokens kept apart +struct gbnf_ac_symbols { + std::vector chars; + std::vector tokens; + + void add(const common_trie::symbol & sym) { + (sym.is_token() ? tokens : chars).push_back(sym.value); + } + + // One alternative for the codepoints and one for the tokens, each followed by next if given + std::vector alternatives(const std::string & next = "") const { + std::vector alts; + const std::string tail = next.empty() ? "" : " " + next; + if (!chars.empty()) { + alts.push_back(gbnf_char_class(chars, false) + tail); + } + if (!tokens.empty()) { + alts.push_back(gbnf_token_set(tokens, false) + tail); + } + return alts; + } +}; + static std::string gbnf_ac_grammar( - const common_grammar_builder & builder, - const std::string & prefix, - const std::vector & strings, - const std::function &, - const std::map> &, - const std::vector &, + const common_grammar_builder & builder, + const std::string & prefix, + const common_trie & trie, + const std::set & opaque, + const std::function &, + const std::map &, + const std::string &, const std::function &)> & build_rule) { - common_aho_corasick ac(strings); + common_aho_corasick ac(trie); + + // With only tokens in the alphabet, the grammar can step a whole token at a time + bool token_only = true; + for (const auto & sym : ac.alphabet) { + token_only = token_only && sym.is_token(); + } auto state_name = [&](size_t s) -> std::string { if (s == 0) { @@ -1481,27 +1793,43 @@ static std::string gbnf_ac_grammar( continue; // match states } - std::map> buckets; - std::vector completing; // chars that complete a delimiter - std::vector specific; // chars with an explicit transition - for (uint32_t c : ac.alphabet) { - size_t d = ac.next(q, c); + std::map buckets; + std::map completing_to; // completing symbols by the match state they reach + gbnf_ac_symbols completing; // symbols that complete a delimiter + gbnf_ac_symbols specific; // symbols with an explicit transition + for (const auto & sym : ac.alphabet) { + size_t d = ac.next(q, sym); if (ac.is_terminal(d)) { - completing.push_back(c); - specific.push_back(c); + completing.add(sym); + completing_to[d].add(sym); + specific.add(sym); } else if (d != 0) { - buckets[d].push_back(c); // specific non-root destination - specific.push_back(c); + buckets[d].add(sym); // specific non-root destination + specific.add(sym); } } - builder.add_rule(state_name(q), build_rule(completing, buckets, specific, state_name)); - } + // every other symbol goes back to the start + std::string fallback; + if (token_only) { + fallback = gbnf_token_set(specific.tokens, true); + } else { + fallback = specific.chars.empty() ? "." : gbnf_char_class(specific.chars, true); - // An empty delimiter makes the start state terminal. Emit an entry rule - // that matches the empty string so the returned reference stays valid. - if (ac.is_terminal(0)) { - builder.add_rule(prefix, "|"); + // Char rules never match a token named by a token rule, so allow the other named tokens by name + std::vector others; + for (auto token : opaque) { + if (std::find(specific.tokens.begin(), specific.tokens.end(), token) == specific.tokens.end()) { + others.push_back(token); + } + } + if (!others.empty()) { + fallback = "(" + fallback + " | " + gbnf_token_set(others, false) + ")"; + } + } + fallback += " " + state_name(0); + + builder.add_rule(state_name(q), build_rule(completing, completing_to, buckets, fallback, state_name)); } return state_name(0); @@ -1514,52 +1842,104 @@ static std::string gbnf_ac_grammar( // ref: https://github.com/ggml-org/llama.cpp/pull/24839 static std::string gbnf_excluding_grammar(const common_grammar_builder & builder, const std::string & prefix, - const std::vector & strings) { - return gbnf_ac_grammar(builder, prefix, strings, - [](const std::vector & /*completing*/, - const std::map> & buckets, - const std::vector & specific, + const common_trie & trie, + const std::set & opaque) { + return gbnf_ac_grammar(builder, prefix, trie, opaque, + [](const gbnf_ac_symbols & /*completing*/, + const std::map & /*completing_to*/, + const std::map & buckets, + const std::string & fallback, const std::function & state_name) { - // every state is accepting and completing chars get no - // alternative, so a forbidden string can never be matched + // every state accepts and completing symbols get no alternative, so a forbidden string never matches std::string rhs = "|"; - for (const auto & [d, chars] : buckets) { - rhs += " " + gbnf_char_class(chars, false) + " " + state_name(d) + " |"; + for (const auto & [d, symbols] : buckets) { + for (const auto & alt : symbols.alternatives(state_name(d))) { + rhs += " " + alt + " |"; + } } - rhs += " " + gbnf_char_class(specific, true) + " " + state_name(0); + rhs += " " + fallback; return rhs; }); } -// GBNF grammar matching everything up to and including the first occurrence of -// any string in `strings`. Emits the Aho-Corasick automaton DFA and returns -// the start state rule name. -static std::string gbnf_including_grammar(const common_grammar_builder & builder, - const std::string & prefix, - const std::vector & strings) { - return gbnf_ac_grammar(builder, prefix, strings, - [](const std::vector & completing, - const std::map> & buckets, - const std::vector & specific, - const std::function & state_name) { +// GBNF grammar matching up to the first pattern in the trie, then the rest rule of that pattern's value. +// For the pattern "ab" with rest "x": +// +// prefix ::= [a] prefix-01 | [^a] prefix +// prefix-01 ::= [b] rest | [a] prefix-01 | [^ab] prefix +// rest ::= "x" +static std::string gbnf_including_grammar(const common_grammar_builder & builder, + const std::string & prefix, + const common_trie & trie, + const std::set & opaque, + const std::vector & rests, + bool optional) { + common_aho_corasick ac(trie); + + // every pattern ending at a match state, the longest and the ones reached by suffix links + auto rests_at = [&](size_t s, bool & terminal) { + std::vector alts; + terminal = false; + for (; s != 0; s = ac.fail[s]) { + auto pattern = ac.t.nodes[s].pattern; + if (pattern < 0) { + continue; + } + if (rests[pattern].empty()) { + terminal = true; + } else if (std::find(alts.begin(), alts.end(), rests[pattern]) == alts.end()) { + alts.push_back(rests[pattern]); + } + } + return alts; + }; + + return gbnf_ac_grammar(builder, prefix, trie, opaque, + [&](const gbnf_ac_symbols & /*completing*/, + const std::map & completing_to, + const std::map & buckets, + const std::string & fallback, + const std::function & state_name) { std::vector alts; - if (!completing.empty()) { - alts.push_back(gbnf_char_class(completing, false)); // terminate on match + gbnf_ac_symbols terminating; // symbols that complete a pattern with no rest + for (const auto & [d, symbols] : completing_to) { + bool terminal = false; + auto rest = rests_at(d, terminal); + if (!rest.empty()) { + for (auto & alt : symbols.alternatives(rest.size() == 1 ? rest[0] : "(" + string_join(rest, " | ") + ")")) { + alts.push_back(std::move(alt)); + } + } + if (terminal) { + terminating.chars.insert(terminating.chars.end(), symbols.chars.begin(), symbols.chars.end()); + terminating.tokens.insert(terminating.tokens.end(), symbols.tokens.begin(), symbols.tokens.end()); + } } - for (const auto & [d, chars] : buckets) { - alts.push_back(gbnf_char_class(chars, false) + " " + state_name(d)); + for (auto & alt : terminating.alternatives()) { + alts.push_back(std::move(alt)); } - // every other character keeps scanning from the start state - alts.push_back(gbnf_char_class(specific, true) + " " + state_name(0)); - return string_join(alts, " | "); + for (const auto & [d, symbols] : buckets) { + for (auto & alt : symbols.alternatives(state_name(d))) { + alts.push_back(std::move(alt)); + } + } + // every other symbol keeps scanning from the start state + alts.push_back(fallback); + return (optional ? "| " : "") + string_join(alts, " | "); }); } -static std::set collect_reachable_rules( +// The rules and the tokens named by token rules that the grammar of a parser reaches +struct common_peg_reachable { + std::set rules; + std::set tokens; +}; + +static void collect_reachable( const common_peg_arena & arena, - const common_peg_parser_id & rule + const common_peg_parser_id & root, + common_peg_reachable & reachable ) { - std::set reachable; std::set visited; std::function visit = [&](common_peg_parser_id id) { @@ -1571,13 +1951,27 @@ static std::set collect_reachable_rules( if constexpr (std::is_same_v || std::is_same_v || std::is_same_v || - std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v) { // These parsers do not have any children + } else if constexpr (std::is_same_v) { + reachable.tokens.insert(p.token); + } else if constexpr (std::is_same_v) { + reachable.tokens.insert(p.tokens.begin(), p.tokens.end()); + } else if constexpr (std::is_same_v) { + // The delimiters name their tokens in the grammar + if (p.content != COMMON_PEG_INVALID_PARSER_ID) { + visit(p.content); + } + for (const auto & branch : p.branches) { + visit(branch.delimiter); + if (branch.rest != COMMON_PEG_INVALID_PARSER_ID) { + visit(branch.rest); + } + } } else if constexpr (std::is_same_v) { for (auto child : p.children) { visit(child); @@ -1592,13 +1986,12 @@ static std::set collect_reachable_rules( std::is_same_v || std::is_same_v || std::is_same_v || - std::is_same_v || std::is_same_v) { visit(p.child); } else if constexpr (std::is_same_v) { if (visited.find(p.name) == visited.end()) { visited.insert(p.name); - reachable.insert(p.name); + reachable.rules.insert(p.name); visit(p.child); } } else if constexpr (std::is_same_v) { @@ -1611,12 +2004,13 @@ static std::set collect_reachable_rules( }, parser); }; - visit(rule); - return reachable; + visit(root); } // GBNF generation implementation void common_peg_arena::build_grammar(const common_grammar_builder & builder, bool lazy) const { + common_peg_reachable reachable; + // A raw string value is parsed by the child rather than constrained by the schema auto schema_delegates = [](const common_peg_schema_parser & s) -> bool { return !s.node || (s.raw && s.node->may_be_string()); @@ -1655,6 +2049,10 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo return ""; } else if constexpr (std::is_same_v) { return gbnf_format_literal(p.literal); + } else if constexpr (std::is_same_v) { + return "<[" + std::to_string(p.token) + "]>"; + } else if constexpr (std::is_same_v) { + return gbnf_token_set(std::vector(p.tokens.begin(), p.tokens.end()), true); } else if constexpr (std::is_same_v) { std::string s; for (const auto & child : p.children) { @@ -1746,10 +2144,19 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo const std::string delim(1, p.delimiter); return R"(( [^)" + delim + R"(\\] | "\\" ( [)" + delim + R"(\\/ bfnrt] | "u" [0-9a-fA-F]{4} ) )*)"; } else if constexpr (std::is_same_v) { - if (p.delimiters.empty()) { - return ".*"; + auto prefix = "until-" + std::to_string(id); + if (!p.include) { + if (p.branches.empty()) { + return ".*"; + } + return gbnf_excluding_grammar(builder, prefix, p.matcher, reachable.tokens); + } + std::vector branch_rests; + for (size_t b = 0; b < p.branches.size(); b++) { + auto rest = p.branches[b].rest; + branch_rests.push_back(rest == COMMON_PEG_INVALID_PARSER_ID ? "" : builder.add_rule(prefix + "-rest-" + std::to_string(b), to_gbnf(rest))); } - return gbnf_excluding_grammar(builder, "until-" + std::to_string(id), p.delimiters); + return gbnf_including_grammar(builder, prefix, p.matcher, reachable.tokens, branch_rests, p.optional); } else if constexpr (std::is_same_v) { if (schema_delegates(p)) { return to_gbnf(p.child); @@ -1766,38 +2173,52 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo return to_gbnf(p.child); } else if constexpr (std::is_same_v) { return p.grammar; - } else if constexpr (std::is_same_v) { - return gbnf_including_grammar(builder, "ac-" + std::to_string(id), p.delimiters); } else { static_assert(is_always_false_v); } }, parser); }; - // Collect reachable rules - std::set reachable_rules; - - if (lazy) { - // Collect rules reachable from trigger rules - for (const auto & [name, id] : rules_) { - const auto & parser = parsers_.at(id); - if (auto rule = std::get_if(&parser)) { - if (rule->trigger) { - // Mark trigger as reachable and visit it - reachable_rules.insert(name); - auto add_rules = collect_reachable_rules(*this, id); - reachable_rules.insert(add_rules.begin(), add_rules.end()); - } + // Trigger rules, sorted for a predictable order + std::vector trigger_rules; + for (const auto & [name, id] : rules_) { + if (auto rule = std::get_if(&parsers_.at(id))) { + if (rule->trigger) { + trigger_rules.push_back(rule); + } + } + } + std::sort(trigger_rules.begin(), trigger_rules.end(), [](const auto * a, const auto * b) { return a->name < b->name; }); + + // A lazy grammar scans for the starts when the trigger rules were built from a start and rest + bool scans = false; + for (const auto * rule : trigger_rules) { + scans = scans || rule->start != COMMON_PEG_INVALID_PARSER_ID; + } + if (scans) { + for (const auto * rule : trigger_rules) { + if (rule->start == COMMON_PEG_INVALID_PARSER_ID) { + throw std::runtime_error("trigger rule without a start in a scanning grammar: " + rule->name); } } + } + + if (lazy && scans) { + for (const auto * rule : trigger_rules) { + collect_reachable(*this, rule->start, reachable); + collect_reachable(*this, rule->rest, reachable); + } + } else if (lazy) { + for (const auto * rule : trigger_rules) { + collect_reachable(*this, rules_.at(rule->name), reachable); + } } else { - // Collect rules reachable from root - reachable_rules = collect_reachable_rules(*this, root_); + collect_reachable(*this, root_, reachable); } // Create GBNF rules for all reachable rules for (const auto & [name, rule_id] : rules_) { - if (reachable_rules.find(name) == reachable_rules.end()) { + if (reachable.rules.find(name) == reachable.rules.end()) { continue; } @@ -1807,20 +2228,27 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo } } - if (lazy) { - // Generate root rule from trigger rules only - std::vector trigger_names; - for (const auto & [name, rule_id] : rules_) { - const auto & parser = parsers_.at(rule_id); - if (auto rule = std::get_if(&parser)) { - if (rule->trigger) { - trigger_names.push_back(rule->name); + if (lazy && scans) { + // The root scans for a trigger start and then constrains its rest + common_trie starts; + std::vector rests; + for (const auto * rule : trigger_rules) { + auto value = (int32_t) rests.size(); + rests.push_back(builder.add_rule(rule->name + "-rest", to_gbnf(rule->rest))); + for (size_t end : insert_delimiter(starts, *this, rule->start)) { + auto owner = starts.mark(end, value); + if (owner != value) { + throw std::runtime_error("trigger rules " + trigger_rules[owner]->name + " and " + rule->name + " must not share a start"); } } } - - // Sort for predictable order - std::sort(trigger_names.begin(), trigger_names.end()); + builder.add_rule("root", gbnf_including_grammar(builder, "trigger", starts, reachable.tokens, rests, /* optional = */ true)); + } else if (lazy) { + // Generate root rule from trigger rules only + std::vector trigger_names; + for (const auto * rule : trigger_rules) { + trigger_names.push_back(rule->name); + } builder.add_rule("root", string_join(trigger_names, " | ")); } else if (root_ != COMMON_PEG_INVALID_PARSER_ID) { builder.add_rule("root", to_gbnf(root_)); diff --git a/common/peg-parser.h b/common/peg-parser.h index 46df99875d35..b7e97083b386 100644 --- a/common/peg-parser.h +++ b/common/peg-parser.h @@ -3,6 +3,7 @@ #include "json-schema.h" #include "json.h" #include "llama.h" +#include "trie.h" #include #include @@ -188,6 +189,22 @@ struct common_peg_recursion_error : std::invalid_argument { using std::invalid_argument::invalid_argument; }; +struct common_peg_token { + std::string text; + llama_token_attr attr; +}; + +struct common_peg_tokens { + std::unordered_map tokens; + std::unordered_map ids; + + common_peg_tokens() = default; + explicit common_peg_tokens(const llama_vocab * vocab); + + // LLAMA_TOKEN_NULL if text is not a special token + llama_token token_id(const std::string & text) const; +}; + struct common_peg_parse_context { std::string input; // [h, e, l, l, o, _, w, o, r, l, d] std::vector tokens; // [id, -1, -1, -1, -1, id, -1, -1, -1, -1, -1] @@ -226,6 +243,16 @@ struct common_peg_literal_parser { std::string literal; }; +struct common_peg_token_parser { + llama_token token; + std::string piece; +}; + +// Matches one token that is not one of the tokens +struct common_peg_token_not_parser { + std::vector tokens; +}; + struct common_peg_sequence_parser { std::vector children; }; @@ -270,8 +297,18 @@ struct common_peg_string_parser { char delimiter; }; +// A delimiter an until parser stops at, and the parser that follows it when the delimiter is consumed +struct common_peg_until_branch { + common_peg_parser_id delimiter; + common_peg_parser_id rest = COMMON_PEG_INVALID_PARSER_ID; +}; + struct common_peg_until_parser { - std::vector delimiters; + std::vector branches; + bool include = false; // consume the first delimiter and parse the rest of its branch + bool optional = false; // with include, the input may end before any delimiter + common_peg_parser_id content = COMMON_PEG_INVALID_PARSER_ID; // with include, parsed up to the delimiter + common_trie matcher; // each pattern valued by its branch }; struct common_peg_schema_parser { @@ -288,6 +325,9 @@ struct common_peg_rule_parser { std::string name; common_peg_parser_id child; bool trigger; + // set when the rule has a start and rest, the lazy grammar scans for the start + common_peg_parser_id start = COMMON_PEG_INVALID_PARSER_ID; + common_peg_parser_id rest = COMMON_PEG_INVALID_PARSER_ID; }; struct common_peg_ref_parser { @@ -308,17 +348,14 @@ struct common_peg_gbnf_parser { std::string grammar; }; -struct common_peg_ac_parser { - common_peg_parser_id child; - std::vector delimiters; -}; - // Variant holding all parser types using common_peg_parser_variant = std::variant< common_peg_epsilon_parser, common_peg_start_parser, common_peg_end_parser, common_peg_literal_parser, + common_peg_token_parser, + common_peg_token_not_parser, common_peg_sequence_parser, common_peg_choice_parser, common_peg_repetition_parser, @@ -334,14 +371,14 @@ using common_peg_parser_variant = std::variant< common_peg_ref_parser, common_peg_atomic_parser, common_peg_tag_parser, - common_peg_gbnf_parser, - common_peg_ac_parser + common_peg_gbnf_parser >; class common_peg_arena { std::vector parsers_; std::unordered_map rules_; common_peg_parser_id root_ = COMMON_PEG_INVALID_PARSER_ID; + common_peg_tokens tokens_; public: const common_peg_parser_variant & get(common_peg_parser_id id) const { return parsers_.at(id); } @@ -356,6 +393,8 @@ class common_peg_arena { common_peg_parser_id root() const { return root_; } void set_root(common_peg_parser_id id) { root_ = id; } + const common_peg_tokens & tokens() const { return tokens_; } + common_peg_parse_result parse(common_peg_parse_context & ctx, size_t start = 0) const; common_peg_parse_result parse(common_peg_parser_id id, common_peg_parse_context & ctx, size_t start) const; @@ -384,6 +423,7 @@ class common_peg_parser_builder { public: common_peg_parser_builder(); + explicit common_peg_parser_builder(common_peg_tokens tokens); // Match nothing, always succeed. // S -> ε @@ -401,6 +441,16 @@ class common_peg_parser_builder { // S -> "hello" common_peg_parser literal(const std::string & literal) { return add(common_peg_literal_parser{literal}); } + // Matches a token. Falls back to a literal if the token is not registered with the builder. + // S -> <[token-id]> + common_peg_parser token(const std::string & piece); + + // Matches one of the tokens. With negate, matches one token that is not in the set. + // A negated set may only name tokens registered with the builder. + // S -> <[id1]> | <[id2]> | ... or !<[id1,id2,...]> + common_peg_parser token(const std::vector & pieces, bool negate = false); + common_peg_parser token(std::initializer_list pieces, bool negate = false) { return token(std::vector(pieces), negate); } + // Matches a sequence of parsers in order, all must succeed. // S -> A B C common_peg_parser sequence() { return add(common_peg_sequence_parser{}); } @@ -457,16 +507,29 @@ class common_peg_parser_builder { // Matches all characters until a delimiter is found (delimiter not consumed). // Invalid UTF-8 is consumed and recorded on the AST nodes. // S -> (!delim .)* - common_peg_parser until(const std::string & delimiter) { return add(common_peg_until_parser{{delimiter}}); } + common_peg_parser until(const std::string & delimiter) { return until_one_of({delimiter}); } // Matches all characters until one of the delimiters in the list is found (delimiter not consumed). // S -> (!delim .)* - common_peg_parser until_one_of(const std::vector & delimiters) { return add(common_peg_until_parser{delimiters}); } + common_peg_parser until_one_of(const std::vector & delimiters); + + // Matches all characters until the delimiter is found (delimiter not consumed). + // The delimiter may only be a sequence of literals, tokens, and choices of them. Tags and atomics may wrap them. + // S -> (!delim .)* + common_peg_parser until(const common_peg_parser & delimiter); // Matches everything // S -> .* common_peg_parser rest() { return until_one_of({}); } + // Matches content, then the first delimiter, then the rest of the branch of that delimiter. + // Branches must not share a delimiter. With optional, the input may end before any delimiter. + // S -> C (D1 R1 | D2 R2 | ...) + common_peg_parser through(const common_peg_parser & content, const std::vector & branches, bool optional = false); + common_peg_parser through(const common_peg_parser & content, std::initializer_list branches, bool optional = false) { return through(content, std::vector(branches), optional); } + common_peg_parser through(const common_peg_parser & content, const common_peg_parser & delimiter) { return through(content, { { delimiter } }); } + common_peg_parser through(const common_peg_parser & content, const std::string & delimiter) { return through(content, literal(delimiter)); } + // Matches between min and max repetitions of a parser (inclusive). // S -> A{m,n} // Use -1 for max to represent unbounded repetition (equivalent to {m,}) @@ -537,6 +600,10 @@ class common_peg_parser_builder { common_peg_parser trigger_rule(const std::string & name, const common_peg_parser & p) { return rule(name, p, true); } common_peg_parser trigger_rule(const std::string & name, const std::function & builder) { return rule(name, builder, true); } + // Creates a trigger rule that matches start followed by rest. A lazy grammar scans for the start of any such rule, then only allows its rest. + // The start has the same limits as an until() delimiter. + common_peg_parser trigger_rule(const std::string & name, const common_peg_parser & start, const common_peg_parser & rest); + // Creates an atomic parser. Atomic parsers do not create an AST node if // the child results in a partial parse, i.e. NEEDS_MORE_INPUT. This is // intended for situations where partial output is undesirable. @@ -550,13 +617,6 @@ class common_peg_parser_builder { // the child's grammar. Parsing delegates entirely to the child. common_peg_parser gbnf(const common_peg_parser & p, const std::string & grammar) { return add(common_peg_gbnf_parser{p, grammar}); } - // Wraps a child parser but emits a GBNF grammar built from the Aho-Corasick - // automaton of `delimiters`, matching everything up to and including the - // first delimiter. Parsing delegates entirely to the child, which is - // responsible for consuming the delimiter (e.g. until(D) + literal(D)). - common_peg_parser ac(const common_peg_parser & p, const std::vector & delimiters); - common_peg_parser ac(const common_peg_parser & p, const std::string & delimiter) { return ac(p, std::vector{delimiter}); } - void set_root(const common_peg_parser & p); common_peg_arena build(); diff --git a/common/reasoning-budget.cpp b/common/reasoning-budget.cpp index 81b7c3e56cdb..ac2cd261db08 100644 --- a/common/reasoning-budget.cpp +++ b/common/reasoning-budget.cpp @@ -31,14 +31,18 @@ struct token_matcher { static common_trie build_trie(const std::vector & seqs) { common_trie t; for (const auto & seq : seqs) { - t.insert(std::vector(seq.begin(), seq.end())); + std::vector symbols; + for (llama_token token : seq) { + symbols.push_back(common_trie::symbol::token(token)); + } + t.insert(symbols); } return t; } // returns the index into seqs of the longest sequence ending at this token, or -1 int32_t advance(llama_token token) { - state = ac.next(state, (uint32_t) token); + state = ac.next(state, common_trie::symbol::token(token)); const int32_t p = ac.match_pattern(state); if (p >= 0) { state = 0; diff --git a/common/trie.cpp b/common/trie.cpp index b5c9666ba2ee..b009b7044fa2 100644 --- a/common/trie.cpp +++ b/common/trie.cpp @@ -4,26 +4,46 @@ #include +common_trie::step common_trie::next(std::string_view sv, const std::vector & token_map, size_t pos) const { + if (!tokens.empty() && pos < token_map.size()) { + const int32_t id = token_map[pos]; + if (id >= 0 && tokens.find(id) != tokens.end()) { + size_t end = pos + 1; + while (end < token_map.size() && token_map[end] < 0) { + ++end; + } + return { utf8_parse_result::SUCCESS, symbol::token(id), end - pos }; + } + } + + auto result = common_parse_utf8_codepoint(sv, pos); + return { result.status, symbol::codepoint(result.codepoint), result.bytes_consumed }; +} + common_trie::match_result common_trie::check_at(std::string_view sv, size_t start_pos) const { + return check_at(sv, {}, start_pos); +} + +common_trie::match_result common_trie::check_at(std::string_view sv, const std::vector & token_map, size_t start_pos) const { size_t current = 0; // Start at root size_t pos = start_pos; // LOG_DBG("%s: checking at pos %zu, sv='%s'\n", __func__, start_pos, std::string(sv).c_str()); while (pos < sv.size()) { - auto result = common_parse_utf8_codepoint(sv, pos); - if (result.status != utf8_parse_result::SUCCESS) { + auto step = next(sv, token_map, pos); + if (step.status != utf8_parse_result::SUCCESS) { break; } - auto it = nodes[current].children.find(result.codepoint); + auto it = nodes[current].children.find(step.symbol); if (it == nodes[current].children.end()) { // Can't continue matching return match_result{match_result::NO_MATCH}; } current = it->second; - pos += result.bytes_consumed; + pos += step.bytes_consumed; // Check if we've matched a complete word if (nodes[current].pattern >= 0) { @@ -42,7 +62,7 @@ common_trie::match_result common_trie::check_at(std::string_view sv, size_t star } int32_t common_trie::insert(const std::string & word) { - std::vector symbols; + std::vector symbols; size_t pos = 0; while (pos < word.length()) { auto result = common_parse_utf8_codepoint(word, pos); @@ -50,28 +70,42 @@ int32_t common_trie::insert(const std::string & word) { break; } - symbols.push_back(result.codepoint); + symbols.push_back(symbol::codepoint(result.codepoint)); pos += result.bytes_consumed; } return insert(symbols); } -int32_t common_trie::insert(const std::vector & symbols) { +int32_t common_trie::insert(const std::vector & symbols) { size_t current = 0; - for (uint32_t ch : symbols) { - auto it = nodes[current].children.find(ch); - if (it == nodes[current].children.end()) { - size_t child = create_node(); - nodes[current].children[ch] = child; - current = child; - } else { - current = it->second; - } + for (symbol ch : symbols) { + current = extend(current, ch); + } + int32_t pattern = mark(current, n_patterns); + if (pattern == n_patterns) { + n_patterns++; } - if (nodes[current].pattern < 0) { - nodes[current].pattern = n_patterns++; + return pattern; +} + +size_t common_trie::extend(size_t node, symbol ch) { + if (ch.is_token()) { + tokens.insert((int32_t) ch.value); + } + auto it = nodes[node].children.find(ch); + if (it != nodes[node].children.end()) { + return it->second; + } + size_t child = create_node(); + nodes[node].children[ch] = child; + return child; +} + +int32_t common_trie::mark(size_t node, int32_t value) { + if (nodes[node].pattern < 0) { + nodes[node].pattern = value; } - return nodes[current].pattern; + return nodes[node].pattern; } common_aho_corasick::common_aho_corasick(common_trie trie) : t(std::move(trie)) { @@ -113,7 +147,7 @@ common_aho_corasick::common_aho_corasick(common_trie trie) : t(std::move(trie)) } } -size_t common_aho_corasick::next(size_t state, uint32_t ch) const { +size_t common_aho_corasick::next(size_t state, common_trie::symbol ch) const { const auto & nodes = t.nodes; while (state && nodes[state].children.find(ch) == nodes[state].children.end()) { state = fail[state]; diff --git a/common/trie.h b/common/trie.h index 0f7b16a36ad2..8c31d7263ddb 100644 --- a/common/trie.h +++ b/common/trie.h @@ -1,5 +1,7 @@ #pragma once +#include "unicode.h" + #include #include #include @@ -10,13 +12,42 @@ // Trie for matching multiple literals. // This is used in common_peg_until_parser and to build a GBNF exclusion grammar struct common_trie { + // A symbol is either a UTF-8 codepoint or a token + struct symbol { + enum kind_type : uint8_t { CODEPOINT, TOKEN }; + + kind_type kind = CODEPOINT; + uint32_t value = 0; + + static symbol codepoint(uint32_t cpt) { return { CODEPOINT, cpt }; } + static symbol token(int32_t id) { return { TOKEN, (uint32_t) id }; } + + bool is_token() const { return kind == TOKEN; } + + bool operator<(const symbol & other) const { + return kind != other.kind ? kind < other.kind : value < other.value; + } + bool operator==(const symbol & other) const { + return kind == other.kind && value == other.value; + } + }; + + struct step { + enum utf8_parse_result::status status; + common_trie::symbol symbol; + size_t bytes_consumed; + }; + struct node { - std::map children; // Use uint32_t to store Unicode codepoints + std::map children; int32_t pattern = -1; // index of the pattern ending at this node, -1 if none }; std::vector nodes; + // every token id used by a pattern, the input is split so these match as single symbols + std::set tokens; + common_trie() { create_node(); // root node } @@ -29,15 +60,25 @@ struct common_trie { enum match_result { NO_MATCH, PARTIAL_MATCH, COMPLETE_MATCH }; + // Read the symbol at pos. It is a token if a pattern uses the token at pos, else a UTF-8 codepoint. + step next(std::string_view sv, const std::vector & token_map, size_t pos) const; + // Check if a delimiter starts at the given position match_result check_at(std::string_view sv, size_t start_pos) const; + match_result check_at(std::string_view sv, const std::vector & token_map, size_t start_pos) const; // Insert a word as a sequence of Unicode codepoints, returns its pattern index int32_t insert(const std::string & word); - // Insert a raw symbol sequence, returns its pattern index (insertion order, - // duplicates keep the first index) - int32_t insert(const std::vector & symbols); + // Insert a symbol sequence, returns its pattern index (insertion order, duplicates keep the first index) + int32_t insert(const std::vector & symbols); + + // Child of node on a symbol, created if missing + size_t extend(size_t node, symbol ch); + + // Mark node as the end of a pattern with a value from the caller. Returns the value already there, or value if the node had none. + // A trie must take its values from mark or from insert, not both. + int32_t mark(size_t node, int32_t value); private: int32_t n_patterns = 0; @@ -51,11 +92,11 @@ struct common_trie { // Aho-Corasick automaton struct common_aho_corasick { - common_trie t; - std::vector fail; // failure links - std::vector order; // states in BFS order - std::vector match; // longest pattern ending at each state (directly or via a suffix link), -1 if none - std::set alphabet; // every character with a transition + common_trie t; + std::vector fail; // failure links + std::vector order; // states in BFS order + std::vector match; // longest pattern ending at each state (directly or via a suffix link), -1 if none + std::set alphabet; // every symbol with a transition common_aho_corasick(common_trie trie); @@ -69,5 +110,5 @@ struct common_aho_corasick { int32_t match_pattern(size_t s) const { return match[s]; } // follow failure links until a transition on `ch` exists. - size_t next(size_t state, uint32_t ch) const; + size_t next(size_t state, common_trie::symbol ch) const; }; diff --git a/docs/development/parsing.md b/docs/development/parsing.md index ab0ccad80bfa..faa64afded0c 100644 --- a/docs/development/parsing.md +++ b/docs/development/parsing.md @@ -67,6 +67,8 @@ For a more complete example, see `test_example_native()` in - **`end()`** - Matches the end of input (anchor `$`) - **`literal(string)`** - Matches an exact literal string - **`any()`** - Matches any single character (`.`) +- **`token(piece)`** - Matches a special token, or the literal `piece` if it is not registered with the builder (see [Special Tokens](#special-tokens)) +- **`token(pieces, negate)`** - Matches one of the tokens, or with `negate` one token that is not one of them ### Combinators @@ -89,6 +91,8 @@ For a more complete example, see `test_example_native()` in - **`space()`** - Matches zero or more whitespace characters (space, tab, newline) - **`until(delimiter)`** - Matches characters until delimiter is found (delimiter not consumed) - **`until_one_of(delimiters)`** - Matches characters until any delimiter in the list is found +- **`until(parser)`** - Matches characters until a delimiter built from literals and tokens is found (delimiter not consumed, see [until(parser)](#untilparser)) +- **`through(content, branches, optional)`** - Matches content, then the first delimiter found and the rest of its branch (delimiter consumed). The grammar scans for the delimiters instead of following content - **`rest()`** - Matches everything remaining (`.*`) ### JSON Parsers @@ -108,6 +112,7 @@ For a more complete example, see `test_example_native()` in - **`ref(name)`** - Creates a lightweight reference to a named rule (for recursive grammars) - **`rule(name, p, trigger)`** - Creates a named rule and returns a reference - **`trigger_rule(name, p)`** - Creates a trigger rule (entry point for lazy grammar generation) +- **`trigger_rule(name, start, rest)`** - Creates a trigger rule matching `start` then `rest`, gating the lazy grammar on the start - **`schema(p, name, schema, raw)`** - Wraps parser with JSON schema metadata for grammar generation - **`schema(p, name, doc, node, raw)`** - Same, for a node of a `common_chat_schema_document` built earlier, e.g. one tool parameter @@ -116,6 +121,110 @@ For a more complete example, see `test_example_native()` in - **`atomic(p)`** - Prevents AST node creation for partial parses - **`tag(tag, p)`** - Creates AST nodes with semantic tags (multiple nodes can share tags) +## Special Tokens + +Matching a special token by its text alone is ambiguous: a model may emit +`<|end|>` as a single control token, or spell it out as plain text, such as +when quoting a chat template. The parser can tell them apart when the builder +knows the special tokens of the vocabulary, and the input carries the ids of +the tokens that produced it. + +A `common_peg_tokens` table constructed from a `llama_vocab` registers every +control and user-defined token. Pass it to the builder: + +```cpp +common_peg_tokens specials(vocab); + +auto parser = build_chat_peg_parser(specials, [&](common_chat_peg_builder & p) { + return p.content(p.until(p.token("<|end|>"))) + p.token("<|end|>"); +}); +``` + +Chat templates initialized with a model build this table from its vocabulary, +and format handlers receive it as `inputs.specials`. + +### token() + +`token(piece)` matches only where the input holds the id of that token, and +consumes the whole piece. The same characters without the id do not match. +If `piece` is not registered with the builder, it falls back to +`literal(piece)`. + +`token(pieces)` matches any of the tokens, and `token(pieces, true)` matches one +token that is not in the set. Every piece of a negated set must be registered, +otherwise it throws `std::invalid_argument`. + +In the grammar, a token emits `<[id]>` and a negated set emits `!<[...]>`: + +```cpp +p.token({ "", "" }) + p.token({ "", "" }, true) +``` + +``` +root ::= (<[1]> | <[2]>) !<[1-2]> +``` + +### until(parser) + +`until(delimiter)` with a parser instead of a string stops at a delimiter that +may contain tokens, or several literals joined in a sequence: + +```cpp +auto end = p.token("<|end|>"); +auto final = p.token("<|channel|>") + p.literal("final"); + +p.reasoning(p.until(end | final)) +``` + +The delimiter may only be built from: + +- `literal()` and `token()` +- `sequence()` and `choice()` of the above +- `tag()` and `atomic()` wrapping any of the above + +Any other parser throws `std::invalid_argument`. A choice inside a sequence +expands to every combination, so `"a" + ("b" | "d")` stops at both `ab` and +`ad`. + +The grammar scans for the delimiters the same way as `until_one_of()`: + +```cpp +p.until((p.literal("a") + p.literal("b")) | p.literal("cd")) +``` + +``` +root ::= until-5 +until-5 ::= | [a] until-5-01 | [c] until-5-03 | [^ac] until-5 +until-5-01 ::= | [a] until-5-01 | [c] until-5-03 | [^abc] until-5 +until-5-03 ::= | [a] until-5-01 | [c] until-5-03 | [^acd] until-5 +``` + +A token never matches a character rule such as `.` or `[^a]`, so the scan lets +the other tokens named elsewhere in the grammar through by name. Here `` is +token 2: + +```cpp +p.until(p.token("") + p.literal("x")) + p.token("") + p.literal("x") + p.token("") +``` + +``` +root ::= until-3 <[1]> "x" <[2]> +until-3 ::= | <[1]> until-3-01 | (. | <[2]>) until-3 +until-3-01 ::= | <[1]> until-3-01 | ([^x] | <[2]>) until-3 +``` + +When the delimiters are made of tokens alone, the scan consumes whole tokens +with a negated token set instead: + +```cpp +p.until(p.token("")) + p.token("") +``` + +``` +root ::= until-1 <[1]> +until-1 ::= | !<[1]> until-1 +``` + ## GBNF Grammar Generation The PEG parser also acts as a convenient DSL for generating GBNF grammars, with @@ -143,6 +252,28 @@ are emitted in the grammar. All trigger rules are added as alternations in the root rule. It is still necessary to define trigger patterns, as the parser has no interaction with the grammar sampling. +With `trigger_rule(name, start, rest)`, the grammar instead scans for a start and +then constrains the rest. It runs from the first token, so `grammar_lazy` is false +and no trigger patterns are needed. For example: + +```cpp +auto ab = p.literal("ab"); +auto cd = p.literal("cd"); +return p.until(ab | cd) + (p.trigger_rule("one", ab, p.literal("x")) | p.trigger_rule("two", cd, p.literal("y"))); +``` + +``` +root ::= trigger +trigger ::= | [a] trigger-01 | [c] trigger-03 | [^ac] trigger +trigger-01 ::= | [b] one-rest | [a] trigger-01 | [c] trigger-03 | [^abc] trigger +trigger-03 ::= | [d] two-rest | [a] trigger-01 | [c] trigger-03 | [^acd] trigger +one-rest ::= "x" +two-rest ::= "y" +``` + +A start may only be a sequence of literals, tokens, and choices of them, possibly +wrapped in tags and atomics. + ### JSON Schema The `schema(p, name, schema, raw)` parser will use the `json-schema-to-grammar` diff --git a/grammars/README.md b/grammars/README.md index f005fc2522b8..b35946a4afe8 100644 --- a/grammars/README.md +++ b/grammars/README.md @@ -73,11 +73,13 @@ Tokens allow grammars to match specific tokenizer tokens rather than character s Tokens can be specified in two ways: -1. **Token ID**: Use angle brackets with the token ID in square brackets: `<[token-id]>`. For example, `<[1000]>` matches the token with ID 1000. +1. **Token ID**: Use angle brackets with the token ID in square brackets: `<[token-id]>`. For example, `<[1000]>` matches the token with ID 1000. Multiple IDs and inclusive ranges can be combined: `<[1000,1005-1010]>` matches token 1000 or any token from 1005 to 1010. 2. **Token string**: Use angle brackets with the token text directly: ``. For example, `` will match the token whose text is exactly ``. This only works if the string tokenizes to exactly one token in the vocabulary, otherwise the grammar will fail to parse. -You can negate token matches using the `!` prefix: `!<[1000]>` or `!` matches any token *except* the specified one. +You can negate token matches using the `!` prefix: `!<[1000]>` or `!` matches any token *except* the specified one, and `!<[1000,1005-1010]>` matches any token outside the set. + +Tokens are matched whole, so a token rule can only match at the start of a token, never after a character rule has consumed part of its text. Any token named by a token rule is also excluded from character rules: once `` appears as a token in a grammar, `.*` in that grammar will not match the `` token. ``` # Match a thinking block: ... diff --git a/src/llama-grammar.cpp b/src/llama-grammar.cpp index 9a0de14307e5..21a018c8c709 100644 --- a/src/llama-grammar.cpp +++ b/src/llama-grammar.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -33,9 +34,9 @@ static std::pair decode_utf8(const char * src) { return std::make_pair(value, pos); } -static std::pair, llama_partial_utf8> decode_utf8( - const std::string & src, - llama_partial_utf8 partial_start) { +std::pair, llama_partial_utf8> llama_grammar_decode_utf8( + const std::string & src, + llama_partial_utf8 partial_start) { static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 }; const char * pos = src.c_str(); std::vector code_points; @@ -185,23 +186,45 @@ static std::pair parse_char(const char * src) { throw std::runtime_error("unexpected end of input"); } -static std::pair parse_token(const llama_vocab * vocab, const char * src) { +static std::pair parse_token_id(const char * src) { + const char * int_end = parse_int(src); + unsigned long id = std::stoul(std::string(src, int_end - src)); + if (id > std::numeric_limits::max()) { + throw std::runtime_error(std::string("parsed token id is too big at ") + src); + } + return std::make_pair(static_cast(id), int_end); +} + +static const char * parse_token(const llama_vocab * vocab, const char * src, llama_gretype type, llama_grammar_rule & rule) { const char * pos = src; if (*pos != '<') { throw std::runtime_error(std::string("expecting '<' at ") + pos); } pos++; - // Parse <[id]> + // Parse <[id,id-id,...]> if (*pos == '[') { pos++; - const char * int_end = parse_int(pos); - unsigned long id = std::stoul(std::string(pos, int_end - pos)); - if (id > std::numeric_limits::max()) { - throw std::runtime_error(std::string("parsed token id is too big at ") + pos); + const size_t start = rule.size(); + while (true) { + auto id_pair = parse_token_id(pos); + uint32_t token_id = id_pair.first; + pos = id_pair.second; + rule.push_back({rule.size() == start ? type : LLAMA_GRETYPE_TOKEN_ALT, token_id}); + if (*pos == '-') { + pos++; + auto end_pair = parse_token_id(pos); + if (end_pair.first < token_id) { + throw std::runtime_error(std::string("invalid token range at ") + pos); + } + pos = end_pair.second; + rule.push_back({LLAMA_GRETYPE_TOKEN_RNG_UPPER, end_pair.first}); + } + if (*pos != ',') { + break; + } + pos++; } - uint32_t token_id = static_cast(id); - pos = int_end; if (*pos != ']') { throw std::runtime_error(std::string("expecting ']' at ") + pos); } @@ -210,7 +233,7 @@ static std::pair parse_token(const llama_vocab * vocab, throw std::runtime_error(std::string("expecting '>' at ") + pos); } pos++; - return std::make_pair(token_id, pos); + return pos; } if (vocab == nullptr) { @@ -232,7 +255,8 @@ static std::pair parse_token(const llama_vocab * vocab, // must tokenize to exactly 1 token throw std::runtime_error("invalid token '" + std::string(src, pos - src) + "'"); } - return std::make_pair(tokens[0], pos); + rule.push_back({type, static_cast(tokens[0])}); + return pos; } static void print_grammar_char(FILE * file, uint32_t c) { @@ -244,6 +268,16 @@ static void print_grammar_char(FILE * file, uint32_t c) { } } +static bool is_token_element(llama_grammar_element elem) { + switch (elem.type) { + case LLAMA_GRETYPE_TOKEN: return true; + case LLAMA_GRETYPE_TOKEN_NOT: return true; + case LLAMA_GRETYPE_TOKEN_ALT: return true; + case LLAMA_GRETYPE_TOKEN_RNG_UPPER: return true; + default: return false; + } +} + static bool is_char_element(llama_grammar_element elem) { switch (elem.type) { case LLAMA_GRETYPE_CHAR: return true; @@ -258,16 +292,18 @@ static bool is_char_element(llama_grammar_element elem) { static void print_rule_binary(FILE * file, const llama_grammar_rule & rule) { for (auto elem : rule) { switch (elem.type) { - case LLAMA_GRETYPE_END: fprintf(file, "END"); break; - case LLAMA_GRETYPE_ALT: fprintf(file, "ALT"); break; - case LLAMA_GRETYPE_RULE_REF: fprintf(file, "RULE_REF"); break; - case LLAMA_GRETYPE_CHAR: fprintf(file, "CHAR"); break; - case LLAMA_GRETYPE_CHAR_NOT: fprintf(file, "CHAR_NOT"); break; - case LLAMA_GRETYPE_CHAR_RNG_UPPER: fprintf(file, "CHAR_RNG_UPPER"); break; - case LLAMA_GRETYPE_CHAR_ALT: fprintf(file, "CHAR_ALT"); break; - case LLAMA_GRETYPE_CHAR_ANY: fprintf(file, "CHAR_ANY"); break; - case LLAMA_GRETYPE_TOKEN: fprintf(file, "TOKEN"); break; - case LLAMA_GRETYPE_TOKEN_NOT: fprintf(file, "TOKEN_NOT"); break; + case LLAMA_GRETYPE_END: fprintf(file, "END"); break; + case LLAMA_GRETYPE_ALT: fprintf(file, "ALT"); break; + case LLAMA_GRETYPE_RULE_REF: fprintf(file, "RULE_REF"); break; + case LLAMA_GRETYPE_CHAR: fprintf(file, "CHAR"); break; + case LLAMA_GRETYPE_CHAR_NOT: fprintf(file, "CHAR_NOT"); break; + case LLAMA_GRETYPE_CHAR_RNG_UPPER: fprintf(file, "CHAR_RNG_UPPER"); break; + case LLAMA_GRETYPE_CHAR_ALT: fprintf(file, "CHAR_ALT"); break; + case LLAMA_GRETYPE_CHAR_ANY: fprintf(file, "CHAR_ANY"); break; + case LLAMA_GRETYPE_TOKEN: fprintf(file, "TOKEN"); break; + case LLAMA_GRETYPE_TOKEN_NOT: fprintf(file, "TOKEN_NOT"); break; + case LLAMA_GRETYPE_TOKEN_RNG_UPPER: fprintf(file, "TOKEN_RNG_UPPER"); break; + case LLAMA_GRETYPE_TOKEN_ALT: fprintf(file, "TOKEN_ALT"); break; } switch (elem.type) { case LLAMA_GRETYPE_END: @@ -295,6 +331,10 @@ static void print_rule_binary(FILE * file, const llama_grammar_rule & rule) { fprintf(file, "%u", elem.value); fprintf(file, "]> "); break; + case LLAMA_GRETYPE_TOKEN_RNG_UPPER: + case LLAMA_GRETYPE_TOKEN_ALT: + fprintf(file, "(%u) ", elem.value); + break; } } fprintf(file, "\n"); @@ -354,14 +394,32 @@ static void print_rule( case LLAMA_GRETYPE_TOKEN: fprintf(file, "<["); fprintf(file, "%u", elem.value); - fprintf(file, "]> "); break; case LLAMA_GRETYPE_TOKEN_NOT: fprintf(file, "!"); fprintf(file, "<["); fprintf(file, "%u", elem.value); - fprintf(file, "]> "); break; + case LLAMA_GRETYPE_TOKEN_RNG_UPPER: + if (i == 0 || !is_token_element(rule[i - 1])) { + throw std::runtime_error( + "LLAMA_GRETYPE_TOKEN_RNG_UPPER without preceding token: " + + std::to_string(rule_id) + "," + std::to_string(i)); + } + fprintf(file, "-%u", elem.value); + break; + case LLAMA_GRETYPE_TOKEN_ALT: + if (i == 0 || !is_token_element(rule[i - 1])) { + throw std::runtime_error( + "LLAMA_GRETYPE_TOKEN_ALT without preceding token: " + + std::to_string(rule_id) + "," + std::to_string(i)); + } + fprintf(file, ",%u", elem.value); + break; + } + if (is_token_element(elem) && + rule[i + 1].type != LLAMA_GRETYPE_TOKEN_ALT && rule[i + 1].type != LLAMA_GRETYPE_TOKEN_RNG_UPPER) { + fprintf(file, "]> "); } if (is_char_element(elem)) { switch (rule[i + 1].type) { @@ -587,11 +645,9 @@ const char * llama_grammar_parser::parse_sequence( type = LLAMA_GRETYPE_TOKEN_NOT; pos++; } - auto token_pair = parse_token(vocab, pos); - const char * token_end = token_pair.second; last_sym_start = rule.size(); n_prev_rules = 1; - rule.push_back({type, token_pair.first}); + const char * token_end = parse_token(vocab, pos, type, rule); pos = parse_space(token_end, is_nested); } else if (is_word_char(*pos)) { // rule reference const char * name_end = parse_name(pos); @@ -854,17 +910,58 @@ static bool llama_grammar_match_partial_char( // returns true iff token matches the rule at pos (regular or inverse) // asserts that pos is pointing to a token element -static bool llama_grammar_match_token( +static std::pair llama_grammar_match_token( const llama_grammar_element * pos, const llama_token token) { - GGML_ASSERT(pos->type == LLAMA_GRETYPE_TOKEN || pos->type == LLAMA_GRETYPE_TOKEN_NOT); - if (pos->type == LLAMA_GRETYPE_TOKEN) { - return pos->value == static_cast(token); + bool is_positive_token = pos->type == LLAMA_GRETYPE_TOKEN; + + GGML_ASSERT(is_positive_token || pos->type == LLAMA_GRETYPE_TOKEN_NOT); + + const uint32_t id = static_cast(token); + + bool found = false; + do { + if (pos[1].type == LLAMA_GRETYPE_TOKEN_RNG_UPPER) { + // inclusive range, e.g. <[1-5]> + found = found || (pos->value <= id && id <= pos[1].value); + pos += 2; + } else { + found = found || pos->value == id; + pos += 1; + } + } while (pos->type == LLAMA_GRETYPE_TOKEN_ALT); + + return std::make_pair(found == is_positive_token, pos); +} + +// every token id a token rule names, merged into sorted inclusive ranges +static std::vector> llama_grammar_opaque_tokens(const llama_grammar_rules & rules) { + std::vector> ranges; + for (const auto & rule : rules) { + for (size_t i = 0; i < rule.size(); i++) { + const auto type = rule[i].type; + if (type == LLAMA_GRETYPE_TOKEN || type == LLAMA_GRETYPE_TOKEN_NOT || type == LLAMA_GRETYPE_TOKEN_ALT) { + const bool is_range = i + 1 < rule.size() && rule[i + 1].type == LLAMA_GRETYPE_TOKEN_RNG_UPPER; + ranges.emplace_back(rule[i].value, is_range ? rule[i + 1].value : rule[i].value); + } + } } - if (pos->type == LLAMA_GRETYPE_TOKEN_NOT) { - return pos->value != static_cast(token); + std::sort(ranges.begin(), ranges.end()); + std::vector> merged; + for (const auto & r : ranges) { + if (!merged.empty() && r.first <= (uint64_t) merged.back().second + 1) { + merged.back().second = std::max(merged.back().second, r.second); + } else { + merged.push_back(r); + } } - return false; + return merged; +} + +bool llama_grammar_is_opaque(const llama_grammar & grammar, llama_token token) { + const auto id = static_cast(token); + auto it = std::upper_bound(grammar.opaque_tokens.begin(), grammar.opaque_tokens.end(), std::make_pair(id, UINT32_MAX)); + return it != grammar.opaque_tokens.begin() && std::prev(it)->second >= id; } // transforms a grammar pushdown stack into N possible stacks, all ending @@ -946,8 +1043,7 @@ static void llama_grammar_advance_stack( break; default: // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range - // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on - // those + // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER) or token set (LLAMA_GRETYPE_TOKEN_ALT, LLAMA_GRETYPE_TOKEN_RNG_UPPER); stack should never be left on those GGML_ABORT("fatal error"); } } @@ -1238,13 +1334,13 @@ static bool llama_grammar_reject_step( if (stack_pos->type == LLAMA_GRETYPE_TOKEN || stack_pos->type == LLAMA_GRETYPE_TOKEN_NOT) { for (const uint32_t i : cur) { const auto & tok = candidates[i]; - if (tok.code_points[depth] == 0) { - // reached the end of a token consumed by char rules, reject iff it ended - // in a partial response - if (tok.partial_utf8.n_remain != 0) { + if (depth > 0) { + // char rules already consumed part of this token, so it cannot match by id. + // accept it only if they consumed all of it and did not end in a partial sequence. + if (tok.code_points[depth] != 0 || tok.partial_utf8.n_remain != 0) { rejects.push_back(i); } - } else if (!llama_grammar_match_token(stack_pos, tok.id)) { + } else if (tok.partial_utf8.n_remain < 0 || !llama_grammar_match_token(stack_pos, tok.id).first) { rejects.push_back(i); } } @@ -1255,7 +1351,10 @@ static bool llama_grammar_reject_step( for (const uint32_t i : cur) { const auto & tok = candidates[i]; - if (tok.code_points[depth] == 0) { + if (tok.opaque) { + // a token named by a token rule only matches token rules + rejects.push_back(i); + } else if (tok.code_points[depth] == 0) { // reached end of full codepoints in token, reject iff it ended in a partial sequence // that cannot satisfy this position in grammar if (tok.partial_utf8.n_remain != 0 && @@ -1425,6 +1524,8 @@ struct llama_grammar * llama_grammar_init_impl( } } while (true); + auto opaque_tokens = llama_grammar_opaque_tokens(vec_rules); + // Important: vec_rules has to be moved here, not copied, because stacks contains // pointers to elements of vec_rules. If vec_rules were copied into llama_grammar // then the pointers would be invalidated when the local vec_rules goes out of scope. @@ -1439,6 +1540,7 @@ struct llama_grammar * llama_grammar_init_impl( /* .trigger_buffer_positions = */ {}, /* .trigger_tokens = */ {}, /* .trigger_patterns = */ {}, + /* .opaque_tokens = */ std::move(opaque_tokens), }; } @@ -1540,6 +1642,8 @@ struct llama_grammar * llama_grammar_init_impl( trigger.regex = std::regex(trigger.pattern); } + auto opaque_tokens = llama_grammar_opaque_tokens(vec_rules); + // Important: vec_rules has to be moved here, not copied, because stacks contains // pointers to elements of vec_rules. If vec_rules were copied into llama_grammar // then the pointers would be invalidated when the local vec_rules goes out of scope. @@ -1554,6 +1658,7 @@ struct llama_grammar * llama_grammar_init_impl( /* .trigger_buffer_positions = */ {}, std::move(vec_trigger_tokens), std::move(vec_trigger_patterns), + std::move(opaque_tokens), }; } @@ -1601,8 +1706,9 @@ void llama_grammar_apply_impl(const struct llama_grammar & grammar, llama_token_ } else if (piece.empty() || piece[0] == 0) { cur_p->data[i].logit = -INFINITY; } else { - candidates_decoded.push_back(decode_utf8(piece, grammar.partial_utf8)); - candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second, id }); + candidates_decoded.push_back(llama_grammar_decode_utf8(piece, grammar.partial_utf8)); + candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second, id, + llama_grammar_is_opaque(grammar, id) }); } } @@ -1673,7 +1779,7 @@ void llama_grammar_accept_impl(struct llama_grammar & grammar, llama_token token void llama_grammar_accept_str(struct llama_grammar & grammar, const std::string & piece) { // Note terminating 0 in decoded string - const auto decoded = decode_utf8(piece, grammar.partial_utf8); + const auto decoded = llama_grammar_decode_utf8(piece, grammar.partial_utf8); const auto & code_points = decoded.first; for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) { @@ -1688,9 +1794,16 @@ void llama_grammar_accept_str(struct llama_grammar & grammar, const std::string void llama_grammar_accept_token(struct llama_grammar & grammar, llama_token token, const std::string & piece) { // Note terminating 0 in decoded string - const auto decoded = decode_utf8(piece, grammar.partial_utf8); + const auto decoded = llama_grammar_decode_utf8(piece, grammar.partial_utf8); const auto & code_points = decoded.first; + // the mask rejects a piece that does not continue a partial character, so accepting one has to fail too + if (decoded.second.n_remain < 0) { + throw std::runtime_error("Invalid UTF-8 continuation in piece: " + piece + " (" + std::to_string(token) + ")"); + } + + const bool opaque = llama_grammar_is_opaque(grammar, token); + llama_grammar_stacks stacks_new; stacks_new.reserve(grammar.stacks.size()); @@ -1702,14 +1815,15 @@ void llama_grammar_accept_token(struct llama_grammar & grammar, llama_token toke const llama_grammar_element * pos = stack.back(); if (pos->type == LLAMA_GRETYPE_TOKEN || pos->type == LLAMA_GRETYPE_TOKEN_NOT) { - if (llama_grammar_match_token(pos, token)) { + auto match = llama_grammar_match_token(pos, token); + if (match.first) { llama_grammar_stack new_stack(stack.begin(), stack.end() - 1); - if (!llama_grammar_is_end_of_sequence(pos + 1)) { - new_stack.push_back(pos + 1); + if (!llama_grammar_is_end_of_sequence(match.second)) { + new_stack.push_back(match.second); } llama_grammar_advance_stack(*grammar.rules, new_stack, stacks_new); } - } else { + } else if (!opaque) { llama_grammar_stacks current_stacks = {stack}; for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) { diff --git a/src/llama-grammar.h b/src/llama-grammar.h index 5829d8edc467..fedc709697e0 100644 --- a/src/llama-grammar.h +++ b/src/llama-grammar.h @@ -38,11 +38,17 @@ enum llama_gretype { // any character (.) LLAMA_GRETYPE_CHAR_ANY = 7, - // terminal element: token (<[token-id]>) + // terminal element: token (<[token-id]>, <[token-id,token-id-token-id]>) LLAMA_GRETYPE_TOKEN = 8, - // inverse token (!<[token-id]>) + // inverse token (!<[token-id]>, !<[token-id,token-id-token-id]>) LLAMA_GRETYPE_TOKEN_NOT = 9, + + // modifies a preceding LLAMA_GRETYPE_TOKEN, LLAMA_GRETYPE_TOKEN_NOT, or LLAMA_GRETYPE_TOKEN_ALT to be an inclusive range (<[1-5]>) + LLAMA_GRETYPE_TOKEN_RNG_UPPER = 10, + + // modifies a preceding LLAMA_GRETYPE_TOKEN, LLAMA_GRETYPE_TOKEN_NOT, or LLAMA_GRETYPE_TOKEN_RNG_UPPER to add an alternate token to match (<[1,5]>, <[1-5,9]>) + LLAMA_GRETYPE_TOKEN_ALT = 11, }; typedef struct llama_grammar_element { @@ -60,6 +66,7 @@ struct llama_grammar_candidate { const uint32_t * code_points; llama_partial_utf8 partial_utf8; llama_token id; + bool opaque; }; using llama_grammar_rule = std::vector< llama_grammar_element>; @@ -84,6 +91,10 @@ std::vector llama_grammar_reject_candidates_for_stack( const llama_grammar_stack & stack, const llama_grammar_candidates & candidates); +std::pair, llama_partial_utf8> llama_grammar_decode_utf8( + const std::string & src, + llama_partial_utf8 partial_start); + struct llama_grammar_parser { const llama_vocab * vocab; std::map symbol_ids; @@ -151,6 +162,8 @@ struct llama_grammar { trigger_patterns; // Regular expressions that trigger a lazy grammar. Must be a full match of the entire generated // string, and the grammar will be given the string from the first match group onwards. + // token ids named by token rules, as sorted inclusive ranges. char rules never match these tokens. + std::vector> opaque_tokens; }; // @@ -195,3 +208,6 @@ void llama_grammar_accept_token( struct llama_grammar & grammar, llama_token token, const std::string & piece); + +// true if a token rule names the token, char rules do not match it +bool llama_grammar_is_opaque(const llama_grammar & grammar, llama_token token); diff --git a/tests/peg-parser/test-basic.cpp b/tests/peg-parser/test-basic.cpp index b6af61491d76..df124c759c68 100644 --- a/tests/peg-parser/test-basic.cpp +++ b/tests/peg-parser/test-basic.cpp @@ -367,6 +367,49 @@ void test_basic(testing & t) { }); + t.test("through", [](testing & t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + return p.through(p.tag("body", p.until_one_of({ "", "" })), { { p.literal(""), p.literal("x") }, { p.literal("") } }, true); + }); + + t.test("consumes the delimiter and its rest", [&](testing & t) { + auto ctx = common_peg_parse_context("hellox"); + auto result = parser.parse(ctx); + t.assert_equal("success", true, result.success()); + t.assert_equal("end", (size_t) 10, result.end); + t.assert_equal("body", std::string("hello"), std::string(ctx.ast.get(result.nodes[0]).text)); + }); + + t.test("picks the branch of the delimiter found", [&](testing & t) { + auto ctx = common_peg_parse_context("hellox"); + auto result = parser.parse(ctx); + t.assert_equal("success", true, result.success()); + t.assert_equal("end", (size_t) 9, result.end); + }); + + t.test("waits for the rest of a partial delimiter", [&](testing & t) { + auto ctx = common_peg_parse_context("hello"); + }); + auto ctx = common_peg_parse_context("hello"); + auto result = parser.parse(ctx); + t.assert_equal("fail", true, result.fail()); + }); + }); + t.test("recursive rules", [](testing &t) { // Test simple number t.test("simple_number", [](testing &t) { diff --git a/tests/peg-parser/test-gbnf-generation.cpp b/tests/peg-parser/test-gbnf-generation.cpp index 60066a817b50..38f3ec9abe23 100644 --- a/tests/peg-parser/test-gbnf-generation.cpp +++ b/tests/peg-parser/test-gbnf-generation.cpp @@ -129,14 +129,14 @@ void test_gbnf_generation(testing &t) { }); assert_gbnf_equal(t, R"""( - root ::= until-0 + root ::= until-1 space ::= | " " | "\n"{1,2} [ \t]{0,20} - until-0 ::= | [<] until-0-01 | [^<] until-0 - until-0-01 ::= | [<] until-0-01 | [/] until-0-02 | [^/<] until-0 - until-0-02 ::= | [<] until-0-01 | [t] until-0-03 | [^] until-0 + until-1 ::= | [<] until-1-01 | [^<] until-1 + until-1-01 ::= | [<] until-1-01 | [/] until-1-02 | [^/<] until-1 + until-1-02 ::= | [<] until-1-01 | [t] until-1-03 | [^] until-1 )""", gbnf); }); @@ -150,22 +150,22 @@ void test_gbnf_generation(testing &t) { }); assert_gbnf_equal(t, R"""( - root ::= until-0 + root ::= until-1 space ::= | " " | "\n"{1,2} [ \t]{0,20} - until-0 ::= | [\n] until-0-01 | [^\n] until-0 - until-0-01 ::= | [\n] until-0-01 | [<] until-0-02 | [^\n<] until-0 - until-0-02 ::= | [\n] until-0-01 | [/] until-0-03 | [^\n/] until-0 - until-0-03 ::= | [\n] until-0-01 | [p] until-0-04 | [^\np] until-0 - until-0-04 ::= | [\n] until-0-01 | [a] until-0-05 | [^\na] until-0 - until-0-05 ::= | [\n] until-0-01 | [r] until-0-06 | [^\nr] until-0 - until-0-06 ::= | [\n] until-0-01 | [a] until-0-07 | [^\na] until-0 - until-0-07 ::= | [\n] until-0-01 | [m] until-0-08 | [^\nm] until-0 - until-0-08 ::= | [\n] until-0-01 | [e] until-0-09 | [^\ne] until-0 - until-0-09 ::= | [\n] until-0-01 | [t] until-0-10 | [^\nt] until-0 - until-0-10 ::= | [\n] until-0-01 | [e] until-0-11 | [^\ne] until-0 - until-0-11 ::= | [\n] until-0-01 | [r] until-0-12 | [^\nr] until-0 - until-0-12 ::= | [\n] until-0-01 | [>] until-0-13 | [^\n>] until-0 - until-0-13 ::= | [^\n] until-0 + until-1 ::= | [\n] until-1-01 | [^\n] until-1 + until-1-01 ::= | [\n] until-1-01 | [<] until-1-02 | [^\n<] until-1 + until-1-02 ::= | [\n] until-1-01 | [/] until-1-03 | [^\n/] until-1 + until-1-03 ::= | [\n] until-1-01 | [p] until-1-04 | [^\np] until-1 + until-1-04 ::= | [\n] until-1-01 | [a] until-1-05 | [^\na] until-1 + until-1-05 ::= | [\n] until-1-01 | [r] until-1-06 | [^\nr] until-1 + until-1-06 ::= | [\n] until-1-01 | [a] until-1-07 | [^\na] until-1 + until-1-07 ::= | [\n] until-1-01 | [m] until-1-08 | [^\nm] until-1 + until-1-08 ::= | [\n] until-1-01 | [e] until-1-09 | [^\ne] until-1 + until-1-09 ::= | [\n] until-1-01 | [t] until-1-10 | [^\nt] until-1 + until-1-10 ::= | [\n] until-1-01 | [e] until-1-11 | [^\ne] until-1 + until-1-11 ::= | [\n] until-1-01 | [r] until-1-12 | [^\nr] until-1 + until-1-12 ::= | [\n] until-1-01 | [>] until-1-13 | [^\n>] until-1 + until-1-13 ::= | [^\n] until-1 )""", gbnf); }); @@ -181,15 +181,15 @@ void test_gbnf_generation(testing &t) { }); assert_gbnf_equal(t, R"""( - root ::= until-0 + root ::= until-1 space ::= | " " | "\n"{1,2} [ \t]{0,20} - until-0 ::= | [<] until-0-01 | [^<] until-0 - until-0-01 ::= | [<] until-0-01 | [\uFF5C] until-0-02 | [^<\uFF5C] until-0 - until-0-02 ::= | [<] until-0-01 | [D] until-0-03 | [^") + p.literal(""), ""); + return p.through(p.until(""), ""); }); auto gbnf = build_grammar([&](const common_grammar_builder & builder) { @@ -222,20 +222,20 @@ void test_gbnf_generation(testing &t) { }); assert_gbnf_equal(t, R"""( - ac-3 ::= [<] ac-3-01 | [^<] ac-3 - ac-3-01 ::= [<] ac-3-01 | [/] ac-3-02 | [^/<] ac-3 - ac-3-02 ::= [<] ac-3-01 | [t] ac-3-03 | [^] | [<] ac-3-01 | [^<>] ac-3 - root ::= ac-3 + root ::= until-3 space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-3 ::= [<] until-3-01 | [^<] until-3 + until-3-01 ::= [<] until-3-01 | [/] until-3-02 | [^/<] until-3 + until-3-02 ::= [<] until-3-01 | [t] until-3-03 | [^] | [<] until-3-01 | [^<>] until-3 )""", gbnf); }); - t.test("ac grammar terminates at first delimiter", [](testing &t) { + t.test("through grammar terminates at first delimiter", [](testing &t) { auto parser = build_peg_parser([](common_peg_parser_builder & p) { - return p.ac(p.until("\n\n") + p.literal("\n\n"), "\n\n"); + return p.through(p.until("\n\n"), "\n\n"); }); auto gbnf = build_grammar([&](const common_grammar_builder & builder) { @@ -243,28 +243,28 @@ void test_gbnf_generation(testing &t) { }); assert_gbnf_equal(t, R"""( - ac-3 ::= [\n] ac-3-01 | [^\n] ac-3 - ac-3-01 ::= [\n] ac-3-01 | [<] ac-3-02 | [^\n<] ac-3 - ac-3-02 ::= [\n] ac-3-01 | [/] ac-3-03 | [^\n/] ac-3 - ac-3-03 ::= [\n] ac-3-01 | [p] ac-3-04 | [^\np] ac-3 - ac-3-04 ::= [\n] ac-3-01 | [a] ac-3-05 | [^\na] ac-3 - ac-3-05 ::= [\n] ac-3-01 | [r] ac-3-06 | [^\nr] ac-3 - ac-3-06 ::= [\n] ac-3-01 | [a] ac-3-07 | [^\na] ac-3 - ac-3-07 ::= [\n] ac-3-01 | [m] ac-3-08 | [^\nm] ac-3 - ac-3-08 ::= [\n] ac-3-01 | [e] ac-3-09 | [^\ne] ac-3 - ac-3-09 ::= [\n] ac-3-01 | [t] ac-3-10 | [^\nt] ac-3 - ac-3-10 ::= [\n] ac-3-01 | [e] ac-3-11 | [^\ne] ac-3 - ac-3-11 ::= [\n] ac-3-01 | [r] ac-3-12 | [^\nr] ac-3 - ac-3-12 ::= [\n] ac-3-01 | [>] ac-3-13 | [^\n>] ac-3 - ac-3-13 ::= [\n] | [^\n] ac-3 - root ::= ac-3 + root ::= until-3 space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-3 ::= [\n] until-3-01 | [^\n] until-3 + until-3-01 ::= [\n] until-3-01 | [<] until-3-02 | [^\n<] until-3 + until-3-02 ::= [\n] until-3-01 | [/] until-3-03 | [^\n/] until-3 + until-3-03 ::= [\n] until-3-01 | [p] until-3-04 | [^\np] until-3 + until-3-04 ::= [\n] until-3-01 | [a] until-3-05 | [^\na] until-3 + until-3-05 ::= [\n] until-3-01 | [r] until-3-06 | [^\nr] until-3 + until-3-06 ::= [\n] until-3-01 | [a] until-3-07 | [^\na] until-3 + until-3-07 ::= [\n] until-3-01 | [m] until-3-08 | [^\nm] until-3 + until-3-08 ::= [\n] until-3-01 | [e] until-3-09 | [^\ne] until-3 + until-3-09 ::= [\n] until-3-01 | [t] until-3-10 | [^\nt] until-3 + until-3-10 ::= [\n] until-3-01 | [e] until-3-11 | [^\ne] until-3 + until-3-11 ::= [\n] until-3-01 | [r] until-3-12 | [^\nr] until-3 + until-3-12 ::= [\n] until-3-01 | [>] until-3-13 | [^\n>] until-3 + until-3-13 ::= [\n] | [^\n] until-3 )""", gbnf); }); - t.test("ac grammar multiple delimiters", [](testing &t) { + t.test("through grammar multiple delimiters", [](testing &t) { auto parser = build_peg_parser([](common_peg_parser_builder & p) { - return p.ac(p.eps(), std::vector{"ab", "cd", "ef"}); + return p.through(p.eps(), { { p.literal("ab") }, { p.literal("cd") }, { p.literal("ef") } }); }); auto gbnf = build_grammar([&](const common_grammar_builder & builder) { @@ -272,12 +272,238 @@ void test_gbnf_generation(testing &t) { }); assert_gbnf_equal(t, R"""( - ac-1 ::= [a] ac-1-01 | [c] ac-1-03 | [e] ac-1-05 | [^ace] ac-1 - ac-1-01 ::= [b] | [a] ac-1-01 | [c] ac-1-03 | [e] ac-1-05 | [^abce] ac-1 - ac-1-03 ::= [d] | [a] ac-1-01 | [c] ac-1-03 | [e] ac-1-05 | [^acde] ac-1 - ac-1-05 ::= [f] | [a] ac-1-01 | [c] ac-1-03 | [e] ac-1-05 | [^acef] ac-1 - root ::= ac-1 + root ::= until-4 space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-4 ::= [a] until-4-01 | [c] until-4-03 | [e] until-4-05 | [^ace] until-4 + until-4-01 ::= [b] | [a] until-4-01 | [c] until-4-03 | [e] until-4-05 | [^abce] until-4 + until-4-03 ::= [d] | [a] until-4-01 | [c] until-4-03 | [e] until-4-05 | [^acde] until-4 + until-4-05 ::= [f] | [a] until-4-01 | [c] until-4-03 | [e] until-4-05 | [^acef] until-4 + )""", gbnf); + }); + + t.test("until grammar with parser delimiters", [](testing &t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + return p.until((p.literal("a") + p.literal("b")) | p.literal("cd")); + }); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder); + }); + + assert_gbnf_equal(t, R"""( + root ::= until-5 + space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-5 ::= | [a] until-5-01 | [c] until-5-03 | [^ac] until-5 + until-5-01 ::= | [a] until-5-01 | [c] until-5-03 | [^abc] until-5 + until-5-03 ::= | [a] until-5-01 | [c] until-5-03 | [^acd] until-5 + )""", gbnf); + }); + + t.test("delimiters see through tags and atomics", [](testing &t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + return p.until(p.tag("open", p.literal("a") + p.atomic(p.literal("b")))); + }); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder); + }); + + assert_gbnf_equal(t, R"""( + root ::= until-5 + space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-5 ::= | [a] until-5-01 | [^a] until-5 + until-5-01 ::= | [a] until-5-01 | [^ab] until-5 + )""", gbnf); + }); + + t.test("delimiters expand a choice in a sequence", [](testing &t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + return p.until(p.literal("a") + (p.literal("b") | p.literal("d"))); + }); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder); + }); + + assert_gbnf_equal(t, R"""( + root ::= until-5 + space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-5 ::= | [a] until-5-01 | [^a] until-5 + until-5-01 ::= | [a] until-5-01 | [^abd] until-5 + )""", gbnf); + }); + + t.test("delimiters reject anything but sequences, choices, literals, and tokens", [](testing &t) { + bool threw = false; + try { + build_peg_parser([](common_peg_parser_builder & p) { + return p.until(p.literal("a") + p.space()); + }); + } catch (const std::invalid_argument &) { + threw = true; + } + t.assert_equal("space_rejected", true, threw); + }); + + t.test("through branches reject a shared delimiter", [](testing &t) { + bool threw = false; + try { + build_peg_parser([](common_peg_parser_builder & p) { + return p.through(p.eps(), { { p.literal("ab"), p.literal("x") }, { p.literal("ab"), p.literal("y") } }); + }); + } catch (const std::invalid_argument &) { + threw = true; + } + t.assert_equal("duplicate_rejected", true, threw); + }); + + t.test("through grammar branches continue with their rest", [](testing &t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + return p.through(p.eps(), { { p.literal("ab"), p.literal("x") }, { p.literal("cd") } }); + }); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder); + }); + + assert_gbnf_equal(t, R"""( + root ::= until-4 + space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-4 ::= [a] until-4-01 | [c] until-4-03 | [^ac] until-4 + until-4-01 ::= [b] until-4-rest-0 | [a] until-4-01 | [c] until-4-03 | [^abc] until-4 + until-4-03 ::= [d] | [a] until-4-01 | [c] until-4-03 | [^acd] until-4 + until-4-rest-0 ::= "x" + )""", gbnf); + }); + + t.test("through grammar optional may end before a delimiter", [](testing &t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + return p.through(p.eps(), { { p.literal("ab"), p.literal("x") } }, true); + }); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder); + }); + + assert_gbnf_equal(t, R"""( + root ::= until-3 + space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-3 ::= | [a] until-3-01 | [^a] until-3 + until-3-01 ::= | [b] until-3-rest-0 | [a] until-3-01 | [^ab] until-3 + until-3-rest-0 ::= "x" + )""", gbnf); + }); + + t.test("trigger rules emit their start and rest when not lazy", [](testing &t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + auto ab = p.literal("ab"); + auto cd = p.literal("cd"); + auto scan = p.until(ab | cd); + return scan + (p.trigger_rule("one", ab, p.literal("x")) | p.trigger_rule("two", cd, p.literal("y"))); + }); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder, false); + }); + + assert_gbnf_equal(t, R"""( + one ::= "ab" "x" + root ::= until-3 (one | two) + space ::= | " " | "\n"{1,2} [ \t]{0,20} + two ::= "cd" "y" + until-3 ::= | [a] until-3-01 | [c] until-3-03 | [^ac] until-3 + until-3-01 ::= | [a] until-3-01 | [c] until-3-03 | [^abc] until-3 + until-3-03 ::= | [a] until-3-01 | [c] until-3-03 | [^acd] until-3 + )""", gbnf); + }); + + t.test("trigger rules make the lazy grammar scan for their starts", [](testing &t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + auto ab = p.literal("ab"); + auto cd = p.literal("cd"); + auto scan = p.until(ab | cd); + return scan + (p.trigger_rule("one", ab, p.literal("x")) | p.trigger_rule("two", cd, p.literal("y"))); + }); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder, true); + }); + + assert_gbnf_equal(t, R"""( + one-rest ::= "x" + root ::= trigger + space ::= | " " | "\n"{1,2} [ \t]{0,20} + trigger ::= | [a] trigger-01 | [c] trigger-03 | [^ac] trigger + trigger-01 ::= | [b] one-rest | [a] trigger-01 | [c] trigger-03 | [^abc] trigger + trigger-03 ::= | [d] two-rest | [a] trigger-01 | [c] trigger-03 | [^acd] trigger + two-rest ::= "y" + )""", gbnf); + }); + + t.test("scanning grammar lets other named tokens through", [](testing &t) { + common_peg_tokens tokens; + tokens.ids.emplace("", 1); + tokens.ids.emplace("", 2); + tokens.tokens.emplace(1, common_peg_token{ "", LLAMA_TOKEN_ATTR_CONTROL }); + tokens.tokens.emplace(2, common_peg_token{ "", LLAMA_TOKEN_ATTR_CONTROL }); + + common_peg_parser_builder p(tokens); + auto start = p.token("") + p.literal("x"); + p.set_root(p.until(start) + p.trigger_rule("tool", start, p.token(""))); + auto parser = p.build(); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder, true); + }); + + assert_gbnf_equal(t, R"""( + root ::= trigger + space ::= | " " | "\n"{1,2} [ \t]{0,20} + tool-rest ::= <[2]> + trigger ::= | <[1]> trigger-01 | (. | <[2]>) trigger + trigger-01 ::= | [x] tool-rest | <[1]> trigger-01 | ([^x] | <[2]>) trigger + )""", gbnf); + }); + + t.test("token sets", [](testing &t) { + common_peg_tokens tokens; + tokens.ids.emplace("", 1); + tokens.ids.emplace("", 2); + tokens.tokens.emplace(1, common_peg_token{ "", LLAMA_TOKEN_ATTR_CONTROL }); + tokens.tokens.emplace(2, common_peg_token{ "", LLAMA_TOKEN_ATTR_CONTROL }); + + common_peg_parser_builder p(tokens); + p.set_root(p.token({ "", "" }) + p.token({ "", "" }, true)); + auto parser = p.build(); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder); + }); + + assert_gbnf_equal(t, R"""( + root ::= (<[1]> | <[2]>) !<[1-2]> + space ::= | " " | "\n"{1,2} [ \t]{0,20} + )""", gbnf); + }); + + t.test("through grammar suffix delimiter offers both rests", [](testing &t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + return p.through(p.eps(), { { p.literal("xab"), p.literal("1") }, { p.literal("ab"), p.literal("2") } }); + }); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder); + }); + + assert_gbnf_equal(t, R"""( + root ::= until-5 + space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-5 ::= [x] until-5-01 | [a] until-5-04 | [^ax] until-5 + until-5-01 ::= [x] until-5-01 | [a] until-5-02 | [^ax] until-5 + until-5-02 ::= [b] (until-5-rest-0 | until-5-rest-1) | [x] until-5-01 | [a] until-5-04 | [^abx] until-5 + until-5-04 ::= [b] until-5-rest-1 | [x] until-5-01 | [a] until-5-04 | [^abx] until-5 + until-5-rest-0 ::= "1" + until-5-rest-1 ::= "2" )""", gbnf); }); diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp index 7b70e7bcc853..11fa68f6a736 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -305,6 +305,66 @@ static std::string get_expected_description(const llama_grammar_rules & rules, c return result; } +// Every text token shares one ID, the parsers and grammars only tell special tokens apart +static constexpr llama_token FAKE_TEXT_TOKEN = 0; + +struct fake_token { + llama_token id; + std::string piece; +}; + +// Splits text into the special tokens it spells, longest first, and one text token per UTF-8 character. +static std::vector fake_tokenize(const common_peg_tokens & specials, const std::string & text) { + std::vector result; + size_t pos = 0; + while (pos < text.size()) { + llama_token best = LLAMA_TOKEN_NULL; + size_t best_len = 0; + for (const auto & [piece, id] : specials.ids) { + if (piece.size() > best_len && text.compare(pos, piece.size(), piece) == 0) { + best = id; + best_len = piece.size(); + } + } + if (best != LLAMA_TOKEN_NULL) { + result.push_back({ best, text.substr(pos, best_len) }); + pos += best_len; + continue; + } + size_t len = 1; + while (pos + len < text.size() && (static_cast(text[pos + len]) & 0xC0) == 0x80) { + len++; + } + result.push_back({ FAKE_TEXT_TOKEN, text.substr(pos, len) }); + pos += len; + } + return result; +} + +// Returns the tokens from byte offset pos. A token split by pos keeps the rest of its piece as text. +static std::vector fake_tokens_from(const std::vector & tokens, size_t pos) { + std::vector result; + size_t start = 0; + for (const auto & token : tokens) { + const size_t end = start + token.piece.size(); + if (start >= pos) { + result.push_back(token); + } else if (end > pos) { + result.push_back({ FAKE_TEXT_TOKEN, token.piece.substr(pos - start) }); + } + start = end; + } + return result; +} + +static common_chat_input fake_input(const std::vector & tokens) { + common_chat_input input; + for (const auto & token : tokens) { + input.append(token.piece, token.id); + } + return input; +} + // Result of a detailed grammar match attempt struct grammar_match_result { bool success = false; // Did the string fully match the grammar? @@ -318,56 +378,49 @@ struct grammar_match_result { bool incomplete = false; // True if matched all input but grammar expects more }; -// Detailed version of match_string that returns failure information -static grammar_match_result match_string_detailed(const std::string & input, llama_grammar * grammar) { - grammar_match_result result; - result.total_bytes = input.size(); +// Detailed version of match_string that returns failure information, accepting the input token by token +static grammar_match_result match_string_detailed(const std::vector & tokens, llama_grammar * grammar) { + std::string input; + for (const auto & token : tokens) { + input += token.piece; + } - const auto cpts = unicode_cpts_from_utf8(input); - result.total_codepoints = cpts.size(); + grammar_match_result result; + result.total_bytes = input.size(); + result.total_codepoints = unicode_cpts_from_utf8(input).size(); auto & stacks_cur = llama_grammar_get_stacks(grammar); const auto & rules = llama_grammar_get_rules(grammar); size_t byte_pos = 0; + size_t cpt_pos = 0; - for (size_t i = 0; i < cpts.size(); i++) { - const auto & cpt = cpts[i]; - + for (const auto & token : tokens) { // Get expected before accepting (for error reporting) std::string expected_before = get_expected_description(rules, stacks_cur); - llama_grammar_accept(grammar, cpt); - - // Calculate byte position for this codepoint - size_t cpt_bytes = 0; - if (cpt < 0x80) { - cpt_bytes = 1; - } else if (cpt < 0x800) { - cpt_bytes = 2; - } else if (cpt < 0x10000) { - cpt_bytes = 3; - } else { - cpt_bytes = 4; - } - - if (stacks_cur.empty()) { + try { + llama_grammar_accept_token(*grammar, token.id, token.piece); + } catch (const std::runtime_error & /*e*/) { // Grammar failed to match at this point result.matched_bytes = byte_pos; - result.matched_codepoints = i; + result.matched_codepoints = cpt_pos; result.matched_prefix = input.substr(0, byte_pos); - result.failing_char = format_codepoint(cpt); + result.failing_char = token.id == FAKE_TEXT_TOKEN + ? format_codepoint(unicode_cpts_from_utf8(token.piece).at(0)) + : token.piece + " (token " + std::to_string(token.id) + ")"; result.expected_description = expected_before; result.incomplete = false; return result; } - byte_pos += cpt_bytes; + byte_pos += token.piece.size(); + cpt_pos += unicode_cpts_from_utf8(token.piece).size(); } // All input matched - check if grammar is complete result.matched_bytes = input.size(); - result.matched_codepoints = cpts.size(); + result.matched_codepoints = result.total_codepoints; result.matched_prefix = input; if (std::any_of(stacks_cur.begin(), stacks_cur.end(), [](const auto & stack) { return stack.empty(); })) { @@ -1129,6 +1182,7 @@ static std::string g_template_filter; static bool g_force_reconstruction_test = false; static void test_peg_parser(common_chat_templates * tmpls, + const common_peg_tokens & specials, const std::function & init, bool detailed_debug) { // UTF-8-safe truncation helper (same as in test_parser_with_streaming) @@ -1173,8 +1227,15 @@ static void test_peg_parser(common_chat_templates * tmpls, tc.expect.role = "assistant"; } + const bool tokenized = !specials.ids.empty(); + common_chat_session_params session_params; session_params.debug = detailed_debug; + if (tokenized) { + session_params.tokenize = [&](const std::string & text) { + return fake_input(fake_tokenize(specials, text)); + }; + } common_chat_session session(tmpls, nullptr, tc.params, session_params); const auto & parser = session.parser(); common_params_sampling sampling; @@ -1200,14 +1261,27 @@ static void test_peg_parser(common_chat_templates * tmpls, common_chat_msg msg_prev; msg_accum.role = msg_prev.role = "assistant"; - size_t fed = 0; - for (size_t i = 1; i <= tc.input.size(); ++i) { - auto is_partial = i < tc.input.size() || tc.is_partial; - // Use UTF-8 safe truncation to avoid corrupting multi-byte characters - size_t safe_len = utf8_truncate_safe_len(std::string_view(tc.input).substr(0, i)); - common_chat_input chunk(tc.input.substr(fed, safe_len - fed)); - fed = safe_len; - const common_chat_msg & msg_current = is_partial ? session.feed(chunk) : session.finish(chunk); + const auto input_tokens = fake_tokenize(specials, tc.input); + + // A token arrives whole, so a special token is never split across chunks + std::vector chunks; + if (tokenized) { + for (const auto & token : input_tokens) { + chunks.push_back(fake_input({ token })); + } + } else { + size_t fed = 0; + for (size_t i = 1; i <= tc.input.size(); ++i) { + // Use UTF-8 safe truncation to avoid corrupting multi-byte characters + size_t safe_len = utf8_truncate_safe_len(std::string_view(tc.input).substr(0, i)); + chunks.emplace_back(tc.input.substr(fed, safe_len - fed)); + fed = safe_len; + } + } + + for (size_t i = 0; i < chunks.size(); ++i) { + auto is_partial = i + 1 < chunks.size() || tc.is_partial; + const common_chat_msg & msg_current = is_partial ? session.feed(chunks[i]) : session.finish(chunks[i]); for (const auto & diff : common_chat_msg_diff::compute_diffs(msg_prev, msg_current)) { if (!diff.reasoning_content_delta.empty()) { @@ -1222,10 +1296,15 @@ static void test_peg_parser(common_chat_templates * tmpls, while (msg_accum.tool_calls.size() <= diff.tool_call_index) { msg_accum.tool_calls.push_back({ "", "", "" }); } - // Always update name and id from diff (may change during incremental parsing), but only if the delta - // actually contains them + // The name and id are set once the delta carries them. + // A name that is already set must not change, clients concatenate name deltas. if (!diff.tool_call_delta.name.empty()) { - msg_accum.tool_calls[diff.tool_call_index].name = diff.tool_call_delta.name; + auto & name = msg_accum.tool_calls[diff.tool_call_index].name; + if (!name.empty() && name != diff.tool_call_delta.name) { + throw std::runtime_error("Tool call " + std::to_string(diff.tool_call_index) + " name changed from " + + name + " to " + diff.tool_call_delta.name + " during incremental parsing"); + } + name = diff.tool_call_delta.name; } if (!diff.tool_call_delta.id.empty()) { msg_accum.tool_calls[diff.tool_call_index].id = diff.tool_call_delta.id; @@ -1413,9 +1492,10 @@ static void test_peg_parser(common_chat_templates * tmpls, // sampler was already active before model output began — constrain from the // start of the model output (i.e. tc.input). std::string constrained = full_input; + size_t constrain_from = 0; bool grammar_triggered = false; if (earliest_trigger_pos != std::string::npos) { - auto constrain_from = std::max(earliest_trigger_pos, gen_prompt.size()); + constrain_from = std::max(earliest_trigger_pos, gen_prompt.size()); constrained = full_input.substr(constrain_from); grammar_triggered = true; } else if (!sampling.grammar_lazy) { @@ -1425,7 +1505,9 @@ static void test_peg_parser(common_chat_templates * tmpls, // Test the constrained portion against the grammar if (grammar_triggered && !tc.is_partial) { - auto result = match_string_detailed(constrained, grammar.get()); + auto full_tokens = fake_tokenize(specials, gen_prompt); + full_tokens.insert(full_tokens.end(), input_tokens.begin(), input_tokens.end()); + auto result = match_string_detailed(fake_tokens_from(full_tokens, constrain_from), grammar.get()); if (!result.success) { std::string error_msg; if (result.incomplete) { @@ -1514,6 +1596,7 @@ class peg_tester { common_chat_templates_ptr tmpls_; std::string template_path_; bool detailed_debug_; + common_peg_tokens specials_; friend class peg_test_builder; public: @@ -1529,6 +1612,18 @@ class peg_tester { const std::string & template_path() const { return template_path_; } + // Run the tests tokenized with these pieces as special tokens, as if the vocab defined them + peg_tester & specials(const std::vector & pieces) { + llama_token id = FAKE_TEXT_TOKEN + 1; + for (const auto & piece : pieces) { + specials_.ids.emplace(piece, id); + specials_.tokens.emplace(id, common_peg_token{ piece, LLAMA_TOKEN_ATTR_CONTROL }); + id++; + } + common_chat_templates_set_specials(tmpls_.get(), specials_); + return *this; + } + peg_test_builder test(const std::string & input); }; @@ -1649,8 +1744,10 @@ class peg_test_builder { return; } } - LOG_INF("\n\x1b[38;5;126m[%s]\x1b[0m\n%s\n\n", tester_.template_path().c_str(), tc_.input.c_str()); - test_peg_parser(tester_.tmpls_.get(), [this](peg_test_case & t) { t = tc_; }, tester_.detailed_debug_); + LOG_INF("\n\x1b[38;5;126m[%s%s]\x1b[0m\n%s\n\n", tester_.template_path().c_str(), + tester_.specials_.ids.empty() ? "" : ", tokenized", tc_.input.c_str()); + test_peg_parser(tester_.tmpls_.get(), tester_.specials_, [this](peg_test_case & t) { t = tc_; }, + tester_.detailed_debug_); } }; @@ -2269,9 +2366,17 @@ static void test_template_output_peg_parsers(bool detailed_debug) { "const": "42" })"; + // Special tokens of the templates that use the Qwen3-Coder format. + // Check that the vocab of a model defines them before reuse. A model can share the syntax without the tokens. + const std::vector qwen3_coder_specials = { + "<|im_start|>", "<|im_end|>", "", "", + "", "", "", "", + }; + { // Qwen3.5 (basically same as Nemotron, but keeping separate tests just in case) auto tst = peg_tester("models/templates/Qwen3.5-4B.jinja", detailed_debug); + tst.specials(qwen3_coder_specials); tst.test("I'm\nthinking\n\n\nHello, world!\nWhat's up?") .reasoning_format(COMMON_REASONING_FORMAT_AUTO) @@ -2843,6 +2948,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { { // NVIDIA Nemotron-3 Nano auto tst = peg_tester("models/templates/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16.jinja", detailed_debug); + tst.specials(qwen3_coder_specials); tst.test("Hello, world!\nWhat's up?"). enable_thinking(false). @@ -3138,6 +3244,8 @@ static void test_template_output_peg_parsers(bool detailed_debug) { { // Google Gemma 4 (tool calling with Gemma4 dict format) auto tst = peg_tester("models/templates/google-gemma-4-31B-it.jinja"); + tst.specials({ "<|turn>", "", "<|channel>", "", "<|tool_call>", "", + "<|tool_response>", "", "<|tool>", "", "<|\"|>", "<|think|>" }); tst.test("Hello, world!").expect(simple_assist_msg("Hello, world!")).run(); @@ -3766,6 +3874,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { { // Qwen3-Coder (tool calling with XML-style format) auto tst = peg_tester("models/templates/Qwen3-Coder.jinja", detailed_debug); + tst.specials(qwen3_coder_specials); tst.test("Hello, world!\nWhat's up?").expect(message_assist).expect_reconstruction().run(); @@ -3794,6 +3903,20 @@ static void test_template_output_peg_parsers(bool detailed_debug) { .expect(message_assist_call) .run(); + // Required tool choice constrains from the first token instead of gating on a trigger + tst.test( + "\n" + "\n" + "\n" + "1\n" + "\n" + "\n" + "") + .tools({ special_function_tool }) + .tool_choice(COMMON_CHAT_TOOL_CHOICE_REQUIRED) + .expect(message_assist_call) + .run(); + tst.test( "Let me call it.\n" "\n" @@ -5895,6 +6018,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { { auto tst = peg_tester("models/templates/LFM3.jinja", detailed_debug); + tst.specials(qwen3_coder_specials); tst.test("Hello, world!\nWhat's up?") .enable_thinking(false) @@ -7157,6 +7281,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { // Muse Glimmer format tests { auto tst = peg_tester("models/templates/muse-glimmer.jinja", detailed_debug); + tst.specials({ "<|start|>", "<|message|>", "<|eom|>" }); const std::string call_markup = "\n" @@ -7166,7 +7291,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { ""; // A plain answer is unaffected - tst.test(" to=user<|message|>Hello, world!\nWhat's up?<|eot|>") + tst.test(" to=user<|message|>Hello, world!\nWhat's up?") .reasoning_format(COMMON_REASONING_FORMAT_AUTO) .expect(message_assist) .run(); @@ -7177,7 +7302,34 @@ static void test_template_output_peg_parsers(bool detailed_debug) { .tools({ special_function_tool }) .reasoning_format(COMMON_REASONING_FORMAT_AUTO) .expect(message_assist_call) - .expect_rules({ "tool-0" }) + .expect_rules({ "tool-0", "tool-calls" }) + .run(); + + // Parallel calls, one message per call + tst.test(" to=special_function<|message|>" + call_markup + "<|eom|>" + "<|start|>assistant to=special_function_with_opt<|message|>" + "\n" + "\n" + "1\n" + "2\n" + "\n" + "") + .tools({ special_function_tool, special_function_tool_with_optional_param }) + .parallel_tool_calls(true) + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .expect_tool_calls({ + { "special_function", R"({"arg1": 1})", {} }, + { "special_function_with_opt", R"({"arg1": 1, "arg2": 2})", {} }, + }) + .run(); + + // Required tool choice after a reasoning message + tst.test(" to=self<|message|>I'm\nthinking<|eom|>" + "<|start|>assistant to=special_function<|message|>" + call_markup) + .tools({ special_function_tool }) + .tool_choice(COMMON_CHAT_TOOL_CHOICE_REQUIRED) + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .expect(message_assist_call_thoughts) .run(); // "Inform then act": the model answers the user and calls a tool in ONE generation, @@ -7193,7 +7345,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { // Markup quoted in an answer has no preceding <|eom|>, so it stays content instead of // becoming an invocation the user never asked for - tst.test(" to=user<|message|>You invoke it like this:\n" + call_markup + "<|eot|>") + tst.test(" to=user<|message|>You invoke it like this:\n" + call_markup) .tools({ special_function_tool }) .reasoning_format(COMMON_REASONING_FORMAT_AUTO) .expect_content("You invoke it like this:\n" + call_markup) @@ -7217,7 +7369,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { // Tool markup inside the analysis channel is reasoning, not a call tst.test(" to=self<|message|>I could use " + call_markup + " here<|eom|>" - "<|start|>assistant to=user<|message|>Hello!<|eot|>") + "<|start|>assistant to=user<|message|>Hello!") .tools({ special_function_tool }) .reasoning_format(COMMON_REASONING_FORMAT_AUTO) .expect_reasoning("I could use " + call_markup + " here") @@ -7288,6 +7440,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { // GPT-OSS format tests { auto tst = peg_tester("models/templates/openai-gpt-oss-120b.jinja", detailed_debug); + tst.specials({ "<|start|>", "<|end|>", "<|message|>", "<|channel|>", "<|constrain|>", "<|return|>", "<|call|>" }); // Basic content only - final channel tst.test("<|channel|>final<|message|>Hello, world!\nWhat's up?").expect(message_assist).run(); @@ -7327,7 +7480,30 @@ static void test_template_output_peg_parsers(bool detailed_debug) { .reasoning_format(COMMON_REASONING_FORMAT_AUTO) .tools({ special_function_tool }) .expect(message_assist_call) - .expect_rules({ "tool-0" }) + .expect_rules({ "tool-0-in-role", "tool-0-in-channel" }) + .run(); + + // A tool whose name prefixes another's must not be reported while the header is still open + tst.test(" to=functions.special_function_with_opt<|channel|>analysis<|message|>{\"arg1\": 1}") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .tools({ special_function_tool, special_function_tool_with_optional_param }) + .expect(simple_assist_msg("", "", "special_function_with_opt", "{\"arg1\": 1}")) + .run(); + + tst.test("<|channel|>commentary to=functions.special_function_with_opt<|message|>{\"arg1\": 1}") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .tools({ special_function_tool, special_function_tool_with_optional_param }) + .expect(simple_assist_msg("", "", "special_function_with_opt", "{\"arg1\": 1}")) + .run(); + + // Required tool choice constrains from the first token instead of gating on a trigger + tst.test( + "<|channel|>analysis<|message|>I'm\nthinking<|end|>" + "<|start|>assistant to=functions.special_function<|channel|>analysis<|message|>{\"arg1\": 1}") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .tools({ special_function_tool }) + .tool_choice(COMMON_CHAT_TOOL_CHOICE_REQUIRED) + .expect(message_assist_call_thoughts) .run(); // Tool call with recipient in channel header: "<|channel|>analysis to=functions.NAME<|message|>JSON" @@ -7544,6 +7720,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { { auto tst = peg_tester("models/templates/StepFun3.5-Flash.jinja", detailed_debug); + tst.specials(qwen3_coder_specials); tst.test("I was thinking\n\nNow I'm not."). enable_thinking(true). diff --git a/tests/test-grammar-integration.cpp b/tests/test-grammar-integration.cpp index a7a7e968ef42..ec2b1b784c1f 100644 --- a/tests/test-grammar-integration.cpp +++ b/tests/test-grammar-integration.cpp @@ -41,15 +41,21 @@ struct token_and_piece { std::string piece; }; -// token() encodes a 32-bit ID as 5 bytes: a 0xff marker followed by the ID in big-endian order. -static std::string token(llama_token id) { +// token() encodes a token and its piece as a 0xff marker, the ID in big-endian order, the piece length, and the piece. +static std::string token(llama_token id, const std::string & piece) { return std::string{ static_cast(0xff), static_cast((id >> 24) & 0xff), static_cast((id >> 16) & 0xff), static_cast((id >> 8) & 0xff), - static_cast(id & 0xff) - }; + static_cast(id & 0xff), + static_cast(piece.size()) + } + piece; +} + +// token() without a piece encodes a token whose piece is its <[id]> spelling. +static std::string token(llama_token id) { + return token(id, "<[" + std::to_string(id) + "]>"); } // parse_tokens() parses the token encodes above and UTF-8 text. @@ -60,7 +66,7 @@ static std::vector parse_tokens(const std::string & input) { while (offset < input.size()) { try { if (static_cast(input[offset]) == 0xff) { - if (offset + 5 > input.size()) { + if (offset + 6 > input.size()) { throw std::runtime_error("not enough bytes for token id"); } uint32_t val = @@ -68,9 +74,12 @@ static std::vector parse_tokens(const std::string & input) { (static_cast(input[offset + 2]) << 16) | (static_cast(input[offset + 3]) << 8) | (static_cast(input[offset + 4])); - auto piece = "<[" + std::to_string(val) + "]>"; - result.push_back({static_cast(val), piece}); - offset += 5; + size_t len = static_cast(input[offset + 5]); + if (offset + 6 + len > input.size()) { + throw std::runtime_error("not enough bytes for token piece"); + } + result.push_back({static_cast(val), input.substr(offset + 6, len)}); + offset += 6 + len; } else { uint32_t cpt = unicode_cpt_from_utf8(input, offset); result.push_back({0, unicode_cpt_to_utf8(cpt)}); @@ -84,23 +93,42 @@ static std::vector parse_tokens(const std::string & input) { return result; } +// Returns true if the sampler mask allows the token. The mask rejects a token only when every stack rejects it. +static bool mask_allows(llama_grammar * grammar, const token_and_piece & in) { + const auto decoded = llama_grammar_decode_utf8(in.piece, grammar->partial_utf8); + + llama_grammar_candidates rejects = { { 0, decoded.first.data(), decoded.second, in.token, llama_grammar_is_opaque(*grammar, in.token) } }; + for (const auto & stack : llama_grammar_get_stacks(grammar)) { + rejects = llama_grammar_reject_candidates_for_stack(llama_grammar_get_rules(grammar), stack, rejects); + } + return rejects.empty(); +} + static bool match_string(const std::string & input, llama_grammar * grammar) { const auto parsed = parse_tokens(input); auto & stacks_cur = llama_grammar_get_stacks(grammar); for (const auto & in : parsed) { + const bool allowed = mask_allows(grammar, in); + + // the mask decides what can be sampled, so it has to agree with what accepting the token does try { llama_grammar_accept_token(*grammar, in.token, in.piece); } catch (const std::runtime_error & /*e*/) { - // normally this shouldn't get hit because of llama_grammar_apply - return false; - } + if (allowed) { + fprintf(stderr, "❌ (token %d \"%s\" is allowed by the mask but not accepted)\n", in.token, in.piece.c_str()); + } + assert(!allowed); - if (stacks_cur.empty()) { // no stacks means that the grammar failed to match at this point return false; } + + if (!allowed) { + fprintf(stderr, "❌ (token %d \"%s\" is masked but accepted)\n", in.token, in.piece.c_str()); + } + assert(allowed); } for (const auto & stack : stacks_cur) { @@ -121,6 +149,7 @@ static void test(const std::string & test_desc, const std::string & grammar_str, // Save the original grammar stacks so that we can reset after every new string we want to test const llama_grammar_stacks stacks_org = llama_grammar_get_stacks(grammar); // copy + const llama_partial_utf8 partial_org = grammar->partial_utf8; llama_grammar_stacks & stacks_cur = llama_grammar_get_stacks(grammar); @@ -160,6 +189,7 @@ static void test(const std::string & test_desc, const std::string & grammar_str, // Reset the grammar stacks stacks_cur = stacks_org; + grammar->partial_utf8 = partial_org; } fprintf(stderr, " 🟠 Invalid strings:\n"); @@ -180,6 +210,7 @@ static void test(const std::string & test_desc, const std::string & grammar_str, // Reset the grammar stacks stacks_cur = stacks_org; + grammar->partial_utf8 = partial_org; } // Clean up allocated memory @@ -522,6 +553,137 @@ static void test_simple_grammar() { ); } +static void test_token_rule_utf8() { + // A byte-level token can hold part of a multibyte character, a token rule still takes it as a whole token + test_grammar( + "byte-split characters under token rules", + R"""( + root ::= <[10]> content <[11]> + content ::= (!<[11]>)*)""", + // Passing strings + { + token(10) + token(20, "\xF0") + token(21, "\x9F\xA6\x99") + token(11), + token(10) + token(22, "\xE2") + token(23, "\x98\x80") + token(11), + token(10) + token(24, "a\xF0") + token(21, "\x9F\xA6\x99") + token(11), + }, + // Failing strings + { + token(10) + token(20, "\xF0"), + token(10) + token(20, "\xF0") + token(11), + } + ); + + // A token rule can only start where a token starts, not after char rules consumed part of it + test_grammar( + "token rule after a char rule", + R"""( + root ::= "a" <[11]>)""", + // Passing strings + { + "a" + token(11), + token(12, "a") + token(11), + }, + // Failing strings + { + token(11, "ab"), + token(12, "ab") + token(11), + } + ); + + // A token partly matched by a char rule stays partly matched for every alternative, whichever is checked first + test_grammar( + "token rule alternative after a char rule", + R"""( + root ::= "a" (!<[7]> | "bx"))""", + // Passing strings + { + "abx", + token(12, "abx"), + "a" + token(5), + }, + // Failing strings + { + token(5, "aby"), + token(5, "ab"), + } + ); +} + +static void test_token_sets() { + test_grammar( + "token set with alternatives and ranges", + R"""( + root ::= <[1,5-9,12]>+)""", + // Passing strings + { + token(1), + token(5) + token(9), + token(7) + token(12) + token(1), + }, + // Failing strings + { + token(2), + token(4), + token(10), + token(13), + token(5) + token(11), + } + ); + + test_grammar( + "negated token set", + R"""( + root ::= <[10]> (!<[11,20-29]>)* <[11]>)""", + // Passing strings + { + token(10) + token(11), + token(10) + "text" + token(12) + token(19) + token(30) + token(11), + }, + // Failing strings + { + token(10) + token(20) + token(11), + token(10) + token(29) + token(11), + token(10) + token(11) + token(11), + } + ); +} + +static void test_opaque_tokens() { + // Char rules do not match a token that a token rule names, other tokens still match as text + test_grammar( + "tokens named by token rules are opaque to char rules", + R"""( + root ::= [^x]* <[11]> "done")""", + // Passing strings + { + "abc" + token(11) + "done", + token(11) + "done", + token(12) + token(11) + "done", + }, + // Failing strings + { + "abc" + token(11) + "more" + token(11) + "done", + token(11) + token(11) + "done", + } + ); + + test_grammar( + "tokens named by a negated set are opaque to char rules", + R"""( + root ::= [^x]* !<[11,20-29]>)""", + // Passing strings + { + "abc" + token(30), + token(12) + token(30), + }, + // Failing strings + { + token(25) + token(30), + token(11) + token(30), + } + ); +} + static void test_complex_grammar() { // Test case for a more complex grammar, with both failure strings and success strings test_grammar( @@ -1539,6 +1701,9 @@ int main() { fprintf(stdout, "Running grammar integration tests...\n"); test_simple_grammar(); test_complex_grammar(); + test_token_rule_utf8(); + test_token_sets(); + test_opaque_tokens(); test_special_chars(); test_quantifiers(); test_failure_missing_root(); diff --git a/tests/test-grammar-parser.cpp b/tests/test-grammar-parser.cpp index a6a99520c013..6a35fd66cd58 100644 --- a/tests/test-grammar-parser.cpp +++ b/tests/test-grammar-parser.cpp @@ -179,6 +179,14 @@ int main() verify_failure(deep_grammar.c_str()); } + verify_failure(R"""( + root ::= <[9-5]> + )"""); + + verify_failure(R"""( + root ::= <[4294967296]> + )"""); + verify_parsing(R"""( root ::= "a"{0,5000} )""", { @@ -594,5 +602,21 @@ int main() {LLAMA_GRETYPE_END, 0}, }); + verify_parsing(R"""( + root ::= <[1,5-9,12]> !<[11,20-29]> + )""", { + {"root", 0} + }, { + // root (index 0) + {LLAMA_GRETYPE_TOKEN, 1}, + {LLAMA_GRETYPE_TOKEN_ALT, 5}, + {LLAMA_GRETYPE_TOKEN_RNG_UPPER, 9}, + {LLAMA_GRETYPE_TOKEN_ALT, 12}, + {LLAMA_GRETYPE_TOKEN_NOT, 11}, + {LLAMA_GRETYPE_TOKEN_ALT, 20}, + {LLAMA_GRETYPE_TOKEN_RNG_UPPER, 29}, + {LLAMA_GRETYPE_END, 0}, + }); + return 0; } diff --git a/tests/test-llama-grammar.cpp b/tests/test-llama-grammar.cpp index 25f432a2f506..3b3beb4384a3 100644 --- a/tests/test-llama-grammar.cpp +++ b/tests/test-llama-grammar.cpp @@ -202,7 +202,7 @@ int main() uint32_t *cp = new uint32_t[2]; // dynamically allocate memory for code_point cp[0] = 37 + i; cp[1] = 0; - next_candidates[i] = {i, cp, {}, 0}; + next_candidates[i] = {i, cp, {}, 0, false}; } std::vector>> expected_reject = { From e14a2d3a63253cb3bdd6a8916d8eda83ed386d37 Mon Sep 17 00:00:00 2001 From: Pedro Cuenca Date: Sun, 22 Nov 2026 18:59:17 +0100 Subject: [PATCH 16/24] skill: Pay attention to tokenizer flags (#32819) --- skills/add-new-model/SKILL.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/skills/add-new-model/SKILL.md b/skills/add-new-model/SKILL.md index 3e4d178ebeb7..3b26828686e7 100644 --- a/skills/add-new-model/SKILL.md +++ b/skills/add-new-model/SKILL.md @@ -69,6 +69,7 @@ These recur often enough in review comments on past add-model PRs that they're w - Before writing a dedicated tool-call/output parser, check whether the existing autoparser already handles the template (`test-chat-auto-parser ` shows what it detects). - Marking a custom EOS/closing-tag token as `eot` at conversion time isn't always sufficient - in long/agentic generations a model can emit the closing sequence as literal text instead of the token, so generation never stops on EOG and raw text leaks past the parser. Verify this case, not just the token path. - If reusing or aliasing an existing pre-tokenizer for convenience, justify and test that choice explicitly - silent reuse is an easy source of subtle tokenizer bugs. +- The GGUF only stores the pre-tokenizer name (`tokenizer.pre`), the behavior flags are hard-coded per name in `src/llama-vocab.cpp`. When adding a new name, set each flag from the HF `tokenizer.json`, not from the case you copied. Examples: `model.ignore_merges` -> `ignore_merges`, the BOS/EOS of the post-processor -> `special_bos_id` / `add_bos`, prefix space and space cleanup -> `add_space_prefix` / `clean_spaces`. The `chkhsh` check in the converter only identifies the pre-tokenizer on a short text, it may not catch a wrong flag. - Watch for excessive graph splits caused by building per-layer view/index tensors inside the layer loop - hoist tensors that don't vary per layer out of the loop (relevant if you hit `GGML_SCHED_MAX_SPLIT_INPUTS`). - A custom KQ mask fed into flash attention must match FA's expected dtype - cast it to F16 before passing it to `build_attn_mha` when FA is enabled. - When padding a custom KV-cache size to an alignment (e.g. `GGML_PAD(..., 256)`), apply the padding after all other size adjustments, not before - otherwise later logic can un-align it again. @@ -83,12 +84,13 @@ These recur often enough in review comments on past add-model PRs that they're w Reference: `examples/model-conversion/README.md`. 1. Convert to GGUF, then inspect/run both the original and converted tensors. -2. Run logits verification (original vs converted). If this model is a new version of an already-supported family, verify the *previous* version still passes logits verification first - numerical differences may be pre-existing, not caused by the new work. The tools to perform full logits validation are available in `examples/model-conversion`. -3. Quantize (including QAT variants if relevant) and re-verify. -4. Run perplexity evaluation (simple and full). -5. Sanity-check across `tools/cli`, `tools/completion`, `tools/imatrix`, `tools/quantize`, and `tools/server`. -6. CPU backend first; other backends (CUDA, Metal, ...) can be separate follow-up PRs per `CONTRIBUTING.md`. -7. Re-review every changed file against the coding/naming guidelines in `AGENTS.md` (and `CONTRIBUTING.md`'s "Coding guidelines"/"Naming guidelines" sections) - this is a separate pass from functional testing and is just as important: no forced line-wrapping, no unicode punctuation, minimal/non-redundant comments, `snake_case` naming (`kebab-case` for file names), matching indentation/brace style, etc. +2. If the model adds a new pre-tokenizer, compare the token ids of `llama-tokenize -f --ids --no-escape` with the HF tokenizer on whole files of prose, code and multilingual text (e.g. wikitext-2 and a few source files). +3. Run logits verification (original vs converted). If this model is a new version of an already-supported family, verify the *previous* version still passes logits verification first - numerical differences may be pre-existing, not caused by the new work. The tools to perform full logits validation are available in `examples/model-conversion`. +4. Quantize (including QAT variants if relevant) and re-verify. +5. Run perplexity evaluation (simple and full). +6. Sanity-check across `tools/cli`, `tools/completion`, `tools/imatrix`, `tools/quantize`, and `tools/server`. +7. CPU backend first; other backends (CUDA, Metal, ...) can be separate follow-up PRs per `CONTRIBUTING.md`. +8. Re-review every changed file against the coding/naming guidelines in `AGENTS.md` (and `CONTRIBUTING.md`'s "Coding guidelines"/"Naming guidelines" sections) - this is a separate pass from functional testing and is just as important: no forced line-wrapping, no unicode punctuation, minimal/non-redundant comments, `snake_case` naming (`kebab-case` for file names), matching indentation/brace style, etc. ## Before opening a PR From 56eea9e4b0f5d125da16b75b551440b170aa8b1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20Gallou=C3=ABt?= Date: Sun, 22 Nov 2026 19:00:05 +0100 Subject: [PATCH 17/24] server : add offset pagination to grep_search tool (#32792) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Adrien Gallouët --- tools/server/server-tools.cpp | 29 +++++-- tools/server/tests/unit/test_tools_builtin.py | 80 +++++++++++++++++++ 2 files changed, 101 insertions(+), 8 deletions(-) diff --git a/tools/server/server-tools.cpp b/tools/server/server-tools.cpp index 63626ddcc3df..060361968c59 100644 --- a/tools/server/server-tools.cpp +++ b/tools/server/server-tools.cpp @@ -1121,6 +1121,7 @@ struct server_tool_grep_search : server_tool { {"literal", {{"type", "boolean"}, {"description", "Treat pattern as a literal string instead of a regular expression (default: false)"}}}, {"ignore_case", {{"type", "boolean"}, {"description", "Case-insensitive search (default: false)"}}}, {"context_lines", {{"type", "integer"}, {"description", "Number of lines of context to show before and after each match (default: 0)"}}}, + {"offset", {{"type", "integer"}, {"description", "Number of matching lines to skip (default: 0)"}}}, }}, {"required", json::array({"path", "pattern"})}, }}, @@ -1137,6 +1138,7 @@ struct server_tool_grep_search : server_tool { bool literal = json_value(params, "literal", false); bool ignore_case = json_value(params, "ignore_case", false); int ctx_lines = std::max(0, json_value(params, "context_lines", 0)); + uint64_t offset = std::max(0, json_value(params, "offset", int64_t{0})); std::string pattern_src = pat_str; if (literal) { @@ -1164,6 +1166,7 @@ struct server_tool_grep_search : server_tool { // collect (absolute_path, display_path) pairs to search std::vector> files; + bool listing_truncated = false; const std::string abs_path = io->resolve(path); if (io->is_regular_file(abs_path)) { files.emplace_back(abs_path, path); @@ -1172,6 +1175,7 @@ struct server_tool_grep_search : server_tool { if (!listing.err.empty()) { return {{"error", listing.err + ": " + path}}; } + listing_truncated = listing.truncated; for (const auto & entry : listing.entries) { if (!path_glob_match(include, entry.rel)) continue; if (!exclude.empty() && path_glob_match(exclude, entry.rel)) continue; @@ -1180,14 +1184,18 @@ struct server_tool_grep_search : server_tool { } else { return {{"error", "path does not exist: " + path}}; } + std::sort(files.begin(), files.end(), [](const auto & a, const auto & b) { + return a.second < b.second; + }); std::ostringstream output_text; + uint64_t skipped = 0; size_t total = 0; - bool limit_reached = false; + bool has_more = false; bool show_num = show_lineno || ctx_lines > 0; for (const auto & file_entry : files) { - if (limit_reached) break; + if (has_more) break; const std::string & fpath = file_entry.first; const std::string & display_path = file_entry.second; @@ -1201,11 +1209,15 @@ struct server_tool_grep_search : server_tool { } for (size_t i = 0; i < lines.size(); i++) { + if (!std::regex_search(lines[i], pattern)) continue; + if (skipped < offset) { + skipped++; + continue; + } if (total >= SERVER_TOOL_GREP_SEARCH_MAX_RESULTS) { - limit_reached = true; + has_more = true; break; } - if (!std::regex_search(lines[i], pattern)) continue; long ctx_start = ctx_lines > 0 ? std::max(0, (long) i - ctx_lines) : (long) i; long ctx_end = ctx_lines > 0 ? std::min((long) lines.size() - 1, (long) i + ctx_lines) : (long) i; @@ -1226,10 +1238,11 @@ struct server_tool_grep_search : server_tool { } output_text << "\n---\nTotal matches: " << total << "\n"; - if (limit_reached) { - output_text << string_format( - "[%zu matches limit reached. Narrow the path/pattern/include to see more.]\n", - SERVER_TOOL_GREP_SEARCH_MAX_RESULTS); + if (has_more) { + output_text << "Continue with offset=" << offset + total << " and the same search arguments.\n"; + } + if (listing_truncated) { + output_text << "[results truncated: time budget or unreadable directory]\n"; } return {{"plain_text_response", output_text.str()}}; diff --git a/tools/server/tests/unit/test_tools_builtin.py b/tools/server/tests/unit/test_tools_builtin.py index b6673a089b09..c830b0642f63 100755 --- a/tools/server/tests/unit/test_tools_builtin.py +++ b/tools/server/tests/unit/test_tools_builtin.py @@ -1,4 +1,5 @@ import os +import re import shutil import subprocess @@ -53,6 +54,85 @@ def test_tools_builtin_grep_search(): assert "Total matches: 1" in text +def _grep_matches(text: str) -> list[tuple[str, int, str]]: + matches = [] + for line in text.splitlines(): + match = re.match(r"^(.*):(\d+):(match-\d+)$", line) + if match: + path, line_number, identity = match.groups() + matches.append((path, int(line_number), identity)) + return matches + + +def test_tools_builtin_grep_search_pagination(tmp_path): + global server + server.start() + + path = tmp_path / "matches.txt" + expected = [f"match-{i:03d}" for i in range(231)] + path.write_text("\n".join(expected) + "\n") + params = {"path": str(path), "pattern": "match-", "return_line_numbers": True} + + pages = [] + next_offset = 0 + for page_index, expected_size in enumerate([100, 100, 31]): + page_params = params if not pages else {**params, "offset": next_offset} + text = call_tool("grep_search", page_params)["plain_text_response"] + matches = _grep_matches(text) + pages.append(matches) + assert len(matches) == expected_size + assert f"\n---\nTotal matches: {expected_size}\n" in text + + continuation = re.search(r"Continue with offset=(\d+) and the same search arguments\.", text) + if page_index < 2: + assert continuation is not None + next_offset = int(continuation.group(1)) + assert next_offset == (page_index + 1) * 100 + else: + assert continuation is None + + assert [identity for page in pages for _, _, identity in page] == expected + + +def test_tools_builtin_grep_search_exact_page_has_no_continuation(tmp_path): + global server + server.start() + + path = tmp_path / "matches.txt" + path.write_text("".join(f"match-{i:03d}\n" for i in range(100)) + "unrelated\n") + res = call_tool("grep_search", {"path": str(path), "pattern": "match-", "return_line_numbers": True}) + text = res["plain_text_response"] + + assert len(_grep_matches(text)) == 100 + assert "Total matches: 100" in text + assert "Continue with offset=" not in text + assert "matches limit reached" not in text + + +def test_tools_builtin_grep_search_page_order_with_context(tmp_path): + global server + server.start() + + (tmp_path / "z.txt").write_text("".join(f"match-{i:03d}\n" for i in range(50))) + (tmp_path / "a.txt").write_text("".join(f"match-{i:03d}\n" for i in range(50, 120))) + params = {"path": str(tmp_path), "pattern": "match-", "context_lines": 1} + + first = call_tool("grep_search", {**params, "offset": 0})["plain_text_response"] + second = call_tool("grep_search", {**params, "offset": 100})["plain_text_response"] + past_end = [call_tool("grep_search", {**params, "offset": offset})["plain_text_response"] for offset in (121, 1 << 32)] + + expected = [("a.txt", line, f"match-{line + 49:03d}") for line in range(1, 71)] + expected += [("z.txt", line, f"match-{line - 1:03d}") for line in range(1, 51)] + assert _grep_matches(first) == expected[:100] + assert _grep_matches(second) == expected[100:] + assert "Continue with offset=100 and the same search arguments." in first + assert "Continue with offset=" not in second + for text in past_end: + assert _grep_matches(text) == [] + assert "Total matches: 0" in text + assert "Continue with offset=" not in text + + def test_tools_builtin_read_file(tmp_path): global server server.start() From 8c6f0c0ca5ba9c59539290904fbb77870a14b4fc Mon Sep 17 00:00:00 2001 From: Piotr Wilkin Date: Sun, 22 Nov 2026 19:22:54 +0100 Subject: [PATCH 18/24] move the indexed bias test to test-backend-ops, add the bias in F32 on CPU Assisted-by: Claude Opus 5.5 --- ggml/include/ggml.h | 2 +- ggml/src/ggml-cpu/ops.cpp | 4 +- tests/CMakeLists.txt | 1 - tests/test-backend-ops.cpp | 133 +++++++++++++++++++++++ tests/test-flash-attn-indexed-bias.cpp | 144 ------------------------- 5 files changed, 136 insertions(+), 148 deletions(-) delete mode 100644 tests/test-flash-attn-indexed-bias.cpp diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 496fadbc30a9..db5fb12615fb 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -2285,7 +2285,7 @@ extern "C" { GGML_API bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a); - // Add table[indices[key, query], head, query] to the mask before its F16 rounding. + // Add table[indices[key, query], head, query] to the mask, in F32. // Queries from all streams are flattened in stream order. Indices must be in [0, table->ne[0]). GGML_API void ggml_flash_attn_ext_add_indexed_bias( struct ggml_tensor * a, diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index 0a286adcb9ce..840e834b0a06 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -8989,7 +8989,7 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( float mv = mp ? GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f; if (bias) { GGML_ASSERT(bins[ic] >= 0 && bins[ic] < n_bins); - mv = GGML_CPU_FP16_TO_FP32(GGML_CPU_FP32_TO_FP16(mv + bias[bins[ic]])); + mv += bias[bins[ic]]; } mv *= slope; if (mv == -INFINITY) { @@ -9257,7 +9257,7 @@ static void ggml_compute_forward_flash_attn_ext_tiled( float m = GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]); if (bias) { GGML_ASSERT(bins[ic + tk] >= 0 && bins[ic + tk] < n_bins); - m = GGML_CPU_FP16_TO_FP32(GGML_CPU_FP32_TO_FP16(m + bias[bins[ic + tk]])); + m += bias[bins[ic + tk]]; } mask32[tq * KV_TILE_SZ + tk] = slope * m; if (mask32[tq * KV_TILE_SZ + tk] != -INFINITY) { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index f9dff8bf8ccd..5b997e91bbcf 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -367,7 +367,6 @@ endif() llama_build(test-backend-ops.cpp LINK ggml Threads::Threads) llama_build_and_test(test-backend-tensor.cpp LINK ggml) -llama_build_and_test(test-flash-attn-indexed-bias.cpp LINK ggml) llama_build_and_test(test-sleep.cpp LINK ggml) llama_build_and_test(test-backend-sched.cpp LINK ggml) diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 711674958542..33046e0ec3b3 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9419,6 +9419,124 @@ struct test_flash_attn_ext_kv_rows : public test_case { } }; +// GGML_OP_FLASH_ATTN_EXT with an indexed bias: mask[key, query] += table[indices[key, query], head, query] +struct test_flash_attn_ext_indexed_bias : public test_case { + const int64_t hs; + const int64_t nh; // K/V heads + const int64_t gqa; + const int64_t kv; // mask columns + const int64_t nb; // queries per stream + const int64_t n_stream; + const int64_t n_bins; + const bool kv_rows; // all streams read one K/V cache of 2*kv rows through kv_rows + const bool sinks; + const ggml_type type_KV; + + std::vector rows; + + std::string vars() override { + return VARS_TO_STR10(hs, nh, gqa, kv, nb, n_stream, n_bins, kv_rows, sinks, type_KV); + } + + double max_nmse_err() override { + return 5e-4; + } + + test_flash_attn_ext_indexed_bias(int64_t hs = 128, int64_t nh = 2, int64_t gqa = 3, int64_t kv = 768, int64_t nb = 7, int64_t n_stream = 2, + int64_t n_bins = 17, bool kv_rows = false, bool sinks = true, ggml_type type_KV = GGML_TYPE_F16) + : hs(hs), nh(nh), gqa(gqa), kv(kv), nb(nb), n_stream(n_stream), n_bins(n_bins), kv_rows(kv_rows), sinks(sinks), type_KV(type_KV) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, hs, nb, nh*gqa, n_stream); + ggml_set_name(q, "q"); + + ggml_tensor * k = ggml_new_tensor_4d(ctx, type_KV, hs, kv_rows ? 2*kv : kv, nh, kv_rows ? 1 : n_stream); + ggml_tensor * v = ggml_new_tensor_4d(ctx, type_KV, hs, kv_rows ? 2*kv : kv, nh, kv_rows ? 1 : n_stream); + ggml_set_name(k, "k"); + ggml_set_name(v, "v"); + + ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, kv, nb, 1, n_stream); + ggml_set_name(m, "m"); + + ggml_tensor * r = nullptr; + if (kv_rows) { + r = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, kv, n_stream); + ggml_set_name(r, "r"); + } + + ggml_tensor * table = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_bins, nh*gqa, nb*n_stream); + ggml_set_name(table, "table"); + + ggml_tensor * indices = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, kv, nb*n_stream); + ggml_set_name(indices, "indices"); + + ggml_tensor * out = ggml_flash_attn_ext_rows(ctx, q, k, v, m, r, 1.0f/sqrtf(hs), 0.0f, 0.0f); + if (sinks) { + ggml_tensor * s = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nh*gqa); + ggml_set_name(s, "s"); + ggml_flash_attn_ext_add_sinks(out, s); + } + ggml_flash_attn_ext_add_indexed_bias(out, table, indices); + ggml_prec_set_acc(out, GGML_PREC_F32); + ggml_set_name(out, "out"); + + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + std::mt19937 gen(0x1B1A); + + // distinct random cells per stream, some of them padding + rows.assign(kv*n_stream, -1); + if (kv_rows) { + std::vector order(2*kv); + for (int64_t s = 0; s < n_stream; ++s) { + for (int64_t i = 0; i < 2*kv; ++i) { + order[i] = i; + } + std::shuffle(order.begin(), order.end(), gen); + for (int64_t i = 0; i < kv; ++i) { + rows[s*kv + i] = i % 19 == 7 ? -1 : order[i]; + } + } + } + + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (strcmp(t->name, "r") == 0) { + ggml_backend_tensor_set(t, rows.data(), 0, rows.size()*sizeof(int32_t)); + } else if (strcmp(t->name, "m") == 0) { + std::vector f(ggml_nelements(t)); + std::uniform_real_distribution dis(-1.0f, 1.0f); + for (int64_t s = 0; s < n_stream; ++s) { + for (int64_t j = 0; j < nb; ++j) { + for (int64_t i = 0; i < kv; ++i) { + const bool pad = kv_rows && rows[s*kv + i] < 0; + const bool drop = (i + 3*j + 5*s) % 11 == 0; + f[(s*nb + j)*kv + i] = pad || drop ? -INFINITY : dis(gen); + } + } + } + std::vector h(f.size()); + ggml_fp32_to_fp16_row(f.data(), h.data(), f.size()); + ggml_backend_tensor_set(t, h.data(), 0, h.size()*sizeof(ggml_fp16_t)); + } else if (strcmp(t->name, "indices") == 0) { + std::vector idx(ggml_nelements(t)); + std::uniform_int_distribution dis(0, n_bins - 1); + for (auto & i : idx) { + i = dis(gen); + } + ggml_backend_tensor_set(t, idx.data(), 0, idx.size()*sizeof(int32_t)); + } else if (strcmp(t->name, "table") == 0) { + init_tensor_uniform(t, -4.0f, 4.0f); + } else if (strcmp(t->name, "s") == 0) { + init_tensor_uniform(t, -10.0f, 10.0f); + } else { + init_tensor_uniform(t); + } + } + } +}; + // GGML_OP_CROSS_ENTROPY_LOSS struct test_cross_entropy_loss : public test_case { const ggml_type type; @@ -13383,6 +13501,21 @@ static std::vector> make_test_cases_eval() { } } + // flash attention with an indexed bias (Inkling 2 relative-position bias) + for (bool kv_rows : {false, true}) { + for (int64_t nb : {1, 7, 65}) { + for (int64_t n_stream : {1, 2}) { + test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, nb, n_stream, 17, kv_rows)); + } + } + test_cases.emplace_back(new test_flash_attn_ext_indexed_bias( 64, 2, 3, 768, 7, 2, 17, kv_rows, false)); + test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 8, 3, 512, 65, 1, 1025, kv_rows)); + for (ggml_type type : {GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) { + test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, 1, 1, 17, kv_rows, true, type)); + test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, 7, 2, 17, kv_rows, true, type)); + } + } + // sparse mask with large batch size test_cases.emplace_back(new test_flash_attn_ext(512, 512, 1, { 8, 1}, 4096, 64, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 512)); test_cases.emplace_back(new test_flash_attn_ext(512, 512, 1, { 8, 1}, 4096, 64, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 2048)); diff --git a/tests/test-flash-attn-indexed-bias.cpp b/tests/test-flash-attn-indexed-bias.cpp deleted file mode 100644 index 048ea0264433..000000000000 --- a/tests/test-flash-attn-indexed-bias.cpp +++ /dev/null @@ -1,144 +0,0 @@ -#include "ggml-alloc.h" -#include "ggml-backend.h" -#include "ggml.h" - -#include -#include -#include -#include - -static void set_kv(ggml_tensor * t, const std::vector & data) { - std::vector bytes(ggml_nbytes(t)); - ggml_quantize_chunk(t->type, data.data(), bytes.data(), 0, ggml_nrows(t), t->ne[0], nullptr); - ggml_backend_tensor_set(t, bytes.data(), 0, bytes.size()); -} - -static void test_indexed_bias(ggml_backend_t backend, int width, bool use_rows, int n_query, int cells = 768, ggml_type kv_type = GGML_TYPE_F16) { - constexpr int heads = 6, kv_heads = 2, streams = 2, bins = 17; - const int cols = use_rows ? std::min(512, cells) : cells; - - ggml_context * ctx = ggml_init({32*ggml_tensor_overhead() + ggml_graph_overhead(), nullptr, true}); - auto * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, width, n_query, heads, streams); - auto * k = ggml_new_tensor_4d(ctx, kv_type, width, cells, kv_heads, use_rows ? 1 : streams); - auto * v = ggml_dup_tensor(ctx, k); - auto * mask = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, cols, n_query, 1, streams); - auto * rows = use_rows ? ggml_new_tensor_2d(ctx, GGML_TYPE_I32, cols, streams) : nullptr; - auto * table = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, bins, heads, n_query*streams); - auto * indices = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, cols, n_query*streams); - auto * sinks = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, heads); - auto * out = ggml_flash_attn_ext_rows(ctx, q, k, v, mask, rows, 1.0f/sqrtf(width), 0, 0); - ggml_flash_attn_ext_add_sinks(out, sinks); - const bool supports_plain = ggml_backend_supports_op(backend, out); - ggml_flash_attn_ext_add_indexed_bias(out, table, indices); - GGML_ASSERT(ggml_flash_attn_ext_has_indexed_bias(out)); - ggml_flash_attn_ext_add_indexed_bias(out, nullptr, nullptr); - GGML_ASSERT(!ggml_flash_attn_ext_has_indexed_bias(out) && !out->src[6] && !out->src[7]); - GGML_ASSERT(ggml_backend_supports_op(backend, out) == supports_plain); - ggml_flash_attn_ext_add_indexed_bias(out, table, indices); - ggml_prec_set_acc(out, GGML_PREC_F32); - - if (!ggml_backend_supports_op(backend, out)) { - ggml_free(ctx); - return; - } - - auto * graph = ggml_new_graph(ctx); - ggml_build_forward_expand(graph, out); - auto * buf = ggml_backend_alloc_ctx_tensors(ctx, backend); - GGML_ASSERT(buf); - ggml_backend_buffer_clear(buf, 0); - - std::vector row(cols*streams), idx(ggml_nelements(indices)); - std::vector visibility(idx.size()); - std::vector keys(ggml_nelements(k)), values(ggml_nelements(v)); - std::vector queries(ggml_nelements(q)); - float sink_logits[heads]; - for (int h = 0; h < heads; ++h) { - sink_logits[h] = float(2*h - 3); - } - for (size_t i = 0; i < queries.size(); i += width) { - queries[i] = 4.0f; - } - std::vector biases(ggml_nelements(table)), expected(n_query*streams*heads), output(ggml_nelements(out)); - for (int s = 0; s < v->ne[3]; ++s) { - for (int h = 0; h < kv_heads; ++h) { - for (int c = 0; c < cells; ++c) { - const float x = float((c + 3*h + 5*s) % 23 - 11)/16; - const int offset = ((s*kv_heads + h)*cells + c)*width; - std::fill_n(values.data() + offset, width, x); - keys[offset] = float((7*c + 2*h + 3*s) % 29 - 14)/4; - } - } - } - for (int s = 0; s < streams; ++s) { - for (int c = 0; c < cols; ++c) { - row[s*cols + c] = use_rows ? (c % 19 == 0 ? -1 : (13*c + 73*s) % cells) : c; - } - for (int j = 0; j < n_query; ++j) { - const int query = s*n_query + j; - for (int h = 0; h < heads; ++h) { - for (int b = 0; b < bins; ++b) { - biases[(query*heads + h)*bins + b] = float((b*(3 + h) + query) % 13 - 6)/2.9f; - } - double sum = exp(double(sink_logits[h])), weighted = 0.0; - for (int c = 0; c < cols; ++c) { - const int cell = row[s*cols + c]; - const int i = query*cols + c; - idx[i] = (c + 3*query) % bins; - const bool visible = (s != 1 || j != 0) && cell >= 0 && (c + j) % 7 != 0; - visibility[i] = ggml_fp32_to_fp16(visible ? 0.25f : -INFINITY); - if (visible) { - const int vk = (use_rows ? 0 : s)*kv_heads + h/(heads/kv_heads); - const double qk = 4.0*keys[(vk*cells + cell)*width]/sqrt(width); - const float m = 0.25f + biases[(query*heads + h)*bins + idx[i]]; - const double weight = exp(qk + ggml_fp16_to_fp32(ggml_fp32_to_fp16(m))); - weighted += weight*values[(vk*cells + cell)*width]; - sum += weight; - } - } - expected[query*heads + h] = weighted/sum; - } - } - } - ggml_backend_tensor_set(q, queries.data(), 0, ggml_nbytes(q)); - set_kv(k, keys); - set_kv(v, values); - ggml_backend_tensor_set(mask, visibility.data(), 0, ggml_nbytes(mask)); - ggml_backend_tensor_set(table, biases.data(), 0, ggml_nbytes(table)); - ggml_backend_tensor_set(sinks, sink_logits, 0, sizeof(sink_logits)); - ggml_backend_tensor_set(indices, idx.data(), 0, ggml_nbytes(indices)); - if (rows) { - ggml_backend_tensor_set(rows, row.data(), 0, ggml_nbytes(rows)); - } - GGML_ASSERT(ggml_backend_graph_compute(backend, graph) == GGML_STATUS_SUCCESS); - ggml_backend_tensor_get(out, output.data(), 0, ggml_nbytes(out)); - float max_error = 0.0f; - for (size_t i = 0; i < output.size(); ++i) { - GGML_ASSERT(std::isfinite(output[i])); - max_error = std::max(max_error, fabsf(output[i] - expected[i/width])); - } - printf("%s: width=%d, kv=%s, rows=%d, queries=%d, cells=%d, max error=%g\n", ggml_backend_name(backend), width, ggml_type_name(kv_type), use_rows, n_query, cells, max_error); - GGML_ASSERT(max_error < 0.001f); - ggml_backend_buffer_free(buf); - ggml_free(ctx); -} - -int main() { - ggml_backend_load_all(); - for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { - auto dev = ggml_backend_dev_get(i); - auto backend = ggml_backend_dev_init(dev, nullptr); - GGML_ASSERT(backend); - for (int width : {64, 128}) { - test_indexed_bias(backend, width, false, 7, 16); - test_indexed_bias(backend, width, true, 7, 16); - test_indexed_bias(backend, width, false, 1, 768, GGML_TYPE_Q4_0); - test_indexed_bias(backend, width, true, 1, 768, GGML_TYPE_Q4_0); - for (int n_query : {1, 7, 65}) { - test_indexed_bias(backend, width, false, n_query); - test_indexed_bias(backend, width, true, n_query); - } - } - ggml_backend_free(backend); - } -} From d2bceda3de6d61429b885f4f012bc983c6dcfd50 Mon Sep 17 00:00:00 2001 From: "Max S." Date: Mon, 23 Nov 2026 01:52:33 +0700 Subject: [PATCH 19/24] vocab: enable ignore_merges for inkling2 (#32799) --- src/llama-vocab.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp index f3e1d0192414..20357e8ef192 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -2673,6 +2673,7 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { pre_type = LLAMA_VOCAB_PRE_TYPE_GPT4O; special_bos_id = LLAMA_TOKEN_NULL; clean_spaces = false; + ignore_merges = true; } else if ( tokenizer_pre == "granite-embed-multi-97m") { pre_type = LLAMA_VOCAB_PRE_TYPE_GRANITE_EMB_MULTI; From 5bacb7c868a2bc98682de15f447fc1ce17c9c49c Mon Sep 17 00:00:00 2001 From: "Piotr Wilkin (ilintar)" Date: Sun, 22 Nov 2026 20:04:21 +0100 Subject: [PATCH 20/24] llama : copy all experts of a host weight shared by several nodes (#32807) * llama : copy all experts of a host weight shared by several nodes The scheduler copies a host weight to the device once per graph, so a partial expert copy made for the first MUL_MAT_ID is stale for the others (e.g. the shared layers of inkling2_loop with --n-cpu-moe). Assisted-by: Claude Opus 5.5 * llama : copy all experts of a host weight shared by several nodes Assisted-by: Codex --- src/llama-context.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 7490cf3794d7..07a0dbafc17e 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -3143,6 +3143,12 @@ bool llama_context::sched_copy_experts(ggml_backend_t backend, const ggml_tensor return false; } + // Later loop passes can select different experts from the same device copy. + // TODO: copy only the experts needed by each pass (see #32807 and #32809). + if (lctx->model.arch == LLM_ARCH_INKLING2_LOOP) { + return false; + } + const ggml_tensor * ids = node->src[2]; if (ggml_nelements(ids) == 0) { return true; From 2d2e833532aa1e997c5f0e91649a5dc65c9d317c Mon Sep 17 00:00:00 2001 From: rafasmour <54501936+rafasmour@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:43:56 +0000 Subject: [PATCH 21/24] CUDA/HIP: indexed bias in the vec and tile flash attention kernels, use it for Inkling 2 Assisted-by: Claude Opus 5.5 --- ggml/src/ggml-cuda/fattn-common.cuh | 34 +++++++++- ggml/src/ggml-cuda/fattn-mma-f16.cuh | 4 +- ggml/src/ggml-cuda/fattn-tile.cuh | 33 ++++++---- ggml/src/ggml-cuda/fattn-vec.cuh | 14 +++-- ggml/src/ggml-cuda/fattn.cu | 15 +++-- src/llama-graph.cpp | 92 +++++++++++++++++----------- src/llama-graph.h | 17 ++++- src/models/inkling2.cpp | 3 +- 8 files changed, 149 insertions(+), 63 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh index 6665180d8b11..a6261c7b058f 100644 --- a/ggml/src/ggml-cuda/fattn-common.cuh +++ b/ggml/src/ggml-cuda/fattn-common.cuh @@ -19,6 +19,25 @@ // The macro on the following line shifts it by a factor of 2**3=8, as was needed to fix https://github.com/ggml-org/llama.cpp/issues/18606 . #define FATTN_KQ_MAX_OFFSET (3.0f*0.6931f) +// optional bias added to the mask: table[indices[query, key], head, query], see ggml_flash_attn_ext_add_indexed_bias +// table is offset to the first query of the sequence and to the first head of the block +struct fattn_indexed_bias { + const float * table; + const int32_t * indices; + int32_t n_bins; + int32_t n_keys; + int32_t n_head; + + __device__ __forceinline__ fattn_indexed_bias offset(const int64_t query, const int head) const { + return {table + (query*n_head + head)*n_bins, indices + query*n_keys, n_bins, n_keys, n_head}; + } + + __device__ __forceinline__ float get(const int query, const int head, const int key) const { + const int bin = indices[int64_t(query)*n_keys + key]; + return uint32_t(bin) < uint32_t(n_bins) ? table[(int64_t(query)*n_head + head)*n_bins + bin] : 0.0f; + } +}; + typedef void (* fattn_kernel_t)( const char * __restrict__ Q, const char * __restrict__ K, @@ -41,7 +60,8 @@ typedef void (* fattn_kernel_t)( const int32_t nb11, const int32_t nb12, const int64_t nb13, const int32_t nb21, const int32_t nb22, const int64_t nb23, const int32_t ne31, const int32_t ne32, const int32_t ne33, - const int32_t nb31, const int64_t nb32, const int64_t nb33); + const int32_t nb31, const int64_t nb32, const int64_t nb33, + const fattn_indexed_bias bias); typedef float (*vec_dot_KQ_t)( const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8 , const void * __restrict__ Q_ds); @@ -1067,6 +1087,10 @@ void launch_fattn( const ggml_tensor * sinks = dst->src[4]; const ggml_tensor * kv_rows = dst->src[5]; + const ggml_tensor * bias_table = dst->src[6]; + const ggml_tensor * bias_indices = dst->src[7]; + GGML_ASSERT(!bias_table || (!use_sparse && ncols2 == 1 && mask && mask->ne[2] == 1)); + // with kv_rows the kernel iterates over the mask columns and reads K/V rows through kv_rows const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : K->ne[1]; GGML_ASSERT(!kv_rows || !use_sparse); @@ -1345,7 +1369,13 @@ void launch_fattn( K->ne[0], n_kv, K->ne[2], K->ne[3], nb11, nb12, nb13, nb21, nb22, nb23, mask ? mask->ne[1] : 0, mask ? mask->ne[2] : 0, mask ? mask->ne[3] : 0, - mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0 + mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0, + fattn_indexed_bias{ + bias_table ? (const float *) bias_table->data : nullptr, + bias_indices ? (const int32_t *) bias_indices->data : nullptr, + bias_table ? (int32_t) bias_table->ne[0] : 0, + bias_indices ? (int32_t) bias_indices->ne[0] : 0, + (int32_t) Q->ne[2]} ); CUDA_CHECK(cudaGetLastError()); diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh index 5b4ae88d9f5f..d7f9a57c00d0 100644 --- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh +++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh @@ -2086,7 +2086,9 @@ static __global__ void flash_attn_ext_f16( const int32_t nb11, const int32_t nb12, const int64_t nb13, const int32_t nb21, const int32_t nb22, const int64_t nb23, const int32_t ne31, const int32_t ne32, const int32_t ne33, - const int32_t nb31, const int64_t nb32, const int64_t nb33) { + const int32_t nb31, const int64_t nb32, const int64_t nb33, + const fattn_indexed_bias bias) { + GGML_UNUSED(bias); ggml_cuda_pdl_sync(); // TODO optimize placement #if defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE)) const char * GGML_CUDA_RESTRICT Q = Q_ptr; diff --git a/ggml/src/ggml-cuda/fattn-tile.cuh b/ggml/src/ggml-cuda/fattn-tile.cuh index 35c0d40aa105..6ac241198ace 100644 --- a/ggml/src/ggml-cuda/fattn-tile.cuh +++ b/ggml/src/ggml-cuda/fattn-tile.cuh @@ -388,7 +388,8 @@ static inline bool ggml_cuda_fattn_tile_direct_kv(const int cc, const ggml_tenso float logit_softcap = 0.0f; memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float)); - if (!GGML_CUDA_CC_IS_RDNA3_0(cc) || (K->ne[0] != 256 && K->ne[0] != 512) || V->ne[0] != K->ne[0] || logit_softcap != 0.0f) { + if (!GGML_CUDA_CC_IS_RDNA3_0(cc) || (K->ne[0] != 256 && K->ne[0] != 512) || V->ne[0] != K->ne[0] || logit_softcap != 0.0f || + ggml_flash_attn_ext_has_indexed_bias(dst)) { return false; } @@ -662,7 +663,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter( const int k_VKQ_0, const int k_VKQ_max, const int col_Q_0, - const int32_t * const __restrict__ rows) { + const int32_t * const __restrict__ rows, + const fattn_indexed_bias bias) { constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); constexpr int cpy_ne = cpy_nb / 4; @@ -723,8 +725,13 @@ static __device__ __forceinline__ void flash_attn_tile_iter( } if (!oob_check || i_KQ < k_VKQ_sup) { - KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] += (ncols2 > 1 || mask) ? - slope*__half2float(mask[j*stride_mask + k_VKQ_0 + i_KQ]) : 0.0f; + if (ncols2 > 1 || mask) { + float m = __half2float(mask[j*stride_mask + k_VKQ_0 + i_KQ]); + if (bias.table) { + m += bias.get(j, 0, k_VKQ_0 + i_KQ); + } + KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] += slope*m; + } KQ_max_new[jc0] = fmaxf(KQ_max_new[jc0], KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] + FATTN_KQ_MAX_OFFSET); } @@ -901,7 +908,8 @@ static __global__ void flash_attn_tile( const int32_t nb11, const int32_t nb12, const int64_t nb13, const int32_t nb21, const int32_t nb22, const int64_t nb23, const int32_t ne31, const int32_t ne32, const int32_t ne33, - const int32_t nb31, const int64_t nb32, const int64_t nb33) { + const int32_t nb31, const int64_t nb32, const int64_t nb33, + const fattn_indexed_bias bias) { #ifdef FLASH_ATTN_AVAILABLE const char * GGML_CUDA_RESTRICT Q = Q_ptr; const char * GGML_CUDA_RESTRICT K = K_ptr; @@ -931,7 +939,7 @@ static __global__ void flash_attn_tile( nb11, nb12, nb13, nb21, nb22, nb23, ne31, ne32, ne33, - nb31, nb32, nb33); + nb31, nb32, nb33, bias); NO_DEVICE_CODE; return; } @@ -956,6 +964,7 @@ static __global__ void flash_attn_tile( const half2 * V_h2 = (const half2 *) (V + nb23*sequence + nb22*(head0 / gqa_ratio)); // K and V have same shape const half * maskh = mask ? (const half *) (mask + nb33*(sequence % ne33) + nb32*(head0 % ne32)) : nullptr; + const fattn_indexed_bias head_bias = bias.table ? bias.offset(int64_t(sequence)*ne01.z, head0) : bias; // K/V rows of this sequence, one per mask column const int32_t * rows = nullptr; @@ -1063,14 +1072,14 @@ static __global__ void flash_attn_tile( constexpr bool oob_check = false; flash_attn_tile_iter (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, - stride_K, stride_V, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, rows); + stride_K, stride_V, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, rows, head_bias); k_VKQ_0 += gridDim.y*nbatch_fa; } if (k_VKQ_0 < k_VKQ_max) { constexpr bool oob_check = true; flash_attn_tile_iter (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, - stride_K, stride_V, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, rows); + stride_K, stride_V, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, rows, head_bias); } } else { // Branch without out-of-bounds checks. @@ -1078,7 +1087,7 @@ static __global__ void flash_attn_tile( constexpr bool oob_check = false; flash_attn_tile_iter (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, - stride_K, stride_V, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, rows); + stride_K, stride_V, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, rows, head_bias); } } @@ -1244,7 +1253,7 @@ static __global__ void flash_attn_tile( nb11, nb12, nb13, nb21, nb22, nb23, ne31, ne32, ne33, - nb31, nb32, nb33); + nb31, nb32, nb33, bias); NO_DEVICE_CODE; #endif // FLASH_ATTN_AVAILABLE } @@ -1369,7 +1378,9 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm // with kv_rows the kernel iterates over the mask columns const int64_t n_kv = dst->src[5] ? dst->src[5]->ne[0] : K->ne[1]; // a mask with a head dimension is not shared by the Q heads of a K/V head - const bool use_gqa_opt = mask && mask->ne[2] == 1 && max_bias == 0.0f && Q->ne[1] <= gqa_limit && n_kv % FATTN_KQ_STRIDE == 0; + // the indexed bias is per Q head + const bool use_gqa_opt = mask && mask->ne[2] == 1 && max_bias == 0.0f && Q->ne[1] <= gqa_limit && n_kv % FATTN_KQ_STRIDE == 0 && + !ggml_flash_attn_ext_has_indexed_bias(dst); if constexpr (DKQ == 320) { // This branch is only used for Mistral Small 4 which has a GQA ratio of 32. diff --git a/ggml/src/ggml-cuda/fattn-vec.cuh b/ggml/src/ggml-cuda/fattn-vec.cuh index 7b1854216375..a2c19746f1ea 100644 --- a/ggml/src/ggml-cuda/fattn-vec.cuh +++ b/ggml/src/ggml-cuda/fattn-vec.cuh @@ -41,7 +41,8 @@ static __global__ void flash_attn_ext_vec( const int32_t nb11, const int32_t nb12, const int64_t nb13, const int32_t nb21, const int32_t nb22, const int64_t nb23, const int32_t ne31, const int32_t ne32, const int32_t ne33, - const int32_t nb31, const int64_t nb32, const int64_t nb33) { + const int32_t nb31, const int64_t nb32, const int64_t nb33, + const fattn_indexed_bias bias) { ggml_cuda_pdl_lc(); #ifdef FLASH_ATTN_AVAILABLE const char * GGML_CUDA_RESTRICT Q = Q_ptr; @@ -64,7 +65,7 @@ static __global__ void flash_attn_ext_vec( nb11, nb12, nb13, nb21, nb22, nb23, ne31, ne32, ne33, - nb31, nb32, nb33); + nb31, nb32, nb33, bias); NO_DEVICE_CODE; return; } @@ -122,6 +123,7 @@ static __global__ void flash_attn_ext_vec( const char * V0 = V; const half * maskh = mask ? (const half *) (mask + nb33*(sequence % ne33) + nb32*(head % ne32) + nb31*ic0) : nullptr; + const fattn_indexed_bias head_bias = bias.table ? bias.offset(int64_t(sequence)*ne01.z + ic0, head) : bias; const float slope = get_alibi_slope(max_bias, head, n_head_log2, m0, m1); @@ -312,7 +314,11 @@ static __global__ void flash_attn_ext_vec( } if (mask && (ncols == 1 || ic0 + j < int(ne01.z))) { - sum += slope*__half2float(maskh[j*ne11 + i_KQ]); + float m = __half2float(maskh[j*ne11 + i_KQ]); + if (head_bias.table) { + m += head_bias.get(j, 0, k_VKQ_0 + i_KQ); + } + sum += slope*m; } KQ_max_new[j] = fmaxf(KQ_max_new[j], sum + FATTN_KQ_MAX_OFFSET); @@ -557,7 +563,7 @@ static __global__ void flash_attn_ext_vec( nb11, nb12, nb13, nb21, nb22, nb23, ne31, ne32, ne33, - nb31, nb32, nb33); + nb31, nb32, nb33, bias); NO_DEVICE_CODE; #endif // FLASH_ATTN_AVAILABLE } diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index e71a54d6e42b..31d51f236005 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -582,10 +582,6 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const return BEST_FATTN_KERNEL_NONE; #endif// FLASH_ATTN_AVAILABLE - if (ggml_flash_attn_ext_has_indexed_bias(dst)) { - return BEST_FATTN_KERNEL_NONE; - } - const ggml_tensor * KQV = dst; const ggml_tensor * Q = dst->src[0]; const ggml_tensor * K = dst->src[1]; @@ -691,7 +687,8 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const const bool kv_rows_rdna3 = kv_rows && amd_wmma_available(cc) && GGML_CUDA_CC_IS_RDNA3_0(cc) && mask && K->type == GGML_TYPE_F16 && V->type == GGML_TYPE_F16; if (kv_rows && !kv_rows_rdna3) { - return GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && mask && Q->ne[0] != 40 && Q->ne[0] != 72 ? + return GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && mask && Q->ne[0] != 40 && Q->ne[0] != 72 && + !ggml_flash_attn_ext_has_indexed_bias(dst) ? BEST_FATTN_KERNEL_MMA_F16 : BEST_FATTN_KERNEL_NONE; } @@ -699,6 +696,14 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const // 192 satisfies % 64 == 0 but has no vec instance (DKQ != DV); force it onto the MMA path. const bool can_use_vector_kernel = Q->ne[0] <= 256 && Q->ne[0] % 64 == 0 && Q->ne[0] != 192 && n_kv % FATTN_KQ_STRIDE == 0; + // only the vec kernel and the tile kernel without the GQA optimization add the indexed bias + if (ggml_flash_attn_ext_has_indexed_bias(dst)) { + if ((Q->ne[0] != 64 && Q->ne[0] != 128 && Q->ne[0] != 256) || V->ne[0] != Q->ne[0]) { + return BEST_FATTN_KERNEL_NONE; + } + return Q->ne[1] <= 2 && can_use_vector_kernel ? BEST_FATTN_KERNEL_VEC : BEST_FATTN_KERNEL_TILE; + } + // If Turing tensor cores are available, use them: if (turing_mma_available(cc)) { if (can_use_vector_kernel) { diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 0b4abbbaca02..e6a4d9e7dc25 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -3129,7 +3129,8 @@ ggml_tensor * llm_graph_context::build_attn_mha( ggml_tensor * v_mla, int64_t n_kv_max, float kq_scale, - int il) const { + int il, + const llm_graph_rel_bias * rel_bias) const { const bool v_trans = v->nb[1] > v->nb[2]; // split the batch into streams if needed @@ -3178,6 +3179,16 @@ ggml_tensor * llm_graph_context::build_attn_mha( ggml_flash_attn_ext_set_n_kv_max(cur, static_cast(n_kv_max)); ggml_prec_set_acc(cur, GGML_PREC_F32); + if (rel_bias) { + GGML_ASSERT(kv_rows == nullptr); + ggml_flash_attn_ext_add_indexed_bias(cur, rel_bias->table, rel_bias->indices); + ggml_backend_dev_t dev = model.dev_layer(il); + if (!cparams.offload_kqv || !dev || !ggml_backend_dev_supports_op(dev, cur)) { + ggml_flash_attn_ext_add_indexed_bias(cur, nullptr, nullptr); + cur->src[3] = build_attn_rel_mask(kq_mask, *rel_bias, il); + } + } + if (v_mla) { #if 0 // v_mla can be applied as a matrix-vector multiplication with broadcasting across dimension 3 == n_tokens. @@ -3197,6 +3208,10 @@ ggml_tensor * llm_graph_context::build_attn_mha( cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]); } else { + if (rel_bias) { + kq_mask = build_attn_rel_mask(kq_mask, *rel_bias, il); + } + ggml_tensor * kq = ggml_mul_mat(ctx0, k, q); cb(kq, "kq", il); @@ -3706,7 +3721,8 @@ static ggml_tensor * build_attn_iswa_impl( ggml_tensor * sinks, ggml_tensor * v_mla, float kq_scale, - int il) { + int il, + const llm_graph_rel_bias * rel_bias = nullptr) { ggml_context * ctx0 = gctx.ctx0; ggml_cgraph * gf = gctx.gf; @@ -3773,7 +3789,7 @@ static ggml_tensor * build_attn_iswa_impl( ggml_tensor * k = use_kv_cur ? k_cur : mctx_cur->get_k(ctx0, il); ggml_tensor * v = use_kv_cur ? v_cur : mctx_cur->get_v(ctx0, il); - ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il); + ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il, rel_bias); cur = build_attn_scale_kv_output(ctx0, mctx_cur, cur, il); gctx.cb(cur, "kqv_out", il); @@ -4435,47 +4451,27 @@ llm_graph_input_mem_hybrid_iswa_rel * llm_graph_context::build_inp_mem_hybrid_is return (llm_graph_input_mem_hybrid_iswa_rel *) res->add_input(std::move(inp)); } -ggml_tensor * llm_graph_context::build_attn( - llm_graph_input_mem_hybrid_iswa_rel * inp, - ggml_tensor * wo, - ggml_tensor * wo_b, - ggml_tensor * wo_s, - ggml_tensor * q_cur, - ggml_tensor * k_cur, - ggml_tensor * v_cur, - ggml_tensor * rel_bias, - ggml_tensor * sinks, - float kq_scale, - int il) const { - const bool is_swa = hparams.is_swa(il); - - auto * inp_attn = inp->get_attn(); - - const auto & attn_mask = is_swa ? inp_attn->self_attn_mask_swa : inp_attn->self_attn_mask; - - // TODO: support kv_rows - fill the distances over the kv_rows cell lists and pass the rows to build_attn_mha, - // needs a kv_rows flash attention with a per-head mask (CUDA has none) - GGML_ASSERT(attn_mask.rows == nullptr); - - ggml_tensor * mask = attn_mask.raw; // [n_kv, n_tps, 1, n_stream] - ggml_tensor * rel_pos = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; // [n_kv, n_tokens] +ggml_tensor * llm_graph_context::build_attn_rel_mask(ggml_tensor * mask, const llm_graph_rel_bias & rel_bias, int il) const { + // [n_bins, n_head, n_tokens] -> [n_head, n_bins, n_tokens] + ggml_tensor * table = ggml_cont(ctx0, ggml_permute(ctx0, rel_bias.table, 1, 0, 2, 3)); + ggml_tensor * rel_pos = rel_bias.indices; // [n_kv, n_tokens] const int64_t n_kv = mask->ne[0]; const int64_t n_tps = mask->ne[1]; const int64_t n_stream = mask->ne[3]; - const int64_t n_head = rel_bias->ne[0]; - const int64_t n_bucket = rel_bias->ne[1]; + const int64_t n_head = table->ne[0]; + const int64_t n_bucket = table->ne[1]; // a mask per head, in the dense layout of the input mask and of its type (F16 for flash attention) ggml_tensor * kq_mask = nullptr; // the bias of all rows at once is n_kv x n_tokens x n_head in F32, which does not fit at long context: // the full-attention layers write the mask a few query rows at a time, at most 32 chunks - const int64_t n_rows = is_swa ? n_tps : std::max(32, (n_tps + 31)/32); + const int64_t n_rows = hparams.is_swa(il) ? n_tps : std::max(32, (n_tps + 31)/32); if (n_rows >= n_tps) { // [n_head, n_kv, n_tokens] -> [n_kv, n_tps, n_head, n_stream] - ggml_tensor * kq_b = ggml_get_rows(ctx0, rel_bias, rel_pos); + ggml_tensor * kq_b = ggml_get_rows(ctx0, table, rel_pos); kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, n_tps, n_stream); kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); @@ -4492,8 +4488,8 @@ ggml_tensor * llm_graph_context::build_attn( for (int64_t i0 = 0; i0 < n_tps; i0 += n_rows) { const int64_t n = std::min(n_rows, n_tps - i0); - ggml_tensor * bias = ggml_view_4d(ctx0, rel_bias, n_head, n_bucket, n, n_stream, - rel_bias->nb[1], rel_bias->nb[2], n_tps*rel_bias->nb[2], i0*rel_bias->nb[2]); + ggml_tensor * bias = ggml_view_4d(ctx0, table, n_head, n_bucket, n, n_stream, + table->nb[1], table->nb[2], n_tps*table->nb[2], i0*table->nb[2]); ggml_tensor * pos = ggml_view_3d(ctx0, rel_pos, n_kv, n, n_stream, rel_pos->nb[1], n_tps*rel_pos->nb[1], i0*rel_pos->nb[1]); // the KQ mask of these rows from the first head, not written yet, broadcast over the heads @@ -4505,7 +4501,7 @@ ggml_tensor * llm_graph_context::build_attn( cur = ggml_cont(ctx0, ggml_permute(ctx0, cur, 2, 0, 1, 3)); cur = ggml_add(ctx0, cur, rows->type == GGML_TYPE_F32 ? rows : ggml_cast(ctx0, rows, GGML_TYPE_F32)); - kq_mask = ggml_set_rows(ctx0, kq_mask, cur, ggml_view_1d(ctx0, inp->self_rows, n, i0*ggml_element_size(inp->self_rows))); + kq_mask = ggml_set_rows(ctx0, kq_mask, cur, ggml_view_1d(ctx0, rel_bias.rows, n, i0*ggml_element_size(rel_bias.rows))); // add the chunks in order, otherwise the graph computes all of them before the first write ggml_build_forward_expand(gf, kq_mask); @@ -4513,7 +4509,33 @@ ggml_tensor * llm_graph_context::build_attn( } cb(kq_mask, "kq_mask_rel_pos", il); - return build_attn_iswa_impl(*this, inp_attn, wo, wo_b, wo_s, q_cur, k_cur, v_cur, nullptr, kq_mask, nullptr, sinks, nullptr, kq_scale, il); + return kq_mask; +} + +ggml_tensor * llm_graph_context::build_attn( + llm_graph_input_mem_hybrid_iswa_rel * inp, + ggml_tensor * wo, + ggml_tensor * wo_b, + ggml_tensor * wo_s, + ggml_tensor * q_cur, + ggml_tensor * k_cur, + ggml_tensor * v_cur, + ggml_tensor * rel_bias, + ggml_tensor * sinks, + float kq_scale, + int il) const { + const bool is_swa = hparams.is_swa(il); + + auto * inp_attn = inp->get_attn(); + + const auto & attn_mask = is_swa ? inp_attn->self_attn_mask_swa : inp_attn->self_attn_mask; + + // TODO: support kv_rows - fill the distances over the kv_rows cell lists and pass the rows to build_attn_mha + GGML_ASSERT(attn_mask.rows == nullptr); + + const llm_graph_rel_bias bias = { rel_bias, is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos, inp->self_rows }; + + return build_attn_iswa_impl(*this, inp_attn, wo, wo_b, wo_s, q_cur, k_cur, v_cur, nullptr, attn_mask.raw, nullptr, sinks, nullptr, kq_scale, il, &bias); } void llm_graph_context::build_dense_out( diff --git a/src/llama-graph.h b/src/llama-graph.h index 2bf74c1c6771..da69953df397 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -1095,6 +1095,13 @@ struct llm_graph_amax_src1 { ggml_tensor * scale_s; // scale to undo on the matmul result, or nullptr }; +// relative-position bias of llm_graph_input_mem_hybrid_iswa_rel: table[indices[key, query], head, query] is added to the KQ mask +struct llm_graph_rel_bias { + ggml_tensor * table; // [n_bins, n_head_q, n_tokens], F32 + ggml_tensor * indices; // [n_kv, n_tokens], I32 + ggml_tensor * rows; // [n_tokens], I32, row indices for the chunked dense mask +}; + struct llm_graph_context { const llama_model & model; @@ -1349,7 +1356,11 @@ struct llm_graph_context { ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v] int64_t n_kv_max, float kq_scale, - int il) const; + int il, + const llm_graph_rel_bias * rel_bias = nullptr) const; + + // the dense KQ mask with the relative-position bias added, for the backends without the indexed bias in flash attention + ggml_tensor * build_attn_rel_mask(ggml_tensor * kq_mask, const llm_graph_rel_bias & rel_bias, int il) const; llm_graph_input_attn_no_cache * build_attn_inp_no_cache() const; @@ -1555,7 +1566,7 @@ struct llm_graph_context { uint32_t extent_swa) const; // rel_bias holds the bias of each query and head by distance bucket, it is gathered by the distance to - // each cell and added to the KQ mask, after the KQ scale + // each cell and added to the KQ mask, after the KQ scale. flash attention gathers it itself where the backend can ggml_tensor * build_attn( llm_graph_input_mem_hybrid_iswa_rel * inp, ggml_tensor * wo, @@ -1564,7 +1575,7 @@ struct llm_graph_context { ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens] ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] - ggml_tensor * rel_bias, // [n_head_q, extent + 1, n_tokens] + ggml_tensor * rel_bias, // [extent + 1, n_head_q, n_tokens] ggml_tensor * sinks, // [n_head_q] float kq_scale, int il) const; diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 5ba058fb05ba..bd749bea17b9 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -349,13 +349,12 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens ggml_tensor * sinks = build_lora_mm(layer.attn_sink_proj, inputs[0]); - // project r on the bias table, the attention gathers it by distance: [n_head, extent + 1, n_tokens] + // project r on the bias table, the attention gathers it by distance: [extent + 1, n_head, n_tokens] // the last bucket is a zero pad, for the cells that are farther than the extent ggml_tensor * table = ggml_mul_mat(ctx0, ggml_pad(ctx0, layer.attn_rel_bias, 0, 1, 0, 0), Rcur); // the sink logit t is per query: exp(s - t)/(1 + sum(exp(s - t))) = exp(s)/(exp(t) + sum(exp(s))), with a zero sink table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks, 1, n_head, n_tokens)); - table = ggml_cont(ctx0, ggml_permute(ctx0, table, 1, 0, 2, 3)); cb(table, "rel_bias", il); sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); From 977a600c1edb3b4fa0e239133e268b22b0ee9272 Mon Sep 17 00:00:00 2001 From: rafasmour <54501936+rafasmour@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:43:56 +0000 Subject: [PATCH 22/24] CUDA: fuse the l2 clip, tanh gate and add + scale chains of Inkling 2 Assisted-by: Claude Opus 5.5 --- ggml/src/ggml-cuda/ggml-cuda.cu | 51 +++++++++++++ ggml/src/ggml-cuda/norm.cu | 88 ++++++++++++++++++++++ ggml/src/ggml-cuda/norm.cuh | 5 ++ ggml/src/ggml-cuda/scale.cu | 29 ++++++++ ggml/src/ggml-cuda/scale.cuh | 4 + ggml/src/ggml-cuda/unary.cu | 28 +++++++ ggml/src/ggml-cuda/unary.cuh | 5 ++ tests/test-backend-ops.cpp | 125 ++++++++++++++++++++++++++++++++ 8 files changed, 335 insertions(+) diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 98dace11aacf..154fd760aa7a 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -5763,6 +5763,57 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph } } + // clip of the row l2 norms, optionally after a MUL: [MUL] SQR SUM_ROWS SQRT SCALE FILL DIV CLAMP MUL + if (node->op == GGML_OP_MUL || node->op == GGML_OP_SQR) { + static const ggml_op clip_ops[] = { GGML_OP_MUL, GGML_OP_SQR, GGML_OP_SUM_ROWS, GGML_OP_SQRT, GGML_OP_SCALE, + GGML_OP_FILL, GGML_OP_DIV, GGML_OP_CLAMP, GGML_OP_MUL }; + const int n_ops = node->op == GGML_OP_MUL ? 9 : 8; + const int j = i + n_ops - 8; // the SQR + const int outputs[] = { i + n_ops - 1 }; + if (ggml_can_fuse_subgraph(cgraph, i, n_ops, clip_ops + 9 - n_ops, outputs, 1) && + ggml_check_edges(cgraph, j, {{1, 0, 0}, {2, 0, 1}, {3, 0, 2}, {4, 0, 3}, {5, 0, 4}, {5, 1, 3}, {6, 0, 5}, {7, 1, 6}})) { + ggml_tensor * const * nd = cgraph->nodes + j; + const ggml_tensor * y = nd[0]->src[0]; + const ggml_tensor * x = n_ops == 9 ? node->src[0] : y; + const ggml_tensor * scale = n_ops == 9 ? node->src[1] : nullptr; + if ((n_ops == 8 || y == node) && nd[7]->src[0] == y && ggml_are_same_shape(y, x) && + ggml_cuda_should_fuse_l2_clip(x, scale, nd[7]) && + ggml_cuda_check_fusion_memory_ranges(cgraph, i, n_ops, outputs, 1)) { + ggml_cuda_op_l2_clip_fused(*cuda_ctx, x, scale, nd[3], nd[4], nd[6], nd[7]); + return n_ops - 1; + } + } + } + + // gate: (cur - tanh(f)*cur) + tanh(g)*msg + if (node->op == GGML_OP_UNARY && ggml_get_unary_op(node) == GGML_UNARY_OP_TANH) { + const ggml_op ops[] = { GGML_OP_UNARY, GGML_OP_MUL, GGML_OP_SUB, GGML_OP_UNARY, GGML_OP_MUL, GGML_OP_ADD }; + const int outputs[] = { i + 5 }; + if (ggml_can_fuse_subgraph(cgraph, i, 6, ops, outputs, 1) && + ggml_get_unary_op(cgraph->nodes[i + 3]) == GGML_UNARY_OP_TANH && + ggml_check_edges(cgraph, i, {{1, 0, 0}, {2, 1, 1}, {4, 0, 3}, {5, 0, 2}, {5, 1, 4}}) && + cgraph->nodes[i + 2]->src[0] == cgraph->nodes[i + 1]->src[1]) { + const ggml_tensor * cur = cgraph->nodes[i + 1]->src[1]; + const ggml_tensor * msg = cgraph->nodes[i + 4]->src[1]; + if (ggml_cuda_should_fuse_tanh_gate(cur, node->src[0], cgraph->nodes[i + 3]->src[0], msg, cgraph->nodes[i + 5]) && + ggml_cuda_check_fusion_memory_ranges(cgraph, i, 6, outputs, 1)) { + ggml_cuda_op_tanh_gate_fused(*cuda_ctx, cur, node->src[0], cgraph->nodes[i + 3]->src[0], msg, cgraph->nodes[i + 5]); + return 5; + } + } + } + + if (node->op == GGML_OP_ADD && i + 1 < cgraph->n_nodes && cgraph->nodes[i + 1]->op == GGML_OP_SCALE) { + const ggml_op ops[] = { GGML_OP_ADD, GGML_OP_SCALE }; + const int outputs[] = { i + 1 }; + if (ggml_can_fuse_subgraph(cgraph, i, 2, ops, outputs, 1) && cgraph->nodes[i + 1]->src[0] == node && + ggml_cuda_should_fuse_add_scale(node, cgraph->nodes[i + 1]) && + ggml_cuda_check_fusion_memory_ranges(cgraph, i, 2, outputs, 1)) { + ggml_cuda_op_add_scale_fused(*cuda_ctx, node, cgraph->nodes[i + 1]); + return 1; + } + } + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, {})) { ggml_cuda_op_rms_norm_mul_rope_fused(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2], cgraph->nodes[i + 4]); return 4; diff --git a/ggml/src/ggml-cuda/norm.cu b/ggml/src/ggml-cuda/norm.cu index f4866713c6d6..ce9cdc76e06e 100644 --- a/ggml/src/ggml-cuda/norm.cu +++ b/ggml/src/ggml-cuda/norm.cu @@ -450,6 +450,50 @@ static __global__ void l2_norm_f32( } } +// the clip of l2 norms as one kernel: y = x*s, dst = y*clamp(c/(sqrt(sum(y*y))*a + b), lo, hi) +// s is optional and is broadcast over the rows, channels and samples of x +template +static __global__ void l2_clip_f32( + const float * x, const float * s, float * dst, const int ncols, const int nchannels, const int nsamples, + const int64_t stride_row, const int64_t stride_channel, const int64_t stride_sample, + const int s_nrows, const int s_nchannels, const int s_nsamples, + const float a, const float b, const float c, const float lo, const float hi) { + const int nrows = gridDim.x; + const int row = blockIdx.x; + const int tid = threadIdx.x; + + extern __shared__ float s_sum[]; + + ggml_cuda_pdl_sync(); + + for (int sample = blockIdx.z; sample < nsamples; sample += gridDim.z) { + for (int channel = blockIdx.y; channel < nchannels; channel += gridDim.y) { + const float * xc = x + sample*stride_sample + channel*stride_channel + row*stride_row; + float * dstc = dst + ((int64_t(sample)*nchannels + channel)*nrows + row)*ncols; + const float * sc = s ? s + ((int64_t(sample % s_nsamples)*s_nchannels + channel % s_nchannels)*s_nrows + row % s_nrows)*ncols : nullptr; + + float tmp = 0.0f; + for (int col = tid; col < ncols; col += block_size) { + const float yi = sc ? xc[col]*sc[col] : xc[col]; + tmp += yi * yi; + } + + tmp = block_reduce(tmp, s_sum); + + const float factor = fminf(fmaxf(c / (sqrtf(tmp)*a + b), lo), hi); + + for (int col = tid; col < ncols; col += block_size) { + const float yi = sc ? xc[col]*sc[col] : xc[col]; + dstc[col] = yi * factor; + } + + if constexpr (block_size > WARP_SIZE) { + __syncthreads(); + } + } + } +} + template static void norm_f32_cuda(const float * x, float * dst, @@ -720,6 +764,25 @@ static void l2_norm_f32_cuda( } } +static void l2_clip_f32_cuda( + const float * x, const float * s, float * dst, const int ncols, const int nrows, const int nchannels, const int nsamples, + const int64_t stride_row, const int64_t stride_channel, const int64_t stride_sample, + const int s_nrows, const int s_nchannels, const int s_nsamples, + const float a, const float b, const float c, const float lo, const float hi, cudaStream_t stream) { + const dim3 blocks_num(nrows, MIN(nchannels, UINT16_MAX), MIN(nsamples, UINT16_MAX)); + if (ncols < 1024) { + const dim3 block_dims(WARP_SIZE, 1, 1); + const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params{blocks_num, block_dims, 0, stream}; + ggml_cuda_kernel_launch(l2_clip_f32, launch_params, x, s, dst, ncols, nchannels, nsamples, stride_row, stride_channel, stride_sample, + s_nrows, s_nchannels, s_nsamples, a, b, c, lo, hi); + } else { + const dim3 block_dims(1024, 1, 1); + const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params{blocks_num, block_dims, 32 * sizeof(float), stream}; + ggml_cuda_kernel_launch(l2_clip_f32<1024>, launch_params, x, s, dst, ncols, nchannels, nsamples, stride_row, stride_channel, stride_sample, + s_nrows, s_nchannels, s_nsamples, a, b, c, lo, hi); + } +} + void ggml_cuda_op_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst, ggml_tensor * mul, ggml_tensor * add) { const ggml_tensor * src0 = dst->src[0]; const float * src0_d = (const float *) src0->data; @@ -1071,3 +1134,28 @@ void ggml_cuda_op_l2_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { l2_norm_f32_cuda(src0_d, dst_d, ne00, ne01, ne02, ne03, s01, s02, s03, eps, stream); } + +// x: the input of SQR, scale: the factor of the MUL before it (or nullptr), then SCALE, FILL and CLAMP of the chain, dst: the last MUL +bool ggml_cuda_should_fuse_l2_clip(const ggml_tensor * x, const ggml_tensor * scale, const ggml_tensor * dst) { + if (x->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || x->nb[0] != sizeof(float) || !ggml_is_contiguous(dst) || !ggml_are_same_shape(x, dst)) { + return false; + } + if (scale && (scale->type != GGML_TYPE_F32 || !ggml_is_contiguous(scale) || scale->ne[0] != x->ne[0] || !ggml_can_repeat(scale, x))) { + return false; + } + return x->ne[1] <= INT_MAX && x->ne[2] <= INT_MAX && x->ne[3] <= INT_MAX; +} + +void ggml_cuda_op_l2_clip_fused(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * scale, + const ggml_tensor * norm_scale, const ggml_tensor * fill, const ggml_tensor * clamp, ggml_tensor * dst) { + const float a = ggml_get_op_params_f32(norm_scale, 0); + const float b = ggml_get_op_params_f32(norm_scale, 1); + const float c = ggml_get_op_params_f32(fill, 0); + const float lo = ggml_get_op_params_f32(clamp, 0); + const float hi = ggml_get_op_params_f32(clamp, 1); + + const size_t ts = sizeof(float); + l2_clip_f32_cuda((const float *) x->data, scale ? (const float *) scale->data : nullptr, (float *) dst->data, + x->ne[0], x->ne[1], x->ne[2], x->ne[3], x->nb[1]/ts, x->nb[2]/ts, x->nb[3]/ts, + scale ? scale->ne[1] : 1, scale ? scale->ne[2] : 1, scale ? scale->ne[3] : 1, a, b, c, lo, hi, ctx.stream()); +} diff --git a/ggml/src/ggml-cuda/norm.cuh b/ggml/src/ggml-cuda/norm.cuh index 0c617dd3c833..0fc6f550d3d0 100644 --- a/ggml/src/ggml-cuda/norm.cuh +++ b/ggml/src/ggml-cuda/norm.cuh @@ -25,3 +25,8 @@ void ggml_cuda_op_rms_norm_fused_add(ggml_backend_cuda_context & ctx, void ggml_cuda_op_rms_norm_back(ggml_backend_cuda_context & ctx, ggml_tensor * dst); void ggml_cuda_op_l2_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst); + +bool ggml_cuda_should_fuse_l2_clip(const ggml_tensor * x, const ggml_tensor * scale, const ggml_tensor * dst); + +void ggml_cuda_op_l2_clip_fused(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * scale, + const ggml_tensor * norm_scale, const ggml_tensor * fill, const ggml_tensor * clamp, ggml_tensor * dst); diff --git a/ggml/src/ggml-cuda/scale.cu b/ggml/src/ggml-cuda/scale.cu index d53f906c5313..095895c60ea9 100644 --- a/ggml/src/ggml-cuda/scale.cu +++ b/ggml/src/ggml-cuda/scale.cu @@ -63,3 +63,32 @@ void ggml_cuda_op_scale(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { scale_f32_cuda((const float *) src0->data, (float *) dst->data, scale, bias, src0, dst, stream); } } + +// fused add + scale: dst = (a + b)*scale + bias, for a and b of the same shape +static __global__ void add_scale_f32(const float * a, const float * b, float * dst, const float scale, const float bias, const int64_t k) { + const int64_t i = int64_t(blockDim.x)*blockIdx.x + threadIdx.x; + if (i >= k) { + return; + } + dst[i] = (a[i] + b[i])*scale + bias; +} + +bool ggml_cuda_should_fuse_add_scale(const ggml_tensor * add, const ggml_tensor * scale) { + const ggml_tensor * tensors[] = { add->src[0], add->src[1], add, scale }; + for (const ggml_tensor * t : tensors) { + if (t->type != GGML_TYPE_F32 || !ggml_is_contiguous(t) || !ggml_are_same_shape(t, scale)) { + return false; + } + } + return true; +} + +void ggml_cuda_op_add_scale_fused(ggml_backend_cuda_context & ctx, const ggml_tensor * add, ggml_tensor * scale) { + const float s = ggml_get_op_params_f32(scale, 0); + const float b = ggml_get_op_params_f32(scale, 1); + const int64_t k = ggml_nelements(scale); + const int64_t num_blocks = (k + CUDA_SCALE_BLOCK_SIZE - 1) / CUDA_SCALE_BLOCK_SIZE; + GGML_ASSERT(num_blocks <= INT_MAX); + add_scale_f32<<>>( + (const float *) add->src[0]->data, (const float *) add->src[1]->data, (float *) scale->data, s, b, k); +} diff --git a/ggml/src/ggml-cuda/scale.cuh b/ggml/src/ggml-cuda/scale.cuh index 8ff75c8298b0..fd398de1f6e6 100644 --- a/ggml/src/ggml-cuda/scale.cuh +++ b/ggml/src/ggml-cuda/scale.cuh @@ -3,3 +3,7 @@ #define CUDA_SCALE_BLOCK_SIZE 256 void ggml_cuda_op_scale(ggml_backend_cuda_context & ctx, ggml_tensor * dst); + +bool ggml_cuda_should_fuse_add_scale(const ggml_tensor * add, const ggml_tensor * scale); + +void ggml_cuda_op_add_scale_fused(ggml_backend_cuda_context & ctx, const ggml_tensor * add, ggml_tensor * scale); diff --git a/ggml/src/ggml-cuda/unary.cu b/ggml/src/ggml-cuda/unary.cu index ed65fd7b5a93..237a5cd57131 100644 --- a/ggml/src/ggml-cuda/unary.cu +++ b/ggml/src/ggml-cuda/unary.cu @@ -940,6 +940,34 @@ void ggml_cuda_op_dot_sigmoid_gate_add( (int64_t) (moe->nb[1] / sizeof(float)), (int64_t) (res->nb[1] / sizeof(float))); } +/* fused gate: dst = (cur - tanh(f)*cur) + tanh(g)*msg, the chain tanh, mul, sub, tanh, mul and add */ + +static __global__ void tanh_gate_f32(const float * cur, const float * f, const float * g, const float * msg, float * dst, const int64_t k) { + const int64_t i = int64_t(blockDim.x)*blockIdx.x + threadIdx.x; + if (i >= k) { + return; + } + dst[i] = (cur[i] - tanhf(f[i])*cur[i]) + tanhf(g[i])*msg[i]; +} + +bool ggml_cuda_should_fuse_tanh_gate(const ggml_tensor * cur, const ggml_tensor * f, const ggml_tensor * g, const ggml_tensor * msg, const ggml_tensor * dst) { + for (const ggml_tensor * t : { cur, f, g, msg, dst }) { + if (t->type != GGML_TYPE_F32 || !ggml_is_contiguous(t) || !ggml_are_same_shape(t, dst)) { + return false; + } + } + return true; +} + +void ggml_cuda_op_tanh_gate_fused(ggml_backend_cuda_context & ctx, const ggml_tensor * cur, const ggml_tensor * f, const ggml_tensor * g, + const ggml_tensor * msg, ggml_tensor * dst) { + const int64_t k = ggml_nelements(dst); + const int64_t num_blocks = (k + CUDA_TANH_BLOCK_SIZE - 1) / CUDA_TANH_BLOCK_SIZE; + GGML_ASSERT(num_blocks <= INT_MAX); + tanh_gate_f32<<>>( + (const float *) cur->data, (const float *) f->data, (const float *) g->data, (const float *) msg->data, (float *) dst->data, k); +} + /* fused relu + sqr */ void ggml_cuda_op_relu_sqr(ggml_backend_cuda_context & ctx, ggml_tensor * relu_node, ggml_tensor * sqr_node) { diff --git a/ggml/src/ggml-cuda/unary.cuh b/ggml/src/ggml-cuda/unary.cuh index 95d9066ca5a3..a498d7544aed 100644 --- a/ggml/src/ggml-cuda/unary.cuh +++ b/ggml/src/ggml-cuda/unary.cuh @@ -107,6 +107,11 @@ void ggml_cuda_op_dot_sigmoid_gate_add( void ggml_cuda_op_relu_sqr(ggml_backend_cuda_context & ctx, ggml_tensor * relu_node, ggml_tensor * sqr_node); +bool ggml_cuda_should_fuse_tanh_gate(const ggml_tensor * cur, const ggml_tensor * f, const ggml_tensor * g, const ggml_tensor * msg, const ggml_tensor * dst); + +void ggml_cuda_op_tanh_gate_fused(ggml_backend_cuda_context & ctx, const ggml_tensor * cur, const ggml_tensor * f, const ggml_tensor * g, + const ggml_tensor * msg, ggml_tensor * dst); + __device__ __forceinline__ float ggml_cuda_op_silu_single(float x) { return x / (1.0f + expf(-x)); } diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 1f3ffaf4b8e1..f1352b339076 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -4169,6 +4169,119 @@ struct test_rms_norm_back : public test_case { } }; +// clip of the row l2 norms as in Inkling 2: [MUL] SQR SUM_ROWS SQRT SCALE FILL DIV CLAMP MUL +struct test_l2_clip : public test_case { + const std::array ne; + const bool with_scale; + const float threshold; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "L2_CLIP"; + } + + bool run_whole_graph() override { return true; } + + std::string vars() override { + return VARS_TO_STR3(ne, with_scale, threshold); + } + + test_l2_clip(std::array ne = {128, 24, 7, 1}, bool with_scale = true, float threshold = 6.5f) + : ne(ne), with_scale(with_scale), threshold(threshold) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * x = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data()); + ggml_set_name(x, "x"); + + ggml_tensor * cur = x; + if (with_scale) { + ggml_tensor * s = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, ne[0], ne[1]); + ggml_set_name(s, "s"); + cur = ggml_mul(ctx, cur, s); + } + + ggml_tensor * norm = ggml_sqrt(ctx, ggml_sum_rows(ctx, ggml_sqr(ctx, cur))); + norm = ggml_scale_bias(ctx, norm, 1.0f, 1e-6f); + + ggml_tensor * factor = ggml_div(ctx, ggml_fill(ctx, norm, threshold), norm); + + ggml_tensor * out = ggml_mul(ctx, cur, ggml_clamp(ctx, factor, 0.0f, 1.0f)); + ggml_set_name(out, "out"); + + return out; + } +}; + +// gate as in Inkling 2: (cur - tanh(f)*cur) + tanh(g)*msg +struct test_tanh_gate : public test_case { + const std::array ne; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "TANH_GATE"; + } + + bool run_whole_graph() override { return true; } + + std::string vars() override { + return VARS_TO_STR1(ne); + } + + test_tanh_gate(std::array ne = {2304, 7, 1, 1}) : ne(ne) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * cur = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data()); + ggml_tensor * f = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data()); + ggml_tensor * g = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data()); + ggml_tensor * msg = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data()); + ggml_set_name(cur, "cur"); + ggml_set_name(f, "f"); + ggml_set_name(g, "g"); + ggml_set_name(msg, "msg"); + + ggml_tensor * gain = ggml_tanh(ctx, g); + ggml_tensor * forget = ggml_tanh(ctx, f); + + ggml_tensor * out = ggml_add(ctx, ggml_sub(ctx, cur, ggml_mul(ctx, forget, cur)), ggml_mul(ctx, gain, msg)); + ggml_set_name(out, "out"); + + return out; + } +}; + +// GGML_OP_ADD + GGML_OP_SCALE of two tensors of the same shape +struct test_add_scale : public test_case { + const std::array ne; + const float scale; + const float bias; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "ADD_SCALE"; + } + + bool run_whole_graph() override { return true; } + + std::string vars() override { + return VARS_TO_STR3(ne, scale, bias); + } + + test_add_scale(std::array ne = {2304, 7, 1, 1}, float scale = 0.3f, float bias = 0.0f) + : ne(ne), scale(scale), bias(bias) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * a = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data()); + ggml_tensor * b = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data()); + ggml_set_name(a, "a"); + ggml_set_name(b, "b"); + + ggml_tensor * out = ggml_scale_bias(ctx, ggml_add(ctx, a, b), scale, bias); + ggml_set_name(out, "out"); + + return out; + } +}; + // GGML_OP_RMS_NORM + GGML_OP_MUL + GGML_OP_ADD (+ GGML_OP_MUL) struct test_rms_norm_mul_add : public test_case { const ggml_type type; @@ -14528,6 +14641,18 @@ static std::vector> make_test_cases_eval() { } } + // fused element-wise chains of Inkling 2 + for (bool with_scale : {false, true}) { + test_cases.emplace_back(new test_l2_clip({128, 24, 7, 1}, with_scale)); + test_cases.emplace_back(new test_l2_clip({ 16, 24, 1, 1}, with_scale, 1.0f)); + test_cases.emplace_back(new test_l2_clip({128, 8, 3, 2}, with_scale, 100.0f)); + test_cases.emplace_back(new test_l2_clip({1536, 3, 2, 1}, with_scale)); + } + test_cases.emplace_back(new test_tanh_gate({2304, 1, 1, 1})); + test_cases.emplace_back(new test_tanh_gate({2304, 7, 1, 1})); + test_cases.emplace_back(new test_add_scale({2304, 1, 1, 1})); + test_cases.emplace_back(new test_add_scale({1024, 7, 2, 1}, 0.2f, 0.5f)); + // flash attention with an indexed bias (Inkling 2 relative-position bias) for (bool kv_rows : {false, true}) { for (int64_t nb : {1, 7, 65}) { From 1cd2adcadc7bcf3f193a286306d0fe15f86c3470 Mon Sep 17 00:00:00 2001 From: rafasmour <54501936+rafasmour@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:43:56 +0000 Subject: [PATCH 23/24] inkling2: stack the depth-mix blocks once, transpose the conv window once, order the gate for fusion Assisted-by: Claude Opus 5.5 --- src/models/inkling2.cpp | 62 +++++++++++++++++++++++++++++++---------- src/models/models.h | 3 ++ 2 files changed, 50 insertions(+), 15 deletions(-) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index bd749bea17b9..50c61d566f13 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -175,17 +175,38 @@ ggml_tensor * llama_model_inkling2::graph::clip(ggml_tensor * cur, ggml_tensor * return ggml_mul(ctx0, cur, ggml_clamp(ctx0, factor, 0.0f, 1.0f)); } +// the normalized blocks stacked along dim 1, [n_embd, n_blocks, n_tokens], built once per list of blocks +ggml_tensor * llama_model_inkling2::graph::stack(const std::vector & blocks) { + if (blocks.empty()) { + return nullptr; + } + auto it = stacks.find(blocks); + if (it != stacks.end()) { + return it->second; + } + ggml_tensor * last = ggml_rms_norm(ctx0, ggml_reshape_3d(ctx0, blocks.back(), n_embd, 1, n_tokens), 1e-6f); + ggml_tensor * prev = stack(std::vector(blocks.begin(), blocks.end() - 1)); + ggml_tensor * res = prev ? ggml_concat(ctx0, prev, last, 1) : last; + stacks.emplace(blocks, res); + return res; +} + // attention over the depth: mix the earlier block outputs and cur with learned queries +// the result does not depend on the order of the states ggml_tensor * llama_model_inkling2::graph::mix(const std::vector & blocks, ggml_tensor * cur, ggml_tensor * query) { - ggml_tensor * states = ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens); - for (ggml_tensor * block : blocks) { - states = ggml_concat(ctx0, ggml_reshape_3d(ctx0, block, n_embd, 1, n_tokens), states, 1); + ggml_tensor * states = ggml_rms_norm(ctx0, ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens), 1e-6f); + if (ggml_tensor * prev = stack(blocks)) { + states = ggml_concat(ctx0, prev, states, 1); } - states = ggml_rms_norm(ctx0, states, 1e-6f); - - ggml_tensor * queries = ggml_repeat(ctx0, query, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd, query->ne[1], n_tokens)); - ggml_tensor * scores = ggml_mul_mat(ctx0, states, queries); + ggml_tensor * scores = nullptr; + if (query->ne[1] == 1) { + // [1, n_states, n_tokens] -> [n_states, 1, n_tokens] + scores = ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, query, states), states->ne[1], 1, n_tokens); + } else { + ggml_tensor * queries = ggml_repeat(ctx0, query, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd, query->ne[1], n_tokens)); + scores = ggml_mul_mat(ctx0, states, queries); + } scores = ggml_soft_max_ext(ctx0, scores, nullptr, 1.0f/sqrtf(n_embd), 0.0f); return ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, states)), scores); @@ -221,12 +242,15 @@ ggml_tensor * llama_model_inkling2::graph::convolve( dynamic = ggml_reshape_3d(ctx0, dynamic, n_conv, n_heads, n_tokens); - for (int64_t lag = 0; lag < n_conv; ++lag) { - ggml_tensor * tap = ggml_view_3d(ctx0, dynamic, 1, n_heads, n_tokens, dynamic->nb[1], dynamic->nb[2], lag*dynamic->nb[0]); - ggml_tensor * window = ggml_view_3d(ctx0, x, n_seq_tokens, n_channels, n_seqs, x->nb[1], x->nb[2], (n_conv - 1 - lag)*x->nb[0]); + // [n_channels, n_conv - 1 + n_seq_tokens, n_seqs], the window of each lag is a view of it + ggml_tensor * xt = ggml_cont(ctx0, ggml_transpose(ctx0, x)); + const int64_t n_embd_head = n_channels/n_heads; - window = ggml_cont(ctx0, ggml_transpose(ctx0, window)); - window = ggml_reshape_3d(ctx0, window, n_channels/n_heads, n_heads, n_tokens); + for (int64_t lag = 0; lag < n_conv; ++lag) { + ggml_tensor * tap = ggml_view_4d(ctx0, dynamic, 1, n_heads, n_seq_tokens, n_seqs, + dynamic->nb[1], dynamic->nb[2], n_seq_tokens*dynamic->nb[2], lag*dynamic->nb[0]); + ggml_tensor * window = ggml_view_4d(ctx0, xt, n_embd_head, n_heads, n_seq_tokens, n_seqs, + n_embd_head*xt->nb[0], xt->nb[1], xt->nb[2], (n_conv - 1 - lag)*xt->nb[1]); ggml_tensor * term = ggml_reshape_2d(ctx0, ggml_mul(ctx0, window, tap), n_channels, n_tokens); @@ -239,11 +263,19 @@ ggml_tensor * llama_model_inkling2::graph::convolve( // mix a cross-pass message into a looped layer input: (1 - forget)*cur + gain*message, both gated on cur and message ggml_tensor * llama_model_inkling2::graph::control(ggml_tensor * cur, ggml_tensor * message, const loop_layer & loop, int ctrl) { - ggml_tensor * gate = ggml_concat(ctx0, ggml_rms_norm(ctx0, cur, 1e-6f), ggml_rms_norm(ctx0, message, 1e-6f), 0); + // [rms_norm(cur), rms_norm(message)] as one norm over [n_embd, 2, n_tokens] + ggml_tensor * gate = ggml_concat(ctx0, ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens), ggml_reshape_3d(ctx0, message, n_embd, 1, n_tokens), 1); + gate = ggml_reshape_2d(ctx0, ggml_rms_norm(ctx0, gate, 1e-6f), 2*n_embd, n_tokens); gate = build_lora_mm(loop.ctrl_down[ctrl], gate); - ggml_tensor * gain = ggml_tanh(ctx0, build_lora_mm(loop.ctrl_gain[ctrl], gate)); - ggml_tensor * forget = ggml_tanh(ctx0, build_lora_mm(loop.ctrl_forget[ctrl], gate)); + // both projections first, so that the element-wise tail is one run of nodes + ggml_tensor * gain = build_lora_mm(loop.ctrl_gain[ctrl], gate); + ggml_tensor * forget = build_lora_mm(loop.ctrl_forget[ctrl], gate); + ggml_build_forward_expand(gf, gain); + ggml_build_forward_expand(gf, forget); + + gain = ggml_tanh(ctx0, gain); + forget = ggml_tanh(ctx0, forget); return ggml_add(ctx0, ggml_sub(ctx0, cur, ggml_mul(ctx0, forget, cur)), ggml_mul(ctx0, gain, message)); } diff --git a/src/models/models.h b/src/models/models.h index b4e24e95f003..857147d48c5c 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2536,6 +2536,7 @@ struct llama_model_inkling2 : public llama_model_base { struct graph : public llm_graph_context { graph(const llm_graph_params & params); + ggml_tensor * stack(const std::vector & blocks); ggml_tensor * mix(const std::vector & blocks, ggml_tensor * cur, ggml_tensor * query); ggml_tensor * clip(ggml_tensor * cur, ggml_tensor * scale, float threshold); ggml_tensor * convolve( @@ -2566,6 +2567,8 @@ struct llama_model_inkling2 : public llama_model_base { ggml_tensor * inp_out_ids = nullptr; ggml_tensor * tau = nullptr; // log-scaled positions + + std::map, ggml_tensor *> stacks; // see stack() }; std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; From cc4688501fea5db9578df251aedb8d3621fcd799 Mon Sep 17 00:00:00 2001 From: rafasmour <54501936+rafasmour@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:59:42 +0000 Subject: [PATCH 24/24] inkling2: one zero sinks tensor per graph Assisted-by: Claude Opus 5.5 --- src/models/inkling2.cpp | 5 ++++- src/models/models.h | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 50c61d566f13..0e2f5ed32a0c 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -293,6 +293,9 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() { tau = ggml_log(ctx0, ggml_clamp(ctx0, ggml_scale(ctx0, tau, 1.0f/hparams.n_log_scale_floor), 1.0f, INFINITY)); tau = ggml_reshape_3d(ctx0, ggml_scale_bias(ctx0, tau, hparams.f_log_scale_alpha, 1.0f), 1, 1, n_tokens); + // the sink logits are folded into the bias table, the attention gets zero sinks + zero_sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, hparams.n_head()), 0.0f); + ggml_tensor * cur = build_inp_embd(model.tok_embd); // important: do not normalize raw embeddings input (i.e. encoded image embeddings) @@ -389,7 +392,7 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks, 1, n_head, n_tokens)); cb(table, "rel_bias", il); - sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); + sinks = zero_sinks->ne[0] == n_head ? zero_sinks : ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); cur = build_attn(inp, nullptr, nullptr, nullptr, diff --git a/src/models/models.h b/src/models/models.h index 857147d48c5c..1792e9908bdd 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2567,6 +2567,7 @@ struct llama_model_inkling2 : public llama_model_base { ggml_tensor * inp_out_ids = nullptr; ggml_tensor * tau = nullptr; // log-scaled positions + ggml_tensor * zero_sinks = nullptr; std::map, ggml_tensor *> stacks; // see stack() };