-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
topology.ts
1683 lines (1549 loc) · 54.2 KB
/
topology.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.
* =============================================================================
*/
/* Original source: keras/engine/topology.py */
import {DataType, Scalar, serialization, Tensor, tidy, util} from '@tensorflow/tfjs-core';
import {getNextUniqueTensorId, getUid} from '../backend/state';
import {getScopedTensorName, getUniqueTensorName, nameScope} from '../common';
import {Constraint} from '../constraints';
import {AttributeError, NotImplementedError, RuntimeError, ValueError} from '../errors';
import {getInitializer, Initializer} from '../initializers';
import {Shape} from '../keras_format/common';
import {Regularizer} from '../regularizers';
import {Kwargs, RegularizerFn} from '../types';
import * as generic_utils from '../utils/generic_utils';
import * as types_utils from '../utils/types_utils';
import * as variable_utils from '../utils/variable_utils';
import {batchGetValue, batchSetValue, LayerVariable} from '../variables';
// TODO(michaelterry): This is a stub until it's defined.
export type Op = (x: LayerVariable) => LayerVariable;
/**
* Constructor arguments for InputSpec.
*/
export interface InputSpecArgs {
/** Expected datatype of the input. */
dtype?: DataType;
/** Expected shape of the input (may include null for unchecked axes). */
shape?: Shape;
/** Expected rank of the input. */
ndim?: number;
/** Maximum rank of the input. */
maxNDim?: number;
/** Minimum rank of the input. */
minNDim?: number;
/** Dictionary mapping integer axes to a specific dimension value. */
axes?: {[axis: number]: number};
}
/**
* Specifies the ndim, dtype and shape of every input to a layer.
*
* Every layer should expose (if appropriate) an `inputSpec` attribute:
* a list of instances of InputSpec (one per input tensor).
*
* A null entry in a shape is compatible with any dimension,
* a null shape is compatible with any shape.
*/
export class InputSpec {
/** Expected datatype of the input. */
dtype?: DataType;
/** Expected shape of the input (may include null for unchecked axes). */
shape?: Shape;
/** Expected rank of the input. */
ndim?: number;
/** Maximum rank of the input. */
maxNDim?: number;
/** Minimum rank of the input. */
minNDim?: number;
/** Dictionary mapping integer axes to a specific dimension value. */
axes?: {[axis: number]: number};
constructor(args: InputSpecArgs) {
this.dtype = args.dtype;
this.shape = args.shape;
/*
TODO(michaelterry): Could throw error if ndim and shape are both defined
(then backport).
*/
if (args.shape != null) {
this.ndim = args.shape.length;
} else {
this.ndim = args.ndim;
}
this.maxNDim = args.maxNDim;
this.minNDim = args.minNDim;
this.axes = args.axes || {};
}
}
/**
* `tf.SymbolicTensor` is a placeholder for a Tensor without any concrete value.
*
* They are most often encountered when building a graph of `Layer`s for a
* `tf.LayersModel` and the input data's shape, but not values are known.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
export class SymbolicTensor {
/* A unique ID for the tensor to be able to differentiate tensors. */
readonly id: number;
// The fully scoped name of this Variable, including a unique suffix if needed
readonly name: string;
// The originally requested fully scoped name of this Variable, not including
// any unique suffix. This may be needed when restoring weights because this
// original name is used as a key.
readonly originalName?: string;
/**
* Rank/dimensionality of the tensor.
*/
readonly rank: number;
/**
* Replacement for _keras_history.
*/
nodeIndex: number;
/**
* Replacement for _keras_history.
*/
tensorIndex: number;
/**
*
* @param dtype
* @param shape
* @param sourceLayer The Layer that produced this symbolic tensor.
* @param inputs The inputs passed to sourceLayer's __call__() method.
* @param nodeIndex
* @param tensorIndex
* @param callArgs The keyword arguments passed to the __call__() method.
* @param name
* @param outputTensorIndex The index of this tensor in the list of outputs
* returned by apply().
*/
constructor(
readonly dtype: DataType, readonly shape: Shape,
public sourceLayer: Layer, readonly inputs: SymbolicTensor[],
readonly callArgs: Kwargs, name?: string,
readonly outputTensorIndex?: number) {
this.id = getNextUniqueTensorId();
if (name != null) {
this.originalName = getScopedTensorName(name);
this.name = getUniqueTensorName(this.originalName);
}
this.rank = shape.length;
}
}
/**
* Constructor arguments for Node.
*/
export interface NodeArgs {
/**
* The layer that takes `inputTensors` and turns them into `outputTensors`.
* (the node gets created when the `call` method of the layer is called).
*/
outboundLayer: Layer;
/**
* A list of layers, the same length as `inputTensors`, the layers from where
* `inputTensors` originate.
*/
inboundLayers: Layer[];
/**
* A list of integers, the same length as `inboundLayers`. `nodeIndices[i]` is
* the origin node of `inputTensors[i]` (necessary since each inbound layer
* might have several nodes, e.g. if the layer is being shared with a
* different data stream).
*/
nodeIndices: number[];
/**
* A list of integers, the same length as `inboundLayers`. `tensorIndices[i]`
* is the index of `inputTensors[i]` within the output of the inbound layer
* (necessary since each inbound layer might have multiple tensor outputs,
* with each one being independently manipulable).
*/
tensorIndices: number[];
/** List of input tensors. */
inputTensors: SymbolicTensor[];
/** List of output tensors. */
outputTensors: SymbolicTensor[];
/** List of input masks (a mask can be a tensor, or null). */
inputMasks: Tensor[];
/** List of output masks (a mask can be a tensor, or null). */
outputMasks: Tensor[];
/** List of input shape tuples. */
inputShapes: Shape|Shape[];
/** List of output shape tuples. */
outputShapes: Shape|Shape[];
}
/**
* The type of the return value of Layer.dispose() and Container.dispose().
*/
export interface DisposeResult {
/**
* Reference count after the dispose call.
*/
refCountAfterDispose: number;
/**
* Number of variables dispose in this dispose call.
*/
numDisposedVariables: number;
}
let _nextNodeID = 0;
/**
* A `Node` describes the connectivity between two layers.
*
* Each time a layer is connected to some new input,
* a node is added to `layer.inboundNodes`.
*
* Each time the output of a layer is used by another layer,
* a node is added to `layer.outboundNodes`.
*
* `nodeIndices` and `tensorIndices` are basically fine-grained coordinates
* describing the origin of the `inputTensors`, verifying the following:
*
* `inputTensors[i] ==
* inboundLayers[i].inboundNodes[nodeIndices[i]].outputTensors[
* tensorIndices[i]]`
*
* A node from layer A to layer B is added to:
* A.outboundNodes
* B.inboundNodes
*/
export class Node {
/**
* The layer that takes `inputTensors` and turns them into `outputTensors`
* (the node gets created when the `call` method of the layer is called).
*/
outboundLayer: Layer;
/**
* A list of layers, the same length as `inputTensors`, the layers from where
* `inputTensors` originate.
*/
inboundLayers: Layer[];
/**
* A list of integers, the same length as `inboundLayers`. `nodeIndices[i]` is
* the origin node of `inputTensors[i]` (necessary since each inbound layer
* might have several nodes, e.g. if the layer is being shared with a
* different data stream).
*/
nodeIndices: number[];
/**
* A list of integers, the same length as `inboundLayers`. `tensorIndices[i]`
* is the index of `inputTensors[i]` within the output of the inbound layer
* (necessary since each inbound layer might have multiple tensor outputs,
* with each one being independently manipulable).
*/
tensorIndices: number[];
/** List of input tensors. */
inputTensors: SymbolicTensor[];
/** List of output tensors. */
outputTensors: SymbolicTensor[];
/** List of input masks (a mask can be a tensor, or null). */
inputMasks: Tensor[];
/** List of output masks (a mask can be a tensor, or null). */
outputMasks: Tensor[];
/** List of input shape tuples. */
inputShapes: Shape|Shape[];
/** List of output shape tuples. */
outputShapes: Shape|Shape[];
readonly id: number;
constructor(
args: NodeArgs,
// TODO(michaelterry): Define actual type for this.
public callArgs?: Kwargs) {
this.id = _nextNodeID++;
/*
Layer instance (NOT a list).
this is the layer that takes a list of input tensors
and turns them into a list of output tensors.
the current node will be added to
the inboundNodes of outboundLayer.
*/
this.outboundLayer = args.outboundLayer;
/*
The following 3 properties describe where
the input tensors come from: which layers,
and for each layer, which node and which
tensor output of each node.
*/
// List of layer instances.
this.inboundLayers = args.inboundLayers;
// List of integers, 1:1 mapping with inboundLayers.
this.nodeIndices = args.nodeIndices;
// List of integers, 1:1 mapping with inboundLayers.
this.tensorIndices = args.tensorIndices;
/*
Following 2 properties:
tensor inputs and outputs of outboundLayer.
*/
// List of tensors. 1:1 mapping with inboundLayers.
this.inputTensors = args.inputTensors;
// List of tensors, created by outboundLayer.call().
this.outputTensors = args.outputTensors;
/*
Following 2 properties: input and output masks.
List of tensors, 1:1 mapping with inputTensor.
*/
this.inputMasks = args.inputMasks;
// List of tensors, created by outboundLayer.computeMask().
this.outputMasks = args.outputMasks;
// Following 2 properties: input and output shapes.
// List of shape tuples, shapes of inputTensors.
this.inputShapes = args.inputShapes;
// List of shape tuples, shapes of outputTensors.
this.outputShapes = args.outputShapes;
// Add nodes to all layers involved.
for (const layer of args.inboundLayers) {
if (layer != null) {
layer.outboundNodes.push(this);
}
}
args.outboundLayer.inboundNodes.push(this);
}
getConfig(): serialization.ConfigDict {
const inboundNames: string[] = [];
for (const layer of this.inboundLayers) {
if (layer != null) {
inboundNames.push(layer.name);
} else {
inboundNames.push(null);
}
}
return {
outboundLayer: this.outboundLayer ? this.outboundLayer.name : null,
inboundLayers: inboundNames,
nodeIndices: this.nodeIndices,
tensorIndices: this.tensorIndices
};
}
}
/** Constructor arguments for Layer. */
export declare interface LayerArgs {
/**
* If defined, will be used to create an input layer to insert before this
* layer. If both `inputShape` and `batchInputShape` are defined,
* `batchInputShape` will be used. This argument is only applicable to input
* layers (the first layer of a model).
*/
inputShape?: Shape;
/**
* If defined, will be used to create an input layer to insert before this
* layer. If both `inputShape` and `batchInputShape` are defined,
* `batchInputShape` will be used. This argument is only applicable to input
* layers (the first layer of a model).
*/
batchInputShape?: Shape;
/**
* If `inputShape` is specified and `batchInputShape` is *not* specified,
* `batchSize` is used to construct the `batchInputShape`: `[batchSize,
* ...inputShape]`
*/
batchSize?: number;
/**
* The data-type for this layer. Defaults to 'float32'.
* This argument is only applicable to input layers (the first layer of a
* model).
*/
dtype?: DataType;
/** Name for this layer. */
name?: string;
/**
* Whether the weights of this layer are updatable by `fit`.
* Defaults to true.
*/
trainable?: boolean;
/**
* Initial weight values of the layer.
*/
weights?: Tensor[];
/** Legacy support. Do not use for new code. */
inputDType?: DataType;
}
// If necessary, add `output` arguments to the CallHook function.
// This is currently used for testing only, but may be used for debugger-related
// purposes in the future.
export type CallHook = (inputs: Tensor|Tensor[], kwargs: Kwargs) => void;
let _nextLayerID = 0;
/**
* A layer is a grouping of operations and weights that can be composed to
* create a `tf.LayersModel`.
*
* Layers are constructed by using the functions under the
* [tf.layers](#Layers-Basic) namespace.
*
* @doc {heading: 'Layers', subheading: 'Classes', namespace: 'layers'}
*/
export abstract class Layer extends serialization.Serializable {
/** Name for this layer. Must be unique within a model. */
name: string;
/**
* List of InputSpec class instances.
*
* Each entry describes one required input:
* - ndim
* - dtype
* A layer with `n` input tensors must have an `inputSpec` of length `n`.
*/
inputSpec: InputSpec[];
supportsMasking: boolean;
/** Whether the layer weights will be updated during training. */
protected trainable_: boolean;
batchInputShape: Shape;
dtype: DataType;
initialWeights: Tensor[];
inboundNodes: Node[];
outboundNodes: Node[];
activityRegularizer: Regularizer;
protected _trainableWeights: LayerVariable[];
private _nonTrainableWeights: LayerVariable[];
private _losses: RegularizerFn[];
// TODO(cais): _updates is currently unused.
private _updates: Tensor[];
private _built: boolean;
private _callHook: CallHook = null;
private _addedWeightNames: string[] = [];
readonly id: number;
// Porting Notes: PyKeras does not have this property in this base Layer
// class. Instead lets Layer subclass set it dynamically and checks the
// value with `hasattr`. In tfjs-layers, we let this be a member of this
// base class.
protected _stateful = false;
protected _refCount: number|null;
// A flag for whether fast (i.e., all-zero) weight initialization is to
// be used during `build()` call. This speeds up weight initialization
// by saving unnecessary calls to expensive initializers in cases where
// the initialized values will be overwritten by loaded weight values
// during model loading.
private fastWeightInitDuringBuild: boolean;
constructor(args: LayerArgs = {}) {
super();
this.id = _nextLayerID++;
this.activityRegularizer = null;
this.inputSpec = null;
this.supportsMasking = false;
// These properties will be set upon call of this.build()
this._trainableWeights = [];
this._nonTrainableWeights = [];
this._losses = [];
this._updates = [];
this._built = false;
/*
These lists will be filled via successive calls
to this.addInboundNode().
*/
this.inboundNodes = [];
this.outboundNodes = [];
let name = args.name;
if (!name) {
const prefix = this.getClassName();
name = generic_utils.toSnakeCase(prefix) + '_' + getUid(prefix);
}
this.name = name;
this.trainable_ = args.trainable == null ? true : args.trainable;
if (args.inputShape != null || args.batchInputShape != null) {
/*
In this case we will later create an input layer
to insert before the current layer
*/
let batchInputShape: Shape;
if (args.batchInputShape != null) {
batchInputShape = args.batchInputShape;
} else if (args.inputShape != null) {
let batchSize: number = null;
if (args.batchSize != null) {
batchSize = args.batchSize;
}
batchInputShape = [batchSize].concat(args.inputShape);
}
this.batchInputShape = batchInputShape;
// Set dtype.
let dtype = args.dtype;
if (dtype == null) {
dtype = args.inputDType;
}
if (dtype == null) {
dtype = 'float32';
}
this.dtype = dtype;
}
if (args.weights != null) {
this.initialWeights = args.weights;
} else {
this.initialWeights = null;
}
// The value of `_refCount` is initialized to null. When the layer is used
// in a symbolic way for the first time, it will be set to 1.
this._refCount = null;
this.fastWeightInitDuringBuild = false;
}
/**
* Converts a layer and its index to a unique (immutable type) name.
* This function is used internally with `this.containerNodes`.
* @param layer The layer.
* @param nodeIndex The layer's position (e.g. via enumerate) in a list of
* nodes.
*
* @returns The unique name.
*/
protected static nodeKey(layer: Layer, nodeIndex: number) {
return layer.name + '_ib-' + nodeIndex.toString();
}
/**
* Returns this.inboundNode at index nodeIndex.
*
* Porting note: This is a replacement for _get_node_attribute_at_index()
* @param nodeIndex
* @param attrName The name of the attribute related to request for this node.
*/
private getNodeAtIndex(nodeIndex: number, attrName: string): Node {
if (this.inboundNodes.length === 0) {
throw new RuntimeError(
'The layer has never been called ' +
`and thus has no defined ${attrName}.`);
}
if (this.inboundNodes.length <= nodeIndex) {
throw new ValueError(
`Asked to get ${attrName} at node ${nodeIndex}, ` +
`but the layer has only ${this.inboundNodes.length} inbound nodes.`);
}
return this.inboundNodes[nodeIndex];
}
/**
* Retrieves the input tensor(s) of a layer at a given node.
*
* @param nodeIndex Integer, index of the node from which to retrieve the
* attribute. E.g. `nodeIndex=0` will correspond to the first time the layer
* was called.
*
* @return A tensor (or list of tensors if the layer has multiple inputs).
*/
getInputAt(nodeIndex: number): SymbolicTensor|SymbolicTensor[] {
return generic_utils.singletonOrArray(
this.getNodeAtIndex(nodeIndex, 'input').inputTensors);
}
/**
* Retrieves the output tensor(s) of a layer at a given node.
*
* @param nodeIndex Integer, index of the node from which to retrieve the
* attribute. E.g. `nodeIndex=0` will correspond to the first time the layer
* was called.
*
* @return A tensor (or list of tensors if the layer has multiple outputs).
*/
getOutputAt(nodeIndex: number): SymbolicTensor|SymbolicTensor[] {
return generic_utils.singletonOrArray(
this.getNodeAtIndex(nodeIndex, 'output').outputTensors);
}
// Properties
/**
* Retrieves the input tensor(s) of a layer.
*
* Only applicable if the layer has exactly one inbound node,
* i.e. if it is connected to one incoming layer.
*
* @return Input tensor or list of input tensors.
*
* @exception AttributeError if the layer is connected to more than one
* incoming layers.
*/
get input(): SymbolicTensor|SymbolicTensor[] {
if (this.inboundNodes.length > 1) {
throw new AttributeError(
`Layer ${this.name}` +
' has multiple inbound nodes, ' +
'hence the notion of "layer input" ' +
'is ill-defined. ' +
'Use `getInputAt(nodeIndex)` instead.');
} else if (this.inboundNodes.length === 0) {
throw new AttributeError(
`Layer ${this.name}` +
' is not connected, no input to return.');
}
return generic_utils.singletonOrArray(
this.getNodeAtIndex(0, 'input').inputTensors);
}
/**
* Retrieves the output tensor(s) of a layer.
*
* Only applicable if the layer has exactly one inbound node,
* i.e. if it is connected to one incoming layer.
*
* @return Output tensor or list of output tensors.
*
* @exception AttributeError if the layer is connected to more than one
* incoming layers.
*/
get output(): SymbolicTensor|SymbolicTensor[] {
if (this.inboundNodes.length === 0) {
throw new AttributeError(
`Layer ${this.name}` +
' has no inbound nodes.');
}
if (this.inboundNodes.length > 1) {
throw new AttributeError(
`Layer ${this.name}` +
' has multiple inbound nodes, ' +
'hence the notion of "layer output" ' +
'is ill-defined. ' +
'Use `getOutputAt(nodeIndex)` instead.');
}
return generic_utils.singletonOrArray(
this.getNodeAtIndex(0, 'output').outputTensors);
}
get losses(): RegularizerFn[] {
return this._losses;
}
/**
* Retrieves the Layer's current loss values.
*
* Used for regularizers during training.
*/
calculateLosses(): Scalar[] {
// Porting Node: This is an augmentation to Layer.loss in PyKeras.
// In PyKeras, Layer.loss returns symbolic tensors. Here a concrete
// Tensor (specifically Scalar) values are returned. This is due to the
// imperative backend.
return this.losses.map(lossFn => lossFn());
}
get updates(): Tensor[] {
return this._updates;
}
get built(): boolean {
return this._built;
}
set built(built: boolean) {
this._built = built;
}
get trainable(): boolean {
return this.trainable_;
}
set trainable(trainable: boolean) {
this._trainableWeights.forEach(w => w.trainable = trainable);
this.trainable_ = trainable;
}
get trainableWeights(): LayerVariable[] {
if (this.trainable_) {
return this._trainableWeights.filter(w => w.trainable);
} else {
return [];
}
}
set trainableWeights(weights: LayerVariable[]) {
this._trainableWeights = weights;
}
get nonTrainableWeights(): LayerVariable[] {
if (this.trainable) {
return this._trainableWeights.filter(w => !w.trainable)
.concat(this._nonTrainableWeights);
} else {
return this._trainableWeights.concat(this._nonTrainableWeights);
}
}
set nonTrainableWeights(weights: LayerVariable[]) {
this._nonTrainableWeights = weights;
}
/**
* The concatenation of the lists trainableWeights and nonTrainableWeights
* (in this order).
*/
get weights(): LayerVariable[] {
return this.trainableWeights.concat(this.nonTrainableWeights);
}
get stateful(): boolean {
return this._stateful;
}
/**
* Reset the states of the layer.
*
* This method of the base Layer class is essentially a no-op.
* Subclasses that are stateful (e.g., stateful RNNs) should override this
* method.
*/
resetStates(): void {
if (!this.stateful) {
throw new Error(
'Cannot call the resetStates() method of a non-stateful Layer ' +
'object.');
}
}
/**
* Checks compatibility between the layer and provided inputs.
*
* This checks that the tensor(s) `input`
* verify the input assumptions of the layer
* (if any). If not, exceptions are raised.
*
* @param inputs Input tensor or list of input tensors.
*
* @exception ValueError in case of mismatch between
* the provided inputs and the expectations of the layer.
*/
protected assertInputCompatibility(inputs: Tensor|Tensor[]|SymbolicTensor|
SymbolicTensor[]): void {
const inputsList = generic_utils.toList(inputs);
if (this.inputSpec == null || this.inputSpec.length === 0) {
return;
}
const inputSpec = generic_utils.toList(this.inputSpec);
if (inputsList.length !== inputSpec.length) {
throw new ValueError(
`Layer ${this.name} expects ${inputSpec.length} inputs, ` +
`but it received ${inputsList.length} input tensors. ` +
`Input received: ${inputs}`);
}
for (let inputIndex = 0; inputIndex < inputsList.length; inputIndex++) {
const x = inputsList[inputIndex];
const spec: InputSpec = inputSpec[inputIndex];
if (spec == null) {
continue;
}
// Check ndim.
const ndim = x.rank;
if (spec.ndim != null) {
if (ndim !== spec.ndim) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ${this.name}: ` +
`expected ndim=${spec.ndim}, found ndim=${ndim}`);
}
}
if (spec.maxNDim != null) {
if (ndim > spec.maxNDim) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ${this.name}` +
`: expected max_ndim=${spec.maxNDim}, found ndim=${ndim}`);
}
}
if (spec.minNDim != null) {
if (ndim < spec.minNDim) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ${this.name}` +
`: expected min_ndim=${spec.minNDim}, found ndim=${ndim}.`);
}
}
// Check dtype.
if (spec.dtype != null) {
if (x.dtype !== spec.dtype) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ${this.name} ` +
`: expected dtype=${spec.dtype}, found dtype=${x.dtype}.`);
}
}
// Check specific shape axes.
if (spec.axes) {
const xShape = x.shape;
for (const key in spec.axes) {
const axis = Number(key);
const value = spec.axes[key];
// Perform Python-style slicing in case axis < 0;
// TODO(cais): Use https://github.com/alvivi/typescript-underscore to
// ensure type safety through Underscore calls.
const xShapeAtAxis =
axis >= 0 ? xShape[axis] : xShape[xShape.length + axis];
if (value != null && [value, null].indexOf(xShapeAtAxis) === -1) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ` +
`${this.name}: expected axis ${axis} of input shape to ` +
`have value ${value} but got shape ${xShape}.`);
}
}
}
// Check shape.
if (spec.shape != null) {
for (let i = 0; i < spec.shape.length; ++i) {
const specDim = spec.shape[i];
const dim = x.shape[i];
if (specDim != null && dim != null) {
if (specDim !== dim) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ` +
`${this.name}: expected shape=${spec.shape}, ` +
`found shape=${x.shape}.`);
}
}
}
}
}
}
/**
* This is where the layer's logic lives.
*
* @param inputs Input tensor, or list/tuple of input tensors.
* @param kwargs Additional keyword arguments.
*
* @return A tensor or list/tuple of tensors.
*/
call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {
return inputs;
}
protected invokeCallHook(inputs: Tensor|Tensor[], kwargs: Kwargs) {
if (this._callHook != null) {
this._callHook(inputs, kwargs);
}
}
/**
* Set call hook.
* This is currently used for testing only.
* @param callHook
*/
setCallHook(callHook: CallHook) {
this._callHook = callHook;
}
/**
* Clear call hook.
* This is currently used for testing only.
*/
clearCallHook() {
this._callHook = null;
}
/**
* Builds or executes a `Layer`'s logic.
*
* When called with `tf.Tensor`(s), execute the `Layer`'s computation and
* return Tensor(s). For example:
*
* ```js
* const denseLayer = tf.layers.dense({
* units: 1,
* kernelInitializer: 'zeros',
* useBias: false
* });
*
* // Invoke the layer's apply() method with a `tf.Tensor` (with concrete
* // numeric values).
* const input = tf.ones([2, 2]);
* const output = denseLayer.apply(input);
*
* // The output's value is expected to be [[0], [0]], due to the fact that
* // the dense layer has a kernel initialized to all-zeros and does not have
* // a bias.
* output.print();
* ```
*
* When called with `tf.SymbolicTensor`(s), this will prepare the layer for
* future execution. This entails internal book-keeping on shapes of
* expected Tensors, wiring layers together, and initializing weights.
*
* Calling `apply` with `tf.SymbolicTensor`s are typically used during the
* building of non-`tf.Sequential` models. For example:
*
* ```js
* const flattenLayer = tf.layers.flatten();
* const denseLayer = tf.layers.dense({units: 1});
*
* // Use tf.layers.input() to obtain a SymbolicTensor as input to apply().
* const input = tf.input({shape: [2, 2]});
* const output1 = flattenLayer.apply(input);
*
* // output1.shape is [null, 4]. The first dimension is the undetermined
* // batch size. The second dimension comes from flattening the [2, 2]
* // shape.
* console.log(JSON.stringify(output1.shape));
*
* // The output SymbolicTensor of the flatten layer can be used to call
* // the apply() of the dense layer:
* const output2 = denseLayer.apply(output1);
*
* // output2.shape is [null, 1]. The first dimension is the undetermined
* // batch size. The second dimension matches the number of units of the
* // dense layer.
* console.log(JSON.stringify(output2.shape));
*
* // The input and output can be used to construct a model that consists
* // of the flatten and dense layers.
* const model = tf.model({inputs: input, outputs: output2});
* ```
*
* @param inputs a `tf.Tensor` or `tf.SymbolicTensor` or an Array of them.
* @param kwargs Additional keyword arguments to be passed to `call()`.
*
* @return Output of the layer's `call` method.
*
* @exception ValueError error in case the layer is missing shape information
* for its `build` call.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
// Porting Note: This is a replacement for __call__() in Python.
apply(
inputs: Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[],
kwargs?: Kwargs): Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[] {
kwargs = kwargs || {};
this.assertNotDisposed();
// Ensure inputs are all the same type.
const inputsList = generic_utils.toList(inputs);
const allAreSymbolic = checkAllSymbolic(inputs);
const noneAreSymbolic = checkNoneSymbolic(inputs);
if (allAreSymbolic === noneAreSymbolic) {
throw new ValueError(
'Arguments to apply() must be all ' +
'SymbolicTensors or all Tensors');
}
// TODO(michaelterry): nameScope() may not be necessary.
return nameScope(this.name, () => {
// Handle laying building (weight creating, input spec locking).
if (!this.built) {
/*
Throw exceptions in case the input is not compatible
with the inputSpec specified in the layer constructor.
*/
this.assertInputCompatibility(inputs);
// Collect input shapes to build layer.
const inputShapes: Shape[] = [];
for (const xElem of generic_utils.toList(inputs)) {
inputShapes.push(xElem.shape);
}
this.build(generic_utils.singletonOrArray(inputShapes));
this.built = true;
// Load weights that were specified at layer instantiation.
if (this.initialWeights) {
this.setWeights(this.initialWeights);
}
if (this._refCount === null && noneAreSymbolic) {
// The first use of this layer is a non-symbolic call, set ref count
// to 1 so the Layer can be properly disposed if its dispose() method
// is called.
this._refCount = 1;
}
}
/*
Throw exceptions in case the input is not compatible
with the inputSpec set at build time.
*/