Hzfengsy commented on a change in pull request #9360:
URL: https://github.com/apache/tvm/pull/9360#discussion_r735241475
##########
File path: src/tir/schedule/analysis.h
##########
@@ -323,6 +327,53 @@ struct ProducerConsumerSplit {
*/
Buffer GetNthAccessBuffer(const ScheduleState& self, const Block& block, int
n, bool is_write);
+/******** Reduction Block Related ********/
+
+/*!
+ * \brief Convert the `init` and `body` of the input block to BufferStores
+ * \tparam in_schedule Whether the function is called by schedule primitives
+ * \param self The schedule state
+ * \param block The block to be analyzed
+ * \return The BufferStores of the `init` and `body` of the input block
+ * \throw ScheduleError If the `init` or `body` is not BufferStore, or they
don't write to the same
+ * buffer
+ */
+template <bool in_schedule>
+std::pair<BufferStore, BufferStore> GetBufferStoreNodes(const ScheduleState&
self,
Review comment:
Prefer name `GetBufferStoreFromReductionBlock`
##########
File path: src/tir/schedule/analysis/analysis.cc
##########
@@ -552,6 +520,9 @@ bool GetVarsTouchedByBlockIters(const BlockRealize&
block_realize,
} else {
has_block_vars_of_other_types = true;
}
+ if (set == nullptr) {
Review comment:
Please add a regression test if it's a bug
##########
File path: src/tir/transforms/lower_cross_thread_reduction.cc
##########
@@ -0,0 +1,590 @@
+/*
+ * 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 lower_cross_thread_reduction.cc
+ */
+#include <tvm/arith/analyzer.h>
+#include <tvm/tir/analysis.h>
+#include <tvm/tir/stmt_functor.h>
+#include <tvm/tir/transform.h>
+
+#include "../schedule/analysis.h"
+#include "ir_utils.h"
+
+namespace tvm {
+namespace tir {
+
+/*!
+ * \brief Check the dominant property of a block:
+ * the block is the only writer of its output, dominating the reader of its
output buffers
+ * \param scope_block The scope block of the block to be checked
+ * \param block The block whose dominant property is to be checked
+ * \return A boolean indicating if the block is a dominant block
+ */
+bool IsDominantBlock(const Block& scope_block, const Block& block) {
+ // Step 1. Count the number of writers for each buffer written by the scope
block.
+ std::unordered_map<const BufferNode*, int> buffer_writer_cnt;
+ PreOrderVisit(scope_block->body, [&buffer_writer_cnt](const ObjectRef& obj) {
+ if (const auto* block = obj.as<BlockNode>()) {
+ for (const BufferRegion& buffer_region : block->writes) {
+ ++buffer_writer_cnt[buffer_region->buffer.get()];
+ }
+ return false;
+ }
+ return true;
+ });
+ // Step 2. Check whether `block` is the only writer of its outputs.
+ for (const BufferRegion& buffer_region : block->writes) {
+ ICHECK(buffer_writer_cnt.count(buffer_region->buffer.get()));
+ if (buffer_writer_cnt[buffer_region->buffer.get()] != 1) {
+ return false;
+ }
+ }
+ return true;
+}
+
+/*!
+ * \brief Check whether the input block is a reduction block.
+ * \param block_realize The block to be checked
+ * \param loop_range_map The mapping from the loop variables outside the input
block to their ranges
+ * \param scope_block The scope block of the input block
+ * \param analyzer The analyzer
+ * \return A boolean indicating whether the input block is a reduction block.
+ * \note A similar check has been implemented in
"src/tir/schedule/analysis.h", but that check is
+ * based on `tir.Schedule`. Here we have no schedule information, and thus we
must implement the
+ * check again.
+ */
+bool IsReductionBlock(const BlockRealize& block_realize, const Map<Var,
Range>& loop_range_map,
+ const Block& scope_block, arith::Analyzer* analyzer) {
+ const auto* block = block_realize->block.as<BlockNode>();
+ // Cond 1. The block has the `init` statement.
+ if (!block->init.defined()) {
+ return false;
+ }
+ // Cond 2. All the block bindings are quasi-affine expressions.
+ if (!IsAffineBinding(block_realize, loop_range_map, analyzer)) {
+ return false;
+ }
+ // Cond 3. All block vars are either data parallel block vars or reduction
block vars. Meanwhile,
+ // we collect all the reduction block vars.
+ if (!ContainsOnlyDataParAndReductionBlockIter(block->iter_vars)) {
+ return false;
+ }
+ // Cond 4. Dominant: the block is the only writer of its output, dominating
the reader of its
+ // output buffers.
+ if (!IsDominantBlock(scope_block, GetRef<Block>(block))) {
+ return false;
+ }
+ // Cond 5. The reduction block vars are not used to index the output buffers.
+ return ReductionIterNotIndexOutputBuffer(GetRef<Block>(block));
+}
+
+/*!
+ * \brief Create an intermediate buffer with specified name and data type
+ * \param name The specified name
+ * \param dtype The specified data type
+ * \return The created buffer
+ */
+Buffer CreateReductionBuffer(String name, const DataType& dtype) {
+ Var var(name, PointerType(PrimType(dtype), "local"));
+ return Buffer(var, dtype, {1}, {1}, PrimExpr(), std::move(name), 0, 0,
kDefault);
+}
+
+/*!
+ * \brief Remove the BufferRegions whose buffer is the input buffer
+ * \param buffer_regions The array of BufferRegions to be
+ * \param buffer_to_remove The specified buffer
+ * \return The mutated array of BufferRegions, no longer containing
BufferRegion of the input buffer
+ */
+Array<BufferRegion> RemoveBufferFromBufferRegions(const Array<BufferRegion>&
buffer_regions,
+ const Buffer&
buffer_to_remove) {
+ Array<BufferRegion> res;
+ res.reserve(buffer_regions.size());
+ for (const BufferRegion& buffer_region : buffer_regions) {
+ if (!buffer_region->buffer.same_as(buffer_to_remove)) {
+ res.push_back(buffer_region);
+ }
+ }
+ return res;
+}
+
+/*!
+ * \brief Substitute a given source buffer with a given target buffer in
statements or expressions
+ */
+class BufferAccessReplacer : public StmtExprMutator {
+ public:
+ explicit BufferAccessReplacer(Buffer src_buffer, Buffer tgt_buffer)
+ : src_buffer_(std::move(src_buffer)), tgt_buffer_(std::move(tgt_buffer))
{}
+
+ private:
+ PrimExpr VisitExpr_(const BufferLoadNode* load) final {
+ return load->buffer.same_as(src_buffer_) ? BufferLoad(tgt_buffer_, {0})
+ : GetRef<BufferLoad>(load);
+ }
+
+ Stmt VisitStmt_(const BufferStoreNode* store) final {
+ if (store->buffer.same_as(src_buffer_)) {
+ PrimExpr value = StmtExprMutator::VisitExpr(store->value);
+ return BufferStore(tgt_buffer_, value, {0});
+ } else {
+ return StmtMutator::VisitStmt_(store);
+ }
+ }
+
+ Buffer src_buffer_;
+ Buffer tgt_buffer_;
+};
+
+/*!
+ * \brief Substitute a given source block with a given target block, or remove
the source block
+ * branch from the AST if the target block is undefined
+ */
+class ReductionBlockReplacer : public StmtMutator {
+ public:
+ explicit ReductionBlockReplacer(const BlockRealizeNode* src_block,
BlockRealize tgt_block)
+ : src_block_(src_block), tgt_block_(std::move(tgt_block)) {}
+
+ private:
+ Stmt VisitStmt_(const BlockRealizeNode* block_realize) final {
+ return block_realize == src_block_ ? tgt_block_ :
GetRef<BlockRealize>(block_realize);
+ }
+
+ Stmt VisitStmt_(const ForNode* loop) final {
+ For res = Downcast<For>(StmtMutator::VisitStmt_(loop));
+ return !res.defined() ? Stmt{nullptr} : (res->thread_binding.defined() ?
res->body : res);
+ }
+
+ Stmt VisitStmt_(const SeqStmtNode* seq) final {
+ Array<Stmt> results;
+ results.reserve(seq->size());
+ for (Stmt stmt : seq->seq) {
Review comment:
```suggestion
for (const Stmt &stmt : seq->seq) {
```
--
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: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]