You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by "Ubospica (via GitHub)" <gi...@apache.org> on 2023/11/04 05:51:48 UTC

[PR] [TIR][Transform] Introduce new `InjectPermutedLayout` pass [tvm]

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

   This PR introduces the new `InjectPermutedLayout` pass, partially adapted from the old version.
   
   The current interface is:
   ```
   with T.block("..."):
       T.block_attr({"permuted_layout": "g2s_A"})
   ```


-- 
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: commits-unsubscribe@tvm.apache.org

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


Re: [PR] [TIR][Transform] Introduce new `InjectPermutedLayout` pass [tvm]

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

   @tvm-bot rerun


-- 
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: commits-unsubscribe@tvm.apache.org

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


Re: [PR] [TIR][Transform] Introduce new `InjectPermutedLayout` pass [tvm]

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


-- 
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: commits-unsubscribe@tvm.apache.org

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


Re: [PR] [TIR][Transform] Introduce new `InjectPermutedLayout` pass [tvm]

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

   @tvm-bot rerun


-- 
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: commits-unsubscribe@tvm.apache.org

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


Re: [PR] [TIR][Transform] Introduce new `InjectPermutedLayout` pass [tvm]

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


##########
src/tir/transforms/inject_permuted_layout.cc:
##########
@@ -77,183 +89,196 @@ class PermutedLayoutInjector : public StmtExprMutator {
       // 0  1  2  3    ==>    2  3  0  1
       // 0  1  2  3    ==>    3  2  1  0
       // 0  1  2  3    ==>    3  2  1  0
-      // in 8 number each line view:
+      // View with 8 elements per row:
       // 0  1  2  3  4  0  1  2  3    ==>    0  1  2  3  0  1  2  3
       // 0  1  2  3  4  0  1  2  3    ==>    1  0  3  2  1  0  3  2
       // 0  1  2  3  4  0  1  2  3    ==>    2  3  0  1  2  3  0  1
       // 0  1  2  3  4  0  1  2  3    ==>    3  2  1  0  3  2  1  0
-      permuted_j = floormod(j, 4) ^ floordiv(floormod(i, 8), 2);
+      auto row_idx_sub = floormod(row_idx, 8);
+      new_col_idx_outer = col_idx_outer ^ floordiv(row_idx_sub, 2);
+    }
+    return {row_idx, analyzer_->Simplify(new_col_idx_outer * 8 + col_idx_inner)};
+  }
+
+  static bool CheckAnnotation(ObjectRef annotation) {
+    if (auto* node = annotation.as<StringObj>()) {
+      // Support string annotation for backward compatibility
+      return GetRef<String>(node) != "";
+    } else if (auto* node = annotation.as<IntImmNode>()) {
+      return node->value != 0;
+    } else {
+      LOG(FATAL) << "Invalid permuted layout annotation: " << annotation;
     }
-    return {s0, permuted_j * 8 + v};
   }
 
