-
Notifications
You must be signed in to change notification settings - Fork 5.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Imperative transfer gru unit #16095
Merged
Merged
Imperative transfer gru unit #16095
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
f49d9b3
Transfer GRU unit
velconia 6871fe6
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
velconia 2050f31
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
velconia 0d27d20
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
velconia d17bb4e
Add unit test for gru unit
velconia de212ae
Polish code
velconia File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -22,7 +22,8 @@ | |
from ..framework import Variable, OpProtoHolder | ||
from ..param_attr import ParamAttr | ||
from ..initializer import Normal, Constant | ||
__all__ = ['Conv2D', 'Pool2D', 'FC', 'BatchNorm', 'Embedding'] | ||
|
||
__all__ = ['Conv2D', 'Pool2D', 'FC', 'BatchNorm', 'Embedding', 'GRUUnit'] | ||
|
||
|
||
class Conv2D(layers.Layer): | ||
|
@@ -468,3 +469,137 @@ def forward(self, input): | |
}) | ||
|
||
return out | ||
|
||
|
||
class GRUUnit(layers.Layer): | ||
""" | ||
**GRU unit layer** | ||
|
||
if origin_mode is True, then the equation of a gru step is from paper | ||
`Learning Phrase Representations using RNN Encoder-Decoder for Statistical | ||
Machine Translation <https://arxiv.org/pdf/1406.1078.pdf>`_ | ||
|
||
.. math:: | ||
u_t & = actGate(xu_{t} + W_u h_{t-1} + b_u) | ||
|
||
r_t & = actGate(xr_{t} + W_r h_{t-1} + b_r) | ||
|
||
m_t & = actNode(xm_t + W_c dot(r_t, h_{t-1}) + b_m) | ||
|
||
h_t & = dot(u_t, h_{t-1}) + dot((1-u_t), m_t) | ||
|
||
if origin_mode is False, then the equation of a gru step is from paper | ||
`Empirical Evaluation of Gated Recurrent Neural Networks on Sequence | ||
Modeling <https://arxiv.org/pdf/1412.3555.pdf>`_ | ||
|
||
.. math:: | ||
u_t & = actGate(xu_{t} + W_u h_{t-1} + b_u) | ||
|
||
r_t & = actGate(xr_{t} + W_r h_{t-1} + b_r) | ||
|
||
m_t & = actNode(xm_t + W_c dot(r_t, h_{t-1}) + b_m) | ||
|
||
h_t & = dot((1-u_t), h_{t-1}) + dot(u_t, m_t) | ||
|
||
|
||
The inputs of gru unit includes :math:`z_t`, :math:`h_{t-1}`. In terms | ||
of the equation above, the :math:`z_t` is split into 3 parts - | ||
:math:`xu_t`, :math:`xr_t` and :math:`xm_t`. This means that in order to | ||
implement a full GRU unit operator for an input, a fully | ||
connected layer has to be applied, such that :math:`z_t = W_{fc}x_t`. | ||
|
||
The terms :math:`u_t` and :math:`r_t` represent the update and reset gates | ||
of the GRU cell. Unlike LSTM, GRU has one lesser gate. However, there is | ||
an intermediate candidate hidden output, which is denoted by :math:`m_t`. | ||
This layer has three outputs :math:`h_t`, :math:`dot(r_t, h_{t-1})` | ||
and concatenation of :math:`u_t`, :math:`r_t` and :math:`m_t`. | ||
|
||
Args: | ||
input (Variable): The fc transformed input value of current step. | ||
name_scope (str): See base class. | ||
hidden (Variable): The hidden value of gru unit from previous step. | ||
size (integer): The input dimension value. | ||
param_attr(ParamAttr|None): The parameter attribute for the learnable | ||
hidden-hidden weight matrix. Note: | ||
|
||
- The shape of the weight matrix is :math:`(T \\times 3D)`, where | ||
:math:`D` is the hidden size. | ||
- All elements in the weight matrix can be divided into two parts. | ||
The first part are weights of the update gate and reset gate with | ||
shape :math:`(D \\times 2D)`, and the second part are weights for | ||
candidate hidden state with shape :math:`(D \\times D)`. | ||
|
||
If it is set to None or one attribute of ParamAttr, gru_unit will | ||
create ParamAttr as param_attr. If the Initializer of the param_attr | ||
is not set, the parameter is initialized with Xavier. Default: None. | ||
bias_attr (ParamAttr|bool|None): The parameter attribute for the bias | ||
of GRU.Note that the bias with :math:`(1 \\times 3D)` concatenates | ||
the bias in the update gate, reset gate and candidate calculations. | ||
If it is set to False, no bias will be applied to the update gate, | ||
reset gate and candidate calculations. If it is set to None or one | ||
attribute of ParamAttr, gru_unit will create ParamAttr as | ||
bias_attr. If the Initializer of the bias_attr is not set, the bias | ||
is initialized zero. Default: None. | ||
activation (string): The activation type for cell (actNode). | ||
Default: 'tanh' | ||
gate_activation (string): The activation type for gates (actGate). | ||
Default: 'sigmoid' | ||
|
||
Returns: | ||
tuple: The hidden value, reset-hidden value and gate values. | ||
""" | ||
|
||
def __init__(self, | ||
name_scope, | ||
size, | ||
param_attr=None, | ||
bias_attr=None, | ||
activation='tanh', | ||
gate_activation='sigmoid', | ||
origin_mode=False, | ||
dtype='float32'): | ||
super(GRUUnit, self).__init__(name_scope) | ||
|
||
activation_dict = dict( | ||
identity=0, | ||
sigmoid=1, | ||
tanh=2, | ||
relu=3, ) | ||
activation = activation_dict[activation] | ||
gate_activation = activation_dict[gate_activation] | ||
|
||
self._dtype = dtype | ||
size = size // 3 | ||
# create weight | ||
self._weight = self.create_parameter( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm thinking. maybe we should make parameter public so people can use it. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can't agree more~ |
||
attr=param_attr, shape=[size, 3 * size], dtype=dtype) | ||
|
||
# create bias | ||
bias_size = [1, 3 * size] | ||
self._bias = self.create_parameter( | ||
attr=bias_attr, shape=bias_size, dtype=dtype, is_bias=True) | ||
|
||
def forward(self, input, hidden): | ||
inputs = {'Input': input, 'HiddenPrev': hidden, 'Weight': self._weight} | ||
if self._bias: | ||
inputs['Bias'] = self._bias | ||
|
||
gate = self._helper.create_variable_for_type_inference(self._dtype) | ||
reset_hidden_pre = self._helper.create_variable_for_type_inference( | ||
self._dtype) | ||
updated_hidden = self._helper.create_variable_for_type_inference( | ||
self._dtype) | ||
self._helper.append_op( | ||
type='gru_unit', | ||
inputs=inputs, | ||
outputs={ | ||
'Gate': gate, | ||
'ResetHiddenPrev': reset_hidden_pre, | ||
'Hidden': updated_hidden, | ||
}, | ||
attrs={ | ||
'activation': 2, # tanh | ||
'gate_activation': 1, # sigmoid | ||
}) | ||
|
||
return updated_hidden, reset_hidden_pre, gate |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
add name_scope?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
OK, I'll add it in next PR
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done