forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrnn_cell.py
1978 lines (1719 loc) · 66.4 KB
/
rnn_cell.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
## @package rnn_cell
# Module caffe2.python.rnn_cell
import functools
import inspect
import logging
import numpy as np
import random
from caffe2.proto import caffe2_pb2
from caffe2.python.attention import (
apply_dot_attention,
apply_recurrent_attention,
apply_regular_attention,
apply_soft_coverage_attention,
AttentionType,
)
from caffe2.python import core, recurrent, workspace, brew, scope, utils
from caffe2.python.modeling.parameter_sharing import ParameterSharing
from caffe2.python.modeling.parameter_info import ParameterTags
from caffe2.python.modeling.initializers import Initializer
from caffe2.python.model_helper import ModelHelper
def _RectifyName(blob_reference_or_name):
if blob_reference_or_name is None:
return None
if isinstance(blob_reference_or_name, str):
return core.ScopedBlobReference(blob_reference_or_name)
if not isinstance(blob_reference_or_name, core.BlobReference):
raise Exception("Unknown blob reference type")
return blob_reference_or_name
def _RectifyNames(blob_references_or_names):
if blob_references_or_names is None:
return None
return [_RectifyName(i) for i in blob_references_or_names]
class RNNCell:
'''
Base class for writing recurrent / stateful operations.
One needs to implement 2 methods: apply_override
and get_state_names_override.
As a result base class will provice apply_over_sequence method, which
allows you to apply recurrent operations over a sequence of any length.
As optional you could add input and output preparation steps by overriding
corresponding methods.
'''
def __init__(self, name=None, forward_only=False, initializer=None):
self.name = name
self.recompute_blobs = []
self.forward_only = forward_only
self._initializer = initializer
@property
def initializer(self):
return self._initializer
@initializer.setter
def initializer(self, value):
self._initializer = value
def scope(self, name):
return self.name + '/' + name if self.name is not None else name
def apply_over_sequence(
self,
model,
inputs,
seq_lengths=None,
initial_states=None,
outputs_with_grads=None,
):
if initial_states is None:
with scope.NameScope(self.name):
if self.initializer is None:
raise Exception("Either initial states "
"or initializer have to be set")
initial_states = self.initializer.create_states(model)
preprocessed_inputs = self.prepare_input(model, inputs)
step_model = ModelHelper(name=self.name, param_model=model)
input_t, timestep = step_model.net.AddScopedExternalInputs(
'input_t',
'timestep',
)
utils.raiseIfNotEqual(
len(initial_states), len(self.get_state_names()),
"Number of initial state values provided doesn't match the number "
"of states"
)
states_prev = step_model.net.AddScopedExternalInputs(*[
s + '_prev' for s in self.get_state_names()
])
states = self._apply(
model=step_model,
input_t=input_t,
seq_lengths=seq_lengths,
states=states_prev,
timestep=timestep,
)
external_outputs = set(step_model.net.Proto().external_output)
for state in states:
if state not in external_outputs:
step_model.net.AddExternalOutput(state)
if outputs_with_grads is None:
outputs_with_grads = [self.get_output_state_index() * 2]
# states_for_all_steps consists of combination of
# states gather for all steps and final states. It looks like this:
# (state_1_all, state_1_final, state_2_all, state_2_final, ...)
states_for_all_steps = recurrent.recurrent_net(
net=model.net,
cell_net=step_model.net,
inputs=[(input_t, preprocessed_inputs)],
initial_cell_inputs=list(zip(states_prev, initial_states)),
links=dict(zip(states_prev, states)),
timestep=timestep,
scope=self.name,
forward_only=self.forward_only,
outputs_with_grads=outputs_with_grads,
recompute_blobs_on_backward=self.recompute_blobs,
)
output = self._prepare_output_sequence(
model,
states_for_all_steps,
)
return output, states_for_all_steps
def apply(self, model, input_t, seq_lengths, states, timestep):
input_t = self.prepare_input(model, input_t)
states = self._apply(
model, input_t, seq_lengths, states, timestep)
output = self._prepare_output(model, states)
return output, states
def _apply(
self,
model, input_t, seq_lengths, states, timestep, extra_inputs=None
):
'''
This method uses apply_override provided by a custom cell.
On the top it takes care of applying self.scope() to all the outputs.
While all the inputs stay within the scope this function was called
from.
'''
args = self._rectify_apply_inputs(
input_t, seq_lengths, states, timestep, extra_inputs)
with core.NameScope(self.name):
return self.apply_override(model, *args)
def _rectify_apply_inputs(
self, input_t, seq_lengths, states, timestep, extra_inputs):
'''
Before applying a scope we make sure that all external blob names
are converted to blob reference. So further scoping doesn't affect them
'''
input_t, seq_lengths, timestep = _RectifyNames(
[input_t, seq_lengths, timestep])
states = _RectifyNames(states)
if extra_inputs:
extra_input_names, extra_input_sizes = zip(*extra_inputs)
extra_inputs = _RectifyNames(extra_input_names)
extra_inputs = zip(extra_input_names, extra_input_sizes)
arg_names = inspect.getargspec(self.apply_override).args
rectified = [input_t, seq_lengths, states, timestep]
if 'extra_inputs' in arg_names:
rectified.append(extra_inputs)
return rectified
def apply_override(
self,
model, input_t, seq_lengths, timestep, extra_inputs=None,
):
'''
A single step of a recurrent network to be implemented by each custom
RNNCell.
model: ModelHelper object new operators would be added to
input_t: singlse input with shape (1, batch_size, input_dim)
seq_lengths: blob containing sequence lengths which would be passed to
LSTMUnit operator
states: previous recurrent states
timestep: current recurrent iteration. Could be used together with
seq_lengths in order to determine, if some shorter sequences
in the batch have already ended.
extra_inputs: list of tuples (input, dim). specifies additional input
which is not subject to prepare_input(). (useful when a cell is a
component of a larger recurrent structure, e.g., attention)
'''
raise NotImplementedError('Abstract method')
def prepare_input(self, model, input_blob):
'''
If some operations in _apply method depend only on the input,
not on recurrent states, they could be computed in advance.
model: ModelHelper object new operators would be added to
input_blob: either the whole input sequence with shape
(sequence_length, batch_size, input_dim) or a single input with shape
(1, batch_size, input_dim).
'''
return input_blob
def get_output_state_index(self):
'''
Return index into state list of the "primary" step-wise output.
'''
return 0
def get_state_names(self):
'''
Returns recurrent state names with self.name scoping applied
'''
return [self.scope(name) for name in self.get_state_names_override()]
def get_state_names_override(self):
'''
Override this function in your custom cell.
It should return the names of the recurrent states.
It's required by apply_over_sequence method in order to allocate
recurrent states for all steps with meaningful names.
'''
raise NotImplementedError('Abstract method')
def get_output_dim(self):
'''
Specifies the dimension (number of units) of stepwise output.
'''
raise NotImplementedError('Abstract method')
def _prepare_output(self, model, states):
'''
Allows arbitrary post-processing of primary output.
'''
return states[self.get_output_state_index()]
def _prepare_output_sequence(self, model, state_outputs):
'''
Allows arbitrary post-processing of primary sequence output.
(Note that state_outputs alternates between full-sequence and final
output for each state, thus the index multiplier 2.)
'''
output_sequence_index = 2 * self.get_output_state_index()
return state_outputs[output_sequence_index]
class LSTMInitializer:
def __init__(self, hidden_size):
self.hidden_size = hidden_size
def create_states(self, model):
return [
model.create_param(
param_name='initial_hidden_state',
initializer=Initializer(operator_name='ConstantFill',
value=0.0),
shape=[self.hidden_size],
),
model.create_param(
param_name='initial_cell_state',
initializer=Initializer(operator_name='ConstantFill',
value=0.0),
shape=[self.hidden_size],
)
]
# based on https://pytorch.org/docs/master/nn.html#torch.nn.RNNCell
class BasicRNNCell(RNNCell):
def __init__(
self,
input_size,
hidden_size,
forget_bias,
memory_optimization,
drop_states=False,
initializer=None,
activation=None,
**kwargs
):
super().__init__(**kwargs)
self.drop_states = drop_states
self.input_size = input_size
self.hidden_size = hidden_size
self.activation = activation
if self.activation not in ['relu', 'tanh']:
raise RuntimeError(
'BasicRNNCell with unknown activation function (%s)'
% self.activation)
def apply_override(
self,
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs=None,
):
hidden_t_prev = states[0]
gates_t = brew.fc(
model,
hidden_t_prev,
'gates_t',
dim_in=self.hidden_size,
dim_out=self.hidden_size,
axis=2,
)
brew.sum(model, [gates_t, input_t], gates_t)
if self.activation == 'tanh':
hidden_t = model.net.Tanh(gates_t, 'hidden_t')
elif self.activation == 'relu':
hidden_t = model.net.Relu(gates_t, 'hidden_t')
else:
raise RuntimeError(
'BasicRNNCell with unknown activation function (%s)'
% self.activation)
if seq_lengths is not None:
# TODO If this codepath becomes popular, it may be worth
# taking a look at optimizing it - for now a simple
# implementation is used to round out compatibility with
# ONNX.
timestep = model.net.CopyFromCPUInput(
timestep, 'timestep_gpu')
valid_b = model.net.GT(
[seq_lengths, timestep], 'valid_b', broadcast=1)
invalid_b = model.net.LE(
[seq_lengths, timestep], 'invalid_b', broadcast=1)
valid = model.net.Cast(valid_b, 'valid', to='float')
invalid = model.net.Cast(invalid_b, 'invalid', to='float')
hidden_valid = model.net.Mul(
[hidden_t, valid],
'hidden_valid',
broadcast=1,
axis=1,
)
if self.drop_states:
hidden_t = hidden_valid
else:
hidden_invalid = model.net.Mul(
[hidden_t_prev, invalid],
'hidden_invalid',
broadcast=1, axis=1)
hidden_t = model.net.Add(
[hidden_valid, hidden_invalid], hidden_t)
return (hidden_t,)
def prepare_input(self, model, input_blob):
return brew.fc(
model,
input_blob,
self.scope('i2h'),
dim_in=self.input_size,
dim_out=self.hidden_size,
axis=2,
)
def get_state_names(self):
return (self.scope('hidden_t'),)
def get_output_dim(self):
return self.hidden_size
class LSTMCell(RNNCell):
def __init__(
self,
input_size,
hidden_size,
forget_bias,
memory_optimization,
drop_states=False,
initializer=None,
**kwargs
):
super().__init__(initializer=initializer, **kwargs)
self.initializer = initializer or LSTMInitializer(
hidden_size=hidden_size)
self.input_size = input_size
self.hidden_size = hidden_size
self.forget_bias = float(forget_bias)
self.memory_optimization = memory_optimization
self.drop_states = drop_states
self.gates_size = 4 * self.hidden_size
def apply_override(
self,
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs=None,
):
hidden_t_prev, cell_t_prev = states
fc_input = hidden_t_prev
fc_input_dim = self.hidden_size
if extra_inputs is not None:
extra_input_blobs, extra_input_sizes = zip(*extra_inputs)
fc_input = brew.concat(
model,
[hidden_t_prev] + list(extra_input_blobs),
'gates_concatenated_input_t',
axis=2,
)
fc_input_dim += sum(extra_input_sizes)
gates_t = brew.fc(
model,
fc_input,
'gates_t',
dim_in=fc_input_dim,
dim_out=self.gates_size,
axis=2,
)
brew.sum(model, [gates_t, input_t], gates_t)
if seq_lengths is not None:
inputs = [hidden_t_prev, cell_t_prev, gates_t, seq_lengths, timestep]
else:
inputs = [hidden_t_prev, cell_t_prev, gates_t, timestep]
hidden_t, cell_t = model.net.LSTMUnit(
inputs,
['hidden_state', 'cell_state'],
forget_bias=self.forget_bias,
drop_states=self.drop_states,
sequence_lengths=(seq_lengths is not None),
)
model.net.AddExternalOutputs(hidden_t, cell_t)
if self.memory_optimization:
self.recompute_blobs = [gates_t]
return hidden_t, cell_t
def get_input_params(self):
return {
'weights': self.scope('i2h') + '_w',
'biases': self.scope('i2h') + '_b',
}
def get_recurrent_params(self):
return {
'weights': self.scope('gates_t') + '_w',
'biases': self.scope('gates_t') + '_b',
}
def prepare_input(self, model, input_blob):
return brew.fc(
model,
input_blob,
self.scope('i2h'),
dim_in=self.input_size,
dim_out=self.gates_size,
axis=2,
)
def get_state_names_override(self):
return ['hidden_t', 'cell_t']
def get_output_dim(self):
return self.hidden_size
class LayerNormLSTMCell(RNNCell):
def __init__(
self,
input_size,
hidden_size,
forget_bias,
memory_optimization,
drop_states=False,
initializer=None,
**kwargs
):
super().__init__(initializer=initializer, **kwargs)
self.initializer = initializer or LSTMInitializer(
hidden_size=hidden_size
)
self.input_size = input_size
self.hidden_size = hidden_size
self.forget_bias = float(forget_bias)
self.memory_optimization = memory_optimization
self.drop_states = drop_states
self.gates_size = 4 * self.hidden_size
def _apply(
self,
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs=None,
):
hidden_t_prev, cell_t_prev = states
fc_input = hidden_t_prev
fc_input_dim = self.hidden_size
if extra_inputs is not None:
extra_input_blobs, extra_input_sizes = zip(*extra_inputs)
fc_input = brew.concat(
model,
[hidden_t_prev] + list(extra_input_blobs),
self.scope('gates_concatenated_input_t'),
axis=2,
)
fc_input_dim += sum(extra_input_sizes)
gates_t = brew.fc(
model,
fc_input,
self.scope('gates_t'),
dim_in=fc_input_dim,
dim_out=self.gates_size,
axis=2,
)
brew.sum(model, [gates_t, input_t], gates_t)
# brew.layer_norm call is only difference from LSTMCell
gates_t, _, _ = brew.layer_norm(
model,
self.scope('gates_t'),
self.scope('gates_t_norm'),
dim_in=self.gates_size,
axis=-1,
)
hidden_t, cell_t = model.net.LSTMUnit(
[
hidden_t_prev,
cell_t_prev,
gates_t,
seq_lengths,
timestep,
],
self.get_state_names(),
forget_bias=self.forget_bias,
drop_states=self.drop_states,
)
model.net.AddExternalOutputs(hidden_t, cell_t)
if self.memory_optimization:
self.recompute_blobs = [gates_t]
return hidden_t, cell_t
def get_input_params(self):
return {
'weights': self.scope('i2h') + '_w',
'biases': self.scope('i2h') + '_b',
}
def prepare_input(self, model, input_blob):
return brew.fc(
model,
input_blob,
self.scope('i2h'),
dim_in=self.input_size,
dim_out=self.gates_size,
axis=2,
)
def get_state_names(self):
return (self.scope('hidden_t'), self.scope('cell_t'))
class MILSTMCell(LSTMCell):
def _apply(
self,
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs=None,
):
hidden_t_prev, cell_t_prev = states
fc_input = hidden_t_prev
fc_input_dim = self.hidden_size
if extra_inputs is not None:
extra_input_blobs, extra_input_sizes = zip(*extra_inputs)
fc_input = brew.concat(
model,
[hidden_t_prev] + list(extra_input_blobs),
self.scope('gates_concatenated_input_t'),
axis=2,
)
fc_input_dim += sum(extra_input_sizes)
prev_t = brew.fc(
model,
fc_input,
self.scope('prev_t'),
dim_in=fc_input_dim,
dim_out=self.gates_size,
axis=2,
)
# defining initializers for MI parameters
alpha = model.create_param(
self.scope('alpha'),
shape=[self.gates_size],
initializer=Initializer('ConstantFill', value=1.0),
)
beta_h = model.create_param(
self.scope('beta1'),
shape=[self.gates_size],
initializer=Initializer('ConstantFill', value=1.0),
)
beta_i = model.create_param(
self.scope('beta2'),
shape=[self.gates_size],
initializer=Initializer('ConstantFill', value=1.0),
)
b = model.create_param(
self.scope('b'),
shape=[self.gates_size],
initializer=Initializer('ConstantFill', value=0.0),
)
# alpha * input_t + beta_h
# Shape: [1, batch_size, 4 * hidden_size]
alpha_by_input_t_plus_beta_h = model.net.ElementwiseLinear(
[input_t, alpha, beta_h],
self.scope('alpha_by_input_t_plus_beta_h'),
axis=2,
)
# (alpha * input_t + beta_h) * prev_t =
# alpha * input_t * prev_t + beta_h * prev_t
# Shape: [1, batch_size, 4 * hidden_size]
alpha_by_input_t_plus_beta_h_by_prev_t = model.net.Mul(
[alpha_by_input_t_plus_beta_h, prev_t],
self.scope('alpha_by_input_t_plus_beta_h_by_prev_t')
)
# beta_i * input_t + b
# Shape: [1, batch_size, 4 * hidden_size]
beta_i_by_input_t_plus_b = model.net.ElementwiseLinear(
[input_t, beta_i, b],
self.scope('beta_i_by_input_t_plus_b'),
axis=2,
)
# alpha * input_t * prev_t + beta_h * prev_t + beta_i * input_t + b
# Shape: [1, batch_size, 4 * hidden_size]
gates_t = brew.sum(
model,
[alpha_by_input_t_plus_beta_h_by_prev_t, beta_i_by_input_t_plus_b],
self.scope('gates_t')
)
hidden_t, cell_t = model.net.LSTMUnit(
[hidden_t_prev, cell_t_prev, gates_t, seq_lengths, timestep],
[self.scope('hidden_t_intermediate'), self.scope('cell_t')],
forget_bias=self.forget_bias,
drop_states=self.drop_states,
)
model.net.AddExternalOutputs(
cell_t,
hidden_t,
)
if self.memory_optimization:
self.recompute_blobs = [gates_t]
return hidden_t, cell_t
class LayerNormMILSTMCell(LSTMCell):
def _apply(
self,
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs=None,
):
hidden_t_prev, cell_t_prev = states
fc_input = hidden_t_prev
fc_input_dim = self.hidden_size
if extra_inputs is not None:
extra_input_blobs, extra_input_sizes = zip(*extra_inputs)
fc_input = brew.concat(
model,
[hidden_t_prev] + list(extra_input_blobs),
self.scope('gates_concatenated_input_t'),
axis=2,
)
fc_input_dim += sum(extra_input_sizes)
prev_t = brew.fc(
model,
fc_input,
self.scope('prev_t'),
dim_in=fc_input_dim,
dim_out=self.gates_size,
axis=2,
)
# defining initializers for MI parameters
alpha = model.create_param(
self.scope('alpha'),
shape=[self.gates_size],
initializer=Initializer('ConstantFill', value=1.0),
)
beta_h = model.create_param(
self.scope('beta1'),
shape=[self.gates_size],
initializer=Initializer('ConstantFill', value=1.0),
)
beta_i = model.create_param(
self.scope('beta2'),
shape=[self.gates_size],
initializer=Initializer('ConstantFill', value=1.0),
)
b = model.create_param(
self.scope('b'),
shape=[self.gates_size],
initializer=Initializer('ConstantFill', value=0.0),
)
# alpha * input_t + beta_h
# Shape: [1, batch_size, 4 * hidden_size]
alpha_by_input_t_plus_beta_h = model.net.ElementwiseLinear(
[input_t, alpha, beta_h],
self.scope('alpha_by_input_t_plus_beta_h'),
axis=2,
)
# (alpha * input_t + beta_h) * prev_t =
# alpha * input_t * prev_t + beta_h * prev_t
# Shape: [1, batch_size, 4 * hidden_size]
alpha_by_input_t_plus_beta_h_by_prev_t = model.net.Mul(
[alpha_by_input_t_plus_beta_h, prev_t],
self.scope('alpha_by_input_t_plus_beta_h_by_prev_t')
)
# beta_i * input_t + b
# Shape: [1, batch_size, 4 * hidden_size]
beta_i_by_input_t_plus_b = model.net.ElementwiseLinear(
[input_t, beta_i, b],
self.scope('beta_i_by_input_t_plus_b'),
axis=2,
)
# alpha * input_t * prev_t + beta_h * prev_t + beta_i * input_t + b
# Shape: [1, batch_size, 4 * hidden_size]
gates_t = brew.sum(
model,
[alpha_by_input_t_plus_beta_h_by_prev_t, beta_i_by_input_t_plus_b],
self.scope('gates_t')
)
# brew.layer_norm call is only difference from MILSTMCell._apply
gates_t, _, _ = brew.layer_norm(
model,
self.scope('gates_t'),
self.scope('gates_t_norm'),
dim_in=self.gates_size,
axis=-1,
)
hidden_t, cell_t = model.net.LSTMUnit(
[hidden_t_prev, cell_t_prev, gates_t, seq_lengths, timestep],
[self.scope('hidden_t_intermediate'), self.scope('cell_t')],
forget_bias=self.forget_bias,
drop_states=self.drop_states,
)
model.net.AddExternalOutputs(
cell_t,
hidden_t,
)
if self.memory_optimization:
self.recompute_blobs = [gates_t]
return hidden_t, cell_t
class DropoutCell(RNNCell):
'''
Wraps arbitrary RNNCell, applying dropout to its output (but not to the
recurrent connection for the corresponding state).
'''
def __init__(
self,
internal_cell,
dropout_ratio=None,
use_cudnn=False,
**kwargs
):
self.internal_cell = internal_cell
self.dropout_ratio = dropout_ratio
assert 'is_test' in kwargs, "Argument 'is_test' is required"
self.is_test = kwargs.pop('is_test')
self.use_cudnn = use_cudnn
super().__init__(**kwargs)
self.prepare_input = internal_cell.prepare_input
self.get_output_state_index = internal_cell.get_output_state_index
self.get_state_names = internal_cell.get_state_names
self.get_output_dim = internal_cell.get_output_dim
self.mask = 0
def _apply(
self,
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs=None,
):
return self.internal_cell._apply(
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs,
)
def _prepare_output(self, model, states):
output = self.internal_cell._prepare_output(
model,
states,
)
if self.dropout_ratio is not None:
output = self._apply_dropout(model, output)
return output
def _prepare_output_sequence(self, model, state_outputs):
output = self.internal_cell._prepare_output_sequence(
model,
state_outputs,
)
if self.dropout_ratio is not None:
output = self._apply_dropout(model, output)
return output
def _apply_dropout(self, model, output):
if self.dropout_ratio and not self.forward_only:
with core.NameScope(self.name or ''):
output = brew.dropout(
model,
output,
str(output) + '_with_dropout_mask{}'.format(self.mask),
ratio=float(self.dropout_ratio),
is_test=self.is_test,
use_cudnn=self.use_cudnn,
)
self.mask += 1
return output
class MultiRNNCellInitializer:
def __init__(self, cells):
self.cells = cells
def create_states(self, model):
states = []
for i, cell in enumerate(self.cells):
if cell.initializer is None:
raise Exception("Either initial states "
"or initializer have to be set")
with core.NameScope("layer_{}".format(i)),\
core.NameScope(cell.name):
states.extend(cell.initializer.create_states(model))
return states
class MultiRNNCell(RNNCell):
'''
Multilayer RNN via the composition of RNNCell instance.
It is the responsibility of calling code to ensure the compatibility
of the successive layers in terms of input/output dimensiality, etc.,
and to ensure that their blobs do not have name conflicts, typically by
creating the cells with names that specify layer number.
Assumes first state (recurrent output) for each layer should be the input
to the next layer.
'''
def __init__(self, cells, residual_output_layers=None, **kwargs):
'''
cells: list of RNNCell instances, from input to output side.
name: string designating network component (for scoping)
residual_output_layers: list of indices of layers whose input will
be added elementwise to their output elementwise. (It is the
responsibility of the client code to ensure shape compatibility.)
Note that layer 0 (zero) cannot have residual output because of the
timing of prepare_input().
forward_only: used to construct inference-only network.
'''
super().__init__(**kwargs)
self.cells = cells
if residual_output_layers is None:
self.residual_output_layers = []
else:
self.residual_output_layers = residual_output_layers
output_index_per_layer = []
base_index = 0
for cell in self.cells:
output_index_per_layer.append(
base_index + cell.get_output_state_index(),
)
base_index += len(cell.get_state_names())
self.output_connected_layers = []
self.output_indices = []
for i in range(len(self.cells) - 1):
if (i + 1) in self.residual_output_layers:
self.output_connected_layers.append(i)
self.output_indices.append(output_index_per_layer[i])
else:
self.output_connected_layers = []
self.output_indices = []
self.output_connected_layers.append(len(self.cells) - 1)
self.output_indices.append(output_index_per_layer[-1])
self.state_names = []
for i, cell in enumerate(self.cells):
self.state_names.extend(
map(self.layer_scoper(i), cell.get_state_names())
)
self.initializer = MultiRNNCellInitializer(cells)
def layer_scoper(self, layer_id):
def helper(name):
return "{}/layer_{}/{}".format(self.name, layer_id, name)
return helper
def prepare_input(self, model, input_blob):
input_blob = _RectifyName(input_blob)
with core.NameScope(self.name or ''):
return self.cells[0].prepare_input(model, input_blob)
def _apply(
self,
model,
input_t,
seq_lengths,
states,
timestep,
extra_inputs=None,
):
'''
Because below we will do scoping across layers, we need
to make sure that string blob names are convereted to BlobReference
objects.
'''
input_t, seq_lengths, states, timestep, extra_inputs = \
self._rectify_apply_inputs(
input_t, seq_lengths, states, timestep, extra_inputs)
states_per_layer = [len(cell.get_state_names()) for cell in self.cells]
assert len(states) == sum(states_per_layer)