TVM Pass优化 -- InferType 类型推导
定义(What)
InferType,类型推断,顾名思义,给表达式进行类型的推断
直接上代码
import tvm
from tvm import relay
import numpy as np
def get_demo_mod():
a = relay.var("a", shape=(2, 3, 10), dtype="float32")
b = relay.var("b", shape=(1, 10), dtype="float32")
c = relay.add(a, b)
func = relay.Function([a, b], c)
mod = tvm.IRModule.from_expr(func)
return mod
mod = get_demo_mod()
print("------before InferType------")
try:
print(mod["main"].body.checked_type)
except Exception:
print("can't get checked_type")
print("------after InferType------")
mod = relay.transform.InferType()(mod)
print(mod["main"].body.checked_type)
执行结果如下:

作用 (Why)
推断表达式的类型及输入输出尺寸
另:在 Relay 优化过程中, 每个 pass 都可以修改/添加/删除 op, 所以每个 pass 之后都需要重新 InferType
如,TVM Pass优化 -- 公共子表达式消除(Common Subexpr Elimination, CSE)对公共子表达式消除一节中FunctionPass()第四个参数就是InferType进行类型推断
怎么做(How)
这块代码主要在src/relay/transforms/type_infer.cc文件中,具体实现如下:
Pass InferType() {
auto pass_info = PassInfo(0, "InferType", {});
return tvm::transform::CreateModulePass(
[=](IRModule mod, const PassContext& pass_ctx) {
...
AddGlobalTypes(mod);
VLOG(1) << "AddGlobalTypes'" << PrettyPrint(mod);
std::vector<std::pair<GlobalVar, Function>> updates;
for (const auto& it : updated_mod->functions) {
if (auto func = it.second.as<Function>()) {
auto inferencer = TypeInferencer(mod, pass_ctx->diag_ctx.value());
VLOG(1) << "it.first'" << PrettyPrint(it.first) << "it.second"<< PrettyPrint(it.second);
auto updated_func = inferencer.Infer(it.first, func.value());
VLOG(1) << "updated_func'" << PrettyPrint(updated_func);
...
it.first->checked_type_ = updated_func->checked_type();
if (!WellFormed(updated_func, pass_ctx->diag_ctx)) {
LOG(FATAL) << "The type checked intermediate representation is malformed";
}
auto free_tvars = FreeTypeVars(updated_func, mod);
ICHECK(free_tvars.size() == 0)
<< "Found unbound type variables in " << updated_func << ": " << free_tvars;
EnsureCheckedType(updated_func);
updates.push_back({it.first, Downcast<Function>(updated_func)});
}
}
for (const auto& pair : updates) {
updated_mod->Add(pair.first, pair.second, true);
}
return updated_mod;
},
0, "InferType", {});
}
TVM_REGISTER_GLOBAL("relay._transform.InferType").set_body_typed([]() { return InferType(); });
和公共子表达式消除的实现可发现,该算子调用的是CreateModulePass,因此它是一个模块级的优化,
模块级优化用于实现过程间优化和分析,模块级优化pass工作在tvm.IRModule对象上,将整个程序作为处理单元,几乎可以对程序执行任何操作。
其中,AddGlobalTypes 给mod添加全局参数,为后续的参数推断做准备,
真正进行推断的是TypeInferencer类的Infer()方法,实现如下:
Expr TypeInferencer::Infer(GlobalVar var, Function function) {
...
// Step 1: Populate the constraints.
GetType(function);
// Step 2: Solve the constraints.
Solve();
// Step 3: Attach resolved types to checked_type field.
auto resolved_expr = Resolver(type_map_, &solver_).VisitExpr(function);
...
}
return resolved_expr;
}
第一步,填充约束
Type GetType(const Expr& expr) {
auto it = type_map_.find(expr);
if (it != type_map_.end() && it->second.checked_type.defined()) {
return it->second.checked_type;
}
Type ret = this->VisitExpr(expr);
ICHECK(ret.defined()) << "expression:" << std::endl << PrettyPrint(expr);
KindCheck(ret, mod_, this->diag_ctx);
ResolvedTypeInfo& rti = type_map_[expr];
rti.checked_type = ret;
return ret;
}
会先从type_map_map表中查找该Expr,第一次执行,如果type_map_中未找到该expr,便会通过VisitExpr()方法在该map表中添加,具体实现如下:
void VisitLeaf(const Expr& expr) {
if (!memo_.count(expr)) {
Type ret = this->DispatchVisitExpr(expr);
memo_[expr] = ret;
}
}
bool CheckVisited(const Expr& expr) {
if (memo_.count(expr)) {
return true;
} else {
return false;
}
}
Type DispatchVisitExpr(const Expr& expr) { return ExprFunctor::VisitExpr(expr); }
Type VisitExpr(const Expr& expr) final {
auto fcheck_visited = [this](const Expr& expr) { return this->CheckVisited(expr); };
auto fvisit_leaf = [this](const Expr& expr) { return this->VisitLeaf(expr); };
if (memo_.count(expr)) {
return memo_[expr];
} else {
ExpandDataflow(expr, fcheck_visited, fvisit_leaf);
return memo_[expr];
}
}
其中fcheck_visited()匿名函数通过调用VisitLeaf方法中的DispatchVisitExpr方法,该函数会调用到ExprFunctor类中构建的包含各种类型的虚表中,根据类型调用对应的VisitExpr_方法,如CallNode类型的参数,代码如下:
Type VisitExpr_(const CallNode* call) final {
Array<Type> arg_types;
for (Expr arg : call->args) {
arg_types.push_back(GetType(arg));
}
if (const OpNode* opnode = call->op.as<OpNode>()) {
Type rtype =
PrimitiveCall(opnode->op_type.as<FuncTypeNode>(), arg_types, call->attrs, call->span);
if (rtype.defined()) {
AddTypeArgs(GetRef<Call>(call), arg_types);
return rtype;
}
}
其中,AddTypeArgs()会向type_map_表中插入该expr
void AddTypeArgs(const Expr& expr, Array<Type> type_args) {
auto type_info = type_map_.find(expr);
if (type_info == type_map_.end()) {
type_map_.insert({expr, ResolvedTypeInfo(Type(), type_args)});
} else {
ICHECK(!type_info->second.type_args.defined());
type_info->second.type_args = type_args;
}
}
第二步,解决约束
bool TypeSolver::Solve() {
while (!update_queue_.empty()) {
RelationNode* rnode = update_queue_.front();
const auto& rel = rnode->rel;
update_queue_.pop();
ICHECK(!rnode->resolved);
// update the relation with given evidence.
Array<Type> args;
for (auto* tlink = rnode->type_list.head; tlink != nullptr; tlink = tlink->next) {
args.push_back(Resolve(tlink->value->FindRoot()->resolved_type));
ICHECK_LE(args.size(), rel->args.size());
}
// We need to set this in order to understand where unification
// errors generated by the error reporting are coming from.
reporter_->SetSpan(rnode->span);
try {
// Call the Type Relation's function.
bool resolved = rel->func(args, rel->num_inputs, rel->attrs, reporter_);
if (resolved) {
++num_resolved_rels_;
}
rnode->resolved = resolved;
} catch (const CompileError& err) {
this->Emit(Diagnostic::Error(rnode->span) << err.what());
rnode->resolved = false;
}
// Mark inqueue as false after the function call
// so that rnode itself won't get enqueued again.
rnode->inqueue = false;
}
// This criterion is not necessarily right for all the possible cases
// TODO(tqchen): We should also count the number of in-complete types.
return num_resolved_rels_ == rel_nodes_.size();
}
通过调用 Solve() 方法,我们求解填充好的类型约束。解决约束的过程使用了类型约束求解器(constraint solver)来尝试找到满足约束条件的类型赋值方案。
第三步,
Resolver(const std::unordered_map<Expr, ResolvedTypeInfo, ObjectPtrHash, ObjectPtrEqual>& tmap,
TypeSolver* solver)
: tmap_(tmap), solver_(solver) {}
Expr MixedModeMutator::VisitExpr(const Expr& expr) {
auto fcheck_visited = [this](const Expr& expr) { return this->CheckVisited(expr); };
auto fvisit_leaf = [this](const Expr& expr) { return this->VisitLeaf(expr); };
if (memo_.count(expr)) {
return memo_[expr];
} else {
ExpandDataflow(expr, fcheck_visited, fvisit_leaf);
return memo_[expr];
}
}
使用 Resolver 类的实例来将解析后的类型信息附加到已解析的表达式的checked_type 字段上。Resolver 类是负责类型解析和处理的工具类。它通过访问表达式的结构,并使用之前求解出的类型信息来确定每个表达式的准确类型。
respect~
TVM Pass优化 -- InferType 类型推导的更多相关文章
- TVM Pass IR如何使用
TVM Pass IR如何使用 随着Relay / tir中优化遍数的增加,执行并手动维护其依赖关系变得很棘手.引入了一个基础结构来管理优化过程,并应用于TVM堆栈中IR的不同层. Relay / t ...
- 如何使用TVM Pass红外线
如何使用TVM Pass红外线 随着Relay / tir中优化遍数的增加,执行并手动维护其依赖关系变得很棘手.引入了一个基础结构来管理优化过程,将其应用于TVM堆栈中IR的不同层. Relay / ...
- 类型推导:函数模板与auto
1.从函数模板谈起 函数模板的类型推导机制是在c++98时代就有的,auto的类型推导机制与其基本一致,所以先理解函数模板类型推导. 函数模板可以用如下代码框架表示: #template<typ ...
- 第1课 类型推导(1)_auto关键字
1. auto关键字 (1)auto的作用是让编译器自动推断变量的类型,而不需要显式指定类型.这种隐式类型的推导发生在编译期. (2)auto并不能代表实际的类型声明,只是一个类型声明的“占位符” ...
- 模板类型推导、auto推导
effective modern c++ 果然是神书,干货满满,简单记录下. item1 模板推倒 典型的模板函数 temlate<class T> void fn(ParamType p ...
- C++11(列表初始化+变量类型推导+类型转换+左右值概念、引用+完美转发和万能应用+定位new+可变参数模板+emplace接口)
列表初始化 用法 在C++98中,{}只能够对数组元素进行统一的列表初始化,但是对应自定义类型,无法使用{}进行初始化,如下所示: // 数组类型 int arr1[] = { 1,2,3,4 }; ...
- Java 8 新特性之泛型的类型推导
1. 泛型究竟是什么? 在讨论类型推导(type inference)之前,必须回顾一下什么是泛型(Generic).泛型是Java SE 1.5的新特性,泛型的本质是参数化类型,也就是说所操作的数据 ...
- C++11 - 类型推导auto关键字
在C++11中,auto关键字被作为类型自动类型推导关键字 (1)基本用法 C++98:类型 变量名 = 初值; int i = 10; C++11:auto 变量名 = 初值; auto i ...
- 图说函数模板右值引用参数(T&&)类型推导规则(C++11)
见下图: 规律总结: 只要我们传递一个基本类型是A④的左值,那么,传递后,T的类型就是A&,形参在函数体中的类型就是A&. 只要我们传递一个基本类型是A的右值,那么,传递后,T的类型就 ...
- C++11 图说VS2013下的引用叠加规则和模板参数类型推导规则
背景: 最近在学习C++STL,出于偶然,在C++Reference上看到了vector下的emplace_back函数,不想由此引发了一系列的“探索”,于是就有了现在这篇博文. 前言: ...
随机推荐
- IPEX几代接口的区别
IPEX共分五代,简单判别IPEX接口是几代的方法是测量直径. IPEX 1代 高度小于3.0mm,端子口径φ2.0 IPEX 2代 高度小于2.1mm,端子口径φ2.0 IPEX ...
- 6. Calcite添加自定义函数
1. 简介 在上篇博文中介绍了如何使用calcite进行sql验证, 但是真正在实际生产环境中我们可能需要使用到 用户自定义函数(UDF): 通过代码实现对应的函数逻辑并注册给calcite sql验 ...
- 介绍一下opentcs
OpenTCS是一个开源的自动运载系统(Automated Guided Vehicle,AGV)控制系统.它旨在管理和控制自动化运输车辆,例如AGV或自动搬运车(AMR),在工业和商业环境中执行各种 ...
- RestClient C# 举例 是用jsonbody ,并列出httpclient 等价的方式
以下是使用 RestSharp 发送 POST 请求并附带 JSON 请求体的示例,以及相应的使用 HttpClient 的等价方式: 首先,使用 RestSharp: using System; u ...
- pandas 删除指定条件的行
inplace=True:不创建新的对象,直接对原始对象进行修改: inplace=False:对数据进行修改,创建并返回新的对象承载其修改结果. 删除工作日餐补为0的记录 row_index=df[ ...
- [tldr]GO使用正则表达式
简述如何使用GO调用正则表达式 是否符合条件 使用MatchString方法实现 _, err := regexp.MatchString(regex, str) 提取内容 Compile 第一步需要 ...
- idea src/main/webapp无法识别为web文件夹
整理项目的时候发现,在项目是src/main/webapp没有被自动识别为web文件夹. 1.确认你的项目已经转换为maven项目了. 2.确认你的项目的pom.xml文件有配置(只有配置了包类型,才 ...
- Docker Hub 镜像加速器——持续更新(2025年3月12日)
国内从 Docker Hub 拉取镜像有时会遇到困难,此时可以配置镜像加速器.Docker 官方和国内很多云服务商都提供了国内加速器服务. 配置加速地址 Ubuntu 16.04+.Debian 8+ ...
- 请求方法:GET 与 POST
根据 RFC 规范,GET 的语义是从服务器获取指定的资源,GET 请求的参数位置一般是写在 URL 中,URL 规定只能支持 ASCII,所以 GET 请求的参数只允许 ASCII 字符 ,而且浏览 ...
- vmware vsphere 6.5
vmware vsphere 6.5是vsphere软件的经典版本,也是一款业界领先的服务器虚拟化平台,作为基础平台,是任何云计算环境的理想之选,其组件包括vCenter Server.ESXi.vS ...