提交 945b2cf8 编写于 作者: Y Youwei Song 提交者: hong

Add save load save_dygraph load_dygraph (#1519)

* add save load save_dygraph load_dygraph, test=develop

* add .idea in gitignore, test=develop

* minor fix, test=develop

* doc refines, test=develop

* doc refines, test=develop
上级 f5acb1ee
.vscode/
/doc/fluid/menu.zh.json
/doc/fluid/menu.en.json
.idea
......@@ -25,7 +25,7 @@ fluid.dygraph
dygraph_cn/InverseTimeDecay_cn.rst
dygraph_cn/Layer_cn.rst
dygraph_cn/LayerNorm_cn.rst
dygraph_cn/load_persistables_cn.rst
dygraph_cn/load_dygraph_cn.rst
dygraph_cn/NaturalExpDecay_cn.rst
dygraph_cn/NCE_cn.rst
dygraph_cn/NoamDecay_cn.rst
......@@ -34,7 +34,7 @@ fluid.dygraph
dygraph_cn/PolynomialDecay_cn.rst
dygraph_cn/Pool2D_cn.rst
dygraph_cn/PRelu_cn.rst
dygraph_cn/save_persistables_cn.rst
dygraph_cn/save_dygraph_cn.rst
dygraph_cn/SpectralNorm_cn.rst
dygraph_cn/to_variable_cn.rst
dygraph_cn/TreeConv_cn.rst
.. _cn_api_fluid_dygraph_load_dygraph:
load_dygraph
-------------------------------
.. py:function:: paddle.fluid.dygraph.load_dygraph(model_path)
该接口尝试从磁盘中加载参数或优化器的 ``dict`` 。
该接口会同时加载 ``model_path + ".pdparams"`` 和 ``model_path + ".pdopt"`` 中的内容。
参数:
- **model_path** (str) – 保存state_dict的文件前缀。该路径不应该包括后缀 ``.pdparams`` 或 ``.pdopt``。
返回: 两个 ``dict`` ,即从文件中恢复的参数 ``dict`` 和优化器 ``dict``
- para_dict: 从文件中恢复的参数 ``dict``
- opti_dict: 从文件中恢复的优化器 ``dict``
返回类型: tuple(dict, dict)
**代码示例**
.. code-block:: python
import paddle.fluid as fluid
with fluid.dygraph.guard():
emb = fluid.dygraph.Embedding( "emb", [10, 10])
state_dict = emb.state_dict()
fluid.save_dygraph( state_dict, "paddle_dy")
adam = fluid.optimizer.Adam( learning_rate = fluid.layers.noam_decay( 100, 10000) )
state_dict = adam.state_dict()
fluid.save_dygraph( state_dict, "padle_dy")
para_state_dict, opti_state_dict = fluid.load_dygraph( "paddle_dy")
.. _cn_api_fluid_dygraph_load_persistables:
load_persistables
-------------------------------
.. py:function:: paddle.fluid.dygraph.load_persistables(dirname='save_dir')
该函数尝试从dirname中加载持久性变量。
参数:
- **dirname** (str) – 目录路径。默认为save_dir
返回: 两个字典:从文件中恢复的参数字典;从文件中恢复的优化器字典
返回类型: dict
**代码示例**
.. code-block:: python
my_layer = layer(fluid.Layer)
param_path = "./my_paddle_model"
sgd = SGDOptimizer(learning_rate=1e-3)
param_dict, optimizer_dict = fluid.dygraph.load_persistables(my_layer.parameters(), param_path)
param_1 = param_dict['PtbModel_0.w_1']
sgd.load(optimizer_dict)
.. _cn_api_fluid_dygraph_save_dygraph:
save_dygraph
-------------------------------
.. py:function:: paddle.fluid.dygraph.save_dygraph(state_dict, model_path)
该接口将传入的参数或优化器的 ``dict`` 保存到磁盘上。
``state_dict`` 是通过 :ref:`cn_api_fluid_dygraph_Layer` 的 ``state_dict()`` 方法得到的。
注: ``model_path`` 不可以是一个目录。
该接口会根据 ``state_dict`` 的内容,自动给 ``model_path`` 添加 ``.pdparams`` 或者 ``.pdopt`` 后缀,
生成 ``model_path + ".pdparms"`` 或者 ``model_path + ".pdopt"`` 文件。
参数:
- **state_dict** (dict of Parameters) – 要保存的模型参数的 ``dict`` 。
- **model_path** (str) – 保存state_dict的文件前缀。格式为 ``目录名称/文件前缀``。如果文件前缀为空字符串,会引发异常。
返回: 无
**代码示例**
.. code-block:: python
import paddle.fluid as fluid
with fluid.dygraph.guard():
emb = fluid.dygraph.Embedding( "emb", [10, 10])
state_dict = emb.state_dict()
fluid.save_dygraph(state_dict, "paddle_dy") # 会保存为 paddle_dy.pdparams
adam = fluid.optimizer.Adam( learning_rate = fluid.layers.noam_decay( 100, 10000) )
state_dict = adam.state_dict()
fluid.save_dygraph(state_dict, "paddle_dy") # 会保存为 paddle_dy.pdopt
.. _cn_api_fluid_dygraph_save_persistables:
save_persistables
-------------------------------
.. py:function:: paddle.fluid.dygraph.save_persistables(model_dict, dirname='save_dir', optimizers=None)
该函数把传入的层中所有参数以及优化器进行保存。
``dirname`` 用于指定保存长期变量的目录。
参数:
- **model_dict** (dict of Parameters) – 参数将会被保存,如果设置为None,不会处理。
- **dirname** (str) – 目录路径
- **optimizers** (fluid.Optimizer|list(fluid.Optimizer)|None) – 要保存的优化器。
返回: None
**代码示例**
.. code-block:: python
import paddle.fluid as fluid
ptb_model = PtbModel(
hidden_size=hidden_size,
vocab_size=vocab_size,
num_layers=num_layers,
num_steps=num_steps,
init_scale=init_scale)
sgd = fluid.optimizer.SGD(learning_rate=0.01)
x_data = np.arange(12).reshape(4, 3).astype('int64')
y_data = np.arange(1, 13).reshape(4, 3).astype('int64')
x_data = x_data.reshape((-1, num_steps, 1))
y_data = y_data.reshape((-1, 1))
init_hidden_data = np.zeros(
(num_layers, batch_size, hidden_size), dtype='float32')
init_cell_data = np.zeros(
(num_layers, batch_size, hidden_size), dtype='float32')
x = to_variable(x_data)
y = to_variable(y_data)
init_hidden = to_variable(init_hidden_data)
init_cell = to_variable(init_cell_data)
dy_loss, last_hidden, last_cell = ptb_model(x, y, init_hidden,
init_cell)
dy_loss.backward()
sgd.minimize(dy_loss)
ptb_model.clear_gradient()
param_path = "./my_paddle_model"
fluid.dygraph.save_persistables(ptb_model.state_dict(), dirname=param_path, sgd)
......@@ -16,6 +16,7 @@ fluid.io
io_cn/compose_cn.rst
io_cn/Fake_cn.rst
io_cn/firstn_cn.rst
io_cn/load_cn.rst
io_cn/load_inference_model_cn.rst
io_cn/load_params_cn.rst
io_cn/load_persistables_cn.rst
......@@ -24,6 +25,7 @@ fluid.io
io_cn/multiprocess_reader_cn.rst
io_cn/PipeReader_cn.rst
io_cn/PyReader_cn.rst
io_cn/save_cn.rst
io_cn/save_inference_model_cn.rst
io_cn/save_params_cn.rst
io_cn/save_persistables_cn.rst
......
.. _cn_api_fluid_io_load:
load
-------------------------------
.. py:function:: paddle.fluid.io.load(program, model_path)
该接口从Program中过滤出参数和优化器信息,然后从文件中获取相应的值。
如果Program和加载的文件之间参数的维度或数据类型不匹配,将引发异常。
**注意:此函数必须在运行启动程序(start_up_program)之后再调用。**
参数:
- **program** ( :ref:`cn_api_fluid_Program` ) – 要加载的Program。
- **model_path** (str) – 保存program的文件前缀。格式为 ``目录名称/文件前缀``。
返回: 无
**代码示例**
.. code-block:: python
import paddle.fluid as fluid
x = fluid.data( name="x", shape=[10, 10], dtype='float32')
y = fluid.layers.fc(x, 10)
z = fluid.layers.fc(y, 10)
place = fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
fluid.save(fluid.default_main_program(), "./test_path")
fluid.load(fluid.default_main_program(), "./test_path")
.. _cn_api_fluid_io_save:
save
-------------------------------
.. py:function:: paddle.fluid.io.save(program, model_path)
该接口将传入的参数、优化器信息和网络描述保存到 ``model_path`` 。
参数包含所有的可训练 :ref:`cn_api_fluid_Variable` ,将保存到后缀为 ``.pdparams`` 的文件中。
优化器信息包含优化器使用的所有变量。对于Adam优化器,包含beta1、beta2、momentum等。
所有信息将保存到后缀为 ``.pdopt`` 的文件中。(如果优化器没有需要保存的变量(如sgd),则不会生成)。
网络描述是程序的描述。它只用于部署。描述将保存到后缀为 ``.pdmodel`` 的文件中。
参数:
- **program** ( :ref:`cn_api_fluid_Program` ) – 要保存的Program。
- **model_path** (str) – 保存program的文件前缀。格式为 ``目录名称/文件前缀``。如果文件前缀为空字符串,会引发异常。
返回: 无
**代码示例**
.. code-block:: python
import paddle.fluid as fluid
x = fluid.data(name="x", shape=[10, 10], dtype='float32')
y = fluid.layers.fc(x, 10)
z = fluid.layers.fc(y, 10)
place = fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
fluid.save(fluid.default_main_program(), "./test_path")
......@@ -611,23 +611,21 @@ Loss at epoch 0 step 0: [0.5767452]
## 模型参数的保存
动态图由于模型和优化器在不同的对象中存储,模型参数和优化器信息要分别存储。

在模型训练中可以使用` fluid.dygraph.save_persistables(your_model_object.state_dict(), "save_dir", optimizers=None)`来保存`your_model_object`中所有的模型参数, 以及使用`learning rate decay`的优化器。也可以自定义需要保存的“参数名” - “参数对象”的Python Dictionary传入。
同样可以使用`models,optimizers = fluid.dygraph.load_persistables("save_dir")`获取保存的模型参数和优化器。
再使用`your_modle_object.load_dict(models)`接口来恢复保存的模型参数从而达到继续训练的目的。
以及使用`your_optimizer_object.load(optimizers)`接口来恢复保存的优化器中的`learning rate decay`

在模型训练中可以使用 `paddle.fluid.dygraph.save_dygraph(state_dict, model_path)` 来保存模型参数的dict或优化器信息的dict。
同样可以使用 `paddle.fluid.dygraph.load_dygraph(model_path)` 获取保存的模型参数的dict和优化器信息的dict。
再使用`your_modle_object.set_dict(para_dict)`接口来恢复保存的模型参数从而达到继续训练的目的。
以及使用`your_optimizer_object.set_dict(opti_dict)`接口来恢复保存的优化器中的`learning rate decay`值。
下面的代码展示了如何在“手写数字识别”任务中保存参数并且读取已经保存的参数来继续训练。
```python
import paddle.fluid as fluid
with fluid.dygraph.guard():
epoch_num = 5
BATCH_SIZE = 64
......@@ -660,14 +658,14 @@ with fluid.dygraph.guard():
avg_loss.backward()
adam.minimize(avg_loss)
if batch_id == 20:
fluid.dygraph.save_persistables(mnist.state_dict(), "save_dir", adam)
fluid.dygraph.save_dygraph(mnist.state_dict(), "paddle_dy")
mnist.clear_gradients()
if batch_id == 20:
for param in mnist.parameters():
dy_param_init_value[param.name] = param.numpy()
model, _ = fluid.dygraph.load_persistables("save_dir")
mnist.load_dict(model)
model, _ = fluid.dygraph.load_dygraph("paddle_dy")
mnist.set_dict(model)
break
if epoch == 0:
break
......@@ -685,7 +683,7 @@ with fluid.dygraph.guard():
```python
if fluid.dygraph.parallel.Env().local_rank == 0:
fluid.dygraph.save_persistables(mnist.state_dict(), "save_dir")
fluid.dygraph.save_dygraph(mnist.state_dict(), "paddle_dy")
```
## 模型评估
......@@ -728,7 +726,7 @@ def inference_mnist():
with fluid.dygraph.guard():
mnist_infer = MNIST("mnist")
# load checkpoint
model_dict, _ = fluid.dygraph.load_persistables("save_dir")
model_dict, _ = fluid.dygraph.load_dygraph("paddle_dy")
mnist_infer.load_dict(model_dict)
print("checkpoint loaded")
......@@ -794,7 +792,7 @@ with fluid.dygraph.guard():
print("Loss at epoch {} , Test avg_loss is: {}, acc is: {}".format(
epoch, test_cost, test_acc))
fluid.dygraph.save_persistables(mnist.state_dict(), "save_dir")
fluid.dygraph.save_dygraph(mnist.state_dict(), "paddle_dy")
print("checkpoint saved")
inference_mnist()
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册