-  Stmt VisitStmt_(const BlockRealizeNode* _op) final {
-    BlockRealize br = Downcast<BlockRealize>(StmtExprMutator::VisitStmt_(_op));
-    BlockRealizeNode* op = br.CopyOnWrite();
-    if (op->block->annotations.count("permuted_layout") == 0) {
-      return br;
+  Stmt VisitStmt_(const BlockNode* op) final {
+    if (op->annotations.count("permuted_layout") == 0) {
+      return IRMutatorWithAnalyzer::VisitStmt_(op);
     }
-    String val = Downcast<String>(op->block->annotations.at("permuted_layout"));
-    if (val.empty()) return br;
-    Block blk = op->block;
-    Stmt body = blk->body;
-    if (support::StartsWith(val, "g2s")) {
-      // Case 1. Rewrite global to share.dyn
-
-      // Step 1.1. Handle case when have local stage
-      // Block with local stage is like
-      // body {
-      //   SeqStmt {
-      //     seq[0]: local <- global
-      //     seq[1]: shared.dyn <- local
-      //   }
-      // }
-      // We only need to rewrite seq[1]
-      bool have_local_stage = (body.as<SeqStmtNode>() != nullptr);
-      Stmt upper_loop;
-      if (have_local_stage) {
-        SeqStmt seq = Downcast<SeqStmt>(body);
-        ICHECK(seq->size() == 2);
-        upper_loop = seq->seq[0];
-        body = seq->seq[1];
-      }
-
-      // Step 1.2. get inner loop body
-      std::vector<const ForNode*> loops;
-      while (const ForNode* loop = body.as<ForNode>()) {
-        loops.push_back(loop);
-        body = loop->body;
-      }
-      Optional<PrimExpr> if_then_else_condition = NullOpt;
-      const BufferStoreNode* store = body.as<BufferStoreNode>();
-      if (!store) {
-        // Case 1.2.1. IfThenElse generated by reverse_compute_inline
-        // It is always like
-        // if condition:
-        //   loop_body
-        // We just extract the inner loop body inside IfThenElseNode
-        const IfThenElseNode* if_then_else = body.as<IfThenElseNode>();
-        store = if_then_else->then_case.as<BufferStoreNode>();
-        ICHECK(!if_then_else->else_case);
-        if_then_else_condition = if_then_else->condition;
-      }
-      ICHECK(store) << body;
-
-      // Step 1.3. Get smem width and refuse to make any difference if invalid
-      auto smem_width = store->buffer->shape[1].as<IntImmNode>()->value;
-      if (smem_width % 32 != 0) {
-        LOG(WARNING) << "Permuted Layout for " << op->block->name_hint
-                     << " is not supported since its second dimension is not divisible by 32";
-        return br;
-      }
-      if (smem_width % 64 == 32) {
-        if (store->buffer->shape[0].as<IntImmNode>()->value % 2 != 0) {
-          LOG(WARNING) << "Permuted Layout for " << op->block->name_hint
-                       << " is not supported since its first dimension is not divisible by 2"
-                       << " and second dimension is not divisible by 64";
-          return br;
-        }
-      }
-
-      // Step 1.4. Set corresponding member variable
-      if (val.at(4) == 'A') {
-        smem_width_A_ = smem_width;
-      } else {
-        smem_width_B_ = smem_width;
-      }
-
-      // Step 1.5. Rewrite index
-      PrimExpr s0 = store->indices[0];
-      PrimExpr s1 = store->indices[1];
-      Array<PrimExpr> new_indices = GetNewIndices(s0, s1, smem_width);
-      // Step 1.6. Create new BlockRealize
-      Stmt new_body = BufferStore(store->buffer, store->value, new_indices);
-      if (if_then_else_condition) {
-        // Case 1.6.1. Add back IfThenElse
-        new_body = IfThenElse(if_then_else_condition.value(), new_body);
-      }
-      for (int i = loops.size() - 1; i >= 0; i--) {
-        const ForNode* loop = loops[i];
-        new_body = For(loop->loop_var, loop->min, loop->extent, loop->kind, new_body,
-                       loop->thread_binding, loop->annotations);
-      }
-      if (have_local_stage) {
-        // Case 1.6.1. Add back local stage
-        new_body = SeqStmt({upper_loop, new_body});
-      }
-      Block new_blk = Block(blk->iter_vars, blk->reads, blk->writes, blk->name_hint, new_body,
-                            blk->init, blk->alloc_buffers, blk->match_buffers, blk->annotations);
-      BlockRealize new_br = BlockRealize(op->iter_values, op->predicate, new_blk);
-      return new_br;
-    } else if (support::StartsWith(val, "s2l")) {
-      // Case 2. rewrite share.dyn to local
-      // Step 2.1. Retrieve previous set member variable
-      int smem_width = val.at(4) == 'A' ? smem_width_A_ : smem_width_B_;
-      if (smem_width == -1) {
-        return br;
-      }
-
-      // Step 2.2. Rewrite index
-      // Body of shared.dyn to local is always T.evaluate(T.ptx_ldmatrix(args...))
-      // Please refer to the load tensor intrinsic
-      Evaluate eval = Downcast<Evaluate>(body);
-      Call ldmat_call = Downcast<Call>(eval->value);
-      ICHECK(ldmat_call->args.size() == 7);
-      Array<PrimExpr> new_ldmat_args;
-      // Step 2.2.1. Add unchanged args
-      for (int i = 0; i < 5; i++) {
-        new_ldmat_args.push_back(ldmat_call->args[i]);
-      }
-      // 5th argument is always a T.tvm_access_ptr call
-      // Please refer to the load tensor intrinsic
-      Call accptr_call = Downcast<Call>(ldmat_call->args[5]);
-      PrimExpr smem_offset = ldmat_call->args[6];
-
-      // Step 2.2.2. Create new access ptr call
-      Array<PrimExpr> new_accptr_args;
-      for (int i = 0; i < 5; i++) {
-        // 2th args of T.tvm_access_ptr call is offset, we set it to 0 and calculate
-        // total offset in ldmatrix call
-        new_accptr_args.push_back(i == 2 ? 0 : accptr_call->args[i]);
-      }
-      Call new_accptr_call = Call(accptr_call->dtype, accptr_call->op, new_accptr_args);
-      new_ldmat_args.push_back(new_accptr_call);
-
-      // Step 2.2.3. Calculate new offset
-      // We convert offset to 2-dimension, reindex it and convert it back
-      PrimExpr accptr_offset = accptr_call->args[2];
-      PrimExpr offset = smem_offset + accptr_offset;
-      PrimExpr s0 = floordiv(offset, smem_width), s1 = floormod(offset, smem_width);
-      Array<PrimExpr> new_indices = GetNewIndices(s0, s1, smem_width);
-      PrimExpr new_offset = new_indices[0] * smem_width + new_indices[1];
-      new_ldmat_args.push_back(new_offset);
-      // Step 2.2.4. Rewrite the rest part
-      Call new_ldmat_call = Call(ldmat_call->dtype, ldmat_call->op, new_ldmat_args);
-      Stmt new_body = Evaluate(new_ldmat_call);
-      Block new_blk = Block(blk->iter_vars, blk->reads, blk->writes, blk->name_hint, new_body,
-                            blk->init, blk->alloc_buffers, blk->match_buffers, blk->annotations);
-      BlockRealize new_br = BlockRealize(op->iter_values, op->predicate, new_blk);
-      return new_br;
+    if (!CheckAnnotation(op->annotations.at("permuted_layout"))) {
+      return IRMutatorWithAnalyzer::VisitStmt_(op);
     }
+    auto prev_permute = permute_;
+    permute_ = true;
+
+    Block block = Downcast<Block>(IRMutatorWithAnalyzer::VisitStmt_(op));
+
+    // erase the permuted_layout annotation after the pass
+    auto block_node = block.CopyOnWrite();
+    block_node->annotations.erase("permuted_layout");
 
-    return StmtExprMutator::VisitStmt_(op);
+    permute_ = prev_permute;
+    return block;
   }
 
-  int smem_width_A_ = -1;
-  int smem_width_B_ = -1;
-};
+  int CheckAndGetBufferRowSize(Buffer buffer) {
+    CHECK(buffer->shape.size() >= 2)
+        << "The dimension of Buffer \"" << buffer->name << "\" with shape " << buffer->shape
+        << " should be at least 2";
 
-PrimFunc InjectPermutedLayout(PrimFunc func) {
-  auto fptr = func.CopyOnWrite();
-  fptr->body = PermutedLayoutInjector()(std::move(fptr->body));
-  return func;
-}
+    auto dim = buffer->shape.size();
+    auto buffer_row_size = buffer->shape[dim - 1].as<IntImmNode>()->value;
+    auto buffer_col_size = buffer->shape[dim - 2].as<IntImmNode>()->value;
+
+    if (buffer_row_size % 64 != 0) {
+      CHECK(buffer_row_size % 32 == 0)
+          << "Permuted Layout for Buffer \"" << buffer->name << "\" with shape " << buffer->shape
+          << " is not supported since its second dimension is not divisible by 32";
+      CHECK(buffer_col_size % 2 == 0)
+          << "Permuted Layout for Buffer \"" << buffer->name << "\" with shape " << buffer->shape
+          << " is not supported since its first dimension is not divisible by 2 and second "
+             "dimension is not divisible by 64";
+    }
+
+    return buffer_row_size;
+  }
+
+  Array<PrimExpr> HandleBufferIndices(Buffer buffer, Array<PrimExpr> indices) {
+    auto buffer_row_size = CheckAndGetBufferRowSize(buffer);
+
+    // Mutate the last two indices
+    auto indices_size = indices.size();
+    PrimExpr row_idx = indices[indices_size - 2];
+    PrimExpr col_idx = indices[indices_size - 1];
+    auto new_indices = PermuteIndices(row_idx, col_idx, buffer_row_size);
+    indices.Set(indices_size - 2, new_indices[0]);
+    indices.Set(indices_size - 1, new_indices[1]);
+    return indices;
+  }
+
+  Stmt VisitStmt_(const BufferStoreNode* op) final {
+    // Rewrite write from global to shared.dyn or shared
+    // We assume the shape of the shared memory is [..., row_size, col_size],
+    // where row_size is divisible by 64, or divisible by 32 and col_size is divisible by 2.
+    auto store = Downcast<BufferStore>(IRMutatorWithAnalyzer::VisitStmt_(op));
+
+    if (!permute_ || store->buffer->shape.size() < 2) {
+      return store;
+    }
+
+    auto scope = StorageScope::Create(GetPtrStorageScope(store->buffer->data));
+    if (scope.rank != StorageRank::kShared) {
+      return store;
+    }
+
+    auto store_node = store.CopyOnWrite();
+    store_node->indices = HandleBufferIndices(store_node->buffer, store_node->indices);
+    return store;
+  }
+
+  PrimExpr VisitExpr_(const BufferLoadNode* op) final {
+    // Rewrite load from shared or shared.dyn to global
+    auto load = Downcast<BufferLoad>(IRMutatorWithAnalyzer::VisitExpr_(op));
+
+    if (!permute_ || load->buffer->shape.size() < 2) {
+      return load;
+    }
+
+    auto scope = StorageScope::Create(GetPtrStorageScope(load->buffer->data));
+    if (scope.rank != StorageRank::kShared) {
+      return load;
+    }
+
+    auto load_node = load.CopyOnWrite();
+    load_node->indices = HandleBufferIndices(load_node->buffer, load_node->indices);
+    return load;
+  }
+
+  PrimExpr HandleAccessPtrAndOffset(PrimExpr access_ptr, Optional<PrimExpr> offset = NullOpt) {
+    // The 2th arg of T.tvm_access_ptr call is offset, we set it to 0 and accumulate it to
+    // smem_offset
+    CHECK(access_ptr->IsInstance<CallNode>())
+        << "Invalid access ptr for permuted layout: " << access_ptr;
+    auto access_ptr_call = Downcast<Call>(access_ptr);
+    CHECK(access_ptr_call->op.same_as(builtin::tvm_access_ptr()))
+        << "Invalid access ptr for permuted layout: " << access_ptr;
+
+    auto buffer = LookupBufferFromData(Downcast<Var>(access_ptr_call->args[1]), func_);
+    CHECK(buffer) << "The buffer corresponding to data Var " << access_ptr_call->args[1]
+                  << " is not found";
+    int buffer_row_size = CheckAndGetBufferRowSize(buffer.value());
+
+    PrimExpr smem_offset = access_ptr_call->args[2] + (offset.defined() ? offset.value() : 0);
+
+    // Convert offset to 2-dimension, reindex it and convert it back
+    PrimExpr row_idx = floordiv(smem_offset, buffer_row_size);
+    PrimExpr col_idx = floormod(smem_offset, buffer_row_size);
+
+    auto new_indices = PermuteIndices(row_idx, col_idx, buffer_row_size);
+    auto new_offset = analyzer_->Simplify(new_indices[0] * buffer_row_size + new_indices[1]);
+
+    auto new_access_ptr = access_ptr_call.CopyOnWrite();
+    new_access_ptr->args.Set(2, new_offset);
+    return access_ptr_call;
+  }
+
+  PrimExpr VisitExpr_(const CallNode* op) final {
+    // Rewrite from/to shared or shared.dyn to/from local
+    auto call = Downcast<Call>(IRMutatorWithAnalyzer::VisitExpr_(op));
+
+    if (!permute_) {
+      return call;
+    }
+
+    if (!call->op.same_as(builtin::ptx_ldmatrix()) && !call->op.same_as(builtin::mma_store())) {
+      return call;
+    }
+
+    if (call->op.same_as(builtin::ptx_ldmatrix())) {
+      // form: T.ptx_ldmatrix(..., smem_ptr, smem_offset)
+      // smem_ptr: T.tvm_access_ptr(ptype, data, offset, extent, rw_mask)
+      auto access_ptr = call->args[5];
+      PrimExpr smem_offset = call->args[6];
+      auto new_access_ptr = HandleAccessPtrAndOffset(access_ptr, smem_offset);

Review Comment:
   it would be better to record var to buffer mapping during visiting to avoid visit the whole prim func to find the buffer



-- 
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: commits-unsubscribe@tvm.apache.org

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