首页 > 其他分享 >TVM Pass优化 -- 移除无用函数(Remove Unused Function)

TVM Pass优化 -- 移除无用函数(Remove Unused Function)

时间:2024-04-14 16:23:59浏览次数:13  
标签:Function 函数 relay RemoveUnusedFunctions Pass Unused 移除 entry mod

定义

移除无用函数,Remove Unused Function,顾名思义,就是删除Module中定义但未用到的函数
当然,它也是一个模块级的优化,
举例子:

def get_mod():
    mod = tvm.IRModule({})
    fn1 = relay.Function([], relay.const(1))
    fn2 = relay.Function([], relay.const(2))
    fn3 = relay.Function([], relay.const(3))
    g1 = relay.GlobalVar("g1")
    g2 = relay.GlobalVar("g2")
    g3 = relay.GlobalVar("g3")
    mod[g1] = fn1
    mod[g2] = fn2
    mod[g3] = fn3
    p = relay.var("p", "bool")
    mod["main"] = relay.Function([p], relay.Call(relay.If(p, g1, g2), []))
    return mod

mod = get_mod()
ref_mod = get_mod()
mod = relay.transform.RemoveUnusedFunctions()(mod)
print(mod)

例子中,get_mod定义了三个函数fn1fn2fn3,下面并未使用fn3,因此,fn3是个无用函数,应该被移除
该例子输出结果如下:
image
通过RemoveUnusedFunctions函数后,fn3已被移除

意义

删除无用代码,可以缩减IR代码,可使程序更小、编译更快、(通常)执行也更快。同时它还可以增强编译器改进代码的能力。

实现

同样,该pass会通过TVM_REGISTER_GLOBAL在C++端进行注册,python端通过FFI接口进行访问,不过需要注意的是,该Pass的IRModule对象中一定要有main函数,否则在运行该Pass时会因找不到main方法而报错。
Python端访问:

def RemoveUnusedFunctions(entry_functions=None):
    if entry_functions is None:
        entry_functions = ["main"]
    return _ffi_api.RemoveUnusedFunctions(entry_functions)

C++端注册:

Pass RemoveUnusedFunctions(Array<runtime::String> entry_functions) {
  runtime::TypedPackedFunc<IRModule(IRModule, PassContext)> pass_func = [=](IRModule m,
                                                                            PassContext pc) {
    return relay::vm::RemoveUnusedFunctions(m, entry_functions);
  };
  return CreateModulePass(pass_func, 1, "RemoveUnusedFunctions", {});
}

TVM_REGISTER_GLOBAL("relay._transform.RemoveUnusedFunctions").set_body_typed(RemoveUnusedFunctions);

CreateModulePass说明了该Pass是一个Module模块级别的优化
该Pass优化的真正实现是在RemoveUnusedFunctions方法中,代码实现如下:

IRModule RemoveUnusedFunctions(const IRModule& module, Array<runtime::String> entry_funcs) {
  std::unordered_set<std::string> called_funcs{};
  for (auto entry : entry_funcs) {
    VLOG(2) << "RemoveUnusedFunctions:" << entry;
    auto funcs = CallTracer(module).Trace(entry);
    called_funcs.insert(funcs.cbegin(), funcs.cend());
  }
  for(auto func : called_funcs)
  {
    VLOG(2) << "called_funcs:" << func;
  }
  auto existing_functions = module->functions;
  for (auto f : existing_functions) {
    VLOG(2) << "existing_functions:" << f.first->name_hint;
    auto it = called_funcs.find(f.first->name_hint);
    if (it == called_funcs.end()) {
      module->Remove(f.first);
    }
  }
  return module;
}

该函数调用CallTracer类(继承ExprVisitor类)的成员函数Trace(),获取IRModule对象中main函数调用的所有函数,并保存在unordered_set<std::string>类型变量called_funcs_中,然后RemoveUnusedFunctions()函数遍历IRModule对象中的所有函数,将不在called_funcs_中的函数视为无用函数,并将它从IRModule对象中移除。
通过上述的调试信息,可以进行佐证:
image

该Pass优化还是比较简单的

Respect~

标签:Function,函数,relay,RemoveUnusedFunctions,Pass,Unused,移除,entry,mod
From: https://www.cnblogs.com/whiteBear/p/18134269

相关文章

  • CF1165E Two Arrays and Sum of Functions 题解
    题目简述已知两个长度均为$n$的数组$a$和$b$。给定一个函数:$f(l,r)=\sum\limits_{l\lei\ler}a_i\cdotb_i$。你的任务是对数组$b$中的元素以任意的顺序重新排序,使$\sum\limits_{1\lel\ler\len}f(l,r)$的值最小。题目分析我们首先进行化简,发现题......
  • 52 Things: Number 20: How are Merkle-Damgaard style hash functions constructed?
    52Things:Number20:HowareMerkle-Damgaardstylehashfunctionsconstructed?52件事:第20件:Merkle-Damgaard风格的散列函数是如何构建的? Thisisthelatestinaseriesofblogpoststoaddressthelistof '52ThingsEveryPhDStudentShouldKnow' todoCr......
  • 人工智能_大模型030_大模型开发框架003_Semantic Kernel中Native Function嵌套调用_SK
    ###4.2、NativeFunction嵌套调用(选)**注意:**NativeFunction的嵌套调用,本质上就是函数嵌套。官方给的写法是在Kernel的设计思想下的实现,通过Kernel来获取函数并执行,观感上较为晦涩。实际开发中,可以根据个人对SK内核与设计理念的理解,自行选择使用以下写法,或使用普......
  • 使用 `omit` 函数移除敏感信息
    exportdefaultfunctionomit<Textendsobject,KextendskeyofT>(obj:T,fields:K[]|readonlyK[],):Omit<T,K>{constclone={...obj};if(Array.isArray(fields)){fields.forEach(key=>{deleteclone[key];......
  • Rust的函数__Function
    FunctionsareprevalentinRustcode.You’vealreadyseenoneofthemostimportantfunctionsinthelanguage:the main function,whichistheentrypointofmanyprograms.You’vealsoseenthe fnkeyword,whichallowsyoutodeclarenewfunctions.函数在......
  • PowerShell中管理和操作Windows映像,允许你执行各种任务,如挂载、修改、添加、移除、更
    管理和操作映像(如Windows映像)的PowerShell命令主要涉及到映像的获取、部署、修改等操作。以下是一些常用的PowerShell命令,可用于管理和操作映像:Get-WindowsImage:这个命令用于获取有关Windows映像的信息,包括版本、架构、安装状态等。powershellCopyCodeGet-WindowsImage-I......
  • lc 27移除元素
     如果找到要删除的目标元素,则将其后面所有元素往前移一格。要注意的是,由于所有元素往前移了一格,所以下标i也需要往前!!classSolution{  publicintremoveElement(int[]nums,intval){  intsize=nums.length;   for(inti=0;i<size;i++){    ......
  • Seurat Dimplot, Vlnplot画图时报错,Error in setup_panel_guides(..., self = self) :
    SeuratDimplot,Vlnplot画图时报错,Errorinsetup_panel_guides(...,self=self):unusedargument(list(~features.plot,~id))pdf(paste0("EBV_GaC","_Marker_genes_Vln.png"),width=30,height=10)>DotPlot(object=subset_cells,featur......
  • P1464 Function
    题目链接:本题为一道极其经典的记忆化搜索模板题,务必搞懂并掌握记忆化搜索的常见书写格式。主要思想就是用一个\(dp\)数组将每一个\(w\)函数的值存储起来,下一次检查\(dp[a][b][c]\)的值,如果已经算过就直接调用,可节省大量时间。#include<cstdio>usingLL=longlong;......
  • function ALV 获取OO ALV event ID
    SAPABAPALV(LVC)的一个自定义事件(F4帮助事件,回车ENTER按钮事件)的一个实例https://blog.csdn.net/zhongguomao/article/details/51775112 1.定义和注册事件接受器类*----------------------------------------------------------------------**CLASSLCL_EVENT_RECE......