From 14c5c3cab99a1570bac74a94ba637be83a3b8b8f Mon Sep 17 00:00:00 2001 From: Julian Ng-Thow-Hing Date: Wed, 24 Jun 2026 13:16:21 -0700 Subject: [PATCH 1/2] [ExecuTorch][WebGPU] q4gsw: route M==1 decode to a cooperative GEMV MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pull Request resolved: https://github.com/pytorch/executorch/pull/20457 Add optimized GEMV kernel for M==1 decode path in q4gsw quantized-linear. **Problem**: The register-tiled GEMM (from D109250327) wastes 75% of each 4×N tile when M=1, as only 1 of 4 rows is used. **Solution**: Add a cooperative GEMV kernel that routes M==1 decode to a more efficient path: - **GEMV**: 64 lanes per workgroup cooperate over K-dimension, each lane loads u32 words (8 K-values), reduces via shared memory - **GEMM**: M>1 prefill continues using the tiled GEMM **Routing Logic** (build-time selection, M is static per graph): - Use GEMV when: M==1 && K%8==0 && group_size%8==0 - Otherwise: Fall back to tiled GEMM **Constraints**: - K%8==0: Kernel loads 8 K-values per u32 word - group_size%8==0: Ensures no quantization-group boundary splits a word (validated via CPU cross-check) - Llama models (group_size=32/64) satisfy both constraints **Implementation**: - New kernel: q4gsw_linear_coop4.wgsl (fixed 64-lane workgroup) - New utility: clamp_workgroup_count() for grid-stride dispatch (vs compute_1d_workgroup_count which throws) - Shared infrastructure: Same bind layout, Params, weight format **Performance**: Keeps decode at measured bandwidth plateau, avoids M=1 tile waste. GEMV uses different reduction order (agrees to fp-rounding, not bit-exact). ghstack-source-id: 396677650 @exported-using-ghexport Differential Revision: [D109250570](https://our.internmc.facebook.com/intern/diff/D109250570/) --- backends/webgpu/runtime/WebGPUUtils.h | 12 ++ .../ops/quantized_linear/QuantizedLinear.cpp | 49 +++++--- .../quantized_linear/q4gsw_linear_coop4.wgsl | 87 ++++++++++++++ .../q4gsw_linear_coop4_wgsl.h | 111 ++++++++++++++++++ 4 files changed, 244 insertions(+), 15 deletions(-) create mode 100644 backends/webgpu/runtime/ops/quantized_linear/q4gsw_linear_coop4.wgsl create mode 100644 backends/webgpu/runtime/ops/quantized_linear/q4gsw_linear_coop4_wgsl.h diff --git a/backends/webgpu/runtime/WebGPUUtils.h b/backends/webgpu/runtime/WebGPUUtils.h index 293ad495be2..c5c779ffd5e 100644 --- a/backends/webgpu/runtime/WebGPUUtils.h +++ b/backends/webgpu/runtime/WebGPUUtils.h @@ -76,4 +76,16 @@ make_uniform(WGPUDevice device, const void* data, size_t size) { return buf; } +// Clamp a 1D workgroup count to the device limit, for grid-stride kernels that +// loop over any excess work (vs compute_1d_workgroup_count, which throws). +inline uint32_t clamp_workgroup_count(WGPUDevice device, uint32_t desired) { + WGPULimits limits = {}; + uint32_t max_count = + wgpuDeviceGetLimits(device, &limits) == WGPUStatus_Success && + limits.maxComputeWorkgroupsPerDimension > 0 + ? limits.maxComputeWorkgroupsPerDimension + : 65535u; // WebGPU spec-default floor + return std::min(desired, max_count); +} + } // namespace executorch::backends::webgpu::utils diff --git a/backends/webgpu/runtime/ops/quantized_linear/QuantizedLinear.cpp b/backends/webgpu/runtime/ops/quantized_linear/QuantizedLinear.cpp index 89e722cdb9a..6da05ff2010 100644 --- a/backends/webgpu/runtime/ops/quantized_linear/QuantizedLinear.cpp +++ b/backends/webgpu/runtime/ops/quantized_linear/QuantizedLinear.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -89,18 +90,6 @@ void q4gsw_linear_impl(WebGPUGraph& graph, const std::vector& args) { "WebGPU linear_q4gsw: N*K_packed must be a multiple of 4 (u32-packed)"); } - // Register-tiled GEMM: one thread per TM x TN tile; validate before alloc. - const uint32_t wg_size = - utils::clamp_workgroup_size(device, kQ4gswLinearWorkgroupSizeX); - const int64_t total_tiles = utils::div_up(M, kQ4gswTileM) * - utils::div_up(N, kQ4gswTileN); - if (total_tiles > static_cast(UINT32_MAX)) { - throw std::runtime_error( - "WebGPU linear_q4gsw: tile count exceeds the 1D dispatch limit"); - } - const uint32_t workgroup_count = utils::compute_1d_workgroup_count( - device, static_cast(total_tiles), wg_size, "linear_q4gsw"); - // fp32-only byte-size guards (no runtime dtype); fp16 scales -> bail. const uint64_t scales_numel = static_cast(num_groups) * static_cast(padded_N); @@ -128,6 +117,35 @@ void q4gsw_linear_impl(WebGPUGraph& graph, const std::vector& args) { "WebGPU linear_q4gsw: scales dims too small for K/N"); } + // M==1 decode -> coop4 GEMV (needs K%8==0 && gs%8==0); else tiled GEMM. + const uint32_t wg_size = + utils::clamp_workgroup_size(device, kQ4gswLinearWorkgroupSizeX); + const bool use_gemv = (M == 1u && K % 8u == 0u && gs % 8u == 0u); + const char* shader_src = use_gemv ? kQ4gswLinearCoop4WGSL : kQ4gswLinearWGSL; + uint32_t workgroup_count; + if (use_gemv) { + // coop4: fixed 64 lanes, 1 workgroup per output, grid-strided over M*N. + const uint64_t outputs = + static_cast(M) * static_cast(N); + if (outputs == 0u || outputs > UINT32_MAX) { + throw std::runtime_error("WebGPU linear_q4gsw: M*N out of range"); + } + workgroup_count = + utils::clamp_workgroup_count(device, static_cast(outputs)); + if (workgroup_count == 0u) { + throw std::runtime_error("WebGPU linear_q4gsw: zero GEMV dispatch"); + } + } else { + const int64_t total_tiles = utils::div_up(M, kQ4gswTileM) * + utils::div_up(N, kQ4gswTileN); + if (total_tiles > static_cast(UINT32_MAX)) { + throw std::runtime_error( + "WebGPU linear_q4gsw: tile count exceeds the 1D dispatch limit"); + } + workgroup_count = utils::compute_1d_workgroup_count( + device, static_cast(total_tiles), wg_size, "linear_q4gsw"); + } + // Optional bias: real buffer if present, else a dummy for the fixed layout. uint32_t has_bias = 0; WGPUBuffer bias_buffer = nullptr; @@ -168,7 +186,7 @@ void q4gsw_linear_impl(WebGPUGraph& graph, const std::vector& args) { WGPUShaderSourceWGSL wgsl_desc = {}; wgsl_desc.chain.sType = WGPUSType_ShaderSourceWGSL; - wgsl_desc.code = {kQ4gswLinearWGSL, WGPU_STRLEN}; + wgsl_desc.code = {shader_src, WGPU_STRLEN}; WGPUShaderModuleDescriptor shader_desc = {}; shader_desc.nextInChain = &wgsl_desc.chain; WGPUShaderModule shader = wgpuDeviceCreateShaderModule(device, &shader_desc); @@ -206,8 +224,9 @@ void q4gsw_linear_impl(WebGPUGraph& graph, const std::vector& args) { pipeline_desc.layout = pipeline_layout; pipeline_desc.compute.module = shader; pipeline_desc.compute.entryPoint = {"main", WGPU_STRLEN}; - pipeline_desc.compute.constantCount = 1; - pipeline_desc.compute.constants = &wg_size_constant; + // coop4 GEMV uses fixed @workgroup_size(64); only the GEMM has an override. + pipeline_desc.compute.constantCount = use_gemv ? 0u : 1u; + pipeline_desc.compute.constants = use_gemv ? nullptr : &wg_size_constant; WGPUComputePipeline pipeline = wgpuDeviceCreateComputePipeline(device, &pipeline_desc); diff --git a/backends/webgpu/runtime/ops/quantized_linear/q4gsw_linear_coop4.wgsl b/backends/webgpu/runtime/ops/quantized_linear/q4gsw_linear_coop4.wgsl new file mode 100644 index 00000000000..af6f661279d --- /dev/null +++ b/backends/webgpu/runtime/ops/quantized_linear/q4gsw_linear_coop4.wgsl @@ -0,0 +1,87 @@ +@group(0) @binding(0) var t_out: array; +@group(0) @binding(1) var t_input: array; +@group(0) @binding(2) var t_weight: array; +@group(0) @binding(3) var t_scales: array; +@group(0) @binding(4) var t_bias: array; + +struct Params { + M: u32, + N: u32, + K: u32, + K_packed: u32, + group_size: u32, + padded_N: u32, + has_bias: u32, + _pad: u32, +} +@group(0) @binding(5) var params: Params; + +// Cooperative-over-K GEMV with u32-batched coalesced weight loads (64 lanes). +const WG: u32 = 64u; +var partial: array; + +@compute @workgroup_size(WG, 1, 1) +fn main( + @builtin(workgroup_id) wid: vec3, + @builtin(num_workgroups) ngrp: vec3, + @builtin(local_invocation_id) lid: vec3) { + let total = params.M * params.N; + let stride = ngrp.x; + let num_words = params.K >> 3u; // K / 8 words per row + let row_words = params.K_packed >> 2u; // u32s per weight row (= K/8) + var idx = wid.x; + loop { + if (idx >= total) { + break; + } + let m = idx / params.N; + let n = idx % params.N; + let in_base = m * params.K; + let wbase = n * row_words; + + var acc: f32 = 0.0; + var w: u32 = lid.x; + loop { + if (w >= num_words) { + break; + } + let word = t_weight[wbase + w]; + let k0 = w << 3u; // first K of this word + let scale = t_scales[(k0 / params.group_size) * params.padded_N + n]; + let ib = in_base + k0; + // 4 bytes, low+high nibble each -> 8 consecutive K. + for (var bi: u32 = 0u; bi < 4u; bi = bi + 1u) { + let byte = (word >> (bi * 8u)) & 0xFFu; + let lo = f32(i32(byte & 0x0Fu) - 8); + let hi = f32(i32((byte >> 4u) & 0x0Fu) - 8); + let kk = bi << 1u; + acc = acc + t_input[ib + kk] * lo * scale; + acc = acc + t_input[ib + kk + 1u] * hi * scale; + } + w = w + WG; + } + + partial[lid.x] = acc; + workgroupBarrier(); + var s: u32 = WG >> 1u; + loop { + if (s == 0u) { + break; + } + if (lid.x < s) { + partial[lid.x] = partial[lid.x] + partial[lid.x + s]; + } + workgroupBarrier(); + s = s >> 1u; + } + if (lid.x == 0u) { + var o = partial[0]; + if (params.has_bias != 0u) { + o = o + t_bias[n]; + } + t_out[idx] = o; + } + workgroupBarrier(); + idx = idx + stride; + } +} diff --git a/backends/webgpu/runtime/ops/quantized_linear/q4gsw_linear_coop4_wgsl.h b/backends/webgpu/runtime/ops/quantized_linear/q4gsw_linear_coop4_wgsl.h new file mode 100644 index 00000000000..7bacedfcb17 --- /dev/null +++ b/backends/webgpu/runtime/ops/quantized_linear/q4gsw_linear_coop4_wgsl.h @@ -0,0 +1,111 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +namespace executorch::backends::webgpu { + +// @generated from q4gsw_linear_coop4.wgsl - DO NOT EDIT. +// wgsl-sha256: 3031886e68c375e617dfb263da39c492c6de4d8c1fb4073d70b18823a3e6a4fe +inline constexpr const char* kQ4gswLinearCoop4WGSL = R"( +@group(0) @binding(0) var t_out: array; +@group(0) @binding(1) var t_input: array; +@group(0) @binding(2) var t_weight: array; +@group(0) @binding(3) var t_scales: array; +@group(0) @binding(4) var t_bias: array; + +struct Params { + M: u32, + N: u32, + K: u32, + K_packed: u32, + group_size: u32, + padded_N: u32, + has_bias: u32, + _pad: u32, +} +@group(0) @binding(5) var params: Params; + +// Cooperative-over-K GEMV with u32-batched coalesced weight loads (64 lanes). +const WG: u32 = 64u; +var partial: array; + +@compute @workgroup_size(WG, 1, 1) +fn main( + @builtin(workgroup_id) wid: vec3, + @builtin(num_workgroups) ngrp: vec3, + @builtin(local_invocation_id) lid: vec3) { + let total = params.M * params.N; + let stride = ngrp.x; + let num_words = params.K >> 3u; // K / 8 words per row + let row_words = params.K_packed >> 2u; // u32s per weight row (= K/8) + var idx = wid.x; + loop { + if (idx >= total) { + break; + } + let m = idx / params.N; + let n = idx % params.N; + let in_base = m * params.K; + let wbase = n * row_words; + + var acc: f32 = 0.0; + var w: u32 = lid.x; + loop { + if (w >= num_words) { + break; + } + let word = t_weight[wbase + w]; + let k0 = w << 3u; // first K of this word + let scale = t_scales[(k0 / params.group_size) * params.padded_N + n]; + let ib = in_base + k0; + // 4 bytes, low+high nibble each -> 8 consecutive K. + for (var bi: u32 = 0u; bi < 4u; bi = bi + 1u) { + let byte = (word >> (bi * 8u)) & 0xFFu; + let lo = f32(i32(byte & 0x0Fu) - 8); + let hi = f32(i32((byte >> 4u) & 0x0Fu) - 8); + let kk = bi << 1u; + acc = acc + t_input[ib + kk] * lo * scale; + acc = acc + t_input[ib + kk + 1u] * hi * scale; + } + w = w + WG; + } + + partial[lid.x] = acc; + workgroupBarrier(); + var s: u32 = WG >> 1u; + loop { + if (s == 0u) { + break; + } + if (lid.x < s) { + partial[lid.x] = partial[lid.x] + partial[lid.x + s]; + } + workgroupBarrier(); + s = s >> 1u; + } + if (lid.x == 0u) { + var o = partial[0]; + if (params.has_bias != 0u) { + o = o + t_bias[n]; + } + t_out[idx] = o; + } + workgroupBarrier(); + idx = idx + stride; + } +} +)"; + +inline constexpr uint32_t kQ4gswLinearCoop4WorkgroupSizeX = 64; +inline constexpr uint32_t kQ4gswLinearCoop4WorkgroupSizeY = 1; +inline constexpr uint32_t kQ4gswLinearCoop4WorkgroupSizeZ = 1; + +} // namespace executorch::backends::webgpu From ab74ef0256df5d560afe230c6bd4f08a3835a424 Mon Sep 17 00:00:00 2001 From: Julian Ng-Thow-Hing Date: Wed, 24 Jun 2026 13:16:21 -0700 Subject: [PATCH 2/2] [ExecuTorch][WebGPU] rms_norm: add a vec4 kernel for 4-aligned row widths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pull Request resolved: https://github.com/pytorch/executorch/pull/20458 Add optimized vec4 kernel for bandwidth-bound rms_norm on Llama decode. **Problem**: Scalar kernel loads one element per lane per iteration — bandwidth-limited on Llama decode. **Solution**: Add vec4 kernel that loads/stores four contiguous elements as `vec4` and squares them with `dot(v, v)`, cutting loop iterations 4× and widening memory transactions. **Routing Logic**: - Use vec4 when: row_width % 4 == 0 - Otherwise: Fall back to scalar kernel **Constraints**: - row_width % 4 == 0: vec4 kernel has no partial-texel tail handling - Llama models (all hidden sizes 4-aligned) satisfy constraint **Implementation**: - New kernel: rms_norm_vec4.wgsl (same 64-lane workgroup) - Shared infrastructure: Same bind layout, Params, dispatch - Numerical: Float reassociation differs, not bit-identical to scalar **Performance**: ~33% faster on Apple M4 Pro / Metal across benchmark shapes (largest on decode, smallest on long prefill where already bandwidth-bound). This change was authored with assistance from Claude. ghstack-source-id: 396677654 @exported-using-ghexport Differential Revision: [D109333390](https://our.internmc.facebook.com/intern/diff/D109333390/) --- .../webgpu/runtime/ops/rms_norm/RmsNorm.cpp | 13 ++- .../runtime/ops/rms_norm/rms_norm_vec4.wgsl | 74 ++++++++++++++ .../runtime/ops/rms_norm/rms_norm_vec4_wgsl.h | 98 +++++++++++++++++++ backends/webgpu/test/op_tests/cases.py | 2 +- backends/webgpu/test/op_tests/test_schema.py | 2 +- .../webgpu/test/ops/rms_norm/test_rms_norm.py | 1 + 6 files changed, 187 insertions(+), 3 deletions(-) create mode 100644 backends/webgpu/runtime/ops/rms_norm/rms_norm_vec4.wgsl create mode 100644 backends/webgpu/runtime/ops/rms_norm/rms_norm_vec4_wgsl.h diff --git a/backends/webgpu/runtime/ops/rms_norm/RmsNorm.cpp b/backends/webgpu/runtime/ops/rms_norm/RmsNorm.cpp index 7de83330810..e73c6e23a88 100644 --- a/backends/webgpu/runtime/ops/rms_norm/RmsNorm.cpp +++ b/backends/webgpu/runtime/ops/rms_norm/RmsNorm.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -92,10 +93,17 @@ void rms_norm_impl(WebGPUGraph& graph, const std::vector& args) { graph.add_uniform_buffer_bytes(sizeof(RmsNormParams)); + // Select the vec4 kernel when the row width is a multiple of 4 (every Llama + // hidden size qualifies); fall back to the scalar kernel otherwise. The two + // kernels are equivalent up to floating-point reassociation (the vec4 + // reduction reorders the sum, so not bit-identical) and share the same bind + // group + dispatch. + const bool use_vec4 = (row_width % 4u == 0u); + // Create shader module from built-in WGSL source WGPUShaderSourceWGSL wgsl_desc = {}; wgsl_desc.chain.sType = WGPUSType_ShaderSourceWGSL; - wgsl_desc.code = {kRmsNormWGSL, WGPU_STRLEN}; + wgsl_desc.code = {use_vec4 ? kRmsNormVec4WGSL : kRmsNormWGSL, WGPU_STRLEN}; WGPUShaderModuleDescriptor shader_desc = {}; shader_desc.nextInChain = &wgsl_desc.chain; @@ -176,6 +184,9 @@ void rms_norm_impl(WebGPUGraph& graph, const std::vector& args) { static_assert( kRmsNormWorkgroupSizeX == 64, "must match @workgroup_size and WG_SIZE in rms_norm.wgsl"); + static_assert( + kRmsNormVec4WorkgroupSizeX == 64, + "must match @workgroup_size and WG_SIZE in rms_norm_vec4.wgsl"); graph.add_dispatch({pipeline, bind_group, num_rows}); // Release intermediate objects (pipeline and bind_group are kept by dispatch) diff --git a/backends/webgpu/runtime/ops/rms_norm/rms_norm_vec4.wgsl b/backends/webgpu/runtime/ops/rms_norm/rms_norm_vec4.wgsl new file mode 100644 index 00000000000..c2f731e5f60 --- /dev/null +++ b/backends/webgpu/runtime/ops/rms_norm/rms_norm_vec4.wgsl @@ -0,0 +1,74 @@ +@group(0) @binding(0) var t_out: array>; +@group(0) @binding(1) var t_in: array>; +@group(0) @binding(2) var t_weight: array>; + +struct Params { + num_rows: u32, + row_width: u32, + epsilon: f32, + _pad: u32, +} +@group(0) @binding(3) var params: Params; + +const WG_SIZE: u32 = 64u; + +var shared_sum: array; + +fn reduce_shared(worker_id: u32) { + workgroupBarrier(); + var stride: u32 = WG_SIZE / 2u; + loop { + if (stride == 0u) { + break; + } + if (worker_id < stride) { + shared_sum[worker_id] = shared_sum[worker_id] + shared_sum[worker_id + stride]; + } + workgroupBarrier(); + stride = stride >> 1u; + } +} + +// vec4 variant of rms_norm: each lane strides by WG_SIZE over rw4 = row_width/4 +// texels and accumulates dot(v, v). row_width is the ELEMENT count, so mean_sq +// divides by it (not rw4). The host selects this only when row_width % 4 == 0. +@compute @workgroup_size(64, 1, 1) +fn main( + @builtin(workgroup_id) wid: vec3, + @builtin(local_invocation_id) lid: vec3) { + let row_idx = wid.x; + let worker_id = lid.x; + + if (row_idx >= params.num_rows) { + return; + } + + let rw4 = params.row_width / 4u; + let base4 = row_idx * rw4; + + var local_sq_sum: f32 = 0.0; + var x4: u32 = worker_id; + loop { + if (x4 >= rw4) { + break; + } + let v = t_in[base4 + x4]; + local_sq_sum = local_sq_sum + dot(v, v); + x4 = x4 + WG_SIZE; + } + + shared_sum[worker_id] = local_sq_sum; + reduce_shared(worker_id); + + let mean_sq = shared_sum[0] / f32(params.row_width); + let rstd = inverseSqrt(mean_sq + params.epsilon); + + x4 = worker_id; + loop { + if (x4 >= rw4) { + break; + } + t_out[base4 + x4] = t_in[base4 + x4] * rstd * t_weight[x4]; + x4 = x4 + WG_SIZE; + } +} diff --git a/backends/webgpu/runtime/ops/rms_norm/rms_norm_vec4_wgsl.h b/backends/webgpu/runtime/ops/rms_norm/rms_norm_vec4_wgsl.h new file mode 100644 index 00000000000..633bf3adfc0 --- /dev/null +++ b/backends/webgpu/runtime/ops/rms_norm/rms_norm_vec4_wgsl.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +namespace executorch::backends::webgpu { + +// @generated from rms_norm_vec4.wgsl - DO NOT EDIT. +// wgsl-sha256: 4c0ba56708bf125a7ec6ea3c51d1288e05ac00a8e2cfa10e38e9a208e230b8df +inline constexpr const char* kRmsNormVec4WGSL = R"( +@group(0) @binding(0) var t_out: array>; +@group(0) @binding(1) var t_in: array>; +@group(0) @binding(2) var t_weight: array>; + +struct Params { + num_rows: u32, + row_width: u32, + epsilon: f32, + _pad: u32, +} +@group(0) @binding(3) var params: Params; + +const WG_SIZE: u32 = 64u; + +var shared_sum: array; + +fn reduce_shared(worker_id: u32) { + workgroupBarrier(); + var stride: u32 = WG_SIZE / 2u; + loop { + if (stride == 0u) { + break; + } + if (worker_id < stride) { + shared_sum[worker_id] = shared_sum[worker_id] + shared_sum[worker_id + stride]; + } + workgroupBarrier(); + stride = stride >> 1u; + } +} + +// vec4 variant of rms_norm: each lane strides by WG_SIZE over rw4 = row_width/4 +// texels and accumulates dot(v, v). row_width is the ELEMENT count, so mean_sq +// divides by it (not rw4). The host selects this only when row_width % 4 == 0. +@compute @workgroup_size(64, 1, 1) +fn main( + @builtin(workgroup_id) wid: vec3, + @builtin(local_invocation_id) lid: vec3) { + let row_idx = wid.x; + let worker_id = lid.x; + + if (row_idx >= params.num_rows) { + return; + } + + let rw4 = params.row_width / 4u; + let base4 = row_idx * rw4; + + var local_sq_sum: f32 = 0.0; + var x4: u32 = worker_id; + loop { + if (x4 >= rw4) { + break; + } + let v = t_in[base4 + x4]; + local_sq_sum = local_sq_sum + dot(v, v); + x4 = x4 + WG_SIZE; + } + + shared_sum[worker_id] = local_sq_sum; + reduce_shared(worker_id); + + let mean_sq = shared_sum[0] / f32(params.row_width); + let rstd = inverseSqrt(mean_sq + params.epsilon); + + x4 = worker_id; + loop { + if (x4 >= rw4) { + break; + } + t_out[base4 + x4] = t_in[base4 + x4] * rstd * t_weight[x4]; + x4 = x4 + WG_SIZE; + } +} +)"; + +inline constexpr uint32_t kRmsNormVec4WorkgroupSizeX = 64; +inline constexpr uint32_t kRmsNormVec4WorkgroupSizeY = 1; +inline constexpr uint32_t kRmsNormVec4WorkgroupSizeZ = 1; + +} // namespace executorch::backends::webgpu diff --git a/backends/webgpu/test/op_tests/cases.py b/backends/webgpu/test/op_tests/cases.py index 428c94d3066..febdbd507a8 100644 --- a/backends/webgpu/test/op_tests/cases.py +++ b/backends/webgpu/test/op_tests/cases.py @@ -37,7 +37,7 @@ RmsNormModule, ) -# rms_norm coverage is exactly the 14 cases the native test covered. +# rms_norm coverage is exactly the 15 cases the native test covered. RMS_NORM_CASES = _CASES diff --git a/backends/webgpu/test/op_tests/test_schema.py b/backends/webgpu/test/op_tests/test_schema.py index 9e62c9558cf..bcc03a40fd9 100644 --- a/backends/webgpu/test/op_tests/test_schema.py +++ b/backends/webgpu/test/op_tests/test_schema.py @@ -41,7 +41,7 @@ def test_add_rms_norm_registered(): assert {"add", "rms_norm"} <= set(op_test_registry) assert len(op_test_registry["add"].cases) >= 3 # regular/self/scalar/chained - # Exact parity, no hardcoded literal (real _CASES == 14; import so it can't drift): + # Exact parity, no hardcoded literal (real _CASES == 15; import so it can't drift): assert len(op_test_registry["rms_norm"].cases) == len(cases.RMS_NORM_CASES) # weight is a construction param, NOT a forward input: rms0 = op_test_registry["rms_norm"].cases[0] diff --git a/backends/webgpu/test/ops/rms_norm/test_rms_norm.py b/backends/webgpu/test/ops/rms_norm/test_rms_norm.py index d4f88de672a..57679d6d097 100644 --- a/backends/webgpu/test/ops/rms_norm/test_rms_norm.py +++ b/backends/webgpu/test/ops/rms_norm/test_rms_norm.py @@ -140,6 +140,7 @@ def _weight_zeros_neg(hidden: int) -> torch.Tensor: {"name": "distinct_rows", "shape": (1, 1, 5, 256), "input_fn": _distinct_rows}, {"name": "single_row", "shape": (1, 1, 1, 896)}, {"name": "mixed_sign", "shape": (1, 1, 4, 128), "input_fn": _mixed_sign}, + {"name": "llama_hidden_2048", "shape": (1, 1, 1, 2048)}, {"name": "large_4096", "shape": (1, 1, 1, 4096)}, {"name": "large_8192", "shape": (1, 1, 1, 8192)}, {