[{"data":1,"prerenderedAt":1053},["ShallowReactive",2],{"content-query-MhcTdXJvQ0":3},{"_path":4,"_dir":5,"_draft":6,"_partial":6,"_locale":7,"title":8,"description":9,"date":10,"cover":11,"type":12,"category":13,"body":14,"_type":1047,"_id":1048,"_source":1049,"_file":1050,"_stem":1051,"_extension":1052},"/technology-blogs/zh/266","zh",false,"","MindSpore大V博文之架构系列（二）","本文重点分析一下AI框架对IR有什么特殊的需求、业界有什么样的方案以及MindSpore的一些思考。","2020-10-09","https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2020/10/09/2ca02b6a43e149bfb187135b7cfef397.png","technology-blogs","大V博文",{"type":15,"children":16,"toc":1037},"root",[17,25,31,34,40,53,64,69,80,85,90,95,100,111,116,136,141,151,156,161,166,171,179,184,189,194,201,206,211,216,221,229,234,242,247,252,257,265,270,278,283,288,296,301,306,313,318,323,331,336,344,349,354,362,367,373,378,383,401,406,412,417,425,430,438,443,451,456,464,469,477,482,487,493,501,506,514,519,524,531,536,543,548,553,560,565,574,581,586,593,598,603,608,613,618,623,629,634,639,647,652,657,662,667,672,680,685,691,696,714,719,724,729,734,742,747,752,757,762,770,775,783,788,795,800,805,810,815,823,828,836,841,848,853,861,866,871,879,884,891,896,901,906,911,919,924,931,936,947,958,963,974,985,990,998],{"type":18,"tag":19,"props":20,"children":22},"element","h1",{"id":21},"mindspore大v博文之架构系列二",[23],{"type":24,"value":8},"text",{"type":18,"tag":19,"props":26,"children":28},{"id":27},"ai框架中图层ir的分析",[29],{"type":24,"value":30},"AI框架中图层IR的分析",{"type":18,"tag":19,"props":32,"children":33},{"id":7},[],{"type":18,"tag":35,"props":36,"children":37},"p",{},[38],{"type":24,"value":39},"作者：金雪锋",{"type":18,"tag":35,"props":41,"children":42},{},[43,45],{"type":24,"value":44},"作者主页：",{"type":18,"tag":46,"props":47,"children":51},"a",{"href":48,"rel":49},"https://www.zhihu.com/people/jin-xue-feng",[50],"nofollow",[52],{"type":24,"value":48},{"type":18,"tag":35,"props":54,"children":55},{},[56,58],{"type":24,"value":57},"文章转自：",{"type":18,"tag":46,"props":59,"children":62},{"href":60,"rel":61},"https://zhuanlan.zhihu.com/p/263420069",[50],[63],{"type":24,"value":60},{"type":18,"tag":35,"props":65,"children":66},{},[67],{"type":24,"value":68},"前段时间一直忙于HC大会和MindSpore1.0的版本准备，国庆期间终于有点时间来交作业了，本文是AI框架分析专栏的第二篇，总体目录参见：",{"type":18,"tag":35,"props":70,"children":71},{},[72,74],{"type":24,"value":73},"AI框架的演进趋势和MindSpore的构想：",{"type":18,"tag":46,"props":75,"children":78},{"href":76,"rel":77},"https://www.mindspore.cn/news/newschildren?id=253",[50],[79],{"type":24,"value":76},{"type":18,"tag":35,"props":81,"children":82},{},[83],{"type":24,"value":84},"背景",{"type":18,"tag":35,"props":86,"children":87},{},[88],{"type":24,"value":89},"IR-Intermediate Representation（中间表示）是程序编译过程中，源代码与目标代码之间翻译的中介，IR的设计对编译器来说非常关键，好的IR要考虑从源代码到目标代码编译的完备性、编译优化的易用性和性能。",{"type":18,"tag":35,"props":91,"children":92},{},[93],{"type":24,"value":94},"AI框架本质的作用在于把一个把用户的模型表达翻译到可执行的代码，然后进行高效执行（训练和推理），其中从用户的模型表达（例如深度神经网络）到最后可执行的代码就是个编译器的行为，这个编译器也有一个IR，它的设计对AI框架的完备性/灵活性/易用性/性能都起到至关重要的作用；本文重点分析一下AI框架对IR有什么特殊的需求、业界有什么样的方案以及MindSpore的一些思考。",{"type":18,"tag":35,"props":96,"children":97},{},[98],{"type":24,"value":99},"在开始之前，我想先介绍一些背景知识—通用的编译器IR的分类以及各自特点",{"type":18,"tag":101,"props":102,"children":104},"h2",{"id":103},"业界ir的介绍",[105],{"type":18,"tag":106,"props":107,"children":108},"strong",{},[109],{"type":24,"value":110},"业界IR的介绍",{"type":18,"tag":35,"props":112,"children":113},{},[114],{"type":24,"value":115},"参考[1]，IR根据其组织结构，可以分为：",{"type":18,"tag":117,"props":118,"children":119},"ul",{},[120,126,131],{"type":18,"tag":121,"props":122,"children":123},"li",{},[124],{"type":24,"value":125},"Linear IR（线性IR）：类似某些抽象机的伪代码，对应的算法通过迭代来遍历简单的线性操作序列。",{"type":18,"tag":121,"props":127,"children":128},{},[129],{"type":24,"value":130},"Graphical IR（图IR）：将编译过程的知识/信息保存在图中，对应的算法通过对图中的对象（节点、边、列表和树）操作来描述。",{"type":18,"tag":121,"props":132,"children":133},{},[134],{"type":24,"value":135},"Hybrid IR（混合IR）：结合了图IR和线性IR的要素。一种常见的混合IR使用底层的线性IR来表示无循环代码块，使用图IR来表示这些块之间的控制流。",{"type":18,"tag":35,"props":137,"children":138},{},[139],{"type":24,"value":140},"线性IR的一个例子是堆栈机代码（Stack-Machine Code），它是一种单地址代码，假定操作数存在一个栈中。大多数操作从栈获得操作数，并将其结果推入栈中。例如：表达式 b-a*3对应的堆栈机代码如下：",{"type":18,"tag":142,"props":143,"children":145},"pre",{"code":144},"push 3\npush a\nmultiply\npush a\nsubstract\n",[146],{"type":18,"tag":147,"props":148,"children":149},"code",{"__ignoreMap":7},[150],{"type":24,"value":144},{"type":18,"tag":35,"props":152,"children":153},{},[154],{"type":24,"value":155},"LLVM IR是一个典型的混合IR，它包含了两个层次（CFG+BB）：",{"type":18,"tag":35,"props":157,"children":158},{},[159],{"type":24,"value":160},"顶层是控制流图（Control Flow Graph，简写为CFG），来表示基本块（Basic Block，简写为BB）间的控制流。CFG的每个节点（Node）为一个基本块，基本块b1和b2之间有一条边（Edge）：b1->b2，如果控制流可能从基本块b1的最后一条指令流向基本块b2的第一条指令。",{"type":18,"tag":35,"props":162,"children":163},{},[164],{"type":24,"value":165},"底层是基本块，在基本块中，每条指令是以SSA（Static Single Assignment）形式呈现，这些指令构成一个指令线性列表。",{"type":18,"tag":35,"props":167,"children":168},{},[169],{"type":24,"value":170},"Sea of Nodes IR（by Cliff Click）是一种典型的图IR，参考[2]，在这种IR中，简化了CFG图中BB+SSA指令的两层结构，去除了BB，剩下只包含指令的一层结构。它通过引入了特殊的REGION、IF、PROJECTION指令，将BB块中的全序指令放松为显式的数据依赖和控制依赖，并且对控制依赖和数据依赖采用相同的表示方式和处理方式，这样就简化了IR的分析和变换。如下为一个简单的IR示例：",{"type":18,"tag":35,"props":172,"children":173},{},[174],{"type":18,"tag":175,"props":176,"children":178},"img",{"alt":7,"src":177},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2020/10/09/57cc381c50714a6b9252791bd1996ac2.jpg",[],{"type":18,"tag":35,"props":180,"children":181},{},[182],{"type":24,"value":183},"在这个示例中，方框为图的节点，表示SSA指令，箭头为图的边；实心箭头表示控制依赖；空心箭头表示数据依赖。从这个示例中可以看到此IR中显式的包含了use-def依赖，不需要进行额外的计算。",{"type":18,"tag":35,"props":185,"children":186},{},[187],{"type":24,"value":188},"基于此IR中显式的use-def信息，可以方便的实现两类优化：1、Parse time优化（Pessimistic）；2、全局优化(Optimistic)；",{"type":18,"tag":35,"props":190,"children":191},{},[192],{"type":24,"value":193},"在Parse的时候，由于还没有程序的全部信息，所以只可做局部的优化，如窥孔优化（例：常量折叠，Identity-function）。通过设计合适的类及继承体系，可以使用简单的算法实现peephole优化：",{"type":18,"tag":35,"props":195,"children":196},{},[197],{"type":18,"tag":175,"props":198,"children":200},{"alt":7,"src":199},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2020/10/09/f5fbf177f2b14db8a9ea89f8c66534ae.jpg",[],{"type":18,"tag":35,"props":202,"children":203},{},[204],{"type":24,"value":205},"对于全局优化，比如Sparse Conditional Constant Propagation（SCCP），也可以很简单的实现；首先是基于图中显式的use-def计算出def-use chains，然后可以很容易的实现SCCP。具体可以参考论文。",{"type":18,"tag":35,"props":207,"children":208},{},[209],{"type":24,"value":210},"Sea of Nodes IR提供了一种非常重要的思路：将依赖信息显式的表示在图IR中。FIRM IR中延续了这个思路。",{"type":18,"tag":35,"props":212,"children":213},{},[214],{"type":24,"value":215},"从常用编程语言的角度来分析IR，我们又可以看到IR的形式分为了两个不同的阵营，一类是命令式编程语言的编译器IR，另外一类是函数编程语言的编译器IR；命令式编程语言的编译器IR以SSA为基本的组成形式，这里就不在赘述了，下面重点介绍一下函数式编程语言的IR，在函数式编程语言的IR中，CPS或者ANF是其基本的组成形式。",{"type":18,"tag":35,"props":217,"children":218},{},[219],{"type":24,"value":220},"Continuation-passing style（CPS）直译为：连续传递风格。CPS 表示这样一种形式：一个函数 f 除了它自身的参数外，总是有一个额外的参数continuation。continuation也是一个函数，当f完成了自己的返回值计算之后，不是返回，而是将此返回值作为continuation的参数，调用continuation。所以CPS形式的函数从形式上看它不会return，当它要return 的时候会将所有的参数传递给continuation，让continuation继续去执行。比如：",{"type":18,"tag":142,"props":222,"children":224},{"code":223},"def foo(x):\nreturn x+1\n",[225],{"type":18,"tag":147,"props":226,"children":227},{"__ignoreMap":7},[228],{"type":24,"value":223},{"type":18,"tag":35,"props":230,"children":231},{},[232],{"type":24,"value":233},"转换为CPS形式，k就是一个continuation：",{"type":18,"tag":142,"props":235,"children":237},{"code":236},"def foo(x,k):\nk(x+1)\n",[238],{"type":18,"tag":147,"props":239,"children":240},{"__ignoreMap":7},[241],{"type":24,"value":236},{"type":18,"tag":35,"props":243,"children":244},{},[245],{"type":24,"value":246},"直观上看，函数不“return”，而是“continue”;",{"type":18,"tag":35,"props":248,"children":249},{},[250],{"type":24,"value":251},"CPS的优点是让如下的信息显式化：过程返回（调用一个continuation），中间值（具有显式的名称），求值顺序，尾调用（采用相同的continuation调用一个过程）。",{"type":18,"tag":35,"props":253,"children":254},{},[255],{"type":24,"value":256},"比如如下的一段python代码，求小于n的所有素数的积。",{"type":18,"tag":142,"props":258,"children":260},{"code":259},"def prodprimes(n):\n    if n == 1:\n        return 1\n    if isprime(n):\n        return n * prodprimes(n - 1)\nreturn prodprimes(n - 1)\n",[261],{"type":18,"tag":147,"props":262,"children":263},{"__ignoreMap":7},[264],{"type":24,"value":259},{"type":18,"tag":35,"props":266,"children":267},{},[268],{"type":24,"value":269},"当采用CPS形式表示时：",{"type":18,"tag":142,"props":271,"children":273},{"code":272},"def prodprimes(n, c):\n    def k(b):\n        if b == True:\n            m = n - 1\n            def j(p):\n                a = n * p\n                c(a)\n            prodprimes(m, j)\n        else:\n            def h(q):\n                c(q)\n            i = n - 1\n            prodprimes(i, h)\n    if n == 1:\n        c(1)\n    else:\n        isprime(n, k)\n",[274],{"type":18,"tag":147,"props":275,"children":276},{"__ignoreMap":7},[277],{"type":24,"value":272},{"type":18,"tag":35,"props":279,"children":280},{},[281],{"type":24,"value":282},"从上面的代码中可以看到，“过程返回”都被调用c、j、k、h等continuation代替；中间值a、b、m、i都被给予了变量名称。",{"type":18,"tag":35,"props":284,"children":285},{},[286],{"type":24,"value":287},"CPS形式非常适合编译器进行分析和变换，比如tail-recursion elimination变换：如果函数f的最后是调用函数g，那么函数g的continuation就不需要是在f内生成的一个continuation，而可以被替换为传递给f的continuation。上面的例子的原始代码中，“return prodprimes(n - 1)”语句就是一个尾递归。在CPS形式中，可以很清楚的看到h(q）的定义其实就等于c(q)，所以可以说h等于c，于是可以进行如下的变换：",{"type":18,"tag":142,"props":289,"children":291},{"code":290},"def h(q):                         i = n - 1\n    c(q)            ->           prodprimes(i, c)\ni = n - 1\nprodprimes(i, h)\n",[292],{"type":18,"tag":147,"props":293,"children":294},{"__ignoreMap":7},[295],{"type":24,"value":290},{"type":18,"tag":35,"props":297,"children":298},{},[299],{"type":24,"value":300},"参考【3】",{"type":18,"tag":35,"props":302,"children":303},{},[304],{"type":24,"value":305},"虽然CPS非常一致和强大，但是它的一个很大问题是难以阅读。所以出现了A-norm Form（ANF）形式。ANF形式直接对Direct Style的源码进行转换，不需要经过CPS形式。参考[4]",{"type":18,"tag":35,"props":307,"children":308},{},[309],{"type":18,"tag":175,"props":310,"children":312},{"alt":7,"src":311},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2020/10/09/92bd78f53f15432d9349fae559aca811.jpg",[],{"type":18,"tag":35,"props":314,"children":315},{},[316],{"type":24,"value":317},"ANF形式将表达式划分为两类：原子表达式和复合表达式，原子表达式表示一个常数值或一个变量或一个原语或一个匿名函数；复合表达式由多个原子表达式复合组成，可以看成是一个匿名函数或原语函数调用，组合的第一个输入是调用的函数，其余输入是调用的参数。一个复合表达式要么被let-bound到一个变量，要么只能出现在最后的位置。可以看到，ANF形式通过let-bound，显式表达了中间值和控制流及求值顺序。",{"type":18,"tag":35,"props":319,"children":320},{},[321],{"type":24,"value":322},"它的文法定义如下，参考[5]：",{"type":18,"tag":142,"props":324,"children":326},{"code":325}," ::= NUMBER | STRING | VAR | BOOLEAN | PRIMOP\n          |  (lambda (VAR …) )\n ::= (  …)\n          |  (if   )\n ::= (let ([VAR ]) ) |  | \n",[327],{"type":18,"tag":147,"props":328,"children":329},{"__ignoreMap":7},[330],{"type":24,"value":325},{"type":18,"tag":35,"props":332,"children":333},{},[334],{"type":24,"value":335},"例如上面的prodprimes函数，如果用上述的文法表示，应该为：",{"type":18,"tag":142,"props":337,"children":339},{"code":338},"(define prodprimes\n  (lambda (n)\n    (let (a (= n 1))\n      (if a 1 (let (b isprime(n))\n                   (if b (let (m (- n 1))\n                           (let (p (prodprimes m))\n                             (* n p)))\n                         (let (s (- n 1))\n                           (prodprimes m))\n                    ))))))\n",[340],{"type":18,"tag":147,"props":341,"children":342},{"__ignoreMap":7},[343],{"type":24,"value":338},{"type":18,"tag":35,"props":345,"children":346},{},[347],{"type":24,"value":348},"这段ANF形式表达，如果翻译为python：",{"type":18,"tag":35,"props":350,"children":351},{},[352],{"type":24,"value":353},"应该类似于：",{"type":18,"tag":142,"props":355,"children":357},{"code":356},"def prodprimes(n):\n    r = n == 1\n    if r:\n        return 1\n    b = isprime(n)\n    if b:\n        m = n - 1\n        p = prodprimes(m)\n        return n * p\n    s = n - 1\nreturn prodprimes(s)\n",[358],{"type":18,"tag":147,"props":359,"children":360},{"__ignoreMap":7},[361],{"type":24,"value":356},{"type":18,"tag":35,"props":363,"children":364},{},[365],{"type":24,"value":366},"通过这段代码，也可以看出，ANF形式比CPS形式简单易懂。",{"type":18,"tag":101,"props":368,"children":370},{"id":369},"ai框架中图层ir的作用",[371],{"type":24,"value":372},"AI框架中图层IR的作用",{"type":18,"tag":35,"props":374,"children":375},{},[376],{"type":24,"value":377},"现在主流的AI框架都有图层IR，好的图层IR有利于AI模型的编译优化和执行，是AI框架进行高效训练和推理的基础。",{"type":18,"tag":35,"props":379,"children":380},{},[381],{"type":24,"value":382},"从训练的角度看，目前业界的AI框架有三种执行模式：Eager执行模式、图执行模式和Staging(混合)执行模式，其中高性能模式下（Graph执行模式和Staging执行模式）都要基于图层IR：",{"type":18,"tag":117,"props":384,"children":385},{},[386,391,396],{"type":18,"tag":121,"props":387,"children":388},{},[389],{"type":24,"value":390},"Eager执行模式一般是利用宿主语言（现在主要是Python）的特性进行解释执行，里面使用了重载和Tape的一些技巧。",{"type":18,"tag":121,"props":392,"children":393},{},[394],{"type":24,"value":395},"Graph执行模式主要是拿到AI模型的图结构，然后进行编译优化和执行，这里的编译优化和执行就要基于图IR，额外提一下，现在有三种方法拿到AI模型的图结构，第一种是程序员使用API构图（TF1.x版本等）；第二种是Tracing JIT（JAX带来的潮流，现在TF2.0/Pytorch等都支持），即把用户的模型脚本模拟跑一下，拿到正向的执行序列，然后基于这个序列进行构图，好处是与Eagle模式比较容易匹配，实现简单，缺点是控制流的转换比较麻烦、执行序列如果与算子执行结果相关的话不好实现、不容易处理副作用，所以TF的AutoGraph还需要结合AST分析解决控制流转换的问题；第三种是AST JIT（Pytorch的TorchScript），基于Python的AST进行构图，优点是转换的功能可以比较全面，包括控制流等，缺点是实现复杂，许多Python动态特性实现起来工作量大。",{"type":18,"tag":121,"props":397,"children":398},{},[399],{"type":24,"value":400},"Staging执行模式类似在Eager模式中，通过Python修饰符，对部分子图进行编译执行加速（使用Tracing JIT或者AST JIT），也会用到图IR。",{"type":18,"tag":35,"props":402,"children":403},{},[404],{"type":24,"value":405},"从推理的角度看，AI框架生成最终的推理模型时需要进行大量的编译优化，如量化、剪枝等，一般都在图层IR上进行，同时最终的推理模型格式也是直接或者间接使用到图层IR。",{"type":18,"tag":101,"props":407,"children":409},{"id":408},"ai框架图层ir的需求和挑战",[410],{"type":24,"value":411},"AI框架图层IR的需求和挑战",{"type":18,"tag":35,"props":413,"children":414},{},[415],{"type":24,"value":416},"与其他通用的IR相比，AI框架的图层IR有一些比较特殊的需求和挑战：",{"type":18,"tag":117,"props":418,"children":419},{},[420],{"type":18,"tag":121,"props":421,"children":422},{},[423],{"type":24,"value":424},"张量表达",{"type":18,"tag":35,"props":426,"children":427},{},[428],{"type":24,"value":429},"AI的模型主要处理的是张量数据，这个与普通的应用差别是比较大的，不过增加张量数据类型对编译器的IR来说并不是件困难的事情。",{"type":18,"tag":117,"props":431,"children":432},{},[433],{"type":18,"tag":121,"props":434,"children":435},{},[436],{"type":24,"value":437},"自动微分",{"type":18,"tag":35,"props":439,"children":440},{},[441],{"type":24,"value":442},"可微分是AI模型开发与一般应用开发区别最大的地方，现代的AI框架都会提供自动微分的功能，挑战在于实现的简洁性、性能以及未来高阶微分的扩展能力。",{"type":18,"tag":117,"props":444,"children":445},{},[446],{"type":18,"tag":121,"props":447,"children":448},{},[449],{"type":24,"value":450},"JIT能力",{"type":18,"tag":35,"props":452,"children":453},{},[454],{"type":24,"value":455},"无论是图模式还是Staging模式，从算法工程师角度看，由于没有显示编译的步骤，都可以认为是JIT方式。对于JIT来说，编译性能是一个主要挑战。",{"type":18,"tag":117,"props":457,"children":458},{},[459],{"type":18,"tag":121,"props":460,"children":461},{},[462],{"type":24,"value":463},"隐式并行",{"type":18,"tag":35,"props":465,"children":466},{},[467],{"type":24,"value":468},"从开发者来说，有两种并行方式，一种是是显式并行，开发者明确告诉系统哪里并行，比如显示启动多线程/添加并行修饰符；还有一种方式是隐式并行，通过编译器来分析依赖，自动实现并行。一般而言，传统的CFG+BB的编译器，由于程序分析使用全序分析，方便做显式并行；函数式的编译器理论上易于数据依赖分析，方便进行隐式并行优化。有趣的是，在深度学习场景中，Kernel执行占了大部分开销，在运行时实现异步并发的模式也可以显著提升整体性能，隐式并行的作用相对会被弱化，但是想要实现极致性能，隐式并行还是有作用的。",{"type":18,"tag":117,"props":470,"children":471},{},[472],{"type":18,"tag":121,"props":473,"children":474},{},[475],{"type":24,"value":476},"Loop优化",{"type":18,"tag":35,"props":478,"children":479},{},[480],{"type":24,"value":481},"AI的计算涉及大量的Tensor运算，对编译器来说就是Loop优化（张量—>标量—>向量化），不过这个挑战主要还是在算子层的IR上。",{"type":18,"tag":35,"props":483,"children":484},{},[485],{"type":24,"value":486},"当然，图层IR也是是一种编译器IR，应该具备通用性，包括类型系统、控制流和数据流分析、副作用消除等基本的功能。",{"type":18,"tag":101,"props":488,"children":490},{"id":489},"业界在图层ir上的一些流派",[491],{"type":24,"value":492},"业界在图层IR上的一些流派",{"type":18,"tag":117,"props":494,"children":495},{},[496],{"type":18,"tag":121,"props":497,"children":498},{},[499],{"type":24,"value":500},"计算图的IR：一种以DAG为中心的实现方式，许多早期的框架都是使用了这种方案。他的设计比较自然，计算图主要由边和节点组成，节点一般用来表达算子、变量、常量等等；边对应于Tensors，实际上表达了一种数据依赖关系。后面的自动微分和优化都是基于这个DAG进行，这一块网上的资料很多，我就不赘述。",{"type":18,"tag":35,"props":502,"children":503},{},[504],{"type":24,"value":505},"总结：这个方案的优点是简单直观、优化时的性能开销小；不足之处是计算图IR不算是真正形式化的编译器IR，在类型系统、复杂逻辑的支持（比如递归）、副作用处理、控制流和数据流分析方面支持不完整。",{"type":18,"tag":117,"props":507,"children":508},{},[509],{"type":18,"tag":121,"props":510,"children":511},{},[512],{"type":24,"value":513},"CFG+BB：基于传统编译器的IR来做图层IR，比如TorchScript、Julia等。",{"type":18,"tag":35,"props":515,"children":516},{},[517],{"type":24,"value":518},"如何实现自动微分？我们以Julia Zygote为例，参考[6]：",{"type":18,"tag":35,"props":520,"children":521},{},[522],{"type":24,"value":523},"对于BB块内的普通代码（非phi，非branch），借助链式法则，可以按照反向的顺序生成AD代码。",{"type":18,"tag":35,"props":525,"children":526},{},[527],{"type":18,"tag":175,"props":528,"children":530},{"alt":7,"src":529},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2020/10/09/6d523739536349c0b975db7353d2ea28.jpg",[],{"type":18,"tag":35,"props":532,"children":533},{},[534],{"type":24,"value":535},"将上述的表达式表示为SSA后，并插入J及计算AD，可以得到如下图表示的伪SSA代码：",{"type":18,"tag":35,"props":537,"children":538},{},[539],{"type":18,"tag":175,"props":540,"children":542},{"alt":7,"src":541},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2020/10/09/d33efeea7dea442fb890af0054544e2e.jpg",[],{"type":18,"tag":35,"props":544,"children":545},{},[546],{"type":24,"value":547},"上图中的 %6 这里节点称为“alpha node”，对应的是Primal中的节点%6，也就是上面一排的B3，“/”operation的反向函数。",{"type":18,"tag":35,"props":549,"children":550},{},[551],{"type":24,"value":552},"对于CFG间的控制流，需要对控制流进行反向分析，并在Primal CFG中插入适当的哑phi节点来记录和回放控制流。例如这一段计算power的代码：",{"type":18,"tag":35,"props":554,"children":555},{},[556],{"type":18,"tag":175,"props":557,"children":559},{"alt":7,"src":558},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2020/10/09/7a5338320317427c8a62a91eafde0dd2.jpg",[],{"type":18,"tag":35,"props":561,"children":562},{},[563],{"type":24,"value":564},"对应的 Primal CFG中，插入了 %1 phi节点作为哑phi节点来记录控制流。然后在AD CFG中使用此 %1 来进行控制（%1记录通过入栈控制流，然后在AD CFG中通过出栈来回放控制流）。",{"type":18,"tag":35,"props":566,"children":567},{},[568],{"type":18,"tag":569,"props":570,"children":571},"em",{},[572],{"type":24,"value":573},"注：AD CFG中的 block #1中goto #4，感觉应该是goto #2；block #2中goto #2，应该是goto #1。",{"type":18,"tag":35,"props":575,"children":576},{},[577],{"type":18,"tag":175,"props":578,"children":580},{"alt":7,"src":579},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2020/10/09/6fefef48303c48c09661032d9837a818.jpg",[],{"type":18,"tag":35,"props":582,"children":583},{},[584],{"type":24,"value":585},"通过后续的代码优化，AD的Power代码类似如下的伪代码：",{"type":18,"tag":35,"props":587,"children":588},{},[589],{"type":18,"tag":175,"props":590,"children":592},{"alt":7,"src":591},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2020/10/09/63a9ff0d762e4ea3ac2902bd159b6613.jpg",[],{"type":18,"tag":35,"props":594,"children":595},{},[596],{"type":24,"value":597},"可以看出，CFG+BB的自动微分最终是通过迭代的方式来实现的，带Scope的SSA形式需要解决边界传递的问题对自动微分还是会带来一些处理上的麻烦。",{"type":18,"tag":35,"props":599,"children":600},{},[601],{"type":24,"value":602},"如何做图优化？",{"type":18,"tag":35,"props":604,"children":605},{},[606],{"type":24,"value":607},"转化成use-def、def-use的形式进行优化。",{"type":18,"tag":35,"props":609,"children":610},{},[611],{"type":24,"value":612},"如何做并行优化？",{"type":18,"tag":35,"props":614,"children":615},{},[616],{"type":24,"value":617},"由于CFG+BB是全序的方式，需要转换成use-def，并结合副作用信息进行分析。",{"type":18,"tag":35,"props":619,"children":620},{},[621],{"type":24,"value":622},"总结：使用CFG+BB方案的好处是功能完备、方案成熟、重用性高，不过CFG+BB的形式对自动微分/图优化/并行优化来说，都要进行一定的转换工作，并不是那么直观和高效。",{"type":18,"tag":101,"props":624,"children":626},{"id":625},"函数式ir使用函数式的ir来做图层ir典型的如relaymyia等",[627],{"type":24,"value":628},"函数式IR：使用函数式的IR来做图层IR，典型的如Relay、Myia等。",{"type":18,"tag":35,"props":630,"children":631},{},[632],{"type":24,"value":633},"如何实现自动微分？",{"type":18,"tag":35,"props":635,"children":636},{},[637],{"type":24,"value":638},"对于非控制流，计算AD的方法和上述的BB块内计算AD的方法相同。对于控制流，函数式IR采用了不同的处理方式，将迭代转换为递归，并且通过switch函数来进行分支的选择。例如上述相同的pow()函数：",{"type":18,"tag":142,"props":640,"children":642},{"code":641},"def pow(x, n):\n    return header_pow(n, 1, x)\ndef header_pow(phi_n, phi_r, x):\ndef body_pow():\n    phi_n_1 = phi_n - 1\n    phi_r_1 = phi_r * x\n        return header_pow(phi_n_1, phi_r_1, x)\n    def after_pow():\n        return phi_r\n    f = switch(phi_n > 0, header_pow, after_pow)\n    f()\n",[643],{"type":18,"tag":147,"props":644,"children":645},{"__ignoreMap":7},[646],{"type":24,"value":641},{"type":18,"tag":35,"props":648,"children":649},{},[650],{"type":24,"value":651},"以pow(5,3) 为例，其递归调用过程如下：",{"type":18,"tag":35,"props":653,"children":654},{},[655],{"type":24,"value":656},"pow(5, 3) -> header_pow(3, 1, 5) -> body_pow() -> header_pow(2, 5, 5) -> body_pow() -> header_pow(1, 5*5, 5) -> body_pow -> header_pow(0, 5*5*5, 5) -> after_pow() (此时return 5*5*5)",{"type":18,"tag":35,"props":658,"children":659},{},[660],{"type":24,"value":661},"可以看到，这里的递归调用的调用和返回分别就对应了上述CFG+BB的控制流phi节点入栈和出栈操作。",{"type":18,"tag":35,"props":663,"children":664},{},[665],{"type":24,"value":666},"由于AD过程就是对函数进行变换的过程，所以AD后的图也是递归调用的结构，因此不需要类似CFG+BB的控制流phi节点入栈和出栈操作，递归调用过程天然的就代替了入栈和出栈的过程。",{"type":18,"tag":35,"props":668,"children":669},{},[670],{"type":24,"value":671},"# 对x求导数",{"type":18,"tag":142,"props":673,"children":675},{"code":674},"def x_grad_pow(x, n):\n    phi_n = n\n    phi_r = 1\n    return x_bprop_header_pow(phi_n, phi_r, x, 1)\n\ndef x_bprop_header_pow(phi_n, phi_r, x, sens):\n    def env_x_bprop_body_pow():\n        %3 = x_bprop_header_pow(phi_n – 1, phi_r * phi_x, x, 1)\n        %4 = phi_r_bprop_header_pow(phi_n – 1, phi_r * phi_x, x, 1)\n        %5 = %4 * phi_r\n        return %3 + %5\n    def env_x_bprop_after_pow():\n        return 0\n\n    f = switch(phi_n > 0, env_x_bprop_body_pow, env_x_bprop_after_pow)\n    r = switch(phi_n > 0, f(), 0)\n    return r\n\ndef phi_r_bprop_header_pow(phi_n, phi_r, x, sens):\n    def env_phi_r_bprop_body_pow():\n        %3 = phi_r_bprop_header_pow(phi_n - 1, phi_r * x, x, 1)\n        %4 = %3 * x\n        return %4\n\n    def env_phi_r_bprop_after_pow():\n        return 1\n\n    if phi_n > 0:\n        %5 = env_phi_r_bprop_body_pow()\n    else:\n        %5 = env_phi_r_bprop_after_pow()\nreturn %5\n",[676],{"type":18,"tag":147,"props":677,"children":678},{"__ignoreMap":7},[679],{"type":24,"value":674},{"type":18,"tag":35,"props":681,"children":682},{},[683],{"type":24,"value":684},"总结：函数式IR的好处是对自动微分友好，比较适合做并行分析，不过挑战在于函数IR的副作用消除以及函数式IR在执行态的性能（含有递归对执行不友好）。",{"type":18,"tag":101,"props":686,"children":688},{"id":687},"mindspore的设计思考",[689],{"type":24,"value":690},"MindSpore的设计思考",{"type":18,"tag":35,"props":692,"children":693},{},[694],{"type":24,"value":695},"MindSpore的图层IR叫做MindIR，MindIR选择的技术路线是采用Functional Graph IR（参考了Sea of Nodes 、Thorin、Myia等），具有如下特征：",{"type":18,"tag":117,"props":697,"children":698},{},[699,704,709],{"type":18,"tag":121,"props":700,"children":701},{},[702],{"type":24,"value":703},"Functional—更自然的自动微分实现方式和更方便的隐式并行分析能力：函数作为一等公民，支持高阶函数，包括控制流也通过特殊的函数来实现，可以以统一的形式来实现微分；函数以无副作用的方式实现，与命令式语言相比，可简化分析和实现更多的优化；原生支持闭包，一方面可以方便的表达用户源代码中的闭包表示，另外也可以自然的支持自动微分算法中在反向函数中要访问原始函数的中间结果的要求：反向函数访问中间结果，并且作为一个闭包返回；使用基于数据依赖的偏序分析，这样可以便于乱序或者并行执行。",{"type":18,"tag":121,"props":705,"children":706},{},[707],{"type":24,"value":708},"Graph based—更适合JIT的快速优化能力：采用类似Sea of Nodes IR的只有一层的表示方式，控制流和数据流合一，更适合JIT优化。",{"type":18,"tag":121,"props":710,"children":711},{},[712],{"type":24,"value":713},"ANF形式：和Thorin类似，都采用Graph IR，都消除了Scope。但是没有采用Thorin IR的CPS形式，而是表达能力类似，更直观也更易检查的ANF形式。",{"type":18,"tag":35,"props":715,"children":716},{},[717],{"type":24,"value":718},"总结，MindIR希望通过Functional的方式更方便的实现自动微分和隐式并行分析，Graph Based方式把控制流和数据流合一支持更高效的JIT优化。",{"type":18,"tag":35,"props":720,"children":721},{},[722],{"type":24,"value":723},"1、MindIR的详解",{"type":18,"tag":35,"props":725,"children":726},{},[727],{"type":24,"value":728},"参考[7]",{"type":18,"tag":35,"props":730,"children":731},{},[732],{"type":24,"value":733},"MindIR文法继承于ANF，其定义如下所示：",{"type":18,"tag":142,"props":735,"children":737},{"code":736}," ::=  | \n ::= Parameter\n ::= Scalar | Named | Tensor | Type | Shape\n               | Primitive | MetaFuncGraph | FuncGraph \n ::= ( …)\n ::=  | \n",[738],{"type":18,"tag":147,"props":739,"children":740},{"__ignoreMap":7},[741],{"type":24,"value":736},{"type":18,"tag":35,"props":743,"children":744},{},[745],{"type":24,"value":746},"MindIR中的ANode对应于ANF的原子表达式，ANode有两个子类分别为ValueNode和ParameterNode。ValueNode表示常数节点，可承载一个常数值（标量、符号、张量、类型、维度等），也可以是一个原语函数（Primitive）或一个元函数（MetaFuncGraph）或一个普通函数（FuncGraph），因为在函数式编程中函数定义本身也是一个值。ParameterNode是参数节点，表示函数的形参。",{"type":18,"tag":35,"props":748,"children":749},{},[750],{"type":24,"value":751},"MindIR中CNode对应于ANF的复合表达式，表示一次函数调用。",{"type":18,"tag":35,"props":753,"children":754},{},[755],{"type":24,"value":756},"在MindSpore自动微分时，会计算ParameterNode和CNode的梯度贡献，并返回最终ParameterNode的梯度，而不计算ValueNode的梯度。",{"type":18,"tag":35,"props":758,"children":759},{},[760],{"type":24,"value":761},"下面以一段程序作为示例，对比理解MindIR。",{"type":18,"tag":142,"props":763,"children":765},{"code":764},"def func(x, y):\n return x / y\n\n@ms_function\ndef test_f(x, y):\n    a = x - 1\n    b = a + y\n    c = b * func(a, b)\n return c\n",[766],{"type":18,"tag":147,"props":767,"children":768},{"__ignoreMap":7},[769],{"type":24,"value":764},{"type":18,"tag":35,"props":771,"children":772},{},[773],{"type":24,"value":774},"这段Python代码对应的ANF表达为：",{"type":18,"tag":142,"props":776,"children":778},{"code":777},"lambda (x, y)\n    let a = x - 1 in\n    let b = a + y in\n    let func = lambda (x, y)\n        let ret = x / y in\n        ret end in\n    let %1 = func(a, b) in\n    let c = b * %1 in\n    c end\n",[779],{"type":18,"tag":147,"props":780,"children":781},{"__ignoreMap":7},[782],{"type":24,"value":777},{"type":18,"tag":35,"props":784,"children":785},{},[786],{"type":24,"value":787},"对应的MindIR为ir.dot：",{"type":18,"tag":35,"props":789,"children":790},{},[791],{"type":18,"tag":175,"props":792,"children":794},{"alt":7,"src":793},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2020/10/09/9b9cba0bd0d04218a5e558a5cdcd72bb.jpg",[],{"type":18,"tag":35,"props":796,"children":797},{},[798],{"type":24,"value":799},"在MindIR中，一个函数图（FuncGraph）表示一个普通函数的定义，函数图一般由ParameterNode、ValueNode和CNode组成有向无环图，可以清晰地表达出从参数到返回值的计算过程。在上图中可以看出，python代码中两个函数test_f和func转换成了两个函数图，其参数x和y转换为函数图的ParameterNode，每一个表达式转换为一个CNode。CNode的第一个输入链接着调用的函数，例如图中的add、func、return。值得注意的是这些节点均是ValueNode，因为它们被理解为常数函数值。CNode的其他输入链接这调用的参数，参数值可以来自于ParameterNode、ValueNode和其他CNode。",{"type":18,"tag":35,"props":801,"children":802},{},[803],{"type":24,"value":804},"在ANF中每个表达式都用let表达式绑定为一个变量，通过对变量的引用来表示对表达式输出的依赖，而在MindIR中每个表达式都绑定为一个节点，通过节点与节点之间的有向边表示依赖关系。",{"type":18,"tag":35,"props":806,"children":807},{},[808],{"type":24,"value":809},"2、函数式语义",{"type":18,"tag":35,"props":811,"children":812},{},[813],{"type":24,"value":814},"MindIR较传统计算图的一个重要特性是不仅可以表达算子之间的数据依赖，还可以表达丰富的函数式语义。",{"type":18,"tag":35,"props":816,"children":817},{},[818],{"type":18,"tag":106,"props":819,"children":820},{},[821],{"type":24,"value":822},"高阶函数",{"type":18,"tag":35,"props":824,"children":825},{},[826],{"type":24,"value":827},"在MindIR中，函数的定义是由一个子图来定义，但其本身可以是一个被传递的值，作为其他高阶函数的输入或输出。 例如下面一个简单的示例中，函数f作为参数传入了函数g，因此函数g是一个接收函数输入的高阶函数，函数f真正的调用点是在函数g内部。",{"type":18,"tag":142,"props":829,"children":831},{"code":830},"@ms_function\ndef hof(x):\n def f(x):\n return x + 3\n def g(function, x):\n return function(x) * function(x)\n    res = g(f, x)\n return res\n",[832],{"type":18,"tag":147,"props":833,"children":834},{"__ignoreMap":7},[835],{"type":24,"value":830},{"type":18,"tag":35,"props":837,"children":838},{},[839],{"type":24,"value":840},"对应的MindIR为hof.dot：",{"type":18,"tag":35,"props":842,"children":843},{},[844],{"type":18,"tag":175,"props":845,"children":847},{"alt":7,"src":846},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2020/10/09/38b77be4800842c8b6d452fbeb6ab912.jpg",[],{"type":18,"tag":35,"props":849,"children":850},{},[851],{"type":24,"value":852},"在实际网络训练脚本中，自动求导泛函GradOperation和优化器中常用到的Partial和HyperMap都是典型的高阶函数。高阶语义极大地提升了MindSpore表达的灵活性和简洁性。",{"type":18,"tag":35,"props":854,"children":855},{},[856],{"type":18,"tag":106,"props":857,"children":858},{},[859],{"type":24,"value":860},"控制流",{"type":18,"tag":35,"props":862,"children":863},{},[864],{"type":24,"value":865},"控制流在MindIR中是以高阶函数选择调用的形式表达。这样的形式把控制流转换为高阶函数的数据流，从而使得自动微分算法更加强大。不仅可以支持数据流的自动微分，还可以支持条件跳转、循环和递归等控制流的自动微分。",{"type":18,"tag":35,"props":867,"children":868},{},[869],{"type":24,"value":870},"下面以一个简单的斐波那契用例来演示说明。",{"type":18,"tag":142,"props":872,"children":874},{"code":873},"@ms_function\ndef fibonacci(n):\n if(n \u003C 1):\n return 0\n elif(n == 1):\n return 1\n else:\n return fibonacci(n-1) + fibonacci(n-2)\n",[875],{"type":18,"tag":147,"props":876,"children":877},{"__ignoreMap":7},[878],{"type":24,"value":873},{"type":18,"tag":35,"props":880,"children":881},{},[882],{"type":24,"value":883},"对应的MindIR为cf.dot：",{"type":18,"tag":35,"props":885,"children":886},{},[887],{"type":18,"tag":175,"props":888,"children":890},{"alt":7,"src":889},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2020/10/09/3a70d017eeae490e8a70ba588643665a.jpg",[],{"type":18,"tag":35,"props":892,"children":893},{},[894],{"type":24,"value":895},"其中fibonacci是顶层函数图，在顶层中有两个函数图被switch选择调用。✓fibonacci是第一个if的True分支，✗fibonacci是第一个if的False分支。在✗fibonacci中被调用的✓✗fibonacci是elif的True分支，✗✗fibonacci是elif的False分支。这里需要理解的关键是在MindIR中，条件跳转和递归是以高阶控制流的形式表达的。例如，✓fibonacci和✗fibonacci是作为switch算子的参数传入，switch根据条件参数选择哪一个函数作为返回值。因此，switch是把输入的函数当成普通的值做了一个二元选择操作，并没有调用，而真正的函数调用是在紧随switch后的CNode上完成。",{"type":18,"tag":35,"props":897,"children":898},{},[899],{"type":24,"value":900},"自由变量和闭包",{"type":18,"tag":35,"props":902,"children":903},{},[904],{"type":24,"value":905},"闭包（closure）是一种编程语言特性，它指的是代码块和作用域环境的结合。自由变量(free variable)是指在代码块中引用作用域环境中的变量而非局部变量。在MindIR中，代码块是以函数图呈现的，而作用域环境可以理解为该函数被调用时的上下文环境，自由变量的捕获方式是值拷贝而非引用。",{"type":18,"tag":35,"props":907,"children":908},{},[909],{"type":24,"value":910},"一个典型的闭包用例如下：",{"type":18,"tag":142,"props":912,"children":914},{"code":913},"@ms_function\ndef func_outer(a, b):\n def func_inner(c):\n return a + b + c\n return func_inner\n\n@ms_function\ndef ms_closure():\n    closure = func_outer(1, 2)\n    out1 = closure(1)\n    out2 = closure(2)\n return out1, out2\n",[915],{"type":18,"tag":147,"props":916,"children":917},{"__ignoreMap":7},[918],{"type":24,"value":913},{"type":18,"tag":35,"props":920,"children":921},{},[922],{"type":24,"value":923},"对应的MindIR为closure.dot：",{"type":18,"tag":35,"props":925,"children":926},{},[927],{"type":18,"tag":175,"props":928,"children":930},{"alt":7,"src":929},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2020/10/09/f068336a8d74470b91a404ac79f06a23.jpg",[],{"type":18,"tag":35,"props":932,"children":933},{},[934],{"type":24,"value":935},"在例子中，a和b是自由变量，因为func_inner中变量a和b是引用的其父图func_outer中定义的参数。变量closure是一个闭包，它是函数func_inner与其上下文func_outer(1, 2)的结合。因此，out1的结果是4，因为其等价于1+2+1，out2的结果是5，因为其等价于1+2+2。",{"type":18,"tag":35,"props":937,"children":938},{},[939,941],{"type":24,"value":940},"MindSpore官网：",{"type":18,"tag":46,"props":942,"children":945},{"href":943,"rel":944},"https://www.mindspore.cn/",[50],[946],{"type":24,"value":943},{"type":18,"tag":35,"props":948,"children":949},{},[950,952],{"type":24,"value":951},"MindSpore论坛：",{"type":18,"tag":46,"props":953,"children":956},{"href":954,"rel":955},"https://bbs.huaweicloud.com/forum/forum-1076-1.html",[50],[957],{"type":24,"value":954},{"type":18,"tag":35,"props":959,"children":960},{},[961],{"type":24,"value":962},"代码仓地址：",{"type":18,"tag":35,"props":964,"children":965},{},[966,968],{"type":24,"value":967},"Gitee-",{"type":18,"tag":46,"props":969,"children":972},{"href":970,"rel":971},"https://gitee.com/mindspore/mindspore",[50],[973],{"type":24,"value":970},{"type":18,"tag":35,"props":975,"children":976},{},[977,979],{"type":24,"value":978},"GitHub-",{"type":18,"tag":46,"props":980,"children":983},{"href":981,"rel":982},"https://github.com/mindspore-ai/mindspore",[50],[984],{"type":24,"value":981},{"type":18,"tag":35,"props":986,"children":987},{},[988],{"type":24,"value":989},"官方QQ群: 871543426",{"type":18,"tag":35,"props":991,"children":992},{},[993],{"type":18,"tag":106,"props":994,"children":995},{},[996],{"type":24,"value":997},"参考文献",{"type":18,"tag":117,"props":999,"children":1000},{},[1001,1006,1011,1016,1021,1032],{"type":18,"tag":121,"props":1002,"children":1003},{},[1004],{"type":24,"value":1005},"[1] 《Engineering a Compiler》Second Edition，Chapter 5. Intermediate Representation",{"type":18,"tag":121,"props":1007,"children":1008},{},[1009],{"type":24,"value":1010},"[2] 《Combining Analyses, Combining Optimizations》",{"type":18,"tag":121,"props":1012,"children":1013},{},[1014],{"type":24,"value":1015},"[3] 《COMPILING WITH CONTINUATIONS》第一章",{"type":18,"tag":121,"props":1017,"children":1018},{},[1019],{"type":24,"value":1020},"[4] 《Functional programming languages Part V: functional intermediate representations》",{"type":18,"tag":121,"props":1022,"children":1023},{},[1024,1026],{"type":24,"value":1025},"[5] ",{"type":18,"tag":46,"props":1027,"children":1030},{"href":1028,"rel":1029},"http://matt.might.net/articles/a-normalization/",[50],[1031],{"type":24,"value":1028},{"type":18,"tag":121,"props":1033,"children":1034},{},[1035],{"type":24,"value":1036},"[6] 《Don't Unroll Adjoint: Differentiating SSA-Form Programs》",{"title":7,"searchDepth":1038,"depth":1038,"links":1039},4,[1040,1042,1043,1044,1045,1046],{"id":103,"depth":1041,"text":110},2,{"id":369,"depth":1041,"text":372},{"id":408,"depth":1041,"text":411},{"id":489,"depth":1041,"text":492},{"id":625,"depth":1041,"text":628},{"id":687,"depth":1041,"text":690},"markdown","content:technology-blogs:zh:266.md","content","technology-blogs/zh/266.md","technology-blogs/zh/266","md",1776506122536]