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 "zhils (via GitHub)" <gi...@apache.org> on 2026/04/06 08:04:35 UTC
[PR] [TIRX] Bind parallel loops to GPU threads before VerifyMemory [tvm]
zhils opened a new pull request, #19363:
URL: https://github.com/apache/tvm/pull/19363
`VerifyMemory` on GPU targets treats direct accesses outside thread environments as illegal. In the ScatterValue CUDA lowering path, `topi.scatter_elements` emits `ForKind::kParallel` loops without explicit thread bindings, which triggers false host-memory access failures (e.g. "Did you forget to bind?") during TIR verification.
This change adds a new `tirx` pass (`BindParallelLoopsToThreads`) and inserts it before `VerifyMemory` in the `s_tir` pipelines (including adreno). The pass rewrites parallel loops into `blockIdx.x/threadIdx.x` thread-extent regions, substitutes loop vars with global thread indices, and adds bounds checks for non-divisible extents. This preserves correctness while ensuring GPU kernels pass memory verification for this path.
--
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] [TIRX] Bind parallel loops to GPU threads before VerifyMemory [tvm]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #19363:
URL: https://github.com/apache/tvm/pull/19363#discussion_r3038503850
##########
src/tirx/transform/bind_parallel_loops_to_threads.cc:
##########
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file bind_parallel_loops_to_threads.cc
+ * \brief Convert ForKind::kParallel loops to GPU thread bindings.
+ */
+
+#include <tvm/ffi/reflection/registry.h>
+#include <tvm/target/target.h>
+#include <tvm/tirx/op.h>
+#include <tvm/tirx/stmt.h>
+#include <tvm/tirx/stmt_functor.h>
+#include <tvm/tirx/transform.h>
+
+namespace tvm {
+namespace tirx {
+namespace {
+
+static bool IsGpuDeviceType(int dev_type) {
+ return dev_type == kDLCUDA || dev_type == kDLROCM || dev_type == kDLOpenCL ||
+ dev_type == kDLVulkan || dev_type == kDLMetal || dev_type == kDLWebGPU;
+}
Review Comment:

The list of GPU device types here includes `kDLWebGPU`, but the corresponding helper `IsGPUDevice` in `src/tirx/analysis/verify_memory.cc` (line 151) does not. This inconsistency should be resolved to ensure that memory verification is correctly applied to all GPU targets that this pass supports.
##########
src/tirx/transform/bind_parallel_loops_to_threads.cc:
##########
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file bind_parallel_loops_to_threads.cc
+ * \brief Convert ForKind::kParallel loops to GPU thread bindings.
+ */
+
+#include <tvm/ffi/reflection/registry.h>
+#include <tvm/target/target.h>
+#include <tvm/tirx/op.h>
+#include <tvm/tirx/stmt.h>
+#include <tvm/tirx/stmt_functor.h>
+#include <tvm/tirx/transform.h>
+
+namespace tvm {
+namespace tirx {
+namespace {
+
+static bool IsGpuDeviceType(int dev_type) {
+ return dev_type == kDLCUDA || dev_type == kDLROCM || dev_type == kDLOpenCL ||
+ dev_type == kDLVulkan || dev_type == kDLMetal || dev_type == kDLWebGPU;
+}
+
+class ParallelLoopToThreadBindingMutator : public StmtExprMutator {
+ public:
+ explicit ParallelLoopToThreadBindingMutator(int64_t max_threads_per_block)
+ : max_threads_per_block_(max_threads_per_block) {}
+
+ private:
+ Stmt VisitStmt_(const ForNode* op) final {
+ Stmt stmt = StmtExprMutator::VisitStmt_(op);
+ const auto* for_node = stmt.as<ForNode>();
+ TVM_FFI_ICHECK(for_node != nullptr);
+ if (for_node->kind != ForKind::kParallel) {
+ return stmt;
+ }
+
+ DataType dtype = for_node->loop_var.dtype();
+ PrimExpr extent = cast(dtype, for_node->extent);
+ PrimExpr max_threads = IntImm(dtype, max_threads_per_block_);
+ PrimExpr num_blocks = ceildiv(extent, max_threads);
+
+ Var tx_var("threadIdx.x", dtype);
+ Var bx_var("blockIdx.x", dtype);
+ IterVar tx_iter(Range::FromMinExtent(IntImm(dtype, 0), max_threads), tx_var,
+ IterVarType::kThreadIndex, "threadIdx.x");
+ IterVar bx_iter(Range::FromMinExtent(IntImm(dtype, 0), num_blocks), bx_var,
+ IterVarType::kThreadIndex, "blockIdx.x");
+
+ PrimExpr global_idx = cast(dtype, bx_var * max_threads + tx_var);
+ Stmt mapped_body = Substitute(for_node->body, {{Var(for_node->loop_var), global_idx}});
+ mapped_body = IfThenElse(global_idx < extent, mapped_body, Evaluate(IntImm(DataType::Int(32), 0)));
+
+ Stmt body_with_tx = AttrStmt(tx_iter, tirx::attr::thread_extent, max_threads, mapped_body);
+ Stmt body_with_bx = AttrStmt(bx_iter, tirx::attr::thread_extent, num_blocks, body_with_tx);
+ return body_with_bx;
+ }
Review Comment:

The current implementation of `ParallelLoopToThreadBindingMutator` recursively transforms all `ForKind::kParallel` loops it encounters. If there are nested parallel loops, this will result in nested `blockIdx.x` and `threadIdx.x` bindings, which is invalid for GPU targets as these are global registers. The pass should either only bind the outermost parallel loop or handle multi-dimensional mapping (e.g., mapping nested loops to `.y` or `.z` axes).
##########
src/tirx/transform/bind_parallel_loops_to_threads.cc:
##########
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file bind_parallel_loops_to_threads.cc
+ * \brief Convert ForKind::kParallel loops to GPU thread bindings.
+ */
+
+#include <tvm/ffi/reflection/registry.h>
+#include <tvm/target/target.h>
+#include <tvm/tirx/op.h>
+#include <tvm/tirx/stmt.h>
+#include <tvm/tirx/stmt_functor.h>
+#include <tvm/tirx/transform.h>
+
+namespace tvm {
+namespace tirx {
+namespace {
+
+static bool IsGpuDeviceType(int dev_type) {
+ return dev_type == kDLCUDA || dev_type == kDLROCM || dev_type == kDLOpenCL ||
+ dev_type == kDLVulkan || dev_type == kDLMetal || dev_type == kDLWebGPU;
+}
+
+class ParallelLoopToThreadBindingMutator : public StmtExprMutator {
+ public:
+ explicit ParallelLoopToThreadBindingMutator(int64_t max_threads_per_block)
+ : max_threads_per_block_(max_threads_per_block) {}
+
+ private:
+ Stmt VisitStmt_(const ForNode* op) final {
+ Stmt stmt = StmtExprMutator::VisitStmt_(op);
+ const auto* for_node = stmt.as<ForNode>();
+ TVM_FFI_ICHECK(for_node != nullptr);
+ if (for_node->kind != ForKind::kParallel) {
+ return stmt;
+ }
+
+ DataType dtype = for_node->loop_var.dtype();
+ PrimExpr extent = cast(dtype, for_node->extent);
+ PrimExpr max_threads = IntImm(dtype, max_threads_per_block_);
+ PrimExpr num_blocks = ceildiv(extent, max_threads);
+
+ Var tx_var("threadIdx.x", dtype);
+ Var bx_var("blockIdx.x", dtype);
+ IterVar tx_iter(Range::FromMinExtent(IntImm(dtype, 0), max_threads), tx_var,
+ IterVarType::kThreadIndex, "threadIdx.x");
+ IterVar bx_iter(Range::FromMinExtent(IntImm(dtype, 0), num_blocks), bx_var,
+ IterVarType::kThreadIndex, "blockIdx.x");
+
+ PrimExpr global_idx = cast(dtype, bx_var * max_threads + tx_var);
+ Stmt mapped_body = Substitute(for_node->body, {{Var(for_node->loop_var), global_idx}});
Review Comment:

`for_node->loop_var` is already of type `Var`. Wrapping it in `Var(...)` is redundant.
```suggestion
Stmt mapped_body = Substitute(for_node->body, {{for_node->loop_var, global_idx}});
```
--
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] [TIRX] Bind parallel loops to GPU threads before VerifyMemory [tvm]
Posted by "tlopex (via GitHub)" <gi...@apache.org>.
tlopex commented on PR #19363:
URL: https://github.com/apache/tvm/pull/19363#issuecomment-4369407769
Hi @zhils, Thank you for your fix! I think the bug is fixed by #19497, so I will close this pr temporarily. You can feel free to reopen it and have any further discussion with me here
--
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] [TIRX] Bind parallel loops to GPU threads before VerifyMemory [tvm]
Posted by "tlopex (via GitHub)" <gi...@apache.org>.
tlopex commented on PR #19363:
URL: https://github.com/apache/tvm/pull/19363#issuecomment-4309511938
Hi @zhils, thanks a lot for turning around the previous fixes so quickly, and sorry for the slow reply. I know you’ve already addressed quite a few comments, but after spending more time on this PR, I think my main concern is actually more fundamental than the first round.
I’m not fully convinced this is fixing the bug at the right layer.
The root cause seems to be that `topi.scatter_elements` emits bare `T.parallel` on CUDA, which then trips `VerifyMemory`. I understand that `scatter_elements` uses `te.extern` with a hand-written IRBuilder body, so it can’t simply get a normal GPU schedule. But to me, that still points to fixing the lowering in the op itself, for example by making the IRBuilder emit `T.thread_binding` on GPU targets, instead of adding a generic cleanup pass later in the pipeline.
A CUDA PrimFunc probably shouldn’t depend on a later pass to turn leftover `T.parallel` into `blockIdx.x/threadIdx.x`.
My worry is that a general pass like this is a bit too broad. It fixes the current `scatter_elements` issue, but it would also silently hide the same kind of bug in future operators. That makes `VerifyMemory` less useful as a safety check, instead of fixing the lowering that produced invalid GPU TIR in the first place.
So I don’t think this should land in its current form. I’d prefer to fix `scatter_elements` directly so its IRBuilder path emits properly bound CUDA TIR.
Happy to discuss if you see this differently, or if there’s some context around the `te.extern` path that I’m missing.
--
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] [TIRX] Bind parallel loops to GPU threads before VerifyMemory [tvm]
Posted by "zhils (via GitHub)" <gi...@apache.org>.
zhils commented on PR #19363:
URL: https://github.com/apache/tvm/pull/19363#issuecomment-4277806659
> A few things to address here:
>
> 1. Please remove `.tmp_scatter_cuda_check.py`. This looks like a local debugging script and should not be committed. It should be replaced with a proper pytest test instead.
> 2. This PR currently mixes several unrelated changes: the NVCC `-allow-unsupported-compiler` workaround, the `loop_partition.cc` `Var{}` fix, and the `kDLWebGPU` change in `verify_memory.cc` are all independent and should be split into separate PRs.
> 3. Please clarify the semantics for nested parallel loops. When `in_parallel_loop_` is already true, inner parallel loops are left as `kParallel`, but once they are inside a GPU kernel they effectively become serial. If that is intentional, it would be good to document it explicitly; otherwise it may be better to reject this case.
> 4. The `else` branch in `IfThenElse` looks unnecessary. `Evaluate(IntImm(DataType::Int(32), 0))` is a no-op, and TIR already supports `IfThenElse` without an `else`, so this can just be `IfThenElse(global_idx < extent, mapped_body)`.
> 5. For target-less `PrimFunc`s, please avoid falling back to `Target::Current()`. If the function has no target attribute, it is better to leave it unchanged rather than guessing from ambient context. That would also be consistent with how other recent passes handle target-less functions.
> 6. This PR also needs proper pytest coverage for the new pass.
Thanks for the review. I removed .tmp_scatter_cuda_check.py and added tests/python/tirx-transform/test_tir_transform_bind_parallel_loops_to_threads.py for the pass. The NVCC workaround, loop_partition Var{} fix, and verify_memory WebGPU change are reverted here and will be submitted as separate PRs. Nested T.parallel is now rejected with a clear error; the pass doc comment explains semantics (including leaving kParallel unchanged under an existing thread env). IfThenElse no longer has a no-op else. PrimFuncs without kTarget are left unchanged (no Target::Current fallback).
--
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] [TIRX] Bind parallel loops to GPU threads before VerifyMemory [tvm]
Posted by "tlopex (via GitHub)" <gi...@apache.org>.
tlopex closed pull request #19363: [TIRX] Bind parallel loops to GPU threads before VerifyMemory
URL: https://github.com/apache/tvm/pull/19363
--
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