diff --git a/.travis.yml b/.travis.yml
index b4b83fcdbc84ce0fb0c91c816ebc3c964acfa590..e217c8f5a740ef5ab7315656ed7839ffa219c805 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -4,7 +4,6 @@ cache:
- $HOME/.ccache
- $HOME/.cache/pip
- $TRAVIS_BUILD_DIR/build/third_party
- - $TRAVIS_BUILD_DIR/build_android/third_party
sudo: required
dist: trusty
os:
@@ -12,7 +11,6 @@ os:
env:
- JOB=build_doc
- JOB=check_style
- - JOB=build_android
addons:
apt:
packages:
@@ -23,7 +21,6 @@ addons:
- python
- python-pip
- python2.7-dev
- - python-numpy
- python-wheel
- libboost-dev
- curl
@@ -37,8 +34,8 @@ before_install:
- if [[ "$JOB" == "check_style" ]]; then sudo ln -s /usr/bin/clang-format-3.8 /usr/bin/clang-format; fi
# Paddle is using protobuf 3.1 currently. Protobuf 3.2 breaks the compatibility. So we specify the python
# protobuf version.
- - pip install -r $TRAVIS_BUILD_DIR/python/requirements.txt
- - pip install wheel sphinx==1.5.6 recommonmark sphinx-rtd-theme==0.1.9 virtualenv pre-commit LinkChecker
+ - sudo pip install -r $TRAVIS_BUILD_DIR/python/requirements.txt
+ - sudo pip install wheel sphinx==1.5.6 recommonmark sphinx-rtd-theme==0.1.9 virtualenv pre-commit LinkChecker
- curl https://glide.sh/get | bash
- eval "$(GIMME_GO_VERSION=1.8.3 gimme)"
- go get -u github.com/alecthomas/gometalinter
diff --git a/CMakeLists.txt b/CMakeLists.txt
index ad559672ad2f83a3d62cdf332b47c6cf1e730f70..08237cd850ae20c515a39c8783a18deaac431626 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -65,8 +65,8 @@ if(NOT CMAKE_BUILD_TYPE)
endif()
if(ANDROID)
- if(${CMAKE_SYSTEM_VERSION} VERSION_LESS "21")
- message(FATAL_ERROR "Unsupport standalone toolchains with Android API level lower than 21")
+ if(${CMAKE_SYSTEM_VERSION} VERSION_LESS "16")
+ message(FATAL_ERROR "Unsupport standalone toolchains with Android API level lower than 16")
endif()
set(WITH_GPU OFF CACHE STRING
diff --git a/Dockerfile.android b/Dockerfile.android
index c0fa58c384f9ebcae60477ffce49ea4ffa929db9..452aa1574550627c2cce6375e12e154a9763254d 100644
--- a/Dockerfile.android
+++ b/Dockerfile.android
@@ -4,9 +4,15 @@ MAINTAINER PaddlePaddle Authors
ARG UBUNTU_MIRROR
RUN /bin/bash -c 'if [[ -n ${UBUNTU_MIRROR} ]]; then sed -i 's#http://archive.ubuntu.com/ubuntu#${UBUNTU_MIRROR}#g' /etc/apt/sources.list; fi'
+# ENV variables
+ARG ANDROID_ABI
+
+ENV ANDROID_ABI=${ANDROID_ABI:-"armeabi-v7a"}
+
ENV HOME=/root \
ANDROID_NDK_HOME=/opt/android-ndk-linux \
- ANDROID_STANDALONE_TOOLCHAIN=/opt/android-toolchain-gcc
+ ANDROID_ARM_STANDALONE_TOOLCHAIN=/opt/arm-toolchain \
+ ANDROID_ARM64_STANDALONE_TOOLCHAIN=/opt/arm64-toolchain
RUN apt-get update && \
apt-get install -y \
@@ -15,12 +21,11 @@ RUN apt-get update && \
apt-get clean -y
# Install Go and glide
-RUN wget -O go.tgz https://storage.googleapis.com/golang/go1.8.1.linux-amd64.tar.gz && \
- tar -C /usr/local -xzf go.tgz && \
+RUN wget -qO- go.tgz https://storage.googleapis.com/golang/go1.8.1.linux-amd64.tar.gz | \
+ tar -xz -C /usr/local && \
mkdir /root/gopath && \
mkdir /root/gopath/bin && \
- mkdir /root/gopath/src && \
- rm go.tgz
+ mkdir /root/gopath/src
ENV GOROOT=/usr/local/go GOPATH=/root/gopath
# should not be in the same line with GOROOT definition, otherwise docker build could not find GOROOT.
ENV PATH=${PATH}:${GOROOT}/bin:${GOPATH}/bin
@@ -42,7 +47,8 @@ RUN mkdir /opt/android-ndk-tmp && \
wget -q https://dl.google.com/android/repository/android-ndk-r14b-linux-x86_64.zip && \
unzip -q android-ndk-r14b-linux-x86_64.zip && \
mv android-ndk-r14b ${ANDROID_NDK_HOME} && \
- ${ANDROID_NDK_HOME}/build/tools/make-standalone-toolchain.sh --arch=arm --platform=android-21 --install-dir=${ANDROID_STANDALONE_TOOLCHAIN} && \
+ ${ANDROID_NDK_HOME}/build/tools/make-standalone-toolchain.sh --arch=arm --platform=android-23 --install-dir=${ANDROID_ARM_STANDALONE_TOOLCHAIN} && \
+ ${ANDROID_NDK_HOME}/build/tools/make-standalone-toolchain.sh --arch=arm64 --platform=android-23 --install-dir=${ANDROID_ARM64_STANDALONE_TOOLCHAIN} && \
rm -rf /opt/android-ndk-tmp && \
rm -rf ${ANDROID_NDK_HOME}
diff --git a/cmake/cross_compiling/android.cmake b/cmake/cross_compiling/android.cmake
index 5e3e437a8da9624df35a5c754fe77be73f20361d..84219cfa5587f5b765b2e8f35180797d7053169f 100644
--- a/cmake/cross_compiling/android.cmake
+++ b/cmake/cross_compiling/android.cmake
@@ -20,6 +20,7 @@
# The supported variables are listed belows:
#
# ANDROID_STANDALONE_TOOLCHAIN
+# ANDROID_TOOLCHAIN
# ANDROID_ABI
# ANDROID_NATIVE_API_LEVEL
# ANDROID_ARM_MODE
@@ -57,6 +58,10 @@ IF(NOT DEFINED CMAKE_SYSTEM_VERSION AND ANDROID_NATIVE_API_LEVEL)
ENDIF()
ENDIF()
+IF(NOT DEFINED ANDROID_TOOLCHAIN)
+ SET(ANDROID_TOOLCHAIN clang)
+ENDIF()
+
IF(NOT DEFINED ANDROID_ABI)
SET(ANDROID_ABI "armeabi-v7a")
ENDIF()
@@ -82,6 +87,7 @@ IF("${CMAKE_VERSION}" VERSION_LESS "3.7.0")
"${CMAKE_VERSION}), when cross-compiling for Android.")
IF(ANDROID_STANDALONE_TOOLCHAIN)
+ # Use standalone toolchain
SET(CMAKE_SYSROOT "${ANDROID_STANDALONE_TOOLCHAIN}/sysroot")
IF(NOT CMAKE_SYSTEM_VERSION)
@@ -96,26 +102,44 @@ IF("${CMAKE_VERSION}" VERSION_LESS "3.7.0")
ENDIF()
# Toolchain
- SET(ANDROID_TOOLCHAIN "gcc")
SET(ANDROID_TOOLCHAIN_ROOT ${ANDROID_STANDALONE_TOOLCHAIN})
- IF(ANDROID_ABI MATCHES "^armeabi(-v7a)?$")
- SET(ANDROID_TOOLCHAIN_NAME arm-linux-androideabi)
- IF(ANDROID_ABI STREQUAL "armeabi")
- SET(CMAKE_SYSTEM_PROCESSOR armv5te)
- ELSEIF(ANDROID_ABI STREQUAL "armeabi-v7a")
- SET(CMAKE_SYSTEM_PROCESSOR armv7-a)
- ENDIF()
- ENDIF()
- IF(ANDROID_ABI STREQUAL "arm64-v8a")
- SET(ANDROID_TOOLCHAIN_NAME aarch64-linux-android)
- SET(CMAKE_SYSTEM_PROCESSOR aarch64)
+ ELSE(ANDROID_NDK)
+ # TODO: use android ndk
+ ENDIF()
+
+ IF(ANDROID_ABI MATCHES "^armeabi(-v7a)?$")
+ SET(ANDROID_TOOLCHAIN_NAME arm-linux-androideabi)
+ IF(ANDROID_ABI STREQUAL "armeabi")
+ SET(CMAKE_SYSTEM_PROCESSOR armv5te)
+ SET(ANDROID_CLANG_TRIPLE armv5te-none-linux-androideabi)
+ ELSEIF(ANDROID_ABI STREQUAL "armeabi-v7a")
+ SET(CMAKE_SYSTEM_PROCESSOR armv7-a)
+ SET(ANDROID_CLANG_TRIPLE armv7-none-linux-androideabi)
ENDIF()
- SET(ANDROID_TOOLCHAIN_PREFIX "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_NAME}-")
+ ELSEIF(ANDROID_ABI STREQUAL "arm64-v8a")
+ SET(ANDROID_TOOLCHAIN_NAME aarch64-linux-android)
+ SET(CMAKE_SYSTEM_PROCESSOR aarch64)
+ SET(ANDROID_CLANG_TRIPLE aarch64-none-linux-android)
+ ELSE()
+ MESSAGE(FATAL_ERROR "Invalid Android ABI: ${ANDROID_ABI}.")
+ ENDIF()
+ SET(ANDROID_TOOLCHAIN_PREFIX "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_NAME}-")
+
+ IF(ANDROID_TOOLCHAIN STREQUAL clang)
+ SET(ANDROID_C_COMPILER_NAME clang)
+ SET(ANDROID_CXX_COMPILER_NAME clang++)
+ SET(CMAKE_C_COMPILER_TARGET ${ANDROID_CLANG_TRIPLE})
+ SET(CMAKE_CXX_COMPILER_TARGET ${ANDROID_CLANG_TRIPLE})
+ ELSEIF(ANDROID_TOOLCHAIN STREQUAL gcc)
+ SET(ANDROID_C_COMPILER_NAME gcc)
+ SET(ANDROID_CXX_COMPILER_NAME g++)
+ ELSE()
+ MESSAGE(FATAL_ERROR "Invalid Android toolchain: ${ANDROID_TOOLCHAIN}")
ENDIF()
# C compiler
IF(NOT CMAKE_C_COMPILER)
- SET(ANDROID_C_COMPILER "${ANDROID_TOOLCHAIN_PREFIX}gcc")
+ SET(ANDROID_C_COMPILER "${ANDROID_TOOLCHAIN_PREFIX}${ANDROID_C_COMPILER_NAME}")
ELSE()
GET_FILENAME_COMPONENT(ANDROID_C_COMPILER ${CMAKE_C_COMPILER} PROGRAM)
ENDIF()
@@ -125,7 +149,7 @@ IF("${CMAKE_VERSION}" VERSION_LESS "3.7.0")
# CXX compiler
IF(NOT CMAKE_CXX_COMPILER)
- SET(ANDROID_CXX_COMPILER "${ANDROID_TOOLCHAIN_PREFIX}g++")
+ SET(ANDROID_CXX_COMPILER "${ANDROID_TOOLCHAIN_PREFIX}${ANDROID_CXX_COMPILER_NAME}")
ELSE()
GET_FILENAME_COMPONENT(ANDROID_CXX_COMPILER ${CMAKE_CXX_COMPILER} PROGRAM)
ENDIF()
@@ -137,7 +161,7 @@ IF("${CMAKE_VERSION}" VERSION_LESS "3.7.0")
SET(CMAKE_CXX_COMPILER ${ANDROID_CXX_COMPILER} CACHE PATH "CXX compiler" FORCE)
# Toolchain and ABI specific flags.
- SET(ANDROID_COMPILER_FLAGS "-ffunction-sections -fdata-sections -finline-limit=64")
+ SET(ANDROID_COMPILER_FLAGS "-ffunction-sections -fdata-sections")
SET(ANDROID_LINKER_FLAGS "-Wl,--gc-sections")
IF(ANDROID_ABI STREQUAL "armeabi")
@@ -145,8 +169,7 @@ IF("${CMAKE_VERSION}" VERSION_LESS "3.7.0")
-march=armv5te
-mtune=xscale
-msoft-float)
- ENDIF()
- IF(ANDROID_ABI STREQUAL "armeabi-v7a")
+ ELSEIF(ANDROID_ABI STREQUAL "armeabi-v7a")
LIST(APPEND ANDROID_COMPILER_FLAGS
-march=armv7-a
-mfloat-abi=softfp)
@@ -156,6 +179,8 @@ IF("${CMAKE_VERSION}" VERSION_LESS "3.7.0")
LIST(APPEND ANDROID_COMPILER_FLAGS -mfpu=vfpv3-d16)
ENDIF()
LIST(APPEND ANDROID_LINKER_FLAGS -Wl,--fix-cortex-a8)
+ ELSEIF(ANDROID_ABI STREQUAL "arm64-v8a")
+ LIST(APPEND ANDROID_COMPILER_FLAGS -march=armv8-a)
ENDIF()
IF(ANDROID_ABI MATCHES "^armeabi(-v7a)?$")
@@ -164,10 +189,18 @@ IF("${CMAKE_VERSION}" VERSION_LESS "3.7.0")
ELSE()
LIST(APPEND ANDROID_COMPILER_FLAGS -mthumb)
ENDIF()
+ IF(ANDROID_TOOLCHAIN STREQUAL clang)
+ # Disable integrated-as for better compatibility.
+ LIST(APPEND ANDROID_COMPILER_FLAGS -fno-integrated-as)
+ ENDIF()
ENDIF()
- IF(ANDROID_ABI STREQUAL "arm64-v8a")
- LIST(APPEND ANDROID_COMPILER_FLAGS -march=armv8-a)
+ IF(ANDROID_TOOLCHAIN STREQUAL clang)
+ # CMake automatically forwards all compiler flags to the linker,
+ # and clang doesn't like having -Wa flags being used for linking.
+ # To prevent CMake from doing this would require meddling with
+ # the CMAKE__COMPILE_OBJECT rules, which would get quite messy.
+ LIST(APPEND ANDROID_LINKER_FLAGS -Qunused-arguments)
ENDIF()
STRING(REPLACE ";" " " ANDROID_COMPILER_FLAGS "${ANDROID_COMPILER_FLAGS}")
diff --git a/cmake/external/openblas.cmake b/cmake/external/openblas.cmake
index 0002a470d90f722e3f9106ca56d70e6bf2cea339..f9e05af59fed7a8ad049390eda2c94d8577db1e7 100644
--- a/cmake/external/openblas.cmake
+++ b/cmake/external/openblas.cmake
@@ -12,6 +12,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+IF(USE_EIGEN_FOR_BLAS)
+ return()
+ENDIF(USE_EIGEN_FOR_BLAS)
+
INCLUDE(cblas)
IF(NOT ${CBLAS_FOUND})
diff --git a/doc/design/functions_operators_layers.md b/doc/design/functions_operators_layers.md
index 7a2e8fd0ace2e3f4462b15215de22c31e944b7cb..d23ba56b5773a36d448a99e4abdebc1475ed789c 100644
--- a/doc/design/functions_operators_layers.md
+++ b/doc/design/functions_operators_layers.md
@@ -86,12 +86,13 @@ def layer.fc(X):
We'd like to have Python bindings to operators in package `paddle.operator`, and Python compositions of operators in package `paddle.layer`. So we have the following concepts in above illustrative example:
-```
+
| C++ functions/functors | mul | add | | |
+|------------------------|--------------|--------------|-------------|----------|
| C++ operator class | mulOp | addOp | FCOp | |
| Python binding | operator.mul | operator.add | operator.fc | |
| Python function | | | | layer.fc |
-```
+
This is how we differentiate layer and operators in PaddlePaddle:
diff --git a/doc/design/graph.md b/doc/design/graph.md
index 87f696f90f164a639ad5182823ddfb14aab7e065..51b7f87638f8ddff752328a562fe0dd0fe56cfd1 100644
--- a/doc/design/graph.md
+++ b/doc/design/graph.md
@@ -1,4 +1,4 @@
-# Design Doc: Computations as Graphs
+# Design Doc: Computations as a Graph
A primary goal of the refactorization of PaddlePaddle is a more flexible representation of deep learning computation, in particular, a graph of operators and variables, instead of sequences of layers as before.
@@ -8,6 +8,8 @@ This document explains that the construction of a graph as three steps:
- construct the backward part
- construct the optimization part
+## The Construction of a Graph
+
Let us take the problem of image classification as a simple example. The application program that trains the model looks like:
```python
@@ -25,7 +27,9 @@ The first four lines of above program build the forward part of the graph.
![](images/graph_construction_example_forward_only.png)
-In particular, the first line `x = layer.data("images")` creates variable x and a Feed operator that copies a column from the minibatch to x. `y = layer.fc(x)` creates not only the FC operator and output variable y, but also two parameters, W and b.
+In particular, the first line `x = layer.data("images")` creates variable x and a Feed operator that copies a column from the minibatch to x. `y = layer.fc(x)` creates not only the FC operator and output variable y, but also two parameters, W and b, and the initialization operators.
+
+Initialization operators are kind of "run-once" operators -- the `Run` method increments a class data member counter so to run at most once. By doing so, a parameter wouldn't be initialized repeatedly, say, in every minibatch.
In this example, all operators are created as `OpDesc` protobuf messages, and all variables are `VarDesc`. These protobuf messages are saved in a `BlockDesc` protobuf message.
@@ -49,3 +53,18 @@ According to the chain rule of gradient computation, `ConstructBackwardGraph` wo
For each parameter, like W and b created by `layer.fc`, marked as double circles in above graphs, `ConstructOptimizationGraph` creates an optimization operator to apply its gradient. Here results in the complete graph:
![](images/graph_construction_example_all.png)
+
+## Block and Graph
+
+The word block and graph are interchangable in the desgin of PaddlePaddle. A [Block[(https://github.com/PaddlePaddle/Paddle/pull/3708) is a metaphore of the code and local variables in a pair of curly braces in programming languages, where operators are like statements or instructions. A graph of operators and variables is a representation of the block.
+
+A Block keeps operators in an array `BlockDesc::ops`
+
+```protobuf
+message BlockDesc {
+ repeated OpDesc ops = 1;
+ repeated VarDesc vars = 2;
+}
+```
+
+in the order that there appear in user programs, like the Python program at the beginning of this article. We can imagine that in `ops`, we have some forward operators, followed by some gradient operators, and then some optimization operators.
diff --git a/doc/design/images/graph_construction_example.dot b/doc/design/images/graph_construction_example.dot
index bedb6de0111a8ccab4030d034d65cf72705fc25a..8d1b673abf6b78c851676fa379dc850c4818f0e5 100644
--- a/doc/design/images/graph_construction_example.dot
+++ b/doc/design/images/graph_construction_example.dot
@@ -2,6 +2,8 @@ digraph ImageClassificationGraph {
///////// The forward part /////////
FeedX [label="Feed", color=blue, shape=box];
FeedY [label="Feed", color=blue, shape=box];
+ InitW [label="Init", color=blue, shape=diamond];
+ Initb [label="Init", color=blue, shape=diamond];
FC [label="FC", color=blue, shape=box];
MSE [label="MSE", color=blue, shape=box];
@@ -14,6 +16,8 @@ digraph ImageClassificationGraph {
FeedX -> x -> FC -> y -> MSE -> cost [color=blue];
FeedY -> l [color=blue];
+ InitW -> W [color=blue];
+ Initb -> b [color=blue];
W -> FC [color=blue];
b -> FC [color=blue];
l -> MSE [color=blue];
diff --git a/doc/design/images/graph_construction_example_all.png b/doc/design/images/graph_construction_example_all.png
index 18d8330b60e12720bb993c8cf588d64ff8db1ea9..181187503472d15779b87284105841168b3945c4 100644
Binary files a/doc/design/images/graph_construction_example_all.png and b/doc/design/images/graph_construction_example_all.png differ
diff --git a/doc/design/images/graph_construction_example_forward_backward.png b/doc/design/images/graph_construction_example_forward_backward.png
index 61c3a02a04bc8891ab5b921a889829bcce386df8..3049a9315fd616464dec54e33064cb75598ca536 100644
Binary files a/doc/design/images/graph_construction_example_forward_backward.png and b/doc/design/images/graph_construction_example_forward_backward.png differ
diff --git a/doc/design/images/graph_construction_example_forward_only.png b/doc/design/images/graph_construction_example_forward_only.png
index 14805df11fc09f64d6bc17f5e969f1400d615148..25d19088cbf0b5f68cf734f2ff21eba8af4a2860 100644
Binary files a/doc/design/images/graph_construction_example_forward_only.png and b/doc/design/images/graph_construction_example_forward_only.png differ
diff --git a/doc/design/ops/dist_train.md b/doc/design/ops/dist_train.md
new file mode 100644
index 0000000000000000000000000000000000000000..fa3c5d7990213cf2b0d236e66e592dd2699da876
--- /dev/null
+++ b/doc/design/ops/dist_train.md
@@ -0,0 +1,106 @@
+# Design Doc: Operation Graph Based Parameter Server
+
+## Abstract
+
+We propose an approach to implement the parameter server. In this
+approach, there is no fundamental difference between the trainer and
+the parameter server: they both run subgraphs, but subgraphs of
+different purposes.
+
+## Background
+
+The previous implementations of the parameter server does not run a
+subgraph. parameter initialization, optimizer computation, network
+communication and checkpointing are implemented twice on both the
+trainer and the parameter server.
+
+It would be great if we can write code once and use them on both the
+trainer and the parameter server: reduces code duplication and
+improves extensibility. Given that after the current refactor, we are
+representing everything as a computing graph on the
+trainer. Representing everything as a computing graph on the parameter
+server becomes a natural extension.
+
+## Design
+
+### Graph Converter
+
+The *graph converter* converts the user-defined operation (OP) graph
+into subgraphs to be scheduled on different nodes with the following
+steps:
+
+1. OP placement: the OPs will be placed on different nodes according
+ to heuristic that minimizes estimated total computation
+ time. Currently we will use a simple heuristic that puts parameter
+ varable on parameter server workers and everything else on trainer
+ workers.
+
+1. Add communication OPs to enable the communication between nodes.
+
+We will need these OPs: *Send*, *Recv*, *Enqueue*, *Dequeue*.
+
+Below is an example of converting the user defined graph to the
+subgraphs for the trainer and the parameter server:
+
+
+
+After converting:
+
+
+
+1. The parameter variable W and it's optimizer subgraph are placed on the parameter server.
+1. Operators are added to the subgraphs.
+ - *Send* sends data to the connected *Recv* operator. The
+ scheduler on the receive node will only schedule *Recv* operator
+ to run when the *Send* operator has ran (the *Send* OP will mark
+ the *Recv* OP runnable automatically).
+ - *Enueue* enqueues the input variable, it can block until space
+ become available in the queue.
+ - *Dequeue* outputs configurable numbers of tensors from the
+ queue. It will block until the queue have the required number of
+ tensors.
+
+
+### Benefits
+
+- Model parallelism become easier to implement: it's an extension to
+ the trainer - parameter server approach. we already have the
+ communication OPs, but need to extend the graph converter's
+ placement functionality.
+
+- User-defined optimizer is easier to add - user can now express it as
+ a subgraph.
+
+- No more duplication logic inside the trainer and the parameter
+ server mentioned in the background section.
+
+### Challenges
+
+- It might be hard for the graph converter to cut a general graph
+ (without any hint for which subgraph is the optimizer). We may need
+ to label which subgraph inside the OP graph is the optimizer.
+
+- It's important to balance the parameter shards of on multiple
+ parameter server. If a single parameter is very big (some
+ word-embedding, fully connected, softmax layer), we need to
+ automatically partition the single parameter onto different
+ parameter servers when possible (only element-wise optimizer depends
+ on the parameter variable).
+
+### Discussion
+
+- In the "Aync SGD" figure, the "W" variable on the parameter server
+ could be read and wrote concurrently, what is our locking strategy?
+ E.g., each variable have a lock cpp method to be invoked by every
+ OP, or, have a lock OP.
+
+- Can the Enqueue OP be implemented under our current tensor design
+ (puts the input tensor into the queue tensor)?
+
+- *Dequeue* OP will have variable numbers of output (depends on the
+ `min_count` attribute), does our current design support it? (similar
+ question for the *Add* OP)
+
+
+### References:
+[1] [TensorFlow: Large-Scale Machine Learning on Heterogeneous Distributed Systems](https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/45166.pdf)
diff --git a/doc/design/ops/src/dist-graph.graffle b/doc/design/ops/src/dist-graph.graffle
new file mode 100644
index 0000000000000000000000000000000000000000..941399c6ced8d5f65b6c595522b770c88259df4b
Binary files /dev/null and b/doc/design/ops/src/dist-graph.graffle differ
diff --git a/doc/design/ops/src/dist-graph.png b/doc/design/ops/src/dist-graph.png
new file mode 100644
index 0000000000000000000000000000000000000000..3546b09f1c2ee3e4f60f519d5e47f823f08051a7
Binary files /dev/null and b/doc/design/ops/src/dist-graph.png differ
diff --git a/doc/design/ops/src/local-graph.graffle b/doc/design/ops/src/local-graph.graffle
new file mode 100644
index 0000000000000000000000000000000000000000..19e509bd9af3c1e9a3f5e0f16ddd281457a339c5
Binary files /dev/null and b/doc/design/ops/src/local-graph.graffle differ
diff --git a/doc/design/ops/src/local-graph.png b/doc/design/ops/src/local-graph.png
new file mode 100644
index 0000000000000000000000000000000000000000..ada51200f793a9bb18911e7d63cfdb3244b967d7
Binary files /dev/null and b/doc/design/ops/src/local-graph.png differ
diff --git a/doc/design/simple_op_design.md b/doc/design/simple_op_design.md
index 5e07c29c56d21728599195d420d3222213d77e7c..fded4a68612396a262121a5a886a8ae573dfa662 100644
--- a/doc/design/simple_op_design.md
+++ b/doc/design/simple_op_design.md
@@ -147,7 +147,7 @@ class CosineOp {
struct CosineOpProtoMaker : public OpProtoMaker {
CosineOpProtoMaker(OpProto* proto) : OpProtoMaker(proto) {
AddInput("input", "input of cosine op");
- AddAttr("scale", "scale of cosine op", float).Default(1.0).LargerThan(0.0);
+ AddAttr("scale", "scale of cosine op", float).Default(1.0).GreaterThan(0.0);
AddType("cos");
AddComment("This is cos op");
}
diff --git a/doc/design/var_desc.md b/doc/design/var_desc.md
new file mode 100644
index 0000000000000000000000000000000000000000..86a95c10d5729704f86c285c9fe92db0cf2158be
--- /dev/null
+++ b/doc/design/var_desc.md
@@ -0,0 +1,124 @@
+## Background
+PaddlePaddle divides the description of neural network computation graph into two stages: compile time and runtime.
+
+PaddlePaddle use proto message to describe compile time graph for
+
+1. Computation graph should be able to be saved to a file.
+1. In distributed training, the graph will be serialized and send to multiple workers.
+
+The computation graph is constructed by Data Node and Operation Node. The concept to represent them is in the table below.
+
+| |compile time|runtime|
+|---|---|---|
+|Data|VarDesc(proto)|Variable(cpp)|
+|Operation|OpDesc(proto)|Operator(cpp)|
+
+
+## Definition of VarDesc
+
+A VarDesc should have a name and value, in PaddlePaddle, the value will always be a tensor. Since we use LoDTensor most of the time. We add a LoDTesnorDesc to represent it.
+
+```proto
+message VarDesc {
+ required string name = 1;
+ optional LoDTensorDesc lod_tensor = 2;
+}
+```
+
+## Definition of LodTensorDesc
+
+```proto
+enum DataType {
+ BOOL = 0;
+ INT16 = 1;
+ INT32 = 2;
+ INT64 = 3;
+ FP16 = 4;
+ FP32 = 5;
+ FP64 = 6;
+}
+
+message LoDTensorDesc {
+ required DataType data_type = 1;
+ repeated int32 dims = 2; // [UNK, 640, 480] is saved as [-1, 640, 480]
+ optional int32 lod_level = 3 [default=0];
+}
+```
+
+## Definition of Variable in Python
+
+In Python API, layer will take Variable as Input, and return Variable as Output. There should be a class `Variable` in python to help create and manage Variable.
+
+```python
+image = Variable(dims=[-1, 640, 480])
+# fc1 and fc2 are both Variable
+fc1 = layer.fc(input=image, output_size=10)
+fc2 = layer.fc(input=fc1, output_size=20)
+```
+### what should class `Variable` Have
+1. `name`.a name of string type is used to mark the value of the Variable.
+1. `initializer`. Since our Tensor does not have value. we will always use some Operator to fullfill it when run. So we should have a initialize method to help add the init operator.
+1. `operator`. Variable should record which operator produce itself. The reaon is:
+ - we use pd.eval(targets=[var1, var2]) to run the related ops to get the value of var1 and var2. var.op is used to trace the dependency of the current variable.
+
+In PaddlePaddle, we use Block to describe Computation Graph, so in the code we will use Block but not Graph.
+
+```python
+import VarDesc
+import LoDTensorDesc
+import framework
+
+def AddInitialOperator(variable, initializer):
+ # add an initialize Operator to block to init this Variable
+
+class Variable(object):
+ def __init__(self, name, dims, type, initializer):
+ self._block = get_default_block()
+ self._name = name
+ self.op = None
+
+ tensor_desc = LoDTensorDesc(data_type=type, dims=dims)
+ _var_desc = VarDesc(name=name, lod_tensor=tensor_desc)
+ self._var = framework.CreateVar(_var_desc)
+ self._block.add_var(self)
+
+ # add initial op according to initializer
+ if initializer is not None:
+ AddInitialOperator(self, initializer)
+
+ def dims(self):
+ return self._var.dims()
+
+ def data_type(self):
+ return self._var.data_type()
+
+ def to_proto(self):
+ pass
+```
+
+Then we can use this Variable to create a fc layer in Python.
+
+```python
+import paddle as pd
+
+def flatten_size(X, num_flatten_dims):
+ prod = 1 # of last num_flatten_dims
+ for i in xrange(num_flatten_dims):
+ prod = prod * X.dims[-i-1]
+ return prod
+
+def layer.fc(X, output_size, num_flatten_dims):
+ W = Variable(pd.random_uniform(), type=FP32, dims=[flatten_size(X, num_flatten_dims), output_size])
+ b = Variable(pd.random_uniform(), type=FP32, dims=[output_size])
+ out = Variable(type=FP32)
+ y = operator.fc(X, W, b, output=out) # fc will put fc op input into out
+ pd.InferShape(y)
+ return out
+
+x = Variable(dims=[-1, 640, 480])
+y = layer.fc(x, output_size=100)
+z = layer.fc(y, output_size=200)
+
+paddle.eval(targets=[z], ...)
+print(z)
+```
diff --git a/doc/howto/dev/new_op_cn.md b/doc/howto/dev/new_op_cn.md
index e3bee32f8eeac0b2db9e15430fd7c950c6fc777a..e3892849abe21fc207d2fcbe4adc65184ba771f4 100644
--- a/doc/howto/dev/new_op_cn.md
+++ b/doc/howto/dev/new_op_cn.md
@@ -23,17 +23,20 @@
- `framework::OperatorWithKernel`:继承自OperatorBase,Op有计算函数,称作有Kernel。
- `class OpProtoAndCheckerMaker`:描述该Op的输入、输出、属性、注释,主要用于Python API接口生成
-依据是否包含kernel,将Op分为两种:包含Kernel的Op和不包含kernel的Op,前者Op的定义继承自`OperatorBase`,后者继承自`OperatorWithKernel`。本教程主要介绍带Kernel的Op如何写,简单总结Op需要包含的内容如下:
+依据是否包含kernel,可以将Op分为两种:包含Kernel的Op和不包含kernel的Op,前者Op的定义继承自`OperatorBase`,后者继承自`OperatorWithKernel`。本教程主要介绍带Kernel的Op如何写,简单总结Op需要包含的内容如下:
-
- 内容 | 定义位置
--------------- | :----------------------
+
+ 内容 | 定义位置
+-------------- | :----------------------
OpProtoMake定义 | `.cc`文件,Backward Op不需要定义OpProtoMake
-Op定义 | `.cc`文件
-Kernel实现 | CPU、GPU共享Kernel在`.h`文件,否则,CPU可以在`.cc`文件,GPU可在`.cu`文件。
-注册Op | Op注册在`.cc`文件;Kernel注册CPU在`.cc`文件,GPU在`.cu`文件
-
-
+Op定义 | `.cc`文件
+Kernel实现 | CPU、GPU共享Kernel实现在`.h`文件中,否则,CPU 实现在`.cc`文件中,GPU 实现在`.cu`文件中。
+注册Op | Op注册实现在`.cc`文件;Kernel注册CPU实现在`.cc`文件中,GPU实现在`.cu`文件中
+
+
+实现新的op都添加至目录[paddle/operators](https://github.com/PaddlePaddle/Paddle/tree/develop/paddle/operators)下,文件命名以`*_op.h`(如有) 、 `*_op.cc` 、`*_op.cu`(如有)结尾。
+
+
下面以矩阵乘操作,即[MulOp](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/operators/mul_op.cc)为例来介绍如何写带Kernel的Operator。
@@ -42,9 +45,11 @@ Kernel实现 | CPU、GPU共享Kernel在`.h`文件,否则,CPU可以在`
### 1. 定义ProtoMaker类
-矩阵乘的公式:$Out = X * Y$, 可见该计算由两个输入,一个输出组成。首先定义`ProtoMaker`来描述该Op的输入、输出及注释:
-
-```
+矩阵乘法的公式:$Out = X * Y$, 可见该计算由两个输入,一个输出组成。
+
+首先定义`ProtoMaker`来描述该Op的输入、输出,并添加注释:
+
+```cpp
class MulOpMaker : public framework::OpProtoAndCheckerMaker {
public:
MulOpMaker(framework::OpProto *proto, framework::OpAttrChecker *op_checker)
@@ -59,20 +64,20 @@ The equation is: Out = X * Y
}
};
```
-
-[`MulOpMaker`](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/operators/mul_op.cc#L43)继承自`framework::OpProtoAndCheckerMaker`,构造函数包括2个:
+
+[`MulOpMaker`](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/operators/mul_op.cc#L43)继承自`framework::OpProtoAndCheckerMaker`,构造函数含有2个参数:
- `framework::OpProto` : 前者存储Op的输入输出和参数属性,将用于Python API接口的生成。
- `framework::OpAttrChecker` :后者用于检查参数属性的合法性。
-
-构造函数里通过`AddInput`添加输入参数,通过`AddOutput`添加输出参数,通过`AddComment`添加该Op的注释,这些函数会将对应内容添加到`OpProto`中。
-在`MulOp`中添加两个输入`X`和`Y`,添加了一个输出`Out`,并解释了各自含义,该命名尽可能的规范。
+构造函数里通过`AddInput`添加输入参数,通过`AddOutput`添加输出参数,通过`AddComment`添加Op的注释。这些函数会将对应内容添加到`OpProto`中。
-
-再举个[`ScaleOp`](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/operators/scale_op.cc#L37)的例子:
-
-```
+上面的代码在`MulOp`中添加两个输入`X`和`Y`,添加了一个输出`Out`,并解释了各自含义,命名请遵守命名规范。
+
+
+再以[`ScaleOp`](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/operators/scale_op.cc#L37)为例:
+
+```cpp
template
class ScaleOpMaker : public framework::OpProtoAndCheckerMaker {
public:
@@ -87,17 +92,19 @@ The equation is: Out = scale*X
}
};
```
-
- 在这个例子里,两处不同:
-
- - `AddInput("X","...").NotInGradient()` : 表示`X`这个输入不参与`ScaleOp`对应的梯度Op计算之中。
- - `AddAttr("scale", "...").SetDefault(1.0);` : 增加`scale`系数,作为参数属性,并且设置默认值为1.0。
-
+
+这个例子有两处不同:
+
+- `AddInput("X","...").NotInGradient()` : 表示`X`这个输入不参与`ScaleOp`对应的梯度Op计算之中,如果Op的某个输入不参与反向梯度的计算,请显示地调用`.NotInGradient()`进行设置。
+
+- `AddAttr("scale", "...").SetDefault(1.0);` : 增加`scale`系数,作为参数属性,并且设置默认值为1.0。
+
### 2. 定义Operator类
+下面的点实现了MulOp的定义:
-```c++
+```cpp
class MulOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
@@ -121,33 +128,46 @@ class MulOp : public framework::OperatorWithKernel {
```
[`MulOp`](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/operators/mul_op.cc#L22)继承自`OperatorWithKernel`。`public`成员:
-
-```c++
+
+```cpp
using framework::OperatorWithKernel::OperatorWithKernel;
```
这句表示使用基类`OperatorWithKernel`的构造函数,也可写成:
-
-```c++
+
+```cpp
MulOp(const std::string &type, const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorWithKernel(type, inputs, outputs, attrs) {}
-```
-
+```
+
还需要重写`InferShape`接口。`InferShape`为const函数,不能修改Op的成员变量,参数为`const framework::InferShapeContext &ctx`,通过该参数可获取到输入输出以及属性。它的功能是:
- 1). 做检查, 尽早报错:检查输入数据维度、类型等是否合法。
- 2). 设置输出Tensor的形状。
-通常`OpProtoMaker`和`Op`类的定义写在`.cc`文件中,和要讲到的注册函数一起放在`.cc`中
+通常`OpProtoMaker`和`Op`类的定义写在`.cc`文件中,和下面将要介绍的注册函数一起放在`.cc`中
### 3. 定义OpKernel类
-```C++
-template
-class MulKernel : public framework::OpKernel {
- public:
+`MulKernel`继承自`framework::OpKernel`,带有下面两个模板参数:
+
+- `typename Place`: 表示设备类型,不同设备(CPU、GPU)共享同一个Kernel时,需加该模板参数,不共享则不加,一个不共享的例子是[`OnehotCrossEntropyOpKernel`](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/operators/cross_entropy_op.h#L43)。
+
+- `typename T` : 表示数据类型,如`float`, `double`等。
+
+需要为`MulKernel`类重写`Compute`接口。
+- `Compute`接受一个输入参数:`const framework::ExecutionContext& context`。
+- 与`InferShapeContext`相比,`ExecutionContext`增加了设备类型,同样可获取到输入输出和属性参数。
+- `Compute`函数里实现`OpKernel`的具体计算逻辑。
+
+下面是 `MulKernel` `Compute`的实现:
+
+ ```cpp
+ template
+ class MulKernel : public framework::OpKernel {
+ public:
void Compute(const framework::ExecutionContext& context) const override {
auto* X = context.Input("X");
auto* Y = context.Input("Y");
@@ -157,141 +177,136 @@ class MulKernel : public framework::OpKernel {
const_cast(context.device_context_);
math::matmul(*X, false, *Y, false, 1, Z, 0, device_context);
}
-};
-```
+ };
+ ```
+
+需要注意:**不同设备(CPU、GPU)共享一个Op定义,是否则共享同一个`OpKernel`,取决于`Compute`调用的函数是否支持不同设备。**
-`MulKernel`继承自`framework::OpKernel`,带有模板参数:
+`MulOp`的CPU、GPU实现共享同一个`Kernel`。`OpKernel`不共享的例子可以参考:[`OnehotCrossEntropyOpKernel`](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/operators/cross_entropy_op.h#L43)。
- - `typename Place`: 表示设备类型,不同设备(CPU、GPU)共享同一个Kernel时,需加该模板参数,不共享则不加,一个不共享的例子是[`OnehotCrossEntropyOpKernel`](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/operators/cross_entropy_op.h#L43)。
-
- - `typename T` : 表示数据类型,如`float`, `double`等。
-
-`MulKernel`需要重写`Compute`接口,该接口参数为`const framework::ExecutionContext& context`, `ExecutionContext`相比`InferShapeContext`增加了设备类型,同样可获取到输入输出和属性参数,`Compute`函数里写具体实现时。
-
-注意,不同设备(CPU、GPU)共享一个Op定义,是否则共享同一个`OpKernel`,取决于`Compute`调用的函数是否支持不同设备。`MulOp`的CPU、GPU实现共享同一个`Kernel`,`OpKernel`不共享的例子可以参考[`OnehotCrossEntropyOpKernel`](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/operators/cross_entropy_op.h#L43)。
+为了使`OpKernel`的计算过程书写更加简单,并且CPU、GPU的代码可以复用,我们通常借助 Eigen unsupported Tensor模块来实现`Compute`接口。关于在PaddlePaddle中如何使用Eigen库,请参考[使用文档](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/howto/dev/use_eigen_cn.md)。
+
+
+到此,前向Op实现完成。接下来,需要在`.cc`文件中注册该op和kernel。
+反向Op类的定义,反向OpKernel的定义与前向Op类似,这里不再赘述。**但需注意反向Op没有`ProtoMaker`**。
-为了使得`OpKernel`的计算过程书写较为简单,CPU、GPU的代码可以复用,我们通常借助Eigen unsupported Tensor模块来实现。关于在paddle中如何使用Eigen库,请参考对应的使用[文档](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/howto/dev/use_eigen_cn.md)
-
-到此前向Op实现完成,需要在`.cc`文件中注册该op和kernel。反向Op类的定义和Kernel定义与前向Op类似,这里不再重复。但注意,反向Op没有`ProtoMaker`。
-
### 4. 注册Operator
-在`.cc`文件中注册前向、反向Op类,注册CPU Kernel。
+- 在`.cc`文件中注册前向、反向Op类,注册CPU Kernel。
-```c++
-namespace ops = paddle::operators;
-REGISTER_OP(mul, ops::MulOp, ops::MulOpMaker, mul_grad, ops::MulOpGrad);
-REGISTER_OP_CPU_KERNEL(mul, ops::MulKernel);
-REGISTER_OP_CPU_KERNEL(mul_grad,
- ops::MulGradKernel);
-```
-
- - `REGISTER_OP` : 注册`ops::MulOp`类,类型名为`mul`,该类的`ProtoMaker`为`ops::MulOpMaker`,注册`ops::MulOpGrad`,类型名为`mul_grad`,
- - `REGISTER_OP_WITHOUT_GRADIENT` : 用于注册没有反向的Op。
- - `REGISTER_OP_CPU_KERNEL` :注册`ops::MulKernel`类,并特化模板参数为`paddle::platform::CPUPlace`和`float`类型,同理,注册`ops::MulKernel`类。
-
-在 `.cu`文件中注册GPU Kernel。请注意,如果GPU Kernel的实现是基于Eigen unsupported模块,那么在 `.cu`的最前面请加上宏定义 `#define EIGEN_USE_GPU`
-
-```c++
-// if use Eigen unsupported module before include head files
-#define EIGEN_USE_GPU
-
-namespace ops = paddle::operators;
-REGISTER_OP_GPU_KERNEL(mul, ops::MulKernel);
-REGISTER_OP_GPU_KERNEL(mul_grad,
- ops::MulGradKernel);
-```
+ ```cpp
+ namespace ops = paddle::operators;
+ REGISTER_OP(mul, ops::MulOp, ops::MulOpMaker, mul_grad, ops::MulOpGrad);
+ REGISTER_OP_CPU_KERNEL(mul, ops::MulKernel);
+ REGISTER_OP_CPU_KERNEL(mul_grad,
+ ops::MulGradKernel);
+ ```
+
+ 在上面的代码中:
+
+ - `REGISTER_OP` : 注册`ops::MulOp`类,类型名为`mul`,该类的`ProtoMaker`为`ops::MulOpMaker`,注册`ops::MulOpGrad`,类型名为`mul_grad`。
+ - `REGISTER_OP_WITHOUT_GRADIENT` : 用于注册没有反向的Op。
+ - `REGISTER_OP_CPU_KERNEL` :注册`ops::MulKernel`类,并特化模板参数为`paddle::platform::CPUPlace`和`float`类型,同理,注册`ops::MulKernel`类。
+
+
+- 在 `.cu`文件中注册GPU Kernel。
+ - 请注意,如果GPU Kernel的实现基于Eigen unsupported模块,那么在 `.cu`的开始请加上宏定义 `#define EIGEN_USE_GPU`,代码示例如下:
+
+ ```cpp
+ // if use Eigen unsupported module before include head files
+ #define EIGEN_USE_GPU
+
+ namespace ops = paddle::operators;
+ REGISTER_OP_GPU_KERNEL(mul, ops::MulKernel);
+ REGISTER_OP_GPU_KERNEL(mul_grad,
+ ops::MulGradKernel);
+ ```
### 5. 编译
-在[paddle/operators/CMakeLists.txt](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/operators/CMakeLists.txt)文件中添加编译。
-
-```
-op_library(mul_op SRCS mul_op.cc mul_op.cu DEPS math_function)
-```
-
-下面命令可以编译:
-
-```
-make mul_op
-```
+- 简单**无特殊依赖**的OP无需修改CMakeList.txt文件。[paddle/operators/CMakeLists.txt](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/operators/CMakeLists.txt) 会自动将 `paddle/operators` 目录下新增的 `*_op.cc` 文件加入编译。
+- 较为复杂、**有额外依赖** 的operator仍需要修改[paddle/operators/CMakeLists.txt](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/operators/CMakeLists.txt)。如,`mul_op` 依赖 `math_function`,需要在`CMakeLists.txt`中添加如下内容:
+
+ ```
+ op_library(mul_op SRCS mul_op.cc mul_op.cu DEPS math_function) +
+ ```
+
+- 运行下面命令可以进行编译:
+
+ ```
+ make mul_op
+ ```
## 绑定Python
-- 绑定Python
-
- 在 [`paddle/pybind/pybind.cc
-`](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/pybind/pybind.cc)文件中添加该类:
+- 绑定Python
+
+ 在 [`paddle/pybind/pybind.cc
+`](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/pybind/pybind.cc) 使用`USE_OP`告知编译器需要链接的Op,具体解释参考[代码注释](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/framework/op_registry.h#L81)。
```
USE_OP(mul);
```
如果只实现了CPU版本,则使用`USE_CPU_ONLY_OP`:
-
+
```
USE_CPU_ONLY_OP(gather);
```
-
+
如果OP不带Kernel,则使用`USE_NO_KENREL_OP`:
-
+
```
USE_NO_KENREL_OP(recurrent);
```
-
- 使用`USE_OP`告知编译器需要链接该Op的目标文件,具体解释参考[代码注释](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/framework/op_registry.h#L81)。
-
-
+
+
- 生成库
- 在 [`paddle/pybind/CMakeLists.txt`](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/pybind/CMakeLists.txt)文件添加类到`DEPS`中,使得该Op可以链接到生成的lib库中。
-
- ```
- if(WITH_PYTHON)
- cc_library(paddle_pybind SHARED
- SRCS pybind.cc
- DEPS pybind python backward
- mul_op
- minus_op)
- endif(WITH_PYTHON)
- ```
+ `paddle/operators` 目录下新增的 `*_op.cc` 文件会被自动添加链接到生成的lib库中。
## 实现单元测试
-单测包括对比前向Op不同设备(CPU、GPU)的实现、对比反向OP不同设备(CPU、GPU)的实现、反向Op的梯度测试。下面介绍介绍[`MulOp`的单测](https://github.com/PaddlePaddle/Paddle/blob/develop/python/paddle/v2/framework/tests/test_mul_op.py)。
+单测包括对比前向Op不同设备(CPU、GPU)的实现、对比反向OP不同设备(CPU、GPU)的实现、反向Op的梯度测试。下面介绍介绍[`MulOp`的单元测试](https://github.com/PaddlePaddle/Paddle/blob/develop/python/paddle/v2/framework/tests/test_mul_op.py)。
-### 前向Operator单测
+### 前向Operator单元测试
-前向Op单测继承自`unittest.TestCase`,并定义元类`__metaclass__ = OpTestMeta`,具体单测流程在`OpTestMeta`里完成。需在`setUp`函数定义输入输出和属性参数,以及Python对比的输出值。
+前向Op单元测试继承自`unittest.TestCase`,并定义元类`__metaclass__ = OpTestMeta`。各项更加具体的单元测试在`OpTestMeta`里完成。测试前向Operator,需要:
-```
-import unittest
-import numpy as np
-from gradient_checker import GradientChecker, create_op
-from op_test_util import OpTestMeta
+1. 在`setUp`函数定义输入、输出,以及相关的属性参数。
+2. 生成随机的输入数据。
+3. 在Python脚本中实现与前向operator相同的计算逻辑,得到输出值,与operator前向计算的输出进行对比。
-class TestMulOp(unittest.TestCase):
- __metaclass__ = OpTestMeta
- def setUp(self):
- self.type = "mul"
- self.inputs = {
- 'X': np.random.random((32, 84)).astype("float32"),
- 'Y': np.random.random((84, 100)).astype("float32")
- }
- self.outputs = {'Out': np.dot(self.inputs['X'], self.inputs['Y'])}
-```
- 首先需要`import`必要的包,下面详细解释其他值:
-
- - `self.type = "mul" ` : 定义类型,和注册的类型一致。
- - `self.inputs` : 定义输入,类型为Numpy.array,并初始化。
- - `self.outputs` : 定义输出,并得到Python结算结果。
+ ```python
+ import unittest
+ import numpy as np
+ from gradient_checker import GradientChecker, create_op
+ from op_test_util import OpTestMeta
-
-### 反向Operator单测
+ class TestMulOp(unittest.TestCase):
+ __metaclass__ = OpTestMeta
-反向Op单测继承自`GradientChecker`,而`GradientChecker`集成自`unittest.TestCase`,所以反向单测函数需要`test_`开头。
+ def setUp(self):
+ self.type = "mul"
+ self.inputs = {
+ 'X': np.random.random((32, 84)).astype("float32"),
+ 'Y': np.random.random((84, 100)).astype("float32")
+ }
+ self.outputs = {'Out': np.dot(self.inputs['X'], self.inputs['Y'])}
+ ```
-```
+上面的代码首先导入依赖的包,下面是对`setUp`函数中操作的重要变量的详细解释:
+
+- `self.type = "mul" ` : 定义类型,与operator注册时注册的类型一致。
+- `self.inputs` : 定义输入,类型为`numpy.array`,并初始化。
+- `self.outputs` : 定义输出,并在Python脚本中完成与operator同样的计算逻辑,返回Python端的计算结果。
+
+
+### 反向Operator单元测试
+
+反向Op单元测试继承自`GradientChecker`,而`GradientChecker`继承自`unittest.TestCase`,因此,**反向单元测试函数需要以`test_`开头**。
+
+```python
class TestMulGradOp(GradientChecker):
def setUp(self):
self.op = create_op("mul")
@@ -325,33 +340,30 @@ class TestMulGradOp(GradientChecker):
no_grad_set={"Y"})
```
-下面解释一些关键的地方:
+下面解释代码中一些关键的地方:
- - 调用`create_op("mul")`创建反向Op对应的前向Op。
- - 调用`compare_grad`函数对比CPU、GPU计算结果。
- - `test_normal`中调用`check_grad`检查梯度稳定性,这里采用数值法检测梯度正确性。
- - 第一个参数`self.op` : 前向Op。
- - 第二个参数`self.inputs` : 输入词典,词典的Key和`ProtoMaker`定义保持一致。
- - 第三个参数`["X", "Y"]` : 指定对输入变量`X`、`Y`做梯度检测。
- - 第四个参数`"Out"` : 指定前向网络最终的输出目标变量`Out`
- - `test_ignore_x`和`test_ignore_y`分支测试只需要计算一个输入梯度的情况。
+- 调用`create_op("mul")`创建反向Op对应的前向Op。
+- 调用`compare_grad`函数对比CPU、GPU计算结果。
+- `test_normal`中调用`check_grad`使用数值法检测梯度正确性和稳定性。
+ - 第一个参数`self.op` : 前向Op。
+ - 第二个参数`self.inputs` : 输入词典,词典的Key和`ProtoMaker`定义保持一致。
+ - 第三个参数`["X", "Y"]` : 指定对输入变量`X`、`Y`做梯度检测。
+ - 第四个参数`"Out"` : 指定前向网络最终的输出目标变量`Out`
+- `test_ignore_x`和`test_ignore_y`分支用来测试只需要计算一个输入梯度的情况。
-### 编译和执行
+### 编译和执行单元测试
-单测完成之后,在[`python/paddle/v2/framework/tests/CMakeLists.txt`](https://github.com/PaddlePaddle/Paddle/blob/develop/python/paddle/v2/framework/tests/CMakeLists.txt)里添加编译:
+`python/paddle/v2/framework/tests` 目录下新增的 `test_*.py` 单元测试会被自动加入工程进行编译。
-```
-py_test(test_mul_op SRCS test_mul_op.py)
-```
+请注意,**不同于Op的编译测试,运行单元测试测时需要编译整个工程**,并且编译时需要打开`WITH_TESTING`, 即`cmake paddle_dir -DWITH_TESTING=ON`。编译成功后,执行下面的命令来运行单元测试:
-编译时需要打开`WITH_TESTING`, 即 `cmake paddle_dir -DWITH_TESTING=ON`,编译成功之后执行单测命令为:
-
-```
+```bash
make test ARGS="-R test_mul_op -V"
```
+
或者:
-```
+```bash
ctest -R test_mul_op
```
diff --git a/doc/howto/dev/write_docs_cn.rst b/doc/howto/dev/write_docs_cn.rst
index 36e5d420c986fc8d88eefee4aa221dba0a0480f2..731a63f945c29ba78538b3d71289b234e569354d 100644
--- a/doc/howto/dev/write_docs_cn.rst
+++ b/doc/howto/dev/write_docs_cn.rst
@@ -5,15 +5,13 @@
PaddlePaddle的文档包括英文文档 ``doc`` 和中文文档 ``doc_cn`` 两个部分。文档都是通过 `cmake`_ 驱动 `sphinx`_ 编译生成,生成后的文档分别存储在编译目录的 ``doc`` 和 ``doc_cn`` 两个子目录下。
-如何构建PaddlePaddle的文档
-==========================
+如何构建文档
+============
-PaddlePaddle的文档构建有直接构建和基于Docker构建两种方式,我们提供了一个构建脚本build_docs.sh来进行构建。
-PaddlePaddle文档需要准备的环境相对较复杂,所以我们推荐使用基于Docker来构建PaddlePaddle的文档。
+PaddlePaddle的文档构建有两种方式。
-
-使用Docker构建PaddlePaddle的文档
---------------------------------
+使用Docker构建
+--------------
使用Docker构建PaddlePaddle的文档,需要在系统里先安装好Docker工具包。Docker安装请参考 `Docker的官网 `_ 。安装好Docker之后可以使用源码目录下的脚本构建文档,即
@@ -21,58 +19,46 @@ PaddlePaddle文档需要准备的环境相对较复杂,所以我们推荐使
cd TO_YOUR_PADDLE_CLONE_PATH
cd paddle/scripts/tools/build_docs
- bash build_docs.sh with_docker
-
-编译完成后,会在当前目录生成两个子目录\:
-
-* doc 英文文档目录
-* doc_cn 中文文档目录
+ sh build_docs.sh
+编译完成之后,会在当前目录生成两个子目录\: doc(英文文档目录)和 doc_cn(中文文档目录)。
打开浏览器访问对应目录下的index.html即可访问本地文档。
-
-
-直接构建PaddlePaddle的文档
---------------------------
-
-因为PaddlePaddle的v2 api文档生成过程依赖于py_paddle Python包,用户需要首先确认py_paddle包已经安装。
-
-.. code-block:: bash
-
- python -c "import py_paddle"
-
-如果提示错误,那么用户需要在本地编译安装PaddlePaddle,请参考 `源码编译文档 `_ 。
-注意,用户在首次编译安装PaddlePaddle时,请将WITH_DOC选项关闭。在编译安装正确之后,请再次确认py_paddle包已经安装,即可进行下一步操作。
+直接构建
+--------
如果提示正确,可以执行以下命令编译生成文档,即
.. code-block:: bash
cd TO_YOUR_PADDLE_CLONE_PATH
- cd paddle/scripts/tools/build_docs
- bash build_docs.sh local
-
-编译完成之后,会在当前目录生成两个子目录\:
-
-* doc 英文文档目录
-* doc_cn 中文文档目录
+ mkdir -p build
+ cd build
+ cmake .. -DCMAKE_BUILD_TYPE=Debug -DWITH_GPU=OFF -DWITH_MKLDNN=OFF -DWITH_MKLML=OFF -DWITH_DOC=ON
+ make gen_proto_py
+ make paddle_docs paddle_docs_cn
+编译完成之后,会在当前目录生成两个子目录\: doc(英文文档目录)和 doc_cn(中文文档目录)。
打开浏览器访问对应目录下的index.html即可访问本地文档。
-如何书写PaddlePaddle的文档
-==========================
+如何书写文档
+============
PaddlePaddle文档使用 `sphinx`_ 自动生成,用户可以参考sphinx教程进行书写。
-如何更新www.paddlepaddle.org文档
-================================
+如何更新文档主题
+================
+
+PaddlePaddle文档主题在 `TO_YOUR_PADDLE_CLONE_PATH/doc_theme` 文件夹下,包含所有和前端网页设计相关的文件。
-开发者给PaddlePaddle代码增加的注释以PR的形式提交到github中,提交方式可参见 `贡献文档 `_ 。
+如何更新doc.paddlepaddle.org
+============================
+
+更新的文档以PR的形式提交到github中,提交方式参见 `贡献文档 `_ 。
目前PaddlePaddle的develop分支的文档是自动触发更新的,用户可以分别查看最新的 `中文文档 `_ 和
`英文文档 `_ 。
-
.. _cmake: https://cmake.org/
.. _sphinx: http://www.sphinx-doc.org/en/1.4.8/
diff --git a/paddle/cuda/include/hl_cpu_gru.cuh b/paddle/cuda/include/hl_cpu_gru.cuh
index c0a37ced2a72a1ab410025e2aa45313c23f1349a..e4f6bf42c61694e9826a127c9628730cfd43ada7 100644
--- a/paddle/cuda/include/hl_cpu_gru.cuh
+++ b/paddle/cuda/include/hl_cpu_gru.cuh
@@ -18,14 +18,6 @@ limitations under the License. */
#ifndef __NVCC__
-#include "paddle/math/MathFunctions.h"
-
-#ifndef PADDLE_TYPE_DOUBLE
-#define CBLAS_GEMM paddle::gemm
-#else
-#define CBLAS_GEMM paddle::gemm
-#endif
-
template
void hl_naive_gru_forward_reset_output(OpResetOutput opResetOutput,
real *gateValue,
@@ -210,51 +202,6 @@ inline void forward_final_output(OpFinalOutput opFinalOutput,
}
}
-template
-void hl_cpu_gru_forward(OpResetOutput opResetOutput,
- OpFinalOutput opFinalOutput,
- hl_gru_value value,
- int frameSize,
- int batchSize,
- hl_activation_mode_t active_node,
- hl_activation_mode_t active_gate) {
- if (value.prevOutValue) {
- CBLAS_GEMM(CblasNoTrans,
- CblasNoTrans,
- batchSize,
- 2 * frameSize,
- frameSize,
- 1,
- value.prevOutValue,
- frameSize,
- value.gateWeight,
- frameSize * 2,
- 1,
- value.gateValue,
- frameSize * 3);
- }
-
- forward_reset_output(opResetOutput, value, frameSize, batchSize, active_gate);
-
- if (value.prevOutValue) {
- CBLAS_GEMM(CblasNoTrans,
- CblasNoTrans,
- batchSize,
- frameSize,
- frameSize,
- 1,
- value.resetOutputValue,
- frameSize,
- value.stateWeight,
- frameSize,
- 1,
- value.gateValue + frameSize * 2,
- frameSize * 3);
- }
-
- forward_final_output(opFinalOutput, value, frameSize, batchSize, active_node);
-}
-
template
void hl_naive_gru_backward_state_grad(OpStateGrad opStateGrad,
real *gateValue,
@@ -525,86 +472,6 @@ inline void backward_reset_grad(OpResetGrad opResetGrad,
}
}
-template
-void hl_cpu_gru_backward(OpStateGrad opStateGrad,
- OpResetGrad opResetGrad,
- hl_gru_value value,
- hl_gru_grad grad,
- int frameSize,
- int batchSize,
- hl_activation_mode_t active_node,
- hl_activation_mode_t active_gate) {
- backward_state_grad(opStateGrad, value, grad,
- frameSize, batchSize, active_node);
-
- if (value.prevOutValue && grad.prevOutGrad) {
- CBLAS_GEMM(CblasNoTrans,
- CblasTrans,
- batchSize,
- frameSize,
- frameSize,
- 1,
- grad.gateGrad + frameSize * 2,
- frameSize * 3,
- value.stateWeight,
- frameSize,
- 0,
- grad.resetOutputGrad,
- frameSize);
-
- if (grad.stateWeightGrad) {
- CBLAS_GEMM(CblasTrans,
- CblasNoTrans,
- frameSize,
- frameSize,
- batchSize,
- 1,
- value.resetOutputValue,
- frameSize,
- grad.gateGrad + frameSize * 2,
- frameSize * 3,
- 1,
- grad.stateWeightGrad,
- frameSize);
- }
- }
-
- backward_reset_grad(opResetGrad, value, grad,
- frameSize, batchSize, active_gate);
-
- if (grad.prevOutGrad && value.prevOutValue) {
- CBLAS_GEMM(CblasNoTrans,
- CblasTrans,
- batchSize,
- frameSize,
- frameSize * 2,
- 1,
- grad.gateGrad,
- frameSize * 3,
- value.gateWeight,
- frameSize * 2,
- 1,
- grad.prevOutGrad,
- frameSize);
-
- if (grad.gateWeightGrad) {
- CBLAS_GEMM(CblasTrans,
- CblasNoTrans,
- frameSize,
- frameSize * 2,
- batchSize,
- 1,
- value.prevOutValue,
- frameSize,
- grad.gateGrad,
- frameSize * 3,
- 1,
- grad.gateWeightGrad,
- frameSize * 2);
- }
- }
-}
-
#endif
#endif // HL_CPU_GRU_CUH_
diff --git a/paddle/framework/CMakeLists.txt b/paddle/framework/CMakeLists.txt
index c0838d9b759110fd706577386d2c81bda6876223..3371962c635c3731f00a6af2a6e287ece33397cd 100644
--- a/paddle/framework/CMakeLists.txt
+++ b/paddle/framework/CMakeLists.txt
@@ -9,6 +9,7 @@ cc_test(eigen_test SRCS eigen_test.cc DEPS tensor)
cc_library(lod_tensor SRCS lod_tensor.cc DEPS ddim place tensor)
cc_test(lod_tensor_test SRCS lod_tensor_test.cc DEPS lod_tensor)
+nv_test(lod_tensor_gpu_test SRCS lod_tensor_test.cu DEPS lod_tensor)
cc_test(variable_test SRCS variable_test.cc)
diff --git a/paddle/framework/attribute.h b/paddle/framework/attribute.h
index 071879a9d453377ccc2e9e71b62e8568a7ef1c9b..2b788a76cafe198abb9aed8ba842e37cc6ff73a6 100644
--- a/paddle/framework/attribute.h
+++ b/paddle/framework/attribute.h
@@ -41,11 +41,23 @@ Attribute GetAttrValue(const OpDesc::Attr& attr_desc);
// check whether a value(attribute) fit a certain limit
template
-class LargerThanChecker {
+class GreaterThanChecker {
public:
- explicit LargerThanChecker(T lower_bound) : lower_bound_(lower_bound) {}
+ explicit GreaterThanChecker(T lower_bound) : lower_bound_(lower_bound) {}
void operator()(T& value) const {
- PADDLE_ENFORCE(value > lower_bound_, "larger_than check fail");
+ PADDLE_ENFORCE(value > lower_bound_, "larger_than check fails.");
+ }
+
+ private:
+ T lower_bound_;
+};
+
+template
+class EqualGreaterThanChecker {
+ public:
+ explicit EqualGreaterThanChecker(T lower_bound) : lower_bound_(lower_bound) {}
+ void operator()(T& value) const {
+ PADDLE_ENFORCE_GE(value, lower_bound_, "equal_larger_than check fails.");
}
private:
@@ -110,8 +122,13 @@ class TypedAttrChecker {
return *this;
}
- TypedAttrChecker& LargerThan(const T& lower_bound) {
- value_checkers_.push_back(LargerThanChecker(lower_bound));
+ TypedAttrChecker& GreaterThan(const T& lower_bound) {
+ value_checkers_.push_back(GreaterThanChecker(lower_bound));
+ return *this;
+ }
+
+ TypedAttrChecker& EqualGreaterThan(const T& lower_bound) {
+ value_checkers_.push_back(EqualGreaterThanChecker(lower_bound));
return *this;
}
diff --git a/paddle/framework/backward.md b/paddle/framework/backward.md
index 8aa6728a95bc464ab8884986f0cec6c817d3303b..0a6d762bc8be5201ac196b4bc6107c06d07a31d7 100644
--- a/paddle/framework/backward.md
+++ b/paddle/framework/backward.md
@@ -2,20 +2,31 @@
## Motivation
-In Neural Network, the backpropagation algorithm follows the chain rule, so we need to compound the fundmental gradient operators/expressions together with chain rule . Every forward network need a backward network to construct the full computation graph, the operator/expression's backward pass will be generated respect to forward pass.
-
-## Backward Operator Registry
+In Neural Network, many model is solved by the the backpropagation algorithm(known as BP) at present. Technically it caculates the gradient of the loss function, then distributed back through the networks. Follows the chain rule, so we need a module chains the gradient operators/expressions together with to construct the backward pass. Every forward network needs a backward network to construct the full computation graph, the operator/expression's backward pass will be generated respect to forward pass.
-A backward network is built up with several backward operators. Backward operators take forward operators' inputs, outputs and output gradients and then calculate its input gradients.
+## Implementation
+
+In this design doc, we exported only one API for generating the backward pass.
+
+```c++
+std::unique_ptr Backward(const OperatorBase& forwardOp,
+ const std::unordered_set& no_grad_vars);
+```
+
+The implementation behind it can be divided into two parts, **Backward Operator Creating** and **Backward Operator Building**.
+
+### Backward Operator Registry
+
+A backward network is built up with several backward operators. Backward operators take forward operators' inputs, outputs, and output gradients and then calculate its input gradients.
| | forward operator | backward operator
| ---------------------- | ---------------- |------------------------- |
| **Operator::inputs_** | Inputs | Inputs, Outputs, OutputGradients |
| **Operator::outputs_** | Outputs | InputGradients |
- In most cases, there is a one-to-one correspondence between forward and backward operators. These correspondences are recorded by a global hash map(`OpInfoMap`). To follow the philosophy of minimum core and make operators pluggable, the registry mechanism is introduced.
+ In most cases, there is a one-to-one correspondence between the forward and backward operators. These correspondences are recorded by a global hash map(`OpInfoMap`). To follow the philosophy of minimum core and make operators pluggable, the registry mechanism is introduced.
-For example, we have got a `mul_op`, and we can register it's information and corresponding backward operator by the following macro:
+For example, we have got a `mul_op`, and we can register its information and corresponding backward operator by the following macro:
```cpp
REGISTER_OP(mul, MulOp, MulOpMaker, mul_grad, MulOpGrad);
@@ -25,58 +36,65 @@ REGISTER_OP(mul, MulOp, MulOpMaker, mul_grad, MulOpGrad);
`mul_grad` is the type of backward operator, and `MulOpGrad` is its class name.
-## Backward Opeartor Creating
+### Backward Opeartor Creating
-Given a certain forward operator, we can get its corresponding backward opeartor by calling:
+Given a certain forward operator, we can get its corresponding backward operator by calling:
```cpp
OperatorBase* bwd_op = BuildGradOp(const OperatorBase* fwd_op);
-```
+```
The function `BuildGradOp` will sequentially execute following processes:
1. Get the `type_` of given forward operator, and then get the corresponding backward operator's type by looking up the `OpInfoMap`.
-2. Build two maps named `inputs` and `outputs` to temporary storage backward operator's inputs and outputs. Copy forward operator's `inputs_` and `outputs_` to map `inputs`, except these are not necessary for gradient computing.
+2. Build two maps named `inputs` and `outputs` to temporary storage backward operator's inputs and outputs. Copy forward operator's `inputs_` and `outputs_` to map `inputs`, except these, are not necessary for gradient computing.
3. Add forward inputs' gradient variables into map `output`, adding forward outputs' gradient variables into map `input`.
4. Building backward operator with `inputs`, `outputs` and forward operator's attributes.
-## Backward Network Building
+### Backward Network Building
-A backward network is a series of backward operators. The main idea of building a backward network is creating backward operators in the inverted sequence and put them together.
-
-In our design, the network itself is also a kind of operator. So the operators contained by a big network may be some small network.
-
-given a forward network, it generates the backward network. We only care about the Gradients—`OutputGradients`,`InputGradients`.
+A backward network is a series of backward operators. The main idea of building a backward network is creating backward operators in the inverted sequence and append them together one by one. There is some corner case need to process specially.
1. Op
- when the input forward network is a Op, return its gradient Operator Immediately.
+ When the input forward network is an Op, return its gradient Operator Immediately. If all of its outputs are in no gradient set, then return a special `NOP`.
2. NetOp
- when the input forward network is a NetOp, it need to call the sub NetOp/Operators backward function recursively. During the process, we need to collect the `OutputGradients` name according to forward NetOp.
+ In our design, the network itself is also a kind of operator(**NetOp**). So the operators contained by a big network may be some small network. When the input forward network is a NetOp, it needs to call the sub NetOp/Operators backward function recursively. During the process, we need to collect the `OutputGradients` name according to the forward NetOp.
+
+3. RnnOp
+
+ RnnOp is a nested stepnet operator. Backward module need to recusively call `Backward` for every stepnet.
+
+4. Sharing Variables
+
+ **sharing variables**. As illustrated in the pictures, two operator's share the same variable name of W@GRAD, which will overwrite their sharing input variable.
+
+
+
- **shared variable**. As illustrated in the pictures, two operator's `Output` `Gradient` will overwirte their shared input variable.
+ pic 1. Sharing variables in operators.
-
-
+
- 1. shared variable in two operators.
+ Sharing variable between operators or same input variable used in multiple operators leads to a duplicate gradient variable. As demo show above, we need to rename gradient name recursively and add a generic add operator to replace the overwrite links.
-
+
+
- Share variable between operators or same input variable used in multiple operators lead to a duplicate gradient variable. As demo show above, we need to rename gradient name recursively, and add a generic add operator replace the overwirte links.
+ pic 2. Replace sharing variable's gradient with `Add` operator.
-
-
+
- 2. replace shared variable gradient with `Add` Operator
+ Because our framework finds variables accord to their names, we need to rename the output links. We add a suffix of number to represent its position in clockwise.
-
+5. Part of Gradient is Zero.
+ In the whole graph, there is some case of that one operator's gradient is not needed, but its input's gradient is a dependency link of other operator, we need to fill a same shape gradient matrix in the position. In our implement, we insert a special `fillZeroLike` operator.
- Then collect the sub graph `OutputGradients`/`InputGradients` as the NetOp's and return it.
+Follow these rules above, then collect the sub graph `OutputGradients`/`InputGradients` as the NetOp's and return it.
diff --git a/paddle/framework/ddim.cc b/paddle/framework/ddim.cc
index 85b7de79743bb0390d66b8999f2e8342a51d14a9..fc3d508553c0e966978b28d58127bdbff10d45f1 100644
--- a/paddle/framework/ddim.cc
+++ b/paddle/framework/ddim.cc
@@ -283,5 +283,14 @@ std::ostream& operator<<(std::ostream& os, const DDim& ddim) {
DDim::DDim(std::initializer_list init_list) {
*this = make_ddim(init_list);
}
+
+DDim flatten_to_2d(const DDim& src, int num_col_dims) {
+ int rank = src.size();
+ return make_ddim({product(slice_ddim(src, 0, num_col_dims)),
+ product(slice_ddim(src, num_col_dims, rank))});
+}
+
+DDim flatten_to_1d(const DDim& src) { return make_ddim({product(src)}); }
+
} // namespace framework
} // namespace paddle
diff --git a/paddle/framework/ddim.h b/paddle/framework/ddim.h
index db30c523948b1d437615aa0e9bfecb5e25569296..ca29e7e8c7776de6adf3e3b0e8f11f0d4d8487c3 100644
--- a/paddle/framework/ddim.h
+++ b/paddle/framework/ddim.h
@@ -115,6 +115,12 @@ int arity(const DDim& ddim);
std::ostream& operator<<(std::ostream&, const DDim&);
+// Reshape a tensor to a matrix. The matrix's first dimension(column length)
+// will be the product of tensor's first `num_col_dims` dimensions.
+DDim flatten_to_2d(const DDim& src, int num_col_dims);
+
+DDim flatten_to_1d(const DDim& src);
+
} // namespace framework
} // namespace paddle
diff --git a/paddle/framework/eigen.h b/paddle/framework/eigen.h
index 2d8d9ae10c56e0632414a5bbc754d35bfa9ce6a5..54bbeafcabdeeb1e2c1017c156b3512c83dada3a 100644
--- a/paddle/framework/eigen.h
+++ b/paddle/framework/eigen.h
@@ -63,20 +63,35 @@ struct EigenTensor {
template
-struct EigenMatrix : public EigenTensor {};
+struct EigenMatrix : public EigenTensor {
+ static typename EigenMatrix::Type Reshape(Tensor& tensor, int num_col_dims) {
+ int rank = tensor.dims_.size();
+ PADDLE_ENFORCE(num_col_dims > 0 && num_col_dims < rank,
+ "`num_col_dims` must be between (0, rank_of_tensor).");
+ return EigenMatrix::From(tensor,
+ flatten_to_2d(tensor.dims(), num_col_dims));
+ }
+
+ static typename EigenMatrix::ConstType Reshape(const Tensor& tensor,
+ int num_col_dims) {
+ int rank = tensor.dims_.size();
+ PADDLE_ENFORCE(num_col_dims > 0 && num_col_dims < rank,
+ "`num_col_dims` must be between (0, rank_of_tensor).");
+ return EigenMatrix::From(tensor,
+ flatten_to_2d(tensor.dims(), num_col_dims));
+ }
+};
template
struct EigenVector : public EigenTensor {
// Flatten reshapes a Tensor into an EigenVector.
static typename EigenVector::Type Flatten(Tensor& tensor) {
- return EigenVector::From(
- tensor, make_ddim({static_cast(product(tensor.dims_))}));
+ return EigenVector::From(tensor, {product(tensor.dims_)});
}
static typename EigenVector::ConstType Flatten(const Tensor& tensor) {
- return EigenVector::From(
- tensor, make_ddim({static_cast(product(tensor.dims_))}));
+ return EigenVector::From(tensor, {product(tensor.dims_)});
}
};
diff --git a/paddle/framework/eigen_test.cc b/paddle/framework/eigen_test.cc
index dc1957691b1a202826e10e84c21ac8874df9e378..bc4a2db32cfba66bef2c444e1f822e0d2a57b91e 100644
--- a/paddle/framework/eigen_test.cc
+++ b/paddle/framework/eigen_test.cc
@@ -108,5 +108,24 @@ TEST(Eigen, Matrix) {
}
}
+TEST(Eigen, MatrixReshape) {
+ Tensor t;
+ float* p = t.mutable_data({2, 3, 6, 4}, platform::CPUPlace());
+ for (int i = 0; i < 2 * 3 * 6 * 4; ++i) {
+ p[i] = static_cast(i);
+ }
+
+ EigenMatrix::Type em = EigenMatrix::Reshape(t, 2);
+
+ ASSERT_EQ(2 * 3, em.dimension(0));
+ ASSERT_EQ(6 * 4, em.dimension(1));
+
+ for (int i = 0; i < 2 * 3; i++) {
+ for (int j = 0; j < 6 * 4; j++) {
+ ASSERT_NEAR(i * 6 * 4 + j, em(i, j), 1e-6f);
+ }
+ }
+}
+
} // namespace framework
} // namespace paddle
diff --git a/paddle/framework/framework.proto b/paddle/framework/framework.proto
index 368136a9729dd2c745cc71bc391031e0a390fc87..dfcb5fb6210a08f35193b83e3b5f7cee92f618d7 100644
--- a/paddle/framework/framework.proto
+++ b/paddle/framework/framework.proto
@@ -87,3 +87,24 @@ message OpProto {
repeated Attr attrs = 4;
required string comment = 5;
}
+
+enum DataType {
+ BOOL = 0;
+ INT16 = 1;
+ INT32 = 2;
+ INT64 = 3;
+ FP16 = 4;
+ FP32 = 5;
+ FP64 = 6;
+}
+
+message LoDTensorDesc {
+ required DataType data_type = 1;
+ repeated int32 dims = 2; // [UNK, 640, 480] is saved as [-1, 640, 480]
+ optional int32 lod_level = 3 [ default = 0 ];
+}
+
+message VarDesc {
+ required string name = 1;
+ optional LoDTensorDesc lod_tensor = 2;
+}
diff --git a/paddle/framework/grad_op_builder_test.cc b/paddle/framework/grad_op_builder_test.cc
index 902c2655e9182d74a48ad13e17a39a3304d5fa57..9e3ca563c6765637f8471d142d32cec447f0b977 100644
--- a/paddle/framework/grad_op_builder_test.cc
+++ b/paddle/framework/grad_op_builder_test.cc
@@ -3,7 +3,7 @@
#include "paddle/framework/op_registry.h"
#include "paddle/framework/operator.h"
-USE_OP(add_two);
+USE_OP(add);
namespace paddle {
namespace framework {
@@ -41,7 +41,7 @@ namespace f = paddle::framework;
TEST(GradOpBuilder, AddTwo) {
std::shared_ptr add_op(f::OpRegistry::CreateOp(
- "add_two", {{"X", {"x"}}, {"Y", {"y"}}}, {{"Out", {"out"}}}, {}));
+ "add", {{"X", {"x"}}, {"Y", {"y"}}}, {{"Out", {"out"}}}, {}));
std::shared_ptr grad_add_op =
f::OpRegistry::CreateGradOp(*add_op);
EXPECT_EQ(grad_add_op->Inputs().size(), 4UL);
diff --git a/paddle/framework/images/duplicate_op2.graffle b/paddle/framework/images/duplicate_op2.graffle
index 2b658085d6a55d368c320051ba7f94ec2900f13c..5cec3bc64dbd44dc99e348485969f29bd128ceb1 100644
Binary files a/paddle/framework/images/duplicate_op2.graffle and b/paddle/framework/images/duplicate_op2.graffle differ
diff --git a/paddle/framework/images/duplicate_op2.png b/paddle/framework/images/duplicate_op2.png
index c5588015d1450fd8c1bda3580680d884494868bb..21cdd5cabf1b5203e1435a75b57770d2f702fa92 100644
Binary files a/paddle/framework/images/duplicate_op2.png and b/paddle/framework/images/duplicate_op2.png differ
diff --git a/paddle/framework/lod_tensor.cc b/paddle/framework/lod_tensor.cc
index 71eac4a10b34c3010a2758120c25754af58f669d..908a1f2fd0abe0aa4016c72dbcbc18dcc144232c 100644
--- a/paddle/framework/lod_tensor.cc
+++ b/paddle/framework/lod_tensor.cc
@@ -19,8 +19,8 @@
namespace paddle {
namespace framework {
-LOD SliceLevels(const LOD& in, size_t level_begin, size_t level_end) {
- LOD new_lod;
+LoD SliceLevels(const LoD& in, size_t level_begin, size_t level_end) {
+ LoD new_lod;
new_lod.reserve(level_end - level_begin);
for (size_t i = level_begin; i < level_end; i++) {
new_lod.emplace_back(in.at(i));
@@ -28,10 +28,10 @@ LOD SliceLevels(const LOD& in, size_t level_begin, size_t level_end) {
return new_lod;
}
-LOD SliceInLevel(const LOD& in, size_t level, size_t elem_begin,
+LoD SliceInLevel(const LoD& in, size_t level, size_t elem_begin,
size_t elem_end) {
// slice the lod.
- LOD new_lod;
+ LoD new_lod;
new_lod.reserve(in.size() - level);
auto start = in.at(level)[elem_begin];
auto end = in.at(level)[elem_end];
@@ -46,13 +46,13 @@ LOD SliceInLevel(const LOD& in, size_t level, size_t elem_begin,
std::transform(new_lod.back().begin(), new_lod.back().end(),
new_lod.back().begin(),
[start](int v) { return v - start; });
- PADDLE_ENFORCE_EQ(new_lod.back().front(), 0, "error in slice LOD");
+ PADDLE_ENFORCE_EQ(new_lod.back().front(), 0, "error in slice LoD");
}
PADDLE_ENFORCE_LE(new_lod.size(), in.size());
return new_lod;
}
-bool operator==(const LOD& a, const LOD& b) {
+bool operator==(const LoD& a, const LoD& b) {
if (a.size() != b.size()) {
return false;
}
@@ -72,12 +72,12 @@ bool operator==(const LOD& a, const LOD& b) {
return true;
}
-void LODTensor::SliceLevels(size_t level_begin, size_t level_end) {
+void LoDTensor::SliceLevels(size_t level_begin, size_t level_end) {
auto new_lod = framework::SliceLevels(lod_, level_begin, level_end);
lod_ = new_lod;
}
-void LODTensor::SliceInLevel(size_t level, size_t elem_begin, size_t elem_end) {
+void LoDTensor::SliceInLevel(size_t level, size_t elem_begin, size_t elem_end) {
PADDLE_ENFORCE(level < NumLevels(), "level [%d] out of range [%d]", level,
NumLevels());
PADDLE_ENFORCE(elem_begin < NumElements(level),
diff --git a/paddle/framework/lod_tensor.h b/paddle/framework/lod_tensor.h
index 9e6b6b4aca41ed464292b56bf6f2d27514f874f7..568f4e89819c8345d8908634f6fa56f09483a763 100644
--- a/paddle/framework/lod_tensor.h
+++ b/paddle/framework/lod_tensor.h
@@ -18,8 +18,10 @@
#ifndef PADDLE_ONLY_CPU
#include
#include
+#include
#endif
+#include
#include "paddle/framework/ddim.h"
#include "paddle/framework/tensor.h"
#include "paddle/platform/enforce.h"
@@ -32,37 +34,38 @@ template
using Vector = std::vector;
#else
template
-using Vector = thrust::host_vector;
+using Vector = thrust::host_vector<
+ T, thrust::system::cuda::experimental::pinned_allocator>;
#endif
-using LOD = std::vector>;
+using LoD = std::vector>;
-LOD SliceLevels(const LOD& in, size_t level_begin, size_t level_end);
+LoD SliceLevels(const LoD& in, size_t level_begin, size_t level_end);
-LOD SliceInLevel(const LOD& in, size_t level, size_t elem_begin,
+LoD SliceInLevel(const LoD& in, size_t level, size_t elem_begin,
size_t elem_end);
-bool operator==(const LOD& a, const LOD& b);
+bool operator==(const LoD& a, const LoD& b);
/*
- * LODTensor (Level of details Tensor)
+ * LoDTensor (Level of details Tensor)
* see https://en.wikipedia.org/wiki/Level_of_details for reference.
*/
-class LODTensor {
+class LoDTensor {
public:
- LODTensor() {}
- LODTensor(const LOD& lod, Tensor* t) : lod_(lod), tensor_(t) {}
+ LoDTensor() {}
+ LoDTensor(const LoD& lod, Tensor* t) : lod_(lod), tensor_(t) {}
- void set_lod(const LOD& lod) { lod_ = lod; }
+ void set_lod(const LoD& lod) { lod_ = lod; }
void set_tensor(Tensor* tensor) { tensor_ = tensor; }
Tensor& tensor() { return *tensor_; }
- LOD lod() { return lod_; }
+ LoD lod() { return lod_; }
/*
- * Get a element from LOD.
+ * Get a element from LoD.
*/
size_t lod_element(size_t level, size_t elem) const {
PADDLE_ENFORCE(level < NumLevels(), "level [%d] out of range [%d]", level,
@@ -74,7 +77,7 @@ class LODTensor {
}
/*
- * Number of LODTensor's levels, each level has units of data, for example,
+ * Number of LoDTensor's levels, each level has units of data, for example,
* in the sentence's view, article, paragraph, sentence are 3 levels.
*/
size_t NumLevels() const { return lod_.size(); }
@@ -100,7 +103,7 @@ class LODTensor {
void SliceInLevel(size_t level, size_t elem_begin, size_t elem_end);
private:
- LOD lod_;
+ LoD lod_;
Tensor* tensor_; // not owned
};
} // namespace framework
diff --git a/paddle/framework/lod_tensor.md b/paddle/framework/lod_tensor.md
index 8dfe3ee823084cb8c38550a82e761a741eabe135..769b61f175a2f462258c1242d027c04c0abd12a9 100644
--- a/paddle/framework/lod_tensor.md
+++ b/paddle/framework/lod_tensor.md
@@ -94,7 +94,7 @@ Let's go on slicing this slice. Its <1,1>-slice is
|||
```
-### The General Slicing Algorithm
+### The Slicing Algorithm
The algorithm, with over-simplified data structure, is defined as
@@ -106,17 +106,41 @@ struct LoDTensor {
float* tensor_;
};
-LoDTensor Slice(const LoDTensor& lodt, int level, int sequence) {
+LoDTensor Slice(const LoDTensor& lodt, int level, int sequence);
+```
+
+Let us revisit the example above
-}
+```
+ 3
+3 1 2
+3 2 4 1 2 3
+||| || |||| | || |||
```
-### Slicing the Top Level
+Suppose that we want to retrieve the <1,2>-slice
-Please be aware that an RNN operator only slices the top level of a LoD Tensor to get the step inputs.
+```
+2
+2 3
+|| |||
+```
-```c++
-LoDTensor Slice(const LoDTensor& lodt, int sequence) {
+we will need to find out the starting position of this slice by summing over all leaf nodes in `LoD` to the left of the slice, i.e., 3 + 2 + 4 + 1 = 10.
+
+To avoid the traversal of the LoD tree at slcing time, we can do it at the construction time -- instead of saving the lengths of the next level in the LoD tree, we can save the starting offset of the next level. For example, above LoD Tensor can be transformed into
+
+```
+ 0
+0 9 10
+0 3 5 9 10 12
+||| || |||| | || |||
+```
+
+We don't really need the 0 on top, so the LoD Tensor could be
-}
+```
+0 9 10
+0 3 5 9 10 12
+||| || |||| | || |||
```
diff --git a/paddle/framework/lod_tensor_test.cc b/paddle/framework/lod_tensor_test.cc
index 9a351605edb5013bdab2c6193bdd9ce401acc937..1da8553134f377f7a4fbe8008d12fe8d4a0e47f4 100644
--- a/paddle/framework/lod_tensor_test.cc
+++ b/paddle/framework/lod_tensor_test.cc
@@ -21,7 +21,7 @@
namespace paddle {
namespace framework {
-class LODTensorTester : public ::testing::Test {
+class LoDTensorTester : public ::testing::Test {
public:
virtual void SetUp() override {
// tensor's batch_size: 30
@@ -29,7 +29,7 @@ class LODTensorTester : public ::testing::Test {
// 0 10 20
// 0 5 10 15 20
// 0 2 5 7 10 12 15 20
- LOD lod;
+ LoD lod;
lod.push_back(std::vector{0, 10, 20});
lod.push_back(std::vector{0, 5, 10, 15, 20});
lod.push_back(std::vector{0, 2, 5, 7, 10, 12, 15, 17, 20});
@@ -47,21 +47,21 @@ class LODTensorTester : public ::testing::Test {
protected:
platform::CPUPlace place;
Tensor tensor;
- LODTensor lod_tensor;
+ LoDTensor lod_tensor;
};
-TEST_F(LODTensorTester, NumLevels) { ASSERT_EQ(lod_tensor.NumLevels(), 3UL); }
+TEST_F(LoDTensorTester, NumLevels) { ASSERT_EQ(lod_tensor.NumLevels(), 3UL); }
-TEST_F(LODTensorTester, NumElements) {
+TEST_F(LoDTensorTester, NumElements) {
ASSERT_EQ(lod_tensor.NumElements(0), 2UL);
ASSERT_EQ(lod_tensor.NumElements(1), 4UL);
ASSERT_EQ(lod_tensor.NumElements(2), 8UL);
}
-TEST_F(LODTensorTester, SliceLevels) {
+TEST_F(LoDTensorTester, SliceLevels) {
// slice 1 level
for (size_t level = 0; level < 3UL; ++level) {
- LODTensor new_lod_tensor = lod_tensor;
+ LoDTensor new_lod_tensor = lod_tensor;
new_lod_tensor.SliceLevels(level, level + 1);
ASSERT_EQ(new_lod_tensor.NumLevels(), 1UL);
ASSERT_EQ(new_lod_tensor.NumElements(0), lod_tensor.NumElements(level));
@@ -70,7 +70,7 @@ TEST_F(LODTensorTester, SliceLevels) {
}
// slice 2 level
for (size_t level = 0; level < 2UL; ++level) {
- LODTensor new_lod_tensor = lod_tensor;
+ LoDTensor new_lod_tensor = lod_tensor;
new_lod_tensor.SliceLevels(level, level + 2);
ASSERT_EQ(new_lod_tensor.NumLevels(), 2UL);
ASSERT_EQ(new_lod_tensor.NumElements(0), lod_tensor.NumElements(level));
@@ -80,9 +80,9 @@ TEST_F(LODTensorTester, SliceLevels) {
}
}
-TEST_F(LODTensorTester, SliceInLevel) {
+TEST_F(LoDTensorTester, SliceInLevel) {
size_t level = 0;
- LODTensor new_lod_tensor = lod_tensor;
+ LoDTensor new_lod_tensor = lod_tensor;
new_lod_tensor.SliceInLevel(level, 0, 2);
EXPECT_EQ(new_lod_tensor.NumLevels(), 3UL);
EXPECT_EQ(new_lod_tensor.NumElements(0), 2UL);
diff --git a/paddle/framework/lod_tensor_test.cu b/paddle/framework/lod_tensor_test.cu
new file mode 100644
index 0000000000000000000000000000000000000000..1079a36a2e7b24f6f8a5bcbb296355567305a765
--- /dev/null
+++ b/paddle/framework/lod_tensor_test.cu
@@ -0,0 +1,52 @@
+/*
+ Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+ http://www.apache.org/licenses/LICENSE-2.0
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include
+#include
+#include "paddle/framework/lod_tensor.h"
+#include "paddle/platform/assert.h"
+
+#include
+
+__global__ void test(size_t* a, int size) {
+ for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < size;
+ i += blockDim.x * gridDim.x) {
+ a[i] *= 2;
+ }
+}
+
+TEST(LoDTensor, LoDInGPU) {
+ paddle::framework::Tensor tensor;
+ paddle::framework::LoDTensor lod_tensor;
+ paddle::platform::GPUPlace place(0);
+
+ paddle::framework::LoD src_lod;
+ src_lod.push_back(std::vector{0, 2, 4, 6, 8, 10, 12, 14});
+
+ tensor.Resize({14, 16});
+ tensor.mutable_data(place);
+
+ lod_tensor.set_lod(src_lod);
+ lod_tensor.set_tensor(&tensor);
+ CHECK_EQ(lod_tensor.lod_element(0, 2), 4);
+ CHECK_EQ(lod_tensor.lod_element(0, 4), 8);
+
+ auto lod = lod_tensor.lod();
+
+ test<<<1, 8>>>(lod[0].data(), lod[0].size());
+ cudaDeviceSynchronize();
+
+ for (size_t i = 0; i < src_lod[0].size(); ++i) {
+ CHECK_EQ(lod[0].data()[i], src_lod[0].data()[i] * 2);
+ }
+}
diff --git a/paddle/framework/op_registry_test.cc b/paddle/framework/op_registry_test.cc
index b43f6a8cc56fdd2dc483bef303cf1213b171a5e4..e00c6e8d904508ec9985537fc703c7c61a14e0de 100644
--- a/paddle/framework/op_registry_test.cc
+++ b/paddle/framework/op_registry_test.cc
@@ -21,7 +21,7 @@ class CosineOpProtoAndCheckerMaker : public OpProtoAndCheckerMaker {
AddOutput("output", "output of cosine op");
AddAttr("scale", "scale of cosine op")
.SetDefault(1.0)
- .LargerThan(0.0);
+ .GreaterThan(0.0);
AddComment("This is cos op");
}
};
@@ -80,7 +80,7 @@ TEST(OpRegistry, CreateOp) {
paddle::framework::Scope scope;
paddle::platform::CPUDeviceContext dev_ctx;
op->Run(scope, dev_ctx);
- float scale_get = op->GetAttr("scale");
+ float scale_get = op->Attr("scale");
ASSERT_EQ(scale_get, scale);
}
@@ -121,7 +121,7 @@ TEST(OpRegistry, DefaultValue) {
paddle::framework::Scope scope;
paddle::platform::CPUDeviceContext dev_ctx;
op->Run(scope, dev_ctx);
- ASSERT_EQ(op->GetAttr("scale"), 1.0);
+ ASSERT_EQ(op->Attr("scale"), 1.0);
}
TEST(OpRegistry, CustomChecker) {
@@ -172,6 +172,6 @@ TEST(OpRegistry, CustomChecker) {
paddle::platform::CPUDeviceContext dev_ctx;
paddle::framework::Scope scope;
op->Run(scope, dev_ctx);
- int test_attr = op->GetAttr("test_attr");
+ int test_attr = op->Attr("test_attr");
ASSERT_EQ(test_attr, 4);
}
\ No newline at end of file
diff --git a/paddle/framework/operator.cc b/paddle/framework/operator.cc
index 790cfc4746b1d34da413fa3c29a266f962c6dde6..e1e122091f7759b1a68f1f982bc2a35e8241f9f0 100644
--- a/paddle/framework/operator.cc
+++ b/paddle/framework/operator.cc
@@ -123,6 +123,15 @@ OperatorBase::OperatorBase(const std::string& type,
CheckAllInputOutputSet();
}
+std::vector OperatorBase::InputVars() const {
+ std::vector ret_val;
+ for (auto& o : outputs_) {
+ ret_val.reserve(ret_val.size() + o.second.size());
+ ret_val.insert(ret_val.end(), o.second.begin(), o.second.end());
+ }
+ return ret_val;
+}
+
std::vector OperatorBase::OutputVars(bool has_intermediate) const {
std::vector ret_val;
if (has_intermediate) {
diff --git a/paddle/framework/operator.h b/paddle/framework/operator.h
index da92220b04e313e4743cc77241755b685d0791ad..4600b06009bcef7d0774d25b816aac4733f30795 100644
--- a/paddle/framework/operator.h
+++ b/paddle/framework/operator.h
@@ -69,7 +69,7 @@ class OperatorBase {
virtual ~OperatorBase() {}
template
- inline const T& GetAttr(const std::string& name) const {
+ inline const T& Attr(const std::string& name) const {
PADDLE_ENFORCE(attrs_.count(name) != 0, "%s should be in AttributeMap",
name);
return boost::get(attrs_.at(name));
@@ -94,11 +94,14 @@ class OperatorBase {
const VariableNameMap& Inputs() const { return inputs_; }
const VariableNameMap& Outputs() const { return outputs_; }
+
//! Get a input with argument's name described in `op_proto`
std::string Input(const std::string& name) const;
//! Get a input which has multiple variables.
const std::vector& Inputs(const std::string& name) const;
+ std::vector InputVars() const;
+
//! Get a output with argument's name described in `op_proto`
std::string Output(const std::string& name) const;
//! Get an output which has multiple variables.
@@ -238,8 +241,8 @@ class InferShapeContext {
const Scope& scope() const { return scope_; }
template
- inline const T& GetAttr(const std::string& name) const {
- return op_.GetAttr(name);
+ inline const T& Attr(const std::string& name) const {
+ return op_.Attr(name);
}
size_t InputSize(const std::string& name) const {
@@ -311,9 +314,9 @@ class InferShapeContext {
}
template
- std::vector MultiOutput(const std::string& name) const {
+ std::vector MultiOutput(const std::string& name) const {
auto names = op_.Outputs(name);
- std::vector res;
+ std::vector res;
res.reserve(names.size());
std::transform(names.begin(), names.end(), std::back_inserter(res),
[&](const std::string& sub_name) {
diff --git a/paddle/framework/operator_test.cc b/paddle/framework/operator_test.cc
index 8a1970c7a8aa5f76abed49bfde445fc743544e66..20bbb11896a4c6f11079669f0b25773f6460594d 100644
--- a/paddle/framework/operator_test.cc
+++ b/paddle/framework/operator_test.cc
@@ -102,7 +102,7 @@ class OpKernelTestProtoAndCheckerMaker : public OpProtoAndCheckerMaker {
AddOutput("y", "output of test op");
AddAttr("scale", "scale of cosine op")
.SetDefault(1.0)
- .LargerThan(0.0);
+ .GreaterThan(0.0);
AddComment("This is test op");
}
};
@@ -140,7 +140,7 @@ class OpKernelTestMultiInputsProtoAndCheckerMaker
AddOutput("ys", "outputs of test op").AsDuplicable();
AddAttr("scale", "scale of cosine op")
.SetDefault(1.0)
- .LargerThan(0.0);
+ .GreaterThan(0.0);
AddComment("This is test op");
}
};
diff --git a/paddle/framework/tensor.h b/paddle/framework/tensor.h
index 643f875491724bf443bd7727391734377ee6180c..4b5a2ae523f2f7fde5445f0534cd99969ad9d59e 100644
--- a/paddle/framework/tensor.h
+++ b/paddle/framework/tensor.h
@@ -43,6 +43,9 @@ class Tensor {
template
friend struct EigenTensor;
+ template
+ friend struct EigenMatrix;
+
template
friend struct EigenVector;
@@ -78,6 +81,9 @@ class Tensor {
/*! Return the dimensions of the memory block. */
inline const DDim& dims() const;
+ /*! Return the numel of the memory block. */
+ inline int64_t numel() const;
+
/*! Resize the dimensions of the memory block. */
inline Tensor& Resize(const DDim& dims);
@@ -159,6 +165,12 @@ class Tensor {
/*! points to dimensions of memory block. */
DDim dims_;
+ /**
+ * A cache of the number of elements in a tensor.
+ * Would be 0 for an uninitialized tensor.
+ */
+ int64_t numel_;
+
/**
* @brief A PlaceHolder may be shared by more than one tensor.
*
diff --git a/paddle/framework/tensor_impl.h b/paddle/framework/tensor_impl.h
index 94f436294f350e2a39785a09959efb3b17bd00a5..642b53efc7095d25712ca324638f5fe9b8316c0c 100644
--- a/paddle/framework/tensor_impl.h
+++ b/paddle/framework/tensor_impl.h
@@ -24,7 +24,7 @@ inline void Tensor::check_memory_size() const {
PADDLE_ENFORCE_NOT_NULL(
holder_, "Tenosr holds no memory. Call Tensor::mutable_data first.");
PADDLE_ENFORCE_GE(
- holder_->size(), product(dims_) * sizeof(T) + offset_,
+ holder_->size(), numel() * sizeof(T) + offset_,
"Tensor's dims_ is out of bound. Call Tensor::mutable_data "
"first to re-allocate memory.\n"
"or maybe the required data-type mismatches the data already stored.");
@@ -54,11 +54,11 @@ inline T* Tensor::mutable_data(DDim dims, platform::Place place) {
template
inline T* Tensor::mutable_data(platform::Place place) {
static_assert(std::is_pod::value, "T must be POD");
- PADDLE_ENFORCE_GT(product(dims_), 0,
+ PADDLE_ENFORCE_GT(numel(), 0,
"Tensor's numel must be larger than zero to call "
"Tensor::mutable_data. Call Tensor::set_dim first.");
/* some versions of boost::variant don't have operator!= */
- int64_t size = product(dims_) * sizeof(T);
+ int64_t size = numel() * sizeof(T);
if (holder_ == nullptr || !(holder_->place() == place) ||
holder_->size() < size + offset_) {
if (platform::is_cpu_place(place)) {
@@ -97,7 +97,7 @@ inline void Tensor::CopyFrom(const Tensor& src,
auto dst_ptr = static_cast(mutable_data(dst_place));
- auto size = product(src.dims_) * sizeof(T);
+ auto size = src.numel() * sizeof(T);
if (platform::is_cpu_place(src_place) && platform::is_cpu_place(dst_place)) {
memory::Copy(boost::get(dst_place), dst_ptr,
@@ -131,7 +131,7 @@ inline Tensor Tensor::Slice(const int& begin_idx, const int& end_idx) const {
PADDLE_ENFORCE_LT(begin_idx, end_idx,
"Begin index must be less than end index.");
PADDLE_ENFORCE_NE(dims_[0], 1, "Can not slice a tensor with dims_[0] = 1.");
- size_t base = product(dims_) / dims_[0];
+ size_t base = numel() / dims_[0];
Tensor dst;
dst.holder_ = holder_;
DDim dst_dims = dims_;
@@ -143,10 +143,21 @@ inline Tensor Tensor::Slice(const int& begin_idx, const int& end_idx) const {
inline Tensor& Tensor::Resize(const DDim& dims) {
dims_ = dims;
+ numel_ = product(dims_);
return *this;
}
inline const DDim& Tensor::dims() const { return dims_; }
+inline int64_t Tensor::numel() const { return numel_; }
+
+template
+inline Tensor ReshapeToMatrix(const Tensor& src, int num_col_dims) {
+ Tensor res;
+ res.ShareDataWith(src);
+ res.Resize(flatten_to_2d(src.dims(), num_col_dims));
+ return res;
+}
+
} // namespace framework
} // namespace paddle
diff --git a/paddle/framework/tensor_test.cc b/paddle/framework/tensor_test.cc
index 7db38d5caeebccf710334e854faf785ef0f64063..55302ea47120f420e952b26830c8ea4cbcce6435 100644
--- a/paddle/framework/tensor_test.cc
+++ b/paddle/framework/tensor_test.cc
@@ -262,3 +262,16 @@ TEST(Tensor, CopyFrom) {
}
#endif
}
+
+TEST(Tensor, ReshapeToMatrix) {
+ using namespace paddle::framework;
+ using namespace paddle::platform;
+ Tensor src;
+ int* src_ptr = src.mutable_data({2, 3, 4, 9}, CPUPlace());
+ for (int i = 0; i < 2 * 3 * 4 * 9; ++i) {
+ src_ptr[i] = i;
+ }
+ Tensor res = ReshapeToMatrix(src, 2);
+ ASSERT_EQ(res.dims()[0], 2 * 3);
+ ASSERT_EQ(res.dims()[1], 4 * 9);
+}
\ No newline at end of file
diff --git a/paddle/function/CMakeLists.txt b/paddle/function/CMakeLists.txt
index f43f15e5cacb70b625d7791e1e02ce7780286200..4fd72d64a90ae6f16dd1499ceb7fba6e40fe4cea 100644
--- a/paddle/function/CMakeLists.txt
+++ b/paddle/function/CMakeLists.txt
@@ -44,6 +44,7 @@ if(WITH_GPU)
add_simple_unittest(RowConvOpTest)
add_simple_unittest(BlockExpandOpTest)
add_simple_unittest(CropOpTest)
+ add_simple_unittest(SwitchOpTest)
endif()
add_simple_unittest(Im2ColTest)
diff --git a/paddle/function/EigenGemm.cpp b/paddle/function/EigenGemm.cpp
index 674141ed39b7f5573948348e3ba3bb526ae43c66..b3e666e860d29d89650d48a23cf44917035a02d7 100644
--- a/paddle/function/EigenGemm.cpp
+++ b/paddle/function/EigenGemm.cpp
@@ -83,9 +83,9 @@ struct EigenBlasGemm {
};
#ifdef PADDLE_TYPE_DOUBLE
-template class EigenBlasGemm;
+template struct EigenBlasGemm;
#else
-template class EigenBlasGemm;
+template struct EigenBlasGemm;
#endif
} // namespace paddle
diff --git a/paddle/function/GruFunctor.h b/paddle/function/GruFunctor.h
new file mode 100644
index 0000000000000000000000000000000000000000..9f6392198ea360502f313cbe15dfae46ece69758
--- /dev/null
+++ b/paddle/function/GruFunctor.h
@@ -0,0 +1,159 @@
+/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License. */
+
+#pragma once
+
+#include "GemmFunctor.h"
+#include "hl_cpu_gru.cuh"
+
+namespace paddle {
+
+template
+struct GruFunctor {
+ template
+ static void compute(OpResetOutput opResetOutput,
+ OpFinalOutput opFinalOutput,
+ hl_gru_value value,
+ int frameSize,
+ int batchSize,
+ hl_activation_mode_t active_node,
+ hl_activation_mode_t active_gate) {
+#ifndef __NVCC__
+ if (value.prevOutValue) {
+ BlasGemm::compute(false,
+ false,
+ batchSize,
+ 2 * frameSize,
+ frameSize,
+ 1,
+ value.prevOutValue,
+ frameSize,
+ value.gateWeight,
+ frameSize * 2,
+ 1,
+ value.gateValue,
+ frameSize * 3);
+ }
+
+ forward_reset_output(
+ opResetOutput, value, frameSize, batchSize, active_gate);
+
+ if (value.prevOutValue) {
+ BlasGemm::compute(false,
+ false,
+ batchSize,
+ frameSize,
+ frameSize,
+ 1,
+ value.resetOutputValue,
+ frameSize,
+ value.stateWeight,
+ frameSize,
+ 1,
+ value.gateValue + frameSize * 2,
+ frameSize * 3);
+ }
+
+ forward_final_output(
+ opFinalOutput, value, frameSize, batchSize, active_node);
+#endif
+ }
+};
+
+template
+struct GruGradFunctor {
+ template
+ static void compute(OpStateGrad opStateGrad,
+ OpResetGrad opResetGrad,
+ hl_gru_value value,
+ hl_gru_grad grad,
+ int frameSize,
+ int batchSize,
+ hl_activation_mode_t active_node,
+ hl_activation_mode_t active_gate) {
+#ifndef __NVCC__
+ backward_state_grad(
+ opStateGrad, value, grad, frameSize, batchSize, active_node);
+
+ if (value.prevOutValue && grad.prevOutGrad) {
+ BlasGemm::compute(false,
+ true,
+ batchSize,
+ frameSize,
+ frameSize,
+ 1,
+ grad.gateGrad + frameSize * 2,
+ frameSize * 3,
+ value.stateWeight,
+ frameSize,
+ 0,
+ grad.resetOutputGrad,
+ frameSize);
+
+ if (grad.stateWeightGrad) {
+ BlasGemm::compute(true,
+ false,
+ frameSize,
+ frameSize,
+ batchSize,
+ 1,
+ value.resetOutputValue,
+ frameSize,
+ grad.gateGrad + frameSize * 2,
+ frameSize * 3,
+ 1,
+ grad.stateWeightGrad,
+ frameSize);
+ }
+ }
+
+ backward_reset_grad(
+ opResetGrad, value, grad, frameSize, batchSize, active_gate);
+
+ if (grad.prevOutGrad && value.prevOutValue) {
+ BlasGemm::compute(false,
+ true,
+ batchSize,
+ frameSize,
+ frameSize * 2,
+ 1,
+ grad.gateGrad,
+ frameSize * 3,
+ value.gateWeight,
+ frameSize * 2,
+ 1,
+ grad.prevOutGrad,
+ frameSize);
+
+ if (grad.gateWeightGrad) {
+ BlasGemm::compute(true,
+ false,
+ frameSize,
+ frameSize * 2,
+ batchSize,
+ 1,
+ value.prevOutValue,
+ frameSize,
+ grad.gateGrad,
+ frameSize * 3,
+ 1,
+ grad.gateWeightGrad,
+ frameSize * 2);
+ }
+ }
+#endif
+ }
+};
+
+} // namespace paddle
diff --git a/paddle/function/Im2Col.h b/paddle/function/Im2Col.h
index 9b91e223a6a28586b11fe7ed4a44421e029a67bb..1e0cff436ff60d5a029e89657d00af2b0bf8b454 100644
--- a/paddle/function/Im2Col.h
+++ b/paddle/function/Im2Col.h
@@ -94,95 +94,4 @@ public:
int paddingWidth);
};
-template
-struct Padding {
- static void run(const T* src,
- T* dest,
- int channels,
- int inputHeight,
- int inputWidth,
- int paddingHeight,
- int paddingWidth) {
- const int destWidth = inputWidth + 2 * paddingWidth;
- for (int c = 0; c < channels; c++) {
- if (paddingHeight > 0) {
- memset(dest, 0, destWidth * paddingHeight * sizeof(T));
- dest += destWidth * paddingHeight;
- }
-
- for (int i = 0; i < inputHeight; i++) {
- // padding head
- for (int j = 0; j < paddingWidth; j++) {
- *dest++ = T(0);
- }
-
- memcpy(dest, src, inputWidth * sizeof(T));
- dest += inputWidth;
- src += inputWidth;
-
- // padding tail
- for (int j = 0; j < paddingWidth; j++) {
- *dest++ = T(0);
- }
- }
-
- if (paddingHeight > 0) {
- memset(dest, 0, destWidth * paddingHeight * sizeof(T));
- dest += destWidth * paddingHeight;
- }
- }
- }
-};
-
-#if defined(__ARM_NEON__) || defined(__ARM_NEON)
-template <>
-struct Padding {
- static void run(const float* src,
- float* dest,
- int channels,
- int inputHeight,
- int inputWidth,
- int paddingHeight,
- int paddingWidth) {
- const int destWidth = inputWidth + 2 * paddingWidth;
- for (int c = 0; c < channels; c++) {
- if (paddingHeight > 0) {
- memset(dest, 0, destWidth * paddingHeight * sizeof(float));
- dest += destWidth * paddingHeight;
- }
-
- for (int i = 0; i < inputHeight; i++) {
- // padding head
- for (int j = 0; j < paddingWidth; j++) {
- *dest++ = float(0);
- }
-
- int step = inputWidth >> 2;
- int remain = inputWidth & 3;
- for (int s = 0; s < step; s++) {
- float32x4_t s0 = vld1q_f32(src);
- vst1q_f32(dest, s0);
- src += 4;
- dest += 4;
- }
- for (int r = 0; r < remain; r++) {
- *dest++ = *src++;
- }
-
- // padding tail
- for (int j = 0; j < paddingWidth; j++) {
- *dest++ = float(0);
- }
- }
-
- if (paddingHeight > 0) {
- memset(dest, 0, destWidth * paddingHeight * sizeof(float));
- dest += destWidth * paddingHeight;
- }
- }
- }
-};
-
-#endif
-
} // namespace paddle
diff --git a/paddle/function/MulOp.cpp b/paddle/function/MulOp.cpp
index 91b4b8ed91b6055babcfbab8f7adb2c55e2747d0..25e41edad54bec0f76a3de4799fab14241407272 100644
--- a/paddle/function/MulOp.cpp
+++ b/paddle/function/MulOp.cpp
@@ -13,18 +13,10 @@ See the License for the specific language governing permissions and
limitations under the License. */
#include "MulOp.h"
-/// todo(tianbing), delete it
-#include
-#include "paddle/math/MathFunctions.h"
+#include "GemmFunctor.h"
#include "paddle/math/SIMDFunctions.h"
#include "paddle/utils/ThreadLocal.h"
-#ifndef PADDLE_TYPE_DOUBLE
-#define GEMM paddle::gemm
-#else
-#define GEMM paddle::gemm
-#endif
-
namespace {
inline void vecAddTo(real* a, const real* b, real scaleB, size_t len) {
for (unsigned int i = 0; i < len; ++i) {
@@ -114,19 +106,20 @@ void MulOp(CpuMatrix& out,
real scaleT,
bool aTrans,
bool bTrans) {
- GEMM(aTrans ? CblasTrans : CblasNoTrans,
- bTrans ? CblasTrans : CblasNoTrans,
- out.getHeight(),
- out.getWidth(),
- !aTrans ? a.getWidth() : a.getHeight(),
- scaleAB,
- a.getData(),
- a.getStride(),
- b.getData(),
- b.getStride(),
- scaleT,
- out.getData(),
- out.getStride());
+ BlasGemm::compute(
+ aTrans,
+ bTrans,
+ out.getHeight(),
+ out.getWidth(),
+ !aTrans ? a.getWidth() : a.getHeight(),
+ scaleAB,
+ a.getData(),
+ a.getStride(),
+ b.getData(),
+ b.getStride(),
+ scaleT,
+ out.getData(),
+ out.getStride());
}
/// dense matrix (+)= sparse matrix * dense matrix
diff --git a/paddle/function/SwitchOp.cpp b/paddle/function/SwitchOp.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..01e252a8dc0cd5fa1e964efa01d04cf282b3dfe7
--- /dev/null
+++ b/paddle/function/SwitchOp.cpp
@@ -0,0 +1,140 @@
+/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License. */
+
+#include "SwitchOp.h"
+#include "paddle/math/Vector.h"
+
+namespace paddle {
+
+template <>
+void NCHW2NHWC(real* outputs,
+ const real* inputs,
+ const int num,
+ const int inC,
+ const int inH,
+ const int inW,
+ const int argType) {
+ for (int n = 0; n < num; ++n) {
+ for (int c = 0; c < inC; ++c) {
+ for (int h = 0; h < inH; ++h) {
+ for (int w = 0; w < inW; ++w) {
+ if (argType == ADD_TO) {
+ outputs[((n * inH + h) * inW + w) * inC + c] += *(inputs++);
+ } else {
+ outputs[((n * inH + h) * inW + w) * inC + c] = *(inputs++);
+ }
+ }
+ }
+ }
+ }
+}
+
+template <>
+void NHWC2NCHW(real* outputs,
+ const real* inputs,
+ const int num,
+ const int inH,
+ const int inW,
+ const int inC,
+ const int argType) {
+ for (int n = 0; n < num; ++n) {
+ for (int h = 0; h < inH; ++h) {
+ for (int w = 0; w < inW; ++w) {
+ for (int c = 0; c < inC; ++c) {
+ if (argType == ADD_TO) {
+ outputs[((n * inC + c) * inH + h) * inW + w] += *(inputs++);
+ } else {
+ outputs[((n * inC + c) * inH + h) * inW + w] = *(inputs++);
+ }
+ }
+ }
+ }
+ }
+}
+
+/**
+ * \brief Switch dimension order of image input.
+ * The input and output is a 4D tensor. Switch order
+ * 'batch_size,channels, height, width' to
+ * order 'batch_size, height, width, channels'.
+ *
+ * Argument in this Function:
+ * \param inputs input data with order 'batch_size,channels, height, width'.
+ * \param outputs output data with order 'batch_size, height, width, channels'.
+ */
+template
+class NCHW2NHWCFunc : public FunctionBase {
+public:
+ void init(const FuncConfig& config) override {}
+
+ void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
+ CHECK_EQ(1UL, inputs.size());
+ CHECK_EQ(1UL, outputs.size());
+
+ size_t num = inputs[0].shape()[0];
+ size_t inC = inputs[0].shape()[1];
+ size_t inH = inputs[0].shape()[2];
+ size_t inW = inputs[0].shape()[3];
+ NCHW2NHWC(outputs[0].data(),
+ inputs[0].data(),
+ num,
+ inC,
+ inH,
+ inW,
+ outputs[0].getArgType());
+ }
+};
+
+/**
+ * \brief Switch dimension order of image input.
+ * The input and output is a 4D tensor. Switch order
+ * 'batch_size, height, width, channels' to
+ * order 'batch_size, channels, height, width'.
+ *
+ * Argument in this Function:
+ * \param inputs input data with order 'batch_size, height, width, channels'.
+ * \param outputs output data with order 'batch_size, channels, height, width'.
+ */
+template
+class NHWC2NCHWFunc : public FunctionBase {
+public:
+ void init(const FuncConfig& config) override {}
+
+ void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
+ CHECK_EQ(1UL, inputs.size());
+ CHECK_EQ(1UL, outputs.size());
+
+ size_t num = inputs[0].shape()[0];
+ size_t inH = inputs[0].shape()[1];
+ size_t inW = inputs[0].shape()[2];
+ size_t inC = inputs[0].shape()[3];
+
+ NHWC2NCHW(outputs[0].data(),
+ inputs[0].data(),
+ num,
+ inH,
+ inW,
+ inC,
+ outputs[0].getArgType());
+ }
+};
+
+REGISTER_TYPED_FUNC(NCHW2NHWC, CPU, NCHW2NHWCFunc);
+REGISTER_TYPED_FUNC(NHWC2NCHW, CPU, NHWC2NCHWFunc);
+#ifndef PADDLE_ONLY_CPU
+REGISTER_TYPED_FUNC(NCHW2NHWC, GPU, NCHW2NHWCFunc);
+REGISTER_TYPED_FUNC(NHWC2NCHW, GPU, NHWC2NCHWFunc);
+#endif
+
+} // namespace paddle
diff --git a/paddle/function/SwitchOp.h b/paddle/function/SwitchOp.h
new file mode 100644
index 0000000000000000000000000000000000000000..e4c1c3ac922f88c3e5424b5943082810aabfacdb
--- /dev/null
+++ b/paddle/function/SwitchOp.h
@@ -0,0 +1,66 @@
+/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License. */
+
+#pragma once
+
+#include "Function.h"
+
+namespace paddle {
+
+/**
+ * \brief This funtion switch dimension order of image input.
+ * The input and output is a 4D tensor. Switch order 'batch_size,
+ *channels, height, width' to
+ * order 'batch_size, height, width, channels'.
+ *
+ * \param[out] outputs save results.
+ * \param[in] inputs input data.
+ * \param[in] num batch size of input data.
+ * \param[in] inC channel number of input data.
+ * \param[in] inH height of input data.
+ * \param[in] inH with of input data.
+ * \param[in] argType type of output argument.
+ */
+template
+void NCHW2NHWC(real* outputs,
+ const real* inputs,
+ const int num,
+ const int inC,
+ const int inH,
+ const int inW,
+ const int argtype);
+
+/**
+ * \brief This funtion switch dimension order of image input.
+ * The input and output is a 4D tensor. Switch order 'batch_size,
+ *height, width, channels' to
+ * order 'batch_size, channels, height, width'.
+ *
+ * \param[out] inGrad gradients of previous layer.
+ * \param[in] outGrad output gradients.
+ * \param[in] num batch size of input data.
+ * \param[in] inH height of input data.
+ * \param[in] inW with of input data.
+ * \param[in] inC channel number of input data.
+ * \param[in] argType type of output argument.
+ */
+template
+void NHWC2NCHW(real* inGrad,
+ const real* outGrad,
+ const int num,
+ const int inH,
+ const int inW,
+ const int inC,
+ const int argType);
+} // namespace paddle
diff --git a/paddle/function/SwitchOpGpu.cu b/paddle/function/SwitchOpGpu.cu
new file mode 100644
index 0000000000000000000000000000000000000000..45390a56c3f776ec18a65a6ba2f7149a7a6ef6c3
--- /dev/null
+++ b/paddle/function/SwitchOpGpu.cu
@@ -0,0 +1,98 @@
+/* Copyright (c) 2016 Paddle
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License. */
+
+#include "SwitchOp.h"
+#include "hl_base.h"
+
+namespace paddle {
+
+__global__ void KeNCHW2NHWC(real* outputs,
+ const real* inputs,
+ int inC,
+ int inH,
+ int inW,
+ int nthreads,
+ int argType) {
+ const int idx = threadIdx.x + blockIdx.x * blockDim.x;
+ if (idx < nthreads) {
+ const int w = idx % inW;
+ const int h = (idx / inW) % inH;
+ const int c = (idx / inW / inH) % inC;
+ const int n = idx / inW / inH / inC;
+
+ const int off = ((n * inH + h) * inW + w) * inC + c;
+ if (argType == ADD_TO) {
+ outputs[off] += inputs[idx];
+ } else {
+ outputs[off] = inputs[idx];
+ }
+ }
+}
+
+template <>
+void NCHW2NHWC(real* outputs,
+ const real* inputs,
+ const int num,
+ const int inC,
+ const int inH,
+ const int inW,
+ const int argType) {
+ size_t nth = num * inC * inH * inW;
+ int blockSize = 1024;
+ int gridSize = (nth + 1024 - 1) / 1024;
+ KeNCHW2NHWC<<>>(
+ outputs, inputs, inC, inH, inW, nth, argType);
+ CHECK_SYNC("NCHW2NHWC");
+}
+
+__global__ void KeNHWC2NCHW(real* outputs,
+ const real* inputs,
+ int inH,
+ int inW,
+ int inC,
+ int nthreads,
+ int argType) {
+ const int idx = threadIdx.x + blockIdx.x * blockDim.x;
+ if (idx < nthreads) {
+ const int c = idx % inC;
+ const int w = (idx / inC) % inW;
+ const int h = (idx / inC / inW) % inH;
+ const int n = idx / inW / inH / inC;
+
+ const int off = ((n * inC + c) * inH + h) * inW + w;
+ if (argType == ADD_TO) {
+ outputs[off] += inputs[idx];
+ } else {
+ outputs[off] = inputs[idx];
+ }
+ }
+}
+
+template <>
+void NHWC2NCHW(real* outputs,
+ const real* inputs,
+ const int num,
+ const int inH,
+ const int inW,
+ const int inC,
+ const int argType) {
+ int nth = num * inC * inH * inW;
+ int blockSize = 1024;
+ int gridSize = (nth + 1024 - 1) / 1024;
+ KeNHWC2NCHW<<>>(
+ outputs, inputs, inH, inW, inC, nth, argType);
+ CHECK_SYNC("NHWC2NCHW");
+}
+
+} // namespace paddle
diff --git a/paddle/function/SwitchOpTest.cpp b/paddle/function/SwitchOpTest.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..03b0dd66ddcbab713969ed747601ecb1b2eb7955
--- /dev/null
+++ b/paddle/function/SwitchOpTest.cpp
@@ -0,0 +1,44 @@
+/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License. */
+
+#include
+#include "FunctionTest.h"
+
+namespace paddle {
+
+TEST(Pad, real) {
+ for (size_t numSamples : {1, 4, 8, 16}) {
+ for (size_t channels : {1, 4, 8, 16}) {
+ for (size_t imgSizeH : {1, 4, 8, 16}) {
+ for (size_t imgSizeW : {1, 4, 8, 16}) {
+ VLOG(3) << " numSamples=" << numSamples << " channels=" << channels
+ << " imgSizeH=" << imgSizeH << " imgSizeW=" << imgSizeW;
+ for (bool test_grad : {true, false}) {
+ CpuGpuFuncCompare compare(test_grad ? "NHWC2NCHW" : "NCHW2NHWC",
+ FuncConfig());
+ TensorShape inDims{numSamples, channels, imgSizeH, imgSizeW};
+ TensorShape outDims{numSamples, imgSizeH, imgSizeW, channels};
+ compare.addInputs(
+ BufferArg(VALUE_TYPE_FLOAT, test_grad ? outDims : inDims));
+ compare.addOutputs(BufferArg(
+ VALUE_TYPE_FLOAT, test_grad ? inDims : outDims, ASSIGN_TO));
+ compare.run();
+ }
+ }
+ }
+ }
+ }
+}
+
+} // namespace paddle
diff --git a/paddle/function/neon/NeonDepthwiseConv.cpp b/paddle/function/neon/NeonDepthwiseConv.cpp
index f09e98587d1681d29a79a9cb0303c2d4356c6935..18126152ea0b4ebfe4ec5c8084479787814ed173 100644
--- a/paddle/function/neon/NeonDepthwiseConv.cpp
+++ b/paddle/function/neon/NeonDepthwiseConv.cpp
@@ -12,468 +12,13 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
-#include "neon_util.h"
+#include "NeonDepthwiseConv.h"
#include "paddle/function/ConvOp.h"
-#include "paddle/function/Im2Col.h"
namespace paddle {
-namespace neon {
-
#if defined(__ARM_NEON__) || defined(__ARM_NEON)
-template
-struct DepthwiseConvKernel {};
-
-inline float32_t conv3x3(float32x4_t r0,
- float32x4_t r1,
- float32x4_t r2,
- float32x4_t k0,
- float32x4_t k1,
- float32x4_t k2) {
- float32x4_t tmp;
- tmp = vmulq_f32(r0, k0);
- tmp = vmlaq_f32(tmp, r1, k1);
- tmp = vmlaq_f32(tmp, r2, k2);
- return vaddvq_f32(tmp);
-}
-
-inline float32_t conv4x4(float32x4_t r0,
- float32x4_t r1,
- float32x4_t r2,
- float32x4_t r3,
- float32x4_t k0,
- float32x4_t k1,
- float32x4_t k2,
- float32x4_t k3) {
- float32x4_t tmp;
- tmp = vmulq_f32(r0, k0);
- tmp = vmlaq_f32(tmp, r1, k1);
- tmp = vmlaq_f32(tmp, r2, k2);
- tmp = vmlaq_f32(tmp, r3, k3);
- return vaddvq_f32(tmp);
-}
-
-/**
- * Each step calculates four elements of the output.
- * First step:
- * R0[0, 1, 2, 3...] * K[0][0]
- * R0[1, 2, 3, 4...] * K[0][1]
- * R0[2, 3, 4, 5...] * K[0][2]
- * R1[0, 1, 2, 3...] * K[1][0]
- * R1[1, 2, 3, 4...] * K[1][1]
- * R1[2, 3, 4, 5...] * K[1][2]
- * R2[0, 1, 2, 3...] * K[2][0]
- * R2[1, 2, 3, 4...] * K[2][1]
- * + R2[2, 3, 4, 5...] * K[2][2]
- * ------------------------------
- * Output[0, 1, 2, 3]
- */
-template <>
-struct DepthwiseConvKernel<3, 1> {
- static void run(const float* inputData,
- const float* filterData,
- int inputHeight,
- int inputWidth,
- int outputChannels,
- int outputHeight,
- int outputWidth,
- int filterMultiplier,
- float* outputData) {
- const int steps = outputWidth >> 2;
- const int remain = outputWidth & 3;
- for (int c = 0; c < outputChannels; c++, filterData += 9) {
- // Load the filters
- float32x4_t k[3];
- k[0] = vld1q_f32(filterData);
- k[1] = vld1q_f32(filterData + 3);
- k[2] = vld1q_f32(filterData + 6);
- k[0] = vsetq_lane_f32(0.f, k[0], 3);
- k[1] = vsetq_lane_f32(0.f, k[1], 3);
- k[2] = vsetq_lane_f32(0.f, k[2], 3);
-
- const float* r0 =
- inputData + (c / filterMultiplier) * (inputHeight * inputWidth);
- const float* r1 = r0 + inputWidth;
- const float* r2 = r0 + inputWidth * 2;
- float32x4_t input[3][3];
- for (int h = 0; h < outputHeight; h++) {
- for (int s = 0; s < steps; s++) {
- // Load the inputs
- float32x4_t tmp;
- input[0][0] = vld1q_f32(r0);
- tmp = vld1q_f32(r0 + 4);
- input[0][1] = vextq_f32(input[0][0], tmp, 1);
- input[0][2] = vextq_f32(input[0][0], tmp, 2);
- input[1][0] = vld1q_f32(r1);
- tmp = vld1q_f32(r1 + 4);
- input[1][1] = vextq_f32(input[1][0], tmp, 1);
- input[1][2] = vextq_f32(input[1][0], tmp, 2);
- input[2][0] = vld1q_f32(r2);
- tmp = vld1q_f32(r2 + 4);
- input[2][1] = vextq_f32(input[2][0], tmp, 1);
- input[2][2] = vextq_f32(input[2][0], tmp, 2);
-
- float32x4_t tmp1 = vdupq_n_f32(0.f);
- float32x4_t tmp2 = vdupq_n_f32(0.f);
- tmp1 = vmlaq_laneq_f32(tmp1, input[0][0], k[0], 0);
- tmp2 = vmlaq_laneq_f32(tmp2, input[0][1], k[0], 1);
- tmp1 = vmlaq_laneq_f32(tmp1, input[0][2], k[0], 2);
- tmp2 = vmlaq_laneq_f32(tmp2, input[1][0], k[1], 0);
- tmp1 = vmlaq_laneq_f32(tmp1, input[1][1], k[1], 1);
- tmp2 = vmlaq_laneq_f32(tmp2, input[1][2], k[1], 2);
- tmp1 = vmlaq_laneq_f32(tmp1, input[2][0], k[2], 0);
- tmp2 = vmlaq_laneq_f32(tmp2, input[2][1], k[2], 1);
- tmp1 = vmlaq_laneq_f32(tmp1, input[2][2], k[2], 2);
- tmp1 = vaddq_f32(tmp1, tmp2);
-
- vst1q_f32(outputData, tmp1);
- r0 += 4;
- r1 += 4;
- r2 += 4;
- outputData += 4;
- }
-
- for (int r = 0; r < remain; r++) {
- float32x4_t i0 = vld1q_f32(r0);
- float32x4_t i1 = vld1q_f32(r1);
- float32x4_t i2 = vld1q_f32(r2);
- *outputData = conv3x3(i0, i1, i2, k[0], k[1], k[2]);
- r0++;
- r1++;
- r2++;
- outputData++;
- }
-
- r0 += 2;
- r1 += 2;
- r2 += 2;
- }
- }
- }
-};
-
-/**
- * Each step calculates four elements of the output.
- * First step:
- * R0[0, 2, 4, 6...] * K[0][0]
- * R0[1, 3, 5, 7...] * K[0][1]
- * R0[2, 4, 6, 8...] * K[0][2]
- * R1[0, 2, 4, 6...] * K[1][0]
- * R1[1, 3, 5, 7...] * K[1][1]
- * R1[2, 4, 6, 8...] * K[1][2]
- * R2[0, 2, 4, 6...] * K[2][0]
- * R2[1, 3, 5, 7...] * K[2][1]
- * R2[2, 4, 6, 8...] * K[2][2]
- * ------------------------------
- * Output[0, 1, 2, 3]
- */
-template <>
-struct DepthwiseConvKernel<3, 2> {
- static void run(const float* inputData,
- const float* filterData,
- int inputHeight,
- int inputWidth,
- int outputChannels,
- int outputHeight,
- int outputWidth,
- int filterMultiplier,
- float* outputData) {
- const int steps = outputWidth >> 2;
- const int remain = outputWidth & 3;
- for (int c = 0; c < outputChannels; c++, filterData += 9) {
- // Load the filters
- float32x4_t k[3];
- k[0] = vld1q_f32(filterData);
- k[1] = vld1q_f32(filterData + 3);
- k[2] = vld1q_f32(filterData + 6);
- k[0] = vsetq_lane_f32(0.f, k[0], 3);
- k[1] = vsetq_lane_f32(0.f, k[1], 3);
- k[2] = vsetq_lane_f32(0.f, k[2], 3);
-
- const float* start =
- inputData + (c / filterMultiplier) * (inputHeight * inputWidth);
- float32x4_t input[3][3];
- for (int h = 0; h < outputHeight; h++) {
- const float* r0 = start + 2 * h * inputWidth;
- const float* r1 = start + (2 * h + 1) * inputWidth;
- const float* r2 = start + (2 * h + 2) * inputWidth;
- for (int s = 0; s < steps; s++) {
- // Load the inputs
- float32x4_t data1;
- float32x4x2_t data2;
-
- data2 = vld2q_f32(r0);
- input[0][0] = data2.val[0];
- input[0][1] = data2.val[1];
- data1 = vld1q_f32(r0 + 8);
- input[0][2] = vextq_f32(data2.val[0], data1, 1);
-
- data2 = vld2q_f32(r1);
- input[1][0] = data2.val[0];
- input[1][1] = data2.val[1];
- data1 = vld1q_f32(r1 + 8);
- input[1][2] = vextq_f32(data2.val[0], data1, 1);
-
- data2 = vld2q_f32(r2);
- input[2][0] = data2.val[0];
- input[2][1] = data2.val[1];
- data1 = vld1q_f32(r2 + 8);
- input[2][2] = vextq_f32(data2.val[0], data1, 1);
-
- float32x4_t tmp1 = vdupq_n_f32(0.f);
- float32x4_t tmp2 = vdupq_n_f32(0.f);
- tmp1 = vmlaq_laneq_f32(tmp1, input[0][0], k[0], 0);
- tmp2 = vmlaq_laneq_f32(tmp2, input[0][1], k[0], 1);
- tmp1 = vmlaq_laneq_f32(tmp1, input[0][2], k[0], 2);
- tmp2 = vmlaq_laneq_f32(tmp2, input[1][0], k[1], 0);
- tmp1 = vmlaq_laneq_f32(tmp1, input[1][1], k[1], 1);
- tmp2 = vmlaq_laneq_f32(tmp2, input[1][2], k[1], 2);
- tmp1 = vmlaq_laneq_f32(tmp1, input[2][0], k[2], 0);
- tmp2 = vmlaq_laneq_f32(tmp2, input[2][1], k[2], 1);
- tmp1 = vmlaq_laneq_f32(tmp1, input[2][2], k[2], 2);
- tmp1 = vaddq_f32(tmp1, tmp2);
-
- vst1q_f32(outputData, tmp1);
- r0 += 8;
- r1 += 8;
- r2 += 8;
- outputData += 4;
- }
-
- for (int r = 0; r < remain; r++) {
- float32x4_t i0 = vld1q_f32(r0);
- float32x4_t i1 = vld1q_f32(r1);
- float32x4_t i2 = vld1q_f32(r2);
- *outputData = conv3x3(i0, i1, i2, k[0], k[1], k[2]);
- r0 += 2;
- r1 += 2;
- r2 += 2;
- outputData++;
- }
- }
- }
- }
-};
-
-/**
- * Each step calculates four elements of the output.
- */
-template <>
-struct DepthwiseConvKernel<4, 1> {
- static void run(const float* inputData,
- const float* filterData,
- int inputHeight,
- int inputWidth,
- int outputChannels,
- int outputHeight,
- int outputWidth,
- int filterMultiplier,
- float* outputData) {
- const int steps = outputWidth >> 2;
- const int remain = outputWidth & 3;
- for (int c = 0; c < outputChannels; c++, filterData += 16) {
- // Load the filters
- float32x4_t k[4];
- k[0] = vld1q_f32(filterData);
- k[1] = vld1q_f32(filterData + 4);
- k[2] = vld1q_f32(filterData + 8);
- k[3] = vld1q_f32(filterData + 12);
-
- const float* r0 =
- inputData + (c / filterMultiplier) * (inputHeight * inputWidth);
- const float* r1 = r0 + inputWidth;
- const float* r2 = r0 + inputWidth * 2;
- const float* r3 = r0 + inputWidth * 3;
- float32x4_t input[4][4];
- for (int h = 0; h < outputHeight; h++) {
- for (int s = 0; s < steps; s++) {
- // Load the inputs
- float32x4_t tmp;
- input[0][0] = vld1q_f32(r0);
- tmp = vld1q_f32(r0 + 4);
- input[0][1] = vextq_f32(input[0][0], tmp, 1);
- input[0][2] = vextq_f32(input[0][0], tmp, 2);
- input[0][3] = vextq_f32(input[0][0], tmp, 3);
-
- input[1][0] = vld1q_f32(r1);
- tmp = vld1q_f32(r1 + 4);
- input[1][1] = vextq_f32(input[1][0], tmp, 1);
- input[1][2] = vextq_f32(input[1][0], tmp, 2);
- input[1][3] = vextq_f32(input[1][0], tmp, 3);
-
- input[2][0] = vld1q_f32(r2);
- tmp = vld1q_f32(r2 + 4);
- input[2][1] = vextq_f32(input[2][0], tmp, 1);
- input[2][2] = vextq_f32(input[2][0], tmp, 2);
- input[2][3] = vextq_f32(input[2][0], tmp, 3);
-
- input[3][0] = vld1q_f32(r3);
- tmp = vld1q_f32(r3 + 4);
- input[3][1] = vextq_f32(input[3][0], tmp, 1);
- input[3][2] = vextq_f32(input[3][0], tmp, 2);
- input[3][3] = vextq_f32(input[3][0], tmp, 3);
-
- float32x4_t tmp1 = vdupq_n_f32(0.f);
- float32x4_t tmp2 = vdupq_n_f32(0.f);
- tmp1 = vmlaq_laneq_f32(tmp1, input[0][0], k[0], 0);
- tmp2 = vmlaq_laneq_f32(tmp2, input[0][1], k[0], 1);
- tmp1 = vmlaq_laneq_f32(tmp1, input[0][2], k[0], 2);
- tmp2 = vmlaq_laneq_f32(tmp2, input[0][3], k[0], 3);
- tmp1 = vmlaq_laneq_f32(tmp1, input[1][0], k[1], 0);
- tmp2 = vmlaq_laneq_f32(tmp2, input[1][1], k[1], 1);
- tmp1 = vmlaq_laneq_f32(tmp1, input[1][2], k[1], 2);
- tmp2 = vmlaq_laneq_f32(tmp2, input[1][3], k[1], 3);
- tmp1 = vmlaq_laneq_f32(tmp1, input[2][0], k[2], 0);
- tmp2 = vmlaq_laneq_f32(tmp2, input[2][1], k[2], 1);
- tmp1 = vmlaq_laneq_f32(tmp1, input[2][2], k[2], 2);
- tmp2 = vmlaq_laneq_f32(tmp2, input[2][3], k[2], 3);
- tmp1 = vmlaq_laneq_f32(tmp1, input[3][0], k[3], 0);
- tmp2 = vmlaq_laneq_f32(tmp2, input[3][1], k[3], 1);
- tmp1 = vmlaq_laneq_f32(tmp1, input[3][2], k[3], 2);
- tmp2 = vmlaq_laneq_f32(tmp2, input[3][3], k[3], 3);
- tmp1 = vaddq_f32(tmp1, tmp2);
-
- vst1q_f32(outputData, tmp1);
- r0 += 4;
- r1 += 4;
- r2 += 4;
- r3 += 4;
- outputData += 4;
- }
-
- for (int r = 0; r < remain; r++) {
- float32x4_t i0 = vld1q_f32(r0);
- float32x4_t i1 = vld1q_f32(r1);
- float32x4_t i2 = vld1q_f32(r2);
- float32x4_t i3 = vld1q_f32(r3);
- *outputData = conv4x4(i0, i1, i2, i3, k[0], k[1], k[2], k[3]);
- r0++;
- r1++;
- r2++;
- r3++;
- outputData++;
- }
-
- r0 += 3;
- r1 += 3;
- r2 += 3;
- r3 += 3;
- }
- }
- }
-};
-
-/**
- * Each step calculates four elements of the output.
- */
-template <>
-struct DepthwiseConvKernel<4, 2> {
- static void run(const float* inputData,
- const float* filterData,
- int inputHeight,
- int inputWidth,
- int outputChannels,
- int outputHeight,
- int outputWidth,
- int filterMultiplier,
- float* outputData) {
- const int steps = outputWidth >> 2;
- const int remain = outputWidth & 3;
- for (int c = 0; c < outputChannels; c++, filterData += 16) {
- // Load the filters
- float32x4_t k[4];
- k[0] = vld1q_f32(filterData);
- k[1] = vld1q_f32(filterData + 4);
- k[2] = vld1q_f32(filterData + 8);
- k[3] = vld1q_f32(filterData + 12);
-
- const float* start =
- inputData + (c / filterMultiplier) * (inputHeight * inputWidth);
- float32x4_t input[4][4];
- for (int h = 0; h < outputHeight; h++) {
- const float* r0 = start + 2 * h * inputWidth;
- const float* r1 = start + (2 * h + 1) * inputWidth;
- const float* r2 = start + (2 * h + 2) * inputWidth;
- const float* r3 = start + (2 * h + 3) * inputWidth;
- for (int s = 0; s < steps; s++) {
- // Load the inputs
- float32x4x2_t data1;
- float32x4x2_t data2;
-
- data1 = vld2q_f32(r0);
- data2 = vld2q_f32(r0 + 8);
- input[0][0] = data1.val[0];
- input[0][1] = data1.val[1];
- input[0][2] = vextq_f32(data1.val[0], data2.val[0], 1);
- input[0][3] = vextq_f32(data1.val[1], data2.val[1], 1);
-
- data1 = vld2q_f32(r1);
- data2 = vld2q_f32(r1 + 8);
- input[1][0] = data1.val[0];
- input[1][1] = data1.val[1];
- input[1][2] = vextq_f32(data1.val[0], data2.val[0], 1);
- input[1][3] = vextq_f32(data1.val[1], data2.val[1], 1);
-
- data1 = vld2q_f32(r2);
- data2 = vld2q_f32(r2 + 8);
- input[2][0] = data1.val[0];
- input[2][1] = data1.val[1];
- input[2][2] = vextq_f32(data1.val[0], data2.val[0], 1);
- input[2][3] = vextq_f32(data1.val[1], data2.val[1], 1);
-
- data1 = vld2q_f32(r3);
- data2 = vld2q_f32(r3 + 8);
- input[3][0] = data1.val[0];
- input[3][1] = data1.val[1];
- input[3][2] = vextq_f32(data1.val[0], data2.val[0], 1);
- input[3][3] = vextq_f32(data1.val[1], data2.val[1], 1);
-
- float32x4_t tmp1 = vdupq_n_f32(0.f);
- float32x4_t tmp2 = vdupq_n_f32(0.f);
- tmp1 = vmlaq_laneq_f32(tmp1, input[0][0], k[0], 0);
- tmp2 = vmlaq_laneq_f32(tmp2, input[0][1], k[0], 1);
- tmp1 = vmlaq_laneq_f32(tmp1, input[0][2], k[0], 2);
- tmp2 = vmlaq_laneq_f32(tmp2, input[0][3], k[0], 3);
- tmp1 = vmlaq_laneq_f32(tmp1, input[1][0], k[1], 0);
- tmp2 = vmlaq_laneq_f32(tmp2, input[1][1], k[1], 1);
- tmp1 = vmlaq_laneq_f32(tmp1, input[1][2], k[1], 2);
- tmp2 = vmlaq_laneq_f32(tmp2, input[1][3], k[1], 3);
- tmp1 = vmlaq_laneq_f32(tmp1, input[2][0], k[2], 0);
- tmp2 = vmlaq_laneq_f32(tmp2, input[2][1], k[2], 1);
- tmp1 = vmlaq_laneq_f32(tmp1, input[2][2], k[2], 2);
- tmp2 = vmlaq_laneq_f32(tmp2, input[2][3], k[2], 3);
- tmp1 = vmlaq_laneq_f32(tmp1, input[3][0], k[3], 0);
- tmp2 = vmlaq_laneq_f32(tmp2, input[3][1], k[3], 1);
- tmp1 = vmlaq_laneq_f32(tmp1, input[3][2], k[3], 2);
- tmp2 = vmlaq_laneq_f32(tmp2, input[3][3], k[3], 3);
- tmp1 = vaddq_f32(tmp1, tmp2);
-
- vst1q_f32(outputData, tmp1);
- r0 += 8;
- r1 += 8;
- r2 += 8;
- r3 += 8;
- outputData += 4;
- }
-
- for (int r = 0; r < remain; r++) {
- float32x4_t i0 = vld1q_f32(r0);
- float32x4_t i1 = vld1q_f32(r1);
- float32x4_t i2 = vld1q_f32(r2);
- float32x4_t i3 = vld1q_f32(r3);
- *outputData = conv4x4(i0, i1, i2, i3, k[0], k[1], k[2], k[3]);
- r0 += 2;
- r1 += 2;
- r2 += 2;
- r3 += 2;
- outputData++;
- }
- }
- }
- }
-};
-
template
class NeonDepthwiseConvFunction : public ConvFunctionBase {
public:
@@ -497,16 +42,16 @@ public:
const TensorShape& filter = inputs[1].shape();
const TensorShape& output = outputs[0].shape();
- size_t batchSize = input[0];
- size_t inputChannels = input[1];
- size_t inputHeight = input[2];
- size_t inputWidth = input[3];
- size_t filterHeight = getFilterHeight(filter);
- size_t filterWidth = getFilterWidth(filter);
- size_t outputChannels = output[1];
- size_t outputHeight = output[2];
- size_t outputWidth = output[3];
- size_t filterMultiplier = outputChannels / groups_;
+ int batchSize = input[0];
+ int inputChannels = input[1];
+ int inputHeight = input[2];
+ int inputWidth = input[3];
+ int filterHeight = getFilterHeight(filter);
+ int filterWidth = getFilterWidth(filter);
+ int outputChannels = output[1];
+ int outputHeight = output[2];
+ int outputWidth = output[3];
+ int filterMultiplier = outputChannels / groups_;
CHECK_EQ(inputChannels, groups_);
// only support strideH() == strideW() and filterHeight == filterWidth.
@@ -519,22 +64,19 @@ public:
// padding the input
float* inputPadding = inputData;
+ int padInputHeight = inputHeight + 2 * paddingH();
+ int padInputWidth = inputWidth + 2 * paddingW();
if (paddingH() > 0 || paddingW() > 0) {
- int newSize = batchSize * inputChannels * (inputHeight + 2 * paddingH()) *
- (inputWidth + 2 * paddingW());
+ int newSize = batchSize * inputChannels * padInputHeight * padInputWidth;
resizeBuffer(newSize);
inputPadding = reinterpret_cast(memory_->getBuf());
- Padding::run(inputData,
- inputPadding,
- batchSize * inputChannels,
- inputHeight,
- inputWidth,
- paddingH(),
- paddingW());
-
- // height and width of padding data
- inputHeight += 2 * paddingH();
- inputWidth += 2 * paddingW();
+ neon::Padding::run(inputData,
+ inputPadding,
+ batchSize * inputChannels,
+ inputHeight,
+ inputWidth,
+ padInputHeight,
+ padInputWidth);
}
std::function::run;
+ DepthWiseConv = neon::DepthwiseConvKernel<3, 1>::run;
} else if (filterWidth == 3 && strideW() == 2) {
- DepthWiseConv = DepthwiseConvKernel<3, 2>::run;
+ DepthWiseConv = neon::DepthwiseConvKernel<3, 2>::run;
} else if (filterWidth == 4 && strideW() == 1) {
- DepthWiseConv = DepthwiseConvKernel<4, 1>::run;
+ DepthWiseConv = neon::DepthwiseConvKernel<4, 1>::run;
} else if (filterWidth == 4 && strideW() == 2) {
- DepthWiseConv = DepthwiseConvKernel<4, 2>::run;
+ DepthWiseConv = neon::DepthwiseConvKernel<4, 2>::run;
} else {
LOG(FATAL) << "Not supported";
}
- for (size_t i = 0; i < batchSize; i++) {
+ for (int i = 0; i < batchSize; i++) {
DepthWiseConv(inputPadding,
filterData,
- inputHeight,
- inputWidth,
+ padInputHeight,
+ padInputWidth,
outputChannels,
outputHeight,
outputWidth,
filterMultiplier,
outputData);
- inputPadding += inputChannels * inputHeight * inputWidth;
+ inputPadding += inputChannels * padInputHeight * padInputWidth;
outputData += outputChannels * outputHeight * outputWidth;
}
}
};
+#ifndef PADDLE_TYPE_DOUBLE
REGISTER_TYPED_FUNC(NeonDepthwiseConv, CPU, NeonDepthwiseConvFunction);
+#endif
#endif
-} // namespace neon
} // namespace paddle
diff --git a/paddle/function/neon/NeonDepthwiseConv.h b/paddle/function/neon/NeonDepthwiseConv.h
new file mode 100644
index 0000000000000000000000000000000000000000..aefeea78badbca3d0d09e292e4e1e148618f8ac6
--- /dev/null
+++ b/paddle/function/neon/NeonDepthwiseConv.h
@@ -0,0 +1,631 @@
+/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License. */
+
+#pragma once
+
+#include
+#include "neon_util.h"
+
+namespace paddle {
+
+namespace neon {
+
+#if defined(__ARM_NEON__) || defined(__ARM_NEON)
+
+template
+struct DepthwiseConvKernel {};
+
+inline float32_t conv3x3(float32x4_t r0,
+ float32x4_t r1,
+ float32x4_t r2,
+ float32x4_t k0,
+ float32x4_t k1,
+ float32x4_t k2) {
+ float32x4_t tmp;
+ tmp = vmulq_f32(r0, k0);
+ tmp = vmlaq_f32(tmp, r1, k1);
+ tmp = vmlaq_f32(tmp, r2, k2);
+ return vaddvq_f32(tmp);
+}
+
+inline float32_t conv4x4(float32x4_t r0,
+ float32x4_t r1,
+ float32x4_t r2,
+ float32x4_t r3,
+ float32x4_t k0,
+ float32x4_t k1,
+ float32x4_t k2,
+ float32x4_t k3) {
+ float32x4_t tmp;
+ tmp = vmulq_f32(r0, k0);
+ tmp = vmlaq_f32(tmp, r1, k1);
+ tmp = vmlaq_f32(tmp, r2, k2);
+ tmp = vmlaq_f32(tmp, r3, k3);
+ return vaddvq_f32(tmp);
+}
+
+/**
+ * Each step calculates four elements of the output.
+ * First step:
+ * R0[0, 1, 2, 3...] * K[0][0]
+ * R0[1, 2, 3, 4...] * K[0][1]
+ * R0[2, 3, 4, 5...] * K[0][2]
+ * R1[0, 1, 2, 3...] * K[1][0]
+ * R1[1, 2, 3, 4...] * K[1][1]
+ * R1[2, 3, 4, 5...] * K[1][2]
+ * R2[0, 1, 2, 3...] * K[2][0]
+ * R2[1, 2, 3, 4...] * K[2][1]
+ * + R2[2, 3, 4, 5...] * K[2][2]
+ * ------------------------------
+ * Output[0, 1, 2, 3]
+ */
+template <>
+struct DepthwiseConvKernel<3, 1> {
+ static void run(const float* inputData,
+ const float* filterData,
+ int inputHeight,
+ int inputWidth,
+ int outputChannels,
+ int outputHeight,
+ int outputWidth,
+ int filterMultiplier,
+ float* outputData) {
+ const int steps = outputWidth >> 2;
+ const int remain = outputWidth & 3;
+ for (int c = 0; c < outputChannels; c++, filterData += 9) {
+ // Load the filters
+ float32x4_t k[3];
+ k[0] = vld1q_f32(filterData);
+ k[1] = vld1q_f32(filterData + 3);
+ k[2] = vld1q_f32(filterData + 6);
+ k[0] = vsetq_lane_f32(0.f, k[0], 3);
+ k[1] = vsetq_lane_f32(0.f, k[1], 3);
+ k[2] = vsetq_lane_f32(0.f, k[2], 3);
+
+ const float* r0 =
+ inputData + (c / filterMultiplier) * (inputHeight * inputWidth);
+ const float* r1 = r0 + inputWidth;
+ const float* r2 = r0 + inputWidth * 2;
+ float32x4_t input[3][3];
+ for (int h = 0; h < outputHeight; h++) {
+ for (int s = 0; s < steps; s++) {
+ // Load the inputs
+ float32x4_t tmp;
+ input[0][0] = vld1q_f32(r0);
+ tmp = vld1q_f32(r0 + 4);
+ input[0][1] = vextq_f32(input[0][0], tmp, 1);
+ input[0][2] = vextq_f32(input[0][0], tmp, 2);
+ input[1][0] = vld1q_f32(r1);
+ tmp = vld1q_f32(r1 + 4);
+ input[1][1] = vextq_f32(input[1][0], tmp, 1);
+ input[1][2] = vextq_f32(input[1][0], tmp, 2);
+ input[2][0] = vld1q_f32(r2);
+ tmp = vld1q_f32(r2 + 4);
+ input[2][1] = vextq_f32(input[2][0], tmp, 1);
+ input[2][2] = vextq_f32(input[2][0], tmp, 2);
+
+ float32x4_t tmp1 = vdupq_n_f32(0.f);
+ float32x4_t tmp2 = vdupq_n_f32(0.f);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[0][0], k[0], 0);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[0][1], k[0], 1);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[0][2], k[0], 2);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[1][0], k[1], 0);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[1][1], k[1], 1);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[1][2], k[1], 2);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[2][0], k[2], 0);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[2][1], k[2], 1);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[2][2], k[2], 2);
+ tmp1 = vaddq_f32(tmp1, tmp2);
+
+ vst1q_f32(outputData, tmp1);
+ r0 += 4;
+ r1 += 4;
+ r2 += 4;
+ outputData += 4;
+ }
+
+ for (int r = 0; r < remain; r++) {
+ float32x4_t i0 = vld1q_f32(r0);
+ float32x4_t i1 = vld1q_f32(r1);
+ float32x4_t i2 = vld1q_f32(r2);
+ *outputData = conv3x3(i0, i1, i2, k[0], k[1], k[2]);
+ r0++;
+ r1++;
+ r2++;
+ outputData++;
+ }
+
+ r0 += 2;
+ r1 += 2;
+ r2 += 2;
+ }
+ }
+ }
+};
+
+/**
+ * Each step calculates four elements of the output.
+ * First step:
+ * R0[0, 2, 4, 6...] * K[0][0]
+ * R0[1, 3, 5, 7...] * K[0][1]
+ * R0[2, 4, 6, 8...] * K[0][2]
+ * R1[0, 2, 4, 6...] * K[1][0]
+ * R1[1, 3, 5, 7...] * K[1][1]
+ * R1[2, 4, 6, 8...] * K[1][2]
+ * R2[0, 2, 4, 6...] * K[2][0]
+ * R2[1, 3, 5, 7...] * K[2][1]
+ * R2[2, 4, 6, 8...] * K[2][2]
+ * ------------------------------
+ * Output[0, 1, 2, 3]
+ */
+template <>
+struct DepthwiseConvKernel<3, 2> {
+ static void run(const float* inputData,
+ const float* filterData,
+ int inputHeight,
+ int inputWidth,
+ int outputChannels,
+ int outputHeight,
+ int outputWidth,
+ int filterMultiplier,
+ float* outputData) {
+ const int steps = outputWidth >> 2;
+ const int remain = outputWidth & 3;
+ for (int c = 0; c < outputChannels; c++, filterData += 9) {
+ // Load the filters
+ float32x4_t k[3];
+ k[0] = vld1q_f32(filterData);
+ k[1] = vld1q_f32(filterData + 3);
+ k[2] = vld1q_f32(filterData + 6);
+ k[0] = vsetq_lane_f32(0.f, k[0], 3);
+ k[1] = vsetq_lane_f32(0.f, k[1], 3);
+ k[2] = vsetq_lane_f32(0.f, k[2], 3);
+
+ const float* start =
+ inputData + (c / filterMultiplier) * (inputHeight * inputWidth);
+ float32x4_t input[3][3];
+ for (int h = 0; h < outputHeight; h++) {
+ const float* r0 = start + 2 * h * inputWidth;
+ const float* r1 = start + (2 * h + 1) * inputWidth;
+ const float* r2 = start + (2 * h + 2) * inputWidth;
+ for (int s = 0; s < steps; s++) {
+ // Load the inputs
+ float32x4_t data1;
+ float32x4x2_t data2;
+
+ data2 = vld2q_f32(r0);
+ input[0][0] = data2.val[0];
+ input[0][1] = data2.val[1];
+ data1 = vld1q_f32(r0 + 8);
+ input[0][2] = vextq_f32(data2.val[0], data1, 1);
+
+ data2 = vld2q_f32(r1);
+ input[1][0] = data2.val[0];
+ input[1][1] = data2.val[1];
+ data1 = vld1q_f32(r1 + 8);
+ input[1][2] = vextq_f32(data2.val[0], data1, 1);
+
+ data2 = vld2q_f32(r2);
+ input[2][0] = data2.val[0];
+ input[2][1] = data2.val[1];
+ data1 = vld1q_f32(r2 + 8);
+ input[2][2] = vextq_f32(data2.val[0], data1, 1);
+
+ float32x4_t tmp1 = vdupq_n_f32(0.f);
+ float32x4_t tmp2 = vdupq_n_f32(0.f);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[0][0], k[0], 0);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[0][1], k[0], 1);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[0][2], k[0], 2);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[1][0], k[1], 0);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[1][1], k[1], 1);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[1][2], k[1], 2);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[2][0], k[2], 0);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[2][1], k[2], 1);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[2][2], k[2], 2);
+ tmp1 = vaddq_f32(tmp1, tmp2);
+
+ vst1q_f32(outputData, tmp1);
+ r0 += 8;
+ r1 += 8;
+ r2 += 8;
+ outputData += 4;
+ }
+
+ for (int r = 0; r < remain; r++) {
+ float32x4_t i0 = vld1q_f32(r0);
+ float32x4_t i1 = vld1q_f32(r1);
+ float32x4_t i2 = vld1q_f32(r2);
+ *outputData = conv3x3(i0, i1, i2, k[0], k[1], k[2]);
+ r0 += 2;
+ r1 += 2;
+ r2 += 2;
+ outputData++;
+ }
+ }
+ }
+ }
+};
+
+/**
+ * Each step calculates four elements of the output.
+ */
+template <>
+struct DepthwiseConvKernel<4, 1> {
+ static void run(const float* inputData,
+ const float* filterData,
+ int inputHeight,
+ int inputWidth,
+ int outputChannels,
+ int outputHeight,
+ int outputWidth,
+ int filterMultiplier,
+ float* outputData) {
+ const int steps = outputWidth >> 2;
+ const int remain = outputWidth & 3;
+ for (int c = 0; c < outputChannels; c++, filterData += 16) {
+ // Load the filters
+ float32x4_t k[4];
+ k[0] = vld1q_f32(filterData);
+ k[1] = vld1q_f32(filterData + 4);
+ k[2] = vld1q_f32(filterData + 8);
+ k[3] = vld1q_f32(filterData + 12);
+
+ const float* r0 =
+ inputData + (c / filterMultiplier) * (inputHeight * inputWidth);
+ const float* r1 = r0 + inputWidth;
+ const float* r2 = r0 + inputWidth * 2;
+ const float* r3 = r0 + inputWidth * 3;
+ float32x4_t input[4][4];
+ for (int h = 0; h < outputHeight; h++) {
+ for (int s = 0; s < steps; s++) {
+ // Load the inputs
+ float32x4_t tmp;
+ input[0][0] = vld1q_f32(r0);
+ tmp = vld1q_f32(r0 + 4);
+ input[0][1] = vextq_f32(input[0][0], tmp, 1);
+ input[0][2] = vextq_f32(input[0][0], tmp, 2);
+ input[0][3] = vextq_f32(input[0][0], tmp, 3);
+
+ input[1][0] = vld1q_f32(r1);
+ tmp = vld1q_f32(r1 + 4);
+ input[1][1] = vextq_f32(input[1][0], tmp, 1);
+ input[1][2] = vextq_f32(input[1][0], tmp, 2);
+ input[1][3] = vextq_f32(input[1][0], tmp, 3);
+
+ input[2][0] = vld1q_f32(r2);
+ tmp = vld1q_f32(r2 + 4);
+ input[2][1] = vextq_f32(input[2][0], tmp, 1);
+ input[2][2] = vextq_f32(input[2][0], tmp, 2);
+ input[2][3] = vextq_f32(input[2][0], tmp, 3);
+
+ input[3][0] = vld1q_f32(r3);
+ tmp = vld1q_f32(r3 + 4);
+ input[3][1] = vextq_f32(input[3][0], tmp, 1);
+ input[3][2] = vextq_f32(input[3][0], tmp, 2);
+ input[3][3] = vextq_f32(input[3][0], tmp, 3);
+
+ float32x4_t tmp1 = vdupq_n_f32(0.f);
+ float32x4_t tmp2 = vdupq_n_f32(0.f);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[0][0], k[0], 0);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[0][1], k[0], 1);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[0][2], k[0], 2);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[0][3], k[0], 3);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[1][0], k[1], 0);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[1][1], k[1], 1);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[1][2], k[1], 2);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[1][3], k[1], 3);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[2][0], k[2], 0);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[2][1], k[2], 1);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[2][2], k[2], 2);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[2][3], k[2], 3);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[3][0], k[3], 0);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[3][1], k[3], 1);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[3][2], k[3], 2);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[3][3], k[3], 3);
+ tmp1 = vaddq_f32(tmp1, tmp2);
+
+ vst1q_f32(outputData, tmp1);
+ r0 += 4;
+ r1 += 4;
+ r2 += 4;
+ r3 += 4;
+ outputData += 4;
+ }
+
+ for (int r = 0; r < remain; r++) {
+ float32x4_t i0 = vld1q_f32(r0);
+ float32x4_t i1 = vld1q_f32(r1);
+ float32x4_t i2 = vld1q_f32(r2);
+ float32x4_t i3 = vld1q_f32(r3);
+ *outputData = conv4x4(i0, i1, i2, i3, k[0], k[1], k[2], k[3]);
+ r0++;
+ r1++;
+ r2++;
+ r3++;
+ outputData++;
+ }
+
+ r0 += 3;
+ r1 += 3;
+ r2 += 3;
+ r3 += 3;
+ }
+ }
+ }
+};
+
+/**
+ * Each step calculates four elements of the output.
+ */
+template <>
+struct DepthwiseConvKernel<4, 2> {
+ static void run(const float* inputData,
+ const float* filterData,
+ int inputHeight,
+ int inputWidth,
+ int outputChannels,
+ int outputHeight,
+ int outputWidth,
+ int filterMultiplier,
+ float* outputData) {
+ const int steps = outputWidth >> 2;
+ const int remain = outputWidth & 3;
+ for (int c = 0; c < outputChannels; c++, filterData += 16) {
+ // Load the filters
+ float32x4_t k[4];
+ k[0] = vld1q_f32(filterData);
+ k[1] = vld1q_f32(filterData + 4);
+ k[2] = vld1q_f32(filterData + 8);
+ k[3] = vld1q_f32(filterData + 12);
+
+ const float* start =
+ inputData + (c / filterMultiplier) * (inputHeight * inputWidth);
+ float32x4_t input[4][4];
+ for (int h = 0; h < outputHeight; h++) {
+ const float* r0 = start + 2 * h * inputWidth;
+ const float* r1 = start + (2 * h + 1) * inputWidth;
+ const float* r2 = start + (2 * h + 2) * inputWidth;
+ const float* r3 = start + (2 * h + 3) * inputWidth;
+ for (int s = 0; s < steps; s++) {
+ // Load the inputs
+ float32x4x2_t data1;
+ float32x4x2_t data2;
+
+ data1 = vld2q_f32(r0);
+ data2 = vld2q_f32(r0 + 8);
+ input[0][0] = data1.val[0];
+ input[0][1] = data1.val[1];
+ input[0][2] = vextq_f32(data1.val[0], data2.val[0], 1);
+ input[0][3] = vextq_f32(data1.val[1], data2.val[1], 1);
+
+ data1 = vld2q_f32(r1);
+ data2 = vld2q_f32(r1 + 8);
+ input[1][0] = data1.val[0];
+ input[1][1] = data1.val[1];
+ input[1][2] = vextq_f32(data1.val[0], data2.val[0], 1);
+ input[1][3] = vextq_f32(data1.val[1], data2.val[1], 1);
+
+ data1 = vld2q_f32(r2);
+ data2 = vld2q_f32(r2 + 8);
+ input[2][0] = data1.val[0];
+ input[2][1] = data1.val[1];
+ input[2][2] = vextq_f32(data1.val[0], data2.val[0], 1);
+ input[2][3] = vextq_f32(data1.val[1], data2.val[1], 1);
+
+ data1 = vld2q_f32(r3);
+ data2 = vld2q_f32(r3 + 8);
+ input[3][0] = data1.val[0];
+ input[3][1] = data1.val[1];
+ input[3][2] = vextq_f32(data1.val[0], data2.val[0], 1);
+ input[3][3] = vextq_f32(data1.val[1], data2.val[1], 1);
+
+ float32x4_t tmp1 = vdupq_n_f32(0.f);
+ float32x4_t tmp2 = vdupq_n_f32(0.f);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[0][0], k[0], 0);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[0][1], k[0], 1);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[0][2], k[0], 2);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[0][3], k[0], 3);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[1][0], k[1], 0);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[1][1], k[1], 1);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[1][2], k[1], 2);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[1][3], k[1], 3);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[2][0], k[2], 0);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[2][1], k[2], 1);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[2][2], k[2], 2);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[2][3], k[2], 3);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[3][0], k[3], 0);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[3][1], k[3], 1);
+ tmp1 = vmlaq_laneq_f32(tmp1, input[3][2], k[3], 2);
+ tmp2 = vmlaq_laneq_f32(tmp2, input[3][3], k[3], 3);
+ tmp1 = vaddq_f32(tmp1, tmp2);
+
+ vst1q_f32(outputData, tmp1);
+ r0 += 8;
+ r1 += 8;
+ r2 += 8;
+ r3 += 8;
+ outputData += 4;
+ }
+
+ for (int r = 0; r < remain; r++) {
+ float32x4_t i0 = vld1q_f32(r0);
+ float32x4_t i1 = vld1q_f32(r1);
+ float32x4_t i2 = vld1q_f32(r2);
+ float32x4_t i3 = vld1q_f32(r3);
+ *outputData = conv4x4(i0, i1, i2, i3, k[0], k[1], k[2], k[3]);
+ r0 += 2;
+ r1 += 2;
+ r2 += 2;
+ r3 += 2;
+ outputData++;
+ }
+ }
+ }
+ }
+};
+
+template
+struct Padding {
+ static void run(const T* input,
+ T* inputPadding,
+ int channels,
+ int inputHeight,
+ int inputWidth,
+ int padInputHeight,
+ int padInputWidth) {
+ const int paddingHeight = (padInputHeight - inputHeight) / 2;
+ const int paddingWidth = (padInputWidth - inputWidth) / 2;
+ for (int c = 0; c < channels; c++) {
+ if (paddingHeight > 0) {
+ memset(inputPadding, 0, padInputWidth * paddingHeight * sizeof(T));
+ inputPadding += padInputWidth * paddingHeight;
+ }
+
+ for (int i = 0; i < inputHeight; i++) {
+ // padding head
+ for (int j = 0; j < paddingWidth; j++) {
+ *inputPadding++ = T(0);
+ }
+
+ memcpy(inputPadding, input, inputWidth * sizeof(T));
+ inputPadding += inputWidth;
+ input += inputWidth;
+
+ // padding tail
+ for (int j = 0; j < paddingWidth; j++) {
+ *inputPadding++ = T(0);
+ }
+ }
+
+ if (paddingHeight > 0) {
+ memset(inputPadding, 0, padInputWidth * paddingHeight * sizeof(T));
+ inputPadding += padInputWidth * paddingHeight;
+ }
+ }
+ }
+};
+
+#if defined(__ARM_NEON__) || defined(__ARM_NEON)
+template <>
+struct Padding {
+ static void run(const float* input,
+ float* inputPadding,
+ int channels,
+ int inputHeight,
+ int inputWidth,
+ int padInputHeight,
+ int padInputWidth) {
+ const int paddingHeight = (padInputHeight - inputHeight) / 2;
+ const int paddingWidth = (padInputWidth - inputWidth) / 2;
+ for (int c = 0; c < channels; c++) {
+ if (paddingHeight > 0) {
+ memset(inputPadding, 0, padInputWidth * paddingHeight * sizeof(float));
+ inputPadding += padInputWidth * paddingHeight;
+ }
+
+ for (int i = 0; i < inputHeight; i++) {
+ // padding head
+ for (int j = 0; j < paddingWidth; j++) {
+ *inputPadding++ = float(0);
+ }
+
+ int step = inputWidth >> 2;
+ int remain = inputWidth & 3;
+ for (int s = 0; s < step; s++) {
+ float32x4_t s0 = vld1q_f32(input);
+ vst1q_f32(inputPadding, s0);
+ input += 4;
+ inputPadding += 4;
+ }
+ for (int r = 0; r < remain; r++) {
+ *inputPadding++ = *input++;
+ }
+
+ // padding tail
+ for (int j = 0; j < paddingWidth; j++) {
+ *inputPadding++ = float(0);
+ }
+ }
+
+ if (paddingHeight > 0) {
+ memset(inputPadding, 0, padInputWidth * paddingHeight * sizeof(float));
+ inputPadding += padInputWidth * paddingHeight;
+ }
+ }
+ }
+};
+
+// for stride is 2
+struct StridePadding {
+ static void run(const float* input,
+ float* inputPadding,
+ int channels,
+ int inputHeight,
+ int inputWidth,
+ int padInputHeight,
+ int padInputWidth) {
+ const int paddingHeight = (padInputHeight - (inputHeight * 2 - 1)) / 2;
+ const int paddingWidth = (padInputWidth - (inputWidth * 2 - 1)) / 2;
+ for (int c = 0; c < channels; c++) {
+ if (paddingHeight > 0) {
+ memset(inputPadding, 0, padInputWidth * paddingHeight * sizeof(float));
+ inputPadding += padInputWidth * paddingHeight;
+ }
+
+ for (int i = 0; i < inputHeight; i++) {
+ // padding head
+ for (int j = 0; j < paddingWidth; j++) {
+ *inputPadding++ = float(0);
+ }
+
+ int step = inputWidth >> 2;
+ int remain = inputWidth & 3;
+ float32x4_t s1 = vdupq_n_f32(0.f);
+ for (int s = 0; s < step; s++) {
+ float32x4_t s0 = vld1q_f32(input);
+ float32x4x2_t v = {s0, s1};
+ vst2q_f32(inputPadding, v);
+ input += 4;
+ inputPadding += 8;
+ }
+ for (int r = 0; r < remain; r++) {
+ *inputPadding++ = *input++;
+ *inputPadding++ = float(0);
+ }
+ inputPadding--;
+
+ // padding tail
+ for (int j = 0; j < paddingWidth; j++) {
+ *inputPadding++ = float(0);
+ }
+ if (i != inputHeight - 1) {
+ memset(inputPadding, 0, padInputWidth * sizeof(float));
+ inputPadding += padInputWidth;
+ }
+ }
+
+ if (paddingHeight > 0) {
+ memset(inputPadding, 0, padInputWidth * paddingHeight * sizeof(float));
+ inputPadding += padInputWidth * paddingHeight;
+ }
+ }
+ }
+};
+
+#endif
+
+#endif
+
+} // namespace neon
+} // namespace paddle
diff --git a/paddle/function/neon/NeonDepthwiseConvTranspose.cpp b/paddle/function/neon/NeonDepthwiseConvTranspose.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..49ca4bc8a0947ba329bd991e9f7d001623901a67
--- /dev/null
+++ b/paddle/function/neon/NeonDepthwiseConvTranspose.cpp
@@ -0,0 +1,136 @@
+/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License. */
+
+#include "NeonDepthwiseConv.h"
+#include "paddle/function/ConvOp.h"
+
+namespace paddle {
+
+#if defined(__ARM_NEON__) || defined(__ARM_NEON)
+
+template
+class NeonDepthwiseConvTransposeFunction : public ConvFunctionBase {
+public:
+ void init(const FuncConfig& config) override {
+ ConvFunctionBase::init(config);
+ }
+
+ void check(const BufferArgs& inputs, const BufferArgs& outputs) override {
+ const TensorShape& input = inputs[0].shape();
+ const TensorShape& filter = inputs[1].shape();
+ const TensorShape& output = outputs[0].shape();
+ checkShape(input, filter, output);
+ }
+
+ void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
+ CHECK_EQ(numInputs_, inputs.size());
+ CHECK_EQ(numOutputs_, outputs.size());
+ check(inputs, outputs);
+
+ const TensorShape& input = inputs[0].shape();
+ const TensorShape& filter = inputs[1].shape();
+ const TensorShape& output = outputs[0].shape();
+
+ int batchSize = input[0];
+ int inputChannels = input[1];
+ int inputHeight = input[2];
+ int inputWidth = input[3];
+ int filterHeight = getFilterHeight(filter);
+ int filterWidth = getFilterWidth(filter);
+ int outputChannels = output[1];
+ int outputHeight = output[2];
+ int outputWidth = output[3];
+ int filterMultiplier = outputChannels / groups_;
+ CHECK_EQ(inputChannels, groups_);
+
+ // only support strideH() == strideW() and filterHeight == filterWidth.
+ CHECK_EQ(strideH(), strideW());
+ CHECK_EQ(paddingH(), paddingW());
+ CHECK_EQ(filterHeight, filterWidth);
+
+ float* inputData = inputs[0].data();
+ float* filterData = inputs[1].data();
+ float* outputData = outputs[0].data();
+
+ // padding the input, input -> inputPadding
+ float* inputPadding = inputData;
+ int padInputHeight =
+ (inputHeight - 1) * strideH() + 2 * filterHeight - 1 - 2 * paddingH();
+ int padInputWidth =
+ (inputWidth - 1) * strideW() + 2 * filterWidth - 1 - 2 * paddingW();
+
+ if (padInputHeight > inputHeight || padInputWidth > inputWidth) {
+ int newSize = batchSize * inputChannels * padInputHeight * padInputWidth;
+ resizeBuffer(newSize);
+ inputPadding = reinterpret_cast(memory_->getBuf());
+ if (strideH() == 1) {
+ neon::Padding::run(inputData,
+ inputPadding,
+ batchSize * inputChannels,
+ inputHeight,
+ inputWidth,
+ padInputHeight,
+ padInputWidth);
+ } else if (strideH() == 2) {
+ neon::StridePadding::run(inputData,
+ inputPadding,
+ batchSize * inputChannels,
+ inputHeight,
+ inputWidth,
+ padInputHeight,
+ padInputWidth);
+ } else {
+ LOG(FATAL) << "Not supported";
+ }
+ }
+
+ std::function
+ DepthWiseConv;
+
+ if (filterWidth == 3) {
+ DepthWiseConv = neon::DepthwiseConvKernel<3, 1>::run;
+ } else if (filterWidth == 4) {
+ DepthWiseConv = neon::DepthwiseConvKernel<4, 1>::run;
+ } else {
+ LOG(FATAL) << "Not supported";
+ }
+
+ for (int i = 0; i < batchSize; i++) {
+ DepthWiseConv(inputPadding,
+ filterData,
+ padInputHeight,
+ padInputWidth,
+ outputChannels,
+ outputHeight,
+ outputWidth,
+ filterMultiplier,
+ outputData);
+ inputPadding += inputChannels * padInputHeight * padInputWidth;
+ outputData += outputChannels * outputHeight * outputWidth;
+ }
+ }
+};
+
+#ifndef PADDLE_TYPE_DOUBLE
+
+REGISTER_TYPED_FUNC(NeonDepthwiseConvTranspose,
+ CPU,
+ NeonDepthwiseConvTransposeFunction);
+
+#endif
+
+#endif
+
+} // namespace paddle
diff --git a/paddle/function/neon/neon_util.h b/paddle/function/neon/neon_util.h
index 56b3febe2d27bb4fbf57e49079b3ad071d556914..e2db0450675084345ad55559d8988c5375801cc9 100644
--- a/paddle/function/neon/neon_util.h
+++ b/paddle/function/neon/neon_util.h
@@ -33,12 +33,8 @@ inline float32_t vaddvq_f32(float32x4_t a) {
return vget_lane_f32(vpadd_f32(v, v), 0);
}
-inline float32x4_t vmlaq_laneq_f32(float32x4_t a,
- float32x4_t b,
- float32x4_t v,
- const int lane) {
- return vmlaq_n_f32(a, b, vgetq_lane_f32(v, lane));
-}
+#define vmlaq_laneq_f32(a, b, v, lane) \
+ vmlaq_n_f32(a, b, vgetq_lane_f32(v, lane))
#endif
} // namespace neon
diff --git a/paddle/gserver/layers/BatchNormBaseLayer.cpp b/paddle/gserver/layers/BatchNormBaseLayer.cpp
index 1ceaaaa206ee3cbc5421238574c7f310011ccaa5..f7a80e23e1bd49549bec57b360587adc6b423794 100644
--- a/paddle/gserver/layers/BatchNormBaseLayer.cpp
+++ b/paddle/gserver/layers/BatchNormBaseLayer.cpp
@@ -62,14 +62,18 @@ void BatchNormBaseLayer::calFeatureMapSize() {
const ImageConfig& conf = config_.inputs(0).image_conf();
imageH_ = inputLayers_[0]->getOutput().getFrameHeight();
imageW_ = inputLayers_[0]->getOutput().getFrameWidth();
+ imageD_ = inputLayers_[0]->getOutput().getFrameDepth();
+
+ if (0 == imageD_) imageD_ = conf.img_size_z();
if (imageH_ == 0 && imageW_ == 0) {
imageH_ = conf.has_img_size_y() ? conf.img_size_y() : conf.img_size();
imageW_ = conf.img_size();
} else {
getOutput().setFrameHeight(imageH_);
getOutput().setFrameWidth(imageW_);
+ getOutput().setFrameDepth(imageD_);
}
- imgPixels_ = imageH_ * imageW_;
+ imgPixels_ = imageH_ * imageW_ * imageD_;
}
} // namespace paddle
diff --git a/paddle/gserver/layers/BatchNormBaseLayer.h b/paddle/gserver/layers/BatchNormBaseLayer.h
index 230bafc31d96bbd49481a7ed135be6888688627e..e721d2d267a31cae46407673b8b1281e87055608 100644
--- a/paddle/gserver/layers/BatchNormBaseLayer.h
+++ b/paddle/gserver/layers/BatchNormBaseLayer.h
@@ -80,6 +80,7 @@ protected:
/// Height or width of input image feature.
/// Both of them are 1 if the input is fully-connected layer.
+ int imageD_;
int imageH_;
int imageW_;
/// Height * Width.
diff --git a/paddle/gserver/layers/Conv3DLayer.cpp b/paddle/gserver/layers/Conv3DLayer.cpp
index 3887aa58b283d319c5b9afec3a38ad676669a8d1..9deda2de989a55d34510560c49b213ea1a52fd07 100644
--- a/paddle/gserver/layers/Conv3DLayer.cpp
+++ b/paddle/gserver/layers/Conv3DLayer.cpp
@@ -83,8 +83,8 @@ void Conv3DLayer::forward(PassType passType) {
int outWidth = getSize();
resetOutput(batchSize, outWidth);
+ REGISTER_TIMER_INFO("FwdConv3D", getName().c_str());
for (size_t i = 0; i != inputLayers_.size(); ++i) {
- REGISTER_TIMER_INFO("FwdConv3D", getName().c_str());
const MatrixPtr &inMat = getInputValue(i);
const MatrixPtr &outMat = getOutputValue();
int M = M_[i];
@@ -120,7 +120,6 @@ void Conv3DLayer::forward(PassType passType) {
}
}
if (nullptr != this->biasParameter_) {
- REGISTER_TIMER_INFO("FwBiasTimer", getName().c_str());
this->addBias();
}
forwardActivation();
@@ -134,15 +133,14 @@ void Conv3DLayer::backward(const UpdateCallback &callback) {
biases_->getParameterPtr()->incUpdate(callback);
}
+ REGISTER_TIMER_INFO("BwdConv3D", getName().c_str());
for (size_t i = 0; i != inputLayers_.size(); ++i) {
- REGISTER_TIMER_INFO("BwdConv3D", getName().c_str());
if (weights_[i]->getWGrad()) {
bpropWeights(i);
}
if (getInputGrad(i)) {
bpropData(i);
}
- REGISTER_TIMER_INFO("WeightUpdate", getName().c_str());
weights_[i]->getParameterPtr()->incUpdate(callback);
}
}
diff --git a/paddle/gserver/layers/CudnnBatchNormLayer.cpp b/paddle/gserver/layers/CudnnBatchNormLayer.cpp
index 44ba2c4b7d1562d2ce839b5f4b4de1af35e6925f..49a9540c0b6e36b59ed786287ff5c4569b69a6a5 100644
--- a/paddle/gserver/layers/CudnnBatchNormLayer.cpp
+++ b/paddle/gserver/layers/CudnnBatchNormLayer.cpp
@@ -37,7 +37,7 @@ bool CudnnBatchNormLayer::init(const LayerMap& layerMap,
}
void CudnnBatchNormLayer::reshape(int batchSize) {
- hl_tensor_reshape(ioDesc_, batchSize, channels_, imageH_, imageW_);
+ hl_tensor_reshape(ioDesc_, batchSize, channels_, imageH_ * imageD_, imageW_);
}
void CudnnBatchNormLayer::forward(PassType passType) {
@@ -104,7 +104,7 @@ void CudnnBatchNormLayer::forward(PassType passType) {
EPS,
batchSize,
channels_,
- imageH_,
+ imageH_ * imageD_,
imageW_);
}
}
diff --git a/paddle/gserver/layers/DeConv3DLayer.cpp b/paddle/gserver/layers/DeConv3DLayer.cpp
index 2838980a973d3dbcce9716f21f2ea07e3a2fa660..3eea638649e8ebfdd7efa18615977a9e1344c695 100644
--- a/paddle/gserver/layers/DeConv3DLayer.cpp
+++ b/paddle/gserver/layers/DeConv3DLayer.cpp
@@ -53,27 +53,27 @@ bool DeConv3DLayer::init(const LayerMap &layerMap,
size_t DeConv3DLayer::getSize() {
CHECK_NE(inputLayers_.size(), 0UL);
- outputH_.clear();
- outputW_.clear();
- outputD_.clear();
+ imgSizeW_.clear();
+ imgSizeH_.clear();
+ imgSizeD_.clear();
N_.clear();
NOut_.clear();
size_t layerSize = 0;
for (size_t i = 0; i < inputLayers_.size(); ++i) {
- outputW_.push_back(
- imageSize(imgSizeW_[i], filterSize_[i], padding_[i], stride_[i], true));
- outputH_.push_back(imageSize(
- imgSizeH_[i], filterSizeY_[i], paddingY_[i], strideY_[i], true));
- outputD_.push_back(imageSize(
- imgSizeD_[i], filterSizeZ_[i], paddingZ_[i], strideZ_[i], true));
- NOut_.push_back(outputD_[i] * outputH_[i] * outputW_[i]);
- N_.push_back(imgSizeD_[i] * imgSizeH_[i] * imgSizeW_[i]);
+ imgSizeW_.push_back(
+ imageSize(outputW_[i], filterSize_[i], padding_[i], stride_[i], true));
+ imgSizeH_.push_back(imageSize(
+ outputH_[i], filterSizeY_[i], paddingY_[i], strideY_[i], true));
+ imgSizeD_.push_back(imageSize(
+ outputD_[i], filterSizeZ_[i], paddingZ_[i], strideZ_[i], true));
+ NOut_.push_back(imgSizeD_[i] * imgSizeH_[i] * imgSizeW_[i]);
+ N_.push_back(outputD_[i] * outputH_[i] * outputW_[i]);
CHECK(layerSize == 0 || N_[i] * size_t(numFilters_) == layerSize);
layerSize += NOut_[i] * numFilters_;
}
- getOutput().setFrameHeight(outputH_[0]);
- getOutput().setFrameWidth(outputW_[0]);
- getOutput().setFrameDepth(outputD_[0]);
+ getOutput().setFrameHeight(imgSizeH_[0]);
+ getOutput().setFrameWidth(imgSizeW_[0]);
+ getOutput().setFrameDepth(imgSizeD_[0]);
return layerSize;
}
@@ -84,8 +84,8 @@ void DeConv3DLayer::forward(PassType passType) {
resetOutput(batchSize, outWidth);
const MatrixPtr outMat = getOutputValue();
+ REGISTER_TIMER_INFO("FwdDeConv3D", getName().c_str());
for (size_t i = 0; i != inputLayers_.size(); ++i) {
- REGISTER_TIMER_INFO("FwdDeConv3D", getName().c_str());
const MatrixPtr &inMat = getInputValue(i);
int M = M_[i];
int N = N_[i];
@@ -103,9 +103,9 @@ void DeConv3DLayer::forward(PassType passType) {
}
colBuf_->col2Vol(outMat->getData() + n * outMat->getStride(),
numFilters_,
- outputD_[i],
- outputH_[i],
- outputW_[i],
+ imgSizeD_[i],
+ imgSizeH_[i],
+ imgSizeW_[i],
filterSizeZ_[i],
filterSizeY_[i],
filterSize_[i],
@@ -120,7 +120,6 @@ void DeConv3DLayer::forward(PassType passType) {
}
}
if (nullptr != this->biasParameter_) {
- REGISTER_TIMER_INFO("FwBiasTimer", getName().c_str());
this->addBias();
}
forwardActivation();
@@ -133,21 +132,21 @@ void DeConv3DLayer::backward(const UpdateCallback &callback) {
bpropBiases();
biases_->getParameterPtr()->incUpdate(callback);
}
+ REGISTER_TIMER_INFO("BwdDeConv3D", getName().c_str());
for (size_t i = 0; i < inputLayers_.size(); ++i) {
if (weights_[i]->getWGrad() || this->needGradient_) {
int M = M_[i];
int N = N_[i];
int K = K_[i];
- REGISTER_TIMER_INFO("BwdDeConv3D", getName().c_str());
Matrix::resizeOrCreate(colBuf_, K * groups_[i], N, false, useGpu_);
const MatrixPtr &inMat = getInputValue(i);
for (int n = 0; n < batchSize; ++n) {
colBuf_->vol2Col(
getOutputGrad()->getData() + n * getOutputGrad()->getStride(),
numFilters_,
- outputD_[i],
- outputH_[i],
- outputW_[i],
+ imgSizeD_[i],
+ imgSizeH_[i],
+ imgSizeW_[i],
filterSizeZ_[i],
filterSizeY_[i],
filterSize_[i],
@@ -182,7 +181,6 @@ void DeConv3DLayer::backward(const UpdateCallback &callback) {
}
}
}
- REGISTER_TIMER_INFO("WeightUpdate", getName().c_str());
weights_[i]->getParameterPtr()->incUpdate(callback);
}
}
diff --git a/paddle/gserver/layers/DetectionOutputLayer.cpp b/paddle/gserver/layers/DetectionOutputLayer.cpp
index 8ab838e191314ab25469631626c0b0564d7fffda..0cf0a92bf4bd8f9b8eba2016b2377d9dfb18c70a 100644
--- a/paddle/gserver/layers/DetectionOutputLayer.cpp
+++ b/paddle/gserver/layers/DetectionOutputLayer.cpp
@@ -139,7 +139,13 @@ void DetectionOutputLayer::forward(PassType passType) {
allDecodedBBoxes,
&allIndices);
- resetOutput(numKept, 7);
+ if (numKept > 0) {
+ resetOutput(numKept, 7);
+ } else {
+ MatrixPtr outV = getOutputValue();
+ outV = NULL;
+ return;
+ }
MatrixPtr outV = getOutputValue();
getDetectionOutput(confBuffer_->getData(),
numKept,
diff --git a/paddle/gserver/layers/DetectionUtil.cpp b/paddle/gserver/layers/DetectionUtil.cpp
index 3e61adc66e60c54250e4f323452aa13045310879..d83674f45a70212a8adc94a31ff58eb0e01baa00 100644
--- a/paddle/gserver/layers/DetectionUtil.cpp
+++ b/paddle/gserver/layers/DetectionUtil.cpp
@@ -469,7 +469,7 @@ size_t getDetectionIndices(
const size_t numClasses,
const size_t backgroundId,
const size_t batchSize,
- const size_t confThreshold,
+ const real confThreshold,
const size_t nmsTopK,
const real nmsThreshold,
const size_t keepTopK,
diff --git a/paddle/gserver/layers/DetectionUtil.h b/paddle/gserver/layers/DetectionUtil.h
index fe4f9f075e4cf011c97f68f49598a828d62327b3..641ed873b4c8645b6455e5ef5e63593e3005b770 100644
--- a/paddle/gserver/layers/DetectionUtil.h
+++ b/paddle/gserver/layers/DetectionUtil.h
@@ -275,7 +275,7 @@ size_t getDetectionIndices(
const size_t numClasses,
const size_t backgroundId,
const size_t batchSize,
- const size_t confThreshold,
+ const real confThreshold,
const size_t nmsTopK,
const real nmsThreshold,
const size_t keepTopK,
diff --git a/paddle/gserver/layers/GruCompute.cpp b/paddle/gserver/layers/GruCompute.cpp
index 06907768e98f4bad952706cffbbd65d1f86cc6df..148516391c6cad8feff34b9bd1c10c27d1a8a0e6 100644
--- a/paddle/gserver/layers/GruCompute.cpp
+++ b/paddle/gserver/layers/GruCompute.cpp
@@ -14,6 +14,7 @@ limitations under the License. */
#include "GruCompute.h"
#include "hl_recurrent_apply.cuh"
+#include "paddle/function/GruFunctor.h"
#include "paddle/utils/Util.h"
namespace paddle {
@@ -25,13 +26,13 @@ void GruCompute::init(LayerConfig &config) {
template <>
void GruCompute::forward<0>(hl_gru_value value, int frameSize, int batchSize) {
- hl_cpu_gru_forward(hppl::forward::gru_resetOutput(),
- hppl::forward::gru_finalOutput(),
- value,
- frameSize,
- batchSize,
- activeNode_,
- activeGate_);
+ GruFunctor::compute(hppl::forward::gru_resetOutput(),
+ hppl::forward::gru_finalOutput(),
+ value,
+ frameSize,
+ batchSize,
+ activeNode_,
+ activeGate_);
}
template <>
@@ -39,14 +40,15 @@ void GruCompute::backward<0>(hl_gru_value value,
hl_gru_grad grad,
int frameSize,
int batchSize) {
- hl_cpu_gru_backward(hppl::backward::gru_stateGrad(),
- hppl::backward::gru_resetGrad(),
- value,
- grad,
- frameSize,
- batchSize,
- activeNode_,
- activeGate_);
+ GruGradFunctor::compute(
+ hppl::backward::gru_stateGrad(),
+ hppl::backward::gru_resetGrad(),
+ value,
+ grad,
+ frameSize,
+ batchSize,
+ activeNode_,
+ activeGate_);
}
} // namespace paddle
diff --git a/paddle/gserver/layers/Layer.h b/paddle/gserver/layers/Layer.h
index edef36194aabdb9c122ec3423deb036169a34d7c..4002a3d0747a86ab7b495ffe52247521831b71b8 100644
--- a/paddle/gserver/layers/Layer.h
+++ b/paddle/gserver/layers/Layer.h
@@ -49,6 +49,12 @@ struct LayerState {
};
typedef std::shared_ptr LayerStatePtr;
+/// Paddle device ID, MKLDNN is -2, CPU is -1
+enum PADDLE_DEVICE_ID {
+ MKLDNN_DEVICE = -2,
+ CPU_DEVICE = -1,
+};
+
/**
* @brief Base class for layer.
* Define necessary variables and functions for every layer.
@@ -59,11 +65,6 @@ protected:
LayerConfig config_;
/// whether to use GPU
bool useGpu_;
- /// Paddle device ID, MKLDNN is -2, CPU is -1
- enum PADDLE_DEVICE_ID {
- MKLDNN_DEVICE = -2,
- CPU_DEVICE = -1,
- };
/// Device Id. MKLDNN is -2, CPU is -1, and GPU is 0, 1, 2 ...
int deviceId_;
/// Input layers
diff --git a/paddle/gserver/layers/MKLDNNFcLayer.cpp b/paddle/gserver/layers/MKLDNNFcLayer.cpp
index 8318c8c519a4cec1610eadd28320ee5ce0b4147d..f70343251ad4fbb99f9614618f6d1bff1174f15e 100644
--- a/paddle/gserver/layers/MKLDNNFcLayer.cpp
+++ b/paddle/gserver/layers/MKLDNNFcLayer.cpp
@@ -14,7 +14,6 @@ limitations under the License. */
#include "MKLDNNFcLayer.h"
#include "paddle/utils/Logging.h"
-#include "paddle/utils/Stat.h"
using namespace mkldnn; // NOLINT
typedef memory::format format;
@@ -40,6 +39,8 @@ bool MKLDNNFcLayer::init(const LayerMap& layerMap,
oc_ = getSize();
oh_ = 1;
ow_ = 1;
+ ih_ = 1;
+ iw_ = 1;
// input size can not change in FC
iLayerSize_ = inputLayers_[0]->getSize();
@@ -77,111 +78,86 @@ void MKLDNNFcLayer::convertWeightsToPaddle() {
wgtVal_->reorderDataTo(wgtVal_, dstFmt, targetDim);
}
-void MKLDNNFcLayer::convertOutputToOtherDevice() {
- copyOutputInfoToOtherDevice();
- // find other cpu device and reorder output to cpu device
- int cnt = 0;
- for (size_t i = 0; i < outputOtherDevice_.size(); i++) {
- if (outputOtherDevice_[i].deviceId == CPU_DEVICE) {
- // fc cpu output value do not need convert
- // just share point
- outputOtherDevice_[i].value = output_.value;
- ++cnt;
- }
- }
-
- if (cnt > 1) {
- LOG(WARNING) << "should not have more than one CPU devie";
- }
-}
+void MKLDNNFcLayer::reshape(
+ int& bs, int& ic, int& ih, int& iw, int oc, int& oh, int& ow) {
+ reshapeInput(bs, ih, iw);
-void MKLDNNFcLayer::reshape() {
- const Argument& input = getInput(0, getPrev(0)->getDeviceId());
- int batchSize = input.getBatchSize();
- if (bs_ == batchSize) {
- return;
- }
- bs_ = batchSize;
- ih_ = input.getFrameHeight();
- iw_ = input.getFrameWidth();
- if (ih_ == 0) {
- ih_ = 1;
- }
- if (iw_ == 0) {
- iw_ = 1;
- }
CHECK_EQ(iLayerSize_, inputLayers_[0]->getSize());
- ic_ = iLayerSize_ / (ih_ * iw_);
- CHECK_EQ(size_t(ic_ * ih_ * iw_), iLayerSize_) << "not divisible";
- CHECK_EQ(size_t(oc_), getSize());
- printSizeInfo();
+ ic = iLayerSize_ / (ih * iw);
+ CHECK_EQ(size_t(ic * ih * iw), iLayerSize_) << "not divisible";
+ CHECK_EQ(size_t(oc), getSize());
- // reset output
- output_.setFrameHeight(oh_);
- output_.setFrameWidth(ow_);
- resetOutput(bs_, oc_);
+ reshapeOutput(oh, ow);
+ resizeOutput(bs, oc);
- // reset mkldnn forward
- resetFwd();
- needResetBwd_ = true;
-
- convertWeightsFromPaddle();
+ printSizeInfo();
}
-void MKLDNNFcLayer::resetFwd() {
+void MKLDNNFcLayer::resetFwd(std::vector& pipeline,
+ MKLDNNMatrixPtr& in,
+ MKLDNNMatrixPtr& wgt,
+ MKLDNNMatrixPtr& bias,
+ MKLDNNMatrixPtr& out) {
+ pipeline.clear();
bool hasBias = biases_ && biases_->getW();
- const MatrixPtr& wgt = weight_->getW();
- const MatrixPtr& bias = hasBias ? biases_->getW() : nullptr;
- const MatrixPtr& out = output_.value;
+ const MatrixPtr& wgtVal = weight_->getW();
+ const MatrixPtr& biasVal = hasBias ? biases_->getW() : nullptr;
+ const MatrixPtr& outVal = output_.value;
if (inputIsOnlyMKLDNN()) {
- const MatrixPtr& in = getInputValue(0);
- inVal_ = std::dynamic_pointer_cast(in);
- CHECK(inVal_) << "Input should be MKLDNNMatrix";
+ const MatrixPtr& inVal = getInputValue(0);
+ in = std::dynamic_pointer_cast(inVal);
+ CHECK(in) << "Input should be MKLDNNMatrix";
} else {
CHECK_EQ(getPrev(0)->getDeviceId(), CPU_DEVICE) << "Only support CPU yet";
- const MatrixPtr& in = getInputValue(0, CPU_DEVICE);
- inVal_ = MKLDNNMatrix::create(
- in, memory::dims{bs_, ic_, ih_, iw_}, format::nchw, engine_);
- }
- inVal_->downSpatial();
- wgtVal_ = MKLDNNMatrix::create(
- wgt, memory::dims{oc_, ic_, ih_, iw_}, format::oihw, engine_);
- wgtVal_->downSpatial();
- biasVal_ =
- hasBias ? MKLDNNMatrix::create(bias, {oc_}, format::x, engine_) : nullptr;
- outVal_ = MKLDNNMatrix::create(out, {bs_, oc_}, format::nc, engine_);
+ const MatrixPtr& inVal = getInputValue(0, CPU_DEVICE);
+ in = MKLDNNMatrix::create(
+ inVal, memory::dims{bs_, ic_, ih_, iw_}, format::nchw, engine_);
+ }
+ in->downSpatial();
+ wgt = MKLDNNMatrix::create(
+ wgtVal, memory::dims{oc_, ic_, ih_, iw_}, format::oihw, engine_);
+ wgt->downSpatial();
+ bias = hasBias ? MKLDNNMatrix::create(biasVal, {oc_}, format::x, engine_)
+ : nullptr;
+ out = MKLDNNMatrix::create(outVal, {bs_, oc_}, format::nc, engine_);
// change original output value to mkldnn output value
- output_.value = std::dynamic_pointer_cast(outVal_);
+ output_.value = std::dynamic_pointer_cast(out);
if (!outputIsOnlyMKLDNN()) {
- convertOutputToOtherDevice();
+ // fc cpu output value do not need create convert
+ // just share point
+ getOutput(CPU_DEVICE).value->setData(output_.value->getData());
}
// create forward handle
prop_kind pk = prop_kind::forward;
fc_fwd::desc fwdDesc = hasBias ? fc_fwd::desc(pk,
- inVal_->getMemoryDesc(),
- wgtVal_->getMemoryDesc(),
- biasVal_->getMemoryDesc(),
- outVal_->getMemoryDesc())
+ in->getMemoryDesc(),
+ wgt->getMemoryDesc(),
+ bias->getMemoryDesc(),
+ out->getMemoryDesc())
: fc_fwd::desc(pk,
- inVal_->getMemoryDesc(),
- wgtVal_->getMemoryDesc(),
- outVal_->getMemoryDesc());
+ in->getMemoryDesc(),
+ wgt->getMemoryDesc(),
+ out->getMemoryDesc());
fc_fwd::primitive_desc fwdPD = fc_fwd::primitive_desc(fwdDesc, engine_);
if (hasBias) {
- fwd_.reset(new fc_fwd(fwdPD, *inVal_, *wgtVal_, *biasVal_, *outVal_));
+ fwd_.reset(new fc_fwd(fwdPD, *in, *wgt, *bias, *out));
} else {
- fwd_.reset(new fc_fwd(fwdPD, *inVal_, *wgtVal_, *outVal_));
+ fwd_.reset(new fc_fwd(fwdPD, *in, *wgt, *out));
}
printValueFormatFlow();
- pipelineFwd_.clear();
- pipelineFwd_.push_back(*fwd_);
+ pipeline.push_back(*fwd_);
}
-void MKLDNNFcLayer::resetBwd() {
+void MKLDNNFcLayer::resetBwd(std::vector& pipeline,
+ MKLDNNMatrixPtr& in,
+ MKLDNNMatrixPtr& wgt,
+ MKLDNNMatrixPtr& bias,
+ MKLDNNMatrixPtr& out) {
+ pipeline.clear();
if (!needResetBwd_) {
return;
}
@@ -190,8 +166,8 @@ void MKLDNNFcLayer::resetBwd() {
/// backward weight
CHECK(inVal_) << "Should have input value";
- const MatrixPtr& wgt = weight_->getWGrad();
- const MatrixPtr& bias = hasBias ? biases_->getWGrad() : nullptr;
+ const MatrixPtr& wgtGrad = weight_->getWGrad();
+ const MatrixPtr& biasGrad = hasBias ? biases_->getWGrad() : nullptr;
// TODO(TJ): merge outgrad
int device = outputIsOnlyMKLDNN() ? MKLDNN_DEVICE : CPU_DEVICE;
@@ -202,101 +178,66 @@ void MKLDNNFcLayer::resetBwd() {
// for CPU device:
// fc do not need to convert from cpu device since output is always nc format
// only need create from cpu device
- const MatrixPtr& out = getOutput(device).grad;
- outGrad_ = MKLDNNMatrix::create(out, outVal_->getPrimitiveDesc());
- wgtGrad_ = MKLDNNMatrix::create(wgt, wgtVal_->getPrimitiveDesc());
- biasGrad_ = hasBias ? MKLDNNMatrix::create(bias, biasVal_->getPrimitiveDesc())
- : nullptr;
+ const MatrixPtr& outGrad = getOutput(device).grad;
+ out = MKLDNNMatrix::create(outGrad, outVal_->getPrimitiveDesc());
+ wgt = MKLDNNMatrix::create(wgtGrad, wgtVal_->getPrimitiveDesc());
+ bias = hasBias ? MKLDNNMatrix::create(biasGrad, biasVal_->getPrimitiveDesc())
+ : nullptr;
// create memory primitive desc
fc_fwd::desc fwdDesc = fc_fwd::desc(prop_kind::forward,
inVal_->getMemoryDesc(),
- wgtGrad_->getMemoryDesc(),
- outGrad_->getMemoryDesc());
+ wgt->getMemoryDesc(),
+ out->getMemoryDesc());
fc_fwd::primitive_desc fwdPD = fc_fwd::primitive_desc(fwdDesc, engine_);
fc_bwdWgt::desc bwdWgtDesc = hasBias
? fc_bwdWgt::desc(inVal_->getMemoryDesc(),
- wgtGrad_->getMemoryDesc(),
- biasGrad_->getMemoryDesc(),
- outGrad_->getMemoryDesc())
+ wgt->getMemoryDesc(),
+ bias->getMemoryDesc(),
+ out->getMemoryDesc())
: fc_bwdWgt::desc(inVal_->getMemoryDesc(),
- wgtGrad_->getMemoryDesc(),
- outGrad_->getMemoryDesc());
+ wgt->getMemoryDesc(),
+ out->getMemoryDesc());
fc_bwdWgt::primitive_desc bwdWgtPD =
fc_bwdWgt::primitive_desc(bwdWgtDesc, engine_, fwdPD);
if (hasBias) {
- bwdWgt_.reset(
- new fc_bwdWgt(bwdWgtPD, *inVal_, *outGrad_, *wgtGrad_, *biasGrad_));
+ bwdWgt_.reset(new fc_bwdWgt(bwdWgtPD, *inVal_, *out, *wgt, *bias));
} else {
- bwdWgt_.reset(new fc_bwdWgt(bwdWgtPD, *inVal_, *outGrad_, *wgtGrad_));
+ bwdWgt_.reset(new fc_bwdWgt(bwdWgtPD, *inVal_, *out, *wgt));
}
- pipelineBwd_.clear();
- pipelineBwd_.push_back(*bwdWgt_);
+ pipeline.push_back(*bwdWgt_);
/// backward data
- device = inputIsOnlyMKLDNN() ? MKLDNN_DEVICE : CPU_DEVICE;
- const MatrixPtr& in = getInputGrad(0, device);
- if (in == nullptr) {
+ const MatrixPtr& inGrad = inputLayers_[0]->getOutput().grad;
+ if (inGrad == nullptr) {
return;
}
- if (getInput(0, device).getAllCount() > 1) {
- // TODO(TJ): use outputMaps_ ways when merge outgrad done
+ if (getInput(0, MKLDNN_DEVICE).getAllCount() > 1) {
+ // TODO(TJ): use outputMaps_ ways to get the inGrad_ when merge outgrad done
} else {
- inGrad_ = MKLDNNMatrix::create(in, inVal_->getPrimitiveDesc());
+ in = MKLDNNMatrix::create(inGrad, inVal_->getPrimitiveDesc());
}
- fc_bwdData::desc bwdDataDesc = fc_bwdData::desc(inVal_->getMemoryDesc(),
- wgtGrad_->getMemoryDesc(),
- outGrad_->getMemoryDesc());
+ fc_bwdData::desc bwdDataDesc = fc_bwdData::desc(
+ inVal_->getMemoryDesc(), wgt->getMemoryDesc(), out->getMemoryDesc());
fc_bwdData::primitive_desc bwdDataPD =
fc_bwdData::primitive_desc(bwdDataDesc, engine_, fwdPD);
CHECK(wgtVal_) << "Should have weight memory";
- bwdData_.reset(new fc_bwdData(bwdDataPD, *outGrad_, *wgtVal_, *inGrad_));
+ bwdData_.reset(new fc_bwdData(bwdDataPD, *out, *wgtVal_, *in));
printGradFormatFlow();
- pipelineBwd_.push_back(*bwdData_);
+ pipeline.push_back(*bwdData_);
}
-void MKLDNNFcLayer::forward(PassType passType) {
- Layer::forward(passType);
- reshape();
-
- {
- REGISTER_TIMER_INFO("mkldnn_FwdTimer", getName().c_str());
- syncInputValue();
-
- // just submit forward pipeline
- stream_->submit(pipelineFwd_);
- }
-
- /* activation */ {
- REGISTER_TIMER_INFO("FwActTimer", getName().c_str());
- forwardActivation();
- }
+void MKLDNNFcLayer::updateInputData() {
+ inVal_->setData(getInputValue(0, CPU_DEVICE)->getData());
}
-void MKLDNNFcLayer::backward(const UpdateCallback& callback) {
- /* Do derivation */ {
- REGISTER_TIMER_INFO("BpActTimer", getName().c_str());
- backwardActivation();
- }
-
- {
- REGISTER_TIMER_INFO("mkldnn_bwdTimer", getName().c_str());
- resetBwd();
-
- syncOutputGrad();
- // just sumbmit backward pipeline
- stream_->submit(pipelineBwd_);
- }
-
- {
- REGISTER_TIMER_INFO("WeightUpdate", getName().c_str());
- weight_->getParameterPtr()->incUpdate(callback);
- if (biases_ && biases_->getWGrad()) {
- biases_->getParameterPtr()->incUpdate(callback);
- }
+void MKLDNNFcLayer::updateWeights(const UpdateCallback& callback) {
+ weight_->getParameterPtr()->incUpdate(callback);
+ if (biases_ && biases_->getWGrad()) {
+ biases_->getParameterPtr()->incUpdate(callback);
}
}
} // namespace paddle
diff --git a/paddle/gserver/layers/MKLDNNFcLayer.h b/paddle/gserver/layers/MKLDNNFcLayer.h
index e138a6faf181c412949218458e7ecf800a0d6a07..3119f863496df092da13c08bf733f13c42e53780 100644
--- a/paddle/gserver/layers/MKLDNNFcLayer.h
+++ b/paddle/gserver/layers/MKLDNNFcLayer.h
@@ -45,35 +45,28 @@ public:
bool init(const LayerMap& layerMap,
const ParameterMap& parameterMap) override;
- void convertWeightsFromPaddle() override;
+ void reshape(
+ int& bs, int& ic, int& ih, int& iw, int oc, int& oh, int& ow) override;
- void convertWeightsToPaddle() override;
+ void resetFwd(std::vector& pipeline,
+ MKLDNNMatrixPtr& in,
+ MKLDNNMatrixPtr& wgt,
+ MKLDNNMatrixPtr& bias,
+ MKLDNNMatrixPtr& out) override;
- void forward(PassType passType) override;
+ void resetBwd(std::vector& pipeline,
+ MKLDNNMatrixPtr& in,
+ MKLDNNMatrixPtr& wgt,
+ MKLDNNMatrixPtr& bias,
+ MKLDNNMatrixPtr& out) override;
- void backward(const UpdateCallback& callback) override;
+ void updateInputData() override;
-protected:
- /**
- * reshape the input image sizes
- * and reset output buffer size
- * and reset mkldnn forward
- */
- void reshape();
-
- /**
- * reset the forward primitve and memory
- * only would be called when input size changes
- */
- void resetFwd();
-
- /**
- * reset the backward primitve and memory for mkldnn fc
- * only would be called when needed
- */
- void resetBwd();
-
- void convertOutputToOtherDevice() override;
+ void updateWeights(const UpdateCallback& callback) override;
+
+ void convertWeightsFromPaddle() override;
+
+ void convertWeightsToPaddle() override;
};
} // namespace paddle
diff --git a/paddle/gserver/layers/MKLDNNLayer.h b/paddle/gserver/layers/MKLDNNLayer.h
index b983b833d510b823c5d4cff0b9390173e4cefc89..169679c8297542cac4a43f5a8e1af311ad9282df 100644
--- a/paddle/gserver/layers/MKLDNNLayer.h
+++ b/paddle/gserver/layers/MKLDNNLayer.h
@@ -19,6 +19,7 @@ limitations under the License. */
#include "MKLDNNBase.h"
#include "mkldnn.hpp"
#include "paddle/math/MKLDNNMatrix.h"
+#include "paddle/utils/Stat.h"
DECLARE_bool(use_mkldnn);
@@ -33,6 +34,8 @@ typedef std::shared_ptr MKLDNNLayerPtr;
*/
class MKLDNNLayer : public Layer {
protected:
+ // input value element count
+ size_t inputElemenCnt_;
// batch size
int bs_;
// input image channel, height and width
@@ -52,7 +55,7 @@ protected:
std::vector pipelineFwd_;
std::vector pipelineBwd_;
- // MKLDNNMatrixPtr
+ // MKLDNNMatrixPtr with internal format
MKLDNNMatrixPtr inVal_;
MKLDNNMatrixPtr inGrad_;
MKLDNNMatrixPtr outVal_;
@@ -65,6 +68,7 @@ protected:
public:
explicit MKLDNNLayer(const LayerConfig& config)
: Layer(config),
+ inputElemenCnt_(0),
bs_(0),
ic_(0),
ih_(0),
@@ -95,12 +99,104 @@ public:
if (!Layer::init(layerMap, parameterMap)) {
return false;
}
+ checkCPUOutputsNumber();
stream_.reset(new MKLDNNStream());
engine_ = CPUEngine::Instance().getEngine();
return true;
}
+ void forward(PassType passType) override {
+ passType_ = passType;
+
+ {
+ REGISTER_TIMER_INFO("mkldnn_FwdTimer", getName().c_str());
+ CHECK(!inputLayers_.empty());
+ copySeqInfoToOutputs();
+ size_t elemenCnt = inputLayers_[0]->getOutput().value->getElementCnt();
+ if (inputElemenCnt_ != elemenCnt) {
+ // reset when input total sizes changed, not only the batchsize
+ inputElemenCnt_ = elemenCnt;
+ reshape(bs_, ic_, ih_, iw_, oc_, oh_, ow_);
+ resetFwd(pipelineFwd_, inVal_, wgtVal_, biasVal_, outVal_);
+ convertWeightsFromPaddle();
+ needResetBwd_ = true;
+ }
+
+ if (inputLayers_[0]->getType() == "data") {
+ updateInputData();
+ }
+
+ stream_->submit(pipelineFwd_);
+ }
+
+ /* activation */ {
+ REGISTER_TIMER_INFO("FwActTimer", getName().c_str());
+ forwardActivation();
+ }
+ }
+
+ void backward(const UpdateCallback& callback) override {
+ /* Do derivation */ {
+ REGISTER_TIMER_INFO("BpActTimer", getName().c_str());
+ backwardActivation();
+ }
+
+ {
+ REGISTER_TIMER_INFO("mkldnn_bwdTimer", getName().c_str());
+ if (needResetBwd_) {
+ resetBwd(pipelineBwd_, inGrad_, wgtGrad_, biasGrad_, outGrad_);
+ needResetBwd_ = false;
+ }
+
+ stream_->submit(pipelineBwd_);
+ }
+
+ {
+ REGISTER_TIMER_INFO("WeightUpdate", getName().c_str());
+ updateWeights(callback);
+ }
+ }
+
+ /**
+ * reshape the input image sizes
+ * and reset output image and buffer size
+ * output channel can not be changed
+ */
+ virtual void reshape(
+ int& bs, int& ic, int& ih, int& iw, int oc, int& oh, int& ow) = 0;
+
+ /**
+ * reset the mkldnn forward primitve and memory
+ * only would be called when input size changes
+ */
+ virtual void resetFwd(std::vector& pipeline,
+ MKLDNNMatrixPtr& in,
+ MKLDNNMatrixPtr& wgt,
+ MKLDNNMatrixPtr& bias,
+ MKLDNNMatrixPtr& out) = 0;
+
+ /**
+ * reset the mkldnn backward primitve and memory for mkldnn fc
+ * only would be called when needed
+ */
+ virtual void resetBwd(std::vector& pipeline,
+ MKLDNNMatrixPtr& in,
+ MKLDNNMatrixPtr& wgt,
+ MKLDNNMatrixPtr& bias,
+ MKLDNNMatrixPtr& out) = 0;
+
+ /**
+ * Update input value data when input layer is "data" type.
+ * Since the input value data address might be changed.
+ */
+ virtual void updateInputData() {}
+
+ /**
+ * Update weights and biases if necessary.
+ */
+ virtual void updateWeights(const UpdateCallback& callback) {}
+
/**
* convert weight from paddle format to mkldnn format
* weight_ will be override
@@ -114,10 +210,38 @@ public:
virtual void convertWeightsToPaddle() {}
/**
- * convert MKLDNN output to other device.
- * only support CPU device yet
+ * add this interface as public for unit test
+ */
+ void addOutputArgument(int deviceId) { Layer::addOutputArgument(deviceId); }
+
+protected:
+ /**
+ * reshape the input image sizes and input batchsize
*/
- virtual void convertOutputToOtherDevice() {}
+ virtual void reshapeInput(int& batchsize, int& height, int& width) {
+ const Argument& input = inputLayers_[0]->getOutput();
+ batchsize = input.getBatchSize();
+ int h = input.getFrameHeight();
+ int w = input.getFrameWidth();
+ if (h != 0) {
+ height = h;
+ }
+ if (w != 0) {
+ width = w;
+ }
+ }
+
+ /**
+ * reshape output image sizes
+ */
+ virtual void reshapeOutput(size_t height, size_t width) {
+ output_.setFrameHeight(height);
+ output_.setFrameWidth(width);
+ for (size_t i = 0; i < outputOtherDevice_.size(); i++) {
+ outputOtherDevice_[i].setFrameHeight(height);
+ outputOtherDevice_[i].setFrameWidth(width);
+ }
+ }
/**
* print info about sizes
@@ -133,8 +257,8 @@ public:
*/
virtual void printValueFormatFlow() {
if (inVal_ && outVal_) {
- VLOG(MKLDNN_FMTS) << "value format flow --- " << inVal_->getFormat()
- << " >>> " << outVal_->getFormat();
+ VLOG(MKLDNN_FMTS) << inVal_->getFormat() << " >>> "
+ << outVal_->getFormat();
}
}
@@ -143,29 +267,12 @@ public:
*/
virtual void printGradFormatFlow() {
if (inGrad_ && outGrad_) {
- VLOG(MKLDNN_FMTS) << "grad format flow --- " << inGrad_->getFormat()
- << " <<< " << outGrad_->getFormat();
+ VLOG(MKLDNN_FMTS) << inGrad_->getFormat() << " <<< "
+ << outGrad_->getFormat();
}
}
protected:
- /**
- * copy image size and sequence info to other device
- * @note: can not directly use Layer::copyOutputToOtherDevice since here only
- * copy base info and do not copy data value
- */
- void copyOutputInfoToOtherDevice() {
- for (size_t i = 0; i < outputOtherDevice_.size(); i++) {
- outputOtherDevice_[i].setFrameHeight(output_.getFrameHeight());
- outputOtherDevice_[i].setFrameWidth(output_.getFrameWidth());
- outputOtherDevice_[i].sequenceStartPositions =
- output_.sequenceStartPositions;
- outputOtherDevice_[i].subSequenceStartPositions =
- output_.subSequenceStartPositions;
- outputOtherDevice_[i].cpuSequenceDims = output_.cpuSequenceDims;
- }
- }
-
/**
* If input only has MKLDNN device.
* Otherwise, only support the previous layer using CPU device.
@@ -193,37 +300,12 @@ protected:
return outputOtherDevice_.size() == 0;
}
- /**
- * Sync input value data
- */
- void syncInputValue() {
- if (inputIsOnlyMKLDNN()) {
- return;
- }
- real* iData = getInputValue(0, CPU_DEVICE)->getData();
- // update input data
- // since it might be changed if this is after data layer
- inVal_->updateData(iData);
- }
-
- /**
- * Sync output grad data
- */
- void syncOutputGrad() {
- if (outputIsOnlyMKLDNN()) {
- return;
- }
-
- // update diff
- real* oDiff = getOutput(CPU_DEVICE).grad->getData();
- outGrad_->updateData(oDiff);
- }
-
/**
* Set deviceId of this layer.
*/
void setDevice(int id) { deviceId_ = id; }
+private:
/**
* Set deviceId of the params used in this layer.
*/
@@ -247,6 +329,42 @@ protected:
parameter->setDevice(id);
}
}
+
+ /**
+ * Check the cpu device number of outputOtherDevice_.
+ * should have only one at most.
+ */
+ void checkCPUOutputsNumber(int max = 1) {
+ int cnt = 0;
+ for (size_t i = 0; i < outputOtherDevice_.size(); i++) {
+ if (outputOtherDevice_[i].deviceId == CPU_DEVICE) {
+ ++cnt;
+ }
+ }
+ CHECK_LE(cnt, max) << "too much CPU devies";
+ }
+
+ /**
+ * copy SeqInfo from input layer to this output and other output devices.
+ * @note: do not use getInput(0) since it used this deviceId_,
+ * use "inputLayers_[0]->getOutput()" instead.
+ */
+ void copySeqInfoToOutputs() {
+ if (inputLayers_.empty() || !needSequenceInfo_) {
+ return;
+ }
+ const Argument& input = inputLayers_[0]->getOutput();
+ output_.sequenceStartPositions = input.sequenceStartPositions;
+ output_.subSequenceStartPositions = input.subSequenceStartPositions;
+ output_.cpuSequenceDims = input.cpuSequenceDims;
+ for (size_t i = 0; i < outputOtherDevice_.size(); i++) {
+ outputOtherDevice_[i].sequenceStartPositions =
+ output_.sequenceStartPositions;
+ outputOtherDevice_[i].subSequenceStartPositions =
+ output_.subSequenceStartPositions;
+ outputOtherDevice_[i].cpuSequenceDims = output_.cpuSequenceDims;
+ }
+ }
};
} // namespace paddle
diff --git a/paddle/gserver/layers/SwitchOrderLayer.cpp b/paddle/gserver/layers/SwitchOrderLayer.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..e97809141a93106f9e6ebaf40c7e8aa9c6010557
--- /dev/null
+++ b/paddle/gserver/layers/SwitchOrderLayer.cpp
@@ -0,0 +1,109 @@
+/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License. */
+
+#include "SwitchOrderLayer.h"
+#include "paddle/utils/Stat.h"
+
+namespace paddle {
+
+REGISTER_LAYER(switch_order, SwitchOrderLayer);
+
+bool SwitchOrderLayer::init(const LayerMap& layerMap,
+ const ParameterMap& parameterMap) {
+ /* Initialize the basic parent class */
+ Layer::init(layerMap, parameterMap);
+ auto& img_conf = config_.inputs(0).image_conf();
+ size_t inD = img_conf.img_size_z();
+ size_t inH =
+ img_conf.has_img_size_y() ? img_conf.img_size_y() : img_conf.img_size();
+ size_t inW = img_conf.img_size();
+ size_t inC = img_conf.channels();
+ inH = inH * inD;
+ inDims_ = TensorShape({0, inC, inH, inW});
+ outDims_ = TensorShape(4);
+
+ auto& reshape_conf = config_.reshape_conf();
+ for (int i = 0; i < reshape_conf.height_axis_size(); i++) {
+ heightAxis_.push_back(reshape_conf.height_axis(i));
+ }
+ for (int i = 0; i < reshape_conf.width_axis_size(); i++) {
+ widthAxis_.push_back(reshape_conf.width_axis(i));
+ }
+ createFunction(nchw2nhwc_, "NCHW2NHWC", FuncConfig());
+ createFunction(nhwc2nchw_, "NHWC2NCHW", FuncConfig());
+ return true;
+}
+
+void SwitchOrderLayer::setOutDims() {
+ outDims_.setDim(0, inDims_[0]);
+ outDims_.setDim(1, inDims_[2]);
+ outDims_.setDim(2, inDims_[3]);
+ outDims_.setDim(3, inDims_[1]);
+ reshapeHeight_ = 1;
+ for (size_t i = 0; i < heightAxis_.size(); i++) {
+ reshapeHeight_ *= outDims_[heightAxis_[i]];
+ }
+ output_.setFrameHeight(reshapeHeight_);
+ reshapeWidth_ = 1;
+ for (size_t i = 0; i < widthAxis_.size(); i++) {
+ reshapeWidth_ *= outDims_[widthAxis_[i]];
+ }
+ output_.setFrameWidth(reshapeWidth_);
+}
+
+void SwitchOrderLayer::setInDims() {
+ MatrixPtr input = inputLayers_[0]->getOutputValue();
+ size_t batchSize = input->getHeight();
+ inDims_.setDim(0, batchSize);
+ int d = inputLayers_[0]->getOutput().getFrameDepth();
+ d = (d == 0 ? 1 : d);
+ int h = inputLayers_[0]->getOutput().getFrameHeight();
+ if (h != 0) inDims_.setDim(2, h * d);
+ int w = inputLayers_[0]->getOutput().getFrameWidth();
+ if (w != 0) inDims_.setDim(3, w);
+ int totalCount = input->getElementCnt();
+ int channels = totalCount / (inDims_[0] * inDims_[2] * inDims_[3]);
+ if (channels != 0) inDims_.setDim(1, channels);
+}
+
+void SwitchOrderLayer::forward(PassType passType) {
+ Layer::forward(passType);
+ setInDims();
+ setOutDims();
+ resetOutput(outDims_[0], outDims_[1] * outDims_[2] * outDims_[3]);
+ if (heightAxis_.size() > 0) {
+ resetOutput(reshapeHeight_, reshapeWidth_);
+ }
+
+ // switch NCHW to NHWC
+ BufferArgs inputs;
+ BufferArgs outputs;
+ inputs.addArg(*getInputValue(0), inDims_);
+ outputs.addArg(*getOutputValue(), outDims_);
+ nchw2nhwc_[0]->calc(inputs, outputs);
+ forwardActivation();
+}
+
+void SwitchOrderLayer::backward(const UpdateCallback& callback) {
+ (void)callback;
+ backwardActivation();
+
+ // switch NHWC to NCHW
+ BufferArgs inputs;
+ BufferArgs outputs;
+ inputs.addArg(*getOutputGrad(), outDims_);
+ outputs.addArg(*getInputGrad(0), inDims_, ADD_TO);
+ nhwc2nchw_[0]->calc(inputs, outputs);
+}
+} // namespace paddle
diff --git a/paddle/gserver/layers/SwitchOrderLayer.h b/paddle/gserver/layers/SwitchOrderLayer.h
new file mode 100644
index 0000000000000000000000000000000000000000..47b1f7f73ee783b3eae3c9cfe08b1459cef16a71
--- /dev/null
+++ b/paddle/gserver/layers/SwitchOrderLayer.h
@@ -0,0 +1,47 @@
+/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License. */
+
+#pragma once
+
+#include "Layer.h"
+
+namespace paddle {
+
+/**
+ * \brief This layer calculate softmax in image channel dimension.
+ */
+class SwitchOrderLayer : public Layer {
+public:
+ explicit SwitchOrderLayer(const LayerConfig& config) : Layer(config) {}
+
+ ~SwitchOrderLayer() {}
+
+ bool init(const LayerMap& layerMap,
+ const ParameterMap& parameterMap) override;
+ void forward(PassType passType) override;
+ void backward(const UpdateCallback& callback = nullptr) override;
+ void setInDims();
+ void setOutDims();
+
+protected:
+ std::vector> nchw2nhwc_;
+ std::vector> nhwc2nchw_;
+ TensorShape inDims_;
+ TensorShape outDims_;
+ std::vector heightAxis_;
+ std::vector widthAxis_;
+ size_t reshapeHeight_;
+ size_t reshapeWidth_;
+};
+} // namespace paddle
diff --git a/paddle/gserver/tests/MKLDNNTester.cpp b/paddle/gserver/tests/MKLDNNTester.cpp
index de1635be2af37cd0ba49010199a417090865b0e4..2f48e5b2d3ffc9337ed1314f6db6549e56263fdd 100644
--- a/paddle/gserver/tests/MKLDNNTester.cpp
+++ b/paddle/gserver/tests/MKLDNNTester.cpp
@@ -63,8 +63,12 @@ void MKLDNNTester::reset(const TestConfig& dnn,
initTestLayer(
configs_[i], &(layerMaps_[i]), &(parameters_[i]), &(testLayers_[i]));
}
- dnnLayer_ = testLayers_[DNN];
refLayer_ = testLayers_[REF];
+ dnnLayer_ = std::dynamic_pointer_cast(testLayers_[DNN]);
+ CHECK(dnnLayer_);
+ // for comparison with Paddle reference results,
+ // need manually add cpu device output for test
+ dnnLayer_->addOutputArgument(CPU_DEVICE);
EXPECT_EQ(dataLayers_[DNN].size(), dataLayers_[REF].size());
EXPECT_EQ(parameters_[DNN].size(), parameters_[REF].size());
@@ -109,20 +113,22 @@ void MKLDNNTester::randomBotDatas() {
void MKLDNNTester::randomTopDiffs() {
refLayer_->getOutputGrad()->randomizeUniform();
- dnnLayer_->getOutputGrad()->copyFrom(*(refLayer_->getOutputGrad()));
- VLOG(lvl_) << "Random dom Backward Input, TopDiff: ";
+ dnnLayer_->getOutput(CPU_DEVICE)
+ .grad->copyFrom(*(refLayer_->getOutputGrad()));
+ VLOG(lvl_) << "Random Backward Input, TopDiff: ";
printMatrix(refLayer_->getOutputGrad());
}
void MKLDNNTester::checkForward() {
- printTopDatas();
- double delta = compareMatrix(testLayers_[DNN]->getOutputValue(),
- testLayers_[REF]->getOutputValue());
VLOG(MKLDNN_ALL) << "Check Forward";
+ printTopDatas();
+ double delta = compareMatrix(dnnLayer_->getOutput(-1).value,
+ refLayer_->getOutputValue());
EXPECT_LE(fabs(delta), eps_);
}
void MKLDNNTester::checkBackwardData() {
+ VLOG(MKLDNN_ALL) << "Check Backward Data";
// TODO(TJ): uncomment me when batch norm ready
// const bool isBN = dnnLayer_->getType() == "mkldnn_batch_norm";
for (size_t i = 0; i < dataLayers_[DNN].size(); ++i) {
@@ -144,14 +150,12 @@ void MKLDNNTester::checkBackwardData() {
}
void MKLDNNTester::checkBackwardWgts() {
+ VLOG(MKLDNN_ALL) << "Check Backward Weight";
CHECK_EQ(parameters_[DNN].size(), parameters_[REF].size());
vector dnnWgts; // used to temply save mkldnn weights
saveWgt(parameters_[DNN], dnnWgts);
- const MKLDNNLayerPtr dnnlayer =
- std::dynamic_pointer_cast(dnnLayer_);
- CHECK(dnnlayer);
- dnnlayer->convertWeightsToPaddle();
+ dnnLayer_->convertWeightsToPaddle();
for (size_t i = 0; i < parameters_[DNN].size(); ++i) {
const VectorPtr& dnn = parameters_[DNN][i]->getBuf(PARAMETER_VALUE);
const VectorPtr& ref = parameters_[REF][i]->getBuf(PARAMETER_VALUE);
@@ -189,38 +193,38 @@ void MKLDNNTester::restoreWgt(const vector& from,
}
// clear parameters grad
-void MKLDNNTester::clearWgtDiffs() {
+void MKLDNNTester::clearWgtDiffs(size_t id) {
+ CHECK_LE(id, parameters_.size());
for (size_t n = 0; n < parameters_.size(); ++n) {
- for (size_t i = 0; i < parameters_[n].size(); ++i) {
- const VectorPtr& grad = parameters_[n][i]->getBuf(PARAMETER_GRADIENT);
- if (grad) {
- grad->zeroMem();
+ if (id == n || id == parameters_.size()) {
+ for (size_t i = 0; i < parameters_[n].size(); ++i) {
+ const VectorPtr& grad = parameters_[n][i]->getBuf(PARAMETER_GRADIENT);
+ if (grad) {
+ grad->zeroMem();
+ }
}
}
}
}
-void MKLDNNTester::clearBotDiffs() {
- // dnn and ref
+void MKLDNNTester::clearBotDiffs(size_t id) {
+ CHECK_LE(id, dataLayers_.size());
for (size_t n = 0; n < dataLayers_.size(); ++n) {
- // all inputs layers
- for (size_t i = 0; i < dataLayers_[n].size(); ++i) {
- dataLayers_[n][i]->getOutputGrad()->zeroMem();
+ if (id == n || id == dataLayers_.size()) {
+ // clear inputs layers of this specific layer
+ for (size_t i = 0; i < dataLayers_[n].size(); ++i) {
+ dataLayers_[n][i]->getOutputGrad()->zeroMem();
+ }
}
}
}
-void MKLDNNTester::clearBotDiffs(int n) {
- CHECK_LT(n, NUM);
- // all inputs layers
- for (size_t i = 0; i < dataLayers_[n].size(); ++i) {
- dataLayers_[n][i]->getOutputGrad()->zeroMem();
- }
-}
-
-void MKLDNNTester::clearTopDatas() {
+void MKLDNNTester::clearTopDatas(size_t id) {
+ CHECK_LE(id, testLayers_.size());
for (size_t i = 0; i < testLayers_.size(); ++i) {
- testLayers_[i]->getOutputValue()->zeroMem();
+ if (id == i || id == testLayers_.size()) {
+ testLayers_[i]->getOutputValue()->zeroMem();
+ }
}
}
@@ -300,16 +304,24 @@ void MKLDNNTester::runOnce() {
checkForward();
// test backward
+ // simple updater
+ UpdateCallback updateCallback = [](Parameter* para) {
+ auto& grad = para->getBuf(PARAMETER_GRADIENT);
+ auto& value = para->getBuf(PARAMETER_VALUE);
+ real lr = 1e-3;
+ value->add(*grad, lr);
+ };
randomTopDiffs();
- dnnLayer_->backward(nullptr);
- refLayer_->backward(nullptr);
+ dnnLayer_->backward(updateCallback);
+ refLayer_->backward(updateCallback);
checkBackwardData();
checkBackwardWgts();
// clear buffers
// ref code will addto the diff, dnn code will writeto it
- // and clearTopDatas() and clearWgtDiffs() should be coverd by test layers
+ // and clearTopDatas(REF) should be coverd by ref layers
clearBotDiffs(REF);
+ clearWgtDiffs(REF);
}
void MKLDNNTester::run(const TestConfig& dnn,
diff --git a/paddle/gserver/tests/MKLDNNTester.h b/paddle/gserver/tests/MKLDNNTester.h
index e55e4493ffdfe45b8cfdee423febd1878b8b3d8a..5ac885638cde7693a0c847733e7a6149c1b7e6c2 100644
--- a/paddle/gserver/tests/MKLDNNTester.h
+++ b/paddle/gserver/tests/MKLDNNTester.h
@@ -18,6 +18,7 @@ limitations under the License. */
#include
#include "LayerGradUtil.h"
#include "paddle/gserver/layers/MKLDNNBase.h"
+#include "paddle/gserver/layers/MKLDNNLayer.h"
namespace paddle {
@@ -40,7 +41,8 @@ protected:
vector layerMaps_;
vector> parameters_;
vector testLayers_;
- LayerPtr dnnLayer_, refLayer_;
+ LayerPtr refLayer_;
+ MKLDNNLayerPtr dnnLayer_;
/// run some iterations, all the result should pass
size_t iter_;
@@ -88,10 +90,10 @@ private:
void checkBackwardData();
void checkBackwardWgts();
- void clearWgtDiffs();
- void clearBotDiffs();
- void clearBotDiffs(int n); // clear specific layer
- void clearTopDatas();
+ // clear specific layer, clear all when id equals NUM
+ void clearWgtDiffs(size_t id = NUM);
+ void clearBotDiffs(size_t id = NUM);
+ void clearTopDatas(size_t id = NUM);
void printTopDatas();
void printMatrix(const MatrixPtr& m);
diff --git a/paddle/gserver/tests/test_LayerGrad.cpp b/paddle/gserver/tests/test_LayerGrad.cpp
index a831ffbc73fbd6ad42fa31b2d6d583718474e59b..090bde7b203652e3ffb1662b8f5b8937885d2608 100644
--- a/paddle/gserver/tests/test_LayerGrad.cpp
+++ b/paddle/gserver/tests/test_LayerGrad.cpp
@@ -1703,6 +1703,55 @@ TEST(Layer, BatchNormalizationLayer) {
#endif
}
+void testBatchNorm3DLayer(const string& type, bool trans, bool useGpu) {
+ TestConfig config;
+ const int CHANNELS = 10;
+ const int IMG_SIZE = 16;
+ const int IMG_SIZE_Y = 8;
+ const int IMG_SIZE_Z = 8;
+ size_t size = CHANNELS * IMG_SIZE * IMG_SIZE_Y * IMG_SIZE_Z;
+ config.layerConfig.set_type(type);
+ config.layerConfig.set_size(size);
+ config.layerConfig.set_active_type("sigmoid");
+ config.biasSize = CHANNELS;
+ config.inputDefs.push_back({INPUT_DATA,
+ "layer_0",
+ /* dim= */ size,
+ /* paraSize= */ CHANNELS});
+
+ config.inputDefs.push_back({INPUT_DATA, "layer_1_running_mean", 1, CHANNELS});
+ config.inputDefs.back().isStatic = true;
+ config.inputDefs.push_back({INPUT_DATA, "layer_2_running_var", 1, CHANNELS});
+ config.inputDefs.back().isStatic = true;
+
+ LayerInputConfig* input = config.layerConfig.add_inputs();
+ config.layerConfig.add_inputs();
+ config.layerConfig.add_inputs();
+
+ ImageConfig* img_conf = input->mutable_image_conf();
+ img_conf->set_channels(CHANNELS);
+ img_conf->set_img_size(IMG_SIZE);
+ img_conf->set_img_size_y(IMG_SIZE_Y);
+ img_conf->set_img_size_z(IMG_SIZE_Z);
+
+ testLayerGrad(config,
+ "batch_norm",
+ 64,
+ /* trans= */ trans,
+ useGpu,
+ /* useWeight */ true);
+}
+
+TEST(Layer, testBatchNorm3DLayer) {
+ testBatchNorm3DLayer("batch_norm", false, false);
+#ifndef PADDLE_ONLY_CPU
+ testBatchNorm3DLayer("batch_norm", false, true);
+ if (hl_get_cudnn_lib_version() >= int(4000)) {
+ testBatchNorm3DLayer("cudnn_batch_norm", false, true);
+ }
+#endif
+}
+
void testConvOperator(bool isDeconv) {
TestConfig config;
const int NUM_FILTERS = 16;
@@ -2008,6 +2057,31 @@ TEST(Layer, CropLayer) {
}
}
+TEST(Layer, SwitchOrderLayer) {
+ TestConfig config;
+ // config input_0
+ config.inputDefs.push_back({INPUT_DATA, "layer_0", 1024, 0});
+ LayerInputConfig* input = config.layerConfig.add_inputs();
+ ImageConfig* img = input->mutable_image_conf();
+ img->set_channels(4);
+ img->set_img_size(16);
+ img->set_img_size_y(16);
+
+ ReshapeConfig* reshape = config.layerConfig.mutable_reshape_conf();
+ reshape->add_height_axis(0);
+ reshape->add_height_axis(1);
+ reshape->add_height_axis(2);
+ reshape->add_width_axis(3);
+
+ // config softmax layer
+ config.layerConfig.set_type("switch_order");
+ config.layerConfig.set_name("switchOrderLayer");
+
+ for (auto useGpu : {false, true}) {
+ testLayerGrad(config, "switch_order", 100, false, useGpu, true);
+ }
+}
+
vector randSampling(real range, int n) {
CHECK_GE(range, n);
vector num(range);
@@ -2228,26 +2302,27 @@ void test3DDeConvLayer(const string& type, bool trans, bool useGpu) {
conv->set_stride(2);
conv->set_stride_y(2);
conv->set_stride_z(2);
- conv->set_img_size(IMAGE_SIZE);
- conv->set_img_size_y(IMAGE_SIZE_Y);
- conv->set_img_size_z(IMAGE_SIZE_Z);
- conv->set_output_x(imageSize(conv->img_size(),
+ conv->set_output_x(IMAGE_SIZE);
+ conv->set_output_y(IMAGE_SIZE_Y);
+ conv->set_output_z(IMAGE_SIZE_Z);
+
+ conv->set_img_size(imageSize(conv->output_x(),
conv->filter_size(),
conv->padding(),
conv->stride(),
true));
- conv->set_output_y(imageSize(conv->img_size_y(),
- conv->filter_size_y(),
- conv->padding_y(),
- conv->stride_y(),
- true));
- conv->set_output_z(imageSize(conv->img_size_z(),
- conv->filter_size_z(),
- conv->padding_z(),
- conv->stride_z(),
- true));
- config.layerConfig.set_size(conv->output_x() * conv->output_y() *
- conv->output_z() * NUM_FILTERS);
+ conv->set_img_size_y(imageSize(conv->output_y(),
+ conv->filter_size_y(),
+ conv->padding_y(),
+ conv->stride_y(),
+ true));
+ conv->set_img_size_z(imageSize(conv->output_z(),
+ conv->filter_size_z(),
+ conv->padding_z(),
+ conv->stride_z(),
+ true));
+ config.layerConfig.set_size(conv->img_size() * conv->img_size_y() *
+ conv->img_size_z() * NUM_FILTERS);
conv->set_groups(1);
conv->set_filter_channels(conv->channels() / conv->groups());
config.inputDefs.push_back(
diff --git a/paddle/math/MKLDNNMatrix.cpp b/paddle/math/MKLDNNMatrix.cpp
index 0a355e2644cce572ce90ecf5c9d2a5b7b395bc61..c4063e5069854242d9f93886b66580385557ca73 100644
--- a/paddle/math/MKLDNNMatrix.cpp
+++ b/paddle/math/MKLDNNMatrix.cpp
@@ -33,14 +33,12 @@ MKLDNNMatrixPtr MKLDNNMatrix::create(MatrixPtr m, memory::primitive_desc pd) {
size_t width = cnts / dims[0];
m = Matrix::create(height, width, false, false);
}
-
CHECK(m) << " Matrix should not be empty";
+
CpuMatrixPtr cpuMatrix = std::dynamic_pointer_cast(m);
CHECK(cpuMatrix) << "Only support create from CPU matrix yet";
-
- CHECK_EQ(cnts, m->getElementCnt()) << "Count size does not match";
- return std::make_shared(
- m->getData(), m->getHeight(), m->getWidth(), pd);
+ CHECK_EQ(cpuMatrix->getElementCnt(), cnts) << "Count size does not match";
+ return std::make_shared(cpuMatrix, pd);
}
MKLDNNMatrixPtr MKLDNNMatrix::create(MatrixPtr m,
@@ -138,7 +136,7 @@ void MKLDNNMatrix::downSpatial() {
mkldnn_primitive_create(&result, pd.get(), nullptr, nullptr),
"could not create a memory primitive");
reset(result);
- set_data_handle(getData());
+ set_data_handle(data_);
}
} // namespace paddle
diff --git a/paddle/math/MKLDNNMatrix.h b/paddle/math/MKLDNNMatrix.h
index e50f698b495713e6f15ab7a12a7ee7487662040f..eef3b429e6fa0087aeac3f5aed9dff983b06e826 100644
--- a/paddle/math/MKLDNNMatrix.h
+++ b/paddle/math/MKLDNNMatrix.h
@@ -30,11 +30,10 @@ typedef std::shared_ptr MKLDNNMatrixPtr;
*/
class MKLDNNMatrix : public CpuMatrix, public mkldnn::memory {
public:
- MKLDNNMatrix(real* data,
- size_t height,
- size_t width,
- mkldnn::memory::primitive_desc pd)
- : CpuMatrix(data, height, width, false), mkldnn::memory(pd, data) {}
+ MKLDNNMatrix(CpuMatrixPtr m, mkldnn::memory::primitive_desc pd)
+ : CpuMatrix(m->getData(), m->getHeight(), m->getWidth(), false),
+ mkldnn::memory(pd, m->getData()),
+ m_(m) {}
~MKLDNNMatrix() {}
@@ -81,11 +80,29 @@ public:
void downSpatial();
/**
- * Update the memory data handle.
+ * set the memory data handle.
* Caution: This will not check the buffer size of the data,
* it should be coverd by user.
*/
- void updateData(void* data) { set_data_handle(data); }
+ void setData(real* data) {
+ set_data_handle(data);
+ CpuMatrix::setData(data);
+ m_.reset();
+ }
+
+ /**
+ * override Matrix::getData
+ * check data before return
+ */
+ real* getData() override {
+ CHECK_EQ((void*)data_, get_data_handle());
+ return data_;
+ }
+
+ const real* getData() const override {
+ CHECK_EQ((void*)data_, get_data_handle());
+ return data_;
+ }
/**
* Get primitive descriptor.
@@ -143,6 +160,10 @@ protected:
memory::format srcFmt,
memory::format dstFmt,
memory::dims dm);
+
+private:
+ // save the CpuMatrixPtr in case the buffer released outside
+ CpuMatrixPtr m_;
};
} // namespace paddle
diff --git a/paddle/math/MathFunctions.cpp b/paddle/math/MathFunctions.cpp
index c8ba1074a1555bbddde7e5f0fb2a046138b27c09..c2f17beeb87942ea681f5d388659c0d280157b26 100644
--- a/paddle/math/MathFunctions.cpp
+++ b/paddle/math/MathFunctions.cpp
@@ -84,6 +84,7 @@ LAPACK_ROUTINE_EACH(DYNAMIC_LOAD_LAPACK_WRAP)
namespace paddle {
+#ifndef PADDLE_USE_EIGEN_FOR_BLAS
template <>
void gemm(const CBLAS_TRANSPOSE transA,
const CBLAS_TRANSPOSE transB,
@@ -143,6 +144,7 @@ void gemm(const CBLAS_TRANSPOSE transA,
C,
ldc);
}
+#endif
template <>
int getrf(const CBLAS_ORDER order,
@@ -182,6 +184,7 @@ int getri(const CBLAS_ORDER order,
return dynload::PADDLE_DGETRI(order, N, A, lda, ipiv);
}
+#ifndef PADDLE_USE_EIGEN_FOR_BLAS
template <>
void axpy(const int n, const float alpha, const float* x, float* y) {
cblas_saxpy(n, alpha, x, 1, y, 1);
@@ -201,6 +204,7 @@ template <>
double dotProduct(const int n, const double* x, const double* y) {
return cblas_ddot(n, x, 1, y, 1);
}
+#endif
#if defined(PADDLE_USE_MKL) || defined(PADDLE_USE_MKLML)
diff --git a/paddle/math/MathFunctions.h b/paddle/math/MathFunctions.h
index 637643838ff433753e0cbb9154ee069c2f7c6d15..e8ea6e37ac527a19c529d1731b94bed970211755 100644
--- a/paddle/math/MathFunctions.h
+++ b/paddle/math/MathFunctions.h
@@ -40,7 +40,14 @@ extern "C" {
#ifndef LAPACK_FOUND
extern "C" {
+#ifndef PADDLE_USE_EIGEN_FOR_BLAS
#include
+#else
+typedef enum CBLAS_ORDER {
+ CblasRowMajor = 101,
+ CblasColMajor = 102
+} CBLAS_ORDER;
+#endif
int LAPACKE_sgetrf(
int matrix_layout, int m, int n, float* a, int lda, int* ipiv);
int LAPACKE_dgetrf(
@@ -56,6 +63,7 @@ int LAPACKE_dgetri(
namespace paddle {
+#ifndef PADDLE_USE_EIGEN_FOR_BLAS
template
void gemm(const CBLAS_TRANSPOSE transA,
const CBLAS_TRANSPOSE transB,
@@ -70,6 +78,7 @@ void gemm(const CBLAS_TRANSPOSE transA,
const T beta,
T* C,
const int ldc);
+#endif
template
int getrf(const CBLAS_ORDER Order,
@@ -84,10 +93,21 @@ int getri(
const CBLAS_ORDER Order, const int N, T* A, const int lda, const int* ipiv);
template
-void axpy(const int n, const T alpha, const T* x, T* y);
+void axpy(const int n, const T alpha, const T* x, T* y) {
+ /// y = y + alpha * x
+ for (int i = 0; i < n; i++) {
+ y[i] = y[i] + alpha * x[i];
+ }
+}
template
-T dotProduct(const int n, const T* x, const T* y);
+T dotProduct(const int n, const T* x, const T* y) {
+ T result = static_cast(0);
+ for (int i = 0; i < n; i++) {
+ result += x[i] * y[i];
+ }
+ return result;
+}
template
void vExp(const int n, const T* a, T* r);
diff --git a/paddle/math/Matrix.cpp b/paddle/math/Matrix.cpp
index 8bc42571f7c141aa31e18d0504b95b2ed4f0da77..4a2132c8d1bfa329ced575f9b78052bdbfe3e4d5 100644
--- a/paddle/math/Matrix.cpp
+++ b/paddle/math/Matrix.cpp
@@ -28,6 +28,7 @@ limitations under the License. */
#include "hl_top_k.h"
#include "paddle/utils/Logging.h"
+#include "paddle/function/GemmFunctor.h"
#include "paddle/utils/ThreadLocal.h"
#include "SIMDFunctions.h"
@@ -2773,24 +2774,24 @@ void CpuMatrix::mul(CpuMatrix* a, CpuMatrix* b, real scaleAB, real scaleT) {
CHECK(!isTransposed()) << "Not supported";
size_t a_col, b_col, a_row, b_row;
- CBLAS_TRANSPOSE a_trans, b_trans;
+ bool a_trans, b_trans;
if (!a->isTransposed()) {
a_col = a->getWidth();
a_row = a->getHeight();
- a_trans = CblasNoTrans;
+ a_trans = false;
} else {
a_col = a->getHeight();
a_row = a->getWidth();
- a_trans = CblasTrans;
+ a_trans = true;
}
if (!b->isTransposed()) {
b_col = b->getWidth();
b_row = b->getHeight();
- b_trans = CblasNoTrans;
+ b_trans = false;
} else {
b_col = b->getHeight();
b_row = b->getWidth();
- b_trans = CblasTrans;
+ b_trans = true;
}
CHECK_EQ(a_col, b_row);
@@ -2807,7 +2808,7 @@ void CpuMatrix::mul(CpuMatrix* a, CpuMatrix* b, real scaleAB, real scaleT) {
int lda = a->getStride();
int ldb = b->getStride();
int ldc = getStride();
- gemm(
+ BlasGemm::compute(
a_trans, b_trans, M, N, K, scaleAB, A, lda, B, ldb, scaleT, C, ldc);
}
diff --git a/paddle/math/Matrix.h b/paddle/math/Matrix.h
index 431d4e071072317c8fdfdc4f0d13e7cd4e3d062b..44180bca8bca53e74d71ce7bed3516399c01c81d 100644
--- a/paddle/math/Matrix.h
+++ b/paddle/math/Matrix.h
@@ -1616,6 +1616,10 @@ public:
};
class CpuMatrix : public Matrix {
+private:
+ MatrixPtr sftmaxSum_;
+ MatrixPtr sftmaxDot_;
+
public:
CpuMatrix(size_t height, size_t width, bool trans = false);
CpuMatrix(real* data, size_t height, size_t width, bool trans = false)
diff --git a/paddle/operators/CMakeLists.txt b/paddle/operators/CMakeLists.txt
index 25dbd236e6432d99b27f1a6ffc4e07bf0f994155..f9ea25ab045a02be5ab9ed81ef9c679126d3a188 100644
--- a/paddle/operators/CMakeLists.txt
+++ b/paddle/operators/CMakeLists.txt
@@ -14,27 +14,31 @@ function(op_library TARGET)
cmake_parse_arguments(op_library "${options}" "${oneValueArgs}"
"${multiValueArgs}" ${ARGN})
- foreach(src ${op_library_SRCS})
- if (${src} MATCHES ".*\\.cu$")
- list(APPEND cu_srcs ${src})
- elseif(${src} MATCHES ".*\\.cc$")
- list(APPEND cc_srcs ${src})
- else()
- message(FATAL_ERROR "${TARGET} Source file ${src} should only be .cc or .cu")
+ list(LENGTH op_library_SRCS op_library_SRCS_len)
+ if (${op_library_SRCS_len} EQUAL 0)
+ if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${TARGET}.cc)
+ list(APPEND cc_srcs ${TARGET}.cc)
endif()
- endforeach()
+ if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${TARGET}.cu)
+ list(APPEND cu_srcs ${TARGET}.cu)
+ endif()
+ else()
+ foreach(src ${op_library_SRCS})
+ if (${src} MATCHES ".*\\.cu$")
+ list(APPEND cu_srcs ${src})
+ elseif(${src} MATCHES ".*\\.cc$")
+ list(APPEND cc_srcs ${src})
+ else()
+ message(FATAL_ERROR "${TARGET} Source file ${src} should only be .cc or .cu")
+ endif()
+ endforeach()
+ endif()
list(LENGTH cc_srcs cc_srcs_len)
if (${cc_srcs_len} EQUAL 0)
message(FATAL_ERROR "The op library ${TARGET} should contains at least one .cc file")
endif()
- list(LENGTH cu_srcs cu_srcs_len)
- list(LENGTH op_library_DEPS dep_len)
- if (${cu_srcs_len} EQUAL 0 AND ${dep_len} EQUAL 0)
- message(WARNING "The op library ${TARGET} not support GPU!")
- endif()
-
if (WITH_GPU)
nv_library(${TARGET} SRCS ${cc_srcs} ${cu_srcs} DEPS ${op_library_DEPS}
${op_common_deps})
@@ -46,22 +50,22 @@ endfunction()
add_subdirectory(math)
-list(REMOVE_ITEM GENERAL_OPS
- net_op
- minus_op
- mul_op
- recurrent_op
- scale_op)
-
-op_library(net_op SRCS net_op.cc)
-op_library(minus_op SRCS minus_op.cc minus_op.cu DEPS scale_op)
-op_library(mul_op SRCS mul_op.cc mul_op.cu DEPS math_function)
+set(DEPS_OPS
+ identity_op
+ minus_op
+ mul_op
+ recurrent_op
+ scale_op)
+op_library(identity_op DEPS scale_op)
+op_library(minus_op DEPS scale_op)
+op_library(mul_op DEPS math_function)
op_library(recurrent_op SRCS recurrent_op.cc rnn/recurrent_op_utils.cc
DEPS framework_proto tensor operator net_op)
-op_library(scale_op SRCS scale_op.cc scale_op.cu DEPS net_op)
+op_library(scale_op DEPS net_op)
+list(REMOVE_ITEM GENERAL_OPS ${DEPS_OPS})
foreach(src ${GENERAL_OPS})
- op_library(${src} SRCS ${src}.cc ${src}.cu)
+ op_library(${src})
endforeach()
set(GLOB_OP_LIB ${OP_LIBRARY} CACHE INTERNAL "Global OP library")
diff --git a/paddle/operators/add_op.cc b/paddle/operators/add_op.cc
index 8ab748ed71e9a5dc0ee0259a78a2b886870bec5b..8dbd47cf0dfbc265032a9966343eed5c7bd8692e 100644
--- a/paddle/operators/add_op.cc
+++ b/paddle/operators/add_op.cc
@@ -57,7 +57,6 @@ class AddOpGrad : public framework::OperatorWithKernel {
} // namespace paddle
namespace ops = paddle::operators;
-REGISTER_OP(add_two, ops::AddOp, ops::AddOpMaker, add_two_grad, ops::AddOpGrad);
+REGISTER_OP(add, ops::AddOp, ops::AddOpMaker, add_grad, ops::AddOpGrad);
-REGISTER_OP_CPU_KERNEL(add_two,
- ops::AddKernel);
+REGISTER_OP_CPU_KERNEL(add, ops::AddKernel);
diff --git a/paddle/operators/add_op.cu b/paddle/operators/add_op.cu
index cec5f558cbc161124620ad4241d6bd8a5324277c..d9c6d20a6c320b59e57ed25da3dd8b093833f8c7 100644
--- a/paddle/operators/add_op.cu
+++ b/paddle/operators/add_op.cu
@@ -12,10 +12,7 @@
See the License for the specific language governing permissions and
limitations under the License. */
-#define EIGEN_USE_GPU
-#include "paddle/framework/op_registry.h"
#include "paddle/operators/add_op.h"
namespace ops = paddle::operators;
-REGISTER_OP_GPU_KERNEL(add_two,
- ops::AddKernel);
+REGISTER_OP_GPU_KERNEL(add, ops::AddKernel);
diff --git a/paddle/operators/concat_op.cc b/paddle/operators/concat_op.cc
new file mode 100644
index 0000000000000000000000000000000000000000..0ebefbab26ec8fdf316f852fbb7f6d9f3bbc48eb
--- /dev/null
+++ b/paddle/operators/concat_op.cc
@@ -0,0 +1,79 @@
+/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License. */
+
+#include "paddle/operators/concat_op.h"
+#include
+
+namespace paddle {
+namespace operators {
+using framework::Tensor;
+
+class ConcatOp : public framework::OperatorWithKernel {
+ public:
+ using framework::OperatorWithKernel::OperatorWithKernel;
+
+ protected:
+ void InferShape(const framework::InferShapeContext &ctx) const override {
+ auto ins = ctx.MultiInput("X");
+ auto *out = ctx.Output("Out");
+ size_t axis = static_cast(ctx.Attr("axis"));
+ size_t n = ins.size();
+
+ PADDLE_ENFORCE_GT(n, 1, "Input tensors count should > 1.");
+
+ auto out_dims = ins[0]->dims();
+ size_t in_zero_dims_size = out_dims.size();
+ for (size_t i = 1; i < n; i++) {
+ for (size_t j = 0; j < in_zero_dims_size; j++) {
+ if (j == axis) {
+ out_dims[axis] += ins[i]->dims()[j];
+ continue;
+ }
+ PADDLE_ENFORCE_EQ(out_dims[j], ins[i]->dims()[j],
+ "Input tensors should have the same "
+ "elements except the specify axis.")
+ }
+ }
+ out->Resize(out_dims);
+ }
+};
+
+class ConcatOpMaker : public framework::OpProtoAndCheckerMaker {
+ public:
+ ConcatOpMaker(framework::OpProto *proto, framework::OpAttrChecker *op_checker)
+ : OpProtoAndCheckerMaker(proto, op_checker) {
+ AddInput("X", "the input tensors of concat operator.").AsDuplicable();
+ AddOutput("Out", "the output tensor of concat operator.");
+ AddComment(R"DOC(
+ Join the input tensors along with the axis.
+ Examples:
+ Input[0] = [[1,2],[3,4]]
+ Input[1] = [[5,6]]
+ axis = 0
+ Output = [[1,2],
+ [3,4],
+ [5,6]]
+ )DOC");
+ AddAttr("axis", "The axis which the inputs will be joined with.")
+ .SetDefault(0);
+ }
+};
+
+} // namespace operators
+} // namespace paddle
+
+namespace ops = paddle::operators;
+REGISTER_OP_WITHOUT_GRADIENT(concat, ops::ConcatOp, ops::ConcatOpMaker)
+REGISTER_OP_CPU_KERNEL(concat,
+ ops::ConcatKernel)
diff --git a/paddle/operators/scatter_op.cu b/paddle/operators/concat_op.cu
similarity index 75%
rename from paddle/operators/scatter_op.cu
rename to paddle/operators/concat_op.cu
index 6716b478833ff3adb6112cdb1ee25b7f1744ea1f..38fee7473dbb2ba97fe95b6632db7a1749cf3bbe 100644
--- a/paddle/operators/scatter_op.cu
+++ b/paddle/operators/concat_op.cu
@@ -4,7 +4,7 @@ Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
+http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -13,8 +13,7 @@ See the License for the specific language governing permissions and
limitations under the License. */
#define EIGEN_USE_GPU
-#include "paddle/operators/scatter_op.h"
+#include "paddle/operators/concat_op.h"
namespace ops = paddle::operators;
-REGISTER_OP_GPU_KERNEL(scatter,
- ops::ScatterOpKernel);
+// TODO(Yancey1989) Add GPU kernel
diff --git a/paddle/operators/concat_op.h b/paddle/operators/concat_op.h
new file mode 100644
index 0000000000000000000000000000000000000000..f977054fdf8aa0164db726b94a21c57f770dd674
--- /dev/null
+++ b/paddle/operators/concat_op.h
@@ -0,0 +1,64 @@
+/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License. */
+
+#pragma once
+
+#include
+#include "paddle/framework/op_registry.h"
+
+namespace paddle {
+namespace operators {
+
+template
+class ConcatKernel : public framework::OpKernel {
+ public:
+ void Compute(const framework::ExecutionContext& ctx) const override {
+ auto ins = ctx.MultiInput("X");
+ auto* out = ctx.Output("Out");
+ int64_t axis = static_cast(ctx.Attr("axis"));
+ size_t n = ins.size();
+ size_t output_axis_dim = 0;
+ size_t before = 1, after = 1;
+ for (size_t i = 0; i < n; i++) {
+ output_axis_dim += ins[i]->dims()[axis];
+ }
+ auto& input_zero = ins[0];
+ for (int64_t i = 0; i < input_zero->dims().size(); i++) {
+ if (i == axis) {
+ continue;
+ }
+ if (i < axis) {
+ before *= input_zero->dims()[i];
+ } else {
+ after *= input_zero->dims()[i];
+ }
+ }
+ size_t output_offset = 0;
+ for (size_t i = 0; i < n; i++) {
+ auto& in = ins[i];
+ auto axis_dim = in->dims()[axis];
+ for (size_t j = 0; j < before; j++) {
+ size_t len = axis_dim * after * sizeof(T);
+ const T* src = in->data() + axis_dim * after * j;
+ T* out_data = out->mutable_data(platform::CPUPlace());
+ T* dest = out_data + output_offset + output_axis_dim * after * j;
+ memcpy(dest, src, len);
+ }
+ output_offset += axis_dim * after;
+ }
+ }
+};
+
+} // namespace operators
+} // namespace paddle
diff --git a/paddle/operators/cos_sim_op.cc b/paddle/operators/cos_sim_op.cc
index e3bee437921356c2dafbe30b98f4b8d5e49049c8..3d0af97aae79089d10d94cb636775c5c6c092d56 100644
--- a/paddle/operators/cos_sim_op.cc
+++ b/paddle/operators/cos_sim_op.cc
@@ -119,10 +119,10 @@ class CosSimOpGrad : public framework::OperatorWithKernel {
PADDLE_ENFORCE(x_dims[0] == y_dims[0] || y_dims[0] == 1,
"The 1st dimension of Input(Y) must be equal to Input(X) or"
" just 1 (which will be broadcasted to match Input(X)).");
- auto target_xnorm_dims = framework::make_ddim({x_dims[0], 1}),
- auto target_ynorm_dims = framework::make_ddim({y_dims[0], 1}),
- PADDLE_ENFORCE_EQ(xnorm_dims, target_xnorm_dims,
- "Shape of Input(XNorm) must be [X.Dim(0), 1].");
+ auto target_xnorm_dims = framework::make_ddim({x_dims[0], 1});
+ auto target_ynorm_dims = framework::make_ddim({y_dims[0], 1});
+ PADDLE_ENFORCE_EQ(xnorm_dims, target_xnorm_dims,
+ "Shape of Input(XNorm) must be [X.Dim(0), 1].");
PADDLE_ENFORCE_EQ(ynorm_dims, target_ynorm_dims,
"Shape of Input(YNorm) must be [Y.Dim(0), 1].");
PADDLE_ENFORCE_EQ(out_dims, target_xnorm_dims,
diff --git a/paddle/operators/cos_sim_op.h b/paddle/operators/cos_sim_op.h
index 4d03d5902d5866e2428ad729285b51c8d1eb05c6..318b63f3707cf77755de773a39b00aa30d2296d3 100644
--- a/paddle/operators/cos_sim_op.h
+++ b/paddle/operators/cos_sim_op.h
@@ -23,6 +23,9 @@ using Tensor = framework::Tensor;
template
using EigenMatrix = framework::EigenMatrix;
+template
+using EigenVector = framework::EigenVector;
template
class CosSimKernel : public framework::OpKernel {
@@ -41,12 +44,11 @@ class CosSimKernel : public framework::OpKernel {
// convert Tensor to Eigen Tensor
int rows_x = in_x->dims()[0];
int rows_y = in_y->dims()[0];
- int cols = framework::product(in_x->dims()) / rows_x;
auto x = EigenMatrix::Reshape(*in_x, 1);
auto y = EigenMatrix::Reshape(*in_y, 1);
- auto z = EigenMatrix::From(*out_z);
- auto x_norm = EigenMatrix::From(*out_x_norm);
- auto y_norm = EigenMatrix::From(*out_y_norm);
+ auto z = EigenVector::Flatten(*out_z);
+ auto x_norm = EigenVector::Flatten(*out_x_norm);
+ auto y_norm = EigenVector::Flatten(*out_y_norm);
// compute
auto place = context.GetEigenDevice();
@@ -81,10 +83,10 @@ class CosSimGradKernel : public framework::OpKernel {
// convert Tensor to Eigen Tensor
auto x = EigenMatrix::Reshape(*in_x, 1);
auto y = EigenMatrix::Reshape(*in_y, 1);
- auto z = EigenMatrix::From(*in_z);
- auto x_norm = EigenMatrix::From(*in_x_norm);
- auto y_norm = EigenMatrix::From(*in_y_norm);
- auto dz = EigenMatrix::From(*in_grad_z);
+ auto z = EigenMatrix::Reshape(*in_z, 1);
+ auto x_norm = EigenMatrix::Reshape(*in_x_norm, 1);
+ auto y_norm = EigenMatrix::Reshape(*in_y_norm, 1);
+ auto dz = EigenMatrix::Reshape(*in_grad_z, 1);
// compute gradident
int rows_x = in_x->dims()[0];
@@ -108,16 +110,18 @@ class CosSimGradKernel : public framework::OpKernel {
// compute dy
if (out_grad_y) {
out_grad_y->mutable_data(context.GetPlace());
- auto dy = EigenMatrix::Reshape(*out_grad_y, 1) auto grad =
- x / norm_prod_bcast - z_bcast * y / y_snorm_bcast;
+ auto dy = EigenMatrix::Reshape(*out_grad_y, 1);
+ auto grad = x / norm_prod_bcast - z_bcast * y / y_snorm_bcast;
dy.device(place) = dz_bcast * grad;
}
} else {
Eigen::DSizes bcast_rows(rows_x, 1);
- Eigen::DSizes bcast_rows_cols(rows_x, 1);
+ Eigen::DSizes bcast_rows_cols(rows_x, cols);
auto y_bcast = y.broadcast(bcast_rows);
auto y_snorm_bcast = y_norm.square().eval().broadcast(bcast_rows_cols);
- auto norm_prod_bcast = x_norm * y_norm.broadcast(bcast_rows_cols);
+ auto norm_prod_bcast = (x_norm * y_norm.eval().broadcast(bcast_rows))
+ .eval()
+ .broadcast(bcast_cols);
// compute dx
if (out_grad_x) {
out_grad_x->mutable_data(context.GetPlace());
diff --git a/paddle/operators/gaussian_random_op.cc b/paddle/operators/gaussian_random_op.cc
index 8bb61275badfccec49953015a47b87b0879153bf..3d76516405960c502a46997108049b2db5cab6bf 100644
--- a/paddle/operators/gaussian_random_op.cc
+++ b/paddle/operators/gaussian_random_op.cc
@@ -19,19 +19,19 @@ template
class CPUGaussianRandomKernel : public framework::OpKernel {
public:
void Compute(const framework::ExecutionContext& context) const override {
- float mean = context.GetAttr("mean");
- float std = context.GetAttr("std");
+ float mean = context.Attr("mean");
+ float std = context.Attr("std");
auto* tensor = context.Output("Out");
T* data = tensor->mutable_data(context.GetPlace());
- unsigned int seed = static_cast(context.GetAttr("seed"));
+ unsigned int seed = static_cast(context.Attr("seed"));
std::minstd_rand engine;
if (seed == 0) {
seed = std::random_device()();
}
engine.seed(seed);
std::normal_distribution dist(mean, std);
- int64_t size = framework::product(tensor->dims());
+ int64_t size = tensor->numel();
for (int64_t i = 0; i < size; ++i) {
data[i] = dist(engine);
}
@@ -45,7 +45,7 @@ class GaussianRandomOp : public framework::OperatorWithKernel {
protected:
void InferShape(const framework::InferShapeContext& context) const override {
auto* tensor = context.Output("Out");
- auto dims = GetAttr>("dims");
+ auto dims = Attr>("dims");
std::vector temp;
temp.reserve(dims.size());
for (auto dim : dims) {
diff --git a/paddle/operators/gaussian_random_op.cu b/paddle/operators/gaussian_random_op.cu
index 833a82bbf293a0892531283dc681ca2edd72f6a1..2d63b3049988cfc3135a87a57dad56b970df3eab 100644
--- a/paddle/operators/gaussian_random_op.cu
+++ b/paddle/operators/gaussian_random_op.cu
@@ -42,16 +42,16 @@ class GPUGaussianRandomKernel : public framework::OpKernel {
void Compute(const framework::ExecutionContext& context) const override {
auto* tensor = context.Output("Out");
T* data = tensor->mutable_data(context.GetPlace());
- unsigned int seed = static_cast(context.GetAttr("seed"));
+ unsigned int seed = static_cast(context.Attr("seed"));
if (seed == 0) {
std::random_device rd;
seed = rd();
}
- T mean = static_cast(context.GetAttr("mean"));
- T std = static_cast(context.GetAttr("std"));
+ T mean = static_cast