diff --git a/.travis.yml b/.travis.yml
index d8f3c0be9bf1b2641ee559bcdee73bfd3124ed60..83f0f45ad10772184b80f000e5abb9d4dc6a36b1 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
- $TRAVIS_BUILD_DIR/build_ios/third_party
sudo: required
dist: trusty
@@ -13,7 +12,6 @@ os:
env:
- JOB=build_doc
- JOB=check_style
- - JOB=build_android
matrix:
include:
- env: JOB=build_ios
@@ -30,7 +28,6 @@ addons:
- python
- python-pip
- python2.7-dev
- - python-numpy
- python-wheel
- libboost-dev
- curl
diff --git a/CMakeLists.txt b/CMakeLists.txt
index ba1febe5e4f2c8a4a21da6a0069652724a94e438..52f9b641095f5fd7b1f30a7163acdb47fdb3ca07 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -65,8 +65,8 @@ if(NOT CMAKE_BUILD_TYPE)
endif()
if(ANDROID OR IOS)
- if(ANDROID AND ${CMAKE_SYSTEM_VERSION} VERSION_LESS "21")
- message(FATAL_ERROR "Unsupport standalone toolchains with Android API level lower than 21")
+ if(ANDROID AND ${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 563633c517fe717c67644252729643fef4f4c217..1cecf443ae356f7fe41ad2fe839238564c5eb0c4 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/api/v2/config/layer.rst b/doc/api/v2/config/layer.rst
index 1329b77bb44f52c66a703740715b890c47234e72..c94627a72806fa2eca77c79da24f7f3ca18f0259 100644
--- a/doc/api/v2/config/layer.rst
+++ b/doc/api/v2/config/layer.rst
@@ -434,9 +434,9 @@ lambda_cost
.. autoclass:: paddle.v2.layer.lambda_cost
:noindex:
-mse_cost
+square_error_cost
--------
-.. autoclass:: paddle.v2.layer.mse_cost
+.. autoclass:: paddle.v2.layer.square_error_cost
:noindex:
rank_cost
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
new file mode 100644
index 0000000000000000000000000000000000000000..51b7f87638f8ddff752328a562fe0dd0fe56cfd1
--- /dev/null
+++ b/doc/design/graph.md
@@ -0,0 +1,70 @@
+# 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.
+
+This document explains that the construction of a graph as three steps:
+
+- construct the forward part
+- 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
+x = layer.data("images")
+l = layer.data("label")
+y = layer.fc(x)
+cost = layer.mse(y, l)
+optimize(cost)
+train(cost, reader=mnist.train())
+```
+
+### Forward Part
+
+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, 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.
+
+### Backward Part
+
+The fifth line `optimize(cost)` calls two functions, `ConstructBackwardGraph` and `ConstructOptimizationGraph`.
+
+`ConstructBackwardGraph` traverses the forward graph in the `BlockDesc` protobuf message and builds the backward part.
+
+![](images/graph_construction_example_forward_backward.png)
+
+According to the chain rule of gradient computation, `ConstructBackwardGraph` would
+
+1. create a gradient operator G for each operator F,
+1. make all inputs, outputs, and outputs' gradient of F as inputs of G,
+1. create gradients for all inputs of F, except for those who don't have gradients, like x and l, and
+1. make all these gradients as outputs of G.
+
+### Optimization Part
+
+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.bash b/doc/design/images/graph_construction_example.bash
new file mode 100755
index 0000000000000000000000000000000000000000..35e6997abd17588e17a82d448918fc1b3bd7220e
--- /dev/null
+++ b/doc/design/images/graph_construction_example.bash
@@ -0,0 +1,11 @@
+cat ./graph_construction_example.dot | \
+ sed 's/color=red/color=red, style=invis/g' | \
+ sed 's/color=green/color=green, style=invis/g' | \
+ dot -Tpng > graph_construction_example_forward_only.png
+
+cat ./graph_construction_example.dot | \
+ sed 's/color=green/color=green, style=invis/g' | \
+ dot -Tpng > graph_construction_example_forward_backward.png
+
+cat ./graph_construction_example.dot | \
+ dot -Tpng > graph_construction_example_all.png
diff --git a/doc/design/images/graph_construction_example.dot b/doc/design/images/graph_construction_example.dot
new file mode 100644
index 0000000000000000000000000000000000000000..8d1b673abf6b78c851676fa379dc850c4818f0e5
--- /dev/null
+++ b/doc/design/images/graph_construction_example.dot
@@ -0,0 +1,69 @@
+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];
+
+ x [label="x", color=blue, shape=oval];
+ l [label="l", color=blue, shape=oval];
+ y [label="y", color=blue, shape=oval];
+ W [label="W", color=blue, shape=doublecircle];
+ b [label="b", color=blue, shape=doublecircle];
+ cost [label="cost", color=blue, shape=oval];
+
+ 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];
+
+ ////////// The backward part /////////
+ MSE_Grad [label="MSE_grad", color=red, shape=box];
+ FC_Grad [label="FC_grad", color=red, shape=box];
+
+ d_cost [label="d cost", color=red, shape=oval];
+ d_y [label="d y", color=red, shape=oval];
+ d_b [label="d b", color=red, shape=oval];
+ d_W [label="d W", color=red, shape=oval];
+
+ cost -> MSE_Grad [color=red];
+ d_cost -> MSE_Grad [color=red];
+ x -> MSE_Grad [color=red];
+ l -> MSE_Grad [color=red];
+ y -> MSE_Grad -> d_y [color=red];
+
+ x -> FC_Grad [color=red];
+ y -> FC_Grad [color=red];
+ d_y -> FC_Grad [color=red];
+ W -> FC_Grad -> d_W [color=red];
+ b -> FC_Grad -> d_b [color=red];
+
+ ////////// The optimizaiton part //////////
+
+ OPT_W [label="SGD", color=green, shape=box];
+ OPT_b [label="SGD", color=green, shape=box];
+
+ W -> OPT_W [color=green];
+ b -> OPT_b [color=green];
+ d_W -> OPT_W -> W [color=green];
+ d_b -> OPT_b -> b [color=green];
+
+ ////////// Groupings //////////
+
+ subgraph clusterMSE {
+ style=invis;
+ MSE;
+ MSE_Grad;
+ }
+
+ subgraph clusterFC {
+ style=invis;
+ FC;
+ FC_Grad;
+ }
+}
diff --git a/doc/design/images/graph_construction_example_all.png b/doc/design/images/graph_construction_example_all.png
new file mode 100644
index 0000000000000000000000000000000000000000..181187503472d15779b87284105841168b3945c4
Binary files /dev/null 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
new file mode 100644
index 0000000000000000000000000000000000000000..3049a9315fd616464dec54e33064cb75598ca536
Binary files /dev/null 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
new file mode 100644
index 0000000000000000000000000000000000000000..25d19088cbf0b5f68cf734f2ff21eba8af4a2860
Binary files /dev/null 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/getstarted/basic_usage/index_cn.rst b/doc/getstarted/basic_usage/index_cn.rst
index 428f58830e0b10c024f31238b7404c6df193eecd..b473944fc7fb89d3e0a0b330933f2226734bb5bd 100644
--- a/doc/getstarted/basic_usage/index_cn.rst
+++ b/doc/getstarted/basic_usage/index_cn.rst
@@ -55,7 +55,7 @@ PaddlePaddle是源于百度的一个深度学习平台。这份简短的介绍
# 线性计算网络层: ȳ = wx + b
ȳ = fc_layer(input=x, param_attr=ParamAttr(name='w'), size=1, act=LinearActivation(), bias_attr=ParamAttr(name='b'))
# 计算误差函数,即 ȳ 和真实 y 之间的距离
- cost = mse_cost(input= ȳ, label=y)
+ cost = square_error_cost(input= ȳ, label=y)
outputs(cost)
@@ -69,7 +69,7 @@ PaddlePaddle是源于百度的一个深度学习平台。这份简短的介绍
- **数据层**:数据层 `data_layer` 是神经网络的入口,它读入数据并将它们传输到接下来的网络层。这里数据层有两个,分别对应于变量 `x` 和 `y`。
- **全连接层**:全连接层 `fc_layer` 是基础的计算单元,这里利用它建模变量之间的线性关系。计算单元是神经网络的核心,PaddlePaddle支持大量的计算单元和任意深度的网络连接,从而可以拟合任意的函数来学习复杂的数据关系。
- - **回归误差代价层**:回归误差代价层 `mse_cost` 是众多误差代价函数层的一种,它们在训练过程作为网络的出口,用来计算模型的误差,是模型参数优化的目标函数。
+ - **回归误差代价层**:回归误差代价层 `square_error_cost` 是众多误差代价函数层的一种,它们在训练过程作为网络的出口,用来计算模型的误差,是模型参数优化的目标函数。
定义了网络结构并保存为 `trainer_config.py` 之后,运行以下训练命令:
diff --git a/doc/getstarted/basic_usage/index_en.rst b/doc/getstarted/basic_usage/index_en.rst
index 6775da20c2f51000f305b095d40abd27b8fa6c0e..2cc438ebbe0f97345d25354b93b4ebbd43502415 100644
--- a/doc/getstarted/basic_usage/index_en.rst
+++ b/doc/getstarted/basic_usage/index_en.rst
@@ -49,7 +49,7 @@ To recover this relationship between ``X`` and ``Y``, we use a neural network wi
x = data_layer(name='x', size=1)
y = data_layer(name='y', size=1)
y_predict = fc_layer(input=x, param_attr=ParamAttr(name='w'), size=1, act=LinearActivation(), bias_attr=ParamAttr(name='b'))
- cost = mse_cost(input=y_predict, label=y)
+ cost = square_error_cost(input=y_predict, label=y)
outputs(cost)
Some of the most fundamental usages of PaddlePaddle are demonstrated:
diff --git a/doc/getstarted/concepts/src/train.py b/doc/getstarted/concepts/src/train.py
index 7e604f23de38543a00f305d508af0791193f78ba..8aceb23406a476f08639cc6223cdf730b728a705 100644
--- a/doc/getstarted/concepts/src/train.py
+++ b/doc/getstarted/concepts/src/train.py
@@ -8,7 +8,7 @@ paddle.init(use_gpu=False)
x = paddle.layer.data(name='x', type=paddle.data_type.dense_vector(2))
y_predict = paddle.layer.fc(input=x, size=1, act=paddle.activation.Linear())
y = paddle.layer.data(name='y', type=paddle.data_type.dense_vector(1))
-cost = paddle.layer.mse_cost(input=y_predict, label=y)
+cost = paddle.layer.square_error_cost(input=y_predict, label=y)
# create parameters
parameters = paddle.parameters.create(cost)
diff --git a/doc/getstarted/concepts/use_concepts_cn.rst b/doc/getstarted/concepts/use_concepts_cn.rst
index f15b11bd780402a3ec1755900e8c648f5d2a7bc5..c243083794bb3c4659242de99b3b2715af9d7c24 100644
--- a/doc/getstarted/concepts/use_concepts_cn.rst
+++ b/doc/getstarted/concepts/use_concepts_cn.rst
@@ -81,9 +81,9 @@ PaddlePaddle支持不同类型的输入数据,主要包括四种类型,和
.. code-block:: bash
y_predict = paddle.layer.fc(input=x, size=1, act=paddle.activation.Linear())
- cost = paddle.layer.mse_cost(input=y_predict, label=y)
+ cost = paddle.layer.square_error_cost(input=y_predict, label=y)
-其中,x与y为之前描述的输入层;而y_predict是接收x作为输入,接上一个全连接层;cost接收y_predict与y作为输入,接上均方误差层。
+其中,x与y为之前描述的输入层;而y_predict是接收x作为输入,接上一个全连接层;cost接收y_predict与y作为输入,接上平方误差层。
最后一层cost中记录了神经网络的所有拓扑结构,通过组合不同的layer,我们即可完成神经网络的搭建。
@@ -147,4 +147,4 @@ PaddlePaddle支持不同类型的输入数据,主要包括四种类型,和
.. literalinclude:: src/train.py
:linenos:
-有关线性回归的实际应用,可以参考PaddlePaddle book的 `第一章节 `_。
\ No newline at end of file
+有关线性回归的实际应用,可以参考PaddlePaddle book的 `第一章节 `_。
diff --git a/doc/howto/dev/new_op_cn.md b/doc/howto/dev/new_op_cn.md
index ec79b7f42b2d70df8fcb25faca5bc3a4759e177c..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,168 +177,193 @@ 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`调用的函数是否支持不同设备。**
+
+`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`**。
-`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`接口,该接口参数为`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)。
-
-到此前向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, 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`为其反向Op。
- - `REGISTER_OP_WITHOUT_GRADIENT` : 用于注册没有反向的Op。
- - `REGISTER_OP_CPU_KERNEL` :注册`ops::MulKernel`类,并特化模板参数为`paddle::platform::CPUPlace`和`float`类型,同理,注册`ops::MulKernel`类。
-
-在 `.cu`文件中注册GPU Kernel。
-
-```c++
-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);
```
-
- 使用`USE_OP`告知编译器需要链接该Op的目标文件,具体解释参考[代码注释](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/framework/op_registry.h#L81)。
-
-
+
+ 如果OP不带Kernel,则使用`USE_NO_KENREL_OP`:
+
+ ```
+ USE_NO_KENREL_OP(recurrent);
+ ```
+
+
- 生成库
- 在 [`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前向计算的输出进行对比。
+
+
+ ```python
+ import unittest
+ import numpy as np
+ from gradient_checker import GradientChecker, create_op
+ from op_test_util import OpTestMeta
-class TestMulOp(unittest.TestCase):
- __metaclass__ = OpTestMeta
+ 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'])}
+ ```
+
+上面的代码首先导入依赖的包,下面是对`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.type = "mul"
+ self.op = create_op("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结算结果。
-
-
-### 反向Operator单测
-
-反向Op单测继承自`GradientChecker`,而`GradientChecker`集成自`unittest.TestCase`,所以反向单测函数需要`test_`开头。
-
- ```
- class MulGradOpTest(GradientChecker):
- def test_mul(self):
- op = create_op("mul")
- inputs = {
- 'X': np.random.random((32, 84)).astype("float32"),
- 'Y': np.random.random((84, 100)).astype("float32")
- }
- self.compare_grad(op, inputs)
+
+ def test_cpu_gpu_compare(self):
+ self.compare_grad(self.op, self.inputs)
+
+ def test_normal(self):
# mul op will enlarge the relative error
self.check_grad(
- op, inputs, set(["X", "Y"]), "Out", max_relative_error=0.5)
- ```
+ self.op, self.inputs, ["X", "Y"], "Out", max_relative_error=0.5)
- - 调用`create_op("mul")`创建反向Op对应的前向Op。
- - 定义输入`inputs`。
- - 调用`compare_grad`函数对比CPU、GPU计算结果。
- - 调用`check_grad`检查梯度稳定性,这里采用数值法检测梯度正确性。
- - 第一个参数`op` : 前向op。
- - 第二个参数`inputs` : 输入词典,词典的Key和`ProtoMaker`定义保持一致。
- - 第三个参数`set(["X", "Y"])` : 指定对输入变量`X`、`Y`做梯度检测。
- - 第四个参数`"Out"` : 指定前向网络最终的输出目标变量`Out`
+ def test_ignore_x(self):
+ self.check_grad(
+ self.op,
+ self.inputs, ["Y"],
+ "Out",
+ max_relative_error=0.5,
+ no_grad_set={"X"})
+ def test_ignore_y(self):
+ self.check_grad(
+ self.op,
+ self.inputs, ["X"],
+ "Out",
+ max_relative_error=0.5,
+ no_grad_set={"Y"})
+```
-### 编译和执行
+下面解释代码中一些关键的地方:
-单测完成之后,在[`python/paddle/v2/framework/tests/CMakeLists.txt`](https://github.com/PaddlePaddle/Paddle/blob/develop/python/paddle/v2/framework/tests/CMakeLists.txt)里添加编译:
+- 调用`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`分支用来测试只需要计算一个输入梯度的情况。
-```
-py_test(test_mul_op SRCS test_mul_op.py)
-```
-编译时需要打开`WITH_TESTING`, 即 `cmake paddle_dir -DWITH_TESTING=ON`,编译成功之后执行单测命令为:
+### 编译和执行单元测试
-```
+`python/paddle/v2/framework/tests` 目录下新增的 `test_*.py` 单元测试会被自动加入工程进行编译。
+
+请注意,**不同于Op的编译测试,运行单元测试测时需要编译整个工程**,并且编译时需要打开`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/use_eigen_cn.md b/doc/howto/dev/use_eigen_cn.md
new file mode 100644
index 0000000000000000000000000000000000000000..1367323b71277984834d9d4f0d9bea0f69478479
--- /dev/null
+++ b/doc/howto/dev/use_eigen_cn.md
@@ -0,0 +1,146 @@
+## 在Paddle中如何使用Eigen
+
+神经网络本质上是一个计算图,计算需要的数据存放在`Tensor`中,而计算过程是由`Operartor`来描述的。在执行时,`Operator`调用对应`OpKernel`中的`Compute`接口,实现对`Tensor`的操作。
+
+
+### Eigen Tensor模块
+
+Eigen Tensor模块对element-wise计算提供了强大的支持,并且书写一份代码,可以同时在CPU、GPU执行。但Eigen Tensor是一个正在开发中的模块,因此可能测试不够完备,文档较少。
+
+关于Eigen Tensor模块的详细介绍请参考[文档1](https://github.com/RLovelett/eigen/blob/master/unsupported/Eigen/CXX11/src/Tensor/README.md) 和[文档2](https://bitbucket.org/eigen/eigen/src/default/unsupported/Eigen/CXX11/src/Tensor/README.md)
+
+
+### paddle::framework::Tensor
+
+Paddle Tensor定义在framework目录下,其主要接口如下:
+
+```cpp
+class Tensor {
+ public:
+ /*! Return a pointer to mutable memory block. */
+ template
+ inline T* data();
+
+ /**
+ * @brief Return a pointer to mutable memory block.
+ * @note If not exist, then allocation.
+ */
+ template
+ inline T* mutable_data(platform::Place place);
+
+ /**
+ * @brief Return a pointer to mutable memory block.
+ *
+ * @param[in] dims The dimensions of the memory block.
+ * @param[in] place The place of the memory block.
+ *
+ * @note If not exist, then allocation.
+ */
+ template
+ inline T* mutable_data(DDim dims, platform::Place place);
+
+ /*! Resize the dimensions of the memory block. */
+ inline Tensor& Resize(const DDim& dims);
+
+ /*! Return the dimensions of the memory block. */
+ inline const DDim& dims() const;
+
+ private:
+ /*! holds the memory block if allocated. */
+ std::shared_ptr holder_;
+
+ /*! points to dimensions of memory block. */
+ DDim dim_;
+};
+```
+
+`Placeholder`的作用是延迟分配内存,即我们可以先定义一个Tensor,然后使用Resize接口设置Tensor的大小,最后再调用mutable_data接口分配实际的内存。
+
+```cpp
+paddle::framework::Tensor t;
+paddle::platform::CPUPlace place;
+// set size first
+t.Resize({2, 3});
+// allocate memory on CPU later
+t.mutable_data(place);
+```
+
+### paddle::framework::Tensor使用样例
+下面以AddOp为例说明Tensor的使用过程:
+
+- InferShape
+
+在运行神经网络计算图时,我们先调用每个`Operator`的`InferShape`接口,根据输入Tensor的大小来设置输出Tensor的大小,`Resize`接口会被调用。
+
+```cpp
+void InferShape(const framework::InferShapeContext &ctx) const override {
+ PADDLE_ENFORCE_EQ(ctx.Input("X")->dims(),
+ ctx.Input("Y")->dims(),
+ "Two input of Add Op's dimension must be same.");
+ ctx.Output("Out")->Resize(ctx.Input("X")->dims());
+}
+```
+
+
+- Run
+
+`Operator`的`Run`接口最终会调用对应`OpKernel`的`Compute`接口,在这时真正的分配内存,`mutable_data`接口会被调用。
+
+```cpp
+void Compute(const framework::ExecutionContext& context) const override {
+ auto* input0 = context.Input("X");
+ auto* input1 = context.Input("Y");
+ auto* output = context.Output("Out");
+
+ output->mutable_data(context.GetPlace());
+
+ auto x = EigenVector::Flatten(*input0);
+ auto y = EigenVector::Flatten(*input1);
+ auto z = EigenVector::Flatten(*output);
+
+ auto place = context.GetEigenDevice();
+
+ z.device(place) = x + y;
+}
+```
+
+
+### paddle::framework::Tensor到EigenTensor的转换
+
+如上一小节所示,在具体的计算中,我们需要先把输入Tensor和输出Tensor转换为Eigen支持的格式。我们在[eigen.h](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/framework/eigen.h)中提供了一些全局函数用来实现paddle::framework::Tensor到EigenTensor/EigenMatrix/EigenVector/EigenScalar的转换。
+
+以EigenTensor为例,做一个介绍
+
+```cpp
+Tensor t;
+float* p = t.mutable_data(make_ddim({1, 2, 3}), platform::CPUPlace());
+for (int i = 0; i < 1 * 2 * 3; i++) {
+ p[i] = static_cast(i);
+}
+
+EigenTensor::Type et = EigenTensor::From(t);
+```
+
+From是EigenTensor模板提供的一个接口,可以实现从paddle::framework::Tensor到对EigenTensor的转换。由于Tensor的rank是模板参数,因此在转换时需要显示的指定。
+
+在Eigen中,不同rank的Tensor是不同类型,Vector是rank为1的Tensor。需要额外注意的是,EigenVector::From方法是把paddle中的一维Tensor转为Eigen的一维Tensor,在这里用EigenVector来表示;而EigenVector::Flatten方法是把paddle中的一个Tensor进行reshape操作,压扁成为Eigen的一维Tensor,类型仍然为EigenVector。
+
+更多的转换方法请参考eigen_test.cc中的[单元测试](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/framework/eigen_test.cc)。
+
+
+
+### 实现计算
+
+当需要完成计算时,我们需要等式左边的EigenTensor调用device接口。在这里需要注意的是,这里的EigenTensor之间的运算只是改变了原有Tensor中的数据,而不会改变原有Tensor的shape信息。
+
+```cpp
+auto x = EigenVector::Flatten(*input0);
+auto y = EigenVector::Flatten(*input1);
+auto z = EigenVector::Flatten(*output);
+auto place = context.GetEigenDevice();
+z.device(place) = x + y;
+```
+
+在这段代码中,input0/input1/output可以是任意维度的Tensor。我们调用了EigenVector的Flatten接口,把任意维度的Tensor转为了一维的EigenVector。而在计算结束之后,input0/input1/output的原有shape信息不变。如果想改变原有Tensor的shape信息,可以调用Resize接口进行改变。
+
+由于Eigen Tensor模块的文档较少,我们可以参考TensorFlow的[kernels](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/kernels)模块下的相关`OpKernel`的计算代码。
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/doc/howto/usage/k8s/k8s_distributed_cn.md b/doc/howto/usage/k8s/k8s_distributed_cn.md
index 3121b3f59df650c0a22d0bd305a6f793b202d30e..a9bebf09558b06993119803458977abedbbfbdd0 100644
--- a/doc/howto/usage/k8s/k8s_distributed_cn.md
+++ b/doc/howto/usage/k8s/k8s_distributed_cn.md
@@ -213,7 +213,7 @@ I1116 09:10:17.123440 50 Util.cpp:130] Calling runInitFunctions
I1116 09:10:17.123764 50 Util.cpp:143] Call runInitFunctions done.
[WARNING 2016-11-16 09:10:17,227 default_decorators.py:40] please use keyword arguments in paddle config.
[INFO 2016-11-16 09:10:17,239 networks.py:1282] The input order is [movie_id, title, genres, user_id, gender, age, occupation, rating]
-[INFO 2016-11-16 09:10:17,239 networks.py:1289] The output order is [__mse_cost_0__]
+[INFO 2016-11-16 09:10:17,239 networks.py:1289] The output order is [__square_error_cost_0__]
I1116 09:10:17.392917 50 Trainer.cpp:170] trainer mode: Normal
I1116 09:10:17.613910 50 PyDataProvider2.cpp:257] loading dataprovider dataprovider::process
I1116 09:10:17.680917 50 PyDataProvider2.cpp:257] loading dataprovider dataprovider::process
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.cc b/paddle/framework/attribute.cc
index 9eb07acdff1d00dd926f1cee9c24f9f151006d7e..27132eaa0b3b0666fc042faf052dac2e169ba9e7 100644
--- a/paddle/framework/attribute.cc
+++ b/paddle/framework/attribute.cc
@@ -43,6 +43,10 @@ template <>
AttrType AttrTypeID>() {
return STRINGS;
}
+template <>
+AttrType AttrTypeID>>() {
+ return INT_PAIRS;
+}
Attribute GetAttrValue(const OpDesc::Attr& attr_desc) {
switch (attr_desc.type()) {
@@ -76,6 +80,14 @@ Attribute GetAttrValue(const OpDesc::Attr& attr_desc) {
}
return val;
}
+ case paddle::framework::AttrType::INT_PAIRS: {
+ std::vector> val(attr_desc.int_pairs_size());
+ for (int i = 0; i < attr_desc.int_pairs_size(); ++i) {
+ val[i].first = attr_desc.int_pairs(i).first();
+ val[i].second = attr_desc.int_pairs(i).second();
+ }
+ return val;
+ }
}
PADDLE_ENFORCE(false, "Unknown OpDesc::AttrDesc::type !");
return boost::blank();
diff --git a/paddle/framework/attribute.h b/paddle/framework/attribute.h
index 08b47cabd4c2225c50022bd35734dcc2663324d6..2b788a76cafe198abb9aed8ba842e37cc6ff73a6 100644
--- a/paddle/framework/attribute.h
+++ b/paddle/framework/attribute.h
@@ -28,7 +28,8 @@ namespace paddle {
namespace framework {
typedef boost::variant,
- std::vector, std::vector>
+ std::vector, std::vector,
+ std::vector>>
Attribute;
typedef std::unordered_map AttributeMap;
@@ -40,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:
@@ -109,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.cc b/paddle/framework/backward.cc
index 6b4c612cd8d9263258e3987914c44002e7bca92c..c5d46622156c56acb98fb77e7db5ee7bca8c937a 100644
--- a/paddle/framework/backward.cc
+++ b/paddle/framework/backward.cc
@@ -182,7 +182,7 @@ static std::unique_ptr BackwardRecursive(
});
// process recurrent gradient op as a special operator.
- if (forwardOp.Type() == "recurrent_op") {
+ if (forwardOp.Type() == "recurrent") {
// NOTE clean up cycle call somewhere (RNN's stepnet constains itself), or
// this will result in infinite loop.
const auto& rnnop =
diff --git a/paddle/framework/backward.md b/paddle/framework/backward.md
index 9500c92a265d60a696e1e2c422d0f2bd1621ef71..0a6d762bc8be5201ac196b4bc6107c06d07a31d7 100644
--- a/paddle/framework/backward.md
+++ b/paddle/framework/backward.md
@@ -2,81 +2,99 @@
## 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, MulOpGrad);
+REGISTER_OP(mul, MulOp, MulOpMaker, mul_grad, MulOpGrad);
```
`mul` is the operator's type. `MulOp` and `MulOpMaker` are the operator class and the operator maker class respectively.
`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/backward_test.cc b/paddle/framework/backward_test.cc
index bf8b11e5f5ae801621f84bdbeffb5c4cf2dd8905..ad8003420dc14538d0dae9a1cb19d6459b154576 100644
--- a/paddle/framework/backward_test.cc
+++ b/paddle/framework/backward_test.cc
@@ -148,14 +148,16 @@ class AddOpMaker : public OpProtoAndCheckerMaker {
namespace f = paddle::framework;
namespace ops = paddle::operators;
using EnforceNotMet = paddle::platform::EnforceNotMet;
-REGISTER_OP(rowwise_add, f::NOP, f::RowWiseAddOpMaker, f::NOP);
-REGISTER_OP(mul, f::NOP, f::MulOpMaker, f::NOP);
-REGISTER_OP(sigmoid, f::NOP, f::SigmoidOpMaker, f::NOP);
+REGISTER_OP(rowwise_add, f::NOP, f::RowWiseAddOpMaker, rowwise_add_grad,
+ f::NOP);
+REGISTER_OP(mul, f::NOP, f::MulOpMaker, mul_grad, f::NOP);
+REGISTER_OP(sigmoid, f::NOP, f::SigmoidOpMaker, sigmoid_grad, f::NOP);
REGISTER_OP_WITHOUT_GRADIENT(nograd, f::NOP, f::NoGradOpMaker);
REGISTER_OP_WITHOUT_GRADIENT(fill_zeros_like, f::NOP, f::FillZeroOpMaker);
-REGISTER_OP(add, f::NOP, f::AddOpMaker, f::NOP);
+REGISTER_OP(add, f::NOP, f::AddOpMaker, add_grad, f::NOP);
REGISTER_OP_WITHOUT_GRADIENT(fc, f::FcOp, f::FcOpMaker);
-REGISTER_OP(many_output_op, f::NOP, f::ManyOutputOpMaker, f::NOP);
+REGISTER_OP(many_output_op, f::NOP, f::ManyOutputOpMaker, many_output_op_grad,
+ f::NOP);
TEST(Backward, simple_op_grad) {
auto fwd = f::OpRegistry::CreateOp(
diff --git a/paddle/framework/ddim.cc b/paddle/framework/ddim.cc
index cfd3e8dfdec0e92620aef5cd246b4622b779ce19..fc3d508553c0e966978b28d58127bdbff10d45f1 100644
--- a/paddle/framework/ddim.cc
+++ b/paddle/framework/ddim.cc
@@ -21,16 +21,16 @@ namespace framework {
/// @cond HIDDEN
template
-Dim make_dim(const int* d) {
+Dim make_dim(const int64_t* d) {
return Dim(*d, make_dim(d + 1));
}
template <>
-Dim<1> make_dim<1>(const int* d) {
+Dim<1> make_dim<1>(const int64_t* d) {
return Dim<1>(*d);
}
-void make_ddim(DDim& ddim, const int* dims, int n) {
+void make_ddim(DDim& ddim, const int64_t* dims, int n) {
switch (n) {
case 1:
ddim = make_dim<1>(dims);
@@ -67,13 +67,13 @@ void make_ddim(DDim& ddim, const int* dims, int n) {
/// @endcond
-DDim make_ddim(std::initializer_list dims) {
+DDim make_ddim(std::initializer_list dims) {
DDim result(make_dim(0));
make_ddim(result, dims.begin(), dims.size());
return result;
}
-DDim make_ddim(const std::vector& dims) {
+DDim make_ddim(const std::vector& dims) {
DDim result(make_dim(0));
make_ddim(result, &dims[0], dims.size());
return result;
@@ -81,12 +81,12 @@ DDim make_ddim(const std::vector& dims) {
/// @cond HIDDEN
// XXX For some reason, putting this in an anonymous namespace causes errors
-class DynamicMutableIndexer : public boost::static_visitor {
+class DynamicMutableIndexer : public boost::static_visitor {
public:
explicit DynamicMutableIndexer(int idx) : idx_(idx) {}
template
- int& operator()(Dim& dim) const {
+ int64_t& operator()(Dim& dim) const {
return dim[idx_];
}
@@ -94,12 +94,12 @@ class DynamicMutableIndexer : public boost::static_visitor {
int idx_;
};
-class DynamicConstIndexer : public boost::static_visitor {
+class DynamicConstIndexer : public boost::static_visitor {
public:
explicit DynamicConstIndexer(int idx) : idx_(idx) {}
template
- int operator()(const Dim& dim) const {
+ int64_t operator()(const Dim& dim) const {
return dim[idx_];
}
@@ -109,22 +109,22 @@ class DynamicConstIndexer : public boost::static_visitor {
/// @endcond
-int& DDim::operator[](int idx) {
+int64_t& DDim::operator[](int idx) {
return boost::apply_visitor(DynamicMutableIndexer(idx), var);
}
-int DDim::operator[](int idx) const {
+int64_t DDim::operator[](int idx) const {
return boost::apply_visitor(DynamicConstIndexer(idx), var);
}
-ssize_t DDim::size() const { return arity(*this); }
+int64_t DDim::size() const { return arity(*this); }
bool DDim::operator==(DDim d) const {
if (var.which() != d.getVar().which()) {
return false;
} else {
- std::vector v1 = vectorize(*this);
- std::vector v2 = vectorize(d);
+ std::vector v1 = vectorize(*this);
+ std::vector v2 = vectorize(d);
for (unsigned int i = 0; i < v1.size(); i++) {
if (v1[i] != v2[i]) {
@@ -139,10 +139,10 @@ bool DDim::operator==(DDim d) const {
bool DDim::operator!=(DDim d) const { return !(*this == d); }
DDim DDim::operator+(DDim d) const {
- std::vector v1 = vectorize(*this);
- std::vector v2 = vectorize(d);
+ std::vector v1 = vectorize(*this);
+ std::vector v2 = vectorize(d);
- std::vector v3;
+ std::vector v3;
assert(v1.size() == v2.size());
@@ -154,10 +154,10 @@ DDim DDim::operator+(DDim d) const {
}
DDim DDim::operator*(DDim d) const {
- std::vector v1 = vectorize(*this);
- std::vector v2 = vectorize(d);
+ std::vector v1 = vectorize(*this);
+ std::vector v2 = vectorize(d);
- std::vector v3;
+ std::vector v3;
assert(v1.size() == v2.size());
@@ -168,15 +168,15 @@ DDim DDim::operator*(DDim d) const {
return make_ddim(v3);
}
-int get(const DDim& ddim, int idx) { return ddim[idx]; }
+int64_t get(const DDim& ddim, int idx) { return ddim[idx]; }
void set(DDim& ddim, int idx, int value) { ddim[idx] = value; }
/// @cond HIDDEN
struct VectorizeVisitor : public boost::static_visitor<> {
- std::vector& vector;
+ std::vector& vector;
- explicit VectorizeVisitor(std::vector& v) : vector(v) {}
+ explicit VectorizeVisitor(std::vector& v) : vector(v) {}
template
void operator()(const T& t) {
@@ -188,31 +188,31 @@ struct VectorizeVisitor : public boost::static_visitor<> {
};
/// @endcond
-std::vector vectorize(const DDim& ddim) {
- std::vector result;
+std::vector vectorize(const DDim& ddim) {
+ std::vector result;
VectorizeVisitor visitor(result);
boost::apply_visitor(visitor, ddim);
return result;
}
-struct ProductVisitor : public boost::static_visitor {
+struct ProductVisitor : public boost::static_visitor {
template
- ssize_t operator()(const Dim& dim) {
+ int64_t operator()(const Dim& dim) {
return product(dim);
}
};
-ssize_t product(const DDim& ddim) {
+int64_t product(const DDim& ddim) {
ProductVisitor visitor;
return boost::apply_visitor(visitor, ddim);
}
struct SliceVectorizeVisitor : public boost::static_visitor<> {
- std::vector& vector;
+ std::vector& vector;
int begin;
int end;
- SliceVectorizeVisitor(std::vector& v, int b, int e)
+ SliceVectorizeVisitor(std::vector& v, int b, int e)
: vector(v), begin(b), end(e) {
PADDLE_ENFORCE(begin < end,
"Begin index must be less than end index in ddim slice.");
@@ -240,7 +240,7 @@ struct SliceVectorizeVisitor : public boost::static_visitor<> {
};
DDim slice_ddim(const DDim& dim, int begin, int end) {
- std::vector vec;
+ std::vector vec;
vec.reserve(end - begin);
SliceVectorizeVisitor visitor(vec, begin, end);
boost::apply_visitor(visitor, dim);
@@ -280,8 +280,17 @@ std::ostream& operator<<(std::ostream& os, const DDim& ddim) {
return os;
}
-DDim::DDim(std::initializer_list init_list) {
+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 95f294b62737be5c3eac39303148ac35da29fe7d..ca29e7e8c7776de6adf3e3b0e8f11f0d4d8487c3 100644
--- a/paddle/framework/ddim.h
+++ b/paddle/framework/ddim.h
@@ -40,7 +40,7 @@ struct DDim {
template
explicit DDim(const Dim& in) : var(in) {}
- /*implicit*/ DDim(std::initializer_list init_list);
+ /*implicit*/ DDim(std::initializer_list init_list);
template
DDim& operator=(const Dim& in) {
@@ -48,8 +48,8 @@ struct DDim {
return *this;
}
- int& operator[](int idx);
- int operator[](int idx) const;
+ int64_t& operator[](int idx);
+ int64_t operator[](int idx) const;
template
typename Visitor::result_type apply_visitor(Visitor& visitor) {
@@ -71,15 +71,15 @@ struct DDim {
DDim operator*(DDim d) const;
- ssize_t size() const;
+ int64_t size() const;
};
/**
- * \brief Make a DDim from std::vector
+ * \brief Make a DDim from std::vector
*
* \param dims An vector of ints. Must be sized between [1, 9]
*/
-DDim make_ddim(const std::vector& dims);
+DDim make_ddim(const std::vector& dims);
/**
* \brief Make a DDim from an initializer list
@@ -87,14 +87,14 @@ DDim make_ddim(const std::vector& dims);
* \param dims An initializer list of ints. Must be sized between [1, 9]
*
*/
-DDim make_ddim(std::initializer_list dims);
+DDim make_ddim(std::initializer_list dims);
-int get(const DDim& dim, int idx);
+int64_t get(const DDim& dim, int idx);
void set(DDim& dim, int idx, int val);
-std::vector vectorize(const DDim& ddim);
+std::vector vectorize(const DDim& ddim);
-ssize_t product(const DDim& ddim);
+int64_t product(const DDim& ddim);
/**
* \brief Slice a ddim
@@ -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/ddim_test.cc b/paddle/framework/ddim_test.cc
index 9d18a2972ce62139430b240b4599854b14290a32..756232b1b56a49d2c91cc2cac950ca508c54fb3f 100644
--- a/paddle/framework/ddim_test.cc
+++ b/paddle/framework/ddim_test.cc
@@ -12,7 +12,7 @@ TEST(DDim, Equality) {
EXPECT_EQ(ddim[2], 5);
// construct a DDim from a vector
- std::vector vec({9, 1, 5});
+ std::vector vec({9, 1, 5});
paddle::framework::DDim vddim = paddle::framework::make_ddim(vec);
EXPECT_EQ(ddim[0], 9);
EXPECT_EQ(ddim[1], 1);
@@ -25,7 +25,7 @@ TEST(DDim, Equality) {
EXPECT_EQ(paddle::framework::get(ddim, 0), 6);
// vectorize a DDim
- std::vector res_vec = paddle::framework::vectorize(vddim);
+ std::vector res_vec = paddle::framework::vectorize(vddim);
EXPECT_EQ(res_vec[0], 9);
EXPECT_EQ(res_vec[1], 1);
EXPECT_EQ(res_vec[2], 5);
diff --git a/paddle/framework/dim.h b/paddle/framework/dim.h
index 883fdc55eb929ebc51e8ae05938e9d07374406ce..04d4b0e604e6f73ad94e0ca79d6b69f663bd4076 100644
--- a/paddle/framework/dim.h
+++ b/paddle/framework/dim.h
@@ -17,13 +17,13 @@ struct Dim {
static constexpr int dimensions = i;
template
- HOSTDEVICE Dim(int _head, Args... _tail) : head(_head), tail(_tail...) {
+ HOSTDEVICE Dim(int64_t _head, Args... _tail) : head(_head), tail(_tail...) {
static_assert(sizeof...(_tail) == i - 1,
"Dim initialized with the wrong number of parameters");
}
HOSTDEVICE
- Dim(int _head, const Dim& _tail) : head(_head), tail(_tail) {}
+ Dim(int64_t _head, const Dim& _tail) : head(_head), tail(_tail) {}
HOSTDEVICE
Dim() : head(0), tail() {}
@@ -31,12 +31,12 @@ struct Dim {
/** Construct a Dim from a linear index and size. Uses Fortran order
* indexing. */
HOSTDEVICE
- Dim(int idx, const Dim& size)
+ Dim(int64_t idx, const Dim& size)
: head(idx % size.head), tail(idx / size.head, size.tail) {}
/** Construct a Dim with each dimension set to the given index */
HOSTDEVICE
- Dim(int idx) : head(idx), tail(idx) {}
+ Dim(int64_t idx) : head(idx), tail(idx) {}
HOSTDEVICE
bool operator==(const Dim& o) const {
@@ -47,13 +47,13 @@ struct Dim {
bool operator!=(const Dim& o) const { return !(*this == o); }
HOSTDEVICE
- int& operator[](int idx);
+ int64_t& operator[](int idx);
HOSTDEVICE
- int operator[](int idx) const;
+ int64_t operator[](int idx) const;
HOST std::string to_string() const;
- int head;
+ int64_t head;
Dim tail;
};
@@ -63,7 +63,7 @@ struct Dim<1> {
static constexpr int dimensions = 1;
HOSTDEVICE
- Dim(int _head) : head(_head) {}
+ Dim(int64_t _head) : head(_head) {}
HOSTDEVICE
Dim() : head(0) {}
@@ -86,11 +86,11 @@ struct Dim<1> {
bool operator!=(const Dim<1>& o) const { return !(*this == o); }
HOSTDEVICE
- int& operator[](int idx);
+ int64_t& operator[](int idx);
HOSTDEVICE
- int operator[](int idx) const;
+ int64_t operator[](int idx) const;
- int head;
+ int64_t head;
};
namespace {
@@ -100,12 +100,12 @@ template
struct DimGetter {
// Return a copy if Dim is const
template
- HOSTDEVICE static int impl(const D& d) {
+ HOSTDEVICE static int64_t impl(const D& d) {
return DimGetter::impl(d.tail);
}
// Return a reference if Dim is mutable
template
- HOSTDEVICE static int& impl(D& d) {
+ HOSTDEVICE static int64_t& impl(D& d) {
return DimGetter::impl(d.tail);
}
};
@@ -115,18 +115,18 @@ template <>
struct DimGetter<0> {
// Return a copy if Dim is const
template
- HOSTDEVICE static int impl(const D& d) {
+ HOSTDEVICE static int64_t impl(const D& d) {
return d.head;
}
// Return a reference if Dim is mutable
template
- HOSTDEVICE static int& impl(D& d) {
+ HOSTDEVICE static int64_t& impl(D& d) {
return d.head;
}
};
template
-HOSTDEVICE int& indexer(Dim& dim, int idx) {
+HOSTDEVICE int64_t& indexer(Dim& dim, int idx) {
#ifndef __CUDA_ARCH__
if (idx < 0) {
throw std::invalid_argument("Tried to access a negative dimension");
@@ -141,7 +141,7 @@ HOSTDEVICE int& indexer(Dim& dim, int idx) {
}
template <>
-HOSTDEVICE int& indexer<1>(Dim<1>& dim, int idx) {
+HOSTDEVICE int64_t& indexer<1>(Dim<1>& dim, int idx) {
#ifndef __CUDA_ARCH__
if (idx != 0) {
throw std::invalid_argument("Invalid index");
@@ -153,7 +153,7 @@ HOSTDEVICE int& indexer<1>(Dim<1>& dim, int idx) {
}
template
-HOSTDEVICE int indexer(const Dim& dim, int idx) {
+HOSTDEVICE int64_t indexer(const Dim& dim, int idx) {
#ifndef __CUDA_ARCH__
if (idx < 0) {
throw std::invalid_argument("Tried to access a negative dimension");
@@ -168,7 +168,7 @@ HOSTDEVICE int indexer(const Dim& dim, int idx) {
}
template <>
-HOSTDEVICE int indexer<1>(const Dim<1>& dim, int idx) {
+HOSTDEVICE int64_t indexer<1>(const Dim<1>& dim, int idx) {
#ifndef __CUDA_ARCH__
if (idx != 0) {
throw std::invalid_argument("Invalid index");
@@ -182,73 +182,76 @@ HOSTDEVICE int indexer<1>(const Dim<1>& dim, int idx) {
} // namespace
// Static access to constant Dim
template
-HOSTDEVICE int get(const Dim& d) {
+HOSTDEVICE int64_t get(const Dim& d) {
return DimGetter::impl(d);
}
// Static access to mutable Dim
template
-HOSTDEVICE int& get(Dim& d) {
+HOSTDEVICE int64_t& get(Dim& d) {
return DimGetter::impl(d);
}
// Dynamic access to constant Dim
template
-HOSTDEVICE int Dim::operator[](int i) const {
+HOSTDEVICE int64_t Dim::operator[](int i) const {
return indexer(*this, i);
}
// Dynamic access to mutable Dim
template
-HOSTDEVICE int& Dim::operator[](int i) {
+HOSTDEVICE int64_t& Dim::operator[](int i) {
return indexer(*this, i);
}
// Dynamic access to constant Dim
-inline HOSTDEVICE int Dim<1>::operator[](int i) const {
+inline HOSTDEVICE int64_t Dim<1>::operator[](int i) const {
return indexer(*this, i);
}
// Dynamic access to mutable Dim
-inline HOSTDEVICE int& Dim<1>::operator[](int i) { return indexer(*this, i); }
+inline HOSTDEVICE int64_t& Dim<1>::operator[](int i) {
+ return indexer(*this, i);
+}
// Dynamic access to constant Dim
// without std::enable_if will try to instantiate this on get<0>(d)
template
-HOSTDEVICE typename std::enable_if<(l > 0), int>::type get(const Dim& d,
- int i) {
+HOSTDEVICE typename std::enable_if<(l > 0), int64_t>::type get(const Dim& d,
+ int i) {
return d[i];
}
// Dynamic access to mutable Dim
template
-HOSTDEVICE typename std::enable_if<(l > 0), int&>::type get(Dim& d, int i) {
+HOSTDEVICE typename std::enable_if<(l > 0), int64_t&>::type get(Dim& d,
+ int i) {
return d[i];
}
// Dot product of two dims
template
-HOSTDEVICE int linearize(const Dim& a, const Dim& b) {
+HOSTDEVICE int64_t linearize(const Dim& a, const Dim& b) {
return a.head * b.head + linearize(a.tail, b.tail);
}
// Base case dot product of two Dims
// Notice it is inline because it is no longer a template
template <>
-HOSTDEVICE inline int linearize(const Dim<1>& a, const Dim<1>& b) {
+HOSTDEVICE inline int64_t linearize(const Dim<1>& a, const Dim<1>& b) {
return a.head * b.head;
}
// Product of a Dim
template
-HOSTDEVICE int product(const Dim& a, int prod = 1) {
+HOSTDEVICE int64_t product(const Dim& a, int prod = 1) {
return prod * a.head * product(a.tail);
}
// Base case product of a Dim
// Notice it is inline because it is no longer a template
template <>
-HOSTDEVICE inline int product(const Dim<1>& a, int prod) {
+HOSTDEVICE inline int64_t product(const Dim<1>& a, int prod) {
return prod * a.head;
}
diff --git a/paddle/framework/dim_test.cu b/paddle/framework/dim_test.cu
index 3898d0a447aa502813b3cb5e86c29eebb814ff84..0a6a87669c900de6cb507dd48f0cfc871defe279 100644
--- a/paddle/framework/dim_test.cu
+++ b/paddle/framework/dim_test.cu
@@ -8,7 +8,7 @@ __global__ void test(paddle::framework::Dim<2>* o) {
o[0] = paddle::framework::make_dim(5, 6);
}
-__global__ void dyn_idx_gpu(int* o) {
+__global__ void dyn_idx_gpu(int64_t* o) {
auto d = paddle::framework::make_dim(5, 6);
o[0] = d[1];
}
@@ -47,9 +47,9 @@ TEST(Dim, Equality) {
EXPECT_EQ(b[1], 11);
// dynamic access on GPU
- thrust::device_vector r(1);
+ thrust::device_vector r(1);
dyn_idx_gpu<<<1, 1>>>(thrust::raw_pointer_cast(r.data()));
- int res = r[0];
+ int64_t res = r[0];
EXPECT_EQ(res, 6);
// ex_prefix_mul
diff --git a/paddle/framework/eigen.h b/paddle/framework/eigen.h
index a4667cc51fadfc020d3211b7a82356db386fced1..54bbeafcabdeeb1e2c1017c156b3512c83dada3a 100644
--- a/paddle/framework/eigen.h
+++ b/paddle/framework/eigen.h
@@ -28,7 +28,7 @@ struct EigenDim {
static Type From(const DDim& dims) {
PADDLE_ENFORCE(arity(dims) == D, "D must match arity(DDim)");
Type ret;
- for (int d = 0; d < arity(dims); d++) {
+ for (int64_t d = 0; d < arity(dims); d++) {
ret[d] = dims[d];
}
return ret;
@@ -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 ae44a1ffd45dacdc44a72edc630e771e7a2f2990..dfcb5fb6210a08f35193b83e3b5f7cee92f618d7 100644
--- a/paddle/framework/framework.proto
+++ b/paddle/framework/framework.proto
@@ -22,8 +22,14 @@ enum AttrType {
INTS = 3;
FLOATS = 4;
STRINGS = 5;
+ INT_PAIRS = 6;
}
+message IntPair {
+ required int32 first = 1;
+ required int32 second = 2;
+};
+
// OpDesc describes an instance of a C++ framework::OperatorBase
// derived class type.
message OpDesc {
@@ -37,6 +43,7 @@ message OpDesc {
repeated int32 ints = 6;
repeated float floats = 7;
repeated string strings = 8;
+ repeated IntPair int_pairs = 9;
};
message Var {
@@ -80,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 8a817a3e13ca64d6f8df566891a1059995e041ae..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);
@@ -54,8 +54,8 @@ TEST(GradOpBuilder, AddTwo) {
EXPECT_EQ(grad_add_op->Output(f::GradVarName("Y")), f::GradVarName("y"));
}
-REGISTER_OP(mult_io, f::NOP, f::MutiInOutOpMaker, f::NOP);
-REGISTER_OP(io_ignored, f::NOP, f::IOIgnoredOpMaker, f::NOP);
+REGISTER_OP(mult_io, f::NOP, f::MutiInOutOpMaker, mult_io_grad, f::NOP);
+REGISTER_OP(io_ignored, f::NOP, f::IOIgnoredOpMaker, io_ignored_grad, f::NOP);
TEST(GradOpBuilder, MutiInOut) {
std::shared_ptr test_op(f::OpRegistry::CreateOp(
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.h b/paddle/framework/op_registry.h
index 64c7f23ab6b79bad9533f566ca39db3cfd5ac5c5..572dff860a306bb03ba9e6702fec85e4a2ea1b54 100644
--- a/paddle/framework/op_registry.h
+++ b/paddle/framework/op_registry.h
@@ -33,7 +33,8 @@ namespace framework {
class OpRegistry {
public:
template
- static void RegisterOp(const std::string& op_type) {
+ static void RegisterOp(const std::string& op_type,
+ const std::string& grad_op_type) {
PADDLE_ENFORCE(!OpInfoMap::Instance().Has(op_type),
"'%s' is registered more than once.", op_type);
OpInfo op_info;
@@ -42,9 +43,9 @@ class OpRegistry {
const VariableNameMap& outputs, const AttributeMap& attrs) {
return new OpType(type, inputs, outputs, attrs);
};
+ op_info.grad_op_type_ = grad_op_type;
if (std::type_index(typeid(ProtoMakerType)) !=
std::type_index(typeid(NOPMaker))) {
- op_info.grad_op_type_ = op_type + "_grad";
op_info.proto_ = new OpProto;
op_info.checker_ = new OpAttrChecker;
auto maker = ProtoMakerType(op_info.proto_, op_info.checker_);
@@ -54,14 +55,15 @@ class OpRegistry {
op_info.proto_->IsInitialized(),
"Fail to initialize %s's OpProto, because %s is not initialized",
op_type, op_info.proto_->InitializationErrorString());
- // register gradient op
- RegisterOp(op_info.grad_op_type_);
} else {
- op_info.grad_op_type_ = "";
op_info.proto_ = nullptr;
op_info.checker_ = nullptr;
}
OpInfoMap::Instance().Insert(op_type, op_info);
+ // register gradient op
+ if (!grad_op_type.empty()) {
+ RegisterOp(grad_op_type, "");
+ }
}
static std::unique_ptr CreateOp(const std::string& type,
@@ -90,8 +92,10 @@ class Registrar {
template
class OpRegistrar : public Registrar {
public:
- explicit OpRegistrar(const char* op_type) {
- OpRegistry::RegisterOp(op_type);
+ explicit OpRegistrar(const char* op_type) { OpRegistrar(op_type, ""); }
+ OpRegistrar(const char* op_type, const char* grad_op_type) {
+ OpRegistry::RegisterOp(op_type,
+ grad_op_type);
}
};
@@ -117,7 +121,8 @@ class OpKernelRegistrar : public Registrar {
/**
* Macro to register Operator.
*/
-#define REGISTER_OP(op_type, op_class, op_maker_class, grad_op_class) \
+#define REGISTER_OP(op_type, op_class, op_maker_class, grad_op_type, \
+ grad_op_class) \
STATIC_ASSERT_GLOBAL_NAMESPACE( \
__reg_op__##op_type, "REGISTER_OP must be called in global namespace"); \
class _OpClass_##op_type##_ : public op_class { \
@@ -132,14 +137,14 @@ class OpKernelRegistrar : public Registrar {
}; \
static ::paddle::framework::OpRegistrar< \
_OpClass_##op_type##_, op_maker_class, _OpGradClass_##op_type##_> \
- __op_registrar_##op_type##__(#op_type); \
+ __op_registrar_##op_type##__(#op_type, #grad_op_type); \
int TouchOpRegistrar_##op_type() { \
__op_registrar_##op_type##__.Touch(); \
return 0; \
}
#define REGISTER_OP_WITHOUT_GRADIENT(op_type, op_class, op_maker_class) \
- REGISTER_OP(op_type, op_class, op_maker_class, ::paddle::framework::NOP)
+ REGISTER_OP(op_type, op_class, op_maker_class, , ::paddle::framework::NOP)
/**
* Macro to register OperatorKernel.
@@ -194,6 +199,8 @@ class OpKernelRegistrar : public Registrar {
USE_OP_DEVICE_KERNEL(op_type, GPU)
#endif
+#define USE_NO_KERNEL_OP(op_type) USE_OP_ITSELF(op_type);
+
#define USE_CPU_ONLY_OP(op_type) \
USE_OP_ITSELF(op_type); \
USE_OP_DEVICE_KERNEL(op_type, CPU);
diff --git a/paddle/framework/op_registry_test.cc b/paddle/framework/op_registry_test.cc
index 50c45919c53af22665feeeebe753da283ded2b0c..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,38 +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);
-}
-
-class TestAttrProtoMaker : public pd::OpProtoAndCheckerMaker {
- public:
- TestAttrProtoMaker(pd::OpProto* proto, pd::OpAttrChecker* op_checker)
- : OpProtoAndCheckerMaker(proto, op_checker) {
- AddAttr("scale", "scale of test op");
- AddAttr("scale", "scale of test op");
- }
-};
-
-TEST(ProtoMaker, DuplicatedAttr) {
- pd::OpProto op_proto;
- pd::OpAttrChecker op_checker;
- auto proto_maker = TestAttrProtoMaker(&op_proto, &op_checker);
- ASSERT_THROW(proto_maker.Validate(), paddle::platform::EnforceNotMet);
-}
-
-class TestInOutProtoMaker : public pd::OpProtoAndCheckerMaker {
- public:
- TestInOutProtoMaker(pd::OpProto* proto, pd::OpAttrChecker* op_checker)
- : OpProtoAndCheckerMaker(proto, op_checker) {
- AddInput("input", "input of test op");
- AddInput("input", "input of test op");
- }
-};
-
-TEST(ProtoMaker, DuplicatedInOut) {
- pd::OpProto op_proto;
- pd::OpAttrChecker op_checker;
- auto proto_maker = TestInOutProtoMaker(&op_proto, &op_checker);
- ASSERT_THROW(proto_maker.Validate(), paddle::platform::EnforceNotMet);
-}
+}
\ 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 590e335fdc8843ed9edd01a09605163de93f52d9..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.
@@ -233,6 +236,15 @@ class InferShapeContext {
InferShapeContext(const OperatorBase& op, const Scope& scope)
: op_(op), scope_(scope) {}
+ const OperatorBase& op() const { return op_; }
+
+ const Scope& scope() const { return scope_; }
+
+ template
+ inline const T& Attr(const std::string& name) const {
+ return op_.Attr(name);
+ }
+
size_t InputSize(const std::string& name) const {
return op_.Inputs(name).size();
}
@@ -302,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) {
@@ -314,6 +326,7 @@ class InferShapeContext {
return res;
}
+ private:
const OperatorBase& op_;
const Scope& scope_;
};
diff --git a/paddle/framework/operator_test.cc b/paddle/framework/operator_test.cc
index 1d7efb7b9403f7c1c6bdbb27a0258f79ae032f43..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");
}
};
@@ -122,10 +122,10 @@ class CPUKernelTest : public OpKernel {
public:
void Compute(const ExecutionContext& ctx) const {
std::cout << "this is cpu kernel" << std::endl;
- std::cout << ctx.op_.DebugString() << std::endl;
+ std::cout << ctx.op().DebugString() << std::endl;
cpu_kernel_run_num++;
- ASSERT_EQ(ctx.op_.Input("x"), "IN1");
- ASSERT_EQ(ctx.op_.Output("y"), "OUT1");
+ ASSERT_EQ(ctx.op().Input("x"), "IN1");
+ ASSERT_EQ(ctx.op().Output("y"), "OUT1");
}
};
@@ -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");
}
};
@@ -148,7 +148,7 @@ class OpKernelTestMultiInputsProtoAndCheckerMaker
class CPUKernalMultiInputsTest : public OpKernel {
public:
void Compute(const ExecutionContext& ctx) const {
- auto xs = ctx.op_.Inputs("xs");
+ auto xs = ctx.op().Inputs("xs");
ASSERT_EQ(xs.size(), 3UL);
ASSERT_EQ(xs[0], "x0");
ASSERT_EQ(xs[1], "x1");
@@ -172,10 +172,10 @@ class CPUKernalMultiInputsTest : public OpKernel {
auto outTensor0 = ctx.MultiOutput("ys");
ASSERT_EQ(outTensor0.size(), 2U);
- auto k = ctx.op_.Input("k");
+ auto k = ctx.op().Input("k");
ASSERT_EQ(k, "k0");
- auto ys = ctx.op_.Outputs("ys");
+ auto ys = ctx.op().Outputs("ys");
ASSERT_EQ(ys.size(), 2UL);
ASSERT_EQ(ys[0], "y0");
ASSERT_EQ(ys[1], "y1");
@@ -263,4 +263,38 @@ TEST(Operator, Clone) {
OperatorClone a("ABC", {}, {}, {});
auto b = a.Clone();
ASSERT_EQ(a.Type(), b->Type());
+}
+
+class TestAttrProtoMaker : public paddle::framework::OpProtoAndCheckerMaker {
+ public:
+ TestAttrProtoMaker(paddle::framework::OpProto* proto,
+ paddle::framework::OpAttrChecker* op_checker)
+ : OpProtoAndCheckerMaker(proto, op_checker) {
+ AddAttr("scale", "scale of test op");
+ AddAttr("scale", "scale of test op");
+ }
+};
+
+TEST(ProtoMaker, DuplicatedAttr) {
+ paddle::framework::OpProto op_proto;
+ paddle::framework::OpAttrChecker op_checker;
+ auto proto_maker = TestAttrProtoMaker(&op_proto, &op_checker);
+ ASSERT_THROW(proto_maker.Validate(), paddle::platform::EnforceNotMet);
+}
+
+class TestInOutProtoMaker : public paddle::framework::OpProtoAndCheckerMaker {
+ public:
+ TestInOutProtoMaker(paddle::framework::OpProto* proto,
+ paddle::framework::OpAttrChecker* op_checker)
+ : OpProtoAndCheckerMaker(proto, op_checker) {
+ AddInput("input", "input of test op");
+ AddInput("input", "input of test op");
+ }
+};
+
+TEST(ProtoMaker, DuplicatedInOut) {
+ paddle::framework::OpProto op_proto;
+ paddle::framework::OpAttrChecker op_checker;
+ auto proto_maker = TestInOutProtoMaker(&op_proto, &op_checker);
+ ASSERT_THROW(proto_maker.Validate(), paddle::platform::EnforceNotMet);
}
\ No newline at end of file
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 7893e233b776425a61d9e3edd43d944a27743188..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!= */
- size_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.");
- int 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