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 "elvin-n (via GitHub)" <gi...@apache.org> on 2026/04/15 13:00:38 UTC
[PR] [S-TIR] Fix cache_read/cache_write region when inner block has T.whe… [tvm]
elvin-n opened a new pull request, #19406:
URL: https://github.com/apache/tvm/pull/19406
…re predicate
When the actual buffer access is gated by T.where on a nested (inner) sblock, the outer block's own predicate is trivially true. Both cache_write and cache_read were computing cache regions based only on that outer predicate, producing allocations as large as the full loop extent instead of the guarded region
Fix:
- Add CollectNestedBlockPredicates(), a single helper parameterised by BufferIndexType (kRead / kWrite) that walks the outer block's body, finds nested sblocks accessing the target buffer, and AND-combines their predicates after substituting iter-var bindings into the outer scope.
- Add extra_predicate parameter to RelaxBufferRegion() and AND it with the block's own predicate before region relaxation.
- cache_write: pass the collected nested-write predicate to RelaxBufferRegion so the cache allocation is tightened.
- cache_read (Case 2 — input buffer): when a non-trivial nested-read predicate exists, relax the consumer block's declared read region under that predicate; otherwise fall back to the original scope_block->reads path (preserves non-int32 dtypes in extents).
--
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] [S-TIR] Fix cache_read/cache_write region when inner block has T.whe… [tvm]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #19406:
URL: https://github.com/apache/tvm/pull/19406#discussion_r3089035706
##########
src/s_tir/schedule/primitive/cache_read_write.cc:
##########
@@ -542,26 +542,94 @@ bool AllConsumersUnderStmt(ScheduleState self, Buffer buffer, StmtSRef scope_sre
return true;
}
+/*!
+ * \brief Collect OR-combined predicates from all nested BlockRealize nodes within
+ * the given statement that access the specified buffer (read or write, controlled by
+ * \p index_type). Each nested block's predicate is expressed in the enclosing block's
+ * scope by substituting the nested block's iter var bindings. This is needed when the
+ * actual access is gated by a predicate (T.where) on a nested block while the outer
+ * block has a trivially-true predicate. Sibling blocks that each access the buffer under
+ * different predicates are OR-ed together so the result covers the union of their access
+ * regions.
+ * \param body The body statement of the outer block to search within.
+ * \param buffer The buffer being accessed.
+ * \param index_type Whether to look for reads (kRead) or writes (kWrite).
+ * \return The OR-combination of all nested block predicates found.
+ */
+static PrimExpr CollectNestedBlockPredicates(const Stmt& body, const Buffer& buffer,
+ BufferIndexType index_type) {
+ struct Collector : public StmtVisitor {
+ Collector(const Buffer& buf, BufferIndexType idx_type)
+ : buffer_(buf), index_type_(idx_type), result_(Bool(false)), found_(false) {}
+
+ void VisitStmt_(const SBlockRealizeNode* realize) final {
+ const SBlockNode* block = realize->block.get();
+ const auto& regions =
+ (index_type_ == BufferIndexType::kRead) ? block->reads : block->writes;
+ bool accesses_buffer = false;
+ for (const BufferRegion& region : regions) {
+ if (region->buffer.same_as(buffer_)) {
+ accesses_buffer = true;
+ break;
+ }
+ }
+ if (accesses_buffer) {
+ // Build substitution: nested block iter vars -> their binding values
+ // (which are already expressed in terms of the outer scope).
+ ffi::Map<Var, PrimExpr> subst;
+ for (size_t i = 0; i < block->iter_vars.size(); ++i) {
+ subst.Set(block->iter_vars[i]->var, realize->iter_values[i]);
+ }
+ PrimExpr pred =
+ subst.empty() ? realize->predicate : Substitute(realize->predicate, subst);
+ // OR the predicates across all accessing nested blocks: each such block is an
+ // independent alternative access path (sibling blocks in a SeqStmt), so the
+ // cache must cover the *union* of their access regions, not the intersection.
+ // Using AND (the previous behaviour) underestimates the required region when
+ // sibling blocks have non-overlapping predicates.
+ result_ = found_ ? (result_ || pred) : pred;
+ found_ = true;
+ }
+ // Continue recursing into deeper nested blocks.
+ StmtVisitor::VisitStmt_(realize);
Review Comment:

The current implementation of `CollectNestedBlockPredicates` may produce an incorrect combined predicate for deeply nested blocks. When a nested block that accesses the target buffer is found, its predicate is OR-ed with the result. However, the visitor then continues to recurse into that block's children.
If a child block also accesses the buffer, its predicate will also be OR-ed. This is incorrect because the child block's execution is already gated by the parent's predicate. The union of access regions is governed by the parent's predicate alone in this case. For example, if a parent block has predicate `P1` and a child has `P2`, the effective predicate for an access in the child is `P1 && P2`. The union of accesses in the parent and child is covered by `P1`, not `P1 || P2`.
To fix this, the recursion should only proceed into blocks that *do not* access the target buffer. If a block accessing the buffer is found, its predicate should be collected, and the visitor should not recurse into its children.
```c
if (accesses_buffer) {
// Build substitution: nested block iter vars -> their binding values
// (which are already expressed in terms of the outer scope).
ffi::Map<Var, PrimExpr> subst;
for (size_t i = 0; i < block->iter_vars.size(); ++i) {
subst.Set(block->iter_vars[i]->var, realize->iter_values[i]);
}
PrimExpr pred =
subst.empty() ? realize->predicate : Substitute(realize->predicate, subst);
// OR the predicates across all accessing nested blocks: each such block is an
// independent alternative access path (sibling blocks in a SeqStmt), so the
// cache must cover the *union* of their access regions, not the intersection.
// Using AND (the previous behaviour) underestimates the required region when
// sibling blocks have non-overlapping predicates.
result_ = found_ ? (result_ || pred) : pred;
found_ = true;
} else {
// Continue recursing into deeper nested blocks if this one doesn't access the buffer.
StmtVisitor::VisitStmt_(realize);
}
```
--
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] [S-TIR] Fix cache_read/cache_write region when inner block has T.whe… [tvm]
Posted by "elvin-n (via GitHub)" <gi...@apache.org>.
elvin-n commented on code in PR #19406:
URL: https://github.com/apache/tvm/pull/19406#discussion_r3087533342
##########
src/s_tir/schedule/primitive/cache_read_write.cc:
##########
@@ -542,26 +542,83 @@ bool AllConsumersUnderStmt(ScheduleState self, Buffer buffer, StmtSRef scope_sre
return true;
}
+/*!
+ * \brief Collect AND-combined predicates from all nested BlockRealize nodes within
+ * the given statement that access the specified buffer (read or write, controlled by
+ * \p index_type). Each nested block's predicate is expressed in the enclosing block's
+ * scope by substituting the nested block's iter var bindings. This is needed when the
+ * actual access is gated by a predicate (T.where) on a nested block while the outer
+ * block has a trivially-true predicate.
+ * \param body The body statement of the outer block to search within.
+ * \param buffer The buffer being accessed.
+ * \param index_type Whether to look for reads (kRead) or writes (kWrite).
+ * \return The AND-combination of all nested block predicates found.
+ */
+static PrimExpr CollectNestedBlockPredicates(const Stmt& body, const Buffer& buffer,
+ BufferIndexType index_type) {
+ struct Collector : public StmtVisitor {
+ Collector(const Buffer& buf, BufferIndexType idx_type)
+ : buffer_(buf), index_type_(idx_type), result_(Bool(true)) {}
+
+ void VisitStmt_(const SBlockRealizeNode* realize) final {
+ const SBlockNode* block = realize->block.get();
+ const auto& regions =
+ (index_type_ == BufferIndexType::kRead) ? block->reads : block->writes;
+ bool accesses_buffer = false;
+ for (const BufferRegion& region : regions) {
+ if (region->buffer.same_as(buffer_)) {
+ accesses_buffer = true;
+ break;
+ }
+ }
+ if (accesses_buffer) {
+ // Build substitution: nested block iter vars -> their binding values
+ // (which are already expressed in terms of the outer scope).
+ ffi::Map<Var, PrimExpr> subst;
+ for (size_t i = 0; i < block->iter_vars.size(); ++i) {
+ subst.Set(block->iter_vars[i]->var, realize->iter_values[i]);
+ }
+ PrimExpr pred =
+ subst.empty() ? realize->predicate : Substitute(realize->predicate, subst);
+ result_ = result_ && pred;
Review Comment:
fixed
--
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] [S-TIR] Fix cache_read/cache_write region when inner block has T.whe… [tvm]
Posted by "tlopex (via GitHub)" <gi...@apache.org>.
tlopex merged PR #19406:
URL: https://github.com/apache/tvm/pull/19406
--
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] [S-TIR] Fix cache_read/cache_write region when inner block has T.whe… [tvm]
Posted by "elvin-n (via GitHub)" <gi...@apache.org>.
elvin-n commented on PR #19406:
URL: https://github.com/apache/tvm/pull/19406#issuecomment-4254124264
/gemini 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] [S-TIR] Fix cache_read/cache_write region when inner block has T.whe… [tvm]
Posted by "elvin-n (via GitHub)" <gi...@apache.org>.
elvin-n commented on PR #19406:
URL: https://github.com/apache/tvm/pull/19406#issuecomment-4255040944
/gemini 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] [S-TIR] Fix cache_read/cache_write region when inner block has T.whe… [tvm]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #19406:
URL: https://github.com/apache/tvm/pull/19406#discussion_r3086643769
##########
src/s_tir/schedule/primitive/cache_read_write.cc:
##########
@@ -1703,9 +1760,25 @@ StmtSRef CacheRead(ScheduleState self, const StmtSRef& block_sref, int read_buff
// Case 2. The buffer is the input block for the scope.
info.loc_sref = scope_sref;
info.loc_pos = 0;
- if (ffi::Optional<BufferRegion> region =
- GetBufferRegionFromBuffer(scope_block->reads, read_buffer)) {
- cache_region = region.value();
+ // When a nested block gates the actual read with T.where, the consumer block's own
+ // predicate is trivially true, so the scope-block read annotation covers the full loop
+ // range. Collect nested-read predicates and, if any are non-trivial, relax the consumer
+ // block's read region under that predicate to get a tighter cache allocation.
+ // Without a nested predicate we fall back to scope_block->reads (which preserves the
+ // original buffer's dtype in its extents, e.g. int64 shapes).
+ ffi::Optional<BufferRegion> read_region_opt =
+ GetBufferRegionFromBuffer(block->reads, read_buffer);
+ PrimExpr nested_pred =
+ read_region_opt
+ ? CollectNestedBlockPredicates(block->body, read_buffer, BufferIndexType::kRead)
+ : Bool(true);
+ if (read_region_opt && !is_one(nested_pred)) {
+ StmtSRef parent_sref = ffi::GetRef<StmtSRef>(block_sref->parent);
Review Comment:

`block_sref->parent` can be `nullptr` if `block_sref` is the root block of the function. Calling `ffi::GetRef<StmtSRef>` on a null pointer will lead to a crash. While it is uncommon to apply `cache_read` to a root block, the code should handle this case safely or ensure that `block_sref` is not a root block before this point.
##########
src/s_tir/schedule/primitive/cache_read_write.cc:
##########
@@ -542,26 +542,83 @@ bool AllConsumersUnderStmt(ScheduleState self, Buffer buffer, StmtSRef scope_sre
return true;
}
+/*!
+ * \brief Collect AND-combined predicates from all nested BlockRealize nodes within
+ * the given statement that access the specified buffer (read or write, controlled by
+ * \p index_type). Each nested block's predicate is expressed in the enclosing block's
+ * scope by substituting the nested block's iter var bindings. This is needed when the
+ * actual access is gated by a predicate (T.where) on a nested block while the outer
+ * block has a trivially-true predicate.
+ * \param body The body statement of the outer block to search within.
+ * \param buffer The buffer being accessed.
+ * \param index_type Whether to look for reads (kRead) or writes (kWrite).
+ * \return The AND-combination of all nested block predicates found.
+ */
+static PrimExpr CollectNestedBlockPredicates(const Stmt& body, const Buffer& buffer,
+ BufferIndexType index_type) {
+ struct Collector : public StmtVisitor {
+ Collector(const Buffer& buf, BufferIndexType idx_type)
+ : buffer_(buf), index_type_(idx_type), result_(Bool(true)) {}
+
+ void VisitStmt_(const SBlockRealizeNode* realize) final {
+ const SBlockNode* block = realize->block.get();
+ const auto& regions =
+ (index_type_ == BufferIndexType::kRead) ? block->reads : block->writes;
+ bool accesses_buffer = false;
+ for (const BufferRegion& region : regions) {
+ if (region->buffer.same_as(buffer_)) {
+ accesses_buffer = true;
+ break;
+ }
+ }
+ if (accesses_buffer) {
+ // Build substitution: nested block iter vars -> their binding values
+ // (which are already expressed in terms of the outer scope).
+ ffi::Map<Var, PrimExpr> subst;
+ for (size_t i = 0; i < block->iter_vars.size(); ++i) {
+ subst.Set(block->iter_vars[i]->var, realize->iter_values[i]);
+ }
+ PrimExpr pred =
+ subst.empty() ? realize->predicate : Substitute(realize->predicate, subst);
+ result_ = result_ && pred;
Review Comment:

The logic for combining predicates from multiple nested blocks using `&&` is incorrect for sibling blocks. If a buffer is accessed in multiple parallel or sequential blocks within the same body (e.g., inside a `SeqStmt`), the total region accessed by the outer block is the union of the regions accessed by each child, which corresponds to the `OR` of their predicates. Using `AND` computes the intersection, which will likely result in an incorrectly small or empty cache region if the predicates are disjoint (e.g., `i < 5` and `i >= 5`). Furthermore, if a buffer is accessed in both a parent block and its child block, the current visitor will AND their predicates, which may exclude the region accessed by the parent if the child's predicate is more restrictive.
##########
src/s_tir/schedule/primitive/cache_read_write.cc:
##########
@@ -1785,8 +1858,13 @@ StmtSRef CacheWrite(ScheduleState self, const StmtSRef& block_sref, int write_bu
StmtSRef parent_sref = ffi::GetRef<StmtSRef>(block_sref->parent);
Review Comment:

Similar to the issue in `CacheRead`, `block_sref->parent` can be `nullptr` if `block_sref` is the root block of the function. Calling `ffi::GetRef<StmtSRef>` on a null pointer will lead to a crash. A check should be added to ensure the parent exists.
--
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] [S-TIR] Fix cache_read/cache_write region when inner block has T.whe… [tvm]
Posted by "elvin-n (via GitHub)" <gi...@apache.org>.
elvin-n commented on code in PR #19406:
URL: https://github.com/apache/tvm/pull/19406#discussion_r3087534657
##########
src/s_tir/schedule/primitive/cache_read_write.cc:
##########
@@ -1703,9 +1760,25 @@ StmtSRef CacheRead(ScheduleState self, const StmtSRef& block_sref, int read_buff
// Case 2. The buffer is the input block for the scope.
info.loc_sref = scope_sref;
info.loc_pos = 0;
- if (ffi::Optional<BufferRegion> region =
- GetBufferRegionFromBuffer(scope_block->reads, read_buffer)) {
- cache_region = region.value();
+ // When a nested block gates the actual read with T.where, the consumer block's own
+ // predicate is trivially true, so the scope-block read annotation covers the full loop
+ // range. Collect nested-read predicates and, if any are non-trivial, relax the consumer
+ // block's read region under that predicate to get a tighter cache allocation.
+ // Without a nested predicate we fall back to scope_block->reads (which preserves the
+ // original buffer's dtype in its extents, e.g. int64 shapes).
+ ffi::Optional<BufferRegion> read_region_opt =
+ GetBufferRegionFromBuffer(block->reads, read_buffer);
+ PrimExpr nested_pred =
+ read_region_opt
+ ? CollectNestedBlockPredicates(block->body, read_buffer, BufferIndexType::kRead)
+ : Bool(true);
+ if (read_region_opt && !is_one(nested_pred)) {
+ StmtSRef parent_sref = ffi::GetRef<StmtSRef>(block_sref->parent);
Review Comment:
fixed
##########
src/s_tir/schedule/primitive/cache_read_write.cc:
##########
@@ -1785,8 +1858,13 @@ StmtSRef CacheWrite(ScheduleState self, const StmtSRef& block_sref, int write_bu
StmtSRef parent_sref = ffi::GetRef<StmtSRef>(block_sref->parent);
Review Comment:
fixed
--
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] [S-TIR] Fix cache_read/cache_write region when inner block has T.whe… [tvm]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #19406:
URL: https://github.com/apache/tvm/pull/19406#discussion_r3088276669
##########
src/s_tir/schedule/primitive/cache_read_write.cc:
##########
@@ -542,26 +542,92 @@ bool AllConsumersUnderStmt(ScheduleState self, Buffer buffer, StmtSRef scope_sre
return true;
}
+/*!
+ * \brief Collect AND-combined predicates from all nested BlockRealize nodes within
+ * the given statement that access the specified buffer (read or write, controlled by
+ * \p index_type). Each nested block's predicate is expressed in the enclosing block's
+ * scope by substituting the nested block's iter var bindings. This is needed when the
+ * actual access is gated by a predicate (T.where) on a nested block while the outer
+ * block has a trivially-true predicate.
+ * \param body The body statement of the outer block to search within.
+ * \param buffer The buffer being accessed.
+ * \param index_type Whether to look for reads (kRead) or writes (kWrite).
+ * \return The AND-combination of all nested block predicates found.
+ */
Review Comment:

The documentation for `CollectNestedBlockPredicates` states that it computes an "AND-combination" of predicates. However, the implementation correctly uses `||` to compute an OR-combination, which is necessary to correctly determine the union of access regions for sibling blocks. This documentation should be updated to reflect the actual behavior.
```suggestion
* \brief Collect OR-combined predicates from all nested BlockRealize nodes within
* the given statement that access the specified buffer (read or write, controlled by
* \p index_type). Each nested block's predicate is expressed in the enclosing block's
* scope by substituting the nested block's iter var bindings. This is needed when the
* actual access is gated by a predicate (T.where) on a nested block while the outer
* block has a trivially-true predicate.
* \param body The body statement of the outer block to search within.
* \param buffer The buffer being accessed.
* \param index_type Whether to look for reads (kRead) or writes (kWrite).
* \return The OR-combination of all nested block predicates found.
```
--
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