-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
n_step_rnn.py
357 lines (274 loc) · 11.9 KB
/
n_step_rnn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import numpy
import six
import chainer
from chainer.functions.array import permutate
from chainer.functions.array import transpose_sequence
from chainer.functions.connection import n_step_rnn as rnn
from chainer.initializers import normal
from chainer import link
from chainer.utils import argument
from chainer import variable
def argsort_list_descent(lst):
return numpy.argsort([-len(x) for x in lst]).astype(numpy.int32)
def permutate_list(lst, indices, inv):
ret = [None] * len(lst)
if inv:
for i, ind in enumerate(indices):
ret[ind] = lst[i]
else:
for i, ind in enumerate(indices):
ret[i] = lst[ind]
return ret
class NStepRNNBase(link.ChainList):
"""__init__(self, n_layers, in_size, out_size, dropout)
Base link class for Stacked RNN/BiRNN links.
This link is base link class for :func:`chainer.links.NStepRNN` and
:func:`chainer.links.NStepBiRNN`.
This link's behavior depends on argument, ``use_bi_direction``.
Args:
n_layers (int): Number of layers.
in_size (int): Dimensionality of input vectors.
out_size (int): Dimensionality of hidden states and output vectors.
dropout (float): Dropout ratio.
.. seealso::
:func:`chainer.links.NStepRNNReLU`
:func:`chainer.links.NStepRNNTanh`
:func:`chainer.links.NStepBiRNNReLU`
:func:`chainer.links.NStepBiRNNTanh`
"""
def __init__(self, n_layers, in_size, out_size, dropout, **kwargs):
if kwargs:
argument.check_unexpected_kwargs(
kwargs,
use_cudnn='use_cudnn argument is not supported anymore. '
'Use chainer.using_config',
use_bi_direction='use_bi_direction is not supported anymore',
activation='activation is not supported anymore')
argument.assert_kwargs_empty(kwargs)
weights = []
if self.use_bi_direction:
direction = 2
else:
direction = 1
for i in six.moves.range(n_layers):
for di in six.moves.range(direction):
weight = link.Link()
with weight.init_scope():
for j in six.moves.range(self.n_weights):
if i == 0 and j < self.n_weights // 2:
w_in = in_size
elif i > 0 and j < self.n_weights // 2:
w_in = out_size * direction
else:
w_in = out_size
w = variable.Parameter(
normal.Normal(numpy.sqrt(1. / w_in)),
(out_size, w_in))
b = variable.Parameter(0, (out_size,))
setattr(weight, 'w%d' % j, w)
setattr(weight, 'b%d' % j, b)
weights.append(weight)
super(NStepRNNBase, self).__init__(*weights)
self.ws = [[getattr(layer, 'w%d' % i)
for i in six.moves.range(self.n_weights)]
for layer in self]
self.bs = [[getattr(layer, 'b%d' % i)
for i in six.moves.range(self.n_weights)]
for layer in self]
self.n_layers = n_layers
self.dropout = dropout
self.out_size = out_size
self.direction = direction
def copy(self, mode='share'):
ret = super(NStepRNNBase, self).copy(mode)
ret.ws = [[getattr(layer, 'w%d' % i)
for i in six.moves.range(ret.n_weights)] for layer in ret]
ret.bs = [[getattr(layer, 'b%d' % i)
for i in six.moves.range(ret.n_weights)] for layer in ret]
return ret
def init_hx(self, xs):
shape = (self.n_layers * self.direction, len(xs), self.out_size)
with chainer.using_device(self.device):
hx = variable.Variable(self.xp.zeros(shape, dtype=xs[0].dtype))
return hx
def rnn(self, *args):
"""Calls RNN function.
This function must be implemented in a child class.
"""
raise NotImplementedError
@property
def n_cells(self):
"""Returns the number of cells.
This function must be implemented in a child class.
"""
return NotImplementedError
def forward(self, hx, xs, **kwargs):
"""forward(self, hx, xs)
Calculates all of the hidden states and the cell states.
Args:
hx (:class:`~chainer.Variable` or None): Initial hidden states.
If ``None`` is specified zero-vector is used.
Its shape is ``(S, B, N)`` for uni-directional RNN
and ``(2S, B, N)`` for bi-directional RNN where ``S`` is
the number of layers and is equal to ``n_layers``, ``B`` is
the mini-batch size, and ``N`` is the dimension of
the hidden units.
xs (list of :class:`~chainer.Variable`): List of input sequences.
Each element ``xs[i]`` is a :class:`chainer.Variable` holding
a sequence. Its shape is ``(L_i, I)``, where ``L_i`` is the
length of a sequence for batch ``i``, and ``I`` is the size of
the input and is equal to ``in_size``.
Returns:
tuple: This function returns a tuple containing two elements,
``hy`` and ``ys``.
- ``hy`` is an updated hidden states whose shape is same as ``hx``.
- ``ys`` is a list of :class:`~chainer.Variable` . Each element
``ys[i]`` holds hidden states of the last layer corresponding
to an input ``xs[i]``. Its shape is ``(L_i, N)`` for
uni-directional RNN and ``(L_i, 2N)`` for bi-directional RNN
where ``L_i`` is the length of a sequence for batch ``i``,
and ``N`` is size of hidden units.
"""
(hy,), ys = self._call([hx], xs, **kwargs)
return hy, ys
def _call(self, hs, xs, **kwargs):
"""Calls RNN function.
Args:
hs (list of ~chainer.Variable or None): Lisit of hidden states.
Its length depends on its implementation.
If ``None`` is specified zero-vector is used.
xs (list of ~chainer.Variable): List of input sequences.
Each element ``xs[i]`` is a :class:`chainer.Variable` holding
a sequence.
Returns:
tuple: hs
"""
if kwargs:
argument.check_unexpected_kwargs(
kwargs, train='train argument is not supported anymore. '
'Use chainer.using_config')
argument.assert_kwargs_empty(kwargs)
assert isinstance(xs, (list, tuple))
indices = argsort_list_descent(xs)
xs = permutate_list(xs, indices, inv=False)
hxs = []
for hx in hs:
if hx is None:
hx = self.init_hx(xs)
else:
hx = permutate.permutate(hx, indices, axis=1, inv=False)
hxs.append(hx)
trans_x = transpose_sequence.transpose_sequence(xs)
args = [self.n_layers, self.dropout] + hxs + \
[self.ws, self.bs, trans_x]
result = self.rnn(*args)
hys = [permutate.permutate(h, indices, axis=1, inv=True)
for h in result[:-1]]
trans_y = result[-1]
ys = transpose_sequence.transpose_sequence(trans_y)
ys = permutate_list(ys, indices, inv=True)
return hys, ys
class NStepRNNTanh(NStepRNNBase):
"""__init__(self, n_layers, in_size, out_size, dropout)
Stacked Uni-directional RNN for sequences.
This link is stacked version of Uni-directional RNN for sequences.
Note that the activation function is ``tanh``.
It calculates hidden and cell states of all layer at end-of-string,
and all hidden states of the last layer for each time.
Unlike :func:`chainer.functions.n_step_rnn`, this function automatically
sort inputs in descending order by length, and transpose the sequence.
Users just need to call the link with a list of :class:`chainer.Variable`
holding sequences.
Args:
n_layers (int): Number of layers.
in_size (int): Dimensionality of input vectors.
out_size (int): Dimensionality of hidden states and output vectors.
dropout (float): Dropout ratio.
.. seealso::
:func:`chainer.functions.n_step_rnn`
"""
n_weights = 2
use_bi_direction = False
def rnn(self, *args):
return rnn.n_step_rnn(*args, activation='tanh')
@property
def n_cells(self):
return 1
class NStepRNNReLU(NStepRNNBase):
"""__init__(self, n_layers, in_size, out_size, dropout)
Stacked Uni-directional RNN for sequences.
This link is stacked version of Uni-directional RNN for sequences.
Note that the activation function is ``relu``.
It calculates hidden and cell states of all layer at end-of-string,
and all hidden states of the last layer for each time.
Unlike :func:`chainer.functions.n_step_rnn`, this function automatically
sort inputs in descending order by length, and transpose the sequence.
Users just need to call the link with a list of :class:`chainer.Variable`
holding sequences.
Args:
n_layers (int): Number of layers.
in_size (int): Dimensionality of input vectors.
out_size (int): Dimensionality of hidden states and output vectors.
dropout (float): Dropout ratio.
.. seealso::
:func:`chainer.functions.n_step_rnn`
"""
n_weights = 2
use_bi_direction = False
def rnn(self, *args):
return rnn.n_step_rnn(*args, activation='relu')
@property
def n_cells(self):
return 1
class NStepBiRNNTanh(NStepRNNBase):
"""__init__(self, n_layers, in_size, out_size, dropout)
Stacked Bi-directional RNN for sequences.
This link is stacked version of Bi-directional RNN for sequences.
Note that the activation function is ``tanh``.
It calculates hidden and cell states of all layer at end-of-string,
and all hidden states of the last layer for each time.
Unlike :func:`chainer.functions.n_step_birnn`, this function automatically
sort inputs in descending order by length, and transpose the sequence.
Users just need to call the link with a list of :class:`chainer.Variable`
holding sequences.
Args:
n_layers (int): Number of layers.
in_size (int): Dimensionality of input vectors.
out_size (int): Dimensionality of hidden states and output vectors.
dropout (float): Dropout ratio.
.. seealso::
:func:`chainer.functions.n_step_birnn`
"""
n_weights = 2
use_bi_direction = True
def rnn(self, *args):
return rnn.n_step_birnn(*args, activation='tanh')
@property
def n_cells(self):
return 1
class NStepBiRNNReLU(NStepRNNBase):
"""__init__(self, n_layers, in_size, out_size, dropout)
Stacked Bi-directional RNN for sequences.
This link is stacked version of Bi-directional RNN for sequences.
Note that the activation function is ``relu``.
It calculates hidden and cell states of all layer at end-of-string,
and all hidden states of the last layer for each time.
Unlike :func:`chainer.functions.n_step_birnn`, this function automatically
sort inputs in descending order by length, and transpose the sequence.
Users just need to call the link with a list of :class:`chainer.Variable`
holding sequences.
Args:
n_layers (int): Number of layers.
in_size (int): Dimensionality of input vectors.
out_size (int): Dimensionality of hidden states and output vectors.
dropout (float): Dropout ratio.
.. seealso::
:func:`chainer.functions.n_step_birnn`
"""
n_weights = 2
use_bi_direction = True
def rnn(self, *args):
return rnn.n_step_birnn(*args, activation='relu')
@property
def n_cells(self):
return 1