提交 9115ab1c 编写于 作者: Y Yu Yang 提交者: GitHub

Merge pull request #450 from reyoung/feature/pre-commit-hooks-scripts

Feature/pre commit hooks scripts
...@@ -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.
...@@ -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>
# 支持双层序列作为输入的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
# 双层RNN配置与示例 # 双层RNN配置与示例
我们在`paddle/gserver/tests/test_RecurrentGradientMachine`单测中,通过多组语义相同的单双层RNN配置,讲解如何使用双层RNN。 我们在`paddle/gserver/tests/test_RecurrentGradientMachine`单测中,通过多组语义相同的单双层RNN配置,讲解如何使用双层RNN。
## 示例1:双进双出,subseq间无memory ## 示例1:双进双出,subseq间无memory
配置:单层RNN(`sequence_layer_group`)和双层RNN(`sequence_nest_layer_group`),语义完全相同。 配置:单层RNN(`sequence_layer_group`)和双层RNN(`sequence_nest_layer_group`),语义完全相同。
### 读取双层序列的方法 ### 读取双层序列的方法
首先,我们看一下单双层序列的不同数据组织形式(您也可以采用别的组织形式): 首先,我们看一下单双层序列的不同数据组织形式(您也可以采用别的组织形式):
- 单层序列的数据(`Sequence/tour_train_wdseg`)如下,一共有10个样本。每个样本由两部分组成,一个label(此处都为2)和一个已经分词后的句子。 - 单层序列的数据(`Sequence/tour_train_wdseg`)如下,一共有10个样本。每个样本由两部分组成,一个label(此处都为2)和一个已经分词后的句子。
```text ```text
2 酒店 有 很 舒适 的 床垫 子 , 床上用品 也 应该 是 一人 一 换 , 感觉 很 利落 对 卫生 很 放心 呀 。 2 酒店 有 很 舒适 的 床垫 子 , 床上用品 也 应该 是 一人 一 换 , 感觉 很 利落 对 卫生 很 放心 呀 。
2 很 温馨 , 也 挺 干净 的 * 地段 不错 , 出来 就 有 全家 , 离 地铁站 也 近 , 交通 很方便 * 就是 都 不 给 刷牙 的 杯子 啊 , 就 第一天 给 了 一次性杯子 * 2 很 温馨 , 也 挺 干净 的 * 地段 不错 , 出来 就 有 全家 , 离 地铁站 也 近 , 交通 很方便 * 就是 都 不 给 刷牙 的 杯子 啊 , 就 第一天 给 了 一次性杯子 *
2 位置 方便 , 强烈推荐 , 十一 出去玩 的 时候 选 的 , 对面 就是 华润万家 , 周围 吃饭 的 也 不少 。 2 位置 方便 , 强烈推荐 , 十一 出去玩 的 时候 选 的 , 对面 就是 华润万家 , 周围 吃饭 的 也 不少 。
2 交通便利 , 吃 很 便利 , 乾 浄 、 安静 , 商务 房 有 电脑 、 上网 快 , 价格 可以 , 就 早餐 不 好吃 。 整体 是 不错 的 。 適 合 出差 來 住 。 2 交通便利 , 吃 很 便利 , 乾 浄 、 安静 , 商务 房 有 电脑 、 上网 快 , 价格 可以 , 就 早餐 不 好吃 。 整体 是 不错 的 。 適 合 出差 來 住 。
2 本来 准备 住 两 晚 , 第 2 天 一早 居然 停电 , 且 无 通知 , 只有 口头 道歉 。 总体来说 性价比 尚可 , 房间 较 新 , 还是 推荐 . 2 本来 准备 住 两 晚 , 第 2 天 一早 居然 停电 , 且 无 通知 , 只有 口头 道歉 。 总体来说 性价比 尚可 , 房间 较 新 , 还是 推荐 .
2 这个 酒店 去过 很多 次 了 , 选择 的 主要原因 是 离 客户 最 便宜 相对 又 近 的 酒店 2 这个 酒店 去过 很多 次 了 , 选择 的 主要原因 是 离 客户 最 便宜 相对 又 近 的 酒店
2 挺好 的 汉庭 , 前台 服务 很 热情 , 卫生 很 整洁 , 房间 安静 , 水温 适中 , 挺好 ! 2 挺好 的 汉庭 , 前台 服务 很 热情 , 卫生 很 整洁 , 房间 安静 , 水温 适中 , 挺好 !
2 HowardJohnson 的 品质 , 服务 相当 好 的 一 家 五星级 。 房间 不错 、 泳池 不错 、 楼层 安排 很 合理 。 还有 就是 地理位置 , 简直 一 流 。 就 在 天一阁 、 月湖 旁边 , 离 天一广场 也 不远 。 下次 来 宁波 还会 住 。 2 HowardJohnson 的 品质 , 服务 相当 好 的 一 家 五星级 。 房间 不错 、 泳池 不错 、 楼层 安排 很 合理 。 还有 就是 地理位置 , 简直 一 流 。 就 在 天一阁 、 月湖 旁边 , 离 天一广场 也 不远 。 下次 来 宁波 还会 住 。
2 酒店 很干净 , 很安静 , 很 温馨 , 服务员 服务 好 , 各方面 都 不错 * 2 酒店 很干净 , 很安静 , 很 温馨 , 服务员 服务 好 , 各方面 都 不错 *
2 挺好 的 , 就是 没 窗户 , 不过 对 得 起 这 价格 2 挺好 的 , 就是 没 窗户 , 不过 对 得 起 这 价格
``` ```
- 双层序列的数据(`Sequence/tour_train_wdseg.nest`)如下,一共有4个样本。样本间用空行分开,代表不同的双层序列,序列数据和上面的完全一样。每个样本的子句数分别为2,3,2,3。 - 双层序列的数据(`Sequence/tour_train_wdseg.nest`)如下,一共有4个样本。样本间用空行分开,代表不同的双层序列,序列数据和上面的完全一样。每个样本的子句数分别为2,3,2,3。
```text ```text
2 酒店 有 很 舒适 的 床垫 子 , 床上用品 也 应该 是 一人 一 换 , 感觉 很 利落 对 卫生 很 放心 呀 。 2 酒店 有 很 舒适 的 床垫 子 , 床上用品 也 应该 是 一人 一 换 , 感觉 很 利落 对 卫生 很 放心 呀 。
2 很 温馨 , 也 挺 干净 的 * 地段 不错 , 出来 就 有 全家 , 离 地铁站 也 近 , 交通 很方便 * 就是 都 不 给 刷牙 的 杯子 啊 , 就 第一天 给 了 一次性杯子 * 2 很 温馨 , 也 挺 干净 的 * 地段 不错 , 出来 就 有 全家 , 离 地铁站 也 近 , 交通 很方便 * 就是 都 不 给 刷牙 的 杯子 啊 , 就 第一天 给 了 一次性杯子 *
2 位置 方便 , 强烈推荐 , 十一 出去玩 的 时候 选 的 , 对面 就是 华润万家 , 周围 吃饭 的 也 不少 。 2 位置 方便 , 强烈推荐 , 十一 出去玩 的 时候 选 的 , 对面 就是 华润万家 , 周围 吃饭 的 也 不少 。
2 交通便利 , 吃 很 便利 , 乾 浄 、 安静 , 商务 房 有 电脑 、 上网 快 , 价格 可以 , 就 早餐 不 好吃 。 整体 是 不错 的 。 適 合 出差 來 住 。 2 交通便利 , 吃 很 便利 , 乾 浄 、 安静 , 商务 房 有 电脑 、 上网 快 , 价格 可以 , 就 早餐 不 好吃 。 整体 是 不错 的 。 適 合 出差 來 住 。
2 本来 准备 住 两 晚 , 第 2 天 一早 居然 停电 , 且 无 通知 , 只有 口头 道歉 。 总体来说 性价比 尚可 , 房间 较 新 , 还是 推荐 . 2 本来 准备 住 两 晚 , 第 2 天 一早 居然 停电 , 且 无 通知 , 只有 口头 道歉 。 总体来说 性价比 尚可 , 房间 较 新 , 还是 推荐 .
2 这个 酒店 去过 很多 次 了 , 选择 的 主要原因 是 离 客户 最 便宜 相对 又 近 的 酒店 2 这个 酒店 去过 很多 次 了 , 选择 的 主要原因 是 离 客户 最 便宜 相对 又 近 的 酒店
2 挺好 的 汉庭 , 前台 服务 很 热情 , 卫生 很 整洁 , 房间 安静 , 水温 适中 , 挺好 ! 2 挺好 的 汉庭 , 前台 服务 很 热情 , 卫生 很 整洁 , 房间 安静 , 水温 适中 , 挺好 !
2 HowardJohnson 的 品质 , 服务 相当 好 的 一 家 五星级 。 房间 不错 、 泳池 不错 、 楼层 安排 很 合理 。 还有 就是 地理位置 , 简直 一 流 。 就 在 天一阁 、 月湖 旁边 , 离 天一广场 也 不远 。 下次 来 宁波 还会 住 。 2 HowardJohnson 的 品质 , 服务 相当 好 的 一 家 五星级 。 房间 不错 、 泳池 不错 、 楼层 安排 很 合理 。 还有 就是 地理位置 , 简直 一 流 。 就 在 天一阁 、 月湖 旁边 , 离 天一广场 也 不远 。 下次 来 宁波 还会 住 。
2 酒店 很干净 , 很安静 , 很 温馨 , 服务员 服务 好 , 各方面 都 不错 * 2 酒店 很干净 , 很安静 , 很 温馨 , 服务员 服务 好 , 各方面 都 不错 *
2 挺好 的 , 就是 没 窗户 , 不过 对 得 起 这 价格 2 挺好 的 , 就是 没 窗户 , 不过 对 得 起 这 价格
``` ```
其次,我们看一下单双层序列的不同dataprovider(见`sequenceGen.py`): 其次,我们看一下单双层序列的不同dataprovider(见`sequenceGen.py`):
- 单层序列的dataprovider如下: - 单层序列的dataprovider如下:
- word_slot是integer_value_sequence类型,代表单层序列。 - word_slot是integer_value_sequence类型,代表单层序列。
- label是integer_value类型,代表一个向量。 - label是integer_value类型,代表一个向量。
```python ```python
def hook(settings, dict_file, **kwargs): def hook(settings, dict_file, **kwargs):
settings.word_dict = dict_file settings.word_dict = dict_file
settings.input_types = [integer_value_sequence(len(settings.word_dict)), settings.input_types = [integer_value_sequence(len(settings.word_dict)),
integer_value(3)] integer_value(3)]
@provider(init_hook=hook) @provider(init_hook=hook)
def process(settings, file_name): def process(settings, file_name):
with open(file_name, 'r') as fdata: with open(file_name, 'r') as fdata:
for line in fdata: for line in fdata:
label, comment = line.strip().split('\t') label, comment = line.strip().split('\t')
label = int(''.join(label.split())) label = int(''.join(label.split()))
words = comment.split() words = comment.split()
word_slot = [settings.word_dict[w] for w in words if w in settings.word_dict] word_slot = [settings.word_dict[w] for w in words if w in settings.word_dict]
yield word_slot, label yield word_slot, label
``` ```
- 双层序列的dataprovider如下: - 双层序列的dataprovider如下:
- word_slot是integer_value_sub_sequence类型,代表双层序列。 - word_slot是integer_value_sub_sequence类型,代表双层序列。
- label是integer_value_sequence类型,代表单层序列,即一个子句一个label。注意:也可以为integer_value类型,代表一个向量,即一个句子一个label。通常根据任务需求进行不同设置。 - label是integer_value_sequence类型,代表单层序列,即一个子句一个label。注意:也可以为integer_value类型,代表一个向量,即一个句子一个label。通常根据任务需求进行不同设置。
- 关于dataprovider中input_types的详细用法,参见PyDataProvider2。 - 关于dataprovider中input_types的详细用法,参见PyDataProvider2。
```python ```python
def hook2(settings, dict_file, **kwargs): def hook2(settings, dict_file, **kwargs):
settings.word_dict = dict_file settings.word_dict = dict_file
settings.input_types = [integer_value_sub_sequence(len(settings.word_dict)), settings.input_types = [integer_value_sub_sequence(len(settings.word_dict)),
integer_value_sequence(3)] integer_value_sequence(3)]
@provider(init_hook=hook2) @provider(init_hook=hook2)
def process2(settings, file_name): def process2(settings, file_name):
with open(file_name) as fdata: with open(file_name) as fdata:
label_list = [] label_list = []
word_slot_list = [] word_slot_list = []
for line in fdata: for line in fdata:
if (len(line)) > 1: if (len(line)) > 1:
label,comment = line.strip().split('\t') label,comment = line.strip().split('\t')
label = int(''.join(label.split())) label = int(''.join(label.split()))
words = comment.split() words = comment.split()
word_slot = [settings.word_dict[w] for w in words if w in settings.word_dict] word_slot = [settings.word_dict[w] for w in words if w in settings.word_dict]
label_list.append(label) label_list.append(label)
word_slot_list.append(word_slot) word_slot_list.append(word_slot)
else: else:
yield word_slot_list, label_list yield word_slot_list, label_list
label_list = [] label_list = []
word_slot_list = [] word_slot_list = []
``` ```
### 模型中的配置 ### 模型中的配置
首先,我们看一下单层序列的配置(见`sequence_layer_group.conf`)。注意:batchsize=5表示一次过5句单层序列,因此2个batch就可以完成1个pass。 首先,我们看一下单层序列的配置(见`sequence_layer_group.conf`)。注意:batchsize=5表示一次过5句单层序列,因此2个batch就可以完成1个pass。
```python ```python
settings(batch_size=5) settings(batch_size=5)
data = data_layer(name="word", size=dict_dim) data = data_layer(name="word", size=dict_dim)
emb = embedding_layer(input=data, size=word_dim) emb = embedding_layer(input=data, size=word_dim)
# (lstm_input + lstm) is equal to lstmemory # (lstm_input + lstm) is equal to lstmemory
with mixed_layer(size=hidden_dim*4) as lstm_input: with mixed_layer(size=hidden_dim*4) as lstm_input:
lstm_input += full_matrix_projection(input=emb) lstm_input += full_matrix_projection(input=emb)
lstm = lstmemory_group(input=lstm_input, lstm = lstmemory_group(input=lstm_input,
size=hidden_dim, size=hidden_dim,
act=TanhActivation(), act=TanhActivation(),
gate_act=SigmoidActivation(), gate_act=SigmoidActivation(),
state_act=TanhActivation(), state_act=TanhActivation(),
lstm_layer_attr=ExtraLayerAttribute(error_clipping_threshold=50)) lstm_layer_attr=ExtraLayerAttribute(error_clipping_threshold=50))
lstm_last = last_seq(input=lstm) lstm_last = last_seq(input=lstm)
with mixed_layer(size=label_dim, with mixed_layer(size=label_dim,
act=SoftmaxActivation(), act=SoftmaxActivation(),
bias_attr=True) as output: bias_attr=True) as output:
output += full_matrix_projection(input=lstm_last) output += full_matrix_projection(input=lstm_last)
outputs(classification_cost(input=output, label=data_layer(name="label", size=1))) outputs(classification_cost(input=output, label=data_layer(name="label", size=1)))
``` ```
其次,我们看一下语义相同的双层序列配置(见`sequence_nest_layer_group.conf`),并对其详细分析: 其次,我们看一下语义相同的双层序列配置(见`sequence_nest_layer_group.conf`),并对其详细分析:
- batchsize=2表示一次过2句双层序列。但从上面的数据格式可知,2句双层序列和5句单层序列的数据完全一样。 - batchsize=2表示一次过2句双层序列。但从上面的数据格式可知,2句双层序列和5句单层序列的数据完全一样。
- data_layer和embedding_layer不关心数据是否是序列格式,因此两个配置在这两层上的输出是一样的。 - data_layer和embedding_layer不关心数据是否是序列格式,因此两个配置在这两层上的输出是一样的。
- lstmemory: - lstmemory:
- 单层序列过了一个mixed_layer和lstmemory_group。 - 单层序列过了一个mixed_layer和lstmemory_group。
- 双层序列在同样的mixed_layer和lstmemory_group外,直接加了一层group。由于这个外层group里面没有memory,表示subseq间不存在联系,即起到的作用仅仅是把双层seq拆成单层,因此双层序列过完lstmemory的输出和单层的一样。 - 双层序列在同样的mixed_layer和lstmemory_group外,直接加了一层group。由于这个外层group里面没有memory,表示subseq间不存在联系,即起到的作用仅仅是把双层seq拆成单层,因此双层序列过完lstmemory的输出和单层的一样。
- last_seq: - last_seq:
- 单层序列直接取了最后一个元素 - 单层序列直接取了最后一个元素
- 双层序列首先(last_seq层)取了每个subseq的最后一个元素,将其拼接成一个新的单层序列;接着(expand_layer层)将其扩展成一个新的双层序列,其中第i个subseq中的所有向量均为输入的单层序列中的第i个向量;最后(average_layer层)取了每个subseq的平均值。 - 双层序列首先(last_seq层)取了每个subseq的最后一个元素,将其拼接成一个新的单层序列;接着(expand_layer层)将其扩展成一个新的双层序列,其中第i个subseq中的所有向量均为输入的单层序列中的第i个向量;最后(average_layer层)取了每个subseq的平均值。
- 分析得出:第一个last_seq后,每个subseq的最后一个元素就等于单层序列的最后一个元素,而expand_layer和average_layer后,依然保持每个subseq最后一个元素的值不变(这两层仅是为了展示它们的用法,实际中并不需要)。因此单双层序列的输出是一样旳。 - 分析得出:第一个last_seq后,每个subseq的最后一个元素就等于单层序列的最后一个元素,而expand_layer和average_layer后,依然保持每个subseq最后一个元素的值不变(这两层仅是为了展示它们的用法,实际中并不需要)。因此单双层序列的输出是一样旳。
```python ```python
settings(batch_size=2) settings(batch_size=2)
data = data_layer(name="word", size=dict_dim) data = data_layer(name="word", size=dict_dim)
emb_group = embedding_layer(input=data, size=word_dim) emb_group = embedding_layer(input=data, size=word_dim)
# (lstm_input + lstm) is equal to lstmemory # (lstm_input + lstm) is equal to lstmemory
def lstm_group(lstm_group_input): def lstm_group(lstm_group_input):
with mixed_layer(size=hidden_dim*4) as group_input: with mixed_layer(size=hidden_dim*4) as group_input:
group_input += full_matrix_projection(input=lstm_group_input) group_input += full_matrix_projection(input=lstm_group_input)
lstm_output = lstmemory_group(input=group_input, lstm_output = lstmemory_group(input=group_input,
name="lstm_group", name="lstm_group",
size=hidden_dim, size=hidden_dim,
act=TanhActivation(), act=TanhActivation(),
gate_act=SigmoidActivation(), gate_act=SigmoidActivation(),
state_act=TanhActivation(), state_act=TanhActivation(),
lstm_layer_attr=ExtraLayerAttribute(error_clipping_threshold=50)) lstm_layer_attr=ExtraLayerAttribute(error_clipping_threshold=50))
return lstm_output return lstm_output
lstm_nest_group = recurrent_group(input=SubsequenceInput(emb_group), lstm_nest_group = recurrent_group(input=SubsequenceInput(emb_group),
step=lstm_group, step=lstm_group,
name="lstm_nest_group") name="lstm_nest_group")
# hasSubseq ->(seqlastins) seq # hasSubseq ->(seqlastins) seq
lstm_last = last_seq(input=lstm_nest_group, agg_level=AggregateLevel.EACH_SEQUENCE) lstm_last = last_seq(input=lstm_nest_group, agg_level=AggregateLevel.EACH_SEQUENCE)
# seq ->(expand) hasSubseq # seq ->(expand) hasSubseq
lstm_expand = expand_layer(input=lstm_last, expand_as=emb_group, expand_level=ExpandLevel.FROM_SEQUENCE) lstm_expand = expand_layer(input=lstm_last, expand_as=emb_group, expand_level=ExpandLevel.FROM_SEQUENCE)
# hasSubseq ->(average) seq # hasSubseq ->(average) seq
lstm_average = pooling_layer(input=lstm_expand, lstm_average = pooling_layer(input=lstm_expand,
pooling_type=AvgPooling(), pooling_type=AvgPooling(),
agg_level=AggregateLevel.EACH_SEQUENCE) agg_level=AggregateLevel.EACH_SEQUENCE)
with mixed_layer(size=label_dim, with mixed_layer(size=label_dim,
act=SoftmaxActivation(), act=SoftmaxActivation(),
bias_attr=True) as output: bias_attr=True) as output:
output += full_matrix_projection(input=lstm_average) output += full_matrix_projection(input=lstm_average)
outputs(classification_cost(input=output, label=data_layer(name="label", size=1))) outputs(classification_cost(input=output, label=data_layer(name="label", size=1)))
``` ```
## 示例2:双进双出,subseq间有memory ## 示例2:双进双出,subseq间有memory
配置:单层RNN(`sequence_rnn.conf`),双层RNN(`sequence_nest_rnn.conf``sequence_nest_rnn_readonly_memory.conf`),语义完全相同。 配置:单层RNN(`sequence_rnn.conf`),双层RNN(`sequence_nest_rnn.conf``sequence_nest_rnn_readonly_memory.conf`),语义完全相同。
### 读取双层序列的方法 ### 读取双层序列的方法
我们看一下单双层序列的不同数据组织形式和dataprovider(见`rnn_data_provider.py` 我们看一下单双层序列的不同数据组织形式和dataprovider(见`rnn_data_provider.py`
```python ```python
data = [ data = [
[[[1, 3, 2], [4, 5, 2]], 0], [[[1, 3, 2], [4, 5, 2]], 0],
[[[0, 2], [2, 5], [0, 1, 2]], 1], [[[0, 2], [2, 5], [0, 1, 2]], 1],
] ]
@provider(input_types=[integer_value_sub_sequence(10), @provider(input_types=[integer_value_sub_sequence(10),
integer_value(3)]) integer_value(3)])
def process_subseq(settings, file_name): def process_subseq(settings, file_name):
for d in data: for d in data:
yield d yield d
@provider(input_types=[integer_value_sequence(10), @provider(input_types=[integer_value_sequence(10),
integer_value(3)]) integer_value(3)])
def process_seq(settings, file_name): def process_seq(settings, file_name):
for d in data: for d in data:
seq = [] seq = []
``` ```
- 单层序列:有两句,分别为[1,3,2,4,5,2]和[0,2,2,5,0,1,2]。 - 单层序列:有两句,分别为[1,3,2,4,5,2]和[0,2,2,5,0,1,2]。
- 双层序列:有两句,分别为[[1,3,2],[4,5,2]](2个子句)和[[0,2],[2,5],[0,1,2]](3个子句)。 - 双层序列:有两句,分别为[[1,3,2],[4,5,2]](2个子句)和[[0,2],[2,5],[0,1,2]](3个子句)。
- 单双层序列的label都分别是0和1 - 单双层序列的label都分别是0和1
### 模型中的配置 ### 模型中的配置
我们选取单双层序列配置中的不同部分,来对比分析两者语义相同的原因。 我们选取单双层序列配置中的不同部分,来对比分析两者语义相同的原因。
- 单层序列:过了一个很简单的recurrent_group。每一个时间步,当前的输入y和上一个时间步的输出rnn_state做了一个全链接。 - 单层序列:过了一个很简单的recurrent_group。每一个时间步,当前的输入y和上一个时间步的输出rnn_state做了一个全链接。
```python ```python
def step(y): def step(y):
mem = memory(name="rnn_state", size=hidden_dim) mem = memory(name="rnn_state", size=hidden_dim)
return fc_layer(input=[y, mem], return fc_layer(input=[y, mem],
size=hidden_dim, size=hidden_dim,
act=TanhActivation(), act=TanhActivation(),
bias_attr=True, bias_attr=True,
name="rnn_state") name="rnn_state")
out = recurrent_group(step=step, input=emb) out = recurrent_group(step=step, input=emb)
``` ```
- 双层序列,外层memory是一个元素: - 双层序列,外层memory是一个元素:
- 内层inner_step的recurrent_group和单层序列的几乎一样。除了boot_layer=outer_mem,表示将外层的outer_mem作为内层memory的初始状态。外层outer_step中,outer_mem是一个子句的最后一个向量,即整个双层group是将前一个子句的最后一个向量,作为下一个子句memory的初始状态。 - 内层inner_step的recurrent_group和单层序列的几乎一样。除了boot_layer=outer_mem,表示将外层的outer_mem作为内层memory的初始状态。外层outer_step中,outer_mem是一个子句的最后一个向量,即整个双层group是将前一个子句的最后一个向量,作为下一个子句memory的初始状态。
- 从输入数据上看,单双层序列的句子是一样的,只是双层序列将其又做了子序列划分。因此双层序列的配置中,必须将前一个子句的最后一个元素,作为boot_layer传给下一个子句的memory,才能保证和单层序列的配置中“每一个时间步都用了上一个时间步的输出结果”一致。 - 从输入数据上看,单双层序列的句子是一样的,只是双层序列将其又做了子序列划分。因此双层序列的配置中,必须将前一个子句的最后一个元素,作为boot_layer传给下一个子句的memory,才能保证和单层序列的配置中“每一个时间步都用了上一个时间步的输出结果”一致。
```python ```python
def outer_step(x): def outer_step(x):
outer_mem = memory(name="outer_rnn_state", size=hidden_dim) outer_mem = memory(name="outer_rnn_state", size=hidden_dim)
def inner_step(y): def inner_step(y):
inner_mem = memory(name="inner_rnn_state", inner_mem = memory(name="inner_rnn_state",
size=hidden_dim, size=hidden_dim,
boot_layer=outer_mem) boot_layer=outer_mem)
return fc_layer(input=[y, inner_mem], return fc_layer(input=[y, inner_mem],
size=hidden_dim, size=hidden_dim,
act=TanhActivation(), act=TanhActivation(),
bias_attr=True, bias_attr=True,
name="inner_rnn_state") name="inner_rnn_state")
inner_rnn_output = recurrent_group( inner_rnn_output = recurrent_group(
step=inner_step, step=inner_step,
input=x) input=x)
last = last_seq(input=inner_rnn_output, name="outer_rnn_state") last = last_seq(input=inner_rnn_output, name="outer_rnn_state")
return inner_rnn_output return inner_rnn_output
out = recurrent_group(step=outer_step, input=SubsequenceInput(emb)) out = recurrent_group(step=outer_step, input=SubsequenceInput(emb))
``` ```
- 双层序列,外层memory是单层序列: - 双层序列,外层memory是单层序列:
- 由于外层每个时间步返回的是一个子句,这些子句的长度往往不等长。因此当外层有is_seq=True的memory时,内层是**无法直接使用**它的,即内层memory的boot_layer不能链接外层的这个memory。 - 由于外层每个时间步返回的是一个子句,这些子句的长度往往不等长。因此当外层有is_seq=True的memory时,内层是**无法直接使用**它的,即内层memory的boot_layer不能链接外层的这个memory。
- 如果内层memory想**间接使用**这个外层memory,只能通过`pooling_layer``last_seq``first_seq`这三个layer将它先变成一个元素。但这种情况下,外层memory必须有boot_layer,否则在第0个时间步时,由于外层memory没有任何seq信息,因此上述三个layer的前向会报出“**Check failed: input.sequenceStartPositions**”的错误。 - 如果内层memory想**间接使用**这个外层memory,只能通过`pooling_layer``last_seq``first_seq`这三个layer将它先变成一个元素。但这种情况下,外层memory必须有boot_layer,否则在第0个时间步时,由于外层memory没有任何seq信息,因此上述三个layer的前向会报出“**Check failed: input.sequenceStartPositions**”的错误。
## 示例3:双进双出,输入不等长 ## 示例3:双进双出,输入不等长
**输入不等长**是指recurrent_group的多个输入在各时刻的长度可以不相等, 但需要指定一个和输出长度一致的input,用<font color="red">targetInlink</font>表示。参考配置:单层RNN(`sequence_rnn_multi_unequalength_inputs.conf`),双层RNN(`sequence_nest_rnn_multi_unequalength_inputs.conf` **输入不等长**是指recurrent_group的多个输入在各时刻的长度可以不相等, 但需要指定一个和输出长度一致的input,用<font color="red">targetInlink</font>表示。参考配置:单层RNN(`sequence_rnn_multi_unequalength_inputs.conf`),双层RNN(`sequence_nest_rnn_multi_unequalength_inputs.conf`
### 读取双层序列的方法 ### 读取双层序列的方法
我们看一下单双层序列的数据组织形式和dataprovider(见`rnn_data_provider.py` 我们看一下单双层序列的数据组织形式和dataprovider(见`rnn_data_provider.py`
```python ```python
data2 = [ data2 = [
[[[1, 2], [4, 5, 2]], [[5, 4, 1], [3, 1]] ,0], [[[1, 2], [4, 5, 2]], [[5, 4, 1], [3, 1]] ,0],
[[[0, 2], [2, 5], [0, 1, 2]],[[1, 5], [4], [2, 3, 6, 1]], 1], [[[0, 2], [2, 5], [0, 1, 2]],[[1, 5], [4], [2, 3, 6, 1]], 1],
] ]
@provider(input_types=[integer_value_sub_sequence(10), @provider(input_types=[integer_value_sub_sequence(10),
integer_value_sub_sequence(10), integer_value_sub_sequence(10),
integer_value(2)], integer_value(2)],
should_shuffle=False) should_shuffle=False)
def process_unequalength_subseq(settings, file_name): #双层RNN的dataprovider def process_unequalength_subseq(settings, file_name): #双层RNN的dataprovider
for d in data2: for d in data2:
yield d yield d
@provider(input_types=[integer_value_sequence(10), @provider(input_types=[integer_value_sequence(10),
integer_value_sequence(10), integer_value_sequence(10),
integer_value(2)], integer_value(2)],
should_shuffle=False) should_shuffle=False)
def process_unequalength_seq(settings, file_name): #单层RNN的dataprovider def process_unequalength_seq(settings, file_name): #单层RNN的dataprovider
for d in data2: for d in data2:
words1=reduce(lambda x,y: x+y, d[0]) words1=reduce(lambda x,y: x+y, d[0])
words2=reduce(lambda x,y: x+y, d[1]) words2=reduce(lambda x,y: x+y, d[1])
yield words1, words2, d[2] yield words1, words2, d[2]
``` ```
data2 中有两个样本,每个样本有两个特征, 记fea1, fea2。 data2 中有两个样本,每个样本有两个特征, 记fea1, fea2。
- 单层序列:两个样本分别为[[1, 2, 4, 5, 2], [5, 4, 1, 3, 1]] 和 [[0, 2, 2, 5, 0, 1, 2], [1, 5, 4, 2, 3, 6, 1]] - 单层序列:两个样本分别为[[1, 2, 4, 5, 2], [5, 4, 1, 3, 1]] 和 [[0, 2, 2, 5, 0, 1, 2], [1, 5, 4, 2, 3, 6, 1]]
- 双层序列:两个样本分别为 - 双层序列:两个样本分别为
- **样本1**:[[[1, 2], [4, 5, 2]], [[5, 4, 1], [3, 1]]]。fea1和fea2都分别有2个子句,fea1=[[1, 2], [4, 5, 2]], fea2=[[5, 4, 1], [3, 1]] - **样本1**:[[[1, 2], [4, 5, 2]], [[5, 4, 1], [3, 1]]]。fea1和fea2都分别有2个子句,fea1=[[1, 2], [4, 5, 2]], fea2=[[5, 4, 1], [3, 1]]
- **样本2**:[[[0, 2], [2, 5], [0, 1, 2]],[[1, 5], [4], [2, 3, 6, 1]]]。fea1和fea2都分别有3个子句, fea1=[[0, 2], [2, 5], [0, 1, 2]], fea2=[[1, 5], [4], [2, 3, 6, 1]]。<br/> - **样本2**:[[[0, 2], [2, 5], [0, 1, 2]],[[1, 5], [4], [2, 3, 6, 1]]]。fea1和fea2都分别有3个子句, fea1=[[0, 2], [2, 5], [0, 1, 2]], fea2=[[1, 5], [4], [2, 3, 6, 1]]。<br/>
- **注意**:每个样本中,各特征的子句数目需要相等。这里说的“双进双出,输入不等长”是指fea1在i时刻的输入的长度可以不等于fea2在i时刻的输入的长度。如对于第1个样本,时刻i=2, fea1[2]=[4, 5, 2],fea2[2]=[3, 1],3≠2。 - **注意**:每个样本中,各特征的子句数目需要相等。这里说的“双进双出,输入不等长”是指fea1在i时刻的输入的长度可以不等于fea2在i时刻的输入的长度。如对于第1个样本,时刻i=2, fea1[2]=[4, 5, 2],fea2[2]=[3, 1],3≠2。
- 单双层序列中,两个样本的label都分别是0和1 - 单双层序列中,两个样本的label都分别是0和1
### 模型中的配置 ### 模型中的配置
单层RNN(`sequence_rnn_multi_unequalength_inputs.conf`)和双层RNN(`sequence_nest_rnn_multi_unequalength_inputs.conf`)两个模型配置达到的效果完全一样,区别只在于输入为单层还是双层序列,现在我们来看它们内部分别是如何实现的。 单层RNN(`sequence_rnn_multi_unequalength_inputs.conf`)和双层RNN(`sequence_nest_rnn_multi_unequalength_inputs.conf`)两个模型配置达到的效果完全一样,区别只在于输入为单层还是双层序列,现在我们来看它们内部分别是如何实现的。
- 单层序列: - 单层序列:
- 过了一个简单的recurrent_group。每一个时间步,当前的输入y和上一个时间步的输出rnn_state做了一个全连接,功能与示例2中`sequence_rnn.conf``step`函数完全相同。这里,两个输入x1,x2分别通过calrnn返回最后时刻的状态。结果得到的encoder1_rep和encoder2_rep分别是单层序列,最后取encoder1_rep的最后一个时刻和encoder2_rep的所有时刻分别相加得到context。 - 过了一个简单的recurrent_group。每一个时间步,当前的输入y和上一个时间步的输出rnn_state做了一个全连接,功能与示例2中`sequence_rnn.conf``step`函数完全相同。这里,两个输入x1,x2分别通过calrnn返回最后时刻的状态。结果得到的encoder1_rep和encoder2_rep分别是单层序列,最后取encoder1_rep的最后一个时刻和encoder2_rep的所有时刻分别相加得到context。
- 注意到这里recurrent_group输入的每个样本中,fea1和fea2的长度都分别相等,这并非偶然,而是因为recurrent_group要求输入为单层序列时,所有输入的长度都必须相等。 - 注意到这里recurrent_group输入的每个样本中,fea1和fea2的长度都分别相等,这并非偶然,而是因为recurrent_group要求输入为单层序列时,所有输入的长度都必须相等。
```python ```python
def step(x1, x2): def step(x1, x2):
def calrnn(y): def calrnn(y):
mem = memory(name = 'rnn_state_' + y.name, size = hidden_dim) mem = memory(name = 'rnn_state_' + y.name, size = hidden_dim)
out = fc_layer(input = [y, mem], out = fc_layer(input = [y, mem],
size = hidden_dim, size = hidden_dim,
act = TanhActivation(), act = TanhActivation(),
bias_attr = True, bias_attr = True,
name = 'rnn_state_' + y.name) name = 'rnn_state_' + y.name)
return out return out
encoder1 = calrnn(x1) encoder1 = calrnn(x1)
encoder2 = calrnn(x2) encoder2 = calrnn(x2)
return [encoder1, encoder2] return [encoder1, encoder2]
encoder1_rep, encoder2_rep = recurrent_group( encoder1_rep, encoder2_rep = recurrent_group(
name="stepout", name="stepout",
step=step, step=step,
input=[emb1, emb2]) input=[emb1, emb2])
encoder1_last = last_seq(input = encoder1_rep) encoder1_last = last_seq(input = encoder1_rep)
encoder1_expandlast = expand_layer(input = encoder1_last, encoder1_expandlast = expand_layer(input = encoder1_last,
expand_as = encoder2_rep) expand_as = encoder2_rep)
context = mixed_layer(input = [identity_projection(encoder1_expandlast), context = mixed_layer(input = [identity_projection(encoder1_expandlast),
identity_projection(encoder2_rep)], identity_projection(encoder2_rep)],
size = hidden_dim) size = hidden_dim)
``` ```
- 双层序列: - 双层序列:
- 双层RNN中,对输入的两个特征分别求时序上的连续全连接(`inner_step1``inner_step2`分别处理fea1和fea2),其功能与示例2中`sequence_nest_rnn.conf``outer_step`函数完全相同。不同之处是,此时输入`[SubsequenceInput(emb1), SubsequenceInput(emb2)]`在各时刻并不等长。 - 双层RNN中,对输入的两个特征分别求时序上的连续全连接(`inner_step1``inner_step2`分别处理fea1和fea2),其功能与示例2中`sequence_nest_rnn.conf``outer_step`函数完全相同。不同之处是,此时输入`[SubsequenceInput(emb1), SubsequenceInput(emb2)]`在各时刻并不等长。
- 函数`outer_step`中可以分别处理这两个特征,但我们需要用<font color=red>targetInlink</font>指定recurrent_group的输出的格式(各子句长度)只能和其中一个保持一致,如这里选择了和emb2的长度一致。 - 函数`outer_step`中可以分别处理这两个特征,但我们需要用<font color=red>targetInlink</font>指定recurrent_group的输出的格式(各子句长度)只能和其中一个保持一致,如这里选择了和emb2的长度一致。
- 最后,依然是取encoder1_rep的最后一个时刻和encoder2_rep的所有时刻分别相加得到context。 - 最后,依然是取encoder1_rep的最后一个时刻和encoder2_rep的所有时刻分别相加得到context。
```python ```python
def outer_step(x1, x2): def outer_step(x1, x2):
outer_mem1 = memory(name = "outer_rnn_state1", size = hidden_dim) outer_mem1 = memory(name = "outer_rnn_state1", size = hidden_dim)
outer_mem2 = memory(name = "outer_rnn_state2", size = hidden_dim) outer_mem2 = memory(name = "outer_rnn_state2", size = hidden_dim)
def inner_step1(y): def inner_step1(y):
inner_mem = memory(name = 'inner_rnn_state_' + y.name, inner_mem = memory(name = 'inner_rnn_state_' + y.name,
size = hidden_dim, size = hidden_dim,
boot_layer = outer_mem1) boot_layer = outer_mem1)
out = fc_layer(input = [y, inner_mem], out = fc_layer(input = [y, inner_mem],
size = hidden_dim, size = hidden_dim,
act = TanhActivation(), act = TanhActivation(),
bias_attr = True, bias_attr = True,
name = 'inner_rnn_state_' + y.name) name = 'inner_rnn_state_' + y.name)
return out return out
def inner_step2(y): def inner_step2(y):
inner_mem = memory(name = 'inner_rnn_state_' + y.name, inner_mem = memory(name = 'inner_rnn_state_' + y.name,
size = hidden_dim, size = hidden_dim,
boot_layer = outer_mem2) boot_layer = outer_mem2)
out = fc_layer(input = [y, inner_mem], out = fc_layer(input = [y, inner_mem],
size = hidden_dim, size = hidden_dim,
act = TanhActivation(), act = TanhActivation(),
bias_attr = True, bias_attr = True,
name = 'inner_rnn_state_' + y.name) name = 'inner_rnn_state_' + y.name)
return out return out
encoder1 = recurrent_group( encoder1 = recurrent_group(
step = inner_step1, step = inner_step1,
name = 'inner1', name = 'inner1',
input = x1) input = x1)
encoder2 = recurrent_group( encoder2 = recurrent_group(
step = inner_step2, step = inner_step2,
name = 'inner2', name = 'inner2',
input = x2) input = x2)
sentence_last_state1 = last_seq(input = encoder1, name = 'outer_rnn_state1') sentence_last_state1 = last_seq(input = encoder1, name = 'outer_rnn_state1')
sentence_last_state2_ = last_seq(input = encoder2, name = 'outer_rnn_state2') sentence_last_state2_ = last_seq(input = encoder2, name = 'outer_rnn_state2')
encoder1_expand = expand_layer(input = sentence_last_state1, encoder1_expand = expand_layer(input = sentence_last_state1,
expand_as = encoder2) expand_as = encoder2)
return [encoder1_expand, encoder2] return [encoder1_expand, encoder2]
encoder1_rep, encoder2_rep = recurrent_group( encoder1_rep, encoder2_rep = recurrent_group(
name="outer", name="outer",
step=outer_step, step=outer_step,
input=[SubsequenceInput(emb1), SubsequenceInput(emb2)], input=[SubsequenceInput(emb1), SubsequenceInput(emb2)],
targetInlink=emb2) targetInlink=emb2)
encoder1_last = last_seq(input = encoder1_rep) encoder1_last = last_seq(input = encoder1_rep)
encoder1_expandlast = expand_layer(input = encoder1_last, encoder1_expandlast = expand_layer(input = encoder1_last,
expand_as = encoder2_rep) expand_as = encoder2_rep)
context = mixed_layer(input = [identity_projection(encoder1_expandlast), context = mixed_layer(input = [identity_projection(encoder1_expandlast),
identity_projection(encoder2_rep)], identity_projection(encoder2_rep)],
size = hidden_dim) size = hidden_dim)
``` ```
## 示例4:beam_search的生成 ## 示例4:beam_search的生成
TBD TBD
\ 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
...@@ -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);
} }
...@@ -48,4 +48,3 @@ public: ...@@ -48,4 +48,3 @@ public:
}; };
} // namespace paddle } // namespace paddle
...@@ -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_
...@@ -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
因为 它太大了无法显示 source diff 。你可以改为 查看blob
...@@ -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)
...@@ -686,8 +686,8 @@ class ConvProjection(Projection): ...@@ -686,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
...@@ -2793,8 +2793,8 @@ class ConcatenateLayer2(LayerBase): ...@@ -2793,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
...@@ -2876,22 +2876,22 @@ class MDLstmLayer(LayerBase): ...@@ -2876,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))
...@@ -2929,8 +2929,8 @@ class GruStepLayer(LayerBase): ...@@ -2929,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)
......
...@@ -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.
先完成此消息的编辑!
想要评论请 注册