-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathrecurrent.ts
2127 lines (1893 loc) · 74.5 KB
/
recurrent.ts
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
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* TensorFlow.js Layers: Recurrent Neural Network Layers.
*/
import * as tfc from '@tensorflow/tfjs-core';
import {DataType, serialization, Tensor, tidy, util} from '@tensorflow/tfjs-core';
import {Activation, getActivation, serializeActivation} from '../activations';
import * as K from '../backend/tfjs_backend';
import {nameScope} from '../common';
import {Constraint, ConstraintIdentifier, getConstraint, serializeConstraint} from '../constraints';
import {InputSpec, SymbolicTensor} from '../engine/topology';
import {Layer, LayerArgs} from '../engine/topology';
import {AttributeError, NotImplementedError, ValueError} from '../errors';
import {getInitializer, Initializer, InitializerIdentifier, Ones, serializeInitializer} from '../initializers';
import {ActivationIdentifier} from '../keras_format/activation_config';
import {Shape} from '../keras_format/common';
import {getRegularizer, Regularizer, RegularizerIdentifier, serializeRegularizer} from '../regularizers';
import {Kwargs, RnnStepFunction} from '../types';
import {assertPositiveInteger} from '../utils/generic_utils';
import * as math_utils from '../utils/math_utils';
import {getExactlyOneShape, getExactlyOneTensor, isArrayOfShapes} from '../utils/types_utils';
import {batchGetValue, batchSetValue, LayerVariable} from '../variables';
import {deserialize} from './serialization';
/**
* Standardize `apply()` args to a single list of tensor inputs.
*
* When running a model loaded from file, the input tensors `initialState` and
* `constants` are passed to `RNN.apply()` as part of `inputs` instead of the
* dedicated kwargs fields. `inputs` consists of
* `[inputs, initialState0, initialState1, ..., constant0, constant1]` in this
* case.
* This method makes sure that arguments are
* separated and that `initialState` and `constants` are `Array`s of tensors
* (or None).
*
* @param inputs Tensor or `Array` of tensors.
* @param initialState Tensor or `Array` of tensors or `null`/`undefined`.
* @param constants Tensor or `Array` of tensors or `null`/`undefined`.
* @returns An object consisting of
* inputs: A tensor.
* initialState: `Array` of tensors or `null`.
* constants: `Array` of tensors or `null`.
* @throws ValueError, if `inputs` is an `Array` but either `initialState` or
* `constants` is provided.
*/
export function standardizeArgs(
inputs: Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[],
initialState: Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[],
constants: Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[],
numConstants?: number): {
inputs: Tensor|SymbolicTensor,
initialState: Tensor[]|SymbolicTensor[],
constants: Tensor[]|SymbolicTensor[]
} {
if (Array.isArray(inputs)) {
if (initialState != null || constants != null) {
throw new ValueError(
'When inputs is an array, neither initialState or constants ' +
'should be provided');
}
if (numConstants != null) {
constants = inputs.slice(inputs.length - numConstants, inputs.length);
inputs = inputs.slice(0, inputs.length - numConstants);
}
if (inputs.length > 1) {
initialState = inputs.slice(1, inputs.length);
}
inputs = inputs[0];
}
function toListOrNull(x: Tensor|Tensor[]|SymbolicTensor|
SymbolicTensor[]): Tensor[]|SymbolicTensor[] {
if (x == null || Array.isArray(x)) {
return x as Tensor[] | SymbolicTensor[];
} else {
return [x] as Tensor[] | SymbolicTensor[];
}
}
initialState = toListOrNull(initialState);
constants = toListOrNull(constants);
return {inputs, initialState, constants};
}
/**
* Iterates over the time dimension of a tensor.
*
* @param stepFunction RNN step function.
* Parameters:
* inputs: tensor with shape `[samples, ...]` (no time dimension),
* representing input for the batch of samples at a certain time step.
* states: an Array of tensors.
* Returns:
* outputs: tensor with shape `[samples, outputDim]` (no time dimension).
* newStates: list of tensors, same length and shapes as `states`. The first
* state in the list must be the output tensor at the previous timestep.
* @param inputs Tensor of temporal data of shape `[samples, time, ...]` (at
* least 3D).
* @param initialStates Tensor with shape `[samples, outputDim]` (no time
* dimension), containing the initial values of the states used in the step
* function.
* @param goBackwards If `true`, do the iteration over the time dimension in
* reverse order and return the reversed sequence.
* @param mask Binary tensor with shape `[sample, time, 1]`, with a zero for
* every element that is masked.
* @param constants An Array of constant values passed at each step.
* @param unroll Whether to unroll the RNN or to use a symbolic loop. *Not*
* applicable to this imperative deeplearn.js backend. Its value is ignored.
* @param needPerStepOutputs Whether the per-step outputs are to be
* concatenated into a single tensor and returned (as the second return
* value). Default: `false`. This arg is included so that the relatively
* expensive concatenation of the stepwise outputs can be omitted unless
* the stepwise outputs need to be kept (e.g., for an LSTM layer of which
* `returnSequence` is `true`.)
* @returns An Array: `[lastOutput, outputs, newStates]`.
* lastOutput: the lastest output of the RNN, of shape `[samples, ...]`.
* outputs: tensor with shape `[samples, time, ...]` where each entry
* `output[s, t]` is the output of the step function at time `t` for sample
* `s`. This return value is provided if and only if the
* `needPerStepOutputs` is set as `true`. If it is set as `false`, this
* return value will be `undefined`.
* newStates: Array of tensors, latest states returned by the step function,
* of shape `(samples, ...)`.
* @throws ValueError If input dimension is less than 3.
*
* TODO(nielsene): This needs to be tidy-ed.
*/
export function rnn(
stepFunction: RnnStepFunction, inputs: Tensor, initialStates: Tensor[],
goBackwards = false, mask?: Tensor, constants?: Tensor[], unroll = false,
needPerStepOutputs = false): [Tensor, Tensor, Tensor[]] {
return tfc.tidy(() => {
const ndim = inputs.shape.length;
if (ndim < 3) {
throw new ValueError(`Input should be at least 3D, but is ${ndim}D.`);
}
// Transpose to time-major, i.e., from [batch, time, ...] to [time, batch,
// ...].
const axes = [1, 0].concat(math_utils.range(2, ndim));
inputs = tfc.transpose(inputs, axes);
if (constants != null) {
throw new NotImplementedError(
'The rnn() functoin of the deeplearn.js backend does not support ' +
'constants yet.');
}
// Porting Note: the unroll option is ignored by the imperative backend.
if (unroll) {
console.warn(
'Backend rnn(): the unroll = true option is not applicable to the ' +
'imperative deeplearn.js backend.');
}
if (mask != null) {
mask = tfc.cast(tfc.cast(mask, 'bool'), 'float32');
if (mask.rank === ndim - 1) {
mask = tfc.expandDims(mask, -1);
}
mask = tfc.transpose(mask, axes);
}
if (goBackwards) {
inputs = tfc.reverse(inputs, 0);
if (mask != null) {
mask = tfc.reverse(mask, 0);
}
}
// Porting Note: PyKeras with TensorFlow backend uses a symbolic loop
// (tf.while_loop). But for the imperative deeplearn.js backend, we just
// use the usual TypeScript control flow to iterate over the time steps in
// the inputs.
// Porting Note: PyKeras patches a "_use_learning_phase" attribute to
// outputs.
// This is not idiomatic in TypeScript. The info regarding whether we are
// in a learning (i.e., training) phase for RNN is passed in a different
// way.
const perStepOutputs: Tensor[] = [];
let lastOutput: Tensor;
let states = initialStates;
const timeSteps = inputs.shape[0];
const perStepInputs = tfc.unstack(inputs);
let perStepMasks: Tensor[];
if (mask != null) {
perStepMasks = tfc.unstack(mask);
}
for (let t = 0; t < timeSteps; ++t) {
const currentInput = perStepInputs[t];
const stepOutputs = tfc.tidy(() => stepFunction(currentInput, states));
if (mask == null) {
lastOutput = stepOutputs[0];
states = stepOutputs[1];
} else {
const maskedOutputs = tfc.tidy(() => {
const stepMask = perStepMasks[t];
const negStepMask = tfc.sub(tfc.onesLike(stepMask), stepMask);
// TODO(cais): Would tfc.where() be better for performance?
const output = tfc.add(
tfc.mul(stepOutputs[0], stepMask),
tfc.mul(states[0], negStepMask));
const newStates = states.map((state, i) => {
return tfc.add(
tfc.mul(stepOutputs[1][i], stepMask),
tfc.mul(state, negStepMask));
});
return {output, newStates};
});
lastOutput = maskedOutputs.output;
states = maskedOutputs.newStates;
}
if (needPerStepOutputs) {
perStepOutputs.push(lastOutput);
}
}
let outputs: Tensor;
if (needPerStepOutputs) {
const axis = 1;
outputs = tfc.stack(perStepOutputs, axis);
}
return [lastOutput, outputs, states] as [Tensor, Tensor, Tensor[]];
});
}
export declare interface BaseRNNLayerArgs extends LayerArgs {
/**
* A RNN cell instance. A RNN cell is a class that has:
* - a `call()` method, which takes `[Tensor, Tensor]` as the
* first input argument. The first item is the input at time t, and
* second item is the cell state at time t.
* The `call()` method returns `[outputAtT, statesAtTPlus1]`.
* The `call()` method of the cell can also take the argument `constants`,
* see section "Note on passing external constants" below.
* Porting Node: PyKeras overrides the `call()` signature of RNN cells,
* which are Layer subtypes, to accept two arguments. tfjs-layers does
* not do such overriding. Instead we preserve the `call()` signature,
* which due to its `Tensor|Tensor[]` argument and return value is
* flexible enough to handle the inputs and states.
* - a `stateSize` attribute. This can be a single integer (single state)
* in which case it is the size of the recurrent state (which should be
* the same as the size of the cell output). This can also be an Array of
* integers (one size per state). In this case, the first entry
* (`stateSize[0]`) should be the same as the size of the cell output.
* It is also possible for `cell` to be a list of RNN cell instances, in which
* case the cells get stacked on after the other in the RNN, implementing an
* efficient stacked RNN.
*/
cell?: RNNCell|RNNCell[];
/**
* Whether to return the last output in the output sequence, or the full
* sequence.
*/
returnSequences?: boolean;
/**
* Whether to return the last state in addition to the output.
*/
returnState?: boolean;
/**
* If `true`, process the input sequence backwards and return the reversed
* sequence (default: `false`).
*/
goBackwards?: boolean;
/**
* If `true`, the last state for each sample at index i in a batch will be
* used as initial state of the sample of index i in the following batch
* (default: `false`).
*
* You can set RNN layers to be "stateful", which means that the states
* computed for the samples in one batch will be reused as initial states
* for the samples in the next batch. This assumes a one-to-one mapping
* between samples in different successive batches.
*
* To enable "statefulness":
* - specify `stateful: true` in the layer constructor.
* - specify a fixed batch size for your model, by passing
* - if sequential model:
* `batchInputShape: [...]` to the first layer in your model.
* - else for functional model with 1 or more Input layers:
* `batchShape: [...]` to all the first layers in your model.
* This is the expected shape of your inputs
* *including the batch size*.
* It should be a tuple of integers, e.g., `[32, 10, 100]`.
* - specify `shuffle: false` when calling `LayersModel.fit()`.
*
* To reset the state of your model, call `resetStates()` on either the
* specific layer or on the entire model.
*/
stateful?: boolean;
// TODO(cais): Explore whether we can warn users when they fail to set
// `shuffle: false` when training a model consisting of stateful RNNs
// and any stateful Layers in general.
/**
* If `true`, the network will be unrolled, else a symbolic loop will be
* used. Unrolling can speed up a RNN, although it tends to be more
* memory-intensive. Unrolling is only suitable for short sequences (default:
* `false`).
* Porting Note: tfjs-layers has an imperative backend. RNNs are executed with
* normal TypeScript control flow. Hence this property is inapplicable and
* ignored in tfjs-layers.
*/
unroll?: boolean;
/**
* Dimensionality of the input (integer).
* This option (or alternatively, the option `inputShape`) is required when
* this layer is used as the first layer in a model.
*/
inputDim?: number;
/**
* Length of the input sequences, to be specified when it is constant.
* This argument is required if you are going to connect `Flatten` then
* `Dense` layers upstream (without it, the shape of the dense outputs cannot
* be computed). Note that if the recurrent layer is not the first layer in
* your model, you would need to specify the input length at the level of the
* first layer (e.g., via the `inputShape` option).
*/
inputLength?: number;
}
export class RNN extends Layer {
/** @nocollapse */
static className = 'RNN';
public readonly cell: RNNCell;
public readonly returnSequences: boolean;
public readonly returnState: boolean;
public readonly goBackwards: boolean;
public readonly unroll: boolean;
public stateSpec: InputSpec[];
protected states_: Tensor[];
// NOTE(cais): For stateful RNNs, the old states cannot be disposed right
// away when new states are set, because the old states may need to be used
// later for backpropagation through time (BPTT) and other purposes. So we
// keep them here for final disposal when the state is reset completely
// (i.e., through no-arg call to `resetStates()`).
protected keptStates: Tensor[][];
private numConstants: number;
constructor(args: RNNLayerArgs) {
super(args);
let cell: RNNCell;
if (args.cell == null) {
throw new ValueError(
'cell property is missing for the constructor of RNN.');
} else if (Array.isArray(args.cell)) {
cell = new StackedRNNCells({cells: args.cell});
} else {
cell = args.cell;
}
if (cell.stateSize == null) {
throw new ValueError(
'The RNN cell should have an attribute `stateSize` (tuple of ' +
'integers, one integer per RNN state).');
}
this.cell = cell;
this.returnSequences =
args.returnSequences == null ? false : args.returnSequences;
this.returnState = args.returnState == null ? false : args.returnState;
this.goBackwards = args.goBackwards == null ? false : args.goBackwards;
this._stateful = args.stateful == null ? false : args.stateful;
this.unroll = args.unroll == null ? false : args.unroll;
this.supportsMasking = true;
this.inputSpec = [new InputSpec({ndim: 3})];
this.stateSpec = null;
this.states_ = null;
// TODO(cais): Add constantsSpec and numConstants.
this.numConstants = null;
// TODO(cais): Look into the use of initial_state in the kwargs of the
// constructor.
this.keptStates = [];
}
// Porting Note: This is the equivalent of `RNN.states` property getter in
// PyKeras.
getStates(): Tensor[] {
if (this.states_ == null) {
const numStates =
Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;
return math_utils.range(0, numStates).map(x => null);
} else {
return this.states_;
}
}
// Porting Note: This is the equivalent of the `RNN.states` property setter in
// PyKeras.
setStates(states: Tensor[]): void {
this.states_ = states;
}
override computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {
if (isArrayOfShapes(inputShape)) {
inputShape = (inputShape as Shape[])[0];
}
inputShape = inputShape as Shape;
// TODO(cais): Remove the casting once stacked RNN cells become supported.
let stateSize = this.cell.stateSize;
if (!Array.isArray(stateSize)) {
stateSize = [stateSize];
}
const outputDim = stateSize[0];
let outputShape: Shape|Shape[];
if (this.returnSequences) {
outputShape = [inputShape[0], inputShape[1], outputDim];
} else {
outputShape = [inputShape[0], outputDim];
}
if (this.returnState) {
const stateShape: Shape[] = [];
for (const dim of stateSize) {
stateShape.push([inputShape[0], dim]);
}
return [outputShape].concat(stateShape);
} else {
return outputShape;
}
}
override computeMask(inputs: Tensor|Tensor[], mask?: Tensor|Tensor[]): Tensor
|Tensor[] {
return tfc.tidy(() => {
if (Array.isArray(mask)) {
mask = mask[0];
}
const outputMask = this.returnSequences ? mask : null;
if (this.returnState) {
const stateMask = this.states.map(s => null);
return [outputMask].concat(stateMask);
} else {
return outputMask;
}
});
}
/**
* Get the current state tensors of the RNN.
*
* If the state hasn't been set, return an array of `null`s of the correct
* length.
*/
get states(): Tensor[] {
if (this.states_ == null) {
const numStates =
Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;
const output: Tensor[] = [];
for (let i = 0; i < numStates; ++i) {
output.push(null);
}
return output;
} else {
return this.states_;
}
}
set states(s: Tensor[]) {
this.states_ = s;
}
public override build(inputShape: Shape|Shape[]): void {
// Note inputShape will be an Array of Shapes of initial states and
// constants if these are passed in apply().
const constantShape: Shape[] = null;
if (this.numConstants != null) {
throw new NotImplementedError(
'Constants support is not implemented in RNN yet.');
}
if (isArrayOfShapes(inputShape)) {
inputShape = (inputShape as Shape[])[0];
}
inputShape = inputShape as Shape;
const batchSize: number = this.stateful ? inputShape[0] : null;
const inputDim = inputShape.slice(2);
this.inputSpec[0] = new InputSpec({shape: [batchSize, null, ...inputDim]});
// Allow cell (if RNNCell Layer) to build before we set or validate
// stateSpec.
const stepInputShape = [inputShape[0]].concat(inputShape.slice(2));
if (constantShape != null) {
throw new NotImplementedError(
'Constants support is not implemented in RNN yet.');
} else {
this.cell.build(stepInputShape);
}
// Set or validate stateSpec.
let stateSize: number[];
if (Array.isArray(this.cell.stateSize)) {
stateSize = this.cell.stateSize;
} else {
stateSize = [this.cell.stateSize];
}
if (this.stateSpec != null) {
if (!util.arraysEqual(
this.stateSpec.map(spec => spec.shape[spec.shape.length - 1]),
stateSize)) {
throw new ValueError(
`An initialState was passed that is not compatible with ` +
`cell.stateSize. Received stateSpec=${this.stateSpec}; ` +
`However cell.stateSize is ${this.cell.stateSize}`);
}
} else {
this.stateSpec =
stateSize.map(dim => new InputSpec({shape: [null, dim]}));
}
if (this.stateful) {
this.resetStates();
}
}
/**
* Reset the state tensors of the RNN.
*
* If the `states` argument is `undefined` or `null`, will set the
* state tensor(s) of the RNN to all-zero tensors of the appropriate
* shape(s).
*
* If `states` is provided, will set the state tensors of the RNN to its
* value.
*
* @param states Optional externally-provided initial states.
* @param training Whether this call is done during training. For stateful
* RNNs, this affects whether the old states are kept or discarded. In
* particular, if `training` is `true`, the old states will be kept so
* that subsequent backpropgataion through time (BPTT) may work properly.
* Else, the old states will be discarded.
*/
override resetStates(states?: Tensor|Tensor[], training = false): void {
tidy(() => {
if (!this.stateful) {
throw new AttributeError(
'Cannot call resetStates() on an RNN Layer that is not stateful.');
}
const batchSize = this.inputSpec[0].shape[0];
if (batchSize == null) {
throw new ValueError(
'If an RNN is stateful, it needs to know its batch size. Specify ' +
'the batch size of your input tensors: \n' +
'- If using a Sequential model, specify the batch size by ' +
'passing a `batchInputShape` option to your first layer.\n' +
'- If using the functional API, specify the batch size by ' +
'passing a `batchShape` option to your Input layer.');
}
// Initialize state if null.
if (this.states_ == null) {
if (Array.isArray(this.cell.stateSize)) {
this.states_ =
this.cell.stateSize.map(dim => tfc.zeros([batchSize, dim]));
} else {
this.states_ = [tfc.zeros([batchSize, this.cell.stateSize])];
}
} else if (states == null) {
// Dispose old state tensors.
tfc.dispose(this.states_);
// For stateful RNNs, fully dispose kept old states.
if (this.keptStates != null) {
tfc.dispose(this.keptStates);
this.keptStates = [];
}
if (Array.isArray(this.cell.stateSize)) {
this.states_ =
this.cell.stateSize.map(dim => tfc.zeros([batchSize, dim]));
} else {
this.states_[0] = tfc.zeros([batchSize, this.cell.stateSize]);
}
} else {
if (!Array.isArray(states)) {
states = [states];
}
if (states.length !== this.states_.length) {
throw new ValueError(
`Layer ${this.name} expects ${this.states_.length} state(s), ` +
`but it received ${states.length} state value(s). Input ` +
`received: ${states}`);
}
if (training === true) {
// Store old state tensors for complete disposal later, i.e., during
// the next no-arg call to this method. We do not dispose the old
// states immediately because that BPTT (among other things) require
// them.
this.keptStates.push(this.states_.slice());
} else {
tfc.dispose(this.states_);
}
for (let index = 0; index < this.states_.length; ++index) {
const value = states[index];
const dim = Array.isArray(this.cell.stateSize) ?
this.cell.stateSize[index] :
this.cell.stateSize;
const expectedShape = [batchSize, dim];
if (!util.arraysEqual(value.shape, expectedShape)) {
throw new ValueError(
`State ${index} is incompatible with layer ${this.name}: ` +
`expected shape=${expectedShape}, received shape=${
value.shape}`);
}
this.states_[index] = value;
}
}
this.states_ = this.states_.map(state => tfc.keep(state.clone()));
});
}
override apply(
inputs: Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[],
kwargs?: Kwargs): Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[] {
// TODO(cais): Figure out whether initialState is in kwargs or inputs.
let initialState: Tensor[]|SymbolicTensor[] =
kwargs == null ? null : kwargs['initialState'];
let constants: Tensor[]|SymbolicTensor[] =
kwargs == null ? null : kwargs['constants'];
if (kwargs == null) {
kwargs = {};
}
const standardized =
standardizeArgs(inputs, initialState, constants, this.numConstants);
inputs = standardized.inputs;
initialState = standardized.initialState;
constants = standardized.constants;
// If any of `initial_state` or `constants` are specified and are
// `tf.SymbolicTensor`s, then add them to the inputs and temporarily modify
// the input_spec to include them.
let additionalInputs: Array<Tensor|SymbolicTensor> = [];
let additionalSpecs: InputSpec[] = [];
if (initialState != null) {
kwargs['initialState'] = initialState;
additionalInputs = additionalInputs.concat(initialState);
this.stateSpec = [];
for (const state of initialState) {
this.stateSpec.push(new InputSpec({shape: state.shape}));
}
// TODO(cais): Use the following instead.
// this.stateSpec = initialState.map(state => new InputSpec({shape:
// state.shape}));
additionalSpecs = additionalSpecs.concat(this.stateSpec);
}
if (constants != null) {
kwargs['constants'] = constants;
additionalInputs = additionalInputs.concat(constants);
// TODO(cais): Add this.constantsSpec.
this.numConstants = constants.length;
}
const isTensor = additionalInputs[0] instanceof SymbolicTensor;
if (isTensor) {
// Compute full input spec, including state and constants.
const fullInput =
[inputs].concat(additionalInputs) as Tensor[] | SymbolicTensor[];
const fullInputSpec = this.inputSpec.concat(additionalSpecs);
// Perform the call with temporarily replaced inputSpec.
const originalInputSpec = this.inputSpec;
this.inputSpec = fullInputSpec;
const output = super.apply(fullInput, kwargs);
this.inputSpec = originalInputSpec;
return output;
} else {
return super.apply(inputs, kwargs);
}
}
// tslint:disable-next-line:no-any
override call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {
// Input shape: `[samples, time (padded with zeros), input_dim]`.
// Note that the .build() method of subclasses **must** define
// this.inputSpec and this.stateSpec owith complete input shapes.
return tidy(() => {
const mask = kwargs == null ? null : kwargs['mask'] as Tensor;
const training = kwargs == null ? null : kwargs['training'];
let initialState: Tensor[] =
kwargs == null ? null : kwargs['initialState'];
inputs = getExactlyOneTensor(inputs);
if (initialState == null) {
if (this.stateful) {
initialState = this.states_;
} else {
initialState = this.getInitialState(inputs);
}
}
const numStates =
Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;
if (initialState.length !== numStates) {
throw new ValueError(
`RNN Layer has ${numStates} state(s) but was passed ` +
`${initialState.length} initial state(s).`);
}
if (this.unroll) {
console.warn(
'Ignoring unroll = true for RNN layer, due to imperative backend.');
}
const cellCallKwargs: Kwargs = {training};
// TODO(cais): Add support for constants.
const step = (inputs: Tensor, states: Tensor[]) => {
// `inputs` and `states` are concatenated to form a single `Array` of
// `tf.Tensor`s as the input to `cell.call()`.
const outputs =
this.cell.call([inputs].concat(states), cellCallKwargs) as Tensor[];
// Marshall the return value into output and new states.
return [outputs[0], outputs.slice(1)] as [Tensor, Tensor[]];
};
// TODO(cais): Add support for constants.
const rnnOutputs =
rnn(step, inputs, initialState, this.goBackwards, mask, null,
this.unroll, this.returnSequences);
const lastOutput = rnnOutputs[0];
const outputs = rnnOutputs[1];
const states = rnnOutputs[2];
if (this.stateful) {
this.resetStates(states, training);
}
const output = this.returnSequences ? outputs : lastOutput;
// TODO(cais): Property set learning phase flag.
if (this.returnState) {
return [output].concat(states);
} else {
return output;
}
});
}
getInitialState(inputs: Tensor): Tensor[] {
return tidy(() => {
// Build an all-zero tensor of shape [samples, outputDim].
// [Samples, timeSteps, inputDim].
let initialState = tfc.zeros(inputs.shape);
// [Samples].
initialState = tfc.sum(initialState, [1, 2]);
initialState = K.expandDims(initialState); // [Samples, 1].
if (Array.isArray(this.cell.stateSize)) {
return this.cell.stateSize.map(
dim => dim > 1 ? K.tile(initialState, [1, dim]) : initialState);
} else {
return this.cell.stateSize > 1 ?
[K.tile(initialState, [1, this.cell.stateSize])] :
[initialState];
}
});
}
override get trainableWeights(): LayerVariable[] {
if (!this.trainable) {
return [];
}
// Porting Note: In TypeScript, `this` is always an instance of `Layer`.
return this.cell.trainableWeights;
}
override get nonTrainableWeights(): LayerVariable[] {
// Porting Note: In TypeScript, `this` is always an instance of `Layer`.
if (!this.trainable) {
return this.cell.weights;
}
return this.cell.nonTrainableWeights;
}
override setFastWeightInitDuringBuild(value: boolean) {
super.setFastWeightInitDuringBuild(value);
if (this.cell != null) {
this.cell.setFastWeightInitDuringBuild(value);
}
}
override getConfig(): serialization.ConfigDict {
const baseConfig = super.getConfig();
const config: serialization.ConfigDict = {
returnSequences: this.returnSequences,
returnState: this.returnState,
goBackwards: this.goBackwards,
stateful: this.stateful,
unroll: this.unroll,
};
if (this.numConstants != null) {
config['numConstants'] = this.numConstants;
}
const cellConfig = this.cell.getConfig();
if (this.getClassName() === RNN.className) {
config['cell'] = {
'className': this.cell.getClassName(),
'config': cellConfig,
} as serialization.ConfigDictValue;
}
// this order is necessary, to prevent cell name from replacing layer name
return {...cellConfig, ...baseConfig, ...config};
}
/** @nocollapse */
static override fromConfig<T extends serialization.Serializable>(
cls: serialization.SerializableConstructor<T>,
config: serialization.ConfigDict,
customObjects = {} as serialization.ConfigDict): T {
const cellConfig = config['cell'] as serialization.ConfigDict;
const cell = deserialize(cellConfig, customObjects) as RNNCell;
return new cls(Object.assign(config, {cell}));
}
}
serialization.registerClass(RNN);
// Porting Note: This is a common parent class for RNN cells. There is no
// equivalent of this in PyKeras. Having a common parent class forgoes the
// need for `has_attr(cell, ...)` checks or its TypeScript equivalent.
/**
* An RNNCell layer.
*
* @doc {heading: 'Layers', subheading: 'Classes'}
*/
export abstract class RNNCell extends Layer {
/**
* Size(s) of the states.
* For RNN cells with only a single state, this is a single integer.
*/
// See
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#properties-overriding-accessors-and-vice-versa-is-an-error
public abstract stateSize: number|number[];
public dropoutMask: Tensor|Tensor[];
public recurrentDropoutMask: Tensor|Tensor[];
}
export declare interface SimpleRNNCellLayerArgs extends LayerArgs {
/**
* units: Positive integer, dimensionality of the output space.
*/
units: number;
/**
* Activation function to use.
* Default: hyperbolic tangent ('tanh').
* If you pass `null`, 'linear' activation will be applied.
*/
activation?: ActivationIdentifier;
/**
* Whether the layer uses a bias vector.
*/
useBias?: boolean;
/**
* Initializer for the `kernel` weights matrix, used for the linear
* transformation of the inputs.
*/
kernelInitializer?: InitializerIdentifier|Initializer;
/**
* Initializer for the `recurrentKernel` weights matrix, used for
* linear transformation of the recurrent state.
*/
recurrentInitializer?: InitializerIdentifier|Initializer;
/**
* Initializer for the bias vector.
*/
biasInitializer?: InitializerIdentifier|Initializer;
/**
* Regularizer function applied to the `kernel` weights matrix.
*/
kernelRegularizer?: RegularizerIdentifier|Regularizer;
/**
* Regularizer function applied to the `recurrent_kernel` weights matrix.
*/
recurrentRegularizer?: RegularizerIdentifier|Regularizer;
/**
* Regularizer function applied to the bias vector.
*/
biasRegularizer?: RegularizerIdentifier|Regularizer;
/**
* Constraint function applied to the `kernel` weights matrix.
*/
kernelConstraint?: ConstraintIdentifier|Constraint;
/**
* Constraint function applied to the `recurrentKernel` weights matrix.
*/
recurrentConstraint?: ConstraintIdentifier|Constraint;
/**
* Constraint function applied to the bias vector.
*/
biasConstraint?: ConstraintIdentifier|Constraint;
/**
* Float number between 0 and 1. Fraction of the units to drop for the linear
* transformation of the inputs.
*/
dropout?: number;
/**
* Float number between 0 and 1. Fraction of the units to drop for the linear
* transformation of the recurrent state.
*/
recurrentDropout?: number;
/**
* This is added for test DI purpose.
*/
dropoutFunc?: Function;
}
export class SimpleRNNCell extends RNNCell {
/** @nocollapse */
static className = 'SimpleRNNCell';
readonly units: number;
readonly activation: Activation;
readonly useBias: boolean;
readonly kernelInitializer: Initializer;
readonly recurrentInitializer: Initializer;
readonly biasInitializer: Initializer;
readonly kernelConstraint: Constraint;
readonly recurrentConstraint: Constraint;
readonly biasConstraint: Constraint;
readonly kernelRegularizer: Regularizer;
readonly recurrentRegularizer: Regularizer;
readonly biasRegularizer: Regularizer;
readonly dropout: number;
readonly recurrentDropout: number;
readonly dropoutFunc: Function;
readonly stateSize: number;
kernel: LayerVariable;
recurrentKernel: LayerVariable;
bias: LayerVariable;
readonly DEFAULT_ACTIVATION = 'tanh';
readonly DEFAULT_KERNEL_INITIALIZER = 'glorotNormal';
readonly DEFAULT_RECURRENT_INITIALIZER = 'orthogonal';
readonly DEFAULT_BIAS_INITIALIZER: InitializerIdentifier = 'zeros';
constructor(args: SimpleRNNCellLayerArgs) {
super(args);
this.units = args.units;
assertPositiveInteger(this.units, `units`);
this.activation = getActivation(
args.activation == null ? this.DEFAULT_ACTIVATION : args.activation);
this.useBias = args.useBias == null ? true : args.useBias;
this.kernelInitializer = getInitializer(
args.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER);
this.recurrentInitializer = getInitializer(