Commit b80ec40d0 for llama.cpp

commit b80ec40d090c71399d9eb42eed17f4575ddef97c
Author: Pascal <admin@serveurperso.com>
Date:   Sun Nov 29 14:01:00 2026 +0100

    webgpu: apply the weight scale of MUL_MAT and MUL_MAT_ID (#33266)

    * webgpu : apply the weight scale of MUL_MAT and MUL_MAT_ID

    Since #28898 a MUL_MAT or MUL_MAT_ID that carries a weight scale is
    rejected by supports_op, so scaled weights (NVFP4 experts, the Q8_0
    experts of Gemma 4) are placed in host memory and run on the CPU.

    Apply the scale after the product with a small epilogue kernel, as the
    Metal backend does: per tensor, per output channel, per expert or per
    output channel of each expert, the expert of a MUL_MAT_ID row read from
    ids and skipped slots left untouched. Activation scales are ignored, as
    on CPU and Metal.

    * webgpu : accumulate MUL_MAT_ID tiles in f32 like MUL_MAT

    The tiled MUL_MAT_ID kernel accumulated its products in f16. NVFP4
    weights are stored at a magnitude that the weight scale brings back
    down, so on real checkpoints such as Inkling 2 Mini the unscaled sums
    exceed the f16 range and the output turns into inf.

    Accumulate in f32 as the tiled MUL_MAT kernel already does, keeping
    the f16 shared memory tiles.

diff --git a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp
index d3dbe8dd5..cb7b6848d 100644
--- a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp
+++ b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp
@@ -598,6 +598,22 @@ struct ggml_webgpu_add_id_pipeline_key_hash {
     }
 };

+/** Mul_Mat scale **/
+
+struct ggml_webgpu_mul_mat_scale_pipeline_key {
+    bool use_ids;
+
+    bool operator==(const ggml_webgpu_mul_mat_scale_pipeline_key & other) const { return use_ids == other.use_ids; }
+};
+
+struct ggml_webgpu_mul_mat_scale_pipeline_key_hash {
+    size_t operator()(const ggml_webgpu_mul_mat_scale_pipeline_key & key) const {
+        size_t seed = 0;
+        ggml_webgpu_hash_combine(seed, key.use_ids);
+        return seed;
+    }
+};
+
 /** Unary **/

 struct ggml_webgpu_unary_pipeline_key {
@@ -1304,10 +1320,14 @@ class ggml_webgpu_shader_lib {
         binary_pipelines;           // type/op/inplace/overlap/src_overlap
     std::unordered_map<ggml_webgpu_add_id_pipeline_key, webgpu_pipeline, ggml_webgpu_add_id_pipeline_key_hash>
         add_id_pipelines;           // inplace
+    std::unordered_map<ggml_webgpu_mul_mat_scale_pipeline_key,
+                       webgpu_pipeline,
+                       ggml_webgpu_mul_mat_scale_pipeline_key_hash>
+        mul_mat_scale_pipelines;  // use_ids
     std::unordered_map<ggml_webgpu_concat_pipeline_key, webgpu_pipeline, ggml_webgpu_concat_pipeline_key_hash>
-        concat_pipelines;           // type
+        concat_pipelines;         // type
     std::unordered_map<ggml_webgpu_repeat_pipeline_key, webgpu_pipeline, ggml_webgpu_repeat_pipeline_key_hash>
-        repeat_pipelines;           // type
+        repeat_pipelines;         // type
     std::unordered_map<ggml_webgpu_flash_attn_vec_pipeline_key,
                        webgpu_pipeline,
                        ggml_webgpu_flash_attn_vec_pipeline_key_hash>
@@ -3062,6 +3082,35 @@ class ggml_webgpu_shader_lib {
         return pipeline;
     }

+    webgpu_pipeline get_mul_mat_scale_pipeline(const ggml_webgpu_shader_lib_context & context, bool use_ids) {
+        ggml_webgpu_mul_mat_scale_pipeline_key key = {};
+        key.use_ids                                = use_ids;
+
+        auto it = mul_mat_scale_pipelines.find(key);
+        if (it != mul_mat_scale_pipelines.end()) {
+            return it->second;
+        }
+
+        std::vector<std::string> defines;
+        std::string              variant = "mul_mat_scale";
+
+        if (key.use_ids) {
+            defines.push_back("USE_IDS");
+            variant += "_ids";
+        }
+
+        defines.push_back(std::string("WG_SIZE=") + std::to_string(context.max_wg_size));
+
+        auto processed              = preprocessor.preprocess(wgsl_mul_mat_scale, defines);
+        auto pipeline_decisions     = std::make_shared<ggml_webgpu_generic_shader_decisions>();
+        pipeline_decisions->wg_size = context.max_wg_size;
+
+        webgpu_pipeline pipeline     = ggml_webgpu_create_pipeline(device, processed, variant);
+        pipeline.context             = pipeline_decisions;
+        mul_mat_scale_pipelines[key] = pipeline;
+        return pipeline;
+    }
+
     webgpu_pipeline get_concat_pipeline(const ggml_webgpu_shader_lib_context & context, bool src_overlap) {
         ggml_webgpu_concat_pipeline_key key = {};
         key.type                            = context.dst->type;
diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp
index edb392439..62c571b0b 100644
--- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp
+++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp
@@ -2177,6 +2177,72 @@ static webgpu_encoded_op ggml_webgpu_mul_mat_id(webgpu_context & ctx,
     return ggml_backend_webgpu_build_multi(ctx, dispatches);
 }

+static webgpu_encoded_op ggml_webgpu_mul_mat_scale(webgpu_context & ctx, ggml_tensor * dst) {
+    ggml_tensor *       scale = const_cast<ggml_tensor *>(ggml_get_src_scale(dst, 0));
+    const ggml_tensor * src0  = dst->src[0];
+    ggml_tensor *       ids   = dst->op == GGML_OP_MUL_MAT_ID ? dst->src[2] : nullptr;
+
+    GGML_ASSERT(scale->type == GGML_TYPE_F32);
+    GGML_ASSERT(dst->type == GGML_TYPE_F32);
+    GGML_ASSERT(ggml_is_contiguous_rows(dst));
+
+    const bool per_channel_expert = ids && scale->ne[0] == dst->ne[0] && scale->ne[1] == src0->ne[2];
+    const bool per_expert         = ids && (ggml_nelements(scale) == src0->ne[2] || per_channel_expert);
+    const bool per_channel = per_expert ? per_channel_expert : scale->ne[0] == dst->ne[0] && ggml_nelements(scale) > 1;
+
+    ggml_webgpu_shader_lib_context shader_lib_ctx = {};
+    shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup;
+
+    webgpu_pipeline pipeline = ctx->shader_lib->get_mul_mat_scale_pipeline(shader_lib_ctx, per_expert);
+
+    const size_t   s_ts   = ggml_type_size(scale->type);
+    const uint32_t n_rows = (uint32_t) (dst->ne[1] * dst->ne[2] * dst->ne[3]);
+
+    std::vector<uint32_t> params = {
+        (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, scale) / s_ts),
+        per_expert ? (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, ids) / ggml_type_size(ids->type)) : 0,
+        (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)),
+        per_channel ? (uint32_t) (scale->nb[0] / s_ts) : 0,
+        per_expert ? (uint32_t) ((per_channel_expert ? scale->nb[1] : scale->nb[0]) / s_ts) : 0,
+        per_expert ? (uint32_t) (ids->nb[0] / ggml_type_size(ids->type)) : 0,
+        per_expert ? (uint32_t) (ids->nb[1] / ggml_type_size(ids->type)) : 0,
+        (uint32_t) (dst->nb[1] / ggml_type_size(dst->type)),
+        (uint32_t) (dst->nb[2] / ggml_type_size(dst->type)),
+        (uint32_t) (dst->nb[3] / ggml_type_size(dst->type)),
+        (uint32_t) dst->ne[0],
+        (uint32_t) dst->ne[1],
+        (uint32_t) dst->ne[2],
+        n_rows,
+    };
+
+    std::vector<wgpu::BindGroupEntry> entries;
+    entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, scale));
+    if (per_expert) {
+        entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, ids));
+    }
+    entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, entries.size(), dst));
+
+    uint32_t wg_x = 1;
+    uint32_t wg_y = 1;
+    compute_2d_workgroups(n_rows, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y);
+
+    return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
+}
+
+static webgpu_encoded_op ggml_webgpu_apply_mul_mat_scale(webgpu_context &  ctx,
+                                                         ggml_tensor *     dst,
+                                                         webgpu_encoded_op op) {
+    if (ggml_get_src_scale(dst, 0) == nullptr) {
+        return op;
+    }
+    webgpu_encoded_op scale_op = ggml_webgpu_mul_mat_scale(ctx, dst);
+    op.num_kernels += scale_op.num_kernels;
+#ifdef GGML_WEBGPU_GPU_PROFILE
+    op.pipeline_names.insert(op.pipeline_names.end(), scale_op.pipeline_names.begin(), scale_op.pipeline_names.end());
+#endif
+    return op;
+}
+
 struct ggml_webgpu_flash_attn_op {
     ggml_webgpu_shader_lib_context    shader_lib_ctx = {};
     std::vector<uint32_t>             params;
@@ -3788,9 +3854,9 @@ static std::optional<webgpu_encoded_op> ggml_webgpu_encode(webgpu_context ctx,
         case GGML_OP_GET_ROWS:
             return ggml_webgpu_get_rows(ctx, src0, src1, node);
         case GGML_OP_MUL_MAT:
-            return ggml_webgpu_mul_mat(ctx, src0, src1, node);
+            return ggml_webgpu_apply_mul_mat_scale(ctx, node, ggml_webgpu_mul_mat(ctx, src0, src1, node));
         case GGML_OP_MUL_MAT_ID:
-            return ggml_webgpu_mul_mat_id(ctx, src0, src1, src2, node);
+            return ggml_webgpu_apply_mul_mat_scale(ctx, node, ggml_webgpu_mul_mat_id(ctx, src0, src1, src2, node));
         case GGML_OP_FLASH_ATTN_EXT:
             return ggml_webgpu_flash_attn(ctx, src0, src1, src2, node->src[3], node->src[4], node);
         case GGML_OP_ADD:
@@ -5054,10 +5120,6 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const
     ggml_tensor * src1 = op->src[1];
     ggml_tensor * src2 = op->src[2];

-    if (ggml_get_src_scale(op, 0)) {
-        return false;
-    }
-
     // on smaller devices (or CI), tensors may be larger than the max storage buffer size
     if (ggml_nbytes(op) > ctx->webgpu_global_ctx->capabilities.limits.maxStorageBufferBindingSize ||
         (src0 != nullptr &&
diff --git a/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_id.wgsl b/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_id.wgsl
index a3c25f656..685c35b2a 100644
--- a/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_id.wgsl
+++ b/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_id.wgsl
@@ -6,14 +6,14 @@ enable f16;
 #include "mul_mat_decls.tmpl"

 #ifdef VEC
-fn store_val(acc: array<array<f16, TILE_M>, TILE_N>, tn: u32, tm: u32) -> vec4<f32> {
-    return vec4<f32>(f32(acc[tn][tm]), f32(acc[tn][tm + 1]), f32(acc[tn][tm + 2]), f32(acc[tn][tm + 3]));
+fn store_val(acc: array<array<f32, TILE_M>, TILE_N>, tn: u32, tm: u32) -> vec4<f32> {
+    return vec4<f32>(acc[tn][tm], acc[tn][tm + 1], acc[tn][tm + 2], acc[tn][tm + 3]);
 }
 #endif

 #ifdef SCALAR
-fn store_val(acc: array<array<f16, TILE_M>, TILE_N>, tn: u32, tm: u32) -> f32 {
-    return f32(acc[tn][tm]);
+fn store_val(acc: array<array<f32, TILE_M>, TILE_N>, tn: u32, tm: u32) -> f32 {
+    return acc[tn][tm];
 }
 #endif

@@ -125,7 +125,7 @@ fn main(@builtin(workgroup_id) wg_id: vec3<u32>,
     let dst2_stride = params.m * params.n_expert_used;
     let dst1_stride = params.m;

-    var acc: array<array<f16, TILE_M>, TILE_N>;
+    var acc: array<array<f32, TILE_M>, TILE_N>;

     for (var k_outer = 0u; k_outer < params.k; k_outer += TILE_K) {

@@ -151,7 +151,7 @@ fn main(@builtin(workgroup_id) wg_id: vec3<u32>,
                     let src1_idx = src1_n * TILE_K + k_inner;
                     let src1_val = shmem[TILE_SRC0_SHMEM + src1_idx];
                     for (var tm = 0u; tm < TILE_M; tm++) {
-                        acc[tn][tm] += src0_tile[tm] * src1_val;
+                        acc[tn][tm] += f32(src0_tile[tm]) * f32(src1_val);
                     }
                 }
             }
diff --git a/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_scale.wgsl b/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_scale.wgsl
new file mode 100644
index 000000000..c679f4475
--- /dev/null
+++ b/ggml/src/ggml-webgpu/wgsl-shaders/mul_mat_scale.wgsl
@@ -0,0 +1,65 @@
+struct Params {
+    offset_scale: u32,
+    offset_ids: u32,
+    offset_dst: u32,
+
+    s_nb0: u32,
+    s_nb1: u32,
+    ids_nb0: u32,
+    ids_nb1: u32,
+
+    nb1: u32,
+    nb2: u32,
+    nb3: u32,
+
+    ne0: u32,
+    ne1: u32,
+    ne2: u32,
+    n_rows: u32,
+};
+
+@group(0) @binding(0) var<storage, read_write> scale: array<f32>;
+
+#ifdef USE_IDS
+
+@group(0) @binding(1) var<storage, read_write> ids: array<i32>;
+@group(0) @binding(2) var<storage, read_write> dst: array<f32>;
+@group(0) @binding(3) var<uniform> params: Params;
+
+#else
+
+@group(0) @binding(1) var<storage, read_write> dst: array<f32>;
+@group(0) @binding(2) var<uniform> params: Params;
+
+#endif
+
+@compute @workgroup_size(WG_SIZE)
+fn main(@builtin(workgroup_id) wg_id: vec3<u32>,
+        @builtin(num_workgroups) num_wg: vec3<u32>,
+        @builtin(local_invocation_id) local_id: vec3<u32>) {
+
+    let row = wg_id.x + wg_id.y * num_wg.x;
+    if (row >= params.n_rows) {
+        return;
+    }
+
+    let i1 = row % params.ne1;
+    let i2 = (row / params.ne1) % params.ne2;
+    let i3 = row / (params.ne1 * params.ne2);
+
+    var scale_row = params.offset_scale;
+
+#ifdef USE_IDS
+    let expert = ids[params.offset_ids + i1 * params.ids_nb0 + i2 * params.ids_nb1];
+    if (expert < 0) {
+        return;
+    }
+    scale_row += u32(expert) * params.s_nb1;
+#endif
+
+    let dst_row = params.offset_dst + i1 * params.nb1 + i2 * params.nb2 + i3 * params.nb3;
+
+    for (var i0 = local_id.x; i0 < params.ne0; i0 += WG_SIZE) {
+        dst[dst_row + i0] = dst[dst_row + i0] * scale[scale_row + i0 * params.s_nb0];
+    }
+}