Commit d27064223 for llama.cpp

commit d270642232e6a6c92a5d4522a163b95efd842b1a
Author: Aman Gupta <amangupta052@gmail.com>
Date:   Mon Dec 7 00:59:22 2026 +0800

    CUDA: skip the slots with id -1 in MUL_MAT_ID and ADD_ID (#33618)

    * CUDA: skip the slots with id -1 in MUL_MAT_ID and ADD_ID

    An id of -1 skips the slot (#26631): MUL_MAT_ID gives a zero row for it and
    ADD_ID a copy of src0. The CUDA backend did not do this, so test-backend-ops
    excluded these cases for it. All paths do it now and the exclusion is removed.

    * CUDA: cap the MUL_MAT_ID zeroing blocks, trim the sorted fallback

    - mm_ids_helper: at most one zeroing block per SM, beyond that a block
      takes several tokens
    - sorted fallback: gather only the rows of the slots that are not
      skipped, zero the extra row only when a slot is skipped
    - tests: add a case with skipped slots at 600 tokens

    * fix performance regression

    ---------

    Co-authored-by: Johannes Gäßler <johannesg@5d6.de>

diff --git a/ggml/src/ggml-cuda/add-id.cu b/ggml/src/ggml-cuda/add-id.cu
index f9fa73dec..09edcd9ca 100644
--- a/ggml/src/ggml-cuda/add-id.cu
+++ b/ggml/src/ggml-cuda/add-id.cu
@@ -19,6 +19,15 @@ static __global__ void add_id_kernel(

         float * dst_row = (float *)((char *)dst + i1*nb1 + i2*nb2);
         const float * src0_row = (const float *)((const char *)src0 +  i1*nb01 + i2*nb02);
+
+        if (i11 < 0) {
+            // a negative id skips the slot
+            for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
+                dst_row[i0] = src0_row[i0];
+            }
+            continue;
+        }
+
         const float * src1_row = (const float *)((const char *)src1 + i11*nb11);

         for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu
index 01c07a3df..6e21eab0e 100644
--- a/ggml/src/ggml-cuda/ggml-cuda.cu
+++ b/ggml/src/ggml-cuda/ggml-cuda.cu
@@ -2408,14 +2408,15 @@ static bool ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor *

     std::vector<int32_t> ids_to_sorted_host;
     ids_to_sorted_host.reserve(2*ne_get_rows);
-    std::vector<int32_t> ids_from_sorted_host(ne_get_rows);
+    std::vector<int32_t> ids_from_sorted_host(ne_get_rows, -1);

     ggml_cuda_pool_alloc<int32_t> ids_buf_dev(ctx.pool(), 2*ne_get_rows);

     std::vector<int32_t> tokens_per_expert(ne02);

     ggml_cuda_pool_alloc<char> src1_sorted(ctx.pool(), ne12*n_expert_used*ne10*ts_src1_sorted);
-    ggml_cuda_pool_alloc<char>  dst_sorted(ctx.pool(), ne2 *n_expert_used* ne0*ts_dst_sorted);
+    // one more row than slots, the zero row of the skipped slots (id -1)
+    ggml_cuda_pool_alloc<char>  dst_sorted(ctx.pool(), (ne2*n_expert_used + 1)*ne0*ts_dst_sorted);

     std::vector<char> ids_host(ggml_nbytes(ids));
     CUDA_CHECK(cudaMemcpyAsync(ids_host.data(), ids->data, ggml_nbytes(ids), cudaMemcpyDeviceToHost, stream));
@@ -2425,7 +2426,7 @@ static bool ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor *
         for (int64_t i12 = 0; i12 < ne12; ++i12) { // tokens
             for (int64_t iex = 0; iex < n_expert_used; ++iex) {
                 const int32_t expert_to_use = *(const int32_t *)(ids_host.data() + i12*ids->nb[1] + iex*ids->nb[0]);
-                assert(expert_to_use >= 0 && expert_to_use < ne02);
+                assert(expert_to_use >= -1 && expert_to_use < ne02);
                 if (expert_to_use == i02) {
                     ids_from_sorted_host[i12*n_expert_used + iex] = ids_to_sorted_host.size();
                     ids_to_sorted_host.push_back(i12*ne11 + iex % ne11);
@@ -2436,7 +2437,18 @@ static bool ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor *
             }
         }
     }
-    GGML_ASSERT(ids_to_sorted_host.size() == size_t(ne_get_rows));
+    // the skipped slots have no sorted row, they take the zero row after the sorted rows
+    const int64_t ne_sorted = ids_to_sorted_host.size();
+    GGML_ASSERT(ne_sorted <= ne_get_rows);
+    ids_to_sorted_host.resize(ne_get_rows);
+    for (int32_t & id : ids_from_sorted_host) {
+        if (id < 0) {
+            id = ne_sorted;
+        }
+    }
+    if (ne_sorted < ne_get_rows) {
+        CUDA_CHECK(cudaMemsetAsync(dst_sorted.ptr + ne_sorted*ne0*ts_dst_sorted, 0, ne0*ts_dst_sorted, stream));
+    }

     ids_to_sorted_host.insert(ids_to_sorted_host.end(), ids_from_sorted_host.begin(), ids_from_sorted_host.end());

@@ -2446,11 +2458,14 @@ static bool ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor *
     const int32_t * ids_to_sorted   = ids_buf_dev.ptr + 0*ne_get_rows;
     const int32_t * ids_from_sorted = ids_buf_dev.ptr + 1*ne_get_rows;

-    get_rows_cuda(src1->data, src1->type, ids_to_sorted, src1_sorted.ptr, type_src1_sorted,
-        ne10, nb11, nb12, nb13,
-        ne_get_rows, 1, 1, sizeof(int32_t), ne_get_rows*sizeof(int32_t), ne_get_rows*sizeof(int32_t),
-        ne10*ts_src1_sorted, ne_get_rows*ne10*ts_src1_sorted, ne_get_rows*ne10*ts_src1_sorted, stream);
-    CUDA_CHECK(cudaGetLastError());
+    // only the slots that are not skipped have a sorted row
+    if (ne_sorted > 0) {
+        get_rows_cuda(src1->data, src1->type, ids_to_sorted, src1_sorted.ptr, type_src1_sorted,
+            ne10, nb11, nb12, nb13,
+            ne_sorted, 1, 1, sizeof(int32_t), ne_get_rows*sizeof(int32_t), ne_get_rows*sizeof(int32_t),
+            ne10*ts_src1_sorted, ne_get_rows*ne10*ts_src1_sorted, ne_get_rows*ne10*ts_src1_sorted, stream);
+        CUDA_CHECK(cudaGetLastError());
+    }

     char * src1_data_cur = (char *) src1_sorted.ptr;
     char *  dst_data_cur = (char *)  dst_sorted.ptr;
@@ -2559,18 +2574,18 @@ static void ggml_cuda_op_mul_mat_scale(ggml_backend_cuda_context & ctx, ggml_ten
     const int64_t ne0 = dst->ne[0], ne1 = dst->ne[1], ne2 = dst->ne[2], ne3 = dst->ne[3];

     // per-expert scale is indexed through ids (scalar [n_expert] or 2D per-channel [n_out, n_expert]);
-    // per-tensor / dense scale is a plain broadcast
+    // per-tensor / dense scale is a plain broadcast, for MUL_MAT_ID it also goes through ids to leave the skipped slots (id -1) at zero
     const bool per_channel_expert = is_id && scale->ne[0] == ne0 && scale->ne[1] == dst->src[0]->ne[2];
     const bool per_expert = is_id && (ggml_nelements(scale) == dst->src[0]->ne[2] || per_channel_expert);

-    if (per_expert) {
+    if (is_id) {
         const ggml_tensor * ids = dst->src[2];
         const int64_t total  = ne0*ne1*ne2;
         const int64_t blocks = (total + CUDA_MUL_MAT_SCALE_BLOCK_SIZE - 1) / CUDA_MUL_MAT_SCALE_BLOCK_SIZE;
         mul_mat_scale_id<<<blocks, CUDA_MUL_MAT_SCALE_BLOCK_SIZE, 0, stream>>>(
             dst_d, scale_d, (const int32_t *) ids->data, ne0, ne1, ne2,
             ids->nb[0]/sizeof(int32_t), ids->nb[1]/sizeof(int32_t),
-            per_channel_expert ? scale->nb[0] : 0, per_channel_expert ? scale->nb[1] : scale->nb[0]);
+            per_channel_expert ? scale->nb[0] : 0, per_channel_expert ? scale->nb[1] : per_expert ? scale->nb[0] : 0);
     } else {
         const int64_t total  = ne0*ne1*ne2*ne3;
         const int64_t blocks = (total + CUDA_MUL_MAT_SCALE_BLOCK_SIZE - 1) / CUDA_MUL_MAT_SCALE_BLOCK_SIZE;
diff --git a/ggml/src/ggml-cuda/mmf.cu b/ggml/src/ggml-cuda/mmf.cu
index 396ad1c11..0219b297f 100644
--- a/ggml/src/ggml-cuda/mmf.cu
+++ b/ggml/src/ggml-cuda/mmf.cu
@@ -87,7 +87,7 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr

         ggml_cuda_launch_mm_ids_helper(ids_d, ids_src_compact_dev.get(), ids_dst_compact_dev.get(), tile_spec_dev.get(),
             static_cast<int>(n_experts), static_cast<int>(n_tokens), static_cast<int>(n_expert_used), static_cast<int>(ne11), 16,
-            si1, sis1, /*write_inverse =*/ false, ctx.stream());
+            si1, sis1, /*write_inverse =*/ false, dst_d, static_cast<int>(ne0), stride_channel_dst, stride_col_dst, ctx.stream());
         CUDA_CHECK(cudaGetLastError());

         ids_info.ids_src_compact = ids_src_compact_dev.get();
diff --git a/ggml/src/ggml-cuda/mmid.cu b/ggml/src/ggml-cuda/mmid.cu
index fe9458763..5e3a4a22c 100644
--- a/ggml/src/ggml-cuda/mmid.cu
+++ b/ggml/src/ggml-cuda/mmid.cu
@@ -68,7 +68,7 @@ static __device__ __forceinline__ void dump_store(

 constexpr int n_unroll = 4; // Manually unroll this many loop iterations for better performance.

-// Helper function for mul_mat_id, converts ids to a more convenient format.
+// Helper function for mul_mat_id, converts ids to a more convenient format and zeroes the dst rows of the skipped slots.
 // ids_src1 describes how to permute the flattened column indices of src1 in order to get a compact src1 tensor sorted by expert.
 // ids_dst describes the same mapping but for the dst tensor.
 // The first (n_tokens*n_expert_used + J - 1) / tile_width elements of tile_spec contain the specication for
@@ -80,11 +80,30 @@ static __global__ void mm_ids_helper(
         const int32_t * __restrict__ ids,
         int32_t * __restrict__ ids_src1, int32_t * __restrict__ ids_dst, ggml_cuda_mm_id_tile_spec * __restrict__ tile_spec,
         const int n_tokens, const int n_expert_used_var, const int nchannels_y, const uint3 tile_width,
-        const int si1, const int sis1, const bool write_inverse, const int ne_store) {
+        const int si1, const int sis1, const bool write_inverse, const int ne_store,
+        float * __restrict__ dst, const int n_experts, const int nrows, const int64_t stride_channel_dst, const int64_t stride_col_dst) {
     constexpr int warp_size = ggml_cuda_get_physical_warp_size();
     const int n_expert_used = n_expert_used_template == 0 ? n_expert_used_var : n_expert_used_template;

-    const int expert = blockIdx.x; // The expert this CUDA block handles.
+    // The blocks after the expert blocks zero the dst rows of the skipped slots (id -1), the tokens are dealt out to them in turn.
+    if (int(blockIdx.x) > n_experts) {
+        const int nblocks = gridDim.x - n_experts - 1;
+        for (int it = blockIdx.x - n_experts - 1; it < n_tokens; it += nblocks) {
+            for (int iex = 0; iex < n_expert_used; ++iex) {
+                if (ids[it*si1 + iex] >= 0) {
+                    continue;
+                }
+                float * dst_row = dst + it*stride_col_dst + iex*stride_channel_dst;
+                for (int i = threadIdx.x; i < nrows; i += blockDim.x) {
+                    dst_row[i] = 0.0f;
+                }
+            }
+        }
+        return;
+    }
+
+    // The expert this CUDA block handles, the block after the last expert takes the skipped slots so that they have valid indices.
+    const int expert = int(blockIdx.x) == n_experts ? -1 : int(blockIdx.x);

     extern __shared__ char data_mm_ids_helper[];
     mm_ids_helper_store * store = (mm_ids_helper_store *) data_mm_ids_helper;
@@ -223,14 +242,19 @@ static __global__ void mm_ids_helper(
     int col_high = nex_prev + min(int(tile_width.z), n_dumped);

     // The while loop covers all tiles at the seams containing the column with % tile_width == 0.
+    // The tiles of the skipped slots are empty, no matrix multiplication is done for them.
     while (col_high > fastdiv(col_low + tile_width.z - 1, tile_width) * tile_width.z) {
         tile_spec[fastdiv(col_low + tile_width.z - 1, tile_width)]
-            = {expert, col_low, col_high, /*padding =*/ 0};
+            = {expert, col_low, expert < 0 ? col_low : col_high, /*padding =*/ 0};

         col_low  = col_high;
         col_high = min(col_high + int(tile_width.z), nex_prev + n_dumped);
     }

+    if (expert < 0) {
+        return;
+    }
+
     // Finally, at most one extra tile_spec between the seams per expert.
     tile_spec[fastdiv(n_tokens*n_expert_used + tile_width.z - 1, tile_width) + expert]
         = {expert, col_low, col_high, /*padding =*/ 0};
@@ -241,7 +265,8 @@ static void launch_mm_ids_helper(
         const int32_t * __restrict__ ids,
         int32_t * __restrict__ ids_src1, int32_t * __restrict__ ids_dst, ggml_cuda_mm_id_tile_spec * __restrict__ tile_spec,
         const int n_experts, const int n_tokens, const int n_expert_used_var, const int nchannels_y, const int tile_width,
-        const int si1, const int sis1, const bool write_inverse, cudaStream_t stream) {
+        const int si1, const int sis1, const bool write_inverse,
+        float * __restrict__ dst, const int nrows, const int64_t stride_channel_dst, const int64_t stride_col_dst, cudaStream_t stream) {
     GGML_ASSERT(n_tokens          < (1 << 22) && "too few bits in mm_ids_helper_store");
     GGML_ASSERT(n_expert_used_var < (1 << 10) && "too few bits in mm_ids_helper_store");

@@ -252,53 +277,65 @@ static void launch_mm_ids_helper(

     const uint3 tile_width_fd = init_fastdiv_values(tile_width);

-    const dim3 num_blocks(n_experts, 1, 1);
+    // at most one zeroing block per SM, beyond that a block takes several tokens
+    const int nblocks_zero = std::min(n_tokens, ggml_cuda_info().devices[id].nsm);
+    const dim3 num_blocks(n_experts + 1 + nblocks_zero, 1, 1);
     const dim3 block_size(warp_size, 1, 1);
     const size_t ne_shared_pad = n_expert_used_template == 0 ? std::max(n_expert_used_var, warp_size) : n_unroll*warp_size;
     const size_t nbytes_store_core = std::min(smpbo - ne_shared_pad * sizeof(mm_ids_helper_store), n_tokens * sizeof(mm_ids_helper_store));
     const size_t nbytes_shared = nbytes_store_core + ne_shared_pad * sizeof(mm_ids_helper_store);
     const size_t ne_store = nbytes_shared / sizeof(mm_ids_helper_store);
     mm_ids_helper<n_expert_used_template><<<num_blocks, block_size, nbytes_shared, stream>>>
-        (ids, ids_src1, ids_dst, tile_spec, n_tokens, n_expert_used_var, nchannels_y, tile_width_fd, si1, sis1, write_inverse, ne_store);
+        (ids, ids_src1, ids_dst, tile_spec, n_tokens, n_expert_used_var, nchannels_y, tile_width_fd, si1, sis1, write_inverse, ne_store,
+         dst, n_experts, nrows, stride_channel_dst, stride_col_dst);
 }

 void ggml_cuda_launch_mm_ids_helper(
         const int32_t * __restrict__ ids,
         int32_t * __restrict__ ids_src1, int32_t * __restrict__ ids_dst, ggml_cuda_mm_id_tile_spec * __restrict__ tile_spec,
         const int n_experts, const int n_tokens, const int n_expert_used, const int nchannels_y, const int tile_width,
-        const int si1, const int sis1, const bool write_inverse, cudaStream_t stream) {
+        const int si1, const int sis1, const bool write_inverse,
+        float * __restrict__ dst, const int nrows, const int64_t stride_channel_dst, const int64_t stride_col_dst, cudaStream_t stream) {
     switch (n_expert_used) {
         case  2:
             launch_mm_ids_helper< 2>(ids, ids_src1, ids_dst, tile_spec,
-                n_experts, n_tokens, n_expert_used, nchannels_y, tile_width, si1, sis1, write_inverse, stream);
+                n_experts, n_tokens, n_expert_used, nchannels_y, tile_width, si1, sis1, write_inverse,
+                dst, nrows, stride_channel_dst, stride_col_dst, stream);
             break;
         case  4:
             launch_mm_ids_helper< 4>(ids, ids_src1, ids_dst, tile_spec,
-                n_experts, n_tokens, n_expert_used, nchannels_y, tile_width, si1, sis1, write_inverse, stream);
+                n_experts, n_tokens, n_expert_used, nchannels_y, tile_width, si1, sis1, write_inverse,
+                dst, nrows, stride_channel_dst, stride_col_dst, stream);
             break;
         case  6:
             launch_mm_ids_helper< 6>(ids, ids_src1, ids_dst, tile_spec,
-                n_experts, n_tokens, n_expert_used, nchannels_y, tile_width, si1, sis1, write_inverse, stream);
+                n_experts, n_tokens, n_expert_used, nchannels_y, tile_width, si1, sis1, write_inverse,
+                dst, nrows, stride_channel_dst, stride_col_dst, stream);
             break;
         case  8:
             launch_mm_ids_helper< 8>(ids, ids_src1, ids_dst, tile_spec,
-                n_experts, n_tokens, n_expert_used, nchannels_y, tile_width, si1, sis1, write_inverse, stream);
+                n_experts, n_tokens, n_expert_used, nchannels_y, tile_width, si1, sis1, write_inverse,
+                dst, nrows, stride_channel_dst, stride_col_dst, stream);
             break;
         case 10:
             launch_mm_ids_helper<10>(ids, ids_src1, ids_dst, tile_spec,
-                n_experts, n_tokens, n_expert_used, nchannels_y, tile_width, si1, sis1, write_inverse, stream);
+                n_experts, n_tokens, n_expert_used, nchannels_y, tile_width, si1, sis1, write_inverse,
+                dst, nrows, stride_channel_dst, stride_col_dst, stream);
             break;
         case 16:
             launch_mm_ids_helper<16>(ids, ids_src1, ids_dst, tile_spec,
-                n_experts, n_tokens, n_expert_used, nchannels_y, tile_width, si1, sis1, write_inverse, stream);
+                n_experts, n_tokens, n_expert_used, nchannels_y, tile_width, si1, sis1, write_inverse,
+                dst, nrows, stride_channel_dst, stride_col_dst, stream);
             break;
         case 32:
             launch_mm_ids_helper<32>(ids, ids_src1, ids_dst, tile_spec,
-                n_experts, n_tokens, n_expert_used, nchannels_y, tile_width, si1, sis1, write_inverse, stream);
+                n_experts, n_tokens, n_expert_used, nchannels_y, tile_width, si1, sis1, write_inverse,
+                dst, nrows, stride_channel_dst, stride_col_dst, stream);
             break;
         default:
             launch_mm_ids_helper< 0>(ids, ids_src1, ids_dst, tile_spec,
-                n_experts, n_tokens, n_expert_used, nchannels_y, tile_width, si1, sis1, write_inverse, stream);
+                n_experts, n_tokens, n_expert_used, nchannels_y, tile_width, si1, sis1, write_inverse,
+                dst, nrows, stride_channel_dst, stride_col_dst, stream);
             break;
     }
 }
