1- # 基本原理
1+ # 基本用法
22
33
44## 一、 @to_static概览
55
6+ 动静转换(@to_static)通过解析 Python代码(抽象语法树,下简称:AST) 实现一行代码即可转为静态图功能,即只需在待转化的函数前添加一个装饰器 `` @paddle.jit.to_static `` 。
7+
68如下是一个使用 @to_static 装饰器的 `` Model `` 示例:
79
810``` python
@@ -14,7 +16,7 @@ class SimpleNet(paddle.nn.Layer):
1416 super (SimpleNet, self ).__init__ ()
1517 self .linear = paddle.nn.Linear(10 , 3 )
1618
17- # 方式一:装饰 forward 函数
19+ # 方式一:装饰 forward 函数(支持训练)
1820 @to_static
1921 def forward (self , x , y ):
2022 out = self .linear(x)
@@ -26,6 +28,12 @@ net = SimpleNet()
2628net = paddle.jit.to_static(net) # 动静转换
2729```
2830
31+ 动转静 @to_static 除了支持预测模型导出,还兼容转为静态图子图训练。仅需要在 `` forward `` 函数上添加此装饰器即可,不需要修改任何其他的代码。
32+
33+ 基本执行流程如下:
34+
35+ <img src =" https://raw.githubusercontent.com/PaddlePaddle/docs/develop/docs/guides/04_dygraph_to_static/images/to_static_train.png " style =" zoom :50% " />
36+
2937
3038### 1.1 动态图 layer 生成 Program
3139
@@ -243,7 +251,7 @@ def add_two(x, y):
243251+ ** 只有** 控制流的判断条件** 依赖了 `` Tensor `` ** (如 `` shape `` 或 `` value `` ),才会转写为对应 Op
244252
245253
246- ![ image ] ( ./ images/convert_cond.png)
254+ < img src = " https://raw.githubusercontent.com/PaddlePaddle/docs/develop/docs/guides/04_dygraph_to_static/ images/convert_cond.png" style = " zoom : 50 % " />
247255
248256
249257
@@ -324,7 +332,7 @@ def depend_tensor_if(x):
324332```
325333
326334
327- `` conver_ifelse `` 是框架底层的函数,在逐行执行用户代码生成 `` Program `` 时,执行到此处时,会根据** 判断条件** 的类型( `` bool `` 还是 `` Bool Tensor `` ),自适应决定是否转为 `` cond_op `` 。
335+ `` convert_ifelse `` 是框架底层的函数,在逐行执行用户代码生成 `` Program `` 时,执行到此处时,会根据** 判断条件** 的类型( `` bool `` 还是 `` Bool Tensor `` ),自适应决定是否转为 `` cond_op `` 。
328336
329337``` python
330338def convert_ifelse (pred , true_fn , false_fn , true_args , false_args , return_vars ):
@@ -464,11 +472,3 @@ class SimpleNet(paddle.nn.Layer):
464472
465473+ 若某个非 `` Tensor `` 数据需要当做 `` Persistable `` 的变量序列化到磁盘,则最好在 `` __init__ `` 中调用 `` self.XX= paddle.to_tensor(xx) `` 接口转为 `` buffer `` 变量
466474
467- ## 六、Program 执行与训练
468-
469- 动转静 @to_static 除了支持预测模型导出,还兼容转为静态图子图训练。仅需要在 `` forward `` 函数上添加此装饰器即可。
470-
471- 基本执行流程如下:
472-
473-
474- ![ image] ( ./images/to_static_train.png )
0 commit comments