diff --git a/benchmark/paddle/image/run_mkldnn.sh b/benchmark/paddle/image/run_mkldnn.sh
index a4527e04968cf8c8c3c31d16f50bc3e28381f6d8..3cc779b48d082985f75ab1c053fbe262bc6d58aa 100755
--- a/benchmark/paddle/image/run_mkldnn.sh
+++ b/benchmark/paddle/image/run_mkldnn.sh
@@ -1,9 +1,7 @@
set -e
function train() {
- unset OMP_NUM_THREADS MKL_NUM_THREADS
- export OMP_DYNAMIC="FALSE"
- export KMP_AFFINITY="granularity=fine,compact,0,0"
+ unset OMP_NUM_THREADS MKL_NUM_THREADS OMP_DYNAMIC KMP_AFFINITY
topology=$1
layer_num=$2
bs=$3
@@ -14,8 +12,6 @@ function train() {
elif [ $4 == "False" ]; then
thread=`nproc`
# each trainer_count use only 1 core to avoid conflict
- export OMP_NUM_THREADS=1
- export MKL_NUM_THREADS=1
log="logs/${topology}-${layer_num}-${thread}mklml-${bs}.log"
else
echo "Wrong input $3, use True or False."
diff --git a/cmake/cross_compiling/ios.cmake b/cmake/cross_compiling/ios.cmake
index 310450f7d009dc0cdae9c0079a96445af8ec8f95..d3f5bf6852b3b295f3b5806b0577a880b0ce6ba6 100644
--- a/cmake/cross_compiling/ios.cmake
+++ b/cmake/cross_compiling/ios.cmake
@@ -76,11 +76,9 @@ set(IOS_PLATFORM ${IOS_PLATFORM} CACHE STRING "Type of iOS Platform")
# Set the architecture for iOS
if(NOT DEFINED IOS_ARCH)
if(IOS_PLATFORM STREQUAL "OS")
- # FIXME(liuyiqun): support "armv7;armv7s;arm64" future
- set(IOS_ARCH "arm64")
+ set(IOS_ARCH "armv7;armv7s;arm64")
elseif(IOS_PLATFORM STREQUAL "SIMULATOR")
- # FIXME(liuyiqun): support "i386;x86_64" future
- set(IOS_ARCH "x86_64")
+ set(IOS_ARCH "i386;x86_64")
endif()
endif()
set(CMAKE_OSX_ARCHITECTURES ${IOS_ARCH} CACHE string "Build architecture for iOS")
@@ -248,7 +246,7 @@ set(IOS_COMPILER_FLAGS "${XCODE_IOS_PLATFORM_VERSION_FLAGS} ${XCODE_IOS_BITCODE_
# Hidden visibilty is required for cxx on iOS
set(CMAKE_C_FLAGS "${IOS_COMPILER_FLAGS} ${CMAKE_C_FLAGS}" CACHE STRING "C flags")
-set(CMAKE_CXX_FLAGS "${IOS_COMPILER_FLAGS} -fvisibility-inlines-hidden ${CMAKE_CXX_FLAGS}" CACHE STRING "CXX flags")
+set(CMAKE_CXX_FLAGS "${IOS_COMPILER_FLAGS} -fvisibility=hidden -fvisibility-inlines-hidden ${CMAKE_CXX_FLAGS}" CACHE STRING "CXX flags")
set(IOS_LINK_FLAGS "${XCODE_IOS_PLATFORM_VERSION_FLAGS} -Wl,-search_paths_first")
diff --git a/cmake/external/openblas.cmake b/cmake/external/openblas.cmake
index 05d83ad58ef8485d36829e7aeede79f625cfdc43..4c4f59656dae68739f2f07f3febd510e727fe2dd 100644
--- a/cmake/external/openblas.cmake
+++ b/cmake/external/openblas.cmake
@@ -29,7 +29,7 @@ IF(NOT ${CBLAS_FOUND})
"${CBLAS_INSTALL_DIR}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}openblas${CMAKE_STATIC_LIBRARY_SUFFIX}"
CACHE FILEPATH "openblas library." FORCE)
- SET(OPENBLAS_CC "${CMAKE_C_COMPILER}")
+ SET(OPENBLAS_CC "${CMAKE_C_COMPILER} -Wno-unused-but-set-variable -Wno-unused-variable")
IF(CMAKE_CROSSCOMPILING)
SET(OPTIONAL_ARGS HOSTCC=${HOST_C_COMPILER})
@@ -45,15 +45,14 @@ IF(NOT ${CBLAS_FOUND})
SET(OPTIONAL_ARGS ${OPTIONAL_ARGS} TARGET=ARMV8 BINARY=64 USE_THREAD=0)
ENDIF()
ELSEIF(IOS)
- # FIXME(liuyiqun): support multiple architectures
- SET(OPENBLAS_COMMIT "b5c96fcfcdc82945502a2303116a64d89985daf5")
- SET(OPENBLAS_CC "${OPENBLAS_CC} ${CMAKE_C_FLAGS} -isysroot ${CMAKE_OSX_SYSROOT}")
- IF(CMAKE_OSX_ARCHITECTURES MATCHES "armv7")
- SET(OPENBLAS_CC "${OPENBLAS_CC} -arch armv7")
- SET(OPTIONAL_ARGS ${OPTIONAL_ARGS} TARGET=ARMV7 ARM_SOFTFP_ABI=1 USE_THREAD=0)
- ELSEIF(CMAKE_OSX_ARCHITECTURES MATCHES "arm64")
+ IF(CMAKE_OSX_ARCHITECTURES MATCHES "arm64")
+ SET(OPENBLAS_COMMIT "b5c96fcfcdc82945502a2303116a64d89985daf5")
+ SET(OPENBLAS_CC "${OPENBLAS_CC} ${CMAKE_C_FLAGS} -isysroot ${CMAKE_OSX_SYSROOT}")
SET(OPENBLAS_CC "${OPENBLAS_CC} -arch arm64")
SET(OPTIONAL_ARGS ${OPTIONAL_ARGS} TARGET=ARMV8 BINARY=64 USE_THREAD=0 CROSS_SUFFIX=${CROSS_SUFFIX})
+ ELSE()
+ MESSAGE(FATAL_ERROR "OpenBLAS only support arm64 architectures on iOS. "
+ "You can set IOS_USE_VECLIB_FOR_BLAS=ON or USE_EIGEN_FOR_BLAS=ON to use other blas library instead.")
ENDIF()
ELSEIF(RPI)
# use hardfp
@@ -98,7 +97,7 @@ IF(NOT ${CBLAS_FOUND})
ENDIF()
INSTALL(CODE "execute_process(
COMMAND ${CMAKE_COMMAND} -E copy_directory ${CBLAS_INSTALL_DIR}/lib
- destination ${CMAKE_INSTALL_PREFIX}/${TMP_INSTALL_DIR}
+ ${CMAKE_INSTALL_PREFIX}/${TMP_INSTALL_DIR}
)"
)
INSTALL(CODE "MESSAGE(STATUS \"Installing: \"
diff --git a/cmake/external/warpctc.cmake b/cmake/external/warpctc.cmake
index 8bd058222880b4df3b08da09c02f9fe7f1d0ee66..a8e1aca49c97df256b1269c286b0bce7732fa932 100644
--- a/cmake/external/warpctc.cmake
+++ b/cmake/external/warpctc.cmake
@@ -12,6 +12,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+IF(MOBILE_INFERENCE)
+ return()
+ENDIF()
+
INCLUDE(ExternalProject)
SET(WARPCTC_SOURCES_DIR ${THIRD_PARTY_PATH}/warpctc)
diff --git a/doc/design/ops/images/2_level_rnn.dot b/doc/design/ops/images/2_level_rnn.dot
index a498e882a3d85a33d44dbad7474fa2a340e33976..5d77865061ca7bbbfcf254dd938f09aef5553505 100644
--- a/doc/design/ops/images/2_level_rnn.dot
+++ b/doc/design/ops/images/2_level_rnn.dot
@@ -1,6 +1,6 @@
digraph G {
- rnn [label="1-th level RNN" shape=box]
+ rnn [label="1st level RNN" shape=box]
subgraph cluster0 {
label = "time step 0"
@@ -8,7 +8,7 @@ digraph G {
sent0 [label="sentence"]
sent1 [label="sentence"]
- rnn1 [label="2-th level RNN" shape=box]
+ rnn1 [label="2nd level RNN" shape=box]
sent0 -> rnn1
sent1 -> rnn1
@@ -20,7 +20,7 @@ digraph G {
sent2 [label="sentence"]
sent3 [label="sentence"]
- rnn2 [label="2-th level RNN" shape=box]
+ rnn2 [label="2nd level RNN" shape=box]
sent2 -> rnn2
sent3 -> rnn2
@@ -32,7 +32,7 @@ digraph G {
sent4 [label="sentence"]
sent5 [label="sentence"]
- rnn3 [label="2-th level RNN" shape=box]
+ rnn3 [label="2nd level RNN" shape=box]
sent4 -> rnn3
sent5 -> rnn3
diff --git a/doc/design/ops/rnn.md b/doc/design/ops/rnn.md
index a78eea7d45e9e9553d153170aa31da55ec6e8289..2f4854793fa1f0b02e4dc17b51a48a972be61c06 100644
--- a/doc/design/ops/rnn.md
+++ b/doc/design/ops/rnn.md
@@ -1,62 +1,62 @@
# RNNOp design
-This document is about an RNN operator which requires that instances in a mini-batch have the same length. We will have a more flexible RNN operator.
+This document describes the RNN (Recurrent Neural Network) operator and how it is implemented in PaddlePaddle. The RNN op requires that all instances in a mini-batch have the same length. We will have a more flexible dynamic RNN operator in the future.
## RNN Algorithm Implementation
-
+
The above diagram shows an RNN unrolled into a full network.
-There are several important concepts:
+There are several important concepts here:
-- *step-net*: the sub-graph to run at each step,
-- *memory*, $h_t$, the state of the current step,
-- *ex-memory*, $h_{t-1}$, the state of the previous step,
-- *initial memory value*, the ex-memory of the first step.
+- *step-net*: the sub-graph that runs at each step.
+- *memory*, $h_t$, the state of the current step.
+- *ex-memory*, $h_{t-1}$, the state of the previous step.
+- *initial memory value*, the memory of the first (initial) step.
### Step-scope
-There could be local variables defined in step-nets. PaddlePaddle runtime realizes these variables in *step-scopes* -- scopes created for each step.
+There could be local variables defined in each step-net. PaddlePaddle runtime realizes these variables in *step-scopes* which are created for each step.
-
+
![](./images/rnn.png)
-Figure 2 the RNN's data flow
+Figure 2 illustrates the RNN's data flow
-Please be aware that all steps run the same step-net. Each step
+Please be aware that every step runs the same step-net. Each step does the following:
-1. creates the step-scope,
-2. realizes local variables, including step-outputs, in the step-scope, and
-3. runs the step-net, which could use these variables.
+1. Creates the step-scope.
+2. Initializes the local variables including step-outputs, in the step-scope.
+3. Runs the step-net, which uses the above mentioned variables.
-The RNN operator will compose its output from step outputs in step scopes.
+The RNN operator will compose its output from step outputs in each of the step scopes.
### Memory and Ex-memory
-Let's give more details about memory and ex-memory via a simply example:
+Let's give more details about memory and ex-memory using a simple example:
$$
h_t = U h_{t-1} + W x_t
$$,
-where $h_t$ and $h_{t-1}$ are the memory and ex-memory of step $t$'s respectively.
+where $h_t$ and $h_{t-1}$ are the memory and ex-memory (previous memory) of step $t$ respectively.
-In the implementation, we can make an ex-memory variable either "refers to" the memory variable of the previous step,
-or copy the value of the previous memory value to the current ex-memory variable.
+In the implementation, we can make an ex-memory variable either "refer to" the memory variable of the previous step,
+or copy the memory value of the previous step to the current ex-memory variable.
### Usage in Python
For more information on Block, please refer to the [design doc](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/block.md).
-We can define an RNN's step-net using Block:
+We can define an RNN's step-net using a Block:
```python
import paddle as pd
-X = some_op() # x is some operator's output, and is a LoDTensor
+X = some_op() # x is some operator's output and is a LoDTensor
a = some_op()
# declare parameters
@@ -68,7 +68,7 @@ with rnn.stepnet():
x = rnn.add_input(X)
# declare a memory (rnn's step)
h = rnn.add_memory(init=a)
- # h.pre_state() means previous memory of rnn
+ # h.pre_state(), the previous memory of rnn
new_state = pd.add_two( pd.matmul(W, x) + pd.matmul(U, h.pre_state()))
# update current memory
h.update(new_state)
@@ -80,19 +80,19 @@ out = rnn()
Python API functions in above example:
-- `rnn.add_input` indicates the parameter is a variable that will be segmented into step-inputs.
-- `rnn.add_memory` creates a variable used as the memory.
-- `rnn.add_outputs` mark the variables that will be concatenated across steps into the RNN output.
+- `rnn.add_input`: indicates that the parameter is a variable that will be segmented into step-inputs.
+- `rnn.add_memory`: creates a variable used as the memory.
+- `rnn.add_outputs`: marks the variables that will be concatenated across steps into the RNN output.
### Nested RNN and LoDTensor
An RNN whose step-net includes other RNN operators is known as an *nested RNN*.
-For example, we could have a 2-level RNN, where the top level corresponds to paragraphs, and the lower level corresponds to sentences.
+For example, we could have a 2-level RNN, where the top level corresponds to paragraphs, and the lower level corresponds to sentences. Each step of the higher level RNN also receives an input from the corresponding step of the lower level, and additionally the output from the previous time step at the same level.
-The following figure illustrates the feeding of text into the lower level, one sentence each step, and the feeding of step outputs to the top level. The final top level output is about the whole text.
+The following figure illustrates feeding in text into the lower level, one sentence at a step, and the feeding in step outputs to the top level. The final top level output is about the whole text.
-
+
@@ -110,7 +110,7 @@ a = some_op()
# chapter_data is a set of 128-dim word vectors
# the first level of LoD is sentence
-# the second level of LoD is chapter
+# the second level of LoD is a chapter
chapter_data = pd.Variable(shape=[None, 128], type=pd.lod_tensor, level=2)
def lower_level_rnn(paragraph):
@@ -138,14 +138,14 @@ with top_level_rnn.stepnet():
pd.matmul(W0, paragraph_data) + pd.matmul(U0, h.pre_state()))
top_level_rnn.add_outputs(h)
-# just output the last step
+# output the last step
chapter_out = top_level_rnn(output_all_steps=False)
```
-in above example, the construction of the `top_level_rnn` calls `lower_level_rnn`. The input is a LoD Tensor. The top level RNN segments input text data into paragraphs, and the lower level RNN segments each paragraph into sentences.
+In the above example, the construction of the `top_level_rnn` calls `lower_level_rnn`. The input is an LoD Tensor. The top level RNN segments input text data into paragraphs, and the lower level RNN segments each paragraph into sentences.
-By default, the `RNNOp` will concatenate the outputs from all the time steps,
-if the `output_all_steps` set to False, it will only output the final time step.
+By default, the `RNNOp` will concatenate the outputs from all the time steps.
+If the `output_all_steps` is set to False, it will only output the final time step.
diff --git a/doc/design/ops/sequence_decoder.md b/doc/design/ops/sequence_decoder.md
index 9007aae7a8355ed06c6720a921351f81b859c1fe..9db5fb8e9a9f89b004bf71ddc064cd976c0d0bee 100644
--- a/doc/design/ops/sequence_decoder.md
+++ b/doc/design/ops/sequence_decoder.md
@@ -1,35 +1,28 @@
# Design: Sequence Decoder Generating LoDTensors
-In tasks such as machine translation and image to text,
-a [sequence decoder](https://github.com/PaddlePaddle/book/blob/develop/08.machine_translation/README.md) is necessary to generate sequences.
+In tasks such as machine translation and visual captioning,
+a [sequence decoder](https://github.com/PaddlePaddle/book/blob/develop/08.machine_translation/README.md) is necessary to generate sequences, one word at a time.
This documentation describes how to implement the sequence decoder as an operator.
## Beam Search based Decoder
-The [beam search algorithm](https://en.wikipedia.org/wiki/Beam_search) is necessary when generating sequences,
-it is a heuristic search algorithm that explores the paths by expanding the most promising node in a limited set.
+The [beam search algorithm](https://en.wikipedia.org/wiki/Beam_search) is necessary when generating sequences. It is a heuristic search algorithm that explores the paths by expanding the most promising node in a limited set.
-In the old version of PaddlePaddle, a C++ class `RecurrentGradientMachine` implements the general sequence decoder based on beam search,
-due to the complexity, the implementation relays on a lot of special data structures,
-quite trivial and hard to be customized by users.
+In the old version of PaddlePaddle, the C++ class `RecurrentGradientMachine` implements the general sequence decoder based on beam search, due to the complexity involved, the implementation relies on a lot of special data structures that are quite trivial and hard to be customized by users.
-There are a lot of heuristic tricks in the sequence generation tasks,
-so the flexibility of sequence decoder is very important to users.
+There are a lot of heuristic tricks in the sequence generation tasks, so the flexibility of sequence decoder is very important to users.
-During PaddlePaddle's refactoring work,
-some new concept is proposed such as [LoDTensor](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/framework/lod_tensor.md) and [TensorArray](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/tensor_array.md) that can better support sequence usage,
-and they can help to make the implementation of beam search based sequence decoder **more transparent and modular** .
+During the refactoring of PaddlePaddle, some new concepts are proposed such as: [LoDTensor](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/framework/lod_tensor.md) and [TensorArray](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/tensor_array.md) that can better support the sequence usage, and they can also help make the implementation of beam search based sequence decoder **more transparent and modular** .
-For example, the RNN sates, candidates IDs and probabilities of beam search can be represented as `LoDTensors`;
+For example, the RNN states, candidates IDs and probabilities of beam search can be represented all as `LoDTensors`;
the selected candidate's IDs in each time step can be stored in a `TensorArray`, and `Packed` to the sentences translated.
## Changing LoD's absolute offset to relative offsets
-The current `LoDTensor` is designed to store levels of variable-length sequences,
-it stores several arrays of integers each represents a level.
+The current `LoDTensor` is designed to store levels of variable-length sequences. It stores several arrays of integers where each represents a level.
-The integers in each level represents the begin and end (not inclusive) offset of a sequence **in the underlying tensor**,
-let's call this format the **absolute-offset LoD** for clear.
+The integers in each level represent the begin and end (not inclusive) offset of a sequence **in the underlying tensor**,
+let's call this format the **absolute-offset LoD** for clarity.
-The relative-offset LoD can fast retrieve any sequence but fails to represent empty sequences, for example, a two-level LoD is as follows
+The relative-offset LoD can retrieve any sequence very quickly but fails to represent empty sequences, for example, a two-level LoD is as follows
```python
[[0, 3, 9]
[0, 2, 3, 3, 3, 9]]
@@ -41,10 +34,9 @@ The first level tells that there are two sequences:
while on the second level, there are several empty sequences that both begin and end at `3`.
It is impossible to tell how many empty second-level sequences exist in the first-level sequences.
-There are many scenarios that relay on empty sequence representation,
-such as machine translation or image to text, one instance has no translations or the empty candidate set for a prefix.
+There are many scenarios that rely on empty sequence representation, for example in machine translation or visual captioning, one instance has no translation or the empty candidate set for a prefix.
-So let's introduce another format of LoD,
+So let's introduce another format of LoD,
it stores **the offsets of the lower level sequences** and is called **relative-offset** LoD.
For example, to represent the same sequences of the above data
@@ -54,19 +46,18 @@ For example, to represent the same sequences of the above data
[0, 2, 3, 3, 3, 9]]
```
-the first level represents that there are two sequences,
+the first level represents that there are two sequences,
their offsets in the second-level LoD is `[0, 3)` and `[3, 5)`.
The second level is the same with the relative offset example because the lower level is a tensor.
It is easy to find out the second sequence in the first-level LoD has two empty sequences.
-The following demos are based on relative-offset LoD.
+The following examples are based on relative-offset LoD.
## Usage in a simple machine translation model
-Let's start from a simple machine translation model that is simplified from [machine translation chapter](https://github.com/PaddlePaddle/book/tree/develop/08.machine_translation) to draw a simple blueprint of what a sequence decoder can do and how to use it.
+Let's start from a simple machine translation model that is simplified from the [machine translation chapter](https://github.com/PaddlePaddle/book/tree/develop/08.machine_translation) to draw a blueprint of what a sequence decoder can do and how to use it.
-The model has an encoder that learns the semantic vector from a sequence,
-and a decoder which uses the sequence decoder to generate new sentences.
+The model has an encoder that learns the semantic vector from a sequence, and a decoder which uses the sequence encoder to generate new sentences.
**Encoder**
```python
@@ -117,7 +108,7 @@ def generate():
# which means there are 2 sentences to translate
# - the first sentence has 1 translation prefixes, the offsets are [0, 1)
# - the second sentence has 2 translation prefixes, the offsets are [1, 3) and [3, 6)
- # the target_word.lod is
+ # the target_word.lod is
# [[0, 1, 6]
# [0, 2, 4, 7, 9 12]]
# which means 2 sentences to translate, each has 1 and 5 prefixes
@@ -154,37 +145,36 @@ def generate():
translation_ids, translation_scores = decoder()
```
-The `decoder.beam_search` is a operator that given the candidates and the scores of translations including the candidates,
-return the result of the beam search algorithm.
+The `decoder.beam_search` is an operator that, given the candidates and the scores of translations including the candidates,
+returns the result of the beam search algorithm.
-In this way, users can customize anything on the inputs or outputs of beam search, for example, two ways to prune some translation prefixes
+In this way, users can customize anything on the input or output of beam search, for example:
-1. meke the correspondind elements in `topk_generated_scores` zero or some small values, beam_search will discard this candidate.
-2. remove some specific candidate in `selected_ids`
-3. get the final `translation_ids`, remove the translation sequence in it.
+1. Make the corresponding elements in `topk_generated_scores` zero or some small values, beam_search will discard this candidate.
+2. Remove some specific candidate in `selected_ids`.
+3. Get the final `translation_ids`, remove the translation sequence in it.
-The implementation of sequence decoder can reuse the C++ class [RNNAlgorithm](https://github.com/Superjom/Paddle/blob/68cac3c0f8451fe62a4cdf156747d6dc0ee000b3/paddle/operators/dynamic_recurrent_op.h#L30),
-so the python syntax is quite similar to a [RNN](https://github.com/Superjom/Paddle/blob/68cac3c0f8451fe62a4cdf156747d6dc0ee000b3/doc/design/block.md#blocks-with-for-and-rnnop).
+The implementation of sequence decoder can reuse the C++ class: [RNNAlgorithm](https://github.com/Superjom/Paddle/blob/68cac3c0f8451fe62a4cdf156747d6dc0ee000b3/paddle/operators/dynamic_recurrent_op.h#L30),
+so the python syntax is quite similar to that of an [RNN](https://github.com/Superjom/Paddle/blob/68cac3c0f8451fe62a4cdf156747d6dc0ee000b3/doc/design/block.md#blocks-with-for-and-rnnop).
-Both of them are two-level `LoDTensors`
+Both of them are two-level `LoDTensors`:
-- the first level represents `batch_size` of (source) sentences;
-- the second level represents the candidate ID sets for translation prefix.
+- The first level represents `batch_size` of (source) sentences.
+- The second level represents the candidate ID sets for translation prefix.
-for example, 3 source sentences to translate, and has 2, 3, 1 candidates.
+For example, 3 source sentences to translate, and has 2, 3, 1 candidates.
-Unlike an RNN, in sequence decoder, the previous state and the current state have different LoD and shape,
-a `lod_expand` operator is used to expand the LoD of the previous state to fit the current state.
+Unlike an RNN, in sequence decoder, the previous state and the current state have different LoD and shape, and an `lod_expand` operator is used to expand the LoD of the previous state to fit the current state.
-For example, the previous state
+For example, the previous state:
* LoD is `[0, 1, 3][0, 2, 5, 6]`
* content of tensor is `a1 a2 b1 b2 b3 c1`
-the current state stored in `encoder_ctx_expanded`
+the current state is stored in `encoder_ctx_expanded`:
* LoD is `[0, 2, 7][0 3 5 8 9 11 11]`
-* the content is
+* the content is
- a1 a1 a1 (a1 has 3 candidates, so the state should be copied 3 times for each candidates)
- a2 a2
- b1 b1 b1
@@ -192,54 +182,48 @@ the current state stored in `encoder_ctx_expanded`
- b3 b3
- None (c1 has 0 candidates, so c1 is dropped)
-Benefit from the relative offset LoD, empty candidate set can be represented naturally.
+The benefit from the relative offset LoD is that the empty candidate set can be represented naturally.
-the status in each time step can be stored in `TensorArray`, and `Pack`ed to a final LoDTensor, the corresponding syntax is
+The status in each time step can be stored in `TensorArray`, and `Pack`ed to a final LoDTensor. The corresponding syntax is:
```python
decoder.output(selected_ids)
decoder.output(selected_generation_scores)
```
-the `selected_ids` is the candidate ids for the prefixes,
-it will be `Packed` by `TensorArray` to a two-level `LoDTensor`,
-the first level represents the source sequences,
-the second level represents generated sequences.
+The `selected_ids` are the candidate ids for the prefixes, and will be `Packed` by `TensorArray` to a two-level `LoDTensor`, where the first level represents the source sequences and the second level represents generated sequences.
-Pack the `selected_scores` will get a `LoDTensor` that stores scores of each candidate of translations.
+Packing the `selected_scores` will get a `LoDTensor` that stores scores of each translation candidate.
-Pack the `selected_generation_scores` will get a `LoDTensor`, and each tail is the probability of the translation.
+Packing the `selected_generation_scores` will get a `LoDTensor`, and each tail is the probability of the translation.
## LoD and shape changes during decoding
-According the image above, the only phrase to change LoD is beam search.
+According to the image above, the only phase that changes the LoD is beam search.
## Beam search design
-The beam search algorthm will be implemented as one method of the sequence decoder, it has 3 inputs
+The beam search algorithm will be implemented as one method of the sequence decoder and has 3 inputs:
-1. `topk_ids`, top K candidate ids for each prefix.
+1. `topk_ids`, the top K candidate ids for each prefix.
2. `topk_scores`, the corresponding scores for `topk_ids`
3. `generated_scores`, the score of the prefixes.
-All of the are LoDTensors, so that the sequence affilication is clear.
-Beam search will keep a beam for each prefix and select a smaller candidate set for each prefix.
+All of these are LoDTensors, so that the sequence affiliation is clear. Beam search will keep a beam for each prefix and select a smaller candidate set for each prefix.
-It will return three variables
+It will return three variables:
1. `selected_ids`, the final candidate beam search function selected for the next step.
2. `selected_scores`, the scores for the candidates.
-3. `generated_scores`, the updated scores for each prefixes (with the new candidates appended).
+3. `generated_scores`, the updated scores for each prefix (with the new candidates appended).
## Introducing the LoD-based `Pack` and `Unpack` methods in `TensorArray`
-The `selected_ids`, `selected_scores` and `generated_scores` are LoDTensors,
-and they exist in each time step,
+The `selected_ids`, `selected_scores` and `generated_scores` are LoDTensors that exist at each time step,
so it is natural to store them in arrays.
-Currently, PaddlePaddle has a module called `TensorArray` which can store an array of tensors,
-the results of beam search are better to store in a `TensorArray`.
+Currently, PaddlePaddle has a module called `TensorArray` which can store an array of tensors. It is better to store the results of beam search in a `TensorArray`.
-The `Pack` and `UnPack` in `TensorArray` are used to package tensors in the array to a `LoDTensor` or split the `LoDTensor` to an array of tensors.
-It needs some extensions to support pack or unpack an array of `LoDTensors`.
+The `Pack` and `UnPack` in `TensorArray` are used to pack tensors in the array to an `LoDTensor` or split the `LoDTensor` to an array of tensors.
+It needs some extensions to support the packing or unpacking an array of `LoDTensors`.
diff --git a/doc/mobile/cross_compiling_for_android_cn.md b/doc/mobile/cross_compiling_for_android_cn.md
index 882066f23714f7ab3bba9199b5fa5ff2325ce849..424d7718c64438496cf0895397babd5408e1ca02 100644
--- a/doc/mobile/cross_compiling_for_android_cn.md
+++ b/doc/mobile/cross_compiling_for_android_cn.md
@@ -1,4 +1,4 @@
-# 构建Android平台上的PaddlePaddle库
+# Android平台编译指南
用户可通过如下两种方式,交叉编译Android平台上适用的PaddlePaddle库:
- 基于Docker容器的编译方式
diff --git a/doc/mobile/cross_compiling_for_ios_cn.md b/doc/mobile/cross_compiling_for_ios_cn.md
index cda636a67de712e072f4cc7ad859dda75211eaa8..9da48e7f2119ce901fbb3abab73400df27be16d2 100644
--- a/doc/mobile/cross_compiling_for_ios_cn.md
+++ b/doc/mobile/cross_compiling_for_ios_cn.md
@@ -1,4 +1,4 @@
-# 构建iOS平台上的PaddlePaddle库
+# iOS平台编译指南
交叉编译iOS平台上适用的PaddlePaddle库,需要在MacOS系统上进行。本文的将介绍在MacOS上,从源码交叉编译iOS平台上适用的PaddlePaddle库。
## 准备交叉编译环境
@@ -25,7 +25,7 @@ iOS平台可选配置参数:
- `IOS_PLATFORM`,可设置为`OS/SIMULATOR`,默认值为`OS`。
- `OS`,构建目标为`arm`架构的iPhone或者iPad等物理设备。
- `SIMULATOR`,构建目标为`x86`架构的模拟器平台。
-- `IOS_ARCH`,目标架构。针对不同的`IOS_PLATFORM`,可设置的目标架构如下表所示:
+- `IOS_ARCH`,目标架构。针对不同的`IOS_PLATFORM`,可设置的目标架构如下表所示,默认编译所有架构:
@@ -41,11 +41,11 @@ iOS平台可选配置参数:
OS |
- armv7, armv7s, arm64 (默认) |
+ armv7, armv7s, arm64 |
SIMULATOR |
- i386, x86_64 (默认) |
+ i386, x86_64 |
@@ -66,7 +66,7 @@ iOS平台可选配置参数:
```bash
cmake -DCMAKE_SYSTEM_NAME=iOS \
-DIOS_PLATFORM=OS \
- -DIOS_ARCH="arm64" \
+ -DIOS_ARCH="armv7;arm64" \
-DIOS_ENABLE_BITCODE=ON \
-DIOS_USE_VECLIB_FOR_BLAS=ON \
-DCMAKE_INSTALL_PREFIX=your/path/to/install \
@@ -112,6 +112,6 @@ $ make install
- `lib`目录,其中包含PaddlePaddle的C-API静态库
- `third_party`目录,其中包含所依赖的所有第三方库
-注意,不同架构的PaddlePaddle库建议安装到不同的目录下,然后使用`lipo`工具将多个静态库合并成一个支持多个架构的fat库。
+注意,如果PaddlePaddle库需要同时支持真机和模拟器,则需要分别编译真机和模拟器版本,然后使用`lipo`工具合并fat库。
自此,PaddlePaddle库已经安装完成,用户可将合成的fat库用于深度学习相关的iOS App中,调用方法见C-API文档。
diff --git a/doc/mobile/cross_compiling_for_raspberry_cn.md b/doc/mobile/cross_compiling_for_raspberry_cn.md
index 6e983645faaed1f67edaeeb82ddbef9cef6bb85f..f8ef9dc8031613831437745995268f3abc392f5b 100644
--- a/doc/mobile/cross_compiling_for_raspberry_cn.md
+++ b/doc/mobile/cross_compiling_for_raspberry_cn.md
@@ -1,4 +1,4 @@
-# 构建Raspberry Pi平台上的PaddlePaddle库
+# Raspberry Pi平台编译指南
通常有两个方法来构建基于 Rasspberry Pi 的版本:
diff --git a/paddle/capi/Main.cpp b/paddle/capi/Main.cpp
index 78c43949dfe325d0e1a6ba10ae51cb7b858f6c52..bb8249a5511c089ec2f2263ff4cc290f0a5a8fce 100644
--- a/paddle/capi/Main.cpp
+++ b/paddle/capi/Main.cpp
@@ -29,6 +29,9 @@ static void initPaddle(int argc, char** argv) {
extern "C" {
paddle_error paddle_init(int argc, char** argv) {
+ static bool isInit = false;
+ if (isInit) return kPD_NO_ERROR;
+
std::vector realArgv;
realArgv.reserve(argc + 1);
realArgv.push_back(strdup(""));
@@ -37,6 +40,7 @@ paddle_error paddle_init(int argc, char** argv) {
}
initPaddle(argc + 1, realArgv.data());
free(realArgv[0]);
+ isInit = true;
return kPD_NO_ERROR;
}
}
diff --git a/paddle/cuda/include/hl_gpu.h b/paddle/cuda/include/hl_gpu.h
index ede2670882ee2b93f610a2261a4ecc1784bc2d0c..4ab8de80d1c7be0f8e3eb848955373dd5e21bc18 100644
--- a/paddle/cuda/include/hl_gpu.h
+++ b/paddle/cuda/include/hl_gpu.h
@@ -25,7 +25,9 @@ limitations under the License. */
#include "hl_matrix.h"
#include "hl_sequence.h"
#include "hl_sparse.h"
+#ifndef PADDLE_MOBILE_INFERENCE
#include "hl_warpctc_wrap.h"
+#endif
#ifdef HPPL_STUB_FUNC
#include "stub/hl_aggregate_stub.h"
diff --git a/paddle/framework/backward.cc b/paddle/framework/backward.cc
index b3b9c45ded95ce2e735b8898d47760956dcacdce..00d9dd238ec5328be28f58f8118daad3a039e08c 100644
--- a/paddle/framework/backward.cc
+++ b/paddle/framework/backward.cc
@@ -270,6 +270,19 @@ static bool AllGradInSet(const std::vector& names,
return false;
}
}
+ if (VLOG_IS_ON(10)) {
+ std::ostringstream sout;
+ sout << "All input {";
+ for (auto& name : names) {
+ sout << name << ",";
+ }
+ sout << "} is in {";
+ for (auto& name : set) {
+ sout << name << ",";
+ }
+ sout << "}";
+ VLOG(10) << sout.str();
+ }
return true;
}
@@ -290,14 +303,12 @@ static void CreateGradVarInBlock(
auto ops = block_desc->AllOps();
for (size_t op_index = grad_op_start_index; op_index < ops.size();
++op_index) {
- bool need_infer_shape = false;
std::unordered_set new_vars;
ForEachVarName(ops[op_index]->Outputs(),
[&](const std::string& grad_var_name) {
if (block_desc->HasVar(grad_var_name)) {
return false;
}
- need_infer_shape = true;
auto var = block_desc->Var(grad_var_name);
new_vars.insert(var->Name());
auto it = param_name_map.find(grad_var_name);
@@ -311,23 +322,21 @@ static void CreateGradVarInBlock(
grad_record.op_idx_ = static_cast(op_index);
return false; /* not break */
});
- if (need_infer_shape) {
- ops[op_index]->InferVarType(block_desc);
- for (auto& arg : ops[op_index]->OutputArgumentNames()) {
- if (new_vars.find(arg) == new_vars.end()) {
- continue;
- }
- auto pname = FwdName(arg);
- auto* param = block_desc->FindVarRecursive(pname);
- auto* grad = block_desc->FindVar(arg);
- if (param == nullptr) {
- grad->SetDataType(DataType::FP32);
- } else {
- grad->SetDataType(param->GetDataType());
- }
+ ops[op_index]->InferVarType(block_desc);
+ for (auto& arg : ops[op_index]->OutputArgumentNames()) {
+ if (new_vars.find(arg) == new_vars.end()) {
+ continue;
+ }
+ auto pname = FwdName(arg);
+ auto* param = block_desc->FindVarRecursive(pname);
+ auto* grad = block_desc->FindVar(arg);
+ if (param == nullptr) {
+ grad->SetDataType(DataType::FP32);
+ } else {
+ grad->SetDataType(param->GetDataType());
}
- ops[op_index]->InferShape(*block_desc);
}
+ ops[op_index]->InferShape(*block_desc);
}
}
@@ -387,6 +396,7 @@ std::vector> MakeBlockBackward(
ProgramDescBind& program_desc, int block_idx,
std::unordered_set* no_grad_vars,
std::unordered_map* grad_to_var) {
+ VLOG(5) << "MakeBlockBackward";
BlockDescBind* cur_block = program_desc.MutableBlock(block_idx);
std::vector op_descs = cur_block->AllOps();
std::unordered_map> dup_out_ops;
@@ -394,9 +404,10 @@ std::vector> MakeBlockBackward(
std::vector> backward_descs;
for (auto it = op_descs.rbegin(); it != op_descs.rend(); ++it) {
+ VLOG(5) << "Making backward " << (*it)->Type() << " op";
std::vector> op_grads;
- if ((*it)->Type() == "recurrent") {
+ if ((*it)->Type() == "recurrent" || (*it)->Type() == "while") {
int step_block_idx = (*it)->GetBlockAttr("step_block");
BlockDescBind* backward_block = CreateStepBlock(
program_desc, no_grad_vars, grad_to_var, step_block_idx);
@@ -410,6 +421,15 @@ std::vector> MakeBlockBackward(
op_grads = MakeOpGrad(*it, no_grad_vars, grad_to_var);
}
+ if (VLOG_IS_ON(10)) {
+ std::ostringstream sout;
+ sout << "Made ";
+ for (auto& op_grad : op_grads) {
+ sout << op_grad->Type() << " ";
+ }
+ VLOG(10) << sout.str();
+ }
+
for (const auto& desc : op_grads) {
for (const std::string& out_name : desc->OutputArgumentNames()) {
if (out_name.find("@GRAD") == std::string::npos) {
@@ -425,6 +445,8 @@ std::vector> MakeBlockBackward(
op_grads.begin(), op_grads.end(), std::back_inserter(backward_descs),
[](std::unique_ptr& ptr) { return std::move(ptr); });
}
+
+ VLOG(5) << "Appending Sums";
// Check whether some variables are written more than once
std::list>> pending_sum_ops;
for (const auto& dup : dup_out_ops) {
@@ -432,16 +454,22 @@ std::vector> MakeBlockBackward(
const std::vector dup_op = dup.second;
if (out_name != kEmptyVarName && dup_op.size() > 1) {
std::vector sum_op_inputs;
+ std::string next_g_name = out_name;
for (size_t i = 0; i < dup_op.size(); ++i) {
+ VLOG(10) << backward_descs[dup_op[i]]->Type() << " has " << out_name
+ << " duplicated";
std::string new_name = out_name + "@RENAME@" + std::to_string(i);
- backward_descs[dup_op[i]]->Rename(out_name, new_name);
+ backward_descs[dup_op[i]]->RenameOutput(out_name, new_name);
+ backward_descs[dup_op[i]]->RenameInput(out_name, next_g_name);
sum_op_inputs.emplace_back(new_name);
+ next_g_name = sum_op_inputs.back();
}
std::unique_ptr sum_op(new OpDescBind(
"sum", {{"X", sum_op_inputs}}, {{"Out", {out_name}}}, {}));
pending_sum_ops.push_back({dup_op.back(), std::move(sum_op)});
}
}
+
pending_sum_ops.sort(
[](const std::pair>& a,
const std::pair>& b) {
@@ -452,6 +480,8 @@ std::vector> MakeBlockBackward(
std::move(p.second));
}
+ VLOG(5) << "MakeBlockBackward Finished";
+
return backward_descs;
}
diff --git a/paddle/framework/data_type.h b/paddle/framework/data_type.h
index 3ec88d7a72c3339bf5e7d0ca3957a3f608f039b7..be144d8fc0104fccc08006532a85906ade25c2a1 100644
--- a/paddle/framework/data_type.h
+++ b/paddle/framework/data_type.h
@@ -29,6 +29,8 @@ inline DataType ToDataType(std::type_index type) {
return DataType::INT32;
} else if (typeid(int64_t).hash_code() == type.hash_code()) {
return DataType::INT64;
+ } else if (typeid(bool).hash_code() == type.hash_code()) {
+ return DataType::BOOL;
} else {
PADDLE_THROW("Not supported");
}
diff --git a/paddle/framework/ddim.cc b/paddle/framework/ddim.cc
index 53b899a23997b71e723a298ec360a4e018d89878..8b6f42b82df14bfcd25f33ef16b5903fb965a8ba 100644
--- a/paddle/framework/ddim.cc
+++ b/paddle/framework/ddim.cc
@@ -60,8 +60,7 @@ void make_ddim(DDim& ddim, const int64_t* dims, int n) {
ddim = make_dim<9>(dims);
break;
default:
- throw std::invalid_argument(
- "Dynamic dimensions must have between [1, 9] dimensions.");
+ PADDLE_THROW("Dynamic dimensions must have between [1, 9] dimensions.");
}
}
diff --git a/paddle/framework/executor.cc b/paddle/framework/executor.cc
index 2fcf41d69f0011b0d9a3d89c97fcebacb0703e97..adedd8cb0e8504fd6fc924e62a2ede3c1c7ce698 100644
--- a/paddle/framework/executor.cc
+++ b/paddle/framework/executor.cc
@@ -120,6 +120,7 @@ void Executor::Run(const ProgramDescBind& pdesc, Scope* scope, int block_id,
for (auto& op_desc : block.AllOps()) {
auto op = paddle::framework::OpRegistry::CreateOp(*op_desc);
+ VLOG(10) << op->DebugString();
op->Run(*local_scope, *device);
}
if (create_local_scope) {
diff --git a/paddle/framework/op_desc.cc b/paddle/framework/op_desc.cc
index 39c8def82e1ebb10a0e357a648af760099020c32..48cd131550dea5ad3f368b25c31d753efbe0dff9 100644
--- a/paddle/framework/op_desc.cc
+++ b/paddle/framework/op_desc.cc
@@ -235,6 +235,23 @@ void OpDescBind::Rename(const std::string &old_name,
need_update_ = true;
}
+void OpDescBind::RenameOutput(const std::string &old_name,
+ const std::string &new_name) {
+ for (auto &output : outputs_) {
+ std::replace(output.second.begin(), output.second.end(), old_name,
+ new_name);
+ }
+ need_update_ = true;
+}
+
+void OpDescBind::RenameInput(const std::string &old_name,
+ const std::string &new_name) {
+ for (auto &input : inputs_) {
+ std::replace(input.second.begin(), input.second.end(), old_name, new_name);
+ }
+ need_update_ = true;
+}
+
struct SetAttrDescVisitor : public boost::static_visitor {
explicit SetAttrDescVisitor(OpDesc::Attr *attr) : attr_(attr) {}
mutable OpDesc::Attr *attr_;
@@ -448,7 +465,12 @@ const std::vector &CompileTimeInferShapeContext::Outputs(
DDim CompileTimeInferShapeContext::GetDim(const std::string &name) const {
auto var = block_.FindVarRecursive(name);
PADDLE_ENFORCE(var != nullptr, "Cannot find variable %s", name);
- return framework::make_ddim(var->Shape());
+ try {
+ return framework::make_ddim(var->Shape());
+ } catch (...) {
+ VLOG(5) << "GetDim of variable " << name << " error";
+ std::rethrow_exception(std::current_exception());
+ }
}
void CompileTimeInferShapeContext::SetDim(const std::string &name,
diff --git a/paddle/framework/op_desc.h b/paddle/framework/op_desc.h
index e3e96441bbf51729f2ba69c9257e6961b1de0d5c..da032319afa775571d3942bf6ae415db7d233735 100644
--- a/paddle/framework/op_desc.h
+++ b/paddle/framework/op_desc.h
@@ -73,6 +73,10 @@ class OpDescBind {
void Rename(const std::string &old_name, const std::string &new_name);
+ void RenameOutput(const std::string &old_name, const std::string &new_name);
+
+ void RenameInput(const std::string &old_name, const std::string &new_name);
+
// Only be used in C++
const AttributeMap &GetAttrMap() const;
diff --git a/paddle/framework/operator.cc b/paddle/framework/operator.cc
index 3276f8af396fe58450a8dc6713fe61e49d5ca708..93467ab8ac796277b47a861a427de2837fb2d3d4 100644
--- a/paddle/framework/operator.cc
+++ b/paddle/framework/operator.cc
@@ -403,19 +403,6 @@ class RuntimeInferShapeContext : public InferShapeContext {
void OperatorWithKernel::Run(const Scope& scope,
const platform::DeviceContext& dev_ctx) const {
- if (VLOG_IS_ON(1)) {
- auto inputs = this->InputVars();
- auto outputs = this->OutputVars(true);
- std::ostringstream sout;
- sout << "Run operator " << this->Type() << " From [";
- std::ostream_iterator out_it(sout, ",");
- std::copy(inputs.begin(), inputs.end(), out_it);
- sout << "] to [";
- std::copy(outputs.begin(), outputs.end(), out_it);
- sout << "]";
- VLOG(1) << sout.str();
- }
-
RuntimeInferShapeContext infer_shape_ctx(*this, scope);
this->InferShape(&infer_shape_ctx);
diff --git a/paddle/framework/scope.cc b/paddle/framework/scope.cc
index 9428b8a07ea0af005f6e960ddaa02da624ad9d97..9ad6272c99dd6a85520ae44c1331ac232bc6a9a2 100644
--- a/paddle/framework/scope.cc
+++ b/paddle/framework/scope.cc
@@ -38,11 +38,12 @@ Scope& Scope::NewScope() const {
Variable* Scope::Var(const std::string& name) {
auto iter = vars_.find(name);
if (iter != vars_.end()) {
+ VLOG(3) << "Get existing variable " << name;
return iter->second;
}
Variable* v = new Variable();
vars_[name] = v;
- VLOG(3) << "Create variable " << name << " on scope";
+ VLOG(3) << "Create variable " << name;
v->name_ = &(vars_.find(name)->first);
return v;
}
diff --git a/paddle/framework/shape_inference.h b/paddle/framework/shape_inference.h
index 7d36ead2ca85328c7843b3b5d423cf8e921d1c93..05dc47f06ac81f0acb6d0317cbecb3009c7dd7f0 100644
--- a/paddle/framework/shape_inference.h
+++ b/paddle/framework/shape_inference.h
@@ -53,6 +53,10 @@ class InferShapeContext {
virtual bool IsRuntime() const = 0;
+ // Note: In while op, we need this to be public
+ void SetDims(const std::vector &names,
+ const std::vector &dims);
+
protected:
virtual framework::DDim GetDim(const std::string &name) const = 0;
virtual void SetDim(const std::string &name, const framework::DDim &dim) = 0;
@@ -60,9 +64,6 @@ class InferShapeContext {
std::vector GetDims(
const std::vector &names) const;
- void SetDims(const std::vector &names,
- const std::vector &dims);
-
std::vector GetVarTypes(
const std::vector &names) const;
diff --git a/paddle/gserver/layers/ROIPoolLayer.cpp b/paddle/gserver/layers/ROIPoolLayer.cpp
index 35d4b12d3d357800fe72899069b5377c252fac5f..02402894d3354a6af221948a3360ef830881bf39 100644
--- a/paddle/gserver/layers/ROIPoolLayer.cpp
+++ b/paddle/gserver/layers/ROIPoolLayer.cpp
@@ -100,8 +100,9 @@ void ROIPoolLayer::forward(PassType passType) {
size_t roiEndH = round(bottomROIs[4] * spatialScale_);
CHECK_GE(roiBatchIdx, 0UL);
CHECK_LT(roiBatchIdx, batchSize);
- size_t roiHeight = std::max(roiEndH - roiStartH + 1, 1UL);
- size_t roiWidth = std::max(roiEndW - roiStartW + 1, 1UL);
+ size_t roiHeight =
+ std::max(roiEndH - roiStartH + 1, static_cast(1));
+ size_t roiWidth = std::max(roiEndW - roiStartW + 1, static_cast(1));
real binSizeH =
static_cast(roiHeight) / static_cast(pooledHeight_);
real binSizeW =
@@ -114,10 +115,14 @@ void ROIPoolLayer::forward(PassType passType) {
size_t wstart = static_cast(std::floor(pw * binSizeW));
size_t hend = static_cast(std::ceil((ph + 1) * binSizeH));
size_t wend = static_cast(std::ceil((pw + 1) * binSizeW));
- hstart = std::min(std::max(hstart + roiStartH, 0UL), height_);
- wstart = std::min(std::max(wstart + roiStartW, 0UL), width_);
- hend = std::min(std::max(hend + roiStartH, 0UL), height_);
- wend = std::min(std::max(wend + roiStartW, 0UL), width_);
+ hstart = std::min(
+ std::max(hstart + roiStartH, static_cast(0)), height_);
+ wstart = std::min(
+ std::max(wstart + roiStartW, static_cast(0)), width_);
+ hend = std::min(std::max(hend + roiStartH, static_cast(0)),
+ height_);
+ wend = std::min(std::max(wend + roiStartW, static_cast(0)),
+ width_);
bool isEmpty = (hend <= hstart) || (wend <= wstart);
size_t poolIndex = ph * pooledWidth_ + pw;
diff --git a/paddle/math/Storage.cpp b/paddle/math/Storage.cpp
index 4adaaef9838f0d178468af3af142031325bfc11d..a2ef731ecbcd18ca4bd0b2381de04650a2686c2d 100644
--- a/paddle/math/Storage.cpp
+++ b/paddle/math/Storage.cpp
@@ -17,9 +17,13 @@ limitations under the License. */
#include "paddle/utils/StringUtil.h"
#include "paddle/utils/Util.h"
+#ifndef PADDLE_MOBILE_INFERENCE
DEFINE_int32(pool_limit_size,
536870912,
"maximum memory size managed by a memory pool, default is 512M");
+#else
+DEFINE_int32(pool_limit_size, 0, "default is 0");
+#endif
namespace paddle {
diff --git a/paddle/memory/README.md b/paddle/memory/README.md
index 7f95e80f980b0c0b93ecb418e6b923045313eaa5..6cb003c50bc7d142d65b0591e7e5235431d2ea42 100644
--- a/paddle/memory/README.md
+++ b/paddle/memory/README.md
@@ -1,4 +1,141 @@
# Region-based Heterogeneous Memory Management
+## Design
-Please check out the [design documentation](http://gangliao.me) to find out more details about
-buddy memory allocator for both CPU and GPU.
+### Usage
+
+To allocate 4KB CPU memory:
+
+```cpp
+p = memory::Alloc(platform::CPUPlace(), 4*1024);
+```
+
+To allocate 4KB memory on the 3rd GPU:
+
+```cpp
+p = memory::Alloc(platform::GPUPlace(2), 4*1024);
+```
+
+To free memory and check the so-far used amount of memory on a place:
+
+```cpp
+auto pl = platform::GPUPlace(0);
+p = memory::Alloc(pl, 4*1024);
+cout << memory::Used(pl);
+memory::Free(pl, p);
+```
+
+### API
+
+In `paddle/memory/memory.h` we have:
+
+```cpp
+namespace memory {
+template void* Alloc(Place, size_t);
+template void Free(Place, void*);
+template size_t Used(Place);
+} // namespace memory
+```
+
+These function templates have specializations on either `platform::CPUPlace` or `platform::GPUPlace`:
+
+```cpp
+template<>
+void* Alloc(CPUPlace p, size_t size) {
+ return GetCPUBuddyAllocator()->Alloc(size);
+}
+```
+
+and
+
+```cpp
+template<>
+void Alloc(GPUPlace p, size_t size) {
+ return GetGPUBuddyAllocator(p.id)->Alloc(size);
+}
+```
+
+Similar specializations exist for `Free` and `Used`.
+
+### Implementation
+
+`GetCPUBuddyAllocator` and `GetGPUBuddyAllocator` are singletions.
+
+```cpp
+BuddyAllocator* GetCPUBuddyAllocator() {
+ static BuddyAllocator* a = NULL;
+ if (a == NULL) {
+ a = new BuddyAllocator(new CPUAllocator /*backup allocator*/, ...);
+ }
+ return a;
+}
+
+BuddyAllocator* GetGPUBuddyAllocator(int gpu_id) {
+ static BuddyAllocator* as = NULL;
+ if (as == NULL) {
+ as = new BuddyAllocator*[platform::NumGPUs()];
+ for (int gpu = 0; gpu < platform::NumGPUs(); gpu++) {
+ as[gpu] = new BuddyAllocator(new GPUAllocator(gpu) /* backup allocator */, ...);
+ }
+ }
+ return as[gpu_id);
+```
+
+#### `BuddyAllocator`
+
+`BuddyAllocator` implements the buddy allocation algorithm. Its constructor takes parameters only related with the algorithm:
+
+```cpp
+BuddyAllocator::BuddyAllocator(initial_pool_size, max_pool_size) {
+ ...
+}
+```
+
+Please be aware that **`BuddyAllocator` always allocate aligned memory**, aligned on 32-bytes, which can hold a `BuddyAllocator::Block` object:
+
+```cpp
+class BuddyAllocator {
+ private:
+ struct Block {
+ size_t size;
+ Block* left, right;
+ size_t index; // allocator id
+ };
+ ...
+};
+```
+
+Because BuddyAllocator has the meta-data of each block, it can trace the used memory -- record the amount returned by `Alloc` freed in `Free`. Instead, `CPUAllocator` and `GPUAllocator` doesn't know the size of freed memory block and cannot do the trace.
+
+#### System Allocators
+
+The `GPUAllocator` and `CPUAllocator` are calls *system allocators*. They work as the fallback allocators of `BuddyAllocator`.
+
+## Justification
+
+I got inspiration from Majel and Caffe2, though above design look different from both.
+
+### Caffe2
+
+In Caffe2, `Tensor::mutable_data()` allocates the memroy. In particular, [`Tensor::mutable_data`](https://github.com/caffe2/caffe2/blob/v0.7.0/caffe2/core/tensor.h#L523) calls [`Tensor::raw_mutable_data`](https://github.com/caffe2/caffe2/blob/v0.7.0/caffe2/core/tensor.h#L459), which in turn calls [`Context::New`](https://github.com/caffe2/caffe2/blob/v0.7.0/caffe2/core/tensor.h#L479).
+
+There are two implementations of `Context`:
+
+1. [`CPUContext`](https://github.com/caffe2/caffe2/blob/v0.7.0/caffe2/core/context.h#L105), whose [`New` method](https://github.com/caffe2/caffe2/blob/v0.7.0/caffe2/core/context.h#L131) calls [`g_cpu_allocator.get()->New(size_t)`](https://github.com/caffe2/caffe2/blob/v0.7.0/caffe2/core/context.cc#L15) to allocate the memory.
+
+1. [`CUDAContext`](https://github.com/caffe2/caffe2/blob/v0.7.0/caffe2/core/context_gpu.h#L99), which has a data member [`int gpu_id_`](https://github.com/caffe2/caffe2/blob/v0.7.0/caffe2/core/context_gpu.h#L202). This looks very similar to class `majel::GPUPlace`, who also has an `int id_` data member. `CUDAContext::New(size_t)` calls [`g_cub_allocator->DeviceAllocate(&ptr, nbytes)`](https://github.com/caffe2/caffe2/blob/v0.7.0/caffe2/core/context_gpu.cu#L355) to allocate the memory.
+
+### Majel
+
+In Majel, there are basically two allocator types:
+
+1. `cpu::SystemAllocator`, which has similar functionality to `caffe2::CPUContext::New/Delete`.
+1. `gpu::SystemAllocator`, which has similar functionality to `caffe2::CUDAContext::New/Delete`.
+
+However, memory allocation is not via these two allocators. Instead, these two allocators are defined in hidden namespaces.
+
+In Majel there are hidden global variables like:
+
+1. `cpu::SystemAllocator g_cpu_allocator`, and
+1. `vector g_gpu_allocators(NUM_GPUS)`.
+
+Programs allocate memory via a BuddyAllocator, which can take the `g_cpu_allocator` or a `g_gpu_allocators[gpu_id]` as its *fallback allocator*, so that if BuddyAllocator cannot find a block in its memory pool, it extends its memory pool by calling the fallback allocator's `New(size_t)`.
diff --git a/paddle/operators/CMakeLists.txt b/paddle/operators/CMakeLists.txt
index 71740b8b0c63886d4a6d2665de671664f10f1729..46c2833030c936119e98adcdd338245bbdaddce7 100644
--- a/paddle/operators/CMakeLists.txt
+++ b/paddle/operators/CMakeLists.txt
@@ -9,6 +9,7 @@ function(op_library TARGET)
set(OP_LIBRARY ${TARGET} ${OP_LIBRARY} PARENT_SCOPE)
set(cc_srcs)
set(cu_srcs)
+ set(cu_cc_srcs)
set(op_common_deps operator op_registry math_function)
set(options "")
set(oneValueArgs "")
@@ -22,6 +23,9 @@ function(op_library TARGET)
if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${TARGET}.cc)
list(APPEND cc_srcs ${TARGET}.cc)
endif()
+ if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${TARGET}.cu.cc)
+ list(APPEND cu_cc_srcs ${TARGET}.cu.cc)
+ endif()
if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${TARGET}.cu)
list(APPEND cu_srcs ${TARGET}.cu)
endif()
@@ -29,6 +33,8 @@ function(op_library TARGET)
foreach(src ${op_library_SRCS})
if (${src} MATCHES ".*\\.cu$")
list(APPEND cu_srcs ${src})
+ elseif(${src} MATCHES ".*\\.cu.cc$")
+ list(APPEND cu_cc_srcs ${src})
elseif(${src} MATCHES ".*\\.cc$")
list(APPEND cc_srcs ${src})
else()
@@ -43,7 +49,7 @@ function(op_library TARGET)
endif()
if (WITH_GPU)
- nv_library(${TARGET} SRCS ${cc_srcs} ${cu_srcs} DEPS ${op_library_DEPS}
+ nv_library(${TARGET} SRCS ${cc_srcs} ${cu_cc_srcs} ${cu_srcs} DEPS ${op_library_DEPS}
${op_common_deps})
else()
cc_library(${TARGET} SRCS ${cc_srcs} DEPS ${op_library_DEPS}
@@ -147,7 +153,9 @@ function(op_library TARGET)
# pybind USE_CPU_ONLY_OP
list(LENGTH cu_srcs cu_srcs_len)
- if (${pybind_flag} EQUAL 0 AND ${cu_srcs_len} EQUAL 0)
+ list(LENGTH cu_cc_srcs cu_cc_srcs_len)
+
+ if (${pybind_flag} EQUAL 0 AND ${cu_srcs_len} EQUAL 0 AND ${cu_cc_srcs_len} EQUAL 0)
file(APPEND ${pybind_file} "USE_CPU_ONLY_OP(${TARGET});\n")
set(pybind_flag 1)
endif()
@@ -167,11 +175,12 @@ set(DEPS_OPS
recurrent_op
dynamic_recurrent_op
softmax_with_cross_entropy_op
+ softmax_op
+ sequence_softmax_op
sum_op
pool_op
pool_with_index_op
conv_op
- lstm_op
conv_transpose_op
nccl_op
sequence_conv_op
@@ -181,13 +190,20 @@ set(DEPS_OPS
array_to_lod_tensor_op
lstm_op
tensor_array_read_write_op
- gru_op)
+ gru_op
+ adagrad_op
+ sgd_op)
+
op_library(cond_op SRCS cond_op.cc DEPS framework_proto tensor operator net_op)
op_library(cross_entropy_op DEPS cross_entropy)
op_library(softmax_with_cross_entropy_op DEPS cross_entropy softmax)
+op_library(softmax_op DEPS softmax)
+op_library(sequence_softmax_op DEPS softmax)
+op_library(sum_op DEPS selected_rows_functor)
+op_library(sgd_op DEPS selected_rows_functor)
+op_library(adagrad_op DEPS selected_rows_functor)
op_library(conv_op DEPS vol2col)
-op_library(sum_op DEPS net_op selected_rows_functor)
op_library(pool_op DEPS pooling)
op_library(pool_with_index_op DEPS pooling)
op_library(lod_rank_table_op SRCS lod_rank_table_op.cc DEPS lod_rank_table)
@@ -227,6 +243,6 @@ cc_test(dynamic_recurrent_op_test SRCS dynamic_recurrent_op_test.cc
rnn/recurrent_op_utils.cc
DEPS dynamic_recurrent_op)
if(WITH_GPU)
- nv_test(nccl_op_test SRCS nccl_op_test.cu DEPS nccl_op gpu_info device_context)
+ cc_test(nccl_op_test SRCS nccl_op_test.cu.cc DEPS nccl_op gpu_info device_context)
endif()
cc_test(save_load_op_test SRCS save_load_op_test.cc DEPS save_op load_op)
diff --git a/paddle/operators/accuracy_op.cu b/paddle/operators/accuracy_op.cu
index b575c682f0d30678a72a33040cce6cc799da26cb..d2dcab4e548b99c6beecfaa570ac31804fd07d82 100644
--- a/paddle/operators/accuracy_op.cu
+++ b/paddle/operators/accuracy_op.cu
@@ -16,6 +16,7 @@ limitations under the License. */
#include
#include "paddle/operators/accuracy_op.h"
#include "paddle/platform/cuda_helper.h"
+#include "paddle/platform/gpu_info.h"
namespace paddle {
namespace operators {
@@ -73,26 +74,28 @@ class AccuracyOpCUDAKernel : public framework::OpKernel {
int num_samples = static_cast(inference->dims()[0]);
size_t infer_width = inference->dims()[1];
- PADDLE_ENFORCE(cudaMemset(accuracy_data, 0, sizeof(float)));
- // cudaMemset((void**)&correct_data, 0, sizeof(float));
+ auto stream = ctx.cuda_device_context().stream();
+ platform::GpuMemsetAsync(accuracy_data, 0, sizeof(float), stream);
if (num_samples == 0) {
return;
}
- cudaMemcpy(total_data, &num_samples, sizeof(int), cudaMemcpyHostToDevice);
+ platform::GpuMemcpyAsync(total_data, &num_samples, sizeof(int),
+ cudaMemcpyHostToDevice, stream);
- AccuracyCudaKernel<<<
- 1, PADDLE_CUDA_NUM_THREADS, 0, ctx.cuda_device_context().stream()>>>(
+ AccuracyCudaKernel<
+ PADDLE_CUDA_NUM_THREADS><<<1, PADDLE_CUDA_NUM_THREADS, 0, stream>>>(
num_samples, infer_width, indices_data, label_data, correct_data,
accuracy_data);
int d_num_samples, d_num_correct;
float d_accuracy;
- cudaMemcpy(&d_num_correct, correct_data, sizeof(int),
- cudaMemcpyDeviceToHost);
- cudaMemcpy(&d_num_samples, total_data, sizeof(int), cudaMemcpyDeviceToHost);
- cudaMemcpy(&d_accuracy, accuracy_data, sizeof(float),
- cudaMemcpyDeviceToHost);
+ platform::GpuMemcpyAsync(&d_num_correct, correct_data, sizeof(int),
+ cudaMemcpyDeviceToHost, stream);
+ platform::GpuMemcpyAsync(&d_num_samples, total_data, sizeof(int),
+ cudaMemcpyDeviceToHost, stream);
+ platform::GpuMemcpyAsync(&d_accuracy, accuracy_data, sizeof(float),
+ cudaMemcpyDeviceToHost, stream);
}
};
diff --git a/paddle/operators/adagrad_op.cc b/paddle/operators/adagrad_op.cc
index 8d1a2b7938d2c6607cbeb3cecb72d1d5b83dd8b9..d6686e3ef3165976cf4c077a7a0f213082aa7716 100644
--- a/paddle/operators/adagrad_op.cc
+++ b/paddle/operators/adagrad_op.cc
@@ -14,6 +14,11 @@ limitations under the License. */
#include "paddle/operators/adagrad_op.h"
+#include
+
+#include "paddle/operators/math/math_function.h"
+#include "paddle/operators/math/selected_rows_functor.h"
+
namespace paddle {
namespace operators {
@@ -21,7 +26,7 @@ class AdagradOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
- void InferShape(framework::InferShapeContext *ctx) const override {
+ void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("Param"),
"Input(Param) of AdagradOp should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Grad"),
@@ -54,8 +59,8 @@ class AdagradOp : public framework::OperatorWithKernel {
class AdagradOpMaker : public framework::OpProtoAndCheckerMaker {
public:
- AdagradOpMaker(framework::OpProto *proto,
- framework::OpAttrChecker *op_checker)
+ AdagradOpMaker(framework::OpProto* proto,
+ framework::OpAttrChecker* op_checker)
: OpProtoAndCheckerMaker(proto, op_checker) {
AddInput("Param", "(Tensor) Input parameter");
AddInput("Grad", "(Tensor) Input gradient");
@@ -87,10 +92,85 @@ for numerical stability to avoid the division by zero error.
)DOC");
}
};
+
+namespace {
+size_t FindPos(const std::vector& rows, int64_t value) {
+ return std::find(rows.begin(), rows.end(), value) - rows.begin();
+}
+} // namespace
+
+template
+struct SparseAdagradFunctor {
+ void operator()(const platform::DeviceContext& context,
+ const framework::SelectedRows& grad,
+ const framework::Tensor& learning_rate, T epsilon,
+ framework::Tensor* moment, framework::Tensor* param) {
+ // 1. g_m.rows = set(g.rows)
+ auto grad_rows = grad.rows();
+ std::set row_set(grad_rows.begin(), grad_rows.end());
+ std::vector merge_rows(row_set.begin(), row_set.end());
+
+ auto grad_width = grad.value().dims()[1];
+ std::unique_ptr grad_merge{
+ new framework::SelectedRows()};
+ grad_merge->set_rows(merge_rows);
+ grad_merge->set_height(grad.height());
+ grad_merge->mutable_value()->mutable_data(
+ framework::make_ddim(
+ {static_cast(merge_rows.size()), grad_width}),
+ context.GetPlace());
+
+ math::SetConstant constant_functor;
+ constant_functor(context, grad_merge->mutable_value(), 0.0);
+
+ auto* grad_merge_data = grad_merge->mutable_value()->data();
+ auto* grad_data = grad.value().data();
+
+ for (size_t i = 0; i < grad_rows.size(); i++) {
+ size_t grad_merge_i = FindPos(merge_rows, grad_rows[i]);
+ for (int64_t j = 0; j < grad_width; j++) {
+ grad_merge_data[grad_merge_i * grad_width + j] +=
+ grad_data[i * grad_width + j];
+ }
+ }
+
+ // 2. m += g_m * g_m
+ std::unique_ptr grad_square{
+ new framework::SelectedRows()};
+ grad_square->set_rows(grad_merge->rows());
+ grad_square->set_height(grad_merge->height());
+ grad_square->mutable_value()->mutable_data(grad_merge->value().dims(),
+ context.GetPlace());
+ auto gs =
+ framework::EigenVector::Flatten(*(grad_square->mutable_value()));
+ auto gm = framework::EigenVector::Flatten(grad_merge->value());
+ gs.device(*context.GetEigenDevice()) = gm * gm;
+
+ math::SelectedRowsAddToTensor functor;
+ functor(context, *grad_square, moment);
+
+ // 3. update parameter
+ auto* lr = learning_rate.data();
+ auto* param_data = param->data();
+ auto* moment_data = moment->data();
+
+ for (size_t i = 0; i < merge_rows.size(); i++) {
+ for (int64_t j = 0; j < grad_width; j++) {
+ param_data[merge_rows[i] * grad_width + j] -=
+ lr[0] * grad_merge_data[i * grad_width + j] /
+ (std::sqrt(moment_data[merge_rows[i] * grad_width + j]) + epsilon);
+ }
+ }
+ }
+};
+
+template struct SparseAdagradFunctor;
+template struct SparseAdagradFunctor;
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OP_WITHOUT_GRADIENT(adagrad, ops::AdagradOp, ops::AdagradOpMaker);
-REGISTER_OP_CPU_KERNEL(adagrad,
- ops::AdagradOpKernel);
+REGISTER_OP_CPU_KERNEL(
+ adagrad, ops::AdagradOpKernel,
+ ops::AdagradOpKernel);
diff --git a/paddle/operators/adagrad_op.cu b/paddle/operators/adagrad_op.cu
index a5b7951121360f78612f9008a522235104708112..5b869e6bc5f4604ba6055ffd62fa21e4a1f41b93 100644
--- a/paddle/operators/adagrad_op.cu
+++ b/paddle/operators/adagrad_op.cu
@@ -14,7 +14,138 @@
#define EIGEN_USE_GPU
#include "paddle/operators/adagrad_op.h"
+#include "paddle/operators/math/selected_rows_functor.h"
+#include "paddle/operators/math/math_function.h"
+#include "paddle/platform/cuda_helper.h"
+
+namespace paddle {
+namespace operators {
+
+namespace {
+
+template
+__global__ void MergeGradKernel(const T* grad, const int64_t* grad_rows,
+ T* grad_merge, const int64_t* grad_merge_rows,
+ size_t grad_merge_rows_size,
+ int64_t row_numel) {
+ const int ty = blockIdx.y;
+ int tid = threadIdx.x;
+ __shared__ size_t grad_merge_idx;
+
+ if (tid == 0) {
+ for (size_t i = 0; i < grad_merge_rows_size; i++) {
+ if (grad_rows[ty] == grad_merge_rows[i]) {
+ grad_merge_idx = i;
+ }
+ }
+ }
+
+ __syncthreads();
+
+ grad += ty * row_numel;
+ grad_merge += grad_merge_idx * row_numel;
+ for (int index = tid; index < row_numel; index += block_size) {
+ paddle::platform::CudaAtomicAdd(grad_merge + index, grad[index]);
+ }
+}
+
+template
+__global__ void SparseAdagradFunctorKernel(const T* grad, const int64_t* rows,
+ const T* learning_rate, T* param,
+ T* moment, int64_t row_numel,
+ T epsilon) {
+ const int ty = blockIdx.y;
+ int tid = threadIdx.x;
+
+ grad += ty * row_numel;
+ param += rows[ty] * row_numel;
+ moment += rows[ty] * row_numel;
+
+ for (int index = tid; index < row_numel; index += block_size) {
+ // Since index in rows of SelectedRows can be duplicate, we have to use
+ // Atomic Operation to avoid concurrent write error.
+ paddle::platform::CudaAtomicAdd(param + index,
+ -1.0 * learning_rate[0] * grad[index] /
+ (sqrt(moment[index]) + epsilon));
+ }
+}
+} // namespace
+
+template
+struct SparseAdagradFunctor {
+ void operator()(const platform::DeviceContext& context,
+ const framework::SelectedRows& grad,
+ const framework::Tensor& learning_rate, T epsilon,
+ framework::Tensor* moment, framework::Tensor* param) {
+ // 1. g_m.rows = set(g.rows)
+ auto grad_rows = grad.rows();
+ std::set row_set(grad_rows.begin(), grad_rows.end());
+ std::vector merge_rows(row_set.begin(), row_set.end());
+
+ auto grad_width = grad.value().dims()[1];
+ std::unique_ptr grad_merge{
+ new framework::SelectedRows()};
+ grad_merge->set_rows(merge_rows);
+ grad_merge->set_height(grad.height());
+ grad_merge->mutable_value()->mutable_data(
+ framework::make_ddim(
+ {static_cast(merge_rows.size()), grad_width}),
+ context.GetPlace());
+
+ math::SetConstant constant_functor;
+ constant_functor(context, grad_merge->mutable_value(), 0.0);
+
+ auto* grad_merge_data = grad_merge->mutable_value()->data();
+ auto* grad_data = grad.value().data();
+
+ const int block_size = 256;
+ dim3 threads(block_size, 1);
+ dim3 grid1(1, grad_rows.size());
+
+ MergeGradKernel<
+ T, 256><<(context)
+ .stream()>>>(grad_data, grad.rows().data(),
+ grad_merge_data, grad_merge->rows().data(),
+ grad_merge->rows().size(), grad_width);
+
+ // 2. m += g_m * g_m
+ std::unique_ptr grad_square{
+ new framework::SelectedRows()};
+ grad_square->set_rows(grad_merge->rows());
+ grad_square->set_height(grad_merge->height());
+ grad_square->mutable_value()->mutable_data(grad_merge->value().dims(),
+ context.GetPlace());
+ auto gs =
+ framework::EigenVector::Flatten(*(grad_square->mutable_value()));
+ auto gm = framework::EigenVector::Flatten(grad_merge->value());
+ gs.device(*context.GetEigenDevice()) = gm * gm;
+
+ math::SelectedRowsAddToTensor functor;
+ functor(context, *grad_square, moment);
+
+ // 3. update parameter
+ auto* lr = learning_rate.data();
+ auto* param_data = param->data();
+ auto* moment_data = moment->data();
+
+ dim3 grid2(1, merge_rows.size());
+ SparseAdagradFunctorKernel<
+ T, 256><<(context)
+ .stream()>>>(grad_merge_data, grad_merge->rows().data(),
+ lr, param_data,
+ moment_data, grad_width, epsilon);
+ }
+};
+
+template struct SparseAdagradFunctor;
+template struct SparseAdagradFunctor;
+
+} // namespace operators
+} // namespace paddle
namespace ops = paddle::operators;
-REGISTER_OP_GPU_KERNEL(adagrad,
- ops::AdagradOpKernel);
+REGISTER_OP_GPU_KERNEL(
+ adagrad, ops::AdagradOpKernel,
+ ops::AdagradOpKernel);
diff --git a/paddle/operators/adagrad_op.h b/paddle/operators/adagrad_op.h
index c5d8f751d3527f89b96d4274328ba0bb5f6efa44..4d4a6434c7c472d8ceb01edfc4050fbb009d6c9f 100644
--- a/paddle/operators/adagrad_op.h
+++ b/paddle/operators/adagrad_op.h
@@ -19,35 +19,59 @@ limitations under the License. */
namespace paddle {
namespace operators {
+template
+struct SparseAdagradFunctor {
+ void operator()(const platform::DeviceContext& context,
+ const framework::SelectedRows& grad,
+ const framework::Tensor& learning_rate, T epsilon,
+ framework::Tensor* moment, framework::Tensor* param);
+};
+
template
class AdagradOpKernel : public framework::OpKernel {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
- auto param_out_tensor = ctx.Output("ParamOut");
- auto moment_out_tensor = ctx.Output("MomentOut");
+ auto* param_out_tensor = ctx.Output("ParamOut");
+ auto* moment_out_tensor = ctx.Output("MomentOut");
param_out_tensor->mutable_data(ctx.GetPlace());
moment_out_tensor->mutable_data(ctx.GetPlace());
- float epsilon = ctx.Attr("epsilon");
-
- auto param = framework::EigenVector::Flatten(
- *ctx.Input("Param"));
- auto grad = framework::EigenVector::Flatten(
- *ctx.Input("Grad"));
- auto moment = framework::EigenVector::Flatten(
- *ctx.Input("Moment"));
- auto lr = framework::EigenVector::Flatten(
- *ctx.Input("LearningRate"));
-
- auto param_out = framework::EigenVector::Flatten(*param_out_tensor);
- auto moment_out = framework::EigenVector::Flatten(*moment_out_tensor);
- auto place = ctx.GetEigenDevice();
-
- moment_out.device(place) = moment + grad * grad;
- Eigen::DSizes m_dsize(moment_out_tensor->numel());
- param_out.device(place) =
- param - lr.broadcast(m_dsize) * grad / (moment_out.sqrt() + epsilon);
+ T epsilon = static_cast(ctx.Attr("epsilon"));
+
+ auto* grad_var = ctx.InputVar("Grad");
+ if (grad_var->IsType()) {
+ auto param = framework::EigenVector::Flatten(
+ *ctx.Input("Param"));
+ auto grad = framework::EigenVector::Flatten(
+ *ctx.Input("Grad"));
+ auto moment = framework::EigenVector::Flatten(
+ *ctx.Input("Moment"));
+ auto lr = framework::EigenVector::Flatten(
+ *ctx.Input("LearningRate"));
+
+ auto param_out = framework::EigenVector::Flatten(*param_out_tensor);
+ auto moment_out = framework::EigenVector::Flatten(*moment_out_tensor);
+ auto place = ctx.GetEigenDevice();
+
+ moment_out.device(place) = moment + grad * grad;
+ Eigen::DSizes m_dsize(moment_out_tensor->numel());
+ param_out.device(place) =
+ param - lr.broadcast(m_dsize) * grad / (moment_out.sqrt() + epsilon);
+ } else if (grad_var->IsType()) {
+ auto* param_tensor = ctx.Input("Param");
+ PADDLE_ENFORCE_EQ(param_tensor, param_out_tensor);
+
+ auto* moment_tensor = ctx.Input("Moment");
+ PADDLE_ENFORCE_EQ(moment_tensor, moment_out_tensor);
+
+ SparseAdagradFunctor functor;
+ functor(ctx.device_context(), *ctx.Input("Grad"),
+ *ctx.Input("LearningRate"), epsilon,
+ moment_out_tensor, param_out_tensor);
+ } else {
+ PADDLE_THROW("Unsupported Variable Type of Grad");
+ }
}
};
diff --git a/paddle/operators/array_operator.h b/paddle/operators/array_operator.h
index 666043e824f885e9c0e79e319d0a38ba108c209a..233a81198e336d3190565fb18556f96979cec0ce 100644
--- a/paddle/operators/array_operator.h
+++ b/paddle/operators/array_operator.h
@@ -42,6 +42,7 @@ class ArrayOp : public framework::OperatorBase {
} else {
offset = static_cast(*i_tensor.data());
}
+ VLOG(10) << " Offset = " << offset;
return offset;
}
};
diff --git a/paddle/operators/batch_norm_op.cu b/paddle/operators/batch_norm_op.cu.cc
similarity index 100%
rename from paddle/operators/batch_norm_op.cu
rename to paddle/operators/batch_norm_op.cu.cc
diff --git a/paddle/operators/beam_search_op.cc b/paddle/operators/beam_search_op.cc
new file mode 100644
index 0000000000000000000000000000000000000000..17926a813d5b0b8ace6a1b20066cd0007703c696
--- /dev/null
+++ b/paddle/operators/beam_search_op.cc
@@ -0,0 +1,185 @@
+/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License. */
+
+#include "paddle/operators/beam_search_op.h"
+
+#include