-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
rnn.py
1979 lines (1663 loc) · 78.2 KB
/
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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.
import math
from collections.abc import Sequence
from functools import partial, reduce
import numpy as np
import paddle
from paddle import _C_ops, _legacy_C_ops, framework, in_dynamic_mode
from paddle.common_ops_import import Variable
from paddle.fluid.data_feeder import check_type, check_variable_and_dtype
from paddle.fluid.dygraph.base import NON_PERSISTABLE_VAR_NAME_SUFFIX
from paddle.fluid.framework import (
default_startup_program,
in_dygraph_mode,
program_guard,
)
from paddle.fluid.layers import control_flow
from paddle.framework import core
from paddle.nn import functional as F
from paddle.nn import initializer as I
from paddle.tensor.manipulation import tensor_array_to_tensor
from .container import LayerList
from .layers import Layer
__all__ = []
def rnn(
cell,
inputs,
initial_states=None,
sequence_length=None,
time_major=False,
is_reverse=False,
**kwargs,
):
r"""
rnn creates a recurrent neural network specified by RNNCell `cell`,
which performs :code:`cell.call()` (for dygraph mode :code:`cell.forward`)
repeatedly until reaches to the maximum length of `inputs`.
Parameters:
cell(RNNCellBase): An instance of `RNNCellBase`.
inputs(Tensor): the input sequences.
If time_major is True, the shape is
`[time_steps, batch_size, input_size]`
else the shape is `[batch_size, time_steps, input_size]`.
initial_states(Tensor|tuple|list, optional): the initial state of the
rnn cell. Tensor or a possibly nested structure of tensors. If not
provided, `cell.get_initial_states` would be called to produce
the initial state. Defaults to None.
sequence_length (Tensor, optional): shape `[batch_size]`, dtype: int64
or int32. The valid lengths of input sequences. Defaults to None.
If `sequence_length` is not None, the inputs are treated as
padded sequences. In each input sequence, elements whose time step
index are not less than the valid length are treated as paddings.
time_major (bool, optional): Whether the first dimension of the input means the
time steps. Defaults to False.
is_reverse (bool, optional): Indicate whether to calculate in the reverse
order of input sequences. Defaults to False.
**kwargs: Additional keyword arguments to pass to `forward` of the cell.
Returns:
outputs (Tensor|list|tuple): the output sequence. Tensor or nested
structure of Tensors.
If `time_major` is True, the shape of each tensor in outpus is
`[time_steps, batch_size, hidden_size]`, else
`[batch_size, time_steps, hidden_size]`.
final_states (Tensor|list|tuple): final states. A (possibly nested structure of)
tensor[s], representing the final state for RNN. It has the same
structure of intial state. Each tensor in final states has the same
shape and dtype as the corresponding tensor in initial states.
Examples:
.. code-block:: python
import paddle
paddle.disable_static()
cell = paddle.nn.SimpleRNNCell(16, 32)
inputs = paddle.rand((4, 23, 16))
prev_h = paddle.randn((4, 32))
outputs, final_states = paddle.nn.layer.rnn(cell, inputs, prev_h)
"""
if in_dygraph_mode():
return _rnn_dynamic_graph(
cell,
inputs,
initial_states,
sequence_length,
time_major,
is_reverse,
**kwargs,
)
else:
return _rnn_static_graph(
cell,
inputs,
initial_states,
sequence_length,
time_major,
is_reverse,
**kwargs,
)
class ArrayWrapper:
def __init__(self, x):
self.array = [x]
def append(self, x):
self.array.append(x)
return self
def __getitem__(self, item):
return self.array.__getitem__(item)
def _maybe_copy(state, new_state, step_mask):
"""update rnn state or just pass the old state through"""
new_state = paddle.tensor.math._multiply_with_axis(
new_state, step_mask, axis=0
) + paddle.tensor.math._multiply_with_axis(state, (1 - step_mask), axis=0)
return new_state
def _transpose_batch_time(x):
perm = [1, 0] + list(range(2, len(x.shape)))
return paddle.transpose(x, perm)
def _rnn_dynamic_graph(
cell,
inputs,
initial_states=None,
sequence_length=None,
time_major=False,
is_reverse=False,
**kwargs,
):
time_step_index = 0 if time_major else 1
flat_inputs = paddle.utils.flatten(inputs)
time_steps = flat_inputs[0].shape[time_step_index]
if initial_states is None:
initial_states = cell.get_initial_states(
batch_ref=inputs, batch_dim_idx=1 if time_major else 0
)
if not time_major:
inputs = paddle.utils.map_structure(_transpose_batch_time, inputs)
if sequence_length is not None:
mask = paddle.static.nn.sequence_lod.sequence_mask(
sequence_length, maxlen=time_steps, dtype=inputs.dtype
)
mask = paddle.transpose(mask, [1, 0])
if is_reverse:
inputs = paddle.utils.map_structure(
lambda x: paddle.reverse(x, axis=[0]), inputs
)
mask = (
paddle.reverse(mask, axis=[0])
if sequence_length is not None
else None
)
states = initial_states
outputs = []
for i in range(time_steps):
step_inputs = paddle.utils.map_structure(lambda x: x[i], inputs)
step_outputs, new_states = cell(step_inputs, states, **kwargs)
if sequence_length is not None:
new_states = paddle.utils.map_structure(
partial(_maybe_copy, step_mask=mask[i]), states, new_states
)
states = new_states
outputs = (
paddle.utils.map_structure(lambda x: ArrayWrapper(x), step_outputs)
if i == 0
else paddle.utils.map_structure(
lambda x, x_array: x_array.append(x), step_outputs, outputs
)
)
final_outputs = paddle.utils.map_structure(
lambda x: paddle.stack(x.array, axis=time_step_index), outputs
)
if is_reverse:
final_outputs = paddle.utils.map_structure(
lambda x: paddle.reverse(x, axis=time_step_index), final_outputs
)
final_states = new_states
return final_outputs, final_states
def _rnn_static_graph(
cell,
inputs,
initial_states=None,
sequence_length=None,
time_major=False,
is_reverse=False,
**kwargs,
):
check_type(inputs, 'inputs', (Variable, list, tuple), 'rnn')
if isinstance(inputs, (list, tuple)):
for i, input_x in enumerate(inputs):
check_variable_and_dtype(
input_x, 'inputs[' + str(i) + ']', ['float32', 'float64'], 'rnn'
)
check_type(
initial_states,
'initial_states',
(Variable, list, tuple, type(None)),
'rnn',
)
check_type(
sequence_length, 'sequence_length', (Variable, type(None)), 'rnn'
)
def _switch_grad(x, stop=False):
x.stop_gradient = stop
return x
if initial_states is None:
initial_states = cell.get_initial_states(
batch_ref=inputs, batch_dim_idx=1 if time_major else 0
)
initial_states = paddle.utils.map_structure(_switch_grad, initial_states)
if not time_major:
inputs = paddle.utils.map_structure(_transpose_batch_time, inputs)
max_seq_len = paddle.shape(paddle.utils.flatten(inputs)[0])[0]
if sequence_length:
mask = paddle.static.nn.sequence_lod.sequence_mask(
sequence_length,
maxlen=max_seq_len,
dtype=paddle.utils.flatten(initial_states)[0].dtype,
)
mask = paddle.transpose(mask, [1, 0])
if is_reverse:
inputs = paddle.utils.map_structure(
lambda x: paddle.reverse(x, axis=[0]), inputs
)
mask = paddle.reverse(mask, axis=[0]) if sequence_length else None
with paddle.fluid.framework.device_guard("cpu"):
start_i = paddle.zeros([], dtype="int64")
end = max_seq_len
end = paddle.cast(end, "int64")
cond = start_i < end
while_op = control_flow.While(cond)
out_array = paddle.tensor.create_array(
dtype=paddle.utils.flatten(inputs)[0].dtype
)
init_array = paddle.utils.map_structure(
lambda x: paddle.tensor.create_array(dtype=x.dtype), initial_states
)
paddle.utils.map_structure(
lambda x, y: paddle.tensor.array_write(x, start_i, y),
initial_states,
init_array,
)
with while_op.block():
step_in = inputs[start_i]
# step_in = paddle.fluid.layers.Print( step_in, message="step in")
pre_state = paddle.utils.map_structure(
lambda x: paddle.tensor.array_read(x, start_i), init_array
)
outputs, new_states = cell(step_in, pre_state, **kwargs)
assert isinstance(outputs, paddle.fluid.framework.Variable)
paddle.utils.assert_same_structure(new_states, pre_state)
if sequence_length:
step_mask = paddle.unsqueeze(mask[start_i], 1)
# new_states = map_structure(
# partial(_maybe_copy, step_mask=step_mask),
# pre_state, new_states
# )
new_states = paddle.utils.map_structure(
lambda x, y: (x * step_mask + y * (1.0 - step_mask)),
new_states,
pre_state,
)
paddle.tensor.array_write(outputs, start_i, out_array)
with paddle.fluid.framework.device_guard("cpu"):
start_i = paddle.tensor.increment(x=start_i, value=1)
paddle.utils.map_structure(
lambda x, y: paddle.tensor.array_write(x, start_i, y),
new_states,
init_array,
)
with paddle.fluid.framework.device_guard("cpu"):
new_cond = paddle.tensor.less_than(start_i, end)
paddle.assign(new_cond, cond)
out, _ = tensor_array_to_tensor(out_array, axis=0, use_stack=True)
all_state = paddle.utils.map_structure(
lambda x: tensor_array_to_tensor(x, axis=0, use_stack=True)[0],
init_array,
)
final_outputs = out
final_states = paddle.utils.map_structure(lambda x: x[-1], all_state)
if is_reverse:
final_outputs = paddle.utils.map_structure(
lambda x: paddle.reverse(x, axis=[0]), final_outputs
)
if not time_major:
final_outputs = paddle.utils.map_structure(
_transpose_batch_time, final_outputs
)
return (final_outputs, final_states)
def birnn(
cell_fw,
cell_bw,
inputs,
initial_states=None,
sequence_length=None,
time_major=False,
**kwargs,
):
r"""
birnn creates a bidirectional recurrent neural network specified by
RNNCell `cell_fw` and `cell_bw`, which performs :code:`cell.call()`
(for dygraph mode :code:`cell.forward`) repeatedly until reaches to
the maximum length of `inputs` and then concat the outputs for both RNNs
along the last axis.
Parameters:
cell_fw(RNNCellBase): An instance of `RNNCellBase`.
cell_bw(RNNCellBase): An instance of `RNNCellBase`.
inputs(Tensor): the input sequences.
If time_major is True, the shape is
`[time_steps, batch_size, input_size]`
else the shape is `[batch_size, time_steps, input_size]`.
initial_states(tuple, optional): A tuple of initial states of
`cell_fw` and `cell_bw`.
If not provided, `cell.get_initial_states` would be called to
produce initial state for each cell. Defaults to None.
sequence_length (Tensor, optional): shape `[batch_size]`, dtype: int64
or int32. The valid lengths of input sequences. Defaults to None.
If `sequence_length` is not None, the inputs are treated as
padded sequences. In each input sequence, elements whose time step
index are not less than the valid length are treated as paddings.
time_major (bool): Whether the first dimension of the input means the
time steps. Defaults to False.
**kwargs: Additional keyword arguments to pass to `forward` of each cell.
Returns:
outputs (Tensor): the outputs of the bidirectional RNN. It is the
concatenation of the outputs from the forward RNN and backward
RNN along the last axis.
If time major is True, the shape is `[time_steps, batch_size, size]`,
else the shape is `[batch_size, time_steps, size]`, where size is
`cell_fw.hidden_size + cell_bw.hidden_size`.
final_states (tuple): A tuple of the final states of the forward
cell and backward cell.
Examples:
.. code-block:: python
import paddle
paddle.disable_static()
cell_fw = paddle.nn.LSTMCell(16, 32)
cell_bw = paddle.nn.LSTMCell(16, 32)
inputs = paddle.rand((4, 23, 16))
hf, cf = paddle.rand((4, 32)), paddle.rand((4, 32))
hb, cb = paddle.rand((4, 32)), paddle.rand((4, 32))
initial_states = ((hf, cf), (hb, cb))
outputs, final_states = paddle.nn.layer.birnn(
cell_fw, cell_bw, inputs, initial_states)
"""
if initial_states is None:
states_fw = cell_fw.get_initial_states(
batch_ref=inputs, batch_dim_idx=1 if time_major else 0
)
states_bw = cell_fw.get_initial_states(
batch_ref=inputs, batch_dim_idx=1 if time_major else 0
)
else:
states_fw, states_bw = initial_states
outputs_fw, states_fw = rnn(
cell_fw,
inputs,
states_fw,
sequence_length,
time_major=time_major,
**kwargs,
)
outputs_bw, states_bw = rnn(
cell_bw,
inputs,
states_bw,
sequence_length,
time_major=time_major,
is_reverse=True,
**kwargs,
)
outputs = paddle.utils.map_structure(
lambda x, y: paddle.concat([x, y], -1), outputs_fw, outputs_bw
)
final_states = (states_fw, states_bw)
return outputs, final_states
def split_states(states, bidirectional=False, state_components=1):
r"""
Split states of RNN network into possibly nested list or tuple of
states of each RNN cells of the RNN network.
Parameters:
states (Tensor|tuple|list): the concatenated states for RNN network.
When `state_components` is 1, states in a Tensor with shape
`(L*D, N, C)` where `L` is the number of layers of the RNN
network, `D` is the number of directions of the RNN network(1
for unidirectional RNNs and 2 for bidirectional RNNs), `N` is
the batch size of the input to the RNN network, `C` is the
hidden size of the RNN network.
When `state_components` is larger than 1, `states` is a tuple of
`state_components` Tensors that meet the requirements described
above.
For SimpleRNNs and GRUs, `state_components` is 1, and for LSTMs,
`state_components` is 2.
bidirectional (bool): whether the state is of a bidirectional RNN
network. Defaults to False.
state_components (int): the number of the components of the states. see
`states` above. Defaults to 1.
Returns:
A nested list or tuple of RNN cell states.
If `bidirectional` is True, it can be indexed twice to get an RNN
cell state. The first index indicates the layer, the second index
indicates the direction.
If `bidirectional` is False, it can be indexed once to get an RNN
cell state. The index indicates the layer.
Note that if `state_components` is larger than 1, an RNN cell state
can be indexed one more time to get a tensor of shape(N, C), where
`N` is the batch size of the input to the RNN cell, and `C` is the
hidden size of the RNN cell.
"""
if state_components == 1:
states = paddle.unstack(states)
if not bidirectional:
return states
else:
return list(zip(states[::2], states[1::2]))
else:
assert len(states) == state_components
states = tuple([paddle.unstack(item) for item in states])
if not bidirectional:
return list(zip(*states))
else:
states = list(zip(*states))
return list(zip(states[::2], states[1::2]))
def concat_states(states, bidirectional=False, state_components=1):
r"""
Concatenate a possibly nested list or tuple of RNN cell states into a
compact form.
Parameters:
states (list|tuple): a possibly nested list or tuple of RNN cell
states.
If `bidirectional` is True, it can be indexed twice to get an
RNN cell state. The first index indicates the layer, the second
index indicates the direction.
If `bidirectional` is False, it can be indexed once to get an RNN
cell state. The index indicates the layer.
Note that if `state_components` is larger than 1, an RNN cell
state can be indexed one more time to get a tensor of shape(N, C),
where `N` is the batch size of the input to the RNN cell, and
`C` is the hidden size of the RNN cell.
bidirectional (bool): whether the state is of a bidirectional RNN
network. Defaults to False.
state_components (int): the number of the components of the states. see
`states` above. Defaults to 1.
Returns:
Concatenated states for RNN network.
When `state_components` is 1, states in a Tensor with shape
`(L\*D, N, C)` where `L` is the number of layers of the RNN
network, `D` is the number of directions of the RNN network(1 for
unidirectional RNNs and 2 for bidirectional RNNs), `N` is the batch
size of the input to the RNN network, `C` is the hidden size of the
RNN network.
"""
if state_components == 1:
return paddle.stack(paddle.utils.flatten(states))
else:
states = paddle.utils.flatten(states)
componnets = []
for i in range(state_components):
componnets.append(states[i::state_components])
return tuple([paddle.stack(item) for item in componnets])
class RNNCellBase(Layer):
r"""
RNNCellBase is the base class for abstraction representing the calculations
mapping the input and state to the output and new state. It is suitable to
and mostly used in RNN.
"""
def get_initial_states(
self, batch_ref, shape=None, dtype=None, init_value=0.0, batch_dim_idx=0
):
r"""
Generate initialized states according to provided shape, data type and
value.
Parameters:
batch_ref (Tensor): A tensor, which shape would be used to
determine the batch size, which is used to generate initial
states. For `batch_ref`'s shape d, `d[batch_dim_idx]` is
treated as batch size.
shape (list|tuple, optional): A (possibly nested structure of) shape[s],
where a shape is a list/tuple of integer. `-1` (for batch size)
will be automatically prepended if a shape does not starts with
it. If None, property `state_shape` will be used. Defaults to
None.
dtype (str|list|tuple, optional): A (possibly nested structure of)
data type[s]. The structure must be same as that of `shape`,
except when all tensors' in states has the same data type, a
single data type can be used. If None and property `cell.state_shape`
is not available, current default floating type of paddle is
used. Defaults to None.
init_value (float, optional): A float value used to initialize states.
Defaults to 0.
batch_dim_idx (int, optional): An integer indicating which
dimension of the of `batch_ref` represents batch. Defaults to 0.
Returns:
init_states (Tensor|tuple|list): tensor of the provided shape and
dtype, or list of tensors that each satisfies the requirements,
packed in the same structure as `shape` and `type` does.
"""
# TODO: use inputs and batch_size
batch_ref = paddle.utils.flatten(batch_ref)[0]
def _is_shape_sequence(seq):
"""For shape, list/tuple of integer is the finest-grained objection"""
if isinstance(seq, (list, tuple)):
if reduce(
lambda flag, x: isinstance(x, int) and flag, seq, True
):
return False
# TODO: Add check for the illegal
if isinstance(seq, dict):
return True
return isinstance(seq, Sequence) and not isinstance(seq, str)
class Shape:
def __init__(self, shape):
self.shape = shape if shape[0] == -1 else ([-1] + list(shape))
# nested structure of shapes
states_shapes = self.state_shape if shape is None else shape
is_sequence_ori = paddle.utils.layers_utils.is_sequence
paddle.utils.layers_utils.is_sequence = _is_shape_sequence
states_shapes = paddle.utils.map_structure(
lambda shape: Shape(shape), states_shapes
)
paddle.utils.layers_utils.is_sequence = is_sequence_ori
# nested structure of dtypes
try:
states_dtypes = self.state_dtype if dtype is None else dtype
except NotImplementedError:
states_dtypes = framework.get_default_dtype()
if len(paddle.utils.flatten(states_dtypes)) == 1:
dtype = paddle.utils.flatten(states_dtypes)[0]
states_dtypes = paddle.utils.map_structure(
lambda shape: dtype, states_shapes
)
init_states = paddle.utils.map_structure(
lambda shape, dtype: paddle.fluid.layers.fill_constant_batch_size_like(
input=batch_ref,
shape=shape.shape,
dtype=dtype,
value=init_value,
input_dim_idx=batch_dim_idx,
),
states_shapes,
states_dtypes,
)
return init_states
@property
def state_shape(self):
r"""
Abstract method (property).
Used to initialize states.
A (possiblely nested structure of) shape[s], where a shape is a
list/tuple of integers (-1 for batch size would be automatically
inserted into a shape if shape is not started with it).
Not necessary to be implemented if states are not initialized by
`get_initial_states` or the `shape` argument is provided when using
`get_initial_states`.
"""
raise NotImplementedError(
"Please add implementaion for `state_shape` in the used cell."
)
@property
def state_dtype(self):
r"""
Abstract method (property).
Used to initialize states.
A (possiblely nested structure of) data types[s]. The structure must be
same as that of `shape`, except when all tensors' in states has the same
data type, a signle data type can be used.
Not necessary to be implemented if states are not initialized
by `get_initial_states` or the `dtype` argument is provided when using
`get_initial_states`.
"""
raise NotImplementedError(
"Please add implementaion for `state_dtype` in the used cell."
)
class SimpleRNNCell(RNNCellBase):
r"""
Elman RNN (SimpleRNN) cell. Given the inputs and previous states, it
computes the outputs and updates states.
The formula used is as follows:
.. math::
h_{t} & = act(W_{ih}x_{t} + b_{ih} + W_{hh}h_{t-1} + b_{hh})
y_{t} & = h_{t}
where :math:`act` is for :attr:`activation`.
Please refer to `Finding Structure in Time
<https://crl.ucsd.edu/~elman/Papers/fsit.pdf>`_ for more details.
Parameters:
input_size (int): The input size.
hidden_size (int): The hidden size.
activation (str, optional): The activation in the SimpleRNN cell.
It can be `tanh` or `relu`. Defaults to `tanh`.
weight_ih_attr (ParamAttr, optional): The parameter attribute for
:math:`weight_ih`. Default: None.
weight_hh_attr(ParamAttr, optional): The parameter attribute for
:math:`weight_hh`. Default: None.
bias_ih_attr (ParamAttr, optional): The parameter attribute for the
:math:`bias_ih`. Default: None.
bias_hh_attr (ParamAttr, optional): The parameter attribute for the
:math:`bias_hh`. Default: None.
name (str, optional): Name for the operation (optional, default is
None). For more information, please refer to :ref:`api_guide_Name`.
Variables:
- **weight_ih** (Parameter): shape (hidden_size, input_size), input to hidden weight, corresponding to :math:`W_{ih}` in the formula.
- **weight_hh** (Parameter): shape (hidden_size, hidden_size), hidden to hidden weight, corresponding to :math:`W_{hh}` in the formula.
- **bias_ih** (Parameter): shape (hidden_size, ), input to hidden bias, corresponding to :math:`b_{ih}` in the formula.
- **bias_hh** (Parameter): shape (hidden_size, ), hidden to hidden bias, corresponding to :math:`b_{hh}` in the formula.
Inputs:
- **inputs** (Tensor): shape `[batch_size, input_size]`, the input, corresponding to :math:`x_{t}` in the formula.
- **states** (Tensor, optional): shape `[batch_size, hidden_size]`, the previous hidden state, corresponding to :math:`h_{t-1}` in the formula. When states is None, zero state is used. Defaults to None.
Returns:
- **outputs** (Tensor): shape `[batch_size, hidden_size]`, the output, corresponding to :math:`h_{t}` in the formula.
- **states** (Tensor): shape `[batch_size, hidden_size]`, the new hidden state, corresponding to :math:`h_{t}` in the formula.
Notes:
All the weights and bias are initialized with `Uniform(-std, std)` by default. Where std = :math:`\frac{1}{\sqrt{hidden\_size}}`. For more information about parameter initialization, please refer to :ref:`api_fluid_ParamAttr`.
Examples:
.. code-block:: python
import paddle
x = paddle.randn((4, 16))
prev_h = paddle.randn((4, 32))
cell = paddle.nn.SimpleRNNCell(16, 32)
y, h = cell(x, prev_h)
print(y.shape)
#[4,32]
"""
def __init__(
self,
input_size,
hidden_size,
activation="tanh",
weight_ih_attr=None,
weight_hh_attr=None,
bias_ih_attr=None,
bias_hh_attr=None,
name=None,
):
super().__init__()
if hidden_size <= 0:
raise ValueError(
"hidden_size of {} must be greater than 0, but now equals to {}".format(
self.__class__.__name__, hidden_size
)
)
std = 1.0 / math.sqrt(hidden_size)
self.weight_ih = self.create_parameter(
(hidden_size, input_size),
weight_ih_attr,
default_initializer=I.Uniform(-std, std),
)
self.weight_hh = self.create_parameter(
(hidden_size, hidden_size),
weight_hh_attr,
default_initializer=I.Uniform(-std, std),
)
self.bias_ih = self.create_parameter(
(hidden_size,),
bias_ih_attr,
is_bias=True,
default_initializer=I.Uniform(-std, std),
)
self.bias_hh = self.create_parameter(
(hidden_size,),
bias_hh_attr,
is_bias=True,
default_initializer=I.Uniform(-std, std),
)
self.input_size = input_size
self.hidden_size = hidden_size
if activation not in ["tanh", "relu"]:
raise ValueError(
"activation for SimpleRNNCell should be tanh or relu, "
"but get {}".format(activation)
)
self.activation = activation
self._activation_fn = paddle.tanh if activation == "tanh" else F.relu
def forward(self, inputs, states=None):
if states is None:
states = self.get_initial_states(inputs, self.state_shape)
pre_h = states
i2h = paddle.matmul(inputs, self.weight_ih, transpose_y=True)
if self.bias_ih is not None:
i2h += self.bias_ih
h2h = paddle.matmul(pre_h, self.weight_hh, transpose_y=True)
if self.bias_hh is not None:
h2h += self.bias_hh
h = self._activation_fn(i2h + h2h)
return h, h
@property
def state_shape(self):
return (self.hidden_size,)
def extra_repr(self):
s = '{input_size}, {hidden_size}'
if self.activation != "tanh":
s += ', activation={activation}'
return s.format(**self.__dict__)
class LSTMCell(RNNCellBase):
r"""
Long-Short Term Memory(LSTM) RNN cell. Given the inputs and previous states,
it computes the outputs and updates states.
The formula used is as follows:
.. math::
i_{t} & = \sigma(W_{ii}x_{t} + b_{ii} + W_{hi}h_{t-1} + b_{hi})
f_{t} & = \sigma(W_{if}x_{t} + b_{if} + W_{hf}h_{t-1} + b_{hf})
o_{t} & = \sigma(W_{io}x_{t} + b_{io} + W_{ho}h_{t-1} + b_{ho})
\widetilde{c}_{t} & = \tanh (W_{ig}x_{t} + b_{ig} + W_{hg}h_{t-1} + b_{hg})
c_{t} & = f_{t} * c_{t-1} + i_{t} * \widetilde{c}_{t}
h_{t} & = o_{t} * \tanh(c_{t})
y_{t} & = h_{t}
where :math:`\sigma` is the sigmoid fucntion, and * is the elemetwise
multiplication operator.
Please refer to `An Empirical Exploration of Recurrent Network Architectures
<http://proceedings.mlr.press/v37/jozefowicz15.pdf>`_ for more details.
Parameters:
input_size (int): The input size.
hidden_size (int): The hidden size.
weight_ih_attr(ParamAttr, optional): The parameter attribute for
`weight_ih`. Default: None.
weight_hh_attr(ParamAttr, optional): The parameter attribute for
`weight_hh`. Default: None.
bias_ih_attr (ParamAttr, optional): The parameter attribute for the
`bias_ih`. Default: None.
bias_hh_attr (ParamAttr, optional): The parameter attribute for the
`bias_hh`. Default: None.
name (str, optional): Name for the operation (optional, default is
None). For more information, please refer to :ref:`api_guide_Name`.
Variables:
- **weight_ih** (Parameter): shape (4 * hidden_size, input_size), input to hidden weight, which corresponds to the concatenation of :math:`W_{ii}, W_{if}, W_{ig}, W_{io}` in the formula.
- **weight_hh** (Parameter): shape (4 * hidden_size, hidden_size), hidden to hidden weight, which corresponds to the concatenation of :math:`W_{hi}, W_{hf}, W_{hg}, W_{ho}` in the formula.
- **bias_ih** (Parameter): shape (4 * hidden_size, ), input to hidden bias, which corresponds to the concatenation of :math:`b_{ii}, b_{if}, b_{ig}, b_{io}` in the formula.
- **bias_hh** (Parameter): shape (4 * hidden_size, ), hidden to hidden bias, swhich corresponds to the concatenation of :math:`b_{hi}, b_{hf}, b_{hg}, b_{ho}` in the formula.
Inputs:
- **inputs** (Tensor): shape `[batch_size, input_size]`, the input, corresponding to :math:`x_t` in the formula.
- **states** (list|tuple, optional): a list/tuple of two tensors, each of shape `[batch_size, hidden_size]`, the previous hidden state, corresponding to :math:`h_{t-1}, c_{t-1}` in the formula. When states is None, zero state is used. Defaults to None.
Returns:
- **outputs** (Tensor): shape `[batch_size, hidden_size]`, the output, corresponding to :math:`h_{t}` in the formula.
- **states** (tuple): a tuple of two tensors, each of shape `[batch_size, hidden_size]`, the new hidden states, corresponding to :math:`h_{t}, c_{t}` in the formula.
Notes:
All the weights and bias are initialized with `Uniform(-std, std)` by
default. Where std = :math:`\frac{1}{\sqrt{hidden\_size}}`. For more
information about parameter initialization, please refer to :ref:`api_fluid_ParamAttr`.
Examples:
.. code-block:: python
import paddle
x = paddle.randn((4, 16))
prev_h = paddle.randn((4, 32))
prev_c = paddle.randn((4, 32))
cell = paddle.nn.LSTMCell(16, 32)
y, (h, c) = cell(x, (prev_h, prev_c))
print(y.shape)
print(h.shape)
print(c.shape)
#[4,32]
#[4,32]
#[4,32]
"""
def __init__(
self,
input_size,
hidden_size,
weight_ih_attr=None,
weight_hh_attr=None,
bias_ih_attr=None,
bias_hh_attr=None,
name=None,
):
super().__init__()
if hidden_size <= 0:
raise ValueError(
"hidden_size of {} must be greater than 0, but now equals to {}".format(
self.__class__.__name__, hidden_size
)
)
std = 1.0 / math.sqrt(hidden_size)
self.weight_ih = self.create_parameter(
(4 * hidden_size, input_size),
weight_ih_attr,
default_initializer=I.Uniform(-std, std),
)
self.weight_hh = self.create_parameter(
(4 * hidden_size, hidden_size),
weight_hh_attr,
default_initializer=I.Uniform(-std, std),
)
self.bias_ih = self.create_parameter(
(4 * hidden_size,),
bias_ih_attr,
is_bias=True,
default_initializer=I.Uniform(-std, std),
)
self.bias_hh = self.create_parameter(
(4 * hidden_size,),
bias_hh_attr,
is_bias=True,
default_initializer=I.Uniform(-std, std),
)
self.hidden_size = hidden_size
self.input_size = input_size
self._gate_activation = F.sigmoid
self._activation = paddle.tanh
def forward(self, inputs, states=None):
if states is None:
states = self.get_initial_states(inputs, self.state_shape)
pre_hidden, pre_cell = states
gates = paddle.matmul(inputs, self.weight_ih, transpose_y=True)
if self.bias_ih is not None:
gates = gates + self.bias_ih
gates += paddle.matmul(pre_hidden, self.weight_hh, transpose_y=True)
if self.bias_hh is not None:
gates = gates + self.bias_hh
chunked_gates = paddle.split(gates, num_or_sections=4, axis=-1)
i = self._gate_activation(chunked_gates[0])
f = self._gate_activation(chunked_gates[1])
o = self._gate_activation(chunked_gates[3])
c = f * pre_cell + i * self._activation(chunked_gates[2])
h = o * self._activation(c)
return h, (h, c)
@property
def state_shape(self):
r"""
The `state_shape` of LSTMCell is a tuple with two shapes:
`((hidden_size, ), (hidden_size,))`. (-1 for batch size would be
automatically inserted into shape). These two shapes correspond
to :math:`h_{t-1}` and :math:`c_{t-1}` separately.
"""
return ((self.hidden_size,), (self.hidden_size,))
def extra_repr(self):
return '{input_size}, {hidden_size}'.format(**self.__dict__)
class GRUCell(RNNCellBase):
r"""
Gated Recurrent Unit (GRU) RNN cell. Given the inputs and previous states,
it computes the outputs and updates states.
The formula for GRU used is as follows:
.. math::
r_{t} & = \sigma(W_{ir}x_{t} + b_{ir} + W_{hr}h_{t-1} + b_{hr})
z_{t} & = \sigma(W_{iz}x_{t} + b_{iz} + W_{hz}h_{t-1} + b_{hz})
\widetilde{h}_{t} & = \tanh(W_{ic}x_{t} + b_{ic} + r_{t} * (W_{hc}h_{t-1} + b_{hc}))
h_{t} & = z_{t} * h_{t-1} + (1 - z_{t}) * \widetilde{h}_{t}
y_{t} & = h_{t}