提交 ffbf00a0 编写于 作者: L Luo Tao

Merge branch 'develop' into group

...@@ -13,8 +13,6 @@ ...@@ -13,8 +13,6 @@
# The document of clang-format is # The document of clang-format is
# http://clang.llvm.org/docs/ClangFormat.html # http://clang.llvm.org/docs/ClangFormat.html
# http://clang.llvm.org/docs/ClangFormatStyleOptions.html # http://clang.llvm.org/docs/ClangFormatStyleOptions.html
#
# TODO(yuyang18): Add python and other language code style
--- ---
Language: Cpp Language: Cpp
BasedOnStyle: Google BasedOnStyle: Google
...@@ -22,8 +20,9 @@ IndentWidth: 2 ...@@ -22,8 +20,9 @@ IndentWidth: 2
TabWidth: 2 TabWidth: 2
ContinuationIndentWidth: 4 ContinuationIndentWidth: 4
AccessModifierOffset: -2 # The private/protected/public has no indent in class AccessModifierOffset: -2 # The private/protected/public has no indent in class
PointerAlignment: Left # int* p/int& p, not int *p/int &p
Standard: Cpp11 Standard: Cpp11
AllowAllParametersOfDeclarationOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true
BinPackParameters: false
BinPackArguments: false
... ...
- repo: https://github.com/Lucas-C/pre-commit-hooks.git
sha: c25201a00e6b0514370501050cf2a8538ac12270
hooks:
- id: remove-crlf
- repo: https://github.com/reyoung/mirrors-yapf.git
sha: v0.13.2
hooks:
- id: yapf
- repo: https://github.com/pre-commit/pre-commit-hooks
sha: 4ef03c4223ad322c7adaa6c6c0efb26b57df3b71
hooks:
- id: check-added-large-files
- id: check-merge-conflict
- id: check-symlinks
- id: detect-private-key
- id: end-of-file-fixer
# TODO(yuyang): trailing whitespace has some bugs on markdown
# files now, please not add it to pre-commit hook now
# - id: trailing-whitespace
#
# TODO(yuyang): debug-statements not fit for Paddle, because
# not all of our python code is runnable. Some are used for
# documenation
# - id: debug-statements
This folder contains scripts used in PaddlePaddle introduction. This folder contains scripts used in PaddlePaddle introduction.
- use `bash train.sh` to train a simple linear regression model - use `bash train.sh` to train a simple linear regression model
- use `python evaluate_model.py` to read model parameters. You can see that `w` and `b` are very close to [2, 0.3]. - use `python evaluate_model.py` to read model parameters. You can see that `w` and `b` are very close to [2, 0.3].
...@@ -19,4 +19,3 @@ done ...@@ -19,4 +19,3 @@ done
cd $DIR cd $DIR
rm -f *.list rm -f *.list
python generate_list.py python generate_list.py
...@@ -14,4 +14,3 @@ ...@@ -14,4 +14,3 @@
"fields": ["id", "title", "genres"] "fields": ["id", "title", "genres"]
} }
} }
...@@ -37,4 +37,3 @@ paddle train \ ...@@ -37,4 +37,3 @@ paddle train \
--use_gpu=false \ --use_gpu=false \
--config_args=is_test=1 \ --config_args=is_test=1 \
2>&1 | tee 'test.log' 2>&1 | tee 'test.log'
...@@ -24,4 +24,3 @@ paddle train \ ...@@ -24,4 +24,3 @@ paddle train \
--show_parameter_stats_period=10 \ --show_parameter_stats_period=10 \
--test_all_data_in_one_period=1 \ --test_all_data_in_one_period=1 \
2>&1 | tee 'train.log' 2>&1 | tee 'train.log'
# Semantic Role labeling Tutorial # # Semantic Role labeling Tutorial #
Semantic role labeling (SRL) is a form of shallow semantic parsing whose goal is to discover the predicate-argument structure of each predicate in a given input sentence. SRL is useful as an intermediate step in a wide range of natural language processing tasks, such as information extraction. automatic document categorization and question answering. An instance is as following [1]: Semantic role labeling (SRL) is a form of shallow semantic parsing whose goal is to discover the predicate-argument structure of each predicate in a given input sentence. SRL is useful as an intermediate step in a wide range of natural language processing tasks, such as information extraction. automatic document categorization and question answering. An instance is as following [1]:
[ <sub>A0</sub> He ] [ <sub>AM-MOD</sub> would ][ <sub>AM-NEG</sub> n’t ] [ <sub>V</sub> accept] [ <sub>A1</sub> anything of value ] from [<sub>A2</sub> those he was writing about ]. [ <sub>A0</sub> He ] [ <sub>AM-MOD</sub> would ][ <sub>AM-NEG</sub> n’t ] [ <sub>V</sub> accept] [ <sub>A1</sub> anything of value ] from [<sub>A2</sub> those he was writing about ].
- V: verb - V: verb
- A0: acceptor - A0: acceptor
- A1: thing accepted - A1: thing accepted
- A2: accepted-from - A2: accepted-from
- A3: Attribute - A3: Attribute
- AM-MOD: modal - AM-MOD: modal
- AM-NEG: negation - AM-NEG: negation
Given the verb "accept", the chunks in sentence would play certain semantic roles. Here, the label scheme is from Penn Proposition Bank. Given the verb "accept", the chunks in sentence would play certain semantic roles. Here, the label scheme is from Penn Proposition Bank.
To this date, most of the successful SRL systems are built on top of some form of parsing results where pre-defined feature templates over the syntactic structure are used. This tutorial will present an end-to-end system using deep bidirectional long short-term memory (DB-LSTM)[2] for solving the SRL task, which largely outperforms the previous state-of-the-art systems. The system regards SRL task as the sequence labelling problem. To this date, most of the successful SRL systems are built on top of some form of parsing results where pre-defined feature templates over the syntactic structure are used. This tutorial will present an end-to-end system using deep bidirectional long short-term memory (DB-LSTM)[2] for solving the SRL task, which largely outperforms the previous state-of-the-art systems. The system regards SRL task as the sequence labelling problem.
## Data Description ## Data Description
The relevant paper[2] takes the data set in CoNLL-2005&2012 Shared Task for training and testing. Accordingto data license, the demo adopts the test data set of CoNLL-2005, which can be reached on website. The relevant paper[2] takes the data set in CoNLL-2005&2012 Shared Task for training and testing. Accordingto data license, the demo adopts the test data set of CoNLL-2005, which can be reached on website.
To download and process the original data, user just need to execute the following command: To download and process the original data, user just need to execute the following command:
```bash ```bash
cd data cd data
./get_data.sh ./get_data.sh
``` ```
Several new files appear in the `data `directory as follows. Several new files appear in the `data `directory as follows.
```bash ```bash
conll05st-release:the test data set of CoNll-2005 shared task conll05st-release:the test data set of CoNll-2005 shared task
test.wsj.words:the Wall Street Journal data sentences test.wsj.words:the Wall Street Journal data sentences
test.wsj.props: the propositional arguments test.wsj.props: the propositional arguments
src.dict:the dictionary of words in sentences src.dict:the dictionary of words in sentences
tgt.dict:the labels dictionary tgt.dict:the labels dictionary
feature: the extracted features from data set feature: the extracted features from data set
``` ```
## Training ## Training
### DB-LSTM ### DB-LSTM
Please refer to the Sentiment Analysis demo to learn more about the long short-term memory unit. Please refer to the Sentiment Analysis demo to learn more about the long short-term memory unit.
Unlike Bidirectional-LSTM that used in Sentiment Analysis demo, the DB-LSTM adopts another way to stack LSTM layer. First a standard LSTM processes the sequence in forward direction. The input and output of this LSTM layer are taken by the next LSTM layer as input, processed in reversed direction. These two standard LSTM layers compose a pair of LSTM. Then we stack LSTM layers pair after pair to obtain the deep LSTM model. Unlike Bidirectional-LSTM that used in Sentiment Analysis demo, the DB-LSTM adopts another way to stack LSTM layer. First a standard LSTM processes the sequence in forward direction. The input and output of this LSTM layer are taken by the next LSTM layer as input, processed in reversed direction. These two standard LSTM layers compose a pair of LSTM. Then we stack LSTM layers pair after pair to obtain the deep LSTM model.
The following figure shows a temporal expanded 2-layer DB-LSTM network. The following figure shows a temporal expanded 2-layer DB-LSTM network.
<center> <center>
![pic](./network_arch.png) ![pic](./network_arch.png)
</center> </center>
### Features ### Features
Two input features play an essential role in this pipeline: predicate (pred) and argument (argu). Two other features: predicate context (ctx-p) and region mark (mr) are also adopted. Because a single predicate word can not exactly describe the predicate information, especially when the same words appear more than one times in a sentence. With the predicate context, the ambiguity can be largely eliminated. Similarly, we use region mark m<sub>r</sub> = 1 to denote the argument position if it locates in the predicate context region, or m<sub>r</sub> = 0 if does not. These four simple features are all we need for our SRL system. Features of one sample with context size set to 1 is showed as following[2]: Two input features play an essential role in this pipeline: predicate (pred) and argument (argu). Two other features: predicate context (ctx-p) and region mark (mr) are also adopted. Because a single predicate word can not exactly describe the predicate information, especially when the same words appear more than one times in a sentence. With the predicate context, the ambiguity can be largely eliminated. Similarly, we use region mark m<sub>r</sub> = 1 to denote the argument position if it locates in the predicate context region, or m<sub>r</sub> = 0 if does not. These four simple features are all we need for our SRL system. Features of one sample with context size set to 1 is showed as following[2]:
<center> <center>
![pic](./feature.jpg) ![pic](./feature.jpg)
</center> </center>
In this sample, the coresponding labelled sentence is: In this sample, the coresponding labelled sentence is:
[ <sub>A1</sub> A record date ] has [ <sub>AM-NEG</sub> n't ] been [ <sub>V</sub> set ] . [ <sub>A1</sub> A record date ] has [ <sub>AM-NEG</sub> n't ] been [ <sub>V</sub> set ] .
In the demo, we adopt the feature template as above, consists of : `argument`, `predicate`, `ctx-p (p=-1,0,1)`, `mark` and use `B/I/O` scheme to label each argument. These features and labels are stored in `feature` file, and separated by `\t`. In the demo, we adopt the feature template as above, consists of : `argument`, `predicate`, `ctx-p (p=-1,0,1)`, `mark` and use `B/I/O` scheme to label each argument. These features and labels are stored in `feature` file, and separated by `\t`.
### Data Provider ### Data Provider
`dataprovider.py` is the python file to wrap data. `hook()` function is to define the data slots for network. The Six features and label are all IndexSlots. `dataprovider.py` is the python file to wrap data. `hook()` function is to define the data slots for network. The Six features and label are all IndexSlots.
``` ```
def hook(settings, word_dict, label_dict, **kwargs): def hook(settings, word_dict, label_dict, **kwargs):
settings.word_dict = word_dict settings.word_dict = word_dict
settings.label_dict = label_dict settings.label_dict = label_dict
#all inputs are integral and sequential type #all inputs are integral and sequential type
settings.slots = [ settings.slots = [
integer_value_sequence(len(word_dict)), integer_value_sequence(len(word_dict)),
integer_value_sequence(len(word_dict)), integer_value_sequence(len(word_dict)),
integer_value_sequence(len(word_dict)), integer_value_sequence(len(word_dict)),
integer_value_sequence(len(word_dict)), integer_value_sequence(len(word_dict)),
integer_value_sequence(len(word_dict)), integer_value_sequence(len(word_dict)),
integer_value_sequence(2), integer_value_sequence(2),
integer_value_sequence(len(label_dict))] integer_value_sequence(len(label_dict))]
``` ```
The corresponding data iterator is as following: The corresponding data iterator is as following:
``` ```
@provider(use_seq=True, init_hook=hook) @provider(use_seq=True, init_hook=hook)
def process(obj, file_name): def process(obj, file_name):
with open(file_name, 'r') as fdata: with open(file_name, 'r') as fdata:
for line in fdata: for line in fdata:
sentence, predicate, ctx_n1, ctx_0, ctx_p1, mark, label = line.strip().split('\t') sentence, predicate, ctx_n1, ctx_0, ctx_p1, mark, label = line.strip().split('\t')
words = sentence.split() words = sentence.split()
sen_len = len(words) sen_len = len(words)
word_slot = [obj.word_dict.get(w, UNK_IDX) for w in words] word_slot = [obj.word_dict.get(w, UNK_IDX) for w in words]
predicate_slot = [obj.word_dict.get(predicate, UNK_IDX)] * sen_len predicate_slot = [obj.word_dict.get(predicate, UNK_IDX)] * sen_len
ctx_n1_slot = [obj.word_dict.get(ctx_n1, UNK_IDX) ] * sen_len ctx_n1_slot = [obj.word_dict.get(ctx_n1, UNK_IDX) ] * sen_len
ctx_0_slot = [obj.word_dict.get(ctx_0, UNK_IDX) ] * sen_len ctx_0_slot = [obj.word_dict.get(ctx_0, UNK_IDX) ] * sen_len
ctx_p1_slot = [obj.word_dict.get(ctx_p1, UNK_IDX) ] * sen_len ctx_p1_slot = [obj.word_dict.get(ctx_p1, UNK_IDX) ] * sen_len
marks = mark.split() marks = mark.split()
mark_slot = [int(w) for w in marks] mark_slot = [int(w) for w in marks]
label_list = label.split() label_list = label.split()
label_slot = [obj.label_dict.get(w) for w in label_list] label_slot = [obj.label_dict.get(w) for w in label_list]
yield word_slot, predicate_slot, ctx_n1_slot, ctx_0_slot, ctx_p1_slot, mark_slot, label_slot yield word_slot, predicate_slot, ctx_n1_slot, ctx_0_slot, ctx_p1_slot, mark_slot, label_slot
``` ```
The `process`function yield 7 lists which are six features and labels. The `process`function yield 7 lists which are six features and labels.
### Neural Network Config ### Neural Network Config
`db_lstm.py` is the neural network config file to load the dictionaries and define the data provider module and network architecture during the training procedure. `db_lstm.py` is the neural network config file to load the dictionaries and define the data provider module and network architecture during the training procedure.
Seven `data_layer` load instances from data provider. Six features are transformed into embedddings respectively, and mixed by `mixed_layer` . Deep bidirectional LSTM layers extract features for the softmax layer. The objective function is cross entropy of labels. Seven `data_layer` load instances from data provider. Six features are transformed into embedddings respectively, and mixed by `mixed_layer` . Deep bidirectional LSTM layers extract features for the softmax layer. The objective function is cross entropy of labels.
### Run Training ### Run Training
The script for training is `train.sh`, user just need to execute: The script for training is `train.sh`, user just need to execute:
```bash ```bash
./train.sh ./train.sh
``` ```
The content in `train.sh`: The content in `train.sh`:
``` ```
paddle train \ paddle train \
--config=./db_lstm.py \ --config=./db_lstm.py \
--save_dir=./output \ --save_dir=./output \
--trainer_count=4 \ --trainer_count=4 \
--log_period=10 \ --log_period=10 \
--num_passes=500 \ --num_passes=500 \
--use_gpu=false \ --use_gpu=false \
--show_parameter_stats_period=10 \ --show_parameter_stats_period=10 \
--test_all_data_in_one_period=1 \ --test_all_data_in_one_period=1 \
2>&1 | tee 'train.log' 2>&1 | tee 'train.log'
``` ```
- \--config=./db_lstm.py : network config file. - \--config=./db_lstm.py : network config file.
- \--save_di=./output: output path to save models. - \--save_di=./output: output path to save models.
- \--trainer_count=4 : set thread number (or GPU count). - \--trainer_count=4 : set thread number (or GPU count).
- \--log_period=10 : print log every 20 batches. - \--log_period=10 : print log every 20 batches.
- \--num_passes=500: set pass number, one pass in PaddlePaddle means training all samples in dataset one time. - \--num_passes=500: set pass number, one pass in PaddlePaddle means training all samples in dataset one time.
- \--use_gpu=false: use CPU to train, set true, if you install GPU version of PaddlePaddle and want to use GPU to train. - \--use_gpu=false: use CPU to train, set true, if you install GPU version of PaddlePaddle and want to use GPU to train.
- \--show_parameter_stats_period=10: show parameter statistic every 100 batches. - \--show_parameter_stats_period=10: show parameter statistic every 100 batches.
- \--test_all_data_in_one_period=1: test all data in every testing. - \--test_all_data_in_one_period=1: test all data in every testing.
After training, the models will be saved in directory `output`. After training, the models will be saved in directory `output`.
### Run testing ### Run testing
The script for testing is `test.sh`, user just need to execute: The script for testing is `test.sh`, user just need to execute:
```bash ```bash
./test.sh ./test.sh
``` ```
The main part in `tesh.sh` The main part in `tesh.sh`
``` ```
paddle train \ paddle train \
--config=./db_lstm.py \ --config=./db_lstm.py \
--model_list=$model_list \ --model_list=$model_list \
--job=test \ --job=test \
--config_args=is_test=1 \ --config_args=is_test=1 \
``` ```
- \--config=./db_lstm.py: network config file - \--config=./db_lstm.py: network config file
- \--model_list=$model_list.list: model list file - \--model_list=$model_list.list: model list file
- \--job=test: indicate the test job - \--job=test: indicate the test job
- \--config_args=is_test=1: flag to indicate test - \--config_args=is_test=1: flag to indicate test
### Run prediction ### Run prediction
The script for prediction is `predict.sh`, user just need to execute: The script for prediction is `predict.sh`, user just need to execute:
```bash ```bash
./predict.sh ./predict.sh
``` ```
In `predict.sh`, user should offer the network config file, model path, label file, word dictionary file, feature file In `predict.sh`, user should offer the network config file, model path, label file, word dictionary file, feature file
``` ```
python predict.py python predict.py
-c $config_file -c $config_file
-w $model_path -w $model_path
-l $label_file -l $label_file
-d $dict_file -d $dict_file
-i $input_file -i $input_file
``` ```
`predict.py` is the main executable python script, which includes functions: load model, load data, data prediction. The network model will output the probability distribution of labels. In the demo, we take the label with maximum probability as result. User can also implement the beam search or viterbi decoding upon the probability distribution matrix. `predict.py` is the main executable python script, which includes functions: load model, load data, data prediction. The network model will output the probability distribution of labels. In the demo, we take the label with maximum probability as result. User can also implement the beam search or viterbi decoding upon the probability distribution matrix.
After prediction, the result is saved in `predict.res`. After prediction, the result is saved in `predict.res`.
## Reference ## Reference
[1] Martha Palmer, Dan Gildea, and Paul Kingsbury. The Proposition Bank: An Annotated Corpus of Semantic Roles , Computational Linguistics, 31(1), 2005. [1] Martha Palmer, Dan Gildea, and Paul Kingsbury. The Proposition Bank: An Annotated Corpus of Semantic Roles , Computational Linguistics, 31(1), 2005.
[2] Zhou, Jie, and Wei Xu. "End-to-end learning of semantic role labeling using recurrent neural networks." Proceedings of the Annual Meeting of the Association for Computational Linguistics. 2015. [2] Zhou, Jie, and Wei Xu. "End-to-end learning of semantic role labeling using recurrent neural networks." Proceedings of the Annual Meeting of the Association for Computational Linguistics. 2015.
...@@ -8,7 +8,7 @@ User Guide ...@@ -8,7 +8,7 @@ User Guide
* [Build and Installation](build/index.rst) * [Build and Installation](build/index.rst)
* [Contribute Code](build/contribute_to_paddle.md) * [Contribute Code](build/contribute_to_paddle.md)
* [User Interface](ui/index.md) * [User Interface](ui/index.md)
* [Model Config Interface](ui/api/trainer_config_helpers/index.md) * [Model Config Interface](ui/api/trainer_config_helpers/index.rst)
* [Example and Demo](demo/index.md) * [Example and Demo](demo/index.md)
* [Cluster Train](cluster/index.md) * [Cluster Train](cluster/index.md)
......
...@@ -98,4 +98,3 @@ There, you have recovered the underlying pattern between `X` and `Y` only from o ...@@ -98,4 +98,3 @@ There, you have recovered the underlying pattern between `X` and `Y` only from o
- <a href="../build/index.html"> Build and Installation </a> - <a href="../build/index.html"> Build and Installation </a>
- <a href="../demo/quick_start/index_en.html">Quick Start</a> - <a href="../demo/quick_start/index_en.html">Quick Start</a>
- <a href="../demo/index.html">Example and Demo</a> - <a href="../demo/index.html">Example and Demo</a>
===========
Activations
===========
BaseActivation BaseActivation
============== ==============
...@@ -102,4 +106,3 @@ STanhActivation ...@@ -102,4 +106,3 @@ STanhActivation
.. automodule:: paddle.trainer_config_helpers.activations .. automodule:: paddle.trainer_config_helpers.activations
:members: STanhActivation :members: STanhActivation
:noindex: :noindex:
Activations
===========
.. toctree::
:maxdepth: 3
activations.rst
==========
Evaluators
==========
Base Base
==== ====
.. automodule:: paddle.trainer_config_helpers.evaluators .. automodule:: paddle.trainer_config_helpers.evaluators
......
Evaluators
==========
.. toctree::
:maxdepth: 3
evaluators.rst
# Model Config Interface
* [Optimizer](optimizers_index.rst)
* [Data Source](data_sources.rst)
* [Layers](layers_index.rst)
* [Activations](activations_index.rst)
* [Poolings](poolings_index.rst)
* [Networks](networks_index.rst)
* [Evaluators](evaluators_index.rst)
* [Parameter and Extra Layer Attribute](attrs.rst)
Model Config Interface
======================
.. toctree::
:maxdepth: 1
optimizers.rst
data_sources.rst
layers.rst
activations.rst
poolings.rst
networks.rst
evaluators.rst
attrs.rst
======
Layers
======
Base Base
====== ======
...@@ -47,7 +51,7 @@ conv_operator ...@@ -47,7 +51,7 @@ conv_operator
:noindex: :noindex:
conv_projection conv_projection
------------- ---------------
.. automodule:: paddle.trainer_config_helpers.layers .. automodule:: paddle.trainer_config_helpers.layers
:members: conv_projection :members: conv_projection
:noindex: :noindex:
...@@ -187,6 +191,12 @@ embedding_layer ...@@ -187,6 +191,12 @@ embedding_layer
:members: embedding_layer :members: embedding_layer
:noindex: :noindex:
scaling_projection
-----------------
.. automodule:: paddle.trainer_config_helpers.layers
:members: scaling_projection
:noindex:
dotmul_projection dotmul_projection
----------------- -----------------
.. automodule:: paddle.trainer_config_helpers.layers .. automodule:: paddle.trainer_config_helpers.layers
......
Layers
======
.. toctree::
:maxdepth: 3
layers.rst
========
Networks
========
The networks module contains pieces of neural network that combine multiple layers.
NLP NLP
=== ===
...@@ -111,4 +117,3 @@ outputs ...@@ -111,4 +117,3 @@ outputs
.. automodule:: paddle.trainer_config_helpers.networks .. automodule:: paddle.trainer_config_helpers.networks
:members: outputs :members: outputs
:noindex: :noindex:
Networks
========
The networks module contains pieces of neural network that combine multiple layers.
.. toctree::
:maxdepth: 3
networks.rst
==========
Optimizers
==========
BaseSGDOptimizer BaseSGDOptimizer
================ ================
.. automodule:: paddle.trainer_config_helpers.optimizers .. automodule:: paddle.trainer_config_helpers.optimizers
...@@ -51,4 +55,3 @@ settings ...@@ -51,4 +55,3 @@ settings
.. automodule:: paddle.trainer_config_helpers.optimizers .. automodule:: paddle.trainer_config_helpers.optimizers
:members: settings :members: settings
:noindex: :noindex:
Optimizers
==========
.. toctree::
:maxdepth: 3
optimizers.rst
========
Poolings
========
BasePoolingType BasePoolingType
=============== ===============
.. automodule:: paddle.trainer_config_helpers.poolings .. automodule:: paddle.trainer_config_helpers.poolings
...@@ -27,4 +31,3 @@ SquareRootNPooling ...@@ -27,4 +31,3 @@ SquareRootNPooling
.. automodule:: paddle.trainer_config_helpers.poolings .. automodule:: paddle.trainer_config_helpers.poolings
:members: SquareRootNPooling :members: SquareRootNPooling
:noindex: :noindex:
Poolings
========
These pooling types are used for sequence input, not for images.
.. toctree::
:maxdepth: 3
poolings.rst
# 支持双层序列作为输入的Layer # 支持双层序列作为输入的Layer
## 概述 ## 概述
在自然语言处理任务中,序列是一种常见的数据类型。一个独立的词语,可以看作是一个非序列输入,或者,我们称之为一个0层的序列;由词语构成的句子,是一个单层序列;若干个句子构成一个段落,是一个双层的序列。 在自然语言处理任务中,序列是一种常见的数据类型。一个独立的词语,可以看作是一个非序列输入,或者,我们称之为一个0层的序列;由词语构成的句子,是一个单层序列;若干个句子构成一个段落,是一个双层的序列。
双层序列是一个嵌套的序列,它的每一个元素,又是一个单层的序列。这是一种非常灵活的数据组织方式,帮助我们构造一些复杂的输入信息。 双层序列是一个嵌套的序列,它的每一个元素,又是一个单层的序列。这是一种非常灵活的数据组织方式,帮助我们构造一些复杂的输入信息。
我们可以按照如下层次定义非序列,单层序列,以及双层序列。 我们可以按照如下层次定义非序列,单层序列,以及双层序列。
+ 0层序列:一个独立的元素,类型可以是PaddlePaddle支持的任意输入数据类型 + 0层序列:一个独立的元素,类型可以是PaddlePaddle支持的任意输入数据类型
+ 单层序列:排成一列的多个元素,每个元素是一个0层序列,元素之间的顺序是重要的输入信息 + 单层序列:排成一列的多个元素,每个元素是一个0层序列,元素之间的顺序是重要的输入信息
+ 双层序列:排成一列的多个元素,每个元素是一个单层序列,称之为双层序列的一个子序列(subseq),subseq的每个元素是一个0层序列 + 双层序列:排成一列的多个元素,每个元素是一个单层序列,称之为双层序列的一个子序列(subseq),subseq的每个元素是一个0层序列
在 PaddlePaddle中,下面这些Layer能够接受双层序列作为输入,完成相应的计算。 在 PaddlePaddle中,下面这些Layer能够接受双层序列作为输入,完成相应的计算。
## pooling_layer ## pooling_layer
pooling_layer的使用示例如下,详细见<a href = "../../../doc/ui/api/trainer_config_helpers/layers.html#pooling-layer">配置API</a> pooling_layer的使用示例如下,详细见<a href = "../../../doc/ui/api/trainer_config_helpers/layers.html#pooling-layer">配置API</a>
```python ```python
seq_pool = pooling_layer(input=layer, seq_pool = pooling_layer(input=layer,
pooling_type=AvgPooling(), pooling_type=AvgPooling(),
agg_level=AggregateLevel.EACH_SEQUENCE) agg_level=AggregateLevel.EACH_SEQUENCE)
``` ```
- `pooling_type` 目前支持两种,分别是:MaxPooling()和AvgPooling()。 - `pooling_type` 目前支持两种,分别是:MaxPooling()和AvgPooling()。
- `agg_level=AggregateLevel.TIMESTEP`时(默认值): - `agg_level=AggregateLevel.TIMESTEP`时(默认值):
- 作用:双层序列经过运算变成一个0层序列,或单层序列经过运算变成一个0层序列 - 作用:双层序列经过运算变成一个0层序列,或单层序列经过运算变成一个0层序列
- 输入:一个双层序列,或一个单层序列 - 输入:一个双层序列,或一个单层序列
- 输出:一个0层序列,即整个输入序列(单层或双层)的平均值(或最大值) - 输出:一个0层序列,即整个输入序列(单层或双层)的平均值(或最大值)
- `agg_level=AggregateLevel.EACH_SEQUENCE`时: - `agg_level=AggregateLevel.EACH_SEQUENCE`时:
- 作用:一个双层序列经过运算变成一个单层序列 - 作用:一个双层序列经过运算变成一个单层序列
- 输入:必须是一个双层序列 - 输入:必须是一个双层序列
- 输出:一个单层序列,序列的每个元素是原来双层序列每个subseq元素的平均值(或最大值) - 输出:一个单层序列,序列的每个元素是原来双层序列每个subseq元素的平均值(或最大值)
## last_seq 和 first_seq ## last_seq 和 first_seq
last_seq的使用示例如下(first_seq类似),详细见<a href = "../../../doc/ui/api/trainer_config_helpers/layers.html#last-seq">配置API</a> last_seq的使用示例如下(first_seq类似),详细见<a href = "../../../doc/ui/api/trainer_config_helpers/layers.html#last-seq">配置API</a>
```python ```python
last = last_seq(input=layer, last = last_seq(input=layer,
agg_level=AggregateLevel.EACH_SEQUENCE) agg_level=AggregateLevel.EACH_SEQUENCE)
``` ```
- `agg_level=AggregateLevel.TIMESTEP`时(默认值): - `agg_level=AggregateLevel.TIMESTEP`时(默认值):
- 作用:一个双层序列经过运算变成一个0层序列,或一个单层序列经过运算变成一个0层序列 - 作用:一个双层序列经过运算变成一个0层序列,或一个单层序列经过运算变成一个0层序列
- 输入:一个双层序列或一个单层序列 - 输入:一个双层序列或一个单层序列
- 输出:一个0层序列,即整个输入序列(双层或者单层)最后一个,或第一个元素。 - 输出:一个0层序列,即整个输入序列(双层或者单层)最后一个,或第一个元素。
- `agg_level=AggregateLevel.EACH_SEQUENCE`时: - `agg_level=AggregateLevel.EACH_SEQUENCE`时:
- 作用:一个双层序列经过运算变成一个单层序列 - 作用:一个双层序列经过运算变成一个单层序列
- 输入:必须是一个双层序列 - 输入:必须是一个双层序列
- 输出:一个单层序列,其中每个元素是双层序列中每个subseq最后一个(或第一个)元素。 - 输出:一个单层序列,其中每个元素是双层序列中每个subseq最后一个(或第一个)元素。
## expand_layer ## expand_layer
expand_layer的使用示例如下,详细见<a href = "../../../doc/ui/api/trainer_config_helpers/layers.html#expand-layer">配置API</a> expand_layer的使用示例如下,详细见<a href = "../../../doc/ui/api/trainer_config_helpers/layers.html#expand-layer">配置API</a>
```python ```python
expand = expand_layer(input=layer1, expand = expand_layer(input=layer1,
expand_as=layer2, expand_as=layer2,
expand_level=ExpandLevel.FROM_TIMESTEP) expand_level=ExpandLevel.FROM_TIMESTEP)
``` ```
- `expand_level=ExpandLevel.FROM_TIMESTEP`时(默认值): - `expand_level=ExpandLevel.FROM_TIMESTEP`时(默认值):
- 作用:一个0层序列经过运算扩展成一个单层序列,或者一个双层序列 - 作用:一个0层序列经过运算扩展成一个单层序列,或者一个双层序列
- 输入:layer1必须是一个0层序列,是待扩展的数据;layer2可以是一个单层序列,或者是一个双层序列,提供扩展的长度信息 - 输入:layer1必须是一个0层序列,是待扩展的数据;layer2可以是一个单层序列,或者是一个双层序列,提供扩展的长度信息
- 输出:一个单层序列,或一个双层序列,输出序列的类型(双层序列,或单层序列)和序列中含有元素的数目同 layer2一致。若输出是单层序列,单层序列的每个元素(0层序列),都是对layer1元素的拷贝;若输出是双层序列,双层序列每个subseq中每个元素(0层序列),都是对layer1元素的拷贝 - 输出:一个单层序列,或一个双层序列,输出序列的类型(双层序列,或单层序列)和序列中含有元素的数目同 layer2一致。若输出是单层序列,单层序列的每个元素(0层序列),都是对layer1元素的拷贝;若输出是双层序列,双层序列每个subseq中每个元素(0层序列),都是对layer1元素的拷贝
- `expand_level=ExpandLevel.FROM_SEQUENCE`时: - `expand_level=ExpandLevel.FROM_SEQUENCE`时:
- 作用:一个单层序列经过运算扩展成一个双层序列 - 作用:一个单层序列经过运算扩展成一个双层序列
- 输入:layer1必须是一个单层序列,是待扩展的数据;layer2必须是一个双层序列,提供扩展的长度信息 - 输入:layer1必须是一个单层序列,是待扩展的数据;layer2必须是一个双层序列,提供扩展的长度信息
- 输出:一个双层序列,序列中含有元素的数目同layer2一致。要求单层序列含有元素的数目(0层序列),和双层序列含有subseq 的数目一致。单层序列第i个元素(0层序列),被扩展为一个单层序列,构成了输出双层序列的第i个subseq。 - 输出:一个双层序列,序列中含有元素的数目同layer2一致。要求单层序列含有元素的数目(0层序列),和双层序列含有subseq 的数目一致。单层序列第i个元素(0层序列),被扩展为一个单层序列,构成了输出双层序列的第i个subseq。
\ No newline at end of file
...@@ -93,4 +93,4 @@ memory只能在`recurrent_group`中定义和使用。memory不能独立存在, ...@@ -93,4 +93,4 @@ memory只能在`recurrent_group`中定义和使用。memory不能独立存在,
使用`beam_search`需要遵循以下约定: 使用`beam_search`需要遵循以下约定:
- 单层RNN:从一个word生成下一个word。 - 单层RNN:从一个word生成下一个word。
- 双层RNN:即把单层RNN生成后的subseq给拼接成一个新的双层seq。从语义上看,也不存在一个subseq直接生成下一个subseq的情况。 - 双层RNN:即把单层RNN生成后的subseq给拼接成一个新的双层seq。从语义上看,也不存在一个subseq直接生成下一个subseq的情况。
\ No newline at end of file
...@@ -8,4 +8,4 @@ PaddlePaddle 0.8.0b1, compiled with ...@@ -8,4 +8,4 @@ PaddlePaddle 0.8.0b1, compiled with
with_gflags: ON with_gflags: ON
with_metric_learning: with_metric_learning:
with_timer: OFF with_timer: OFF
with_predict_sdk: with_predict_sdk:
\ No newline at end of file
...@@ -4,7 +4,7 @@ PaddlePaddle 基本使用概念 ...@@ -4,7 +4,7 @@ PaddlePaddle 基本使用概念
PaddlePaddle是一个神经网络学习框架。其单机进程为 :code:`paddle train`。 单机的所有设备使用,均在单机进程内调度完成。 而多机辅助进程 :code:`paddle pserver` 负责联合多个单机进程进行通信,进而充分利用集群的计算资源。 PaddlePaddle同时以 :code:`swig api` 的形式,提供训练结果模型预测的方法和自定义训练流程。 PaddlePaddle是一个神经网络学习框架。其单机进程为 :code:`paddle train`。 单机的所有设备使用,均在单机进程内调度完成。 而多机辅助进程 :code:`paddle pserver` 负责联合多个单机进程进行通信,进而充分利用集群的计算资源。 PaddlePaddle同时以 :code:`swig api` 的形式,提供训练结果模型预测的方法和自定义训练流程。
下面我们会分别介绍主要进程 :code:`paddle train` 中的一些概念。这些概念会对如何使用PaddlePaddle有一定的帮助。 了解这些概念的前提是,读者已经了解 `基本的神经网络/机器学习原理和概念 <nn.rst>`_ 。同时,如果想要了解PaddlePaddle实现中的一些概念,请参考 `PaddlePaddle 编程中的基本概念 <program_concepts.rst>`_ 。 下面我们会分别介绍主要进程 :code:`paddle train` 中的一些概念。这些概念会对如何使用PaddlePaddle有一定的帮助。 了解这些概念的前提是,读者已经了解 `基本的神经网络/机器学习原理和概念 <nn.html>`_ 。同时,如果想要了解PaddlePaddle实现中的一些概念,请参考 `PaddlePaddle 编程中的基本概念 <program_concepts.html>`_ 。
.. contents:: .. contents::
...@@ -184,8 +184,8 @@ PaddlePaddle多机使用的经典方法是通过 :code:`Parameter Server` 来对 ...@@ -184,8 +184,8 @@ PaddlePaddle多机使用的经典方法是通过 :code:`Parameter Server` 来对
详细的说明可以参考,使用 `集群训练Paddle`_ 。 详细的说明可以参考,使用 `集群训练Paddle`_ 。
.. _PyDataProvider: ../ui/data_provider/pydataprovider2.rst .. _PyDataProvider: ../ui/data_provider/pydataprovider2.html
.. _settings: ../../doc/ui/api/trainer_config_helpers/optimizers.rst .. _settings: ../../doc/ui/api/trainer_config_helpers/optimizers.html#settings
.. _mixed_layer: ../../doc/ui/api/trainer_config_helpers/layers.rst .. _mixed_layer: ../../doc/ui/api/trainer_config_helpers/layers.html#mixed-layer
.. _masking-gpu: http://www.acceleware.com/blog/cudavisibledevices-masking-gpus .. _masking-gpu: http://www.acceleware.com/blog/cudavisibledevices-masking-gpus
.. _集群训练Paddle: ../cluster/index.rst .. _集群训练Paddle: ../cluster/index.html
...@@ -3,4 +3,4 @@ def process(settings, filename): ...@@ -3,4 +3,4 @@ def process(settings, filename):
os.system('shuf %s > %s.shuf' % (filename, filename)) # shuffle before. os.system('shuf %s > %s.shuf' % (filename, filename)) # shuffle before.
with open('%s.shuf' % filename, 'r') as f: with open('%s.shuf' % filename, 'r') as f:
for line in f: for line in f:
yield get_sample_from_line(line) yield get_sample_from_line(line)
\ No newline at end of file
...@@ -117,4 +117,4 @@ set_port() ...@@ -117,4 +117,4 @@ set_port()
fi fi
done done
} }
\ No newline at end of file
...@@ -17,5 +17,3 @@ endif() ...@@ -17,5 +17,3 @@ endif()
if(WITH_SWIG_PY) if(WITH_SWIG_PY)
add_subdirectory(api) add_subdirectory(api)
endif() endif()
...@@ -65,4 +65,3 @@ struct ArgumentsPrivate { ...@@ -65,4 +65,3 @@ struct ArgumentsPrivate {
return *(std::shared_ptr<T>*)(rawPtr); return *(std::shared_ptr<T>*)(rawPtr);
} }
}; };
add_test(NAME test_swig_api add_test(NAME test_swig_api
COMMAND bash ${PROJ_ROOT}/paddle/api/test/run_tests.sh) COMMAND bash ${PROJ_ROOT}/paddle/api/test/run_tests.sh)
\ No newline at end of file
...@@ -69,8 +69,8 @@ class TestMatrix(unittest.TestCase): ...@@ -69,8 +69,8 @@ class TestMatrix(unittest.TestCase):
def test_numpy(self): def test_numpy(self):
numpy_mat = np.matrix([[1, 2], [3, 4], [5, 6]], dtype="float32") numpy_mat = np.matrix([[1, 2], [3, 4], [5, 6]], dtype="float32")
m = swig_paddle.Matrix.createCpuDenseFromNumpy(numpy_mat) m = swig_paddle.Matrix.createCpuDenseFromNumpy(numpy_mat)
self.assertEqual( self.assertEqual((int(m.getHeight()), int(m.getWidth())),
(int(m.getHeight()), int(m.getWidth())), numpy_mat.shape) numpy_mat.shape)
# the numpy matrix and paddle matrix shared the same memory. # the numpy matrix and paddle matrix shared the same memory.
numpy_mat[0, 1] = 342.23 numpy_mat[0, 1] = 342.23
......
...@@ -254,4 +254,3 @@ extern __thread cudaStream_t default_stream; ...@@ -254,4 +254,3 @@ extern __thread cudaStream_t default_stream;
#endif /* __NVCC__ */ #endif /* __NVCC__ */
#endif /* HL_BASE_H_ */ #endif /* HL_BASE_H_ */
...@@ -199,4 +199,3 @@ inline void hl_batch_norm_backward(hl_tensor_descriptor inputDesc, ...@@ -199,4 +199,3 @@ inline void hl_batch_norm_backward(hl_tensor_descriptor inputDesc,
real *savedInvVar) {} real *savedInvVar) {}
#endif // HL_CUDA_CUDNN_STUB_H_ #endif // HL_CUDA_CUDNN_STUB_H_
...@@ -718,4 +718,3 @@ void sincos256_ps(v8sf x, v8sf *s, v8sf *c) { ...@@ -718,4 +718,3 @@ void sincos256_ps(v8sf x, v8sf *s, v8sf *c) {
*s = _mm256_xor_ps(xmm1, sign_bit_sin); *s = _mm256_xor_ps(xmm1, sign_bit_sin);
*c = _mm256_xor_ps(xmm2, sign_bit_cos); *c = _mm256_xor_ps(xmm2, sign_bit_cos);
} }
...@@ -605,7 +605,7 @@ public: ...@@ -605,7 +605,7 @@ public:
int batchSize = input->getHeight(); int batchSize = input->getHeight();
int size = 1; int size = 1;
resizeOutput(batchSize, size); resizeOutput(batchSize, size);
output_.value->sumRows(*input); output_.value->sumRows(*input, /* scaleSum= */1, /* scaleDest= */0);
} }
virtual void backward(const UpdateCallback& callback = nullptr) { virtual void backward(const UpdateCallback& callback = nullptr) {
......
...@@ -52,7 +52,9 @@ void FullMatrixProjection::backward(const UpdateCallback& callback) { ...@@ -52,7 +52,9 @@ void FullMatrixProjection::backward(const UpdateCallback& callback) {
} }
hl_set_sync_flag(syncFlag); hl_set_sync_flag(syncFlag);
parameter_->incUpdate(callback); if (weight_->getWGrad()) {
parameter_->incUpdate(callback);
}
} }
} // namespace paddle } // namespace paddle
...@@ -48,4 +48,3 @@ public: ...@@ -48,4 +48,3 @@ public:
}; };
} // namespace paddle } // namespace paddle
/* Copyright (c) 2016 Baidu, Inc. 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 "Projection.h"
namespace paddle {
class ScalingProjection : public Projection {
public:
ScalingProjection(const ProjectionConfig& config,
const ParameterPtr& parameter, bool useGpu)
: Projection(config, parameter, useGpu) {
CHECK_EQ(parameter->getSize(), 1UL);
weight_.reset(new Weight(1, 1, parameter));
}
void forward() {
CHECK(in_->value);
out_->value->add(*in_->value, weight_->getW()->getElement(0, 0));
}
void backward(const UpdateCallback& callback) {
if (weight_->getWGrad()) {
auto sum = Matrix::create(in_->value->getHeight(), 1, false, useGpu_);
sum->sumOfProducts(*in_->value, *out_->grad,
/* scaleSum= */1, /* scaleDest= */0);
weight_->getWGrad()->sumCols(*sum,
/* scaleSum= */1, /* scaleDest= */1);
parameter_->incUpdate(callback);
}
if (in_->grad) {
in_->grad->add(*out_->grad, weight_->getW()->getElement(0, 0));
}
}
protected:
std::unique_ptr<Weight> weight_;
};
REGISTER_PROJECTION(scaling, ScalingProjection);
} // namespace paddle
...@@ -135,6 +135,17 @@ TEST(Projection, identity) { ...@@ -135,6 +135,17 @@ TEST(Projection, identity) {
} }
} }
TEST(Projection, scaling) {
ProjectionConfig conf;
conf.set_type("scaling");
conf.set_input_size(10);
conf.set_output_size(10);
for (auto useGpu : {false}) {
testProjectionGrad(conf, INPUT_DATA, /* parameterSize */ 1,
/* batchSize */ 100, useGpu);
}
}
#ifndef PADDLE_ONLY_CPU #ifndef PADDLE_ONLY_CPU
TEST(Projection, conv) { TEST(Projection, conv) {
const int NUM_FILTERS = 16; const int NUM_FILTERS = 16;
......
...@@ -1451,6 +1451,8 @@ int BaseMatrixT<real>::applyRow(Agg agg, BaseMatrixT& b) { ...@@ -1451,6 +1451,8 @@ int BaseMatrixT<real>::applyRow(Agg agg, BaseMatrixT& b) {
MatrixOffset offset(0, 0, 0, 0, 0, 0); MatrixOffset offset(0, 0, 0, 0, 0, 0);
int numRows = b.height_; int numRows = b.height_;
int numCols = b.width_; int numCols = b.width_;
CHECK_EQ(height_, numRows);
CHECK_EQ(width_, 1UL);
aggregate(agg, base::unary::identity(), base::binary::second(), b, numRows, aggregate(agg, base::unary::identity(), base::binary::second(), b, numRows,
numCols, offset, false_type(), true_type() /*aAsColVector*/); numCols, offset, false_type(), true_type() /*aAsColVector*/);
...@@ -1463,18 +1465,69 @@ int BaseMatrixT<real>::applyRow(Agg agg, Saver sv, BaseMatrixT& b) { ...@@ -1463,18 +1465,69 @@ int BaseMatrixT<real>::applyRow(Agg agg, Saver sv, BaseMatrixT& b) {
MatrixOffset offset(0, 0, 0, 0, 0, 0); MatrixOffset offset(0, 0, 0, 0, 0, 0);
int numRows = b.height_; int numRows = b.height_;
int numCols = b.width_; int numCols = b.width_;
CHECK_EQ(height_, numRows);
CHECK_EQ(width_, 1UL);
aggregate(agg, base::unary::identity(), sv, b, numRows, numCols, offset, aggregate(agg, base::unary::identity(), sv, b, numRows, numCols, offset,
false_type(), true_type() /*aAsColVector*/); false_type(), true_type() /*aAsColVector*/);
return 0; return 0;
} }
template<>
template <class Agg>
int BaseMatrixT<real>::applyRow(
Agg agg, real scaleDest, real scaleAgg, BaseMatrixT& b) {
if (scaleDest != 0) {
applyRow(agg, base::binary::add2(scaleDest, scaleAgg), b);
} else {
applyRow(agg, base::binary::second(), b);
if (scaleAgg != 1) {
mulScalar(scaleAgg);
}
}
return 0;
}
template<>
template <class Agg, class Op, class Saver>
int BaseMatrixT<real>::applyRow(Agg agg, Op op, Saver sv,
BaseMatrixT& b, BaseMatrixT& c) {
MatrixOffset offset(0, 0, 0, 0, 0, 0);
int numRows = b.height_;
int numCols = b.width_;
CHECK_EQ(height_, numRows);
CHECK_EQ(width_, 1UL);
CHECK_EQ(c.height_, numRows);
CHECK_EQ(c.width_, numCols);
aggregate(agg, op, sv,
b, c, numRows, numCols, offset,
false_type(), true_type() /*aAsColVector*/);
return 0;
}
template<>
template <class Agg, class Op>
int BaseMatrixT<real>::applyRow(Agg agg, Op op, real scaleDest, real scaleAgg,
BaseMatrixT& b, BaseMatrixT& c) {
if (scaleDest != 0) {
applyRow(agg, op, base::binary::add2(scaleDest, scaleAgg), b, c);
} else {
applyRow(agg, op, base::binary::second(), b, c);
if (scaleAgg != 1) {
mulScalar(scaleAgg);
}
}
return 0;
}
template<> template<>
template <class Agg> template <class Agg>
int BaseMatrixT<real>::applyCol(Agg agg, BaseMatrixT& b) { int BaseMatrixT<real>::applyCol(Agg agg, BaseMatrixT& b) {
MatrixOffset offset(0, 0, 0, 0, 0, 0); MatrixOffset offset(0, 0, 0, 0, 0, 0);
int numRows = b.height_; int numRows = b.height_;
int numCols = b.width_; int numCols = b.width_;
CHECK_EQ(width_, numCols);
CHECK_EQ(height_, 1UL);
aggregate(agg, base::unary::identity(), base::binary::second(), b, numRows, aggregate(agg, base::unary::identity(), base::binary::second(), b, numRows,
numCols, offset, true_type() /*aAsRowVector*/, false_type()); numCols, offset, true_type() /*aAsRowVector*/, false_type());
...@@ -1487,6 +1540,8 @@ int BaseMatrixT<real>::applyCol(Agg agg, Saver sv, BaseMatrixT& b) { ...@@ -1487,6 +1540,8 @@ int BaseMatrixT<real>::applyCol(Agg agg, Saver sv, BaseMatrixT& b) {
MatrixOffset offset(0, 0, 0, 0, 0, 0); MatrixOffset offset(0, 0, 0, 0, 0, 0);
int numRows = b.height_; int numRows = b.height_;
int numCols = b.width_; int numCols = b.width_;
CHECK_EQ(width_, numCols);
CHECK_EQ(height_, 1UL);
aggregate(agg, base::unary::identity(), sv, b, numRows, numCols, offset, aggregate(agg, base::unary::identity(), sv, b, numRows, numCols, offset,
true_type() /*aAsRowVector*/, false_type()); true_type() /*aAsRowVector*/, false_type());
...@@ -1494,8 +1549,23 @@ int BaseMatrixT<real>::applyCol(Agg agg, Saver sv, BaseMatrixT& b) { ...@@ -1494,8 +1549,23 @@ int BaseMatrixT<real>::applyCol(Agg agg, Saver sv, BaseMatrixT& b) {
} }
template<> template<>
void BaseMatrixT<real>::sumRows(BaseMatrixT& b) { template <class Agg>
applyRow(aggregate::sum(), b); int BaseMatrixT<real>::applyCol(
Agg agg, real scaleDest, real scaleAgg, BaseMatrixT& b) {
if (scaleDest != 0) {
applyCol(agg, base::binary::add2(scaleDest, scaleAgg), b);
} else {
applyCol(agg, base::binary::second(), b);
if (scaleAgg != 1) {
mulScalar(scaleAgg);
}
}
return 0;
}
template<>
void BaseMatrixT<real>::sumRows(BaseMatrixT& b, real scaleSum, real scaleDest) {
applyRow(aggregate::sum(), scaleDest, scaleSum, b);
} }
template<> template<>
...@@ -1524,18 +1594,22 @@ void BaseMatrixT<real>::minCols(BaseMatrixT& b) { ...@@ -1524,18 +1594,22 @@ void BaseMatrixT<real>::minCols(BaseMatrixT& b) {
} }
template<> template<>
void BaseMatrixT<real>::sumCols(BaseMatrixT& b, real scale) { void BaseMatrixT<real>::sumCols(BaseMatrixT& b, real scaleSum, real scaleDest) {
applyCol(aggregate::sum(), base::binary::add2(1.0, scale), b); applyCol(aggregate::sum(), scaleDest, scaleSum, b);
} }
template<> template<>
void BaseMatrixT<real>::sumOfSquares(BaseMatrixT& b, BaseMatrixT& c) { void BaseMatrixT<real>::sumOfSquaredDiffs(
int numRows = b.height_; BaseMatrixT& b, BaseMatrixT& c, real scaleSum, real scaleDest) {
int numCols = b.width_; applyRow(aggregate::sum(), base::binary::squaredDiff(),
MatrixOffset offset(0, 0, 0, 0, 0, 0); scaleDest, scaleSum, b, c);
aggregate(aggregate::sum(), base::binary::squaredDiff(), base::binary::add(), }
b, c, numRows, numCols, offset, false_type(),
true_type() /*aAsColVector*/); template<>
void BaseMatrixT<real>::sumOfProducts(
BaseMatrixT& b, BaseMatrixT& c, real scaleSum, real scaleDest) {
applyRow(aggregate::sum(), base::binary::mul(),
scaleDest, scaleSum, b, c);
} }
template class BaseMatrixT<real>; template class BaseMatrixT<real>;
......
...@@ -305,6 +305,23 @@ public: ...@@ -305,6 +305,23 @@ public:
template <class Agg> template <class Agg>
int applyRow(Agg agg, BaseMatrixT& b); int applyRow(Agg agg, BaseMatrixT& b);
/**
* a aggregate expression that apply each row of matrix b.
*
* @code
* for each row i & 0 <= j < b.width_, do:
* dst = agg(op(b[i*ldb + j], c[i*ldc + j])
* this[i] = sv(this[i], dst)
* @endcode
*/
template <class Agg, class Op, class Saver>
int applyRow(Agg agg, Op op, Saver sv, BaseMatrixT& b, BaseMatrixT& c);
// Same as the above with the special handing of sv=add2(scaleDest, scaleAgg)
template <class Agg, class Op>
int applyRow(Agg agg, Op op, real scaleDest, real scaleAgg,
BaseMatrixT& b, BaseMatrixT& c);
/** /**
* a aggregate expression that apply each row of matrix b. * a aggregate expression that apply each row of matrix b.
* *
...@@ -317,6 +334,10 @@ public: ...@@ -317,6 +334,10 @@ public:
template <class Agg, class Saver> template <class Agg, class Saver>
int applyRow(Agg agg, Saver sv, BaseMatrixT& b); int applyRow(Agg agg, Saver sv, BaseMatrixT& b);
// Same as the above with the special handing of sv=add2(scaleDest, scaleAgg)
template <class Agg>
int applyRow(Agg agg, real scaleDest, real scaleAgg, BaseMatrixT& b);
/** /**
* a aggregate expression that apply each column of matrix b. * a aggregate expression that apply each column of matrix b.
* *
...@@ -340,6 +361,10 @@ public: ...@@ -340,6 +361,10 @@ public:
template <class Agg, class Saver> template <class Agg, class Saver>
int applyCol(Agg agg, Saver sv, BaseMatrixT& b); int applyCol(Agg agg, Saver sv, BaseMatrixT& b);
// Same as the above with the special handing of sv=add2(scaleDest, scaleAgg)
template <class Agg>
int applyCol(Agg agg, real scaleDest, real scaleAgg, BaseMatrixT& b);
bool useGpu() const { return useGpu_; } bool useGpu() const { return useGpu_; }
const T* rowBuf(size_t row) const { return data_ + width_ * row; } const T* rowBuf(size_t row) const { return data_ + width_ * row; }
...@@ -920,7 +945,9 @@ public: ...@@ -920,7 +945,9 @@ public:
void addRowScale(size_t cCol, BaseMatrixT& b, BaseMatrixT& c); void addRowScale(size_t cCol, BaseMatrixT& b, BaseMatrixT& c);
/// calculate the sum of each row of the matrix b. /// calculate the sum of each row of the matrix b.
void sumRows(BaseMatrixT& b); /// this_i = scaleDest * this_i + scaleSum * \sum_j b_{ij}
void sumRows(BaseMatrixT& b, T scaleSum, T scaleDest);
/// calculate the maximum value of each row of the matrix b. /// calculate the maximum value of each row of the matrix b.
void maxRows(BaseMatrixT& b); void maxRows(BaseMatrixT& b);
/// calculate the minimum value of each row of the matrix b. /// calculate the minimum value of each row of the matrix b.
...@@ -932,10 +959,18 @@ public: ...@@ -932,10 +959,18 @@ public:
void maxCols(BaseMatrixT& b); void maxCols(BaseMatrixT& b);
/// calculate the minimum value of each column of the matrix b. /// calculate the minimum value of each column of the matrix b.
void minCols(BaseMatrixT& b); void minCols(BaseMatrixT& b);
void sumCols(BaseMatrixT& b, T scale);
/// calculate the sum of each row of (b - c)^2. /// calculate the sum of each column of the matrix b.
void sumOfSquares(BaseMatrixT& b, BaseMatrixT& c); /// this_i = scaleDest * this_i + scaleSum * \sum_j b_{ji}
void sumCols(BaseMatrixT& b, T scaleSum, T scaleDest);
/// this_i = scaleDest * this_i + scaleSum * \sum_j (b_{ij} - c_{ij})^2
void sumOfSquaredDiffs(BaseMatrixT& b, BaseMatrixT& c,
T scaleSum, T scaleDest);
/// this_i = scaleDest * this_i + scaleSum * \sum_j b_{ij} * c_{ij}
void sumOfProducts(BaseMatrixT& b, BaseMatrixT& c,
T scaleSum, T scaleDest);
/** /**
* @code * @code
......
...@@ -80,4 +80,3 @@ void vTanh(const int n, const T* a, T* r); ...@@ -80,4 +80,3 @@ void vTanh(const int n, const T* a, T* r);
} // namespace paddle } // namespace paddle
#endif // MATHFUNCTIONS_H_ #endif // MATHFUNCTIONS_H_
...@@ -242,7 +242,7 @@ real GpuMatrix::getSum() { ...@@ -242,7 +242,7 @@ real GpuMatrix::getSum() {
void GpuMatrix::accumulateColSum(Matrix& src) { void GpuMatrix::accumulateColSum(Matrix& src) {
CHECK_EQ(getWidth(), src.getWidth()); CHECK_EQ(getWidth(), src.getWidth());
CHECK_EQ(getHeight(), (size_t)1); CHECK_EQ(getHeight(), (size_t)1);
sumCols(src, 1.0); sumCols(src, 1.0, 1.0);
} }
real GpuMatrix::getAbsSum() { real GpuMatrix::getAbsSum() {
...@@ -389,7 +389,7 @@ void GpuMatrix::collectBias(Matrix& a, real scale) { ...@@ -389,7 +389,7 @@ void GpuMatrix::collectBias(Matrix& a, real scale) {
CHECK_EQ(width_, a.getWidth()); CHECK_EQ(width_, a.getWidth());
GpuSparseMatrix* sMatPtr = dynamic_cast<GpuSparseMatrix*>(&a); GpuSparseMatrix* sMatPtr = dynamic_cast<GpuSparseMatrix*>(&a);
if (!sMatPtr) { if (!sMatPtr) {
sumCols(a, scale); sumCols(a, /* scaleSum= */scale, /* scaleDest= */1);
} else { } else {
real* data = getData(); real* data = getData();
hl_sparse_matrix_s A_d = sMatPtr->sMatrix_.get(); hl_sparse_matrix_s A_d = sMatPtr->sMatrix_.get();
...@@ -589,7 +589,7 @@ void GpuMatrix::addToRows(Matrix& table, IVector& ids) { ...@@ -589,7 +589,7 @@ void GpuMatrix::addToRows(Matrix& table, IVector& ids) {
void GpuMatrix::colMerge(Matrix& src) { void GpuMatrix::colMerge(Matrix& src) {
CHECK(src.height_ == height_); CHECK(src.height_ == height_);
if (!trans_ && !src.trans_) { if (!trans_ && !src.trans_) {
sumRows(src); sumRows(src, /* scaleSum= */1, /* scaleDest= */0);
} else { } else {
LOG(FATAL) << "Is not supported"; LOG(FATAL) << "Is not supported";
} }
...@@ -599,7 +599,7 @@ void GpuMatrix::rowSum(Matrix& sum) { ...@@ -599,7 +599,7 @@ void GpuMatrix::rowSum(Matrix& sum) {
CHECK_EQ(sum.getHeight(), getHeight()); CHECK_EQ(sum.getHeight(), getHeight());
CHECK_EQ(sum.getWidth(), (size_t)1); CHECK_EQ(sum.getWidth(), (size_t)1);
sum.sumRows(*this); sum.sumRows(*this, /* scaleSum= */1, /* scaleDest= */0);
} }
void GpuMatrix::rowMax(Matrix& max) { void GpuMatrix::rowMax(Matrix& max) {
...@@ -790,7 +790,8 @@ void GpuMatrix::sumOfSquares(Matrix& output, Matrix& label) { ...@@ -790,7 +790,8 @@ void GpuMatrix::sumOfSquares(Matrix& output, Matrix& label) {
LOG(FATAL) << "not supported: GpuSparseMatrix as label"; LOG(FATAL) << "not supported: GpuSparseMatrix as label";
} }
BaseMatrix::sumOfSquares(output, label); BaseMatrix::sumOfSquaredDiffs(output, label,
/* scaleSum= */1, /* scaleDest= */1);
} }
void GpuMatrix::sumOfSquaresBp(Matrix& outputV, Matrix& label) { void GpuMatrix::sumOfSquaresBp(Matrix& outputV, Matrix& label) {
...@@ -1501,7 +1502,7 @@ void CpuMatrix::accumulateColSum(Matrix& src) { ...@@ -1501,7 +1502,7 @@ void CpuMatrix::accumulateColSum(Matrix& src) {
CHECK_EQ(getWidth(), src.getWidth()); CHECK_EQ(getWidth(), src.getWidth());
CHECK_EQ(getHeight(), (size_t)1); CHECK_EQ(getHeight(), (size_t)1);
sumCols(src, 1.0); sumCols(src, /* scaleSum= */1, /* scaleDest= */1);
} }
real CpuMatrix::getAbsSum() { real CpuMatrix::getAbsSum() {
...@@ -2188,7 +2189,7 @@ void CpuMatrix::collectBias(Matrix& a, real scale) { ...@@ -2188,7 +2189,7 @@ void CpuMatrix::collectBias(Matrix& a, real scale) {
CHECK_EQ(width_, a.getWidth()); CHECK_EQ(width_, a.getWidth());
CpuSparseMatrix* aptr = dynamic_cast<CpuSparseMatrix*>(&a); CpuSparseMatrix* aptr = dynamic_cast<CpuSparseMatrix*>(&a);
if (!aptr) { if (!aptr) {
sumCols(a, scale); sumCols(a, /* scaleSum= */scale, /* scaleDest= */1);
} else { } else {
size_t nnz = aptr->getElementCnt(); size_t nnz = aptr->getElementCnt();
int* cols = aptr->getCols(); int* cols = aptr->getCols();
...@@ -2227,7 +2228,7 @@ void CpuMatrix::sequenceAvgForward(Matrix& a, ...@@ -2227,7 +2228,7 @@ void CpuMatrix::sequenceAvgForward(Matrix& a,
real* dst = getData(); real* dst = getData();
real* src = a.getData(); real* src = a.getData();
const int* starts = startsPos.getData(); const int* starts = startsPos.getData();
MatrixPtr outMtx = Matrix::create(1, 1, false, false); MatrixPtr outMtx = Matrix::create(nullptr, 1, width, false, false);
MatrixPtr dataMtx = Matrix::create(nullptr, 1, width, false, false); MatrixPtr dataMtx = Matrix::create(nullptr, 1, width, false, false);
for (size_t i = 0; i < height; i++) { for (size_t i = 0; i < height; i++) {
int sequenceLength = starts[i + 1] - starts[i]; int sequenceLength = starts[i + 1] - starts[i];
...@@ -2239,13 +2240,15 @@ void CpuMatrix::sequenceAvgForward(Matrix& a, ...@@ -2239,13 +2240,15 @@ void CpuMatrix::sequenceAvgForward(Matrix& a,
dataMtx->setData(src + starts[i] * width, sequenceLength, width); dataMtx->setData(src + starts[i] * width, sequenceLength, width);
if (mode == 0) { if (mode == 0) {
// plain average // plain average
outMtx->sumCols(*dataMtx, (real)1 / (real)sequenceLength); outMtx->sumCols(*dataMtx, (real)1 / (real)sequenceLength,
/* scaleDest= */1);
} else if (mode == 1) { } else if (mode == 1) {
// sum instead of average // sum instead of average
outMtx->sumCols(*dataMtx, (real)1); outMtx->sumCols(*dataMtx, /* scaleSum= */1, /* scaleDest= */1);
} else if (mode == 2) { } else if (mode == 2) {
// divide by square root of sequenceLength // divide by square root of sequenceLength
outMtx->sumCols(*dataMtx, (real)1 / std::sqrt(sequenceLength)); outMtx->sumCols(*dataMtx, (real)1 / std::sqrt(sequenceLength),
/* scaleDest= */1);
} else { } else {
LOG(FATAL) << "should not reach here"; LOG(FATAL) << "should not reach here";
} }
...@@ -2932,7 +2935,7 @@ void CpuMatrix::rowSum(Matrix& sum) { ...@@ -2932,7 +2935,7 @@ void CpuMatrix::rowSum(Matrix& sum) {
CHECK_EQ(sum.getHeight(), getHeight()); CHECK_EQ(sum.getHeight(), getHeight());
CHECK_EQ(sum.getWidth(), (size_t)1); CHECK_EQ(sum.getWidth(), (size_t)1);
sum.sumRows(*this); sum.sumRows(*this, /* scaleSum= */1, /* scaleDest= */0);
} }
void CpuMatrix::rowMaxId(IVector& maxIds) { void CpuMatrix::rowMaxId(IVector& maxIds) {
...@@ -3485,7 +3488,8 @@ void CpuMatrix::sumOfSquares(Matrix& output, Matrix& label) { ...@@ -3485,7 +3488,8 @@ void CpuMatrix::sumOfSquares(Matrix& output, Matrix& label) {
} }
} }
BaseMatrix::sumOfSquares(output, label); BaseMatrix::sumOfSquaredDiffs(output, label,
/* scaleSum= */1, /* scaleDest= */1);
} }
/* calculate the error of outputV according to label */ /* calculate the error of outputV according to label */
......
...@@ -10,4 +10,4 @@ add_style_check_target(paddle_parameter ${PARAMETERS_HEADERS}) ...@@ -10,4 +10,4 @@ add_style_check_target(paddle_parameter ${PARAMETERS_HEADERS})
add_dependencies(paddle_parameter gen_proto_cpp) add_dependencies(paddle_parameter gen_proto_cpp)
if(WITH_TESTING) if(WITH_TESTING)
add_subdirectory(tests) add_subdirectory(tests)
endif() endif()
\ No newline at end of file
add_simple_unittest(test_common) add_simple_unittest(test_common)
\ No newline at end of file
...@@ -6,4 +6,4 @@ configure_file(submit_local.sh.in ...@@ -6,4 +6,4 @@ configure_file(submit_local.sh.in
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/submit_local.sh DESTINATION bin install(FILES ${CMAKE_CURRENT_BINARY_DIR}/submit_local.sh DESTINATION bin
PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ
GROUP_EXECUTE GROUP_READ WORLD_EXECUTE WORLD_READ GROUP_EXECUTE GROUP_READ WORLD_EXECUTE WORLD_READ
RENAME paddle) RENAME paddle)
\ No newline at end of file
此差异已折叠。
...@@ -33,5 +33,3 @@ cmake .. -DWITH_GPU=ON -DWITH_SWIG_PY=ON -DWITH_AVX=OFF -DCUDNN_ROOT=/usr/ ...@@ -33,5 +33,3 @@ cmake .. -DWITH_GPU=ON -DWITH_SWIG_PY=ON -DWITH_AVX=OFF -DCUDNN_ROOT=/usr/
make -j `nproc` make -j `nproc`
cpack -D CPACK_GENERATOR='DEB' .. cpack -D CPACK_GENERATOR='DEB' ..
mv *.deb ~/dist/gpu-noavx mv *.deb ~/dist/gpu-noavx
...@@ -58,4 +58,3 @@ m4 -DPADDLE_WITH_GPU=ON -DPADDLE_IS_DEVEL=ON -DPADDLE_WITH_DEMO=ON \ ...@@ -58,4 +58,3 @@ m4 -DPADDLE_WITH_GPU=ON -DPADDLE_IS_DEVEL=ON -DPADDLE_WITH_DEMO=ON \
-DPADDLE_BASE_IMAGE=nvidia/cuda:7.5-cudnn5-devel-ubuntu14.04 \ -DPADDLE_BASE_IMAGE=nvidia/cuda:7.5-cudnn5-devel-ubuntu14.04 \
-DPADDLE_WITH_AVX=OFF \ -DPADDLE_WITH_AVX=OFF \
Dockerfile.m4 > Dockerfile.gpu-noavx-demo Dockerfile.m4 > Dockerfile.gpu-noavx-demo
...@@ -2,4 +2,3 @@ ...@@ -2,4 +2,3 @@
set -e set -e
mkdir -p ../../../build mkdir -p ../../../build
cd ../../../build cd ../../../build
...@@ -998,4 +998,3 @@ from IN B-PP ...@@ -998,4 +998,3 @@ from IN B-PP
Friday NNP B-NP Friday NNP B-NP
's POS B-NP 's POS B-NP
Tokyo NNP I-NP Tokyo NNP I-NP
...@@ -6,4 +6,4 @@ ...@@ -6,4 +6,4 @@
5 5
6 6
7 7
8 8
\ No newline at end of file
...@@ -4998,4 +4998,3 @@ However RB B-ADVP ...@@ -4998,4 +4998,3 @@ However RB B-ADVP
the DT B-NP the DT B-NP
disclosure NN I-NP disclosure NN I-NP
of IN B-PP of IN B-PP
...@@ -109,4 +109,3 @@ int main(int argc, char** argv) { ...@@ -109,4 +109,3 @@ int main(int argc, char** argv) {
} }
#endif #endif
...@@ -410,8 +410,8 @@ def RecurrentLayerGroupEnd(name): ...@@ -410,8 +410,8 @@ def RecurrentLayerGroupEnd(name):
"RecurrentLayerGroup not begin") "RecurrentLayerGroup not begin")
for pair in g_current_submodel.memories: #check exist for pair in g_current_submodel.memories: #check exist
layer = g_layer_map[pair.layer_name] layer = g_layer_map[pair.layer_name]
config_assert(layer is not None, "memory declare wrong name:%s" % config_assert(layer is not None,
pair.layer_name) "memory declare wrong name:%s" % pair.layer_name)
memory_link = g_layer_map[pair.link_name] memory_link = g_layer_map[pair.link_name]
config_assert(layer.size == memory_link.size, config_assert(layer.size == memory_link.size,
"memory declare wrong size:%d" % memory_link.size) "memory declare wrong size:%d" % memory_link.size)
...@@ -592,6 +592,20 @@ class DotMulProjection(Projection): ...@@ -592,6 +592,20 @@ class DotMulProjection(Projection):
def calc_parameter_dims(self, input_size, output_size): def calc_parameter_dims(self, input_size, output_size):
return [1, output_size] return [1, output_size]
# ScalingProjection
@config_class
class ScalingProjection(Projection):
type = 'scaling'
def calc_output_size(self, input_layer_config):
return input_layer_config.size
def calc_parameter_size(self, input_size, output_size):
return 1
def calc_parameter_dims(self, input_size, output_size):
return [1, 1]
@config_class @config_class
class TableProjection(Projection): class TableProjection(Projection):
...@@ -672,8 +686,8 @@ class ConvProjection(Projection): ...@@ -672,8 +686,8 @@ class ConvProjection(Projection):
parse_conv(conv_conf, input_layer_name, self.proj_conf.conv_conf, parse_conv(conv_conf, input_layer_name, self.proj_conf.conv_conf,
num_filters) num_filters)
# TODO: support rectangle input # TODO: support rectangle input
self.proj_conf.output_size = (self.proj_conf.conv_conf.output_x** self.proj_conf.output_size = (self.proj_conf.conv_conf.output_x
2) * num_filters **2) * num_filters
def calc_output_size(self, input_layer_config): def calc_output_size(self, input_layer_config):
return self.proj_conf.output_size return self.proj_conf.output_size
...@@ -2779,8 +2793,8 @@ class ConcatenateLayer2(LayerBase): ...@@ -2779,8 +2793,8 @@ class ConcatenateLayer2(LayerBase):
@config_layer('recurrent') @config_layer('recurrent')
class RecurrentLayer(LayerBase): class RecurrentLayer(LayerBase):
def __init__(self, name, inputs, reversed=False, bias=True, **xargs): def __init__(self, name, inputs, reversed=False, bias=True, **xargs):
super(RecurrentLayer, self).__init__(name, 'recurrent', 0, inputs, ** super(RecurrentLayer, self).__init__(name, 'recurrent', 0, inputs,
xargs) **xargs)
config_assert(len(self.inputs) == 1, 'RecurrentLayer must have 1 input') config_assert(len(self.inputs) == 1, 'RecurrentLayer must have 1 input')
input_layer = self.get_input_layer(0) input_layer = self.get_input_layer(0)
size = input_layer.size size = input_layer.size
...@@ -2862,22 +2876,22 @@ class MDLstmLayer(LayerBase): ...@@ -2862,22 +2876,22 @@ class MDLstmLayer(LayerBase):
active_state_type="sigmoid", active_state_type="sigmoid",
bias=True, bias=True,
**xargs): **xargs):
super(MDLstmLayer, self).__init__(name, 'mdlstmemory', 0, inputs, ** super(MDLstmLayer, self).__init__(name, 'mdlstmemory', 0, inputs,
xargs) **xargs)
config_assert(len(self.inputs) == 1, 'MDLstmLayer must have 1 input') config_assert(len(self.inputs) == 1, 'MDLstmLayer must have 1 input')
input_layer = self.get_input_layer(0) input_layer = self.get_input_layer(0)
dim_num = len(directions) dim_num = len(directions)
#check input_layer.size is divided by (3+dim_num) #check input_layer.size is divided by (3+dim_num)
config_assert(input_layer.size % config_assert(input_layer.size % (3 + dim_num) == 0,
(3 + dim_num) == 0, "size % (dim_num) should be 0!") "size % (dim_num) should be 0!")
size = input_layer.size / (3 + dim_num) size = input_layer.size / (3 + dim_num)
self.set_layer_size(size) self.set_layer_size(size)
self.config.active_gate_type = active_gate_type self.config.active_gate_type = active_gate_type
self.config.active_state_type = active_state_type self.config.active_state_type = active_state_type
for i in xrange(len(directions)): for i in xrange(len(directions)):
self.config.directions.append(int(directions[i])) self.config.directions.append(int(directions[i]))
self.create_input_parameter(0, size * size * self.create_input_parameter(0, size * size * (3 + dim_num),
(3 + dim_num), [size, size, 3 + dim_num]) [size, size, 3 + dim_num])
#bias includes 3 kinds of peephole, 3+dim_num+2+dim_num #bias includes 3 kinds of peephole, 3+dim_num+2+dim_num
self.create_bias_parameter(bias, size * (5 + 2 * dim_num)) self.create_bias_parameter(bias, size * (5 + 2 * dim_num))
...@@ -2915,8 +2929,8 @@ class GruStepLayer(LayerBase): ...@@ -2915,8 +2929,8 @@ class GruStepLayer(LayerBase):
active_gate_type="sigmoid", active_gate_type="sigmoid",
bias=True, bias=True,
**xargs): **xargs):
super(GruStepLayer, self).__init__(name, 'gru_step', size, inputs, ** super(GruStepLayer, self).__init__(name, 'gru_step', size, inputs,
xargs) **xargs)
config_assert(len(self.inputs) == 2, 'GruStepLayer must have 2 input') config_assert(len(self.inputs) == 2, 'GruStepLayer must have 2 input')
input_layer0 = self.get_input_layer(0) input_layer0 = self.get_input_layer(0)
input_layer1 = self.get_input_layer(1) input_layer1 = self.get_input_layer(1)
......
...@@ -65,6 +65,7 @@ __all__ = [ ...@@ -65,6 +65,7 @@ __all__ = [
'StaticInput', 'StaticInput',
'expand_layer', 'expand_layer',
'scaling_layer', 'scaling_layer',
'scaling_projection',
'power_layer', 'power_layer',
'interpolation_layer', 'interpolation_layer',
'bilinear_interp_layer', 'bilinear_interp_layer',
...@@ -458,7 +459,7 @@ def identity_projection(input, offset=None): ...@@ -458,7 +459,7 @@ def identity_projection(input, offset=None):
:type input: LayerOutput :type input: LayerOutput
:param offset: Offset, None if use default. :param offset: Offset, None if use default.
:type offset: int :type offset: int
:return: A IdentityProjection or IdentityOffsetProjection Object :return: A IdentityProjection or IdentityOffsetProjection object
:rtype: IdentityProjection or IdentityOffsetProjection :rtype: IdentityProjection or IdentityOffsetProjection
""" """
if offset is None: if offset is None:
...@@ -471,6 +472,34 @@ def identity_projection(input, offset=None): ...@@ -471,6 +472,34 @@ def identity_projection(input, offset=None):
return proj return proj
@wrap_param_attr_default()
def scaling_projection(input, param_attr=None):
"""
scaling_projection multiplies the input with a scalar parameter and add to
the output.
.. math::
out += w * in
The example usage is:
.. code-block:: python
proj = scaling_projection(input=layer)
:param input: Input Layer.
:type input: LayerOutput
:param param_attr: Parameter config, None if use default.
:type param_attr: ParameterAttribute
:return: A ScalingProjection object
:rtype: ScalingProjection
"""
proj = ScalingProjection(input_layer_name=input.name,
**param_attr.attr)
proj.origin = input
return proj
@wrap_param_attr_default() @wrap_param_attr_default()
def dotmul_projection(input, param_attr=None): def dotmul_projection(input, param_attr=None):
""" """
...@@ -1426,11 +1455,11 @@ def bilinear_interp_layer(input, ...@@ -1426,11 +1455,11 @@ def bilinear_interp_layer(input,
.. code-block:: python .. code-block:: python
bilinear = bilinear_interp_layer(input=layer1, out_size_x=64, out_size_y=64) bilinear = bilinear_interp_layer(input=layer1, out_size_x=64, out_size_y=64)
:param input: A input layer. :param input: A input layer.
:type input: LayerOutput. :type input: LayerOutput.
:param out_size_x: bilinear interpolation output width. :param out_size_x: bilinear interpolation output width.
:type out_size_x: int|None :type out_size_x: int|None
:param out_size_y: bilinear interpolation output height. :param out_size_y: bilinear interpolation output height.
:type out_size_y: int|None :type out_size_y: int|None
:param name: The layer's name, which cna not be specified. :param name: The layer's name, which cna not be specified.
...@@ -1742,11 +1771,11 @@ def img_conv_layer(input, ...@@ -1742,11 +1771,11 @@ def img_conv_layer(input,
The details of convolution layer, please refer UFLDL's `convolution The details of convolution layer, please refer UFLDL's `convolution
<http://ufldl.stanford.edu/tutorial/supervised/ <http://ufldl.stanford.edu/tutorial/supervised/
FeatureExtractionUsingConvolution/>`_ . FeatureExtractionUsingConvolution/>`_ .
Convolution Transpose (deconv) layer for image. Paddle only support square Convolution Transpose (deconv) layer for image. Paddle only support square
input currently and thus input image's width equals height. input currently and thus input image's width equals height.
The details of convolution transpose layer, The details of convolution transpose layer,
please refer to the following explanation and references therein please refer to the following explanation and references therein
<http://datascience.stackexchange.com/questions/6107/ <http://datascience.stackexchange.com/questions/6107/
what-are-deconvolutional-layers/>`_ . what-are-deconvolutional-layers/>`_ .
...@@ -4411,7 +4440,7 @@ def cross_entropy(input, label, name=None, coeff=1.0, layer_attr=None): ...@@ -4411,7 +4440,7 @@ def cross_entropy(input, label, name=None, coeff=1.0, layer_attr=None):
.. code-block:: python .. code-block:: python
cost = cross_entropy(input=input_layer, cost = cross_entropy(input=input_layer,
label=label_layer) label=label_layer)
:param input: The first input layer. :param input: The first input layer.
...@@ -4451,7 +4480,7 @@ def cross_entropy_with_selfnorm(input, ...@@ -4451,7 +4480,7 @@ def cross_entropy_with_selfnorm(input,
.. code-block:: python .. code-block:: python
cost = cross_entropy_with_selfnorm(input=input_layer, cost = cross_entropy_with_selfnorm(input=input_layer,
label=label_layer) label=label_layer)
:param input: The first input layer. :param input: The first input layer.
...@@ -4521,7 +4550,7 @@ def huber_cost(input, label, name=None, coeff=1.0, layer_attr=None): ...@@ -4521,7 +4550,7 @@ def huber_cost(input, label, name=None, coeff=1.0, layer_attr=None):
.. code-block:: python .. code-block:: python
cost = huber_cost(input=input_layer, cost = huber_cost(input=input_layer,
label=label_layer) label=label_layer)
:param input: The first input layer. :param input: The first input layer.
...@@ -4561,7 +4590,7 @@ def multi_binary_label_cross_entropy(input, ...@@ -4561,7 +4590,7 @@ def multi_binary_label_cross_entropy(input,
.. code-block:: python .. code-block:: python
cost = multi_binary_label_cross_entropy(input=input_layer, cost = multi_binary_label_cross_entropy(input=input_layer,
label=label_layer) label=label_layer)
:param input: The first input layer. :param input: The first input layer.
......
...@@ -26,6 +26,7 @@ with mixed_layer() as m5: ...@@ -26,6 +26,7 @@ with mixed_layer() as m5:
with mixed_layer() as m6: with mixed_layer() as m6:
m6 += dotmul_operator(a=m3, b=m4) m6 += dotmul_operator(a=m3, b=m4)
m6 += scaling_projection(m3)
img = data_layer(name='img', size=32 * 32) img = data_layer(name='img', size=32 * 32)
flt = data_layer(name='filter', size=3 * 3 * 1 * 64) flt = data_layer(name='filter', size=3 * 3 * 1 * 64)
......
...@@ -111,13 +111,23 @@ layers { ...@@ -111,13 +111,23 @@ layers {
inputs { inputs {
input_layer_name: "__mixed_2__" input_layer_name: "__mixed_2__"
} }
inputs {
input_layer_name: "__mixed_2__"
input_parameter_name: "___mixed_5__.w1"
proj_conf {
type: "scaling"
name: "___mixed_5__.w1"
input_size: 100
output_size: 100
}
}
inputs { inputs {
input_layer_name: "__mixed_3__" input_layer_name: "__mixed_3__"
} }
operator_confs { operator_confs {
type: "dot_mul" type: "dot_mul"
input_indices: 0 input_indices: 0
input_indices: 1 input_indices: 2
input_sizes: 100 input_sizes: 100
input_sizes: 100 input_sizes: 100
output_size: 100 output_size: 100
...@@ -258,6 +268,16 @@ parameters { ...@@ -258,6 +268,16 @@ parameters {
initial_strategy: 0 initial_strategy: 0
initial_smart: false initial_smart: false
} }
parameters {
name: "___mixed_5__.w1"
size: 1
initial_mean: 0.0
initial_std: 1.0
dims: 1
dims: 1
initial_strategy: 0
initial_smart: true
}
parameters { parameters {
name: "___mixed_7__.w0" name: "___mixed_7__.w0"
size: 30000 size: 30000
......
...@@ -12,4 +12,4 @@ ...@@ -12,4 +12,4 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
__all__ = ['dump_config'] __all__ = ['dump_config']
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册