tqchen commented on a change in pull request #8354: URL: https://github.com/apache/tvm/pull/8354#discussion_r659730908
########## File path: src/tir/ir/specialize.cc ########## @@ -0,0 +1,326 @@ +/* + * 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 src/tir/ir/specialize.cc + * \brief Specialize parameters of PrimFunc. + */ +#include <tvm/runtime/registry.h> +#include <tvm/tir/analysis.h> +#include <tvm/tir/function.h> +#include <tvm/tir/stmt_functor.h> + +#include <functional> + +#include "functor_common.h" + +namespace tvm { +namespace tir { + +using VarMap = std::unordered_map<Var, PrimExpr, ObjectPtrHash, ObjectPtrEqual>; + +/**************** Helper functions ****************/ + +/*! \brief Helper function to check whether the given var is in function parameter list. */ +inline bool IsParam(const PrimFunc& func, const Var& param) { + return std::any_of(func->params.begin(), func->params.end(), + [&](const Var& var) { return var.same_as(param); }); +} + +/*! \brief Mutator to specialize function and remove const parameters */ +class PrimFuncSpecializer : public StmtExprMutator { + public: + explicit PrimFuncSpecializer(VarMap var_map) : var_map_(var_map) {} + + static PrimFunc Specialize(PrimFunc f, const VarMap& var_map) { + PrimFuncSpecializer specializer(var_map); + // Updating Buffer map + Map<Var, Buffer> buffer_map; + for (const auto& it : f->buffer_map) { + const Var& var = it.first; + const Buffer& buffer = it.second; + Buffer new_buffer = specializer.MutateBuffer(buffer); + buffer_map.Set(var, new_buffer); + if (!new_buffer.same_as(buffer)) { + specializer.buffer_map_[buffer] = new_buffer; + } + } + + // Updating parmeters + Array<Var> params; + for (const auto& var : f->params) { + // Remove parmeters which has been specialized. + if (var_map.find(var) == var_map.end()) { + params.push_back(var); + } + } + + PrimFuncNode* f_ptr = f.CopyOnWrite(); + f_ptr->params = std::move(params); + f_ptr->buffer_map = std::move(buffer_map); + f_ptr->body = specializer(std::move(f_ptr->body)); + + // Updating attrs + if (f->attrs.defined()) { + auto& attr_dict = f_ptr->attrs.CopyOnWrite()->dict; + for (const auto& kv : attr_dict) { + const String& key = kv.first; + const ObjectRef& value = kv.second; + if (value->IsInstance<PrimExprNode>()) { + attr_dict.Set(key, Substitute(Downcast<PrimExpr>(value), var_map)); + } + } + } + return f; + } + + private: + Stmt VisitStmt_(const BlockNode* op) final { + Array<Buffer> alloc_buffers = MutateArray( + op->alloc_buffers, + std::bind(&PrimFuncSpecializer::MutateAllocBuffer, this, std::placeholders::_1)); + Array<BufferRegion> reads = MutateArray( + op->reads, + std::bind(&PrimFuncSpecializer::MutateBufferRegion, this, std::placeholders::_1)); + Array<BufferRegion> writes = MutateArray( + op->writes, + std::bind(&PrimFuncSpecializer::MutateBufferRegion, this, std::placeholders::_1)); + Array<IterVar> block_vars = MutateArray( + op->iter_vars, std::bind(&PrimFuncSpecializer::MutateIterVar, this, std::placeholders::_1)); + Optional<Stmt> init = NullOpt; + if (op->init.defined()) { + init = VisitStmt(op->init.value()); + } + Stmt body = VisitStmt(op->body); + + if (alloc_buffers.same_as(op->alloc_buffers) && reads.same_as(op->reads) && + writes.same_as(op->writes) && block_vars.same_as(op->iter_vars) && body.same_as(op->body) && + init.same_as(op->init)) { + return GetRef<Block>(op); + } else { + ObjectPtr<BlockNode> n = CopyOnWrite(op); + n->alloc_buffers = std::move(alloc_buffers); + n->reads = std::move(reads); + n->writes = std::move(writes); + n->iter_vars = std::move(block_vars); + n->body = std::move(body); + n->init = std::move(init); + return Stmt(n); + } + } + + Stmt VisitStmt_(const BufferStoreNode* op) final { + auto it = buffer_map_.find(op->buffer); + if (it == buffer_map_.end()) { Review comment: need to recursive visit the expressions(e.g. what if the src contains a buffer load, please add a regression test). Always consider recursive visit first ########## File path: src/tir/ir/specialize.cc ########## @@ -0,0 +1,326 @@ +/* + * 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 src/tir/ir/specialize.cc + * \brief Specialize parameters of PrimFunc. + */ +#include <tvm/runtime/registry.h> +#include <tvm/tir/analysis.h> +#include <tvm/tir/function.h> +#include <tvm/tir/stmt_functor.h> + +#include <functional> + +#include "functor_common.h" + +namespace tvm { +namespace tir { + +using VarMap = std::unordered_map<Var, PrimExpr, ObjectPtrHash, ObjectPtrEqual>; + +/**************** Helper functions ****************/ + +/*! \brief Helper function to check whether the given var is in function parameter list. */ +inline bool IsParam(const PrimFunc& func, const Var& param) { + return std::any_of(func->params.begin(), func->params.end(), + [&](const Var& var) { return var.same_as(param); }); +} + +/*! \brief Mutator to specialize function and remove const parameters */ +class PrimFuncSpecializer : public StmtExprMutator { + public: + explicit PrimFuncSpecializer(VarMap var_map) : var_map_(var_map) {} + + static PrimFunc Specialize(PrimFunc f, const VarMap& var_map) { + PrimFuncSpecializer specializer(var_map); + // Updating Buffer map + Map<Var, Buffer> buffer_map; + for (const auto& it : f->buffer_map) { + const Var& var = it.first; + const Buffer& buffer = it.second; + Buffer new_buffer = specializer.MutateBuffer(buffer); + buffer_map.Set(var, new_buffer); + if (!new_buffer.same_as(buffer)) { + specializer.buffer_map_[buffer] = new_buffer; + } + } + + // Updating parmeters + Array<Var> params; + for (const auto& var : f->params) { + // Remove parmeters which has been specialized. + if (var_map.find(var) == var_map.end()) { + params.push_back(var); + } + } + + PrimFuncNode* f_ptr = f.CopyOnWrite(); + f_ptr->params = std::move(params); + f_ptr->buffer_map = std::move(buffer_map); + f_ptr->body = specializer(std::move(f_ptr->body)); + + // Updating attrs + if (f->attrs.defined()) { + auto& attr_dict = f_ptr->attrs.CopyOnWrite()->dict; + for (const auto& kv : attr_dict) { + const String& key = kv.first; + const ObjectRef& value = kv.second; + if (value->IsInstance<PrimExprNode>()) { + attr_dict.Set(key, Substitute(Downcast<PrimExpr>(value), var_map)); + } + } + } + return f; + } + + private: + Stmt VisitStmt_(const BlockNode* op) final { + Array<Buffer> alloc_buffers = MutateArray( + op->alloc_buffers, + std::bind(&PrimFuncSpecializer::MutateAllocBuffer, this, std::placeholders::_1)); + Array<BufferRegion> reads = MutateArray( + op->reads, + std::bind(&PrimFuncSpecializer::MutateBufferRegion, this, std::placeholders::_1)); + Array<BufferRegion> writes = MutateArray( + op->writes, + std::bind(&PrimFuncSpecializer::MutateBufferRegion, this, std::placeholders::_1)); + Array<IterVar> block_vars = MutateArray( + op->iter_vars, std::bind(&PrimFuncSpecializer::MutateIterVar, this, std::placeholders::_1)); + Optional<Stmt> init = NullOpt; + if (op->init.defined()) { + init = VisitStmt(op->init.value()); + } + Stmt body = VisitStmt(op->body); + + if (alloc_buffers.same_as(op->alloc_buffers) && reads.same_as(op->reads) && + writes.same_as(op->writes) && block_vars.same_as(op->iter_vars) && body.same_as(op->body) && + init.same_as(op->init)) { + return GetRef<Block>(op); + } else { + ObjectPtr<BlockNode> n = CopyOnWrite(op); + n->alloc_buffers = std::move(alloc_buffers); + n->reads = std::move(reads); + n->writes = std::move(writes); + n->iter_vars = std::move(block_vars); + n->body = std::move(body); + n->init = std::move(init); + return Stmt(n); + } + } + + Stmt VisitStmt_(const BufferStoreNode* op) final { + auto it = buffer_map_.find(op->buffer); + if (it == buffer_map_.end()) { + return GetRef<BufferStore>(op); + } + + PrimExpr value = VisitExpr(op->value); + Array<PrimExpr> indices = + MutateArray(op->indices, [this](const PrimExpr& e) { return this->VisitExpr(e); }); + + auto n = CopyOnWrite(op); + n->buffer = it->second; + n->value = std::move(value); + n->indices = std::move(indices); + return Stmt(n); + } + + PrimExpr VisitExpr_(const BufferLoadNode* op) final { + auto it = buffer_map_.find(op->buffer); + if (it == buffer_map_.end()) { + return GetRef<BufferLoad>(op); + } + + Array<PrimExpr> indices = + MutateArray(op->indices, [this](const PrimExpr& e) { return this->VisitExpr(e); }); Review comment: need to recursive visit the indices, always use the post order recursive pattern when possible. e.g. first call StmtExprMutator::VisitExpr_(op); This will also allows you to skip the lines of indices mutation. Please add a regression test ########## File path: src/tir/ir/specialize.cc ########## @@ -0,0 +1,326 @@ +/* + * 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 src/tir/ir/specialize.cc + * \brief Specialize parameters of PrimFunc. + */ +#include <tvm/runtime/registry.h> +#include <tvm/tir/analysis.h> +#include <tvm/tir/function.h> +#include <tvm/tir/stmt_functor.h> + +#include <functional> + +#include "functor_common.h" + +namespace tvm { +namespace tir { + +using VarMap = std::unordered_map<Var, PrimExpr, ObjectPtrHash, ObjectPtrEqual>; + +/**************** Helper functions ****************/ + +/*! \brief Helper function to check whether the given var is in function parameter list. */ +inline bool IsParam(const PrimFunc& func, const Var& param) { + return std::any_of(func->params.begin(), func->params.end(), + [&](const Var& var) { return var.same_as(param); }); +} + +/*! \brief Mutator to specialize function and remove const parameters */ +class PrimFuncSpecializer : public StmtExprMutator { + public: + explicit PrimFuncSpecializer(VarMap var_map) : var_map_(var_map) {} + + static PrimFunc Specialize(PrimFunc f, const VarMap& var_map) { + PrimFuncSpecializer specializer(var_map); + // Updating Buffer map + Map<Var, Buffer> buffer_map; + for (const auto& it : f->buffer_map) { + const Var& var = it.first; + const Buffer& buffer = it.second; + Buffer new_buffer = specializer.MutateBuffer(buffer); + buffer_map.Set(var, new_buffer); + if (!new_buffer.same_as(buffer)) { + specializer.buffer_map_[buffer] = new_buffer; + } + } + + // Updating parmeters + Array<Var> params; + for (const auto& var : f->params) { + // Remove parmeters which has been specialized. + if (var_map.find(var) == var_map.end()) { + params.push_back(var); + } + } + + PrimFuncNode* f_ptr = f.CopyOnWrite(); + f_ptr->params = std::move(params); + f_ptr->buffer_map = std::move(buffer_map); + f_ptr->body = specializer(std::move(f_ptr->body)); + + // Updating attrs + if (f->attrs.defined()) { + auto& attr_dict = f_ptr->attrs.CopyOnWrite()->dict; + for (const auto& kv : attr_dict) { + const String& key = kv.first; + const ObjectRef& value = kv.second; + if (value->IsInstance<PrimExprNode>()) { + attr_dict.Set(key, Substitute(Downcast<PrimExpr>(value), var_map)); + } + } + } + return f; + } + + private: + Stmt VisitStmt_(const BlockNode* op) final { + Array<Buffer> alloc_buffers = MutateArray( + op->alloc_buffers, + std::bind(&PrimFuncSpecializer::MutateAllocBuffer, this, std::placeholders::_1)); + Array<BufferRegion> reads = MutateArray( + op->reads, + std::bind(&PrimFuncSpecializer::MutateBufferRegion, this, std::placeholders::_1)); + Array<BufferRegion> writes = MutateArray( + op->writes, + std::bind(&PrimFuncSpecializer::MutateBufferRegion, this, std::placeholders::_1)); + Array<IterVar> block_vars = MutateArray( + op->iter_vars, std::bind(&PrimFuncSpecializer::MutateIterVar, this, std::placeholders::_1)); + Optional<Stmt> init = NullOpt; + if (op->init.defined()) { + init = VisitStmt(op->init.value()); + } + Stmt body = VisitStmt(op->body); + + if (alloc_buffers.same_as(op->alloc_buffers) && reads.same_as(op->reads) && + writes.same_as(op->writes) && block_vars.same_as(op->iter_vars) && body.same_as(op->body) && + init.same_as(op->init)) { + return GetRef<Block>(op); + } else { + ObjectPtr<BlockNode> n = CopyOnWrite(op); + n->alloc_buffers = std::move(alloc_buffers); + n->reads = std::move(reads); + n->writes = std::move(writes); + n->iter_vars = std::move(block_vars); + n->body = std::move(body); + n->init = std::move(init); + return Stmt(n); + } + } + + Stmt VisitStmt_(const BufferStoreNode* op) final { + auto it = buffer_map_.find(op->buffer); + if (it == buffer_map_.end()) { + return GetRef<BufferStore>(op); + } + + PrimExpr value = VisitExpr(op->value); + Array<PrimExpr> indices = + MutateArray(op->indices, [this](const PrimExpr& e) { return this->VisitExpr(e); }); + + auto n = CopyOnWrite(op); Review comment: always try to return the original ones when possible. ########## File path: tests/python/unittest/test_tvmscript_meta_programming.py ########## @@ -0,0 +1,185 @@ +# 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. +# pylint: disable=missing-function-docstring, missing-module-docstring + +import tvm +from tvm import tir +from tvm.script import ty + + [email protected] +def matmul(a: ty.handle, b: ty.handle, c: ty.handle, n: ty.int32) -> None: + m = tir.var("int32") + A = tir.match_buffer(a, [m, n]) + B = tir.match_buffer(b, [m, n]) + C = tir.match_buffer(c, [m, m]) + + with tir.block([m, m, tir.reduce_axis(0, n)], "update") as [vi, vj, vk]: + with tir.init(): + C[vi, vj] = 0.0 + C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk] + + [email protected] +def matmul_128(a: ty.handle, b: ty.handle, c: ty.handle) -> None: + A = tir.match_buffer(a, [128, 128]) + B = tir.match_buffer(b, [128, 128]) + C = tir.match_buffer(c, [128, 128]) + + with tir.block([128, 128, tir.reduce_axis(0, 128)], "update") as [vi, vj, vk]: + with tir.init(): + C[vi, vj] = 0.0 + C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk] + + [email protected] +def matmul_m_128(a: ty.handle, b: ty.handle, c: ty.handle) -> None: + m = tir.var("int32") + A = tir.match_buffer(a, [m, 128]) + B = tir.match_buffer(b, [m, 128]) + C = tir.match_buffer(c, [m, m]) + + with tir.block([m, m, tir.reduce_axis(0, 128)], "update") as [vi, vj, vk]: + with tir.init(): + C[vi, vj] = 0.0 + C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk] + + [email protected] +def matmul_m_8x(a: ty.handle, b: ty.handle, c: ty.handle) -> None: + x = tir.var("int32") + m = tir.var("int32") + A = tir.match_buffer(a, [m, x * 8]) + B = tir.match_buffer(b, [m, x * 8]) + C = tir.match_buffer(c, [m, m]) + + with tir.block([m, m, tir.reduce_axis(0, x * 8)], "update") as [vi, vj, vk]: + with tir.init(): + C[vi, vj] = 0.0 + C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk] + + [email protected] +def element_wise(a: ty.handle, c: ty.handle) -> None: + m = tir.var("int32") + n = tir.var("int32") + A = tir.match_buffer(a, (m, n), "float32") + C = tir.match_buffer(c, (m, n), "float32") + + B = tir.alloc_buffer((m, n), "float32") + + with tir.block([m, n], "B") as [vi, vj]: + B[vi, vj] = A[vi, vj] * 2.0 + + with tir.block([m, n], "C") as [vi, vj]: + C[vi, vj] = B[vi, vj] + 1.0 + + [email protected] +def element_wise_128_64(a: ty.handle, c: ty.handle) -> None: + A = tir.match_buffer(a, (128, 64), "float32") + C = tir.match_buffer(c, (128, 64), "float32") + B = tir.alloc_buffer((128, 64), "float32") + + with tir.block([128, 64], "B") as [vi, vj]: + B[vi, vj] = A[vi, vj] * 2.0 + + with tir.block([128, 64], "C") as [vi, vj]: + C[vi, vj] = B[vi, vj] + 1.0 + + [email protected] +def element_wise_128_n(a: ty.handle, c: ty.handle) -> None: + n = tir.var("int32") + A = tir.match_buffer(a, (128, n), "float32") + C = tir.match_buffer(c, (128, n), "float32") + B = tir.alloc_buffer((128, n), "float32") + + with tir.block([128, n], "B") as [vi, vj]: + B[vi, vj] = A[vi, vj] * 2.0 + + with tir.block([128, n], "C") as [vi, vj]: + C[vi, vj] = B[vi, vj] + 1.0 + + [email protected] +def mem_copy(a: ty.handle, b: ty.handle, m: ty.int32, n: ty.int32) -> None: + A = tir.match_buffer(a, (m, n), "float32") + B = tir.match_buffer(b, (m, n), "float32") + + with tir.block([m, n], "") as [vi, vj]: + B[vi, vj] = A[vi, vj] + + [email protected] +def mem_copy_16_16(a: ty.handle, b: ty.handle) -> None: + A = tir.match_buffer(a, (16, 16), "float32") + B = tir.match_buffer(b, (16, 16), "float32") + + with tir.block([16, 16], "") as [vi, vj]: + B[vi, vj] = A[vi, vj] + + [email protected] +def mem_copy_m_16(a: ty.handle, b: ty.handle, m: ty.int32) -> None: + A = tir.match_buffer(a, (m, 16), "float32") + B = tir.match_buffer(b, (m, 16), "float32") + + with tir.block([m, 16], "") as [vi, vj]: + B[vi, vj] = A[vi, vj] + + +def test_tensor_dimension_invariant_code_matmul(): + a, _, _, n = matmul.params + # fully specialized + func = matmul.specialize({a: tir.decl_buffer((128, 128))}) + tvm.ir.assert_structural_equal(func, matmul_128) + # partially specialized + func = matmul.specialize({n: 128}) + tvm.ir.assert_structural_equal(func, matmul_m_128) + # symbolic specialized + func = matmul.specialize({n: tir.Var("x", "int32") * 8}) + tvm.ir.assert_structural_equal(func, matmul_m_8x) + + +def test_tensor_dimension_invariant_code_elemwise(): + a, c = element_wise.params + C = element_wise.buffer_map[c] + # fully specialized + func = element_wise.specialize({a: tir.decl_buffer((128, 64))}) + tvm.ir.assert_structural_equal(func, element_wise_128_64) + # partially specialized + func = element_wise.specialize({c: tir.decl_buffer((128, C.shape[1]))}) + tvm.ir.assert_structural_equal(func, element_wise_128_n) Review comment: add a testcase of nothing being specialized, require that the function itself remains the same(pointer equality) -- 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]