diff --git a/ggml/src/ggml-cuda/mmid.cuh b/ggml/src/ggml-cuda/mmid.cuh
index dc878a71c..6e79bcc32 100644
--- a/ggml/src/ggml-cuda/mmid.cuh
+++ b/ggml/src/ggml-cuda/mmid.cuh
@@ -13,4 +13,5 @@ void ggml_cuda_launch_mm_ids_helper(
         const int32_t * __restrict__ ids,
         int32_t * __restrict__ ids_src1, int32_t * __restrict__ ids_dst, ggml_cuda_mm_id_tile_spec * __restrict__ tile_spec,
         const int n_experts, const int n_tokens, const int n_expert_used, const int nchannels_y, const int tile_width,
-        const int si1, const int sis1, const bool write_inverse, cudaStream_t stream);
+        const int si1, const int sis1, const bool write_inverse,
+        float * __restrict__ dst, const int nrows, const int64_t stride_channel_dst, const int64_t stride_col_dst, cudaStream_t stream);
diff --git a/ggml/src/ggml-cuda/mmq-few.cu b/ggml/src/ggml-cuda/mmq-few.cu
index ab258f182..3d9408300 100644
--- a/ggml/src/ggml-cuda/mmq-few.cu
+++ b/ggml/src/ggml-cuda/mmq-few.cu
@@ -1538,7 +1538,8 @@ void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor
         pairs.alloc(int64_t(npairs_max)*MMQ_FEW_PAIR_INTS);
         src1_q.alloc(int64_t(npairs_max)*nunits*MMQ_FEW_Q8_1_INT4);
         quantize_mmq_few_id_q8_1_cuda(src1->data, src1->type, (const int32_t *) ids->data, src1_q.get(), pairs.get(), mmq_few_ds_layout(src0->type),
-            ne00, nb11/nb10, nb12/nb10, ne11, ne02, n_expert_used, n_tokens, ids->nb[1]/sizeof(int32_t), npairs_max, stream);
+            ne00, nb11/nb10, nb12/nb10, ne11, ne02, n_expert_used, n_tokens, ids->nb[1]/sizeof(int32_t), npairs_max,
+            (float *) dst->data, ne0, nb1/sizeof(float), nb2/sizeof(float), stream);
     } else {
         GGML_ASSERT(ne11 <= MMQ_FEW_MAX_NCG*MMQ_FEW_NCOLS);
         GGML_ASSERT(ne12 % ne02 == 0 && ne13 % ne03 == 0);
diff --git a/ggml/src/ggml-cuda/mmq.cu b/ggml/src/ggml-cuda/mmq.cu
index e58c2fc77..e7ba22970 100644
--- a/ggml/src/ggml-cuda/mmq.cu
+++ b/ggml/src/ggml-cuda/mmq.cu
@@ -340,7 +340,7 @@ void ggml_cuda_mul_mat_q(
         const int sis1 = nb12 / nb11;

         ggml_cuda_launch_mm_ids_helper((const int32_t *) ids->data, ids_src1.get(), ids_dst.get(), tile_spec.get(),
-            ne02, ne12, n_expert_used, ne11, J_best, si1, sis1, /*write_inverse =*/ dedup_bcast, stream);
+            ne02, ne12, n_expert_used, ne11, J_best, si1, sis1, /*write_inverse =*/ dedup_bcast, dst_d, ne0, s1, s2, stream);
         CUDA_CHECK(cudaGetLastError());
     }

diff --git a/ggml/src/ggml-cuda/mmvf.cu b/ggml/src/ggml-cuda/mmvf.cu
index 600c92a8f..c016dfb0d 100644
--- a/ggml/src/ggml-cuda/mmvf.cu
+++ b/ggml/src/ggml-cuda/mmvf.cu
@@ -152,58 +152,26 @@ static __global__ void mul_mat_vec_f(
         }
     }

-    if constexpr (std::is_same_v<T, float>) {
-        const float2 * y2 = (const float2 *) y;
-        const float2 * x2 = (const float2 *) x;
-        [[maybe_unused]] const float2 * gate_x2 = nullptr;
-        if constexpr (has_fusion) {
-            if (use_gate) {
-                gate_x2 = (const float2 *) gate_x;
-            }
-        }
-
-        for (int col2 = tid; col2 < ncols2; col2 += block_size) {
-            const float2 tmpx = x2[col2];
-            float2 tmpx_gate = make_float2(0.0f, 0.0f);
+    if (channel_x >= 0) {
+        if constexpr (std::is_same_v<T, float>) {
+            const float2 * y2 = (const float2 *) y;
+            const float2 * x2 = (const float2 *) x;
+            [[maybe_unused]] const float2 * gate_x2 = nullptr;
             if constexpr (has_fusion) {
                 if (use_gate) {
-                    tmpx_gate = gate_x2[col2];
+                    gate_x2 = (const float2 *) gate_x;
                 }
             }

-#pragma unroll
-            for (int j = 0; j < ncols_dst; ++j) {
-                const float2 tmpy = y2[j*stride_col_y2 + col2];
-                ggml_cuda_mad(sumf[j], tmpx.x, tmpy.x);
-                ggml_cuda_mad(sumf[j], tmpx.y, tmpy.y);
-
-                if constexpr (has_fusion) {
-                    if (use_gate) {
-                        ggml_cuda_mad(sumf_gate[j], tmpx_gate.x, tmpy.x);
-                        ggml_cuda_mad(sumf_gate[j], tmpx_gate.y, tmpy.y);
-                    }
-                }
-            }
-        }
-    } else if constexpr (std::is_same_v<T, half>) {
-        const float2 * y2 = (const float2 *) y;
-        const half2 * x2 = (const half2 *) x;
-        [[maybe_unused]] const half2 * gate_x2 = nullptr;
-        if constexpr (has_fusion) {
-            if (use_gate) {
-                gate_x2 = (const half2 *) gate_x;
-            }
-        }
-
-        if (std::is_same_v<type_acc, float>) {
             for (int col2 = tid; col2 < ncols2; col2 += block_size) {
-                const float2 tmpx = __half22float2(x2[col2]);
+                const float2 tmpx = x2[col2];
                 float2 tmpx_gate = make_float2(0.0f, 0.0f);
                 if constexpr (has_fusion) {
                     if (use_gate) {
-                        tmpx_gate = __half22float2(gate_x2[col2]);
+                        tmpx_gate = gate_x2[col2];
                     }
                 }
+
 #pragma unroll
                 for (int j = 0; j < ncols_dst; ++j) {
                     const float2 tmpy = y2[j*stride_col_y2 + col2];
@@ -218,141 +186,175 @@ static __global__ void mul_mat_vec_f(
                     }
                 }
             }
-        } else {
-#ifdef FP16_AVAILABLE
-            half2 sumh2[ncols_dst] = {{0.0f, 0.0f}};
-            half2 sumh2_gate[ncols_dst] = {{0.0f, 0.0f}};
+        } else if constexpr (std::is_same_v<T, half>) {
+            const float2 * y2 = (const float2 *) y;
+            const half2 * x2 = (const half2 *) x;
+            [[maybe_unused]] const half2 * gate_x2 = nullptr;
+            if constexpr (has_fusion) {
+                if (use_gate) {
+                    gate_x2 = (const half2 *) gate_x;
+                }
+            }

-            for (int col2 = tid; col2 < ncols2; col2 += block_size) {
-                const half2 tmpx = x2[col2];
-                half2 tmpx_gate = make_half2(0.0f, 0.0f);
-                if constexpr (has_fusion) {
-                    if (use_gate) {
-                        tmpx_gate = gate_x2[col2];
+            if (std::is_same_v<type_acc, float>) {
+                for (int col2 = tid; col2 < ncols2; col2 += block_size) {
+                    const float2 tmpx = __half22float2(x2[col2]);
+                    float2 tmpx_gate = make_float2(0.0f, 0.0f);
+                    if constexpr (has_fusion) {
+                        if (use_gate) {
+                            tmpx_gate = __half22float2(gate_x2[col2]);
+                        }
                     }
-                }
 #pragma unroll
-                for (int j = 0; j < ncols_dst; ++j) {
-                    const float2 tmpy = y2[j*stride_col_y2 + col2];
-                    sumh2[j] += tmpx * make_half2(tmpy.x, tmpy.y);
+                    for (int j = 0; j < ncols_dst; ++j) {
+                        const float2 tmpy = y2[j*stride_col_y2 + col2];
+                        ggml_cuda_mad(sumf[j], tmpx.x, tmpy.x);
+                        ggml_cuda_mad(sumf[j], tmpx.y, tmpy.y);
+
+                        if constexpr (has_fusion) {
+                            if (use_gate) {
+                                ggml_cuda_mad(sumf_gate[j], tmpx_gate.x, tmpy.x);
+                                ggml_cuda_mad(sumf_gate[j], tmpx_gate.y, tmpy.y);
+                            }
+                        }
+                    }
+                }
+            } else {
+#ifdef FP16_AVAILABLE
+                half2 sumh2[ncols_dst] = {{0.0f, 0.0f}};
+                half2 sumh2_gate[ncols_dst] = {{0.0f, 0.0f}};

+                for (int col2 = tid; col2 < ncols2; col2 += block_size) {
+                    const half2 tmpx = x2[col2];
+                    half2 tmpx_gate = make_half2(0.0f, 0.0f);
                     if constexpr (has_fusion) {
                         if (use_gate) {
-                            sumh2_gate[j] += tmpx_gate * make_half2(tmpy.x, tmpy.y);
+                            tmpx_gate = gate_x2[col2];
+                        }
+                    }
+#pragma unroll
+                    for (int j = 0; j < ncols_dst; ++j) {
+                        const float2 tmpy = y2[j*stride_col_y2 + col2];
+                        sumh2[j] += tmpx * make_half2(tmpy.x, tmpy.y);
+
+                        if constexpr (has_fusion) {
+                            if (use_gate) {
+                                sumh2_gate[j] += tmpx_gate * make_half2(tmpy.x, tmpy.y);
+                            }
                         }
                     }
                 }
-            }

 #pragma unroll
-            for (int j = 0; j < ncols_dst; ++j) {
-                sumf[j] = __low2float(sumh2[j]) + __high2float(sumh2[j]);
-            }
+                for (int j = 0; j < ncols_dst; ++j) {
+                    sumf[j] = __low2float(sumh2[j]) + __high2float(sumh2[j]);
+                }

-            if constexpr (has_fusion) {
-                if (use_gate) {
+                if constexpr (has_fusion) {
+                    if (use_gate) {
 #pragma unroll
-                    for (int j = 0; j < ncols_dst; ++j) {
-                        sumf_gate[j] = __low2float(sumh2_gate[j]) + __high2float(sumh2_gate[j]);
+                        for (int j = 0; j < ncols_dst; ++j) {
+                            sumf_gate[j] = __low2float(sumh2_gate[j]) + __high2float(sumh2_gate[j]);
+                        }
                     }
                 }
-            }
 #else
-            NO_DEVICE_CODE;
+                NO_DEVICE_CODE;
 #endif // FP16_AVAILABLE
-        }
-    } else if constexpr (std::is_same_v<T, nv_bfloat16>) {
-        const T_y2 * y2 = (const T_y2 *) y;
+            }
+        } else if constexpr (std::is_same_v<T, nv_bfloat16>) {
+            const T_y2 * y2 = (const T_y2 *) y;
 //TODO: add support for ggml_cuda_mad for hip_bfloat162
 #if defined(GGML_USE_HIP)
-        const int * x2 = (const int *) x;
-        const int * gate_x2 = nullptr;
-        if constexpr (has_fusion) {
-            if (use_gate) {
-                gate_x2 = (const int *) gate_x;
-            }
-        }
-        for (int col2 = tid; col2 < ncols2; col2 += block_size) {
-            const int tmpx = x2[col2];
-            int tmpx_gate = 0;
+            const int * x2 = (const int *) x;
+            const int * gate_x2 = nullptr;
             if constexpr (has_fusion) {
                 if (use_gate) {
-                    tmpx_gate = gate_x2[col2];
+                    gate_x2 = (const int *) gate_x;
                 }
             }
-#pragma unroll
-            for (int j = 0; j < ncols_dst; ++j) {
-                const float2 tmpy = ggml_cuda_cast<float2>(y2[j*stride_col_y2 + col2]);
-                const float tmpx0 = ggml_cuda_cast<float>(reinterpret_cast<const nv_bfloat16 *>(&tmpx)[0]);
-                const float tmpx1 = ggml_cuda_cast<float>(reinterpret_cast<const nv_bfloat16 *>(&tmpx)[1]);
-                ggml_cuda_mad(sumf[j], tmpx0, tmpy.x);
-                ggml_cuda_mad(sumf[j], tmpx1, tmpy.y);
-
+            for (int col2 = tid; col2 < ncols2; col2 += block_size) {
+                const int tmpx = x2[col2];
+                int tmpx_gate = 0;
                 if constexpr (has_fusion) {
                     if (use_gate) {
-                        const float tmpx0_gate = ggml_cuda_cast<float>(reinterpret_cast<const nv_bfloat16 *>(&tmpx_gate)[0]);
-                        const float tmpx1_gate = ggml_cuda_cast<float>(reinterpret_cast<const nv_bfloat16 *>(&tmpx_gate)[1]);
-                        ggml_cuda_mad(sumf_gate[j], tmpx0_gate, tmpy.x);
-                        ggml_cuda_mad(sumf_gate[j], tmpx1_gate, tmpy.y);
+                        tmpx_gate = gate_x2[col2];
+                    }
+                }
+#pragma unroll
+                for (int j = 0; j < ncols_dst; ++j) {
+                    const float2 tmpy = ggml_cuda_cast<float2>(y2[j*stride_col_y2 + col2]);
+                    const float tmpx0 = ggml_cuda_cast<float>(reinterpret_cast<const nv_bfloat16 *>(&tmpx)[0]);
+                    const float tmpx1 = ggml_cuda_cast<float>(reinterpret_cast<const nv_bfloat16 *>(&tmpx)[1]);
+                    ggml_cuda_mad(sumf[j], tmpx0, tmpy.x);
+                    ggml_cuda_mad(sumf[j], tmpx1, tmpy.y);
+
+                    if constexpr (has_fusion) {
+                        if (use_gate) {
+                            const float tmpx0_gate = ggml_cuda_cast<float>(reinterpret_cast<const nv_bfloat16 *>(&tmpx_gate)[0]);
+                            const float tmpx1_gate = ggml_cuda_cast<float>(reinterpret_cast<const nv_bfloat16 *>(&tmpx_gate)[1]);
+                            ggml_cuda_mad(sumf_gate[j], tmpx0_gate, tmpy.x);
+                            ggml_cuda_mad(sumf_gate[j], tmpx1_gate, tmpy.y);
+                        }
                     }
                 }
             }
-        }
 #else
-        const nv_bfloat162 * x2 = (const nv_bfloat162 *) x;
-        [[maybe_unused]] const nv_bfloat162 * gate_x2 = nullptr;
-        if constexpr (has_fusion) {
-            if (use_gate) {
-                gate_x2 = (const nv_bfloat162 *) gate_x;
-            }
-        }
-        for (int col2 = tid; col2 < ncols2; col2 += block_size) {
-            const nv_bfloat162 tmpx = x2[col2];
-            [[maybe_unused]] nv_bfloat162 tmpx_gate;
+            const nv_bfloat162 * x2 = (const nv_bfloat162 *) x;
+            [[maybe_unused]] const nv_bfloat162 * gate_x2 = nullptr;
             if constexpr (has_fusion) {
                 if (use_gate) {
-                    tmpx_gate = gate_x2[col2];
+                    gate_x2 = (const nv_bfloat162 *) gate_x;
                 }
             }
-#pragma unroll
-            for (int j = 0; j < ncols_dst; ++j) {
-                const float2 tmpy = ggml_cuda_cast<float2>(y2[j*stride_col_y2 + col2]);
-                ggml_cuda_mad(sumf[j], tmpx.x, tmpy.x);
-                ggml_cuda_mad(sumf[j], tmpx.y, tmpy.y);
-
+            for (int col2 = tid; col2 < ncols2; col2 += block_size) {
+                const nv_bfloat162 tmpx = x2[col2];
+                [[maybe_unused]] nv_bfloat162 tmpx_gate;
                 if constexpr (has_fusion) {
                     if (use_gate) {
-                        ggml_cuda_mad(sumf_gate[j], tmpx_gate.x, tmpy.x);
-                        ggml_cuda_mad(sumf_gate[j], tmpx_gate.y, tmpy.y);
+                        tmpx_gate = gate_x2[col2];
+                    }
+                }
+#pragma unroll
+                for (int j = 0; j < ncols_dst; ++j) {
+                    const float2 tmpy = ggml_cuda_cast<float2>(y2[j*stride_col_y2 + col2]);
+                    ggml_cuda_mad(sumf[j], tmpx.x, tmpy.x);
+                    ggml_cuda_mad(sumf[j], tmpx.y, tmpy.y);
+
+                    if constexpr (has_fusion) {
+                        if (use_gate) {
+                            ggml_cuda_mad(sumf_gate[j], tmpx_gate.x, tmpy.x);
+                            ggml_cuda_mad(sumf_gate[j], tmpx_gate.y, tmpy.y);
+                        }
                     }
                 }
             }
-        }
 #endif
-    } else if constexpr (std::is_same_v<T, ggml_fp8_e4m3_t>) {
-        const T_y2 * y2 = (const T_y2 *) y;
-        for (int col2 = tid; col2 < ncols2; col2 += block_size) {
-            const float2 tmpx = mmvf_load_fp8x2(x, col2);
-            float2 tmpx_gate = {};
-            if constexpr (has_fusion) {
-                if (use_gate) {
-                    tmpx_gate = mmvf_load_fp8x2(gate_x, col2);
+        } else if constexpr (std::is_same_v<T, ggml_fp8_e4m3_t>) {
+            const T_y2 * y2 = (const T_y2 *) y;
+            for (int col2 = tid; col2 < ncols2; col2 += block_size) {
+                const float2 tmpx = mmvf_load_fp8x2(x, col2);
+                float2 tmpx_gate = {};
+                if constexpr (has_fusion) {
+                    if (use_gate) {
+                        tmpx_gate = mmvf_load_fp8x2(gate_x, col2);
+                    }
                 }
-            }
 #pragma unroll
-            for (int j = 0; j < ncols_dst; ++j) {
-                const float2 tmpy = ggml_cuda_cast<float2>(y2[j*stride_col_y2 + col2]);
-                ggml_cuda_mad(sumf[j], tmpx, tmpy);
+                for (int j = 0; j < ncols_dst; ++j) {
+                    const float2 tmpy = ggml_cuda_cast<float2>(y2[j*stride_col_y2 + col2]);
+                    ggml_cuda_mad(sumf[j], tmpx, tmpy);

-                if constexpr (has_fusion) {
-                    if (use_gate) {
-                        ggml_cuda_mad(sumf_gate[j], tmpx_gate, tmpy);
+                    if constexpr (has_fusion) {
+                        if (use_gate) {
+                            ggml_cuda_mad(sumf_gate[j], tmpx_gate, tmpy);
+                        }
                     }
                 }
             }
+        } else {
+            static_assert(std::is_same_v<T, void>, "unsupported type");
         }
-    } else {
-        static_assert(std::is_same_v<T, void>, "unsupported type");
     }

     ggml_cuda_pdl_lc();
@@ -401,6 +403,10 @@ static __global__ void mul_mat_vec_f(
     float value = sumf[tid];

     if constexpr (has_fusion) {
+        if (ids && channel_x < 0) {
+            dst[tid*stride_col_dst + row] = 0.0f;
+            return;
+        }
         if (use_scale) {
             value *= x_scale[ids ? channel_x : 0];
         }
diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu
index 3c9060a69..b1d560c52 100644
--- a/ggml/src/ggml-cuda/mmvq.cu
+++ b/ggml/src/ggml-cuda/mmvq.cu
@@ -761,9 +761,22 @@ static __global__ void mul_mat_vec_q(
     uint32_t sample_dst;

     ggml_cuda_pdl_sync();
-    channel_x  = shared_expert ? 0 : ncols_dst == 1 && ids ? ids[channel_dst] : fastdiv(channel_dst, channel_ratio);
-    channel_y  = ncols_dst == 1 && ids ? fastmodulo(channel_dst, nchannels_y) : channel_dst;
     sample_dst = blockIdx.z;
+    if (ncols_dst == 1 && ids) {
+        const int32_t id = shared_expert ? 0 : ids[channel_dst];
+        if (id < 0) {
+            // a negative id skips the expert, its rows of the result are zero
+            if (threadIdx.y == 0 && threadIdx.x < rows_per_cuda_block && (rows_per_cuda_block == 1 || uint32_t(row0 + threadIdx.x) < stride_col_dst)) {
+                dst[sample_dst*stride_sample_dst + channel_dst*stride_channel_dst + row0 + threadIdx.x] = 0.0f;
+            }
+            return;
+        }
+        channel_x = id;
+        channel_y = fastmodulo(channel_dst, nchannels_y);
+    } else {
+        channel_x = shared_expert ? 0 : fastdiv(channel_dst, channel_ratio);
+        channel_y = channel_dst;
+    }

     const uint32_t sample_x    = fastdiv(sample_dst, sample_ratio);
     const uint32_t sample_y    = sample_dst;
@@ -1042,7 +1055,15 @@ static __global__ void mul_mat_vec_q_moe(
     }

     ggml_cuda_pdl_sync();
-    const uint32_t channel_x = shared_expert ? 0 : ids[channel_dst + token_idx * ids_stride];
+    const int32_t id = shared_expert ? 0 : ids[channel_dst + token_idx * ids_stride];
+    if (id < 0) {
+        // a negative id skips the expert, its rows of the result are zero
+        if (threadIdx.x < c_rows_per_block && (c_rows_per_block == 1 || uint32_t(row0 + threadIdx.x) < nrows_x)) {
+            dst[channel_dst*stride_channel_dst + token_idx*stride_col_dst + row0 + threadIdx.x] = 0.0f;
+        }
+        return;
+    }
+    const uint32_t channel_x = id;
     const uint32_t channel_y = fastmodulo(channel_dst, nchannels_y);

     const block_q8_1 * y = ((const block_q8_1 *) vy) + channel_y*stride_channel_y + token_idx*stride_col_y;
diff --git a/ggml/src/ggml-cuda/quantize.cu b/ggml/src/ggml-cuda/quantize.cu
index c2f963e6d..0e6723ab5 100644
--- a/ggml/src/ggml-cuda/quantize.cu
+++ b/ggml/src/ggml-cuda/quantize.cu
@@ -805,11 +805,13 @@ static __global__ void quantize_mmq_few_q8_1(
 }

 // MUL_MAT_ID: block x is the (token, slot) entry, ids are as in mm_ids_helper. Each block finds the pair of its entry in shared memory, block (0, 0) also writes all pairs.
+// A skipped slot has no pair, its dst row is zeroed here.
 // Entry rank r = number of earlier tokens with the same expert, pair = first pair of the expert + r/MMQ_FEW_NCOLS, column = r % MMQ_FEW_NCOLS.
 template <typename src_t, mmq_q8_1_ds_layout ds_layout>
 static __global__ void quantize_mmq_few_id_q8_1(
         const src_t * x_ptr, const int32_t * ids, void * vy_ptr, int * pairs, const int64_t ne00, const int64_t s11, const int64_t s12,
-        const int ne11, const int n_experts, const int n_expert_used, const int64_t si1, const int npairs_max) {
+        const int ne11, const int n_experts, const int n_expert_used, const int64_t si1, const int npairs_max,
+        float * dst, const int nrows_dst, const int64_t stride_channel_dst, const int64_t stride_col_dst) {
     // per expert: bit t set if token t uses it and the index of its first pair; then the total number of pairs
     extern __shared__ unsigned int data_mmq_few_id[];
     unsigned int * tokens = data_mmq_few_id;
@@ -882,11 +884,17 @@ static __global__ void quantize_mmq_few_id_q8_1(

     const int     e  = expert_of(blockIdx.x);
     const int64_t i0 = ((int64_t)blockDim.x*blockIdx.y + threadIdx.x)*4;
+    const int     it = blockIdx.x / n_expert_used;
+    const int     is = blockIdx.x % n_expert_used;
+    if (e < 0 && blockIdx.y == 0) {
+        float * dst_row = dst + it*stride_col_dst + is*stride_channel_dst;
+        for (int i = threadIdx.x; i < nrows_dst; i += blockDim.x) {
+            dst_row[i] = 0.0f;
+        }
+    }
     if (e < 0 || i0 >= ne00) {
         return;
     }
-    const int    it = blockIdx.x / n_expert_used;
-    const int    is = blockIdx.x % n_expert_used;
     const float4 xi = quantize_load4(x + it*s12 + (is % ne11)*s11 + i0, 0);

     const int r = rank(blockIdx.x, e);
@@ -1099,7 +1107,8 @@ void quantize_mmq_few_wmma_q8_1_cuda(
 template <typename src_t>
 static void quantize_mmq_few_id_q8_1_cuda(
         const src_t * x, const int32_t * ids, void * vy, int * pairs, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s11, const int64_t s12,
-        const int64_t ne11, const int64_t n_experts, const int64_t n_expert_used, const int64_t n_tokens, const int64_t si1, const int64_t npairs_max, cudaStream_t stream) {
+        const int64_t ne11, const int64_t n_experts, const int64_t n_expert_used, const int64_t n_tokens, const int64_t si1, const int64_t npairs_max,
+        float * dst, const int64_t nrows_dst, const int64_t stride_channel_dst, const int64_t stride_col_dst, cudaStream_t stream) {
     GGML_ASSERT(ne00 % QK_K == 0);
     GGML_ASSERT(n_tokens <= 32); // one bit per token

@@ -1112,11 +1121,13 @@ static void quantize_mmq_few_id_q8_1_cuda(
     switch (ds_layout) {
         case MMQ_Q8_1_DS_LAYOUT_D4:
             ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D4>, launch_params,
-                x, ids, vy, pairs, ne00, s11, s12, (int) ne11, (int) n_experts, (int) n_expert_used, si1, (int) npairs_max);
+                x, ids, vy, pairs, ne00, s11, s12, (int) ne11, (int) n_experts, (int) n_expert_used, si1, (int) npairs_max,
+                dst, (int) nrows_dst, stride_channel_dst, stride_col_dst);
             break;
         case MMQ_Q8_1_DS_LAYOUT_DS4:
             ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_DS4>, launch_params,
-                x, ids, vy, pairs, ne00, s11, s12, (int) ne11, (int) n_experts, (int) n_expert_used, si1, (int) npairs_max);
+                x, ids, vy, pairs, ne00, s11, s12, (int) ne11, (int) n_experts, (int) n_expert_used, si1, (int) npairs_max,
+                dst, (int) nrows_dst, stride_channel_dst, stride_col_dst);
             break;
         default:
             GGML_ABORT("fatal error");
@@ -1125,9 +1136,11 @@ static void quantize_mmq_few_id_q8_1_cuda(

 void quantize_mmq_few_id_q8_1_cuda(
         const void * x, const ggml_type type_src1, const int32_t * ids, void * vy, int * pairs, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s11, const int64_t s12,
-        const int64_t ne11, const int64_t n_experts, const int64_t n_expert_used, const int64_t n_tokens, const int64_t si1, const int64_t npairs_max, cudaStream_t stream) {
+        const int64_t ne11, const int64_t n_experts, const int64_t n_expert_used, const int64_t n_tokens, const int64_t si1, const int64_t npairs_max,
+        float * dst, const int64_t nrows_dst, const int64_t stride_channel_dst, const int64_t stride_col_dst, cudaStream_t stream) {
     quantize_launch_typed(x, type_src1, [&](auto * x_t) {
-        quantize_mmq_few_id_q8_1_cuda(x_t, ids, vy, pairs, ds_layout, ne00, s11, s12, ne11, n_experts, n_expert_used, n_tokens, si1, npairs_max, stream);
+        quantize_mmq_few_id_q8_1_cuda(x_t, ids, vy, pairs, ds_layout, ne00, s11, s12, ne11, n_experts, n_expert_used, n_tokens, si1, npairs_max,
+            dst, nrows_dst, stride_channel_dst, stride_col_dst, stream);
     });
 }

diff --git a/ggml/src/ggml-cuda/quantize.cuh b/ggml/src/ggml-cuda/quantize.cuh
index 55e0b7fa8..606341062 100644
--- a/ggml/src/ggml-cuda/quantize.cuh
+++ b/ggml/src/ggml-cuda/quantize.cuh
@@ -65,7 +65,8 @@ static constexpr int MMQ_FEW_PAIR_INTS = 2 + MMQ_FEW_NCOLS;

 void quantize_mmq_few_id_q8_1_cuda(
         const void * x, ggml_type type_src1, const int32_t * ids, void * vy, int * pairs, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s11, int64_t s12,
-        int64_t ne11, int64_t n_experts, int64_t n_expert_used, int64_t n_tokens, int64_t si1, int64_t npairs_max, cudaStream_t stream);
+        int64_t ne11, int64_t n_experts, int64_t n_expert_used, int64_t n_tokens, int64_t si1, int64_t npairs_max,
+        float * dst, int64_t nrows_dst, int64_t stride_channel_dst, int64_t stride_col_dst, cudaStream_t stream);

 // src1 of the few-row MMQ for RDNA3 WMMA, which multiplies 16 src1 columns and needs the same A and B data in both half-warps.
 // Per channel, 256 values and group of MMQ_FEW_WMMA_NCOLS columns:
diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp
index ddcba7a11..b2cd823df 100644
--- a/tests/test-backend-ops.cpp
+++ b/tests/test-backend-ops.cpp
@@ -1225,29 +1225,6 @@ static bool op_filter_entry_matches(std::string_view entry, std::string_view op_
     return std::regex_search(op_name.data(), op_name.data() + op_name.size(), re);
 }

-// TODO: [TAG_MUL_MAT_ID_SKIP] see https://github.com/ggml-org/llama.cpp/pull/26631
-static bool backend_lacks_skipped_ids(ggml_backend_t backend, ggml_cgraph * gf) {
-    const char * name = ggml_backend_reg_name(ggml_backend_dev_backend_reg(ggml_backend_get_device(backend)));
-    if (strcmp(name, "CUDA") != 0 && strcmp(name, "ROCm") != 0 && strcmp(name, "MUSA") != 0) {
-        return false;
-    }
-    for (int i = 0; i < ggml_graph_n_nodes(gf); i++) {
-        const ggml_tensor * node = ggml_graph_node(gf, i);
-        if (node->op != GGML_OP_MUL_MAT_ID && node->op != GGML_OP_ADD_ID) {
-            continue;
-        }
-        const ggml_tensor * ids = node->src[2];
-        std::vector<int32_t> row(ids->ne[0]);
-        for (int64_t i1 = 0; i1 < ids->ne[1]; i1++) {
-            ggml_backend_tensor_get(ids, row.data(), i1*ids->nb[1], ids->ne[0]*sizeof(int32_t));
-            if (std::find(row.begin(), row.end(), -1) != row.end()) {
-                return true;
-            }
-        }
-    }
-    return false;
-}
-
 struct test_case {
     virtual ~test_case() {}

@@ -1546,13 +1523,6 @@ struct test_case {
             initialize_tensors(ctx_weights.get());
         }

-        // TODO: [TAG_MUL_MAT_ID_SKIP] @ngxson : remove this once CUDA implements mul_mat_id with -1 = skipped
-        if (backend_lacks_skipped_ids(backend1, gf)) {
-            test_result result(ggml_backend_name(backend1), current_op_name, vars(), "test", false, false, "not supported");
-            print_test_result_locked(output_printer, result);
-            return test_status_t::NOT_SUPPORTED;
-        }
-
         // compare
         struct callback_userdata {
             bool   ok;
@@ -6906,7 +6876,11 @@ static void init_mul_mat_id_ids(ggml_context * ctx, int n_mats, bool skip = fals

 static void init_mul_mat_id_tensors(ggml_context * ctx, int n_mats, bool skip = false) {
     for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
-        if (t->type != GGML_TYPE_I32) {
+        if (skip && t->op != GGML_OP_NONE && !ggml_is_view_op(t->op) && t->type == GGML_TYPE_F32) {
+            // a result row of a skipped slot that is not written stays NaN
+            std::vector<float> data(ggml_nelements(t), NAN);
+            ggml_backend_tensor_set(t, data.data(), 0, ggml_nbytes(t));
+        } else if (t->type != GGML_TYPE_I32) {
             init_tensor_uniform(t);
         }
     }
@@ -7062,6 +7036,21 @@ struct test_mul_mat_id_dup : public test_mul_mat_id {
     }
 };

+// MUL_MAT_ID with all slots skipped, the result is all zeros
+struct test_mul_mat_id_skip_all : public test_mul_mat_id {
+    using test_mul_mat_id::test_mul_mat_id;
+    std::string vars() override { return test_mul_mat_id::vars() + ",skip_all=1"; }
+    void initialize_tensors(ggml_context * ctx) override {
+        test_mul_mat_id::initialize_tensors(ctx);
+        for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
+            if (t->type == GGML_TYPE_I32 && !ggml_is_view_op(t->op)) {
+                std::vector<int32_t> data(ggml_nelements(t), -1);
+                ggml_backend_tensor_set(t, data.data(), 0, ggml_nbytes(t));
+            }
+        }
+    }
+};
+
 // FP4 W4A8 path on the MoE path (GGML_PREC_Q8 on src1 disallows 4-bit activations)
 struct test_mul_mat_id_w4a8 : public test_mul_mat_id {
     test_mul_mat_id_w4a8(ggml_type type_a = GGML_TYPE_NVFP4, ggml_type type_b = GGML_TYPE_F32,
@@ -7253,12 +7242,13 @@ struct test_mul_mat_id_fusion : public test_case {
 struct test_mul_mat_id_shared : public test_case {
     const ggml_type type;
     const int64_t n;
+    const bool skip; // set some ids to a negative value
     ggml_tensor * routed = nullptr;
     ggml_tensor * shared = nullptr;

-    test_mul_mat_id_shared(ggml_type type, int64_t n) : type(type), n(n) {}
+    test_mul_mat_id_shared(ggml_type type, int64_t n, bool skip = false) : type(type), n(n), skip(skip) {}

-    std::string vars() override { return VARS_TO_STR2(type, n); }
+    std::string vars() override { return VARS_TO_STR3(type, n, skip); }
     std::string op_desc(ggml_tensor *) override { return "MUL_MAT_ID_SHARED"; }
     bool run_whole_graph() override { return true; }
     double max_nmse_err() override { return 5e-4; }
@@ -7279,7 +7269,7 @@ struct test_mul_mat_id_shared : public test_case {
     }

     void initialize_tensors(ggml_context * ctx) override {
-        init_mul_mat_id_tensors(ctx, 8);
+        init_mul_mat_id_tensors(ctx, 8, skip);
     }
 };

@@ -14512,6 +14502,7 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
     for (ggml_type type : { GGML_TYPE_Q4_K, GGML_TYPE_Q8_0 }) {
         for (int64_t n : { 1, 2, 3, 4, 8, 9 }) {
             test_cases.emplace_back(new test_mul_mat_id_shared(type, n));
+            test_cases.emplace_back(new test_mul_mat_id_shared(type, n, true));
         }
     }

@@ -14596,6 +14587,28 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
             }
         }
     }
+    // skipped slots at 2 to 32 tokens with K = 2 units of 256 values, e.g. for the CUDA few-row MMQ, and with all slots skipped
+    for (ggml_type type_a : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_F8_E4M3, GGML_TYPE_Q4_0, GGML_TYPE_Q3_K, GGML_TYPE_Q4_K,
+                             GGML_TYPE_Q8_0, GGML_TYPE_IQ4_XS, GGML_TYPE_NVFP4}) {
+        for (bool b : {false, true}) {
+            for (int n : {2, 3, 5, 8, 9, 16, 32}) {
+                test_cases.emplace_back(new test_mul_mat_id(type_a, GGML_TYPE_F32, 8, 4, b, 96, n, 512, 0, false, true));
+            }
+        }
+        for (int n : {1, 2, 8, 9, 33}) {
+            test_cases.emplace_back(new test_mul_mat_id_skip_all(type_a, GGML_TYPE_F32, 8, 4, false, 96, n, 512, 0, false, true));
+        }
+    }
+    // BF16 src1, CUDA takes MMVF for these
+    for (int n : {1, 2, 8}) {
+        test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_BF16, GGML_TYPE_BF16, 8, 4, false, 96, n, 512, 0, false, true));
+        test_cases.emplace_back(new test_mul_mat_id_skip_all(GGML_TYPE_BF16, GGML_TYPE_BF16, 8, 4, false, 96, n, 512, 0, false, true));
+    }
+    // more tokens than the CUDA MMF takes, the experts are done one by one
+    test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_F32, GGML_TYPE_F32, 4, 2, false, 32, 600, 64, 0, false, true));
+    test_cases.emplace_back(new test_mul_mat_id_skip_all(GGML_TYPE_F32, GGML_TYPE_F32, 4, 2, false, 32, 600, 64, 0, false, true));
+    // more tokens than a GPU has SMs, a CUDA block zeroes the rows of several tokens
+    test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q4_0, GGML_TYPE_F32, 8, 4, false, 96, 600, 512, 0, false, true));
     // n_used == n_mats, so every expert can be skipped
     test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_F16, GGML_TYPE_F32, 4, 4, false, 512, 64, 256, 0, false, true));
     test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_F16, GGML_TYPE_F32, 1, 1, false, 8, 16, 1, 0, false, true));
@@ -15739,8 +15752,10 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
                                 }
                                 // the lane scale does a GET_ROWS on the ids, which does not accept -1
                                 if (use_id && !with_lane_scale) {
-                                    test_cases.emplace_back(new test_mul_mat_fusion(type, glu_op, 8, 32, 256,
-                                        use_id, 16, 8, b, with_bias, with_gate, with_lane_scale, {1, 1}, true));
+                                    for (int64_t m_batch : { 1, 8 }) {
+                                        test_cases.emplace_back(new test_mul_mat_fusion(type, glu_op, m_batch, 32, 256,
+                                            use_id, 16, 8, b, with_bias, with_gate, with_lane_scale, {1, 1}, true));
+                                    }
                                 }
                             }
                         }
@@ -15814,6 +15829,8 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
     // The same with experts (~1280 tiles each): 17 tokens with broadcast input (one MMA tile per warp), 2048 tokens without (two, several column tiles per expert).
     test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K,   GGML_GLU_OP_SWIGLU,        17,  5120, 256, true, 16, 8, true));
     test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q8_0,   GGML_GLU_OP_SWIGLU,      2048,   128, 256, true, 40, 8, false));
+    // with skipped slots
+    test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K,   GGML_GLU_OP_SWIGLU,        17,  5120, 256, true, 16, 8, true, false, true, false, { 4, 2 }, true));
     // NVFP4 with experts, without and with per-expert weight scales.
     test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4,  GGML_GLU_OP_SWIGLU,       150,  2560, 256, true, 16, 8, false));
     test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4,  GGML_GLU_OP_SWIGLU,        17,  5120, 256, true, 16, 8, true,  false, true, true));