You are viewing a plain text version of this content. The canonical link for it is here.
Posted to discuss-archive@tvm.apache.org by "ksgr5566 (via GitHub)" <gi...@apache.org> on 2026/02/25 18:41:53 UTC

[PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

ksgr5566 opened a new pull request, #18823:
URL: https://github.com/apache/tvm/pull/18823

   ## Summary
   This adds gating logic on top of #17699 to support optional subgroup shuffle 
   primitives based on a compile-time flag.
   
   ## Problem
   The PR #17699 always generates subgroup shuffle ops when targeting WebGPU. 
   However, not all WebGPU devices support subgroups. We need a way to:
   - Default to shared memory reductions (universally compatible)
   - Optionally enable subgroup shuffles for devices that support them
   
   ## Solution
   Implement gating via TVM target parameter:
   - Default `thread_warp_size=1` disables warp reductions (uses shared memory + barriers)
   - Add target parser `UpdateWebGPUAttrs()` that sets `thread_warp_size=32` when `supports_subgroups=true`
   - Add `--enable-subgroups` CLI flag in mlc-llm to surface the option to users
   
   The gating happens at the reduction path selection level (`IsWarpReduction()` in 
   `lower_thread_allreduce.cc`), ensuring subgroup ops are never generated unless explicitly enabled.
   
   ## Changes
   - TVM: Target parser + default thread_warp_size=1
   - MLC-LLM: --enable-subgroups flag  (https://github.com/mlc-ai/mlc-llm/pull/3431)
   - WebLLM: WGSL shader dumping for verification
   
   ## Testing
   
   Tested with Llama-3.2-1B-q4f16_1. Baseline (no flag) uses shared memory reductions; 
   with flag, generates subgroupShuffle* ops.
   Both the generated WGSLs here: https://gist.github.com/ksgr5566/301664a5dda3e46f44092be4d09b2d4f


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "MasterJH5574 (via GitHub)" <gi...@apache.org>.
MasterJH5574 commented on code in PR #18823:
URL: https://github.com/apache/tvm/pull/18823#discussion_r2855228758


##########
src/s_tir/transform/lower_thread_allreduce.cc:
##########
@@ -510,7 +510,9 @@ class ThreadAllreduceBuilder final : public StmtExprMutator {
         //
         // The former may cause dead lock as there is a divergent
         // branch with a warp sync call inside.
-        PrimExpr other = WarpShuffle(builtin::tvm_warp_shuffle_down(), mask_buffer, val, offset);
+        bool cast_offset_to_uint = target_->kind->name == "webgpu";

Review Comment:
   For changes in `src/s_tir/transform/lower_thread_allreduce.cc`, could you please add a unit test in `tests/python/tir-transform/test_tir_transform_lower_thread_all_reduce.py` to test the expected behavior?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "MasterJH5574 (via GitHub)" <gi...@apache.org>.
MasterJH5574 commented on PR #18823:
URL: https://github.com/apache/tvm/pull/18823#issuecomment-4183796776

   @ksgr5566 @akaashrp And I have a question that, is "subgroup support" completely decided by a flag that users set when compile a kernel, or it can be automatically detected?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "ksgr5566 (via GitHub)" <gi...@apache.org>.
ksgr5566 commented on PR #18823:
URL: https://github.com/apache/tvm/pull/18823#issuecomment-4184080376

   > @ksgr5566 @akaashrp And I have a question that, is "subgroup support" completely decided by a flag that users set when compile a kernel, or it can be automatically detected?
   
   Subgroup support is decided by the user’s compile flag. Automatic device detection is not part of this compile path. It is only possible during WebGPU runtime in the browser, and WebGPU can then select the relevant compiled WASM.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "MasterJH5574 (via GitHub)" <gi...@apache.org>.
MasterJH5574 commented on code in PR #18823:
URL: https://github.com/apache/tvm/pull/18823#discussion_r3033144294


##########
src/target/target_kind.cc:
##########
@@ -427,8 +427,41 @@ TVM_REGISTER_TARGET_KIND("vulkan", kDLVulkan)
     // Tags
     .set_default_keys({"vulkan", "gpu"});
 
+/*!
+ * \brief Update WebGPU target attributes for subgroup-enabled lowering.
+ * Runtime routing on the WebLLM side guarantees subgroup size == 32.
+ * Runtime routing on the WebLLM side guarantees
+ * maxComputeInvocationsPerWorkgroup >= 1024.
+ * This is intentionally constrained for the subgroup-enabled WASM variant.
+ * When supports_subgroups is true, canonicalize thread_warp_size to 32 so
+ * TIR lowering can emit subgroup shuffle reductions.
+ */
+ffi::Map<ffi::String, ffi::Any> UpdateWebGPUAttrs(ffi::Map<ffi::String, ffi::Any> target) {

Review Comment:
   Can we move this function to line ~258, since we have a lot of UpdateXXXAttrs there?



##########
web/emcc/webgpu_runtime.cc:
##########
@@ -40,6 +40,8 @@
 #include "../../src/runtime/metadata.h"
 #include "../../src/runtime/workspace_pool.h"
 #include "../../src/support/bytes_io.h"
+#include "3rdparty/tvm-ffi/src/ffi/extra/json_parser.cc"
+#include "3rdparty/tvm-ffi/src/ffi/extra/json_writer.cc"

Review Comment:
   Just curious: are these two lines related to this PR, or they are for some other purpose?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "MasterJH5574 (via GitHub)" <gi...@apache.org>.
MasterJH5574 commented on PR #18823:
URL: https://github.com/apache/tvm/pull/18823#issuecomment-3961799186

   Also there are failing tests. Please take a look and resolve them.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "ksgr5566 (via GitHub)" <gi...@apache.org>.
ksgr5566 commented on code in PR #18823:
URL: https://github.com/apache/tvm/pull/18823#discussion_r2870109063


##########
src/target/target_kind.cc:
##########
@@ -424,8 +424,27 @@ TVM_REGISTER_TARGET_KIND("vulkan", kDLVulkan)
     // Tags
     .set_default_keys({"vulkan", "gpu"});
 
+/*!
+ * \brief Update WebGPU target attributes based on subgroup support.
+ * When supports_subgroups is true, set thread_warp_size to 32 so that
+ * TIR lowering uses warp-level shuffle reductions instead of shared memory.
+ */
+TargetJSON UpdateWebGPUAttrs(TargetJSON target) {
+  if (target.count("supports_subgroups")) {
+    bool subgroups = Downcast<Bool>(target.at("supports_subgroups"));
+    if (subgroups) {
+      target.Set("thread_warp_size", int64_t(32));
+    }
+  }
+  return target;
+}
+
 TVM_REGISTER_TARGET_KIND("webgpu", kDLWebGPU)
     .add_attr_option<int64_t>("max_num_threads", 256)
+    .add_attr_option<bool>("supports_subgroups", false)
+    // thread_warp_size=1: is_subwarp_reduction and is_multiwarp_reduction returns false, so no subgroup ops are emitted.
+    .add_attr_option<int64_t>("thread_warp_size", 1)
+    .set_target_parser(UpdateWebGPUAttrs)
     .set_default_keys({"webgpu", "gpu"});

Review Comment:
   added



##########
src/target/target_kind.cc:
##########
@@ -424,8 +424,27 @@ TVM_REGISTER_TARGET_KIND("vulkan", kDLVulkan)
     // Tags
     .set_default_keys({"vulkan", "gpu"});
 
+/*!
+ * \brief Update WebGPU target attributes based on subgroup support.
+ * When supports_subgroups is true, set thread_warp_size to 32 so that
+ * TIR lowering uses warp-level shuffle reductions instead of shared memory.
+ */
+TargetJSON UpdateWebGPUAttrs(TargetJSON target) {
+  if (target.count("supports_subgroups")) {
+    bool subgroups = Downcast<Bool>(target.at("supports_subgroups"));
+    if (subgroups) {
+      target.Set("thread_warp_size", int64_t(32));
+    }

Review Comment:
   
   supports_subgroups flag is the single intentional entry point, and UpdateWebGPUAttrs already sets thread_warp_size=32 when it's true. Manually setting thread_warp_size without supports_subgroups isn't a supported configuration.



##########
src/target/source/codegen_webgpu.cc:
##########
@@ -118,7 +121,9 @@ void CodeGenWebGPU::InitFuncState(const PrimFunc& f) {
   }
 }
 
-CodeGenWebGPU::CodeGenWebGPU(Target target) : target_(target) {}
+CodeGenWebGPU::CodeGenWebGPU(Target target) : target_(target) {
+  enable_subgroups_ = target_->GetAttr<Bool>("supports_subgroups").value_or(Bool(false));

Review Comment:
   
   supports_subgroups flag is the single intentional entry point, and UpdateWebGPUAttrs already sets thread_warp_size=32 when it's true. Manually setting thread_warp_size without supports_subgroups isn't a supported configuration.



##########
src/s_tir/transform/lower_thread_allreduce.cc:
##########


Review Comment:
   CodeGenWebGPU::PrintType already handles this. I think adding one more check here is redundant.



##########
src/s_tir/transform/lower_thread_allreduce.cc:
##########
@@ -510,7 +510,9 @@ class ThreadAllreduceBuilder final : public StmtExprMutator {
         //
         // The former may cause dead lock as there is a divergent
         // branch with a warp sync call inside.
-        PrimExpr other = WarpShuffle(builtin::tvm_warp_shuffle_down(), mask_buffer, val, offset);
+        bool cast_offset_to_uint = target_->kind->name == "webgpu";

Review Comment:
   added



##########
src/target/source/codegen_webgpu.cc:
##########
@@ -120,7 +123,9 @@ void CodeGenWebGPU::InitFuncState(const PrimFunc& f) {
   }
 }
 
-CodeGenWebGPU::CodeGenWebGPU(Target target) : target_(target) {}
+CodeGenWebGPU::CodeGenWebGPU(Target target) : target_(target) {
+  enable_subgroups_ = target_->GetAttr<Bool>("supports_subgroups").value_or(Bool(false));

Review Comment:
   I added validation in UpdateWebGPUAttrs so that combination is rejected up front



##########
src/s_tir/transform/lower_thread_allreduce.cc:
##########
@@ -719,11 +723,11 @@ class ThreadAllreduceBuilder final : public StmtExprMutator {
   bool IsWarpReduction(const std::vector<DataType>& types, int group_extent, int reduce_extent,
                        int contiguous_reduce_extent) {
     if ((target_->kind->name != "cuda") && (target_->kind->name != "rocm") &&
-        (target_->kind->name != "metal")) {
+        (target_->kind->name != "metal") && (target_->kind->name != "webgpu")) {
       return false;
     }
 

Review Comment:
   Instead of adding another WebGPU-specific branch in here, I fixed the invariant at target construction in target_kind.cc. Now that target shape is rejected up front, so this scenario never comes up in lowering/codegen. I also added a test for that in test_target_target.py.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "ksgr5566 (via GitHub)" <gi...@apache.org>.
ksgr5566 commented on code in PR #18823:
URL: https://github.com/apache/tvm/pull/18823#discussion_r3033408551


##########
web/emcc/webgpu_runtime.cc:
##########
@@ -40,6 +40,8 @@
 #include "../../src/runtime/metadata.h"
 #include "../../src/runtime/workspace_pool.h"
 #include "../../src/support/bytes_io.h"
+#include "3rdparty/tvm-ffi/src/ffi/extra/json_parser.cc"
+#include "3rdparty/tvm-ffi/src/ffi/extra/json_writer.cc"

Review Comment:
   Without this I encountered a failure at at WebGPU runtime in the browser, when loading the compiled model WASM.
   
   Upon further digging I found that the break came from the refactor that replaced `dmlc::JSONWriter` with `tvm::ffi::json::Stringify` in `webgpu_runtime.cc`. dmlc was header-only, but `tvm::ffi::json` splits declaration and implementation, so in the WASM unity build the `Stringify` implementation was not compiled into the WebGPU runtime unit and showed up as a missing runtime symbol.
   
   These two includes are there to pull the JSON implementation into the same WASM compilation unit.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "akaashrp (via GitHub)" <gi...@apache.org>.
akaashrp commented on PR #18823:
URL: https://github.com/apache/tvm/pull/18823#issuecomment-4165773719

   cc @tqchen for review


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #18823:
URL: https://github.com/apache/tvm/pull/18823#issuecomment-3961251330

   ## Summary of Changes
   
   Hello @ksgr5566, I'm Gemini Code Assist[^1]! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
   
   This pull request enhances WebGPU support by introducing a flexible mechanism for utilizing subgroup shuffle primitives. Recognizing that not all WebGPU devices support subgroups, the changes ensure that shared memory reductions are used as a default, universally compatible approach. For devices that do support subgroups, a new target parameter (`supports_subgroups`) and an associated CLI flag (`--enable-subgroups` in MLC-LLM) allow for their optional activation, leading to potential performance improvements. This gating logic is applied at the reduction path selection level, preventing the generation of unsupported subgroup operations.
   
   ### Highlights
   
   * **Conditional Subgroup Shuffles**: Implemented gating logic to enable WebGPU subgroup shuffle primitives only when explicitly supported by the target device.
   * **Default to Shared Memory**: Ensured that shared memory reductions are used by default for universal compatibility across WebGPU devices.
   * **Target Parameter and CLI Flag**: Introduced a `supports_subgroups` target parameter and a corresponding `thread_warp_size` adjustment, along with a `--enable-subgroups` CLI flag in MLC-LLM, to allow users to opt-in to subgroup optimizations.
   
   🧠 **New Feature in Public Preview:** You can now enable **Memory** to help **Gemini Code Assist** learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. **Click [here](https://codeassist.google/code-review/login) to enable Memory in your admin console.**
   
   <details>
   <summary><b>Changelog</b></summary>
   
   * **src/target/source/codegen_webgpu.cc**
       * Enabled the `subgroups` WGSL extension in the generated header.
       * Initialized the `enable_subgroups_` flag based on target attributes.
   * **src/target/source/codegen_webgpu.h**
       * Added a boolean member `enable_subgroups_` to track subgroup support.
   * **src/target/source/intrin_rule_webgpu.cc**
       * Defined WebGPU-specific intrinsic rules to map generic `tvm_warp_shuffle` operations to `tir.webgpu.subgroup_shuffle` built-ins.
   * **src/target/target_kind.cc**
       * Implemented `UpdateWebGPUAttrs` to dynamically set `thread_warp_size` to 32 when `supports_subgroups` is true.
       * Registered new target attributes for WebGPU, including `supports_subgroups` and `thread_warp_size`.
   * **src/tir/transforms/lower_thread_allreduce.cc**
       * Modified the `WarpShuffle` function to conditionally cast the delta argument to `uint32` for WebGPU.
       * Extended `IsWarpReduction` to include WebGPU as a target for warp reductions, while disabling the warp shuffle mask for it.
   * **web/package-lock.json**
       * Updated various JavaScript package dependencies, including `@babel` components and `semver`.
   * **web/src/webgpu.ts**
       * Added logic to detect and request the `subgroups` feature when initializing a WebGPU adapter.
   </details>
   
   <details>
   <summary><b>Activity</b></summary>
   
   * No specific activity was provided in the context for this pull request.
   </details>
   
   <details>
   <summary><b>Using Gemini Code Assist</b></summary>
   <br>
   
   The full guide for Gemini Code Assist can be found on our [documentation page](https://developers.google.com/gemini-code-assist/docs/review-github-code), here are some quick tips.
   
   <b>Invoking Gemini</b>
   
   You can request assistance from Gemini at any point by creating a comment using either `/gemini <command>` or `@gemini-code-assist <command>`. Below is a summary of the supported commands on the current page.
   
   Feature | Command | Description
   --- | --- | ---
   Code Review | `/gemini review` | Performs a code review for the current pull request in its current state.
   Pull Request Summary | `/gemini summary` | Provides a summary of the current pull request in its current state.
   Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in pull request comments and review comments.
   Help | `/gemini help` | Displays a list of available commands.
   
   <b>Customization</b>
   
   To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a `.gemini/` folder in the base of the repository. Detailed instructions can be found [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github).
   
   <b>Limitations & Feedback</b>
   
   Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with :thumbsup: and :thumbsdown: on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up [here](https://google.qualtrics.com/jfe/form/SV_2cyuGuTWsEw84yG).
   
   <b>You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the [Gemini Code Assist IDE Extension](https://cloud.google.com/products/gemini/code-assist).</b>
   </details>
   
   
   [^1]: Review the [Privacy Notices](https://policies.google.com/privacy), [Generative AI Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy), [Terms of Service](https://policies.google.com/terms), and learn how to configure Gemini Code Assist in GitHub [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github). Gemini can make mistakes, so double check it and [use code with caution](https://support.google.com/legal/answer/13505487).
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "akaashrp (via GitHub)" <gi...@apache.org>.
akaashrp commented on PR #18823:
URL: https://github.com/apache/tvm/pull/18823#issuecomment-4180455126

   @MasterJH5574 would appreciate it if you could take a look. Thanks!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "akaashrp (via GitHub)" <gi...@apache.org>.
akaashrp commented on code in PR #18823:
URL: https://github.com/apache/tvm/pull/18823#discussion_r2916185667


##########
src/s_tir/transform/lower_thread_allreduce.cc:
##########


Review Comment:
   I think we should add a check of the following form here since WebGPU does not support f64, i64, or u64:
   ```
   if (target_->kind->name == "webgpu" &&
       std::any_of(types.begin(), types.end(), [](DataType ty) {
         if (ty.is_float() && ty.bits() > 32) return true;              // f64
         if ((ty.is_int() || ty.is_uint()) && ty.bits() > 32) return true;  // i64/u64
         return false;
       })) {
     return false;
   }
   
   ```



##########
src/target/target_kind.cc:
##########
@@ -427,8 +427,28 @@ TVM_REGISTER_TARGET_KIND("vulkan", kDLVulkan)
     // Tags
     .set_default_keys({"vulkan", "gpu"});
 
+/*!
+ * \brief Update WebGPU target attributes based on subgroup support.
+ * When supports_subgroups is true, set thread_warp_size to 32 so that
+ * TIR lowering uses warp-level shuffle reductions instead of shared memory.
+ */
+ffi::Map<ffi::String, ffi::Any> UpdateWebGPUAttrs(ffi::Map<ffi::String, ffi::Any> target) {
+  if (target.count("supports_subgroups")) {
+    bool subgroups = Downcast<Bool>(target.at("supports_subgroups"));
+    if (subgroups) {

Review Comment:
   Could you add a comment stating the following:
   1. Runtime routing on the WebLLM side guarantees subgroup size == 32
   2. Runtime routing on the WebLLM side guarantees maxComputeInvocationsPerWorkgroup >= 1024
   3. This is intentionally constrained for the subgroup-enabled WASM variant



##########
src/target/source/codegen_webgpu.cc:
##########
@@ -120,7 +123,9 @@ void CodeGenWebGPU::InitFuncState(const PrimFunc& f) {
   }
 }
 
-CodeGenWebGPU::CodeGenWebGPU(Target target) : target_(target) {}
+CodeGenWebGPU::CodeGenWebGPU(Target target) : target_(target) {
+  enable_subgroups_ = target_->GetAttr<Bool>("supports_subgroups").value_or(Bool(false));

Review Comment:
   Let's add the following check here:
   ```
   Bool supports_subgroups = target_->GetAttr<Bool>("supports_subgroups").value_or(Bool(false));
   int64_t thread_warp_size = target_->GetAttr<Integer>("thread_warp_size", 1).value()->value;
   if (thread_warp_size > 1 && !supports_subgroups) {
     LOG(FATAL) << "WebGPU target has thread_warp_size=" << thread_warp_size
                << " but supports_subgroups is false.";
   }
   enable_subgroups_ = supports_subgroups;
   ```



##########
src/s_tir/transform/lower_thread_allreduce.cc:
##########
@@ -719,11 +723,11 @@ class ThreadAllreduceBuilder final : public StmtExprMutator {
   bool IsWarpReduction(const std::vector<DataType>& types, int group_extent, int reduce_extent,
                        int contiguous_reduce_extent) {
     if ((target_->kind->name != "cuda") && (target_->kind->name != "rocm") &&
-        (target_->kind->name != "metal")) {
+        (target_->kind->name != "metal") && (target_->kind->name != "webgpu")) {
       return false;
     }
 

Review Comment:
   Add a check here of the following form:
   ```
   if (target_->kind->name == "webgpu" && !supports_subgroups_) {
     return false;
   }
   ```
   
   This is to avoid scenarios where a target such as `{"kind":"webgpu","thread_warp_size":32,"supports_subgroups":false}` would still emit subgroup ops, but the WGSL would not contain `enable subgroups;`.



##########
src/s_tir/transform/lower_thread_allreduce.cc:
##########
@@ -700,6 +700,10 @@ class ThreadAllreduceBuilder final : public StmtExprMutator {
   // Emit warp shuffle  calls.
   PrimExpr WarpShuffle(const Op& op, ffi::Optional<Buffer> mask_buffer, PrimExpr val,
                        PrimExpr delta_or_lane) {
+    // WebGPU's WGSL requires u32 for subgroupShuffle lane/delta arguments.

Review Comment:
   I believe you can move this to DispatchWebGPUShuffle by casting call->args[2] to UInt(32)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "MasterJH5574 (via GitHub)" <gi...@apache.org>.
MasterJH5574 commented on PR #18823:
URL: https://github.com/apache/tvm/pull/18823#issuecomment-4183756352

   BTW just a quick note.  @ksgr5566 you can resolve all addressed comments, which helps make the PR page cleaner.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "akaashrp (via GitHub)" <gi...@apache.org>.
akaashrp commented on PR #18823:
URL: https://github.com/apache/tvm/pull/18823#issuecomment-4194259593

   @MasterJH5574 comments should be fixed now. Just to add to what @ksgr5566 said, automatic device detection is not really possible since browser limits and features are only observed during runtime. The best we can do at the moment is to compile separate WASMs depending on capabilities and route in WebLLM or the tvm/web runtime depending on browser limits. For now, we prefer to route in WebLLM to avoid enforcing subgroup-enabled WASMs on users until we get better speedups. 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #18823:
URL: https://github.com/apache/tvm/pull/18823#discussion_r2854736683


##########
src/tir/transforms/lower_thread_allreduce.cc:
##########
@@ -717,11 +722,11 @@ class ThreadAllreduceBuilder final : public StmtExprMutator {
   bool IsWarpReduction(const std::vector<DataType>& types, int group_extent, int reduce_extent,
                        int contiguous_reduce_extent) {
     if ((target_->kind->name != "cuda") && (target_->kind->name != "rocm") &&
-        (target_->kind->name != "metal")) {
+        (target_->kind->name != "metal") && (target_->kind->name != "webgpu")) {
       return false;
     }
 
-    need_warp_shuffle_mask_ = target_->kind->name != "metal";
+    need_warp_shuffle_mask_ = target_->kind->name != "metal" && target_->kind->name != "webgpu";

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   To improve maintainability, consider using `std::unordered_set` for checking the target kind. This makes it easier to add or remove supported targets in the future.
   
   ```suggestion
       const std::unordered_set<std::string> supported_targets = {"cuda", "rocm", "metal", "webgpu"};
       if (!supported_targets.count(target_->kind->name)) {
         return false;
       }
   
       const std::unordered_set<std::string> no_mask_targets = {"metal", "webgpu"};
       need_warp_shuffle_mask_ = !no_mask_targets.count(target_->kind->name);
   ```



##########
src/target/target_kind.cc:
##########
@@ -424,8 +424,27 @@ TVM_REGISTER_TARGET_KIND("vulkan", kDLVulkan)
     // Tags
     .set_default_keys({"vulkan", "gpu"});
 
+/*!
+ * \brief Update WebGPU target attributes based on subgroup support.
+ * When supports_subgroups is true, set thread_warp_size to 32 so that
+ * TIR lowering uses warp-level shuffle reductions instead of shared memory.
+ */
+TargetJSON UpdateWebGPUAttrs(TargetJSON target) {
+  if (target.count("supports_subgroups")) {
+    bool subgroups = Downcast<Bool>(target.at("supports_subgroups"));
+    if (subgroups) {
+      target.Set("thread_warp_size", int64_t(32));
+    }

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   This implementation unconditionally sets `thread_warp_size` to 32 if `supports_subgroups` is true. This will overwrite any user-provided value for `thread_warp_size`. It would be more flexible to only set this value if the user has not already specified one, allowing for overrides on devices that may have different subgroup sizes.
   
   ```suggestion
       if (subgroups && !target.count("thread_warp_size")) {
         target.Set("thread_warp_size", int64_t(32));
       }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #18823:
URL: https://github.com/apache/tvm/pull/18823#discussion_r2854762076


##########
src/tir/transforms/lower_thread_allreduce.cc:
##########
@@ -508,7 +508,9 @@ class ThreadAllreduceBuilder final : public StmtExprMutator {
         //
         // The former may cause dead lock as there is a divergent
         // branch with a warp sync call inside.
-        PrimExpr other = WarpShuffle(builtin::tvm_warp_shuffle_down(), mask_buffer, val, offset);
+        bool cast_offset_to_uint = target_->kind->name == "webgpu";
+        PrimExpr other = WarpShuffle(builtin::tvm_warp_shuffle_down(), mask_buffer, val, offset,
+                                     cast_offset_to_uint);

Review Comment:
   For WebGPU, WGSL subgroupShuffle* builtins require the lane/delta argument to be `u32`, but this change only casts the shuffle_down offset. Other call sites (e.g. the tvm_warp_shuffle used for broadcasting the lane-0 result) can still pass an `i32` lane id, which will codegen to `subgroupShuffle(x, <i32>)` and fail WGSL type-checking. Consider ensuring all WebGPU warp shuffle lane/delta values are cast to `u32` (either by making WebGPU always cast in WarpShuffle, or by handling the cast in the WebGPU intrinsic lowering).



##########
src/target/source/intrin_rule_webgpu.cc:
##########
@@ -32,6 +32,29 @@ namespace intrin {
 
 using tir::FLowerIntrinsic;
 
+// warp-level primitives. Follows implementation in intrin_rule_metal.cc
+struct WebGPUWarpIntrinsic {
+    const Op operator()(DataType t, const Op& orig_op) const {
+        if (orig_op.same_as(builtin::tvm_warp_shuffle())) {
+            return Op::Get("tir.webgpu.subgroup_shuffle");
+        } else if (orig_op.same_as(builtin::tvm_warp_shuffle_up())) {
+            return Op::Get("tir.webgpu.subgroup_shuffle_up");
+        } else {
+            ICHECK(orig_op.same_as(builtin::tvm_warp_shuffle_down()));
+            return Op::Get("tir.webgpu.subgroup_shuffle_down");
+        }
+    }
+};
+
+template <typename T>
+static PrimExpr DispatchWebGPUShuffle(const PrimExpr& e) {
+    const CallNode* call = e.as<CallNode>();
+    ICHECK(call != nullptr);
+    ICHECK_EQ(call->args.size(), 5);  // mask, value, warp_id, width, warp_size
+    ffi::Array<PrimExpr> webgpu_args{{call->args[1], call->args[2]}};
+    return Call(call->dtype, T()(call->dtype, Downcast<Op>(call->op)), webgpu_args);

Review Comment:
   The newly added WebGPU warp shuffle lowering block uses an indentation style that differs from the rest of this file (4-space indentation vs the surrounding 2-space style). Please reformat these lines to match the existing file formatting for consistency.
   ```suggestion
     const Op operator()(DataType t, const Op& orig_op) const {
       if (orig_op.same_as(builtin::tvm_warp_shuffle())) {
         return Op::Get("tir.webgpu.subgroup_shuffle");
       } else if (orig_op.same_as(builtin::tvm_warp_shuffle_up())) {
         return Op::Get("tir.webgpu.subgroup_shuffle_up");
       } else {
         ICHECK(orig_op.same_as(builtin::tvm_warp_shuffle_down()));
         return Op::Get("tir.webgpu.subgroup_shuffle_down");
       }
     }
   };
   
   template <typename T>
   static PrimExpr DispatchWebGPUShuffle(const PrimExpr& e) {
     const CallNode* call = e.as<CallNode>();
     ICHECK(call != nullptr);
     ICHECK_EQ(call->args.size(), 5);  // mask, value, warp_id, width, warp_size
     ffi::Array<PrimExpr> webgpu_args{{call->args[1], call->args[2]}};
     return Call(call->dtype, T()(call->dtype, Downcast<Op>(call->op)), webgpu_args);
   ```



##########
src/target/source/intrin_rule_webgpu.cc:
##########
@@ -32,6 +32,29 @@ namespace intrin {
 
 using tir::FLowerIntrinsic;
 
+// warp-level primitives. Follows implementation in intrin_rule_metal.cc
+struct WebGPUWarpIntrinsic {
+    const Op operator()(DataType t, const Op& orig_op) const {
+        if (orig_op.same_as(builtin::tvm_warp_shuffle())) {
+            return Op::Get("tir.webgpu.subgroup_shuffle");
+        } else if (orig_op.same_as(builtin::tvm_warp_shuffle_up())) {
+            return Op::Get("tir.webgpu.subgroup_shuffle_up");
+        } else {
+            ICHECK(orig_op.same_as(builtin::tvm_warp_shuffle_down()));
+            return Op::Get("tir.webgpu.subgroup_shuffle_down");
+        }
+    }
+};
+
+template <typename T>
+static PrimExpr DispatchWebGPUShuffle(const PrimExpr& e) {
+    const CallNode* call = e.as<CallNode>();
+    ICHECK(call != nullptr);
+    ICHECK_EQ(call->args.size(), 5);  // mask, value, warp_id, width, warp_size
+    ffi::Array<PrimExpr> webgpu_args{{call->args[1], call->args[2]}};

Review Comment:
   `DispatchWebGPUShuffle` forwards `call->args[2]` directly as the lane/delta argument, but WGSL subgroupShuffle/subgroupShuffleUp/subgroupShuffleDown expect that parameter to be `u32`. Since WebGPU thread indices are typically `u32` cast to `i32` in codegen, the delta/lane often ends up as `i32`, producing invalid WGSL. Please cast `call->args[2]` to `u32` (or otherwise enforce u32) in this dispatcher so all shuffle variants/call sites are handled consistently.
   ```suggestion
       PrimExpr lane = Cast(DataType::UInt(32), call->args[2]);
       ffi::Array<PrimExpr> webgpu_args{{call->args[1], lane}};
   ```



##########
src/target/source/codegen_webgpu.cc:
##########
@@ -118,7 +121,9 @@ void CodeGenWebGPU::InitFuncState(const PrimFunc& f) {
   }
 }
 
-CodeGenWebGPU::CodeGenWebGPU(Target target) : target_(target) {}
+CodeGenWebGPU::CodeGenWebGPU(Target target) : target_(target) {
+  enable_subgroups_ = target_->GetAttr<Bool>("supports_subgroups").value_or(Bool(false));

Review Comment:
   `enable subgroups;` is currently controlled only by the `supports_subgroups` target attr, but subgroup shuffle ops can be emitted whenever `thread_warp_size` is set > 1 (e.g. if a user sets `-thread-warp-size=32` directly on the WebGPU target). In that case, the generated WGSL would contain `subgroupShuffle*` calls without the required `enable subgroups;` directive. To avoid this inconsistent state, consider deriving `enable_subgroups_` from `thread_warp_size > 1` as well, or emitting a clear error if subgroup ops are encountered while `supports_subgroups` is false.
   ```suggestion
     Bool supports_subgroups = target_->GetAttr<Bool>("supports_subgroups").value_or(Bool(false));
     Optional<Integer> thread_warp_size = target_->GetAttr<Integer>("thread_warp_size");
     bool warp_uses_subgroups =
         thread_warp_size.defined() && thread_warp_size.value()->value > 1;
     if (warp_uses_subgroups && !supports_subgroups) {
       LOG(FATAL) << "WebGPU target has thread_warp_size=" << thread_warp_size.value()->value
                  << " but does not support subgroups. Either enable the 'supports_subgroups' "
                  << "target attribute or set thread_warp_size <= 1.";
     }
     enable_subgroups_ = supports_subgroups || warp_uses_subgroups;
   ```



##########
src/target/target_kind.cc:
##########
@@ -424,8 +424,27 @@ TVM_REGISTER_TARGET_KIND("vulkan", kDLVulkan)
     // Tags
     .set_default_keys({"vulkan", "gpu"});
 
+/*!
+ * \brief Update WebGPU target attributes based on subgroup support.
+ * When supports_subgroups is true, set thread_warp_size to 32 so that
+ * TIR lowering uses warp-level shuffle reductions instead of shared memory.
+ */
+TargetJSON UpdateWebGPUAttrs(TargetJSON target) {
+  if (target.count("supports_subgroups")) {
+    bool subgroups = Downcast<Bool>(target.at("supports_subgroups"));
+    if (subgroups) {
+      target.Set("thread_warp_size", int64_t(32));
+    }
+  }
+  return target;
+}
+
 TVM_REGISTER_TARGET_KIND("webgpu", kDLWebGPU)
     .add_attr_option<int64_t>("max_num_threads", 256)
+    .add_attr_option<bool>("supports_subgroups", false)
+    // thread_warp_size=1: is_subwarp_reduction and is_multiwarp_reduction returns false, so no subgroup ops are emitted.
+    .add_attr_option<int64_t>("thread_warp_size", 1)
+    .set_target_parser(UpdateWebGPUAttrs)
     .set_default_keys({"webgpu", "gpu"});

Review Comment:
   This PR introduces new WebGPU target attributes (`supports_subgroups`) and a target parser side effect that mutates `thread_warp_size`. There are existing Python tests covering target parsing and LowerThreadAllreduce behavior, but none validating the new WebGPU defaults/gating. Please add a unit test to assert (1) `Target('webgpu')` defaults `thread_warp_size` to 1, and (2) `Target({'kind':'webgpu','supports_subgroups': True})` results in `thread_warp_size==32` (and ideally that subgroup shuffles are only emitted in the latter case).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "MasterJH5574 (via GitHub)" <gi...@apache.org>.
MasterJH5574 merged PR #18823:
URL: https://github.com/apache/tvm/pull/18823


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [WebGPU] Add gating logic for subgroup shuffle primitives [tvm]

Posted by "ksgr5566 (via GitHub)" <gi...@apache.org>.
ksgr5566 commented on code in PR #18823:
URL: https://github.com/apache/tvm/pull/18823#discussion_r3035184054


##########
web/emcc/webgpu_runtime.cc:
##########
@@ -40,6 +40,8 @@
 #include "../../src/runtime/metadata.h"
 #include "../../src/runtime/workspace_pool.h"
 #include "../../src/support/bytes_io.h"
+#include "3rdparty/tvm-ffi/src/ffi/extra/json_parser.cc"
+#include "3rdparty/tvm-ffi/src/ffi/extra/json_writer.cc"

Review Comment:
   Removing as https://github.com/apache/tvm/pull/18944 takes care of it



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org