diff --git a/doc/howto/cross_compiling/cross_compiling_for_ios_cn.md b/doc/howto/cross_compiling/cross_compiling_for_ios_cn.md
new file mode 100644
index 0000000000000000000000000000000000000000..32c490d9aa4202e17aa1784a45a317c5307b98ea
--- /dev/null
+++ b/doc/howto/cross_compiling/cross_compiling_for_ios_cn.md
@@ -0,0 +1,99 @@
+# 构建iOS平台上的PaddlePaddle库
+交叉编译iOS平台上适用的PaddlePaddle库,需要在MacOS系统上进行。本文的将介绍在MacOS上,从源码交叉编译iOS平台上适用的PaddlePaddle库。
+
+## 准备交叉编译环境
+Apple官方为iOS开发提供了完整的交叉编译工具和集成开发环境,用户从App Store下载安装Xcode即可。也可自行前往官网下载,[Xcode](https://developer.apple.com/cn/xcode/)。安装完成之后,可在命令行执行`xcodebuild -version`,判断是否安装成功。
+
+```bash
+$ xcodebuild -version
+Xcode 9.0
+Build version 9A235
+```
+
+## 配置交叉编译参数
+
+PaddlePaddle为交叉编译提供了工具链配置文档[cmake/cross_compiling/ios.cmake](https://github.com/PaddlePaddle/Paddle/blob/develop/cmake/cross_compiling/ios.cmake),以提供一些默认的编译器和编译参数配置。
+
+交叉编译iOS版本的PaddlePaddle库时,有一些必须配置的参数:
+
+- `CMAKE_SYSTEM_NAME`,CMake编译的目标平台,必须设置为`iOS`。在设置`CMAKE_SYSTEM_NAME=iOS`后,PaddlePaddle的CMake系统会自动编译所有的第三方依赖库,并且强制设置一些PaddlePaddle参数的值(`WITH_C_API=ON`、`WITH_GPU=OFF`、`WITH_AVX=OFF`、`WITH_PYTHON=OFF`、`WITH_RDMA=OFF`)。
+- `WITH_C_API`,是否编译C-API预测库,必须设置为ON。在iOS平台上只支持使用C-API来预测。
+- `WITH_SWIG_PY`,必须设置为ON。在iOS平台上不支持通过swig调用来训练或者预测。
+
+iOS平台可选配置参数:
+
+- `IOS_PLATFORM`,可设置为`OS/SIMULATOR`,默认值为`OS`。
+ - `OS`,构建目标为`arm`架构的iPhone或者iPad等物理设备。
+ - `SIMULATOR`,构建目标为`x86`架构的模拟器平台。
+- `IOS_ARCH`,目标架构。针对不同的`IOS_PLATFORM`,可设置的目标架构如下表所示:
+
+ | IOS_PLATFORM | IOS_ARCH |
+ |--------------|----------------------|
+ | OS | armv7, armv7s, arm64 (默认) |
+ | SIMULATOR | i386, x86_64 (默认) |
+
+- `IOS_DEPLOYMENT_TARGET`,最小的iOS部署版本,默认值为`7.0`。
+- `IOS_ENABLE_BITCODE`,是否使能[Bitcode](https://developer.apple.com/library/content/documentation/IDEs/Conceptual/AppDistributionGuide/AppThinning/AppThinning.html#//apple_ref/doc/uid/TP40012582-CH35-SW3),可设置`ON/OFF`,默认值为`ON`。
+- `IOS_USE_VECLIB_FOR_BLAS`,是否使用[vecLib](https://developer.apple.com/documentation/accelerate/veclib)框架进行BLAS矩阵计算,可设置`ON/OFF`,默认值为`OFF`。
+- `IOS_DEVELOPMENT_ROOT`,`Developer`目录,可显式指定为`/path/to/platform/Developer`。若未显式指定,PaddlePaddle将会根据`IOS_PLATFORM`自动选择`Xcode`对应`platform`的`Developer`目录。
+- `IOS_SDK_ROOT`,所使用`SDK`的根目录,可显式指定为`/path/to/platform/Developer/SDKs/SDK`。若未显式指定,PaddlePaddle将会自动选择`IOS_DEVELOPMENT_ROOT`目录下最新的`SDK`版本。
+
+其他配置参数:
+
+- `USE_EIGEN_FOR_BLAS`,是否使用Eigen库进行矩阵计算,在`IOS_USE_VECLIB_FOR_BLAS=OFF`时有效。可设置`ON/OFF`,默认值为`OFF`。
+- `HOST_C/CXX_COMPILER`,宿主机的C/C++编译器。默认值为环境变量`CC/CXX`的值;若环境变量`CC/CXX`未设置,则使用`cc/c++`编译器。
+
+常用的cmake配置如下:
+
+```bash
+cmake -DCMAKE_SYSTEM_NAME=iOS \
+ -DIOS_PLATFORM=OS \
+ -DIOS_ARCH="arm64" \
+ -DIOS_ENABLE_BITCODE=ON \
+ -DIOS_USE_VECLIB_FOR_BLAS=ON \
+ -DCMAKE_INSTALL_PREFIX=your/path/to/install \
+ -DWITH_C_API=ON \
+ -DWITH_TESTING=OFF \
+ -DWITH_SWIG_PY=OFF \
+ ..
+```
+
+```bash
+cmake -DCMAKE_SYSTEM_NAME=iOS \
+ -DIOS_PLATFORM=SIMULATOR \
+ -DIOS_ARCH="x86_64" \
+ -DIOS_USE_VECLIB_FOR_BLAS=ON \
+ -DCMAKE_INSTALL_PREFIX=your/path/to/install \
+ -DWITH_C_API=ON \
+ -DWITH_TESTING=OFF \
+ -DWITH_SWIG_PY=OFF \
+ ..
+```
+
+用户还可根据自己的需求设置其他编译参数。比如希望最小化生成库的大小,可以设置`CMAKE_BUILD_TYPE`为`MinSizeRel`;若希望得到最快的执行速度,则可设置`CMAKE_BUILD_TYPE`为`Release`。亦可以通过手动设置`CMAKE_C/CXX_FLAGS`来影响PaddlePaddle的编译过程。
+
+**性能TIPS**,为了达到最快的计算速度,在CMake参数配置上,有以下建议:
+
+- 设置`CMAKE_BUILD_TYPE`为`Release`
+- 设置`IOS_USE_VECLIB_FOR_BLAS=ON`,调用`vecLib`框架提供的BLAS函数进行矩阵计算。
+
+## 编译和安装
+
+CMake配置完成后,执行以下命令,PaddlePaddle将自动下载和编译所有第三方依赖库、编译和安装PaddlePaddle预测库。
+
+```
+$ make
+$ make install
+```
+
+注意:如果你曾在源码目录下编译过其他平台的PaddlePaddle库,请先使用`rm -rf`命令删除`third_party`目录和`build`目录,以确保所有的第三方依赖库和PaddlePaddle代码都是针对新的CMake配置重新编译的。
+
+执行完安装命令后,`your/path/to/install`目录中会包含以下内容:
+
+- `include`目录,其中包含所有C-API的头文件
+- `lib`目录,其中包含PaddlePaddle的C-API静态库
+- `third_party`目录,其中包含所依赖的所有第三方库
+
+注意,不同架构的PaddlePaddle库建议安装到不同的目录下,然后使用`lipo`工具将多个静态库合并成一个支持多个架构的fat库。
+
+自此,PaddlePaddle库已经安装完成,用户可将合成的fat库用于深度学习相关的iOS App中,调用方法见C-API文档。
diff --git a/doc/howto/cross_compiling/cross_compiling_for_raspberry_cn.md b/doc/howto/cross_compiling/cross_compiling_for_raspberry_cn.md
index 026c0c6f3b2a2ca322d063f38e1736a010e1197e..6e983645faaed1f67edaeeb82ddbef9cef6bb85f 100644
--- a/doc/howto/cross_compiling/cross_compiling_for_raspberry_cn.md
+++ b/doc/howto/cross_compiling/cross_compiling_for_raspberry_cn.md
@@ -59,4 +59,4 @@ make install
注意:如果你曾经在源码目录下编译过其他平台的PaddlePaddle库,请先使用`rm -rf`命令删除`third_party`目录和`build`目录,以确保所有的第三方依赖库和PaddlePaddle代码都是针对新的CMake配置重新编译的。
-执行完安装命令后,,`your/path/to/install`目录中会包含`include`和`lib`目录,其中`include`中包含C-API的头文件,`lib`中包含一个Raspberry Pi版本的库。
+执行完安装命令后,`your/path/to/install`目录中会包含`include`和`lib`目录,其中`include`中包含C-API的头文件,`lib`中包含一个Raspberry Pi版本的库。
diff --git a/doc/howto/cross_compiling/cross_compiling_for_raspberry_en.md b/doc/howto/cross_compiling/cross_compiling_for_raspberry_en.md
index 09ac4733ec98c598dfd62f22beaf838320dc7531..3c1a5950ff9553bb725d5a96e3fdf2e5e9f6f95c 100644
--- a/doc/howto/cross_compiling/cross_compiling_for_raspberry_en.md
+++ b/doc/howto/cross_compiling/cross_compiling_for_raspberry_en.md
@@ -44,7 +44,7 @@ cmake -DCMAKE_SYSTEM_NAME=RPi \
..
```
-To build the inference library, please set the argument WITH_API to ON: `WITH_C_API=ON`.
+To build the inference library, please set the argument WITH\_C\_API to ON: `WITH_C_API=ON`.
You can add more arguments. For example, to minimize the size of the generated inference library, you may use `CMAKE_BUILD_TYPE=MinSizeRel`. For performance optimization, you may use `CMAKE_BUILD_TYPE=Release`.
diff --git a/doc/howto/usage/cluster/cluster_train_cn.md b/doc/howto/usage/cluster/cluster_train_cn.md
index 93c5544bcfa911f8bdcdaea39a75b3ab7ef218f8..2e98b3de3fe2284375f87e883ff4bac19255dbeb 100644
--- a/doc/howto/usage/cluster/cluster_train_cn.md
+++ b/doc/howto/usage/cluster/cluster_train_cn.md
@@ -19,7 +19,7 @@
* [启动集群作业](#启动集群作业-1)
* [在Kubernetes集群中提交训练作业](#在kubernetes集群中提交训练作业)
-# 概述
+## 概述
本文将介绍如何使用PaddlePaddle在不同的集群框架下完成分布式训练。分布式训练架构如下图所示:
@@ -32,7 +32,7 @@
在使用同步SGD训练神经网络时,PaddlePaddle使用同步屏障(barrier),使梯度的提交和参数的更新按照顺序方式执行。在异步SGD中,则并不会等待所有trainer提交梯度才更新参数,这样极大地提高了计算的并行性:参数服务器之间不相互依赖,并行地接收梯度和更新参数,参数服务器也不会等待计算节点全部都提交梯度之后才开始下一步,计算节点之间也不会相互依赖,并行地执行模型的训练。可以看出,虽然异步SGD方式会提高参数更新并行度, 但是并不能保证参数同步更新,在任意时间某一台参数服务器上保存的参数可能比另一台要更新,与同步SGD相比,梯度会有噪声。
-# 环境准备
+## 环境准备
1. 准备您的计算集群。计算集群通常由一组(几台到几千台规模)的Linux服务器组成。服务器之间可以通过局域网(LAN)联通,每台服务器具有集群中唯一的IP地址(或者可被DNS解析的主机名)。集群中的每台计算机通常被成为一个“节点”。
1. 我们需要在集群的所有节点上安装 PaddlePaddle。 如果要启用GPU,还需要在节点上安装对应的GPU驱动以及CUDA。PaddlePaddle的安装可以参考[build_and_install](https://github.com/PaddlePaddle/Paddle/tree/develop/doc/getstarted/build_and_install)的多种安装方式。我们推荐使用[Docker](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_cn.rst)安装方式来快速安装PaddlePaddle。
@@ -51,8 +51,8 @@ PaddlePaddle 0.10.0, compiled with
下面以`doc/howto/usage/cluster/src/word2vec`中的代码作为实例,介绍使用PaddlePaddle v2 API完成分布式训练。
-# 启动参数说明
-## 启动参数服务器
+## 启动参数说明
+### 启动参数服务器
执行以下的命令启动一个参数服务器并等待和计算节点的数据交互
```bash
$ paddle pserver --port=7164 --ports_num=1 --ports_num_for_sparse=1 --num_gradient_servers=1
@@ -70,7 +70,7 @@ $ stdbuf -oL /usr/bin/nohup paddle pserver --port=7164 --ports_num=1 --ports_num
| ports_num_for_sparse | 必选 | 1 | 用于稀疏类型参数通信的端口个数 |
| num_gradient_servers | 必选 | 1 | 当前训练任务pserver总数 |
-## 启动计算节点
+### 启动计算节点
执行以下命令启动使用python编写的trainer程序(文件名为任意文件名,如train.py)
```bash
$ python train.py
@@ -117,7 +117,7 @@ paddle.init(
| pservers | 必选 | 127.0.0.1 | 当前训练任务启动的pserver的IP列表,多个IP使用“,”隔开 |
-## 准备数据集
+### 准备数据集
参考样例数据准备脚本[prepare.py](https://github.com/PaddlePaddle/Paddle/tree/develop/doc/howto/usage/cluster/src/word2vec/prepare.py),准备训练数据和验证数据集,我们使用paddle.dataset.imikolov数据集,并根据分布式训练并发数(trainer节点个数),在`prepare.py`开头部分指定`SPLIT_COUNT`将数据切分成多份。
@@ -149,7 +149,7 @@ test.txt-00002
对于不同的训练任务,训练数据格式和训练程序的`reader()`会大不相同,所以开发者需要根据自己训练任务的实际场景完成训练数据的分割和`reader()`的编写。
-## 准备训练程序
+### 准备训练程序
我们会对每个训练任务都会在每个节点上创建一个工作空间(workspace),其中包含了用户的训练程序、程序依赖、挂载或下载的训练数据分片。
@@ -184,7 +184,7 @@ test.txt-00002
- `train_data_dir`:包含训练数据的目录,可以是从分布式存储挂载过来的,也可以是在任务启动前下载到本地的。
- `test_data_dir`:包含测试数据集的目录。
-# 使用分布式计算平台或工具
+## 使用分布式计算平台或工具
PaddlePaddle可以使用多种分布式计算平台构建分布式计算任务,包括:
- [Kubernetes](http://kubernetes.io) Google开源的容器集群的调度框架,支持大规模集群生产环境的完整集群方案。
@@ -195,12 +195,12 @@ PaddlePaddle可以使用多种分布式计算平台构建分布式计算任务
在使用分布式计算平台进行训练时,任务被调度在集群中时,分布式计算平台通常会通过API或者环境变量提供任务运行需要的参数,比如节点的ID、IP和任务节点个数等。
-## 使用Fabric启动集群作业
+### 使用Fabric启动集群作业
-### 准备一个Linux集群
+#### 准备一个Linux集群
可以在`paddle/scripts/cluster_train_v2/fabric/docker_cluster`目录下,执行`kubectl -f ssh_servers.yaml`启动一个测试集群,并使用`kubectl get po -o wide`获得这些节点的IP地址。
-### 启动集群作业
+#### 启动集群作业
`paddle.py` 提供了自动化脚本来启动不同节点中的所有 PaddlePaddle 集群进程。默认情况下,所有命令行选项可以设置为 `paddle.py` 命令选项并且 `paddle.py` 将透明、自动地将这些选项应用到 PaddlePaddle 底层进程。
@@ -216,10 +216,10 @@ sh run.sh
集群作业将会在几秒后启动。
-### 终止集群作业
+#### 终止集群作业
`paddle.py`能获取`Ctrl + C` SIGINT 信号来自动终止它启动的所有进程。只需中断 `paddle.py` 任务来终止集群作业。如果程序崩溃你也可以手动终止。
-### 检查集群训练结果
+#### 检查集群训练结果
详细信息请检查 $workspace/log 里的日志,每一个节点都有相同的日志结构。
`paddle_trainer.INFO`
@@ -234,13 +234,13 @@ sh run.sh
`train.log`
提供训练过程的 stderr 和 stdout。训练失败时可以检查错误日志。
-### 检查模型输出
+#### 检查模型输出
运行完成后,模型文件将被写入节点 0 的 `output` 目录中。
工作空间中的 `nodefile` 表示当前集群作业的节点 ID。
-## 在OpenMPI集群中提交训练作业
+### 在OpenMPI集群中提交训练作业
-### 准备OpenMPI集群
+#### 准备OpenMPI集群
执行下面的命令以启动3个节点的OpenMPI集群和一个"head"节点:
@@ -252,7 +252,7 @@ kubectl create -f mpi-nodes.yaml
然后可以从head节点ssh无密码登录到OpenMPI的每个节点上。
-### 启动集群作业
+#### 启动集群作业
您可以按照下面的步骤在OpenMPI集群中提交paddle训练任务:
@@ -280,6 +280,6 @@ scp train.txt-00002 test.txt-00002 [node3IP]:/home/tutorial
mpirun -hostfile machines -n 3 /home/tutorial/start_mpi_train.sh
```
-## 在Kubernetes集群中提交训练作业
+### 在Kubernetes集群中提交训练作业
此部分的使用方法可以参考[here](../k8s/k8s_distributed_cn.md)。
diff --git a/doc/howto/usage/cluster/cluster_train_en.md b/doc/howto/usage/cluster/cluster_train_en.md
index 1e8b4d54b9ffa99b3beef35ecaf95bbd0866535f..baa97c0c02ae490fff8587071bd2d4adfb5325e3 100644
--- a/doc/howto/usage/cluster/cluster_train_en.md
+++ b/doc/howto/usage/cluster/cluster_train_en.md
@@ -19,7 +19,7 @@
* [Launching Cluster Job](#launching-cluster-job-1)
* [Cluster Training Using Kubernetes](#cluster-training-using-kubernetes)
-# Introduction
+## Introduction
In this article, we'll explain how to run distributed training jobs with PaddlePaddle on different types of clusters. The diagram below shows the main architecture of a distributed trainning job:
@@ -33,7 +33,7 @@ PaddlePaddle can support both synchronize stochastic gradient descent (SGD) and
When training with synchronize SGD, PaddlePaddle uses an internal "synchronize barrier" which makes gradients update and parameter download in strict order. On the other hand, asynchronous SGD won't wait for all trainers to finish upload at a single step, this will increase the parallelism of distributed training: parameter servers do not depend on each other, they'll do parameter optimization concurrently. Parameter servers will not wait for trainers, so trainers will also do their work concurrently. But asynchronous SGD will introduce more randomness and noises in the gradient.
-# Preparations
+## Preparations
1. Prepare your computer cluster. It's normally a bunch of Linux servers connected by LAN. Each server will be assigned a unique IP address. The computers in the cluster can be called "nodes".
2. Install PaddlePaddle on every node. If you are going to take advantage of GPU cards, you'll also need to install proper driver and CUDA libraries. To install PaddlePaddle please read [this build and install](https://github.com/PaddlePaddle/Paddle/tree/develop/doc/getstarted/build_and_install) document. We strongly recommend using [Docker installation](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_en.rst).
@@ -52,9 +52,9 @@ PaddlePaddle 0.10.0rc, compiled with
We'll take `doc/howto/usage/cluster/src/word2vec` as an example to introduce distributed training using PaddlePaddle v2 API.
-# Command-line arguments
+## Command-line arguments
-## Starting parameter server
+### Starting parameter server
Type the below command to start a parameter server which will wait for trainers to connect:
@@ -74,7 +74,7 @@ $ stdbuf -oL /usr/bin/nohup paddle pserver --port=7164 --ports_num=1 --ports_num
| ports_num_for_sparse | required | 1 | number of ports which serves sparse parameter update |
| num_gradient_servers | required | 1 | total number of gradient servers |
-## Starting trainer
+### Starting trainer
Type the command below to start the trainer(name the file whatever you want, like "train.py")
```bash
@@ -122,7 +122,7 @@ paddle.init(
| trainer_id | required | 0 | ID for every trainer, start from 0 |
| pservers | required | 127.0.0.1 | list of IPs of parameter servers, separated by "," |
-## Prepare Training Dataset
+### Prepare Training Dataset
Here's some example code [prepare.py](https://github.com/PaddlePaddle/Paddle/tree/develop/doc/howto/usage/cluster/src/word2vec/prepare.py), it will download public `imikolov` dataset and split it into multiple files according to job parallelism(trainers count). Modify `SPLIT_COUNT` at the begining of `prepare.py` to change the count of output files.
@@ -155,7 +155,7 @@ When job started, every trainer needs to get it's own part of data. In some dist
Different training jobs may have different data format and `reader()` function, developers may need to write different data prepare scripts and `reader()` functions for their job.
-## Prepare Training program
+### Prepare Training program
We'll create a *workspace* directory on each node, storing your training program, dependencies, mounted or downloaded dataset directory.
@@ -191,7 +191,7 @@ Your workspace may looks like:
- `train_data_dir`: containing training data. Mount from storage service or copy trainning data to here.
- `test_data_dir`: containing testing data.
-# Use cluster platforms or cluster management tools
+## Use cluster platforms or cluster management tools
PaddlePaddle supports running jobs on several platforms including:
- [Kubernetes](http://kubernetes.io) open-source system for automating deployment, scaling, and management of containerized applications from Google.
@@ -202,13 +202,13 @@ We'll introduce cluster job management on these platforms. The examples can be f
These cluster platforms provide API or environment variables for training processes, when the job is dispatched to different nodes. Like node ID, IP or total number of nodes etc.
-## Cluster Training Using Fabric
+### Cluster Training Using Fabric
-### Prepare a Linux cluster
+#### Prepare a Linux cluster
Run `kubectl -f ssh_servers.yaml` under the directory: `paddle/scripts/cluster_train_v2/fabric/docker_cluster` will launch a demo cluster. Run `kubectl get po -o wide` to get IP addresses of these nodes.
-### Launching Cluster Job
+#### Launching Cluster Job
`paddle.py` provides automatical scripts to start all PaddlePaddle cluster processes in different nodes. By default, all command line options can be set as `paddle.py` command options and `paddle.py` will transparently and automatically set these options to PaddlePaddle lower level processes.
`paddle.py`provides two distinguished command option for easy job launching.
@@ -224,10 +224,10 @@ sh run.sh
The cluster Job will start in several seconds.
-### Kill Cluster Job
+#### Kill Cluster Job
`paddle.py` can capture `Ctrl + C` SIGINT signal to automatically kill all processes launched by it. So just stop `paddle.py` to kill cluster job. You should manually kill the job if the program crashed.
-### Check Cluster Training Result
+#### Check Cluster Training Result
Check log in $workspace/log for details, each node owns same log structure.
`paddle_trainer.INFO`
@@ -242,13 +242,13 @@ It provides stderr and stdout of parameter server process. Check error log if tr
`train.log`
It provides stderr and stdout of trainer process. Check error log if training crashes.
-### Check Model Output
+#### Check Model Output
After one pass finished, model files will be written in `output` directory in node 0.
`nodefile` in workspace indicates the node id of current cluster job.
-## Cluster Training Using OpenMPI
+### Cluster Training Using OpenMPI
-### Prepare an OpenMPI cluster
+#### Prepare an OpenMPI cluster
Run the following command to start a 3-node MPI cluster and one "head" node.
@@ -260,7 +260,7 @@ kubectl create -f mpi-nodes.yaml
Then you can log in to every OpenMPI node using ssh without input any passwords.
-### Launching Cluster Job
+#### Launching Cluster Job
Follow the steps to launch a PaddlePaddle training job in OpenMPI cluster:\
@@ -288,6 +288,6 @@ scp train.txt-00002 test.txt-00002 [node3IP]:/home/tutorial
mpirun -hostfile machines -n 3 /home/tutorial/start_mpi_train.sh
```
-## Cluster Training Using Kubernetes
+### Cluster Training Using Kubernetes
The details can be found [here](../k8s/k8s_cn.md)
diff --git a/paddle/framework/attribute.cc b/paddle/framework/attribute.cc
index 29fe352ca450740e55ee87b63392e3aabac8aa40..b1e17936417e4ce09bace1d1a5d346d1c9cfa710 100644
--- a/paddle/framework/attribute.cc
+++ b/paddle/framework/attribute.cc
@@ -19,7 +19,7 @@ limitations under the License. */
namespace paddle {
namespace framework {
-Attribute GetAttrValue(const OpDesc::Attr& attr_desc, ProgramDesc* program) {
+Attribute GetAttrValue(const OpDesc::Attr& attr_desc) {
switch (attr_desc.type()) {
case framework::AttrType::BOOLEAN: {
return attr_desc.b();
@@ -61,13 +61,9 @@ Attribute GetAttrValue(const OpDesc::Attr& attr_desc, ProgramDesc* program) {
}
return val;
}
- case framework::AttrType::BLOCK: {
- PADDLE_ENFORCE(program != nullptr,
- "Need to specify ProgramDesc when get a block attr");
- return program->mutable_blocks(attr_desc.block_idx());
- }
+ default:
+ PADDLE_THROW("Unsupport attr type %d", attr_desc.type());
}
- PADDLE_ENFORCE(false, "Unknown OpDesc::AttrDesc::type !");
return boost::blank();
}
diff --git a/paddle/framework/attribute.h b/paddle/framework/attribute.h
index 9744662b8f7229b0b17e910ae5cd997fa7d31e06..0641907d6ff7546df1601d3b0263ff42f4186968 100644
--- a/paddle/framework/attribute.h
+++ b/paddle/framework/attribute.h
@@ -32,7 +32,7 @@ inline AttrType AttrTypeID() {
return static_cast(tmp.which() - 1);
}
-Attribute GetAttrValue(const OpDesc::Attr& attr_desc, ProgramDesc* desc);
+Attribute GetAttrValue(const OpDesc::Attr& attr_desc);
class AttrReader {
public:
diff --git a/paddle/framework/backward.cc b/paddle/framework/backward.cc
index 150c152367e1bcdc095bce6f77fafdef601e1c47..dbd5a14f9f3b681f0b77b9bd507b34edfaa78766 100644
--- a/paddle/framework/backward.cc
+++ b/paddle/framework/backward.cc
@@ -18,6 +18,7 @@
#include
#include
#include
+#include
#include "paddle/framework/block_desc.h"
#include "paddle/framework/op_registry.h"
@@ -285,6 +286,15 @@ static bool AllGradInSet(const std::vector& names,
return true;
}
+static std::string FwdName(const std::string& grad_name) {
+ auto pos = grad_name.find("@GRAD");
+ if (pos == std::string::npos) {
+ return "";
+ } else {
+ return grad_name.substr(0, pos);
+ }
+}
+
static void CreateGradVarInBlock(
size_t grad_op_start_index,
const std::unordered_map& param_name_map,
@@ -294,6 +304,7 @@ static void CreateGradVarInBlock(
for (size_t op_index = grad_op_start_index; op_index < ops.size();
++op_index) {
bool need_infer_shape = false;
+ std::unordered_set new_vars;
ForEachVarName(ops[op_index]->Outputs(),
[&](const std::string& grad_var_name) {
if (block_desc->HasVar(grad_var_name)) {
@@ -301,8 +312,7 @@ static void CreateGradVarInBlock(
}
need_infer_shape = true;
auto var = block_desc->Var(grad_var_name);
- // FIXME(qiao) infer the datatype
- var->SetDataType(framework::DataType::FP32);
+ new_vars.insert(var->Name());
auto it = param_name_map.find(grad_var_name);
if (it == param_name_map.end()) {
return false;
@@ -316,6 +326,21 @@ static void CreateGradVarInBlock(
});
if (need_infer_shape) {
ops[op_index]->InferVarType(block_desc);
+ for (auto& arg : ops[op_index]->OutputArgumentNames()) {
+ if (new_vars.find(arg) == new_vars.end()) {
+ continue;
+ }
+ auto pname = FwdName(arg);
+ auto* param = block_desc->FindVar(pname);
+ auto* grad = block_desc->FindVar(arg);
+ if (param == nullptr) {
+ LOG(WARNING) << "Cannot find forward variable of " << arg
+ << ". Set its gradient to FP32";
+ grad->SetDataType(DataType::FP32);
+ } else {
+ grad->SetDataType(param->GetDataType());
+ }
+ }
ops[op_index]->InferShape(*block_desc);
}
}
@@ -368,7 +393,7 @@ std::vector> MakeBlockBackward(
ProgramDescBind& program_desc, int block_idx,
std::unordered_set* no_grad_vars,
std::unordered_map* grad_to_var) {
- BlockDescBind* cur_block = program_desc.Block(block_idx);
+ BlockDescBind* cur_block = program_desc.MutableBlock(block_idx);
std::vector op_descs = cur_block->AllOps();
std::unordered_map> dup_out_ops;
size_t grad_desc_idx = 0;
@@ -443,7 +468,7 @@ ParamGradInfoMap AppendBackward(
}
const int root_block_idx = 0;
- auto root_block = program_desc.Block(root_block_idx);
+ auto root_block = program_desc.MutableBlock(root_block_idx);
// insert fill one op for target
// TODO(qiao) add some check to the target.
@@ -492,7 +517,7 @@ ParamGradInfoMap AppendBackward(
CreateGradVarInBlock(forward_op_num, grad_to_var, root_block, &retv);
for (size_t block_index = forward_block_num;
block_index < program_desc.Size(); ++block_index) {
- CreateGradVarInBlock(0, grad_to_var, program_desc.Block(block_index),
+ CreateGradVarInBlock(0, grad_to_var, program_desc.MutableBlock(block_index),
&retv);
}
return retv;
diff --git a/paddle/framework/backward_test.cc b/paddle/framework/backward_test.cc
index 421f1321948235aa0c1acd2e24037b34716e449a..4e8d630c2634682ff63b38182108eadebb5c7ff9 100644
--- a/paddle/framework/backward_test.cc
+++ b/paddle/framework/backward_test.cc
@@ -499,7 +499,7 @@ TEST(Backward, linear_net_intermediate_variable_has_no_grad) {
TEST(Backward, simple_single_op) {
f::ProgramDescBind program;
- f::BlockDescBind *block = program.Block(0);
+ f::BlockDescBind *block = program.MutableBlock(0);
f::OpDescBind *op = block->AppendOp();
op->SetType("rowwise_add");
@@ -535,7 +535,7 @@ TEST(Backward, simple_single_op) {
TEST(Backward, default_attribute) {
f::ProgramDescBind program;
- f::BlockDescBind *block = program.Block(0);
+ f::BlockDescBind *block = program.MutableBlock(0);
f::OpDescBind *op = block->AppendOp();
op->SetType("mul");
op->SetInput("X", {"x"});
@@ -561,7 +561,7 @@ TEST(Backward, default_attribute) {
TEST(Backward, simple_mult_op) {
f::ProgramDescBind program;
- f::BlockDescBind *block = program.Block(0);
+ f::BlockDescBind *block = program.MutableBlock(0);
f::OpDescBind *op1 = block->AppendOp();
op1->SetType("rowwise_add");
op1->SetInput("X", {"x1"});
@@ -644,7 +644,7 @@ TEST(Backward, simple_mult_op) {
TEST(Backward, intermedia_var_no_grad) {
f::ProgramDescBind program;
- f::BlockDescBind *block = program.Block(0);
+ f::BlockDescBind *block = program.MutableBlock(0);
f::OpDescBind *op1 = block->AppendOp();
op1->SetType("rowwise_add");
op1->SetInput("X", {"x1"});
@@ -714,7 +714,7 @@ TEST(Backward, intermedia_var_no_grad) {
TEST(Backward, var_no_grad) {
f::ProgramDescBind program;
- f::BlockDescBind *block = program.Block(0);
+ f::BlockDescBind *block = program.MutableBlock(0);
f::OpDescBind *op1 = block->AppendOp();
op1->SetType("mult_in_out");
op1->SetInput("X", {"x1"});
@@ -790,7 +790,7 @@ TEST(Backward, var_no_grad) {
TEST(Backward, shared_var) {
f::ProgramDescBind program;
- f::BlockDescBind *block = program.Block(0);
+ f::BlockDescBind *block = program.MutableBlock(0);
f::OpDescBind *op1 = block->AppendOp();
op1->SetType("rowwise_add");
op1->SetInput("X", {"x1"});
@@ -880,7 +880,7 @@ TEST(Backward, shared_var) {
TEST(Backward, half_backward) {
f::ProgramDescBind program;
- f::BlockDescBind *block = program.Block(0);
+ f::BlockDescBind *block = program.MutableBlock(0);
auto *op1 = block->AppendOp();
op1->SetType("minus");
op1->SetInput("X", {"a"});
diff --git a/paddle/framework/block_desc.cc b/paddle/framework/block_desc.cc
index b73a20cc89d936c2beee6a39cdf71cda3915bcdc..9e3d597f3a2c84623a1ce9e4b6f4b956cffde211 100644
--- a/paddle/framework/block_desc.cc
+++ b/paddle/framework/block_desc.cc
@@ -113,7 +113,7 @@ BlockDescBind *BlockDescBind::ParentBlock() const {
if (this->desc_->parent_idx() == kNoneBlockIndex) {
return nullptr;
}
- return prog_->Block(static_cast(this->desc_->parent_idx()));
+ return prog_->MutableBlock(static_cast(this->desc_->parent_idx()));
}
BlockDesc *BlockDescBind::Proto() {
diff --git a/paddle/framework/executor.cc b/paddle/framework/executor.cc
index 3e9d8b3084e8a76f3d5b8367b0ec45ed74dec42f..9bf2311dc835c701c9311880b8adba486a7d446c 100644
--- a/paddle/framework/executor.cc
+++ b/paddle/framework/executor.cc
@@ -73,33 +73,32 @@ static void CreateTensor(Variable* var, VarDesc::VarType var_type) {
}
}
-void Executor::Run(const ProgramDesc& pdesc, Scope* scope, int block_id) {
+void Executor::Run(const ProgramDescBind& pdesc, Scope* scope, int block_id) {
// TODO(tonyyang-svail):
// - only runs on the first device (i.e. no interdevice communication)
// - will change to use multiple blocks for RNN op and Cond Op
- PADDLE_ENFORCE_GT(pdesc.blocks_size(), block_id);
- auto& block = pdesc.blocks(block_id);
+ PADDLE_ENFORCE_LT(block_id, pdesc.Size());
+ auto& block = pdesc.Block(block_id);
auto& device = device_contexts_[0];
Scope& local_scope = scope->NewScope();
- for (auto& var : block.vars()) {
- if (var.persistable()) {
- auto* ptr = scope->Var(var.name());
- CreateTensor(ptr, var.type());
- VLOG(3) << "Create Variable " << var.name()
+ for (auto& var : block.AllVars()) {
+ if (var->Persistable()) {
+ auto* ptr = scope->Var(var->Name());
+ CreateTensor(ptr, var->GetType());
+ VLOG(3) << "Create Variable " << var->Name()
<< " global, which pointer is " << ptr;
} else {
- auto* ptr = local_scope.Var(var.name());
- CreateTensor(ptr, var.type());
- VLOG(3) << "Create Variable " << var.name()
+ auto* ptr = local_scope.Var(var->Name());
+ CreateTensor(ptr, var->GetType());
+ VLOG(3) << "Create Variable " << var->Name()
<< " locally, which pointer is " << ptr;
}
}
- for (auto& op_desc : block.ops()) {
- auto op = paddle::framework::OpRegistry::CreateOp(
- op_desc, const_cast(&pdesc));
+ for (auto& op_desc : block.AllOps()) {
+ auto op = paddle::framework::OpRegistry::CreateOp(*op_desc);
op->Run(local_scope, *device);
}
diff --git a/paddle/framework/executor.h b/paddle/framework/executor.h
index 793ee954e25f7da6c9d04ea6acc2ad78812e8329..c78bfe8f9f07f1324515f0baaca4a94cc0fe844e 100644
--- a/paddle/framework/executor.h
+++ b/paddle/framework/executor.h
@@ -14,8 +14,8 @@ limitations under the License. */
#pragma once
-#include "paddle/framework/framework.pb.h"
#include "paddle/framework/op_info.h"
+#include "paddle/framework/program_desc.h"
#include "paddle/framework/scope.h"
#include "paddle/framework/tensor.h"
@@ -34,7 +34,7 @@ class Executor {
* ProgramDesc
* Scope
*/
- void Run(const ProgramDesc&, Scope*, int);
+ void Run(const ProgramDescBind&, Scope*, int);
private:
std::vector device_contexts_;
diff --git a/paddle/framework/lod_tensor_test.cu b/paddle/framework/lod_tensor_test.cu
index c79c4d0c721f9e568c937cb9e524e925fcdc83d0..5b90fbfca7f6bec4f2c862d0ff18dfd7cf39e181 100644
--- a/paddle/framework/lod_tensor_test.cu
+++ b/paddle/framework/lod_tensor_test.cu
@@ -36,8 +36,8 @@ TEST(LoDTensor, LoDInGPU) {
lod_tensor.mutable_data(place);
lod_tensor.set_lod(src_lod);
- CHECK_EQ(lod_tensor.lod_element(0, 2).first, 4UL);
- CHECK_EQ(lod_tensor.lod_element(0, 4).first, 8UL);
+ EXPECT_EQ(lod_tensor.lod_element(0, 2).first, 4UL);
+ EXPECT_EQ(lod_tensor.lod_element(0, 4).first, 8UL);
auto lod = lod_tensor.lod();
@@ -45,6 +45,6 @@ TEST(LoDTensor, LoDInGPU) {
cudaDeviceSynchronize();
for (size_t i = 0; i < src_lod[0].size(); ++i) {
- CHECK_EQ(lod[0].data()[i], src_lod[0].data()[i] * 2);
+ EXPECT_EQ(lod[0].data()[i], src_lod[0].data()[i] * 2);
}
-}
\ No newline at end of file
+}
diff --git a/paddle/framework/op_desc.cc b/paddle/framework/op_desc.cc
index c2d6f124ad292bf46b4e7e9a1dcc2984aae7fcda..0779137639e6cd9f6ecf3bbbc24d081cae3de9c0 100644
--- a/paddle/framework/op_desc.cc
+++ b/paddle/framework/op_desc.cc
@@ -52,6 +52,22 @@ class CompileTimeInferShapeContext : public InferShapeContext {
const std::vector &Outputs(
const std::string &name) const override;
+ void ShareLoD(const std::string &in, const std::string &out, size_t i = 0,
+ size_t j = 0) const override {
+ PADDLE_ENFORCE_LT(i, Inputs(in).size());
+ PADDLE_ENFORCE_LT(j, Outputs(out).size());
+ auto *in_var = block_.FindVarRecursive(Inputs(in)[i]);
+ auto *out_var = block_.FindVarRecursive(Outputs(out)[j]);
+ if (in_var->GetType() != VarDesc::LOD_TENSOR) {
+ VLOG(3) << "input " << in << "is not LodTensor";
+ return;
+ }
+ PADDLE_ENFORCE_EQ(in_var->GetType(), VarDesc::LOD_TENSOR,
+ "The %d-th output of Output(%s) must be LoDTensor.", j,
+ out);
+ in_var->SetLoDLevel(out_var->GetLodLevel());
+ }
+
private:
DDim GetDim(const std::string &name) const override;
@@ -98,7 +114,12 @@ OpDescBind::OpDescBind(const OpDesc &desc, ProgramDescBind *prog)
// restore attrs_
for (const OpDesc::Attr &attr : desc_.attrs()) {
std::string attr_name = attr.name();
- attrs_[attr_name] = GetAttrValue(attr, prog->Proto());
+ if (attr.type() != AttrType::BLOCK) {
+ attrs_[attr_name] = GetAttrValue(attr);
+ } else {
+ auto bid = attr.block_idx();
+ attrs_[attr_name] = prog->MutableBlock(bid);
+ }
}
}
@@ -172,8 +193,7 @@ void OpDescBind::SetAttr(const std::string &name, const Attribute &v) {
}
void OpDescBind::SetBlockAttr(const std::string &name, BlockDescBind &block) {
- BlockDesc *desc = block.Proto();
- this->attrs_[name] = desc;
+ this->attrs_[name] = █
need_update_ = true;
}
@@ -192,7 +212,7 @@ Attribute OpDescBind::GetAttr(const std::string &name) const {
int OpDescBind::GetBlockAttr(const std::string &name) const {
auto it = attrs_.find(name);
PADDLE_ENFORCE(it != attrs_.end(), "Attribute %s is not found", name);
- return boost::get(it->second)->idx();
+ return boost::get(it->second)->ID();
}
const std::unordered_map &OpDescBind::GetAttrMap()
diff --git a/paddle/framework/op_registry.cc b/paddle/framework/op_registry.cc
index c2f2438edf6daadf26cbc6db37f6668739ab1726..8dedd873aad648174b770b84e5232cd17b577e72 100644
--- a/paddle/framework/op_registry.cc
+++ b/paddle/framework/op_registry.cc
@@ -43,13 +43,15 @@ static VariableNameMap ConvertOpDescVarsToVarNameMap(
return ret_val;
}
-std::unique_ptr OpRegistry::CreateOp(const OpDesc& op_desc,
- ProgramDesc* program) {
+std::unique_ptr OpRegistry::CreateOp(const OpDesc& op_desc) {
+ VLOG(1) << "CreateOp directly from OpDesc is deprecated. It should only be"
+ "used in unit tests. Use CreateOp(const OpDescBind& op_desc) "
+ "instead.";
VariableNameMap inputs = ConvertOpDescVarsToVarNameMap(op_desc.inputs());
VariableNameMap outputs = ConvertOpDescVarsToVarNameMap(op_desc.outputs());
AttributeMap attrs;
for (auto& attr : op_desc.attrs()) {
- attrs[attr.name()] = GetAttrValue(attr, program);
+ attrs[attr.name()] = GetAttrValue(attr);
}
return CreateOp(op_desc.type(), inputs, outputs, attrs);
diff --git a/paddle/framework/op_registry.h b/paddle/framework/op_registry.h
index 19a9fc3802a2f2348ad7d50a267615ed70bbc4fe..2bb5e0e8ec29fb2df81549650aa0c65bc1e51c49 100644
--- a/paddle/framework/op_registry.h
+++ b/paddle/framework/op_registry.h
@@ -77,8 +77,7 @@ class OpRegistry {
const VariableNameMap& outputs,
AttributeMap attrs);
- static std::unique_ptr CreateOp(const OpDesc& op_desc,
- ProgramDesc* program);
+ static std::unique_ptr CreateOp(const OpDesc& op_desc);
static std::unique_ptr CreateOp(const OpDescBind& op_desc);
};
diff --git a/paddle/framework/op_registry_test.cc b/paddle/framework/op_registry_test.cc
index 6289125d7c782e542e5c55e1d4403836351b7e05..b860fe6cac773d1e85adecc43f5dfec42b6c7661 100644
--- a/paddle/framework/op_registry_test.cc
+++ b/paddle/framework/op_registry_test.cc
@@ -74,7 +74,7 @@ TEST(OpRegistry, CreateOp) {
attr->set_type(paddle::framework::AttrType::FLOAT);
attr->set_f(scale);
- auto op = paddle::framework::OpRegistry::CreateOp(op_desc, nullptr);
+ auto op = paddle::framework::OpRegistry::CreateOp(op_desc);
paddle::framework::Scope scope;
paddle::platform::CPUDeviceContext dev_ctx;
op->Run(scope, dev_ctx);
@@ -95,7 +95,7 @@ TEST(OpRegistry, IllegalAttr) {
bool caught = false;
try {
- paddle::framework::OpRegistry::CreateOp(op_desc, nullptr);
+ paddle::framework::OpRegistry::CreateOp(op_desc);
} catch (paddle::platform::EnforceNotMet err) {
caught = true;
std::string msg = "larger_than check fail";
@@ -115,7 +115,7 @@ TEST(OpRegistry, DefaultValue) {
ASSERT_TRUE(op_desc.IsInitialized());
- auto op = paddle::framework::OpRegistry::CreateOp(op_desc, nullptr);
+ auto op = paddle::framework::OpRegistry::CreateOp(op_desc);
paddle::framework::Scope scope;
paddle::platform::CPUDeviceContext dev_ctx;
op->Run(scope, dev_ctx);
@@ -131,7 +131,7 @@ TEST(OpRegistry, CustomChecker) {
// attr 'test_attr' is not set
bool caught = false;
try {
- paddle::framework::OpRegistry::CreateOp(op_desc, nullptr);
+ paddle::framework::OpRegistry::CreateOp(op_desc);
} catch (paddle::platform::EnforceNotMet err) {
caught = true;
std::string msg = "Attribute 'test_attr' is required!";
@@ -149,7 +149,7 @@ TEST(OpRegistry, CustomChecker) {
attr->set_i(3);
caught = false;
try {
- paddle::framework::OpRegistry::CreateOp(op_desc, nullptr);
+ paddle::framework::OpRegistry::CreateOp(op_desc);
} catch (paddle::platform::EnforceNotMet err) {
caught = true;
std::string msg = "'test_attr' must be even!";
@@ -166,7 +166,7 @@ TEST(OpRegistry, CustomChecker) {
attr->set_name("test_attr");
attr->set_type(paddle::framework::AttrType::INT);
attr->set_i(4);
- auto op = paddle::framework::OpRegistry::CreateOp(op_desc, nullptr);
+ auto op = paddle::framework::OpRegistry::CreateOp(op_desc);
paddle::platform::CPUDeviceContext dev_ctx;
paddle::framework::Scope scope;
op->Run(scope, dev_ctx);
diff --git a/paddle/framework/operator.cc b/paddle/framework/operator.cc
index 222a252dc409bf30d5d6abea95156b41cfcd221a..aa46829fdde82b58a649108bf708901299cd8153 100644
--- a/paddle/framework/operator.cc
+++ b/paddle/framework/operator.cc
@@ -351,6 +351,20 @@ class RuntimeInferShapeContext : public InferShapeContext {
return op_.Outputs(name);
}
+ void ShareLoD(const std::string& in, const std::string& out, size_t i = 0,
+ size_t j = 0) const override {
+ PADDLE_ENFORCE_LT(i, Inputs(in).size());
+ PADDLE_ENFORCE_LT(j, Outputs(out).size());
+ Variable* in_var = scope_.FindVar(Inputs(in)[i]);
+ Variable* out_var = scope_.FindVar(Outputs(out)[j]);
+ if (!in_var->IsType()) return;
+ PADDLE_ENFORCE(out_var->IsType(),
+ "The %d-th output of Output(%s) must be LoDTensor.", j, out);
+ auto in_tensor = in_var->Get();
+ auto* out_tensor = out_var->GetMutable();
+ out_tensor->set_lod(in_tensor.lod());
+ }
+
private:
DDim GetDim(const std::string& name) const override {
Variable* var = scope_.FindVar(name);
diff --git a/paddle/framework/operator_test.cc b/paddle/framework/operator_test.cc
index 3c07621293389fc7803b0295d9d30b2c12d6e327..42e0d52eed3911d8e684e76a88bc690ca0783ce5 100644
--- a/paddle/framework/operator_test.cc
+++ b/paddle/framework/operator_test.cc
@@ -83,7 +83,7 @@ TEST(OperatorBase, all) {
paddle::platform::CPUDeviceContext device_context;
paddle::framework::Scope scope;
- auto op = paddle::framework::OpRegistry::CreateOp(op_desc, nullptr);
+ auto op = paddle::framework::OpRegistry::CreateOp(op_desc);
scope.Var("OUT1");
ASSERT_EQ(paddle::framework::op_run_num, 0);
op->Run(scope, device_context);
@@ -208,7 +208,7 @@ TEST(OpKernel, all) {
paddle::platform::CPUDeviceContext cpu_device_context;
paddle::framework::Scope scope;
- auto op = paddle::framework::OpRegistry::CreateOp(op_desc, nullptr);
+ auto op = paddle::framework::OpRegistry::CreateOp(op_desc);
ASSERT_EQ(paddle::framework::cpu_kernel_run_num, 0);
op->Run(scope, cpu_device_context);
ASSERT_EQ(paddle::framework::cpu_kernel_run_num, 1);
@@ -244,7 +244,7 @@ TEST(OpKernel, multi_inputs) {
scope.Var("y0")->GetMutable();
scope.Var("y1")->GetMutable();
- auto op = paddle::framework::OpRegistry::CreateOp(op_desc, nullptr);
+ auto op = paddle::framework::OpRegistry::CreateOp(op_desc);
op->Run(scope, cpu_device_context);
}
diff --git a/paddle/framework/program_desc.h b/paddle/framework/program_desc.h
index ce1721472d9046f50b7fc88253fa3f2dbaaf51a8..b1cb086de4345902482d8254b8aeec041ecf81bc 100644
--- a/paddle/framework/program_desc.h
+++ b/paddle/framework/program_desc.h
@@ -37,7 +37,9 @@ class ProgramDescBind {
BlockDescBind *AppendBlock(const BlockDescBind &parent);
- BlockDescBind *Block(size_t idx) { return blocks_[idx].get(); }
+ BlockDescBind *MutableBlock(size_t idx) { return blocks_[idx].get(); }
+
+ const BlockDescBind &Block(size_t idx) const { return *blocks_[idx]; }
size_t Size() const { return blocks_.size(); }
diff --git a/paddle/framework/program_desc_test.cc b/paddle/framework/program_desc_test.cc
index d28c2a0bff932f5aa37c69231495895dacb07bb3..83e7286e0ec3639fa589b0958922543a3ba16a00 100644
--- a/paddle/framework/program_desc_test.cc
+++ b/paddle/framework/program_desc_test.cc
@@ -20,7 +20,7 @@ namespace paddle {
namespace framework {
TEST(ProgramDesc, copy_ctor) {
ProgramDescBind program;
- auto* global_block = program.Block(0);
+ auto* global_block = program.MutableBlock(0);
auto* x = global_block->Var("X");
x->SetType(VarDesc_VarType_LOD_TENSOR);
x->SetLoDLevel(0);
@@ -44,7 +44,7 @@ TEST(ProgramDesc, copy_ctor) {
ProgramDescBind program_copy(program);
- auto* global_block_copy = program_copy.Block(0);
+ auto* global_block_copy = program_copy.MutableBlock(0);
ASSERT_NE(global_block, global_block_copy);
auto assert_same_var = [&](const std::string& name, VarDescBind* var_before) {
@@ -82,7 +82,7 @@ TEST(ProgramDesc, copy_ctor) {
TEST(ProgramDescBind, serialize_and_deserialize) {
ProgramDescBind program_origin;
- auto* global_block = program_origin.Block(0);
+ auto* global_block = program_origin.MutableBlock(0);
auto* x = global_block->Var("X");
x->SetType(VarDesc_VarType_LOD_TENSOR);
x->SetLoDLevel(0);
@@ -108,7 +108,7 @@ TEST(ProgramDescBind, serialize_and_deserialize) {
program_origin.Proto()->SerializeToString(&binary_str);
ProgramDescBind program_restored(binary_str);
- auto* global_block_restored = program_restored.Block(0);
+ auto* global_block_restored = program_restored.MutableBlock(0);
ASSERT_NE(global_block, global_block_restored);
auto assert_same_var = [&](const std::string& name, VarDescBind* var_before) {
diff --git a/paddle/framework/prune_test.cc b/paddle/framework/prune_test.cc
index cadd114fbc3de897a13504e665ce464e83d312ff..5988874809f51c09b3d3d279be6c1e8d43d7a782 100644
--- a/paddle/framework/prune_test.cc
+++ b/paddle/framework/prune_test.cc
@@ -52,7 +52,7 @@ void AddOp(const std::string &type, const f::VariableNameMap &inputs,
TEST(Prune, one_operator) {
f::ProgramDescBind program;
- f::BlockDescBind *block = program.Block(0);
+ f::BlockDescBind *block = program.MutableBlock(0);
AddOp("one_one", {{"input", {"a"}}}, {{"output", {"b"}}}, {}, block);
@@ -69,7 +69,7 @@ TEST(Prune, one_operator) {
TEST(Prune, forward) {
f::ProgramDescBind program;
- f::BlockDescBind *block = program.Block(0);
+ f::BlockDescBind *block = program.MutableBlock(0);
AddOp("one_one", {{"input", {"a"}}}, {{"output", {"b"}}}, {}, block);
AddOp("one_one", {{"input", {"b"}}}, {{"output", {"c"}}}, {}, block);
@@ -88,7 +88,7 @@ TEST(Prune, forward) {
TEST(Prune, multi_input_op) {
f::ProgramDescBind program;
- f::BlockDescBind *block = program.Block(0);
+ f::BlockDescBind *block = program.MutableBlock(0);
AddOp("one_one", {{"input", {"a0"}}}, {{"output", {"b0"}}}, {}, block);
AddOp("one_one", {{"input", {"a1"}}}, {{"output", {"b1"}}}, {}, block);
@@ -106,7 +106,7 @@ TEST(Prune, multi_input_op) {
TEST(Prune, multi_output_op) {
f::ProgramDescBind program;
- f::BlockDescBind *block = program.Block(0);
+ f::BlockDescBind *block = program.MutableBlock(0);
AddOp("one_two", {{"input", {"a"}}}, {{"output", {"b", "c"}}}, {}, block);
AddOp("one_one", {{"input", {"b"}}}, {{"output", {"b1"}}}, {}, block);
@@ -122,7 +122,7 @@ TEST(Prune, multi_output_op) {
TEST(Prune, multi_target) {
f::ProgramDescBind program;
- f::BlockDescBind *block = program.Block(0);
+ f::BlockDescBind *block = program.MutableBlock(0);
AddOp("one_two", {{"input", {"a"}}}, {{"output", {"b", "c"}}}, {}, block);
AddOp("one_one", {{"input", {"b"}}}, {{"output", {"b1"}}}, {}, block);
diff --git a/paddle/framework/shape_inference.cc b/paddle/framework/shape_inference.cc
index 33a1d0b9b217c5d2a4b0fb63f427529e7988b24e..8169df8e4629e2d02d3dabcd6a8a102ad0077a81 100644
--- a/paddle/framework/shape_inference.cc
+++ b/paddle/framework/shape_inference.cc
@@ -28,9 +28,6 @@ void InferShapeContext::SetOutputsDim(
SetDims(names, dims);
}
-void InferShapeContext::ShareLoD(const std::string &in, const std::string &out,
- size_t i, size_t j) const {}
-
std::vector InferShapeContext::GetDims(
const std::vector &names) const {
std::vector ret;
diff --git a/paddle/framework/shape_inference.h b/paddle/framework/shape_inference.h
index f1f1e44bccd771be81cad7c28efe9b1b885eef6b..6f19900ef1a3e88fe78d457a03c344ea586ab551 100644
--- a/paddle/framework/shape_inference.h
+++ b/paddle/framework/shape_inference.h
@@ -43,9 +43,8 @@ class InferShapeContext {
virtual const std::vector &Outputs(
const std::string &name) const = 0;
- // TODO(qiao) implement this function
- void ShareLoD(const std::string &in, const std::string &out, size_t i = 0,
- size_t j = 0) const;
+ virtual void ShareLoD(const std::string &in, const std::string &out,
+ size_t i = 0, size_t j = 0) const = 0;
protected:
virtual framework::DDim GetDim(const std::string &name) const = 0;
diff --git a/paddle/framework/type_defs.h b/paddle/framework/type_defs.h
index c38c4a8ae9a46c8bda913e7643e812592de68e6e..afeeb1914ac30188b93c3b9da30bb5ceaf74416e 100644
--- a/paddle/framework/type_defs.h
+++ b/paddle/framework/type_defs.h
@@ -36,7 +36,7 @@ using VariableNameMap = std::map>;
using Attribute =
boost::variant,
std::vector, std::vector, bool,
- std::vector, BlockDesc*>;
+ std::vector, BlockDescBind*>;
using AttributeMap = std::unordered_map;
diff --git a/paddle/framework/var_type_inference_test.cc b/paddle/framework/var_type_inference_test.cc
index 918de1fd055e32888f71ffea1f33993ba1210e86..9035e63fa48ffdf7c72061b0a4248538d7a357e4 100644
--- a/paddle/framework/var_type_inference_test.cc
+++ b/paddle/framework/var_type_inference_test.cc
@@ -63,41 +63,43 @@ namespace framework {
TEST(InferVarType, sum_op) {
ProgramDescBind prog;
- auto *op = prog.Block(0)->AppendOp();
+ auto *op = prog.MutableBlock(0)->AppendOp();
op->SetType("sum");
op->SetInput("X", {"test_a", "test_b", "test_c"});
op->SetOutput("Out", {"test_out"});
- prog.Block(0)->Var("test_a")->SetType(VarDesc::SELECTED_ROWS);
- prog.Block(0)->Var("test_b")->SetType(VarDesc::SELECTED_ROWS);
- prog.Block(0)->Var("test_c")->SetType(VarDesc::SELECTED_ROWS);
- prog.Block(0)->Var("test_out");
+ prog.MutableBlock(0)->Var("test_a")->SetType(VarDesc::SELECTED_ROWS);
+ prog.MutableBlock(0)->Var("test_b")->SetType(VarDesc::SELECTED_ROWS);
+ prog.MutableBlock(0)->Var("test_c")->SetType(VarDesc::SELECTED_ROWS);
+ prog.MutableBlock(0)->Var("test_out");
- op->InferVarType(prog.Block(0));
+ op->InferVarType(prog.MutableBlock(0));
- ASSERT_EQ(VarDesc::SELECTED_ROWS, prog.Block(0)->Var("test_out")->GetType());
+ ASSERT_EQ(VarDesc::SELECTED_ROWS,
+ prog.MutableBlock(0)->Var("test_out")->GetType());
- prog.Block(0)->Var("test_b")->SetType(VarDesc::LOD_TENSOR);
- op->InferVarType(prog.Block(0));
- ASSERT_EQ(VarDesc::LOD_TENSOR, prog.Block(0)->Var("test_out")->GetType());
+ prog.MutableBlock(0)->Var("test_b")->SetType(VarDesc::LOD_TENSOR);
+ op->InferVarType(prog.MutableBlock(0));
+ ASSERT_EQ(VarDesc::LOD_TENSOR,
+ prog.MutableBlock(0)->Var("test_out")->GetType());
}
TEST(InferVarType, sum_op_without_infer_var_type) {
ProgramDescBind prog;
- auto *op = prog.Block(0)->AppendOp();
+ auto *op = prog.MutableBlock(0)->AppendOp();
op->SetType("sum_without_infer_var_type");
op->SetInput("X", {"test2_a", "test2_b", "test2_c"});
op->SetOutput("Out", {"test2_out"});
- prog.Block(0)->Var("test2_a")->SetType(VarDesc::SELECTED_ROWS);
- prog.Block(0)->Var("test2_b")->SetType(VarDesc::SELECTED_ROWS);
- prog.Block(0)->Var("test2_c")->SetType(VarDesc::SELECTED_ROWS);
- prog.Block(0)->Var("test2_out");
+ prog.MutableBlock(0)->Var("test2_a")->SetType(VarDesc::SELECTED_ROWS);
+ prog.MutableBlock(0)->Var("test2_b")->SetType(VarDesc::SELECTED_ROWS);
+ prog.MutableBlock(0)->Var("test2_c")->SetType(VarDesc::SELECTED_ROWS);
+ prog.MutableBlock(0)->Var("test2_out");
- op->InferVarType(prog.Block(0));
+ op->InferVarType(prog.MutableBlock(0));
ASSERT_EQ(VarDesc_VarType_LOD_TENSOR,
- prog.Block(0)->Var("test2_out")->GetType());
+ prog.MutableBlock(0)->Var("test2_out")->GetType());
}
} // namespace framework
diff --git a/paddle/gserver/layers/SequenceReshapeLayer.cpp b/paddle/gserver/layers/SequenceReshapeLayer.cpp
index 433592953b220eda4db4634124a57a2074cef4c0..822974407283c9ee6d0efee71bc945bc418b1942 100644
--- a/paddle/gserver/layers/SequenceReshapeLayer.cpp
+++ b/paddle/gserver/layers/SequenceReshapeLayer.cpp
@@ -70,11 +70,23 @@ void SequenceReshapeLayer::forward(PassType passType) {
size_t outDim = getSize();
size_t numSequences = input.getNumSequences();
- auto startPositions = input.sequenceStartPositions->getVector(false);
- const int* starts = startPositions->getData();
- CHECK_EQ(starts[numSequences], input.getBatchSize());
- CHECK_EQ(numSequences, startPositions->getSize() - 1);
+ // by default, we assume each instance as a sequence
+ IVectorPtr seqStarts;
+ IVector::resizeOrCreate(seqStarts, input.getBatchSize() + 1, false);
+ int* startsData = seqStarts->getData();
+ for (int i = 0; i < input.getBatchSize() + 1; i++) {
+ startsData[i] = i;
+ }
+ const int* starts = startsData;
+
+ // if there is sequence, then use start positions
+ if (input.sequenceStartPositions) {
+ auto startPositions = input.sequenceStartPositions->getVector(false);
+ starts = startPositions->getData();
+ CHECK_EQ(starts[numSequences], input.getBatchSize());
+ CHECK_EQ(numSequences, startPositions->getSize() - 1);
+ }
for (size_t seqID = 0; seqID < numSequences; seqID++) {
size_t inNumIns = starts[seqID + 1] - starts[seqID];
diff --git a/paddle/memory/detail/buddy_allocator.cc b/paddle/memory/detail/buddy_allocator.cc
index e212f7737a4093125857126cabb5b1a7b3e055b1..64ee53803891f192302bb915027f0499dfa36411 100644
--- a/paddle/memory/detail/buddy_allocator.cc
+++ b/paddle/memory/detail/buddy_allocator.cc
@@ -27,11 +27,11 @@ BuddyAllocator::BuddyAllocator(SystemAllocator* system_allocator,
system_allocator_(std::move(system_allocator)) {}
BuddyAllocator::~BuddyAllocator() {
- VLOG(3) << "BuddyAllocator Disconstructor makes sure that all of these "
- "have actually been freed";
+ VLOG(10) << "BuddyAllocator Disconstructor makes sure that all of these "
+ "have actually been freed";
while (!pool_.empty()) {
auto block = static_cast(std::get<2>(*pool_.begin()));
- VLOG(3) << "Free from block (" << block << ", " << max_chunk_size_ << ")";
+ VLOG(10) << "Free from block (" << block << ", " << max_chunk_size_ << ")";
system_allocator_->Free(block, max_chunk_size_, block->index(cache_));
cache_.invalidate(block);
@@ -51,11 +51,12 @@ void* BuddyAllocator::Alloc(size_t unaligned_size) {
// acquire the allocator lock
std::lock_guard lock(mutex_);
- VLOG(3) << "Allocate " << unaligned_size << " bytes from chunk size " << size;
+ VLOG(10) << "Allocate " << unaligned_size << " bytes from chunk size "
+ << size;
// if the allocation is huge, send directly to the system allocator
if (size > max_chunk_size_) {
- VLOG(3) << "Allocate from system allocator.";
+ VLOG(10) << "Allocate from system allocator.";
return SystemAlloc(size);
}
@@ -70,9 +71,9 @@ void* BuddyAllocator::Alloc(size_t unaligned_size) {
return nullptr;
}
} else {
- VLOG(3) << "Allocation from existing memory block " << std::get<2>(*it)
- << " at address "
- << reinterpret_cast(std::get<2>(*it))->data();
+ VLOG(10) << "Allocation from existing memory block " << std::get<2>(*it)
+ << " at address "
+ << reinterpret_cast(std::get<2>(*it))->data();
}
total_used_ += size;
@@ -89,10 +90,10 @@ void BuddyAllocator::Free(void* p) {
// Acquire the allocator lock
std::lock_guard lock(mutex_);
- VLOG(3) << "Free from address " << block;
+ VLOG(10) << "Free from address " << block;
if (block->type(cache_) == MemoryBlock::HUGE_CHUNK) {
- VLOG(3) << "Free directly from system allocator";
+ VLOG(10) << "Free directly from system allocator";
system_allocator_->Free(block, block->total_size(cache_),
block->index(cache_));
@@ -109,8 +110,8 @@ void BuddyAllocator::Free(void* p) {
// Trying to merge the right buddy
if (block->has_right_buddy(cache_)) {
- VLOG(3) << "Merging this block " << block << " with its right buddy "
- << block->right_buddy(cache_);
+ VLOG(10) << "Merging this block " << block << " with its right buddy "
+ << block->right_buddy(cache_);
auto right_buddy = block->right_buddy(cache_);
@@ -127,8 +128,8 @@ void BuddyAllocator::Free(void* p) {
// Trying to merge the left buddy
if (block->has_left_buddy(cache_)) {
- VLOG(3) << "Merging this block " << block << " with its left buddy "
- << block->left_buddy(cache_);
+ VLOG(10) << "Merging this block " << block << " with its left buddy "
+ << block->left_buddy(cache_);
auto left_buddy = block->left_buddy(cache_);
@@ -144,8 +145,8 @@ void BuddyAllocator::Free(void* p) {
}
// Dumping this block into pool
- VLOG(3) << "Inserting free block (" << block << ", "
- << block->total_size(cache_) << ")";
+ VLOG(10) << "Inserting free block (" << block << ", "
+ << block->total_size(cache_) << ")";
pool_.insert(
IndexSizeAddress(block->index(cache_), block->total_size(cache_), block));
@@ -164,7 +165,7 @@ void* BuddyAllocator::SystemAlloc(size_t size) {
size_t index = 0;
void* p = system_allocator_->Alloc(index, size);
- VLOG(3) << "Allocated " << p << " from system allocator.";
+ VLOG(10) << "Allocated " << p << " from system allocator.";
if (p == nullptr) return nullptr;
@@ -190,8 +191,8 @@ BuddyAllocator::PoolSet::iterator BuddyAllocator::RefillPool() {
if (p == nullptr) return pool_.end();
- VLOG(3) << "Creating and inserting new block " << p
- << " from system allocator";
+ VLOG(10) << "Creating and inserting new block " << p
+ << " from system allocator";
static_cast(p)->init(cache_, MemoryBlock::FREE_CHUNK, index,
max_chunk_size_, nullptr, nullptr);
@@ -235,19 +236,19 @@ void* BuddyAllocator::SplitToAlloc(BuddyAllocator::PoolSet::iterator it,
auto block = static_cast(std::get<2>(*it));
pool_.erase(it);
- VLOG(3) << "Split block (" << block << ", " << block->total_size(cache_)
- << ") into";
+ VLOG(10) << "Split block (" << block << ", " << block->total_size(cache_)
+ << ") into";
block->split(cache_, size);
- VLOG(3) << "Left block (" << block << ", " << block->total_size(cache_)
- << ")";
+ VLOG(10) << "Left block (" << block << ", " << block->total_size(cache_)
+ << ")";
block->set_type(cache_, MemoryBlock::ARENA_CHUNK);
// the rest of memory if exist
if (block->has_right_buddy(cache_)) {
if (block->right_buddy(cache_)->type(cache_) == MemoryBlock::FREE_CHUNK) {
- VLOG(3) << "Insert right block (" << block->right_buddy(cache_) << ", "
- << block->right_buddy(cache_)->total_size(cache_) << ")";
+ VLOG(10) << "Insert right block (" << block->right_buddy(cache_) << ", "
+ << block->right_buddy(cache_)->total_size(cache_) << ")";
pool_.insert(
IndexSizeAddress(block->right_buddy(cache_)->index(cache_),
@@ -274,7 +275,7 @@ void BuddyAllocator::CleanIdleFallBackAlloc() {
return;
}
- VLOG(3) << "Return block " << block << " to fallback allocator.";
+ VLOG(10) << "Return block " << block << " to fallback allocator.";
system_allocator_->Free(block, max_chunk_size_, block->index(cache_));
cache_.invalidate(block);
@@ -310,7 +311,7 @@ void BuddyAllocator::CleanIdleNormalAlloc() {
MemoryBlock* block = static_cast(std::get<2>(*pool));
- VLOG(3) << "Return block " << block << " to base allocator.";
+ VLOG(10) << "Return block " << block << " to base allocator.";
system_allocator_->Free(block, max_chunk_size_, block->index(cache_));
cache_.invalidate(block);
diff --git a/paddle/memory/detail/meta_cache.cc b/paddle/memory/detail/meta_cache.cc
index f0721c3b94b74eed3a02e4bc744c24b97ac170a9..7e2f92b00ca5d787c1114176c5dc3304ca3ebe26 100644
--- a/paddle/memory/detail/meta_cache.cc
+++ b/paddle/memory/detail/meta_cache.cc
@@ -30,7 +30,7 @@ Metadata MetadataCache::load(const MemoryBlock* block) {
return existing_metadata->second;
} else {
auto* meta = reinterpret_cast(block);
- VLOG(3) << "Load MetaData type=" << meta->type;
+ VLOG(10) << "Load MetaData type=" << meta->type;
PADDLE_ASSERT(meta->check_guards());
return *reinterpret_cast(block);
}
diff --git a/paddle/memory/detail/system_allocator.cc b/paddle/memory/detail/system_allocator.cc
index 33166d9ce23a4a345fc00a65adf63281b13643c3..6b4e46f56a0c9c9836c5b353ec9c554454ab0491 100644
--- a/paddle/memory/detail/system_allocator.cc
+++ b/paddle/memory/detail/system_allocator.cc
@@ -41,7 +41,16 @@ void* CPUAllocator::Alloc(size_t& index, size_t size) {
index = 0; // unlock memory
- void* p = malloc(size);
+ void* p;
+
+#ifdef PADDLE_USE_MKLDNN
+ // refer to https://github.com/01org/mkl-dnn/blob/master/include/mkldnn.hpp
+ // memory alignment
+ PADDLE_ENFORCE_EQ(posix_memalign(&p, 4096ul, size), 0);
+#else
+ PADDLE_ENFORCE_EQ(posix_memalign(&p, 32ul, size), 0);
+#endif
+ PADDLE_ENFORCE(p, "Fail to allocate CPU memory: size = %d .", size);
if (p != nullptr) {
if (FLAGS_use_pinned_memory) {
diff --git a/paddle/memory/memory.cc b/paddle/memory/memory.cc
index 0b648642f90a09db7452cce97eb04cedfcf55f4f..5eb1c44eb6fc45db31ef44bf79e74b79193e08aa 100644
--- a/paddle/memory/memory.cc
+++ b/paddle/memory/memory.cc
@@ -39,15 +39,15 @@ BuddyAllocator* GetCPUBuddyAllocator() {
template <>
void* Alloc(platform::CPUPlace place, size_t size) {
- VLOG(3) << "Allocate " << size << " bytes on " << platform::Place(place);
+ VLOG(10) << "Allocate " << size << " bytes on " << platform::Place(place);
void* p = GetCPUBuddyAllocator()->Alloc(size);
- VLOG(3) << " pointer=" << p;
+ VLOG(10) << " pointer=" << p;
return p;
}
template <>
void Free(platform::CPUPlace place, void* p) {
- VLOG(3) << "Free pointer=" << p << " on " << platform::Place(place);
+ VLOG(10) << "Free pointer=" << p << " on " << platform::Place(place);
GetCPUBuddyAllocator()->Free(p);
}
@@ -69,11 +69,12 @@ BuddyAllocator* GetGPUBuddyAllocator(int gpu_id) {
platform::GpuMinChunkSize(),
platform::GpuMaxChunkSize());
}
- VLOG(3) << "\n\nNOTE: each GPU device use "
- << FLAGS_fraction_of_gpu_memory_to_use * 100 << "% of GPU memory.\n"
- << "You can set environment variable '"
- << platform::kEnvFractionGpuMemoryToUse
- << "' to change the fraction of GPU usage.\n\n";
+ VLOG(10) << "\n\nNOTE: each GPU device use "
+ << FLAGS_fraction_of_gpu_memory_to_use * 100
+ << "% of GPU memory.\n"
+ << "You can set environment variable '"
+ << platform::kEnvFractionGpuMemoryToUse
+ << "' to change the fraction of GPU usage.\n\n";
}
platform::SetDeviceId(gpu_id);
return as[gpu_id];
diff --git a/paddle/operators/dynamic_recurrent_op_test.cc b/paddle/operators/dynamic_recurrent_op_test.cc
index fff63efb24c70b7e864e2d5b011a22883c13dede..8d840e259b190ead86a66df8ab31c5170db4d824 100644
--- a/paddle/operators/dynamic_recurrent_op_test.cc
+++ b/paddle/operators/dynamic_recurrent_op_test.cc
@@ -51,7 +51,7 @@ class RNNAlgorithmTestHelper : public ::testing::Test {
CreateGlobalVariables();
auto op_desc = CreateOpDesc();
- op = paddle::framework::OpRegistry::CreateOp(op_desc, nullptr);
+ op = paddle::framework::OpRegistry::CreateOp(op_desc);
dop = &(dynamic_cast(op.get())->rnn);
InitCacheManually();
InitStepNet();
diff --git a/paddle/operators/gaussian_random_op.cc b/paddle/operators/gaussian_random_op.cc
index 04dfdf7c48381240108cf924979764966599151f..be7f542a7a274d88d2dac953995d6a83a6ce022d 100644
--- a/paddle/operators/gaussian_random_op.cc
+++ b/paddle/operators/gaussian_random_op.cc
@@ -45,14 +45,14 @@ class GaussianRandomOp : public framework::OperatorWithKernel {
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasOutput("Out"),
"Output(Out) of GaussianRandomOp should not be null.");
- auto dims = ctx->Attrs().Get>("dims");
+ auto shape = ctx->Attrs().Get>("shape");
std::vector temp;
- temp.reserve(dims.size());
- for (auto dim : dims) {
+ temp.reserve(shape.size());
+ for (auto dim : shape) {
temp.push_back(static_cast(dim));
}
- PADDLE_ENFORCE(dims.size() > 0UL,
- "dims can be one int or array. dims must be set.");
+ PADDLE_ENFORCE(shape.size() > 0UL,
+ "shape can be one int or array. shape must be set.");
ctx->SetOutputDim("Out", framework::make_ddim(temp));
}
@@ -74,7 +74,7 @@ GaussianRandom operator.
Use to initialize tensor with gaussian random generator.
)DOC");
- AddAttr>("dims", "The dimension of random tensor.");
+ AddAttr>("shape", "The dimension of random tensor.");
AddAttr("mean", "mean of random tensor.").SetDefault(.0f);
AddAttr("std", "std of random tensor.").SetDefault(1.0f);
AddAttr("seed",
diff --git a/paddle/operators/lookup_table_op.cc b/paddle/operators/lookup_table_op.cc
index 8fdd42352e5e6857e4bf0e4645f82c8e2fcdc6fd..0b361e20f2037b9b75bc8670488dff1c50fb689c 100644
--- a/paddle/operators/lookup_table_op.cc
+++ b/paddle/operators/lookup_table_op.cc
@@ -43,7 +43,7 @@ class LookupTableOp : public framework::OperatorWithKernel {
protected:
framework::DataType IndicateDataType(
const framework::ExecutionContext& ctx) const override {
- return framework::ToDataType(ctx.Input("W")->type());
+ return framework::ToDataType(ctx.Input("W")->type());
}
};
@@ -93,7 +93,7 @@ class LookupTableOpGrad : public framework::OperatorWithKernel {
protected:
framework::DataType IndicateDataType(
const framework::ExecutionContext& ctx) const override {
- return framework::ToDataType(ctx.Input("W")->type());
+ return framework::ToDataType(ctx.Input("W")->type());
}
};
diff --git a/paddle/operators/lookup_table_op.cu b/paddle/operators/lookup_table_op.cu
index 837b2a1f4c94f201c0ab498671f936aab6c7a811..c7ba1720662fe80c945f2b4aa19745e408d40948 100644
--- a/paddle/operators/lookup_table_op.cu
+++ b/paddle/operators/lookup_table_op.cu
@@ -61,16 +61,16 @@ template
class LookupTableCUDAKernel : public framework::OpKernel {
public:
void Compute(const framework::ExecutionContext& context) const override {
- auto table_t = context.Input("W");
- auto ids_t = context.Input("Ids");
- auto output_t = context.Output("Out");
+ auto* table_t = context.Input("W");
+ auto* ids_t = context.Input("Ids");
+ auto* output_t = context.Output("Out");
size_t N = table_t->dims()[0];
size_t D = table_t->dims()[1];
size_t K = ids_t->numel();
- auto ids = ids_t->data();
- auto table = table_t->data();
- auto output = output_t->mutable_data(context.GetPlace());
+ auto* ids = ids_t->data();
+ auto* table = table_t->data();
+ auto* output = output_t->mutable_data(context.GetPlace());
dim3 threads(128, 8);
dim3 grids(8, 1);
@@ -87,9 +87,9 @@ class LookupTableGradCUDAKernel : public framework::OpKernel {
void Compute(const framework::ExecutionContext& context) const override {
bool is_sparse = context.Attr("is_sparse");
if (is_sparse) {
- auto* ids = context.Input("Ids");
- auto* table = context.Input("W");
- auto* d_output = context.Input(framework::GradVarName("Out"));
+ auto* ids = context.Input("Ids");
+ auto* table = context.Input("W");
+ auto* d_output = context.Input(framework::GradVarName("Out"));
auto* d_table = context.Output(framework::GradVarName("W"));
auto* ids_data = ids->data();
@@ -116,12 +116,12 @@ class LookupTableGradCUDAKernel : public framework::OpKernel {
auto* d_output_data = d_output->data();
PADDLE_ENFORCE_EQ(d_table_value->dims(), d_output->dims());
memory::Copy(gpu_place, d_table_data, gpu_place, d_output_data,
- d_output->numel(), stream);
+ d_output->numel() * sizeof(T), stream);
} else {
- auto ids_t = context.Input("Ids");
- auto d_output_t = context.Input(framework::GradVarName("Out"));
- auto d_table_t = context.Output(framework::GradVarName("W"));
+ auto ids_t = context.Input("Ids");
+ auto d_output_t = context.Input(framework::GradVarName("Out"));
+ auto d_table_t = context.Output(framework::GradVarName("W"));
int N = d_table_t->dims()[0];
int D = d_table_t->dims()[1];
diff --git a/paddle/operators/lookup_table_op.h b/paddle/operators/lookup_table_op.h
index 54067cd01d3ef35a050a3c2565ea19cb6520bcec..ea3289d2731a4b2098c3a199464559b0a0ce7202 100644
--- a/paddle/operators/lookup_table_op.h
+++ b/paddle/operators/lookup_table_op.h
@@ -19,22 +19,22 @@
namespace paddle {
namespace operators {
-using Tensor = framework::Tensor;
+using LoDTensor = framework::LoDTensor;
using SelectedRows = framework::SelectedRows;
template
class LookupTableKernel : public framework::OpKernel {
public:
void Compute(const framework::ExecutionContext& context) const override {
- auto table_t = context.Input("W"); // float tensor
- auto ids_t = context.Input("Ids"); // int tensor
- auto output_t = context.Output("Out"); // float tensor
+ auto* table_t = context.Input("W"); // float tensor
+ auto* ids_t = context.Input("Ids"); // int tensor
+ auto* output_t = context.Output("Out"); // float tensor
int N = table_t->dims()[0];
int D = table_t->dims()[1];
- auto ids = ids_t->data();
- auto table = table_t->data();
- auto output = output_t->mutable_data(context.GetPlace());
+ auto* ids = ids_t->data();
+ auto* table = table_t->data();
+ auto* output = output_t->mutable_data(context.GetPlace());
for (int64_t i = 0; i < ids_t->numel(); ++i) {
PADDLE_ENFORCE_LT(ids[i], N);
PADDLE_ENFORCE_GE(ids[i], 0);
@@ -49,9 +49,9 @@ class LookupTableGradKernel : public framework::OpKernel {
void Compute(const framework::ExecutionContext& context) const override {
bool is_sparse = context.Attr("is_sparse");
if (is_sparse) {
- auto* ids = context.Input("Ids");
- auto* table = context.Input("W");
- auto* d_output = context.Input(framework::GradVarName("Out"));
+ auto* ids = context.Input("Ids");
+ auto* table = context.Input("W");
+ auto* d_output = context.Input(framework::GradVarName("Out"));
auto* d_table = context.Output(framework::GradVarName("W"));
auto* ids_data = ids->data();
@@ -76,10 +76,10 @@ class LookupTableGradKernel : public framework::OpKernel {
PADDLE_ENFORCE_EQ(d_table_value->dims(), d_output->dims());
memcpy(d_table_data, d_output_data, sizeof(T) * d_output->numel());
} else {
- auto* ids = context.Input("Ids");
- auto* d_output = context.Input(framework::GradVarName("Out"));
- auto* d_table = context.Output(framework::GradVarName("W"));
- auto* table = context.Input("W");
+ auto* ids = context.Input("Ids");
+ auto* d_output = context.Input(framework::GradVarName("Out"));
+ auto* d_table = context.Output(framework::GradVarName("W"));
+ auto* table = context.Input("W");
auto* ids_data = ids->data();
auto ids_dim = ids->dims();
diff --git a/paddle/operators/lstm_op.cc b/paddle/operators/lstm_op.cc
index 0a089b7c2dc1e05224525bc4fe5399ec39036d01..94342d940704d850a2a45c281a3d88de5a132753 100644
--- a/paddle/operators/lstm_op.cc
+++ b/paddle/operators/lstm_op.cc
@@ -21,7 +21,6 @@ class LSTMOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
- protected:
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("Input"),
"Input(Input) of LSTM should not be null.");
@@ -29,9 +28,13 @@ class LSTMOp : public framework::OperatorWithKernel {
"Output(Hidden) of LSTM should not be null.");
PADDLE_ENFORCE(ctx->HasOutput("Cell"),
"Output(Cell) of LSTM should not be null.");
+ PADDLE_ENFORCE(ctx->HasOutput("BatchGate"),
+ "Output(BatchGate) of LSTM should not be null.");
+ PADDLE_ENFORCE(ctx->HasOutput("BatchCellPreAct"),
+ "Output(BatchGate) of LSTM should not be null.");
- auto x_dims = ctx->GetInputDim("Input");
- PADDLE_ENFORCE_EQ(x_dims.size(), 2, "Input(X)'s rank must be 2.");
+ auto in_dims = ctx->GetInputDim("Input");
+ PADDLE_ENFORCE_EQ(in_dims.size(), 2, "Input(X)'s rank must be 2.");
if (ctx->HasInput("H0")) {
PADDLE_ENFORCE(ctx->HasInput("C0"),
@@ -44,7 +47,7 @@ class LSTMOp : public framework::OperatorWithKernel {
"should be the same.");
}
- int frame_size = x_dims[1] / 4;
+ int frame_size = in_dims[1] / 4;
auto w_dims = ctx->GetInputDim("Weight");
PADDLE_ENFORCE_EQ(w_dims.size(), 2,
"The rank of Input(Weight) should be 2.");
@@ -71,12 +74,21 @@ class LSTMOp : public framework::OperatorWithKernel {
"4 * %d if disable peepholes connection",
frame_size);
}
- ctx->SetOutputDim("Hidden", {x_dims[0], frame_size});
- ctx->SetOutputDim("Cell", {x_dims[0], frame_size});
- ctx->SetOutputDim("BatchGate", x_dims);
+ framework::DDim out_dims({in_dims[0], frame_size});
+ ctx->SetOutputDim("Hidden", out_dims);
+ ctx->SetOutputDim("Cell", out_dims);
+ ctx->SetOutputDim("BatchGate", in_dims);
+ ctx->SetOutputDim("BatchCellPreAct", out_dims);
ctx->ShareLoD("Input", "Hidden");
ctx->ShareLoD("Input", "Cell");
}
+
+ protected:
+ framework::DataType IndicateDataType(
+ const framework::ExecutionContext& ctx) const override {
+ return framework::ToDataType(
+ ctx.Input("Input")->type());
+ }
};
class LSTMOpMaker : public framework::OpProtoAndCheckerMaker {
@@ -86,16 +98,18 @@ class LSTMOpMaker : public framework::OpProtoAndCheckerMaker {
AddInput("Input",
"(LoDTensor) the first input is a LodTensor, which support "
"variable-time length input sequence. The underlying tensor in "
- "this LoDTensor is a matrix with shape (T X 4D), where, T is the "
+ "this LoDTensor is a matrix with shape (T X 4D), where T is the "
"total time steps in this mini-batch, D is the hidden size.");
AddInput("H0",
"(Tensor, optional) the initial hidden state is an optional "
"input. This is a tensor with shape (N x D), where N is the "
- "batch size, D is the hidden size.");
+ "batch size, D is the hidden size.")
+ .AsDispensable();
AddInput("C0",
"(Tensor, optional) the initial cell state is an optional "
"input. This is a tensor with shape (N x D), where N is the "
- "batch size. `H0` and `C0` can be NULL but only at the same time");
+ "batch size. `H0` and `C0` can be NULL but only at the same time")
+ .AsDispensable();
AddInput("Weight",
"(Tensor) the learnable hidden-hidden weights."
" - The shape is (D x 4D), where D is the hidden size. "
@@ -109,22 +123,27 @@ class LSTMOpMaker : public framework::OpProtoAndCheckerMaker {
" - Bias = {b_c, b_i, b_f, b_o}."
"2. `usePeepholes = True` "
" - The shape is (1 x 7D). "
- " - Bias = {b_c, b_i, b_f, b_o, W_ic, W_fc, W_oc}.");
+ " - Bias = {b_c, b_i, b_f, b_o, W_ic, W_fc, W_oc}.")
+ .AsDispensable();
+ AddOutput("Hidden",
+ "(LoDTensor) the hidden state of LSTM operator. "
+ "The shape is (T x D), and lod is the same with the `Input`.");
+ AddOutput("Cell",
+ "(LoDTensor) the cell state of LSTM operator. "
+ "The shape is (T x D), and lod is the same with the `Input`.");
AddOutput("BatchGate",
"(LoDTensor) This LoDTensor contains input gate, forget gate "
"and output gate after the nonlinear computation. This "
"LoDTensor has the same shape with the reorganized input, which "
- "was also be called batch input. The LoD size is 2. The first "
+ "is also be called batch input. The LoD size is 2. The first "
"LoD is the batch offsets and the second LoD contains the "
"indexes, which denote the position of reorganized sequence "
"in the raw input.")
.AsIntermediate();
- AddOutput("Hidden",
- "(LoDTensor) the hidden state lod tensor of LSTM operator. "
- "The shape and lod is the same with the `Input`.");
- AddOutput("Cell",
- "(LoDTensor) the cell state lod tensor of LSTM operator. "
- "The shape and lod is the same with the `Input`.");
+ AddOutput("BatchCellPreAct",
+ "(LoDTensor) This LoDTensor is got in the forward and used "
+ "in the backward.")
+ .AsIntermediate();
AddAttr("usePeepholes",
"(bool, defalut: True) "
"whether to enable diagonal/peephole connections.")
@@ -202,15 +221,37 @@ class LSTMGradOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
- protected:
void InferShape(framework::InferShapeContext* ctx) const override {
- PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Hidden")),
- "Input(Hidden@GRAD) should not be null");
- PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Cell")),
- "Input(Cell@GRAD) should not be null");
- ctx->SetOutputDim(framework::GradVarName("Weight"),
- ctx->GetInputDim("Weight"));
- ctx->SetOutputDim(framework::GradVarName("Bias"), ctx->GetInputDim("Bias"));
+ PADDLE_ENFORCE(ctx->HasInput("Input"),
+ "Input(Input) of LSTM should not be null.");
+ PADDLE_ENFORCE(ctx->HasInput("Hidden"),
+ "Input(Hidden) of LSTM should not be null.");
+ PADDLE_ENFORCE(ctx->HasInput("Cell"),
+ "Input(Cell) of LSTM should not be null.");
+
+ PADDLE_ENFORCE(ctx->HasInput("BatchGate"),
+ "Input(BatchGate) of LSTM should not be null.");
+ PADDLE_ENFORCE(ctx->HasInput("BatchCellPreAct"),
+ "Input(BatchGate) of LSTM should not be null.");
+
+ auto in_g_name = framework::GradVarName("Input");
+ if (ctx->HasOutput(in_g_name))
+ ctx->SetOutputDim(in_g_name, ctx->GetInputDim("Input"));
+
+ auto w_g_name = framework::GradVarName("Weight");
+ if (ctx->HasOutput(w_g_name))
+ ctx->SetOutputDim(w_g_name, ctx->GetInputDim("Weight"));
+
+ auto b_g_name = framework::GradVarName("Bias");
+ if (ctx->HasOutput(b_g_name))
+ ctx->SetOutputDim(b_g_name, ctx->GetInputDim("Bias"));
+ }
+
+ protected:
+ framework::DataType IndicateDataType(
+ const framework::ExecutionContext& ctx) const override {
+ return framework::ToDataType(
+ ctx.Input("Input")->type());
}
};
diff --git a/paddle/operators/lstm_op.h b/paddle/operators/lstm_op.h
index 0af5694c48fcb4437e3acd422606de013bb2e145..af088b80b4283cf221a1dff74546d73d977fada3 100644
--- a/paddle/operators/lstm_op.h
+++ b/paddle/operators/lstm_op.h
@@ -21,8 +21,9 @@ limitations under the License. */
namespace paddle {
namespace operators {
-using framework::LoDTensor;
-using framework::Tensor;
+using LoDTensor = framework::LoDTensor;
+using Tensor = framework::Tensor;
+
template
using EigenMatrix = framework::EigenMatrix;
@@ -31,15 +32,15 @@ template
class LSTMKernel : public framework::OpKernel {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
- auto* input = ctx.Input("Input");
- auto* weight = ctx.Input("Weight");
- auto* bias = ctx.Input("Bias");
+ auto* input = ctx.Input("Input");
+ auto* weight = ctx.Input("Weight");
+ auto* bias = ctx.Input("Bias");
- auto* batch_gate = ctx.Output("BatchGate");
+ auto* batch_gate = ctx.Output("BatchGate");
batch_gate->mutable_data(ctx.GetPlace());
- auto* hidden_out = ctx.Output("Hidden");
+ auto* hidden_out = ctx.Output("Hidden");
hidden_out->mutable_data(ctx.GetPlace());
- auto* cell_out = ctx.Output("Cell");
+ auto* cell_out = ctx.Output("Cell");
cell_out->mutable_data(ctx.GetPlace());
// Now the function ShareLoD in InferShape is not implemented.
@@ -49,7 +50,8 @@ class LSTMKernel : public framework::OpKernel {
bool is_reverse = ctx.Attr("isReverse");
math::LoDTensor2BatchFunctor to_batch;
- to_batch(ctx.device_context(), *input, *batch_gate, is_reverse);
+ auto& device_ctx = ctx.device_context();
+ to_batch(device_ctx, *input, *batch_gate, true, is_reverse);
auto in_dims = input->dims();
int frame_size = static_cast(in_dims[1] / 4);
@@ -69,17 +71,26 @@ class LSTMKernel : public framework::OpKernel {
}
math::LstmMetaValue lstm_value;
- T* bias_data = const_cast(bias->data());
- // the code style in LstmMetaValue will be updated later.
- lstm_value.checkIg = bias_data + 4 * frame_size;
- lstm_value.checkFg = lstm_value.checkIg + frame_size;
- lstm_value.checkOg = lstm_value.checkFg + frame_size;
+ if (bias) {
+ T* bias_data = const_cast(bias->data());
+ // the code style in LstmMetaValue will be updated later.
+
+ lstm_value.checkIg = bias_data + 4 * frame_size;
+ lstm_value.checkFg = lstm_value.checkIg + frame_size;
+ lstm_value.checkOg = lstm_value.checkFg + frame_size;
+ } else {
+ lstm_value.checkIg = nullptr;
+ lstm_value.checkFg = nullptr;
+ lstm_value.checkOg = nullptr;
+ }
lstm_value.prevStateValue = nullptr;
- framework::LoDTensor batch_out, batch_cell, batch_cell_pre_act;
- batch_out.mutable_data(dims, ctx.GetPlace());
+ // Use the local variable as here.
+ LoDTensor batch_hidden, batch_cell;
+ auto* batch_cell_pre_act = ctx.Output("BatchCellPreAct");
+ batch_hidden.mutable_data(dims, ctx.GetPlace());
batch_cell.mutable_data(dims, ctx.GetPlace());
- batch_cell_pre_act.mutable_data(dims, ctx.GetPlace());
+ batch_cell_pre_act->mutable_data(dims, ctx.GetPlace());
auto batch_starts = batch_gate->lod()[0];
size_t num_batch = batch_starts.size() - 1;
@@ -92,18 +103,18 @@ class LSTMKernel : public framework::OpKernel {
int bend = static_cast(batch_starts[n + 1]);
Tensor gate_t = batch_gate->Slice(bstart, bend);
- Tensor out_t = batch_out.Slice(bstart, bend);
+ Tensor out_t = batch_hidden.Slice(bstart, bend);
Tensor cell_t = batch_cell.Slice(bstart, bend);
- Tensor cell_pre_act_t = batch_cell_pre_act.Slice(bstart, bend);
+ Tensor cell_pre_act_t = batch_cell_pre_act->Slice(bstart, bend);
int cur_batch_size = bend - bstart;
if (n != 0) {
int pre_h_start = static_cast(batch_starts[n - 1]);
int pre_h_end = pre_h_start + cur_batch_size;
- auto pre_hidden_t = batch_out.Slice(pre_h_start, pre_h_end);
- math::matmul(ctx.device_context(), pre_hidden_t, false,
- *weight, false, static_cast(1.0), &gate_t,
+ auto pre_hidden_t = batch_hidden.Slice(pre_h_start, pre_h_end);
+ math::matmul(device_ctx, pre_hidden_t, false, *weight, false,
+ static_cast(1.0), &gate_t,
static_cast(1.0));
}
// else if : FIXME support the initial hidden and cell
@@ -112,27 +123,186 @@ class LSTMKernel : public framework::OpKernel {
lstm_value.outputValue = out_t.data();
lstm_value.stateValue = cell_t.data();
lstm_value.stateActiveValue = cell_pre_act_t.data();
- math::LstmUnitFunctor::compute(ctx.device_context(), lstm_value,
+ math::LstmUnitFunctor::compute(device_ctx, lstm_value,
frame_size, cur_batch_size,
gate_act, cell_act, cand_act);
lstm_value.prevStateValue = lstm_value.stateValue;
}
math::Batch2LoDTensorFunctor to_seq;
- batch_out.set_lod(batch_gate->lod());
+ batch_hidden.set_lod(batch_gate->lod());
// restore the output hidden in LoDTensor from the batch hidden
- to_seq(ctx.device_context(), batch_out, *hidden_out);
+ to_seq(device_ctx, batch_hidden, *hidden_out);
batch_cell.set_lod(batch_gate->lod());
// restore the output cell state in LoDTensor from the batch cell
- to_seq(ctx.device_context(), batch_cell, *cell_out);
+ to_seq(device_ctx, batch_cell, *cell_out);
}
};
template
class LSTMGradKernel : public framework::OpKernel {
public:
- void Compute(const framework::ExecutionContext& ctx) const override {}
+ void Compute(const framework::ExecutionContext& ctx) const override {
+ auto* input = ctx.Input("Input");
+ auto* weight = ctx.Input("Weight");
+ auto* bias = ctx.Input("Bias");
+
+ auto* hidden_out = ctx.Input("Hidden");
+ auto* cell_out = ctx.Input("Cell");
+
+ auto* batch_gate = ctx.Input("BatchGate");
+ auto* batch_cell_pre_act = ctx.Input("BatchCellPreAct");
+
+ auto* hidden_g = ctx.Input(framework::GradVarName("Hidden"));
+
+ auto* in_g = ctx.Output(framework::GradVarName("Input"));
+ auto* weight_g = ctx.Output(framework::GradVarName("Weight"));
+ auto* bias_g = ctx.Output(framework::GradVarName("Bias"));
+
+ auto& device_ctx = ctx.device_context();
+ math::SetConstant zero;
+ if (weight_g) {
+ weight_g->mutable_data(ctx.GetPlace());
+ zero(device_ctx, weight_g, static_cast(0.0));
+ }
+
+ auto in_dims = input->dims();
+ auto out_dims = hidden_g->dims();
+ int frame_size = static_cast(in_dims[1] / 4);
+ PADDLE_ENFORCE_EQ(frame_size, out_dims[1]);
+
+ math::LstmMetaValue lstm_value;
+ if (bias) {
+ T* bias_data = const_cast(bias->data());
+ lstm_value.checkIg = bias_data + 4 * frame_size;
+ lstm_value.checkFg = lstm_value.checkIg + frame_size;
+ lstm_value.checkOg = lstm_value.checkFg + frame_size;
+ } else {
+ lstm_value.checkIg = nullptr;
+ lstm_value.checkFg = nullptr;
+ lstm_value.checkOg = nullptr;
+ }
+
+ math::LstmMetaGrad lstm_grad;
+ if (bias && bias_g) {
+ T* bias_g_data = const_cast(bias_g->mutable_data(ctx.GetPlace()));
+ zero(device_ctx, bias_g, static_cast(0.0));
+ lstm_grad.checkIgGrad = bias_g_data + 4 * frame_size;
+ lstm_grad.checkFgGrad = lstm_grad.checkIgGrad + frame_size;
+ lstm_grad.checkOgGrad = lstm_grad.checkFgGrad + frame_size;
+ } else {
+ lstm_grad.checkIgGrad = nullptr;
+ lstm_grad.checkFgGrad = nullptr;
+ lstm_grad.checkOgGrad = nullptr;
+ }
+
+ math::LoDTensor2BatchFunctor to_batch;
+
+ // use the local variable as here.
+ LoDTensor batch_hidden;
+ batch_hidden.mutable_data(out_dims, ctx.GetPlace());
+ batch_hidden.set_lod(batch_gate->lod());
+ to_batch(device_ctx, *hidden_out, batch_hidden, false);
+
+ LoDTensor batch_hidden_g;
+ batch_hidden_g.mutable_data(out_dims, ctx.GetPlace());
+ batch_hidden_g.set_lod(batch_gate->lod());
+ to_batch(device_ctx, *hidden_g, batch_hidden_g, false);
+
+ LoDTensor batch_cell;
+ batch_cell.mutable_data(out_dims, ctx.GetPlace());
+ batch_cell.set_lod(batch_gate->lod());
+ to_batch(device_ctx, *cell_out, batch_cell, false);
+
+ LoDTensor batch_cell_g;
+ batch_cell_g.mutable_data(out_dims, ctx.GetPlace());
+ batch_cell_g.set_lod(batch_gate->lod());
+ // TODO(qingqing) support the case output cell has gradient.
+ // to_batch(device_ctx, *cell_g, batch_cell_g, false);
+ zero(device_ctx, &batch_cell_g, static_cast(0.0));
+
+ LoDTensor batch_gate_g;
+ batch_gate_g.mutable_data(batch_gate->dims(), ctx.GetPlace());
+ batch_gate_g.set_lod(batch_gate->lod());
+
+ auto gate_act = ctx.Attr("gateActivation");
+ auto cell_act = ctx.Attr("cellActivation");
+ auto cand_act = ctx.Attr("candidateActivation");
+
+ auto batch_starts = batch_gate->lod()[0];
+ size_t num_batch = batch_starts.size() - 1;
+ for (int n = static_cast(num_batch) - 1; n >= 0; n--) {
+ int bstart = static_cast(batch_starts[n]);
+ int bend = static_cast(batch_starts[n + 1]);
+
+ Tensor gate = batch_gate->Slice(bstart, bend);
+ Tensor cell = batch_cell.Slice(bstart, bend);
+ Tensor cell_pre_act = batch_cell_pre_act->Slice(bstart, bend);
+ lstm_value.gateValue = gate.data();
+ lstm_value.stateValue = cell.data();
+ lstm_value.stateActiveValue = cell_pre_act.data();
+
+ Tensor out_g = batch_hidden_g.Slice(bstart, bend);
+ Tensor gate_g = batch_gate_g.Slice(bstart, bend);
+ Tensor cell_g = batch_cell_g.Slice(bstart, bend);
+ lstm_grad.stateGrad = cell_g.data();
+ lstm_grad.gateGrad = gate_g.data();
+ lstm_grad.outputGrad = out_g.data();
+
+ if (n) {
+ int bstart_pre = static_cast(batch_starts[n - 1]);
+ Tensor cell_pre = batch_cell.Slice(bstart_pre, bstart);
+ Tensor cell_pre_g = batch_cell_g.Slice(bstart_pre, bstart);
+ lstm_value.prevStateValue = cell_pre.data();
+ lstm_grad.prevStateGrad = cell_pre_g.data();
+ } else {
+ lstm_value.prevStateValue = nullptr;
+ lstm_grad.prevStateGrad = nullptr;
+ }
+
+ int cur_batch_size = bend - bstart;
+ math::LstmUnitGradFunctor::compute(
+ device_ctx, lstm_value, lstm_grad, frame_size, cur_batch_size,
+ gate_act, cell_act, cand_act);
+
+ if (n != 0) {
+ int pre_h_start = static_cast(batch_starts[n - 1]);
+ int pre_h_end = pre_h_start + cur_batch_size;
+ auto pre_hidden_g = batch_hidden_g.Slice(pre_h_start, pre_h_end);
+ math::matmul(device_ctx, gate_g, false, *weight, true,
+ static_cast(1.0), &pre_hidden_g,
+ static_cast(1.0));
+ if (weight_g) {
+ /* backward weight */
+ auto pre_hidden = batch_hidden.Slice(pre_h_start, pre_h_end);
+ math::matmul(device_ctx, pre_hidden, true, gate_g, false,
+ static_cast(1.0), weight_g,
+ static_cast(1.0));
+ }
+ }
+ }
+
+ math::Batch2LoDTensorFunctor to_seq;
+ if (in_g) {
+ /* backward data */
+ in_g->mutable_data(ctx.GetPlace());
+ to_seq(device_ctx, batch_gate_g, *in_g);
+ }
+ if (bias && bias_g) {
+ /* backward bias */
+ int m = static_cast(batch_gate_g.dims()[0]);
+ int n = static_cast(batch_gate_g.dims()[1]);
+
+ Tensor ones;
+ ones.mutable_data({m}, ctx.GetPlace());
+ math::SetConstant set;
+ set(device_ctx, &ones, static_cast(1.0));
+
+ math::gemv(device_ctx, true, m, n, 1., batch_gate_g.data(),
+ ones.data(), 0., bias_g->data());
+ }
+ }
};
} // namespace operators
diff --git a/paddle/operators/math/detail/lstm_cpu_kernel.h b/paddle/operators/math/detail/lstm_cpu_kernel.h
index 74d51d7bc9b91f4c8088384d77183131f57aafab..d0ed55ea168bc3e701c421c51d662c646e475351 100644
--- a/paddle/operators/math/detail/lstm_cpu_kernel.h
+++ b/paddle/operators/math/detail/lstm_cpu_kernel.h
@@ -26,10 +26,7 @@ namespace detail {
template