-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathinitializers.ts
668 lines (588 loc) · 19.3 KB
/
initializers.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
/**
* @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.
* =============================================================================
*/
import {DataType, eye, linalg, mul, ones, randomUniform, scalar, serialization, Tensor, tidy, truncatedNormal, util, zeros} from '@tensorflow/tfjs-core';
import * as K from './backend/tfjs_backend';
import {checkDataFormat} from './common';
import {NotImplementedError, ValueError} from './errors';
import {DataFormat, Shape} from './keras_format/common';
import {Distribution, FanMode, VALID_DISTRIBUTION_VALUES, VALID_FAN_MODE_VALUES} from './keras_format/initializer_config';
import {checkStringTypeUnionValue, deserializeKerasObject, serializeKerasObject} from './utils/generic_utils';
import {arrayProd} from './utils/math_utils';
export function checkFanMode(value?: string): void {
checkStringTypeUnionValue(VALID_FAN_MODE_VALUES, 'FanMode', value);
}
export function checkDistribution(value?: string): void {
checkStringTypeUnionValue(VALID_DISTRIBUTION_VALUES, 'Distribution', value);
}
/**
* Initializer base class.
*
* @doc {
* heading: 'Initializers', subheading: 'Classes', namespace: 'initializers'}
*/
export abstract class Initializer extends serialization.Serializable {
public fromConfigUsesCustomObjects(): boolean {
return false;
}
/**
* Generate an initial value.
* @param shape
* @param dtype
* @return The init value.
*/
abstract apply(shape: Shape, dtype?: DataType): Tensor;
getConfig(): serialization.ConfigDict {
return {};
}
}
export class Zeros extends Initializer {
/** @nocollapse */
static className = 'Zeros';
apply(shape: Shape, dtype?: DataType): Tensor {
return zeros(shape, dtype);
}
}
serialization.registerClass(Zeros);
export class Ones extends Initializer {
/** @nocollapse */
static className = 'Ones';
apply(shape: Shape, dtype?: DataType): Tensor {
return ones(shape, dtype);
}
}
serialization.registerClass(Ones);
export interface ConstantArgs {
/** The value for each element in the variable. */
value: number;
}
export class Constant extends Initializer {
/** @nocollapse */
static className = 'Constant';
private value: number;
constructor(args: ConstantArgs) {
super();
if (typeof args !== 'object') {
throw new ValueError(
`Expected argument of type ConstantConfig but got ${args}`);
}
if (args.value === undefined) {
throw new ValueError(`config must have value set but got ${args}`);
}
this.value = args.value;
}
apply(shape: Shape, dtype?: DataType): Tensor {
return tidy(() => mul(scalar(this.value), ones(shape, dtype)));
}
override getConfig(): serialization.ConfigDict {
return {
value: this.value,
};
}
}
serialization.registerClass(Constant);
export interface RandomUniformArgs {
/** Lower bound of the range of random values to generate. */
minval?: number;
/** Upper bound of the range of random values to generate. */
maxval?: number;
/** Used to seed the random generator. */
seed?: number;
}
export class RandomUniform extends Initializer {
/** @nocollapse */
static className = 'RandomUniform';
readonly DEFAULT_MINVAL = -0.05;
readonly DEFAULT_MAXVAL = 0.05;
private minval: number;
private maxval: number;
private seed: number;
constructor(args: RandomUniformArgs) {
super();
this.minval = args.minval || this.DEFAULT_MINVAL;
this.maxval = args.maxval || this.DEFAULT_MAXVAL;
this.seed = args.seed;
}
apply(shape: Shape, dtype?: DataType): Tensor {
return randomUniform(shape, this.minval, this.maxval, dtype, this.seed);
}
override getConfig(): serialization.ConfigDict {
return {minval: this.minval, maxval: this.maxval, seed: this.seed};
}
}
serialization.registerClass(RandomUniform);
export interface RandomNormalArgs {
/** Mean of the random values to generate. */
mean?: number;
/** Standard deviation of the random values to generate. */
stddev?: number;
/** Used to seed the random generator. */
seed?: number;
}
export class RandomNormal extends Initializer {
/** @nocollapse */
static className = 'RandomNormal';
readonly DEFAULT_MEAN = 0.;
readonly DEFAULT_STDDEV = 0.05;
private mean: number;
private stddev: number;
private seed: number;
constructor(args: RandomNormalArgs) {
super();
this.mean = args.mean || this.DEFAULT_MEAN;
this.stddev = args.stddev || this.DEFAULT_STDDEV;
this.seed = args.seed;
}
apply(shape: Shape, dtype?: DataType): Tensor {
dtype = dtype || 'float32';
if (dtype !== 'float32' && dtype !== 'int32') {
throw new NotImplementedError(
`randomNormal does not support dType ${dtype}.`);
}
return K.randomNormal(shape, this.mean, this.stddev, dtype, this.seed);
}
override getConfig(): serialization.ConfigDict {
return {mean: this.mean, stddev: this.stddev, seed: this.seed};
}
}
serialization.registerClass(RandomNormal);
export interface TruncatedNormalArgs {
/** Mean of the random values to generate. */
mean?: number;
/** Standard deviation of the random values to generate. */
stddev?: number;
/** Used to seed the random generator. */
seed?: number;
}
export class TruncatedNormal extends Initializer {
/** @nocollapse */
static className = 'TruncatedNormal';
readonly DEFAULT_MEAN = 0.;
readonly DEFAULT_STDDEV = 0.05;
private mean: number;
private stddev: number;
private seed: number;
constructor(args: TruncatedNormalArgs) {
super();
this.mean = args.mean || this.DEFAULT_MEAN;
this.stddev = args.stddev || this.DEFAULT_STDDEV;
this.seed = args.seed;
}
apply(shape: Shape, dtype?: DataType): Tensor {
dtype = dtype || 'float32';
if (dtype !== 'float32' && dtype !== 'int32') {
throw new NotImplementedError(
`truncatedNormal does not support dType ${dtype}.`);
}
return truncatedNormal(shape, this.mean, this.stddev, dtype, this.seed);
}
override getConfig(): serialization.ConfigDict {
return {mean: this.mean, stddev: this.stddev, seed: this.seed};
}
}
serialization.registerClass(TruncatedNormal);
export interface IdentityArgs {
/**
* Multiplicative factor to apply to the identity matrix.
*/
gain?: number;
}
export class Identity extends Initializer {
/** @nocollapse */
static className = 'Identity';
private gain: number;
constructor(args: IdentityArgs) {
super();
this.gain = args.gain != null ? args.gain : 1.0;
}
apply(shape: Shape, dtype?: DataType): Tensor {
return tidy(() => {
if (shape.length !== 2 || shape[0] !== shape[1]) {
throw new ValueError(
'Identity matrix initializer can only be used for' +
' 2D square matrices.');
} else {
return mul(this.gain, eye(shape[0]));
}
});
}
override getConfig(): serialization.ConfigDict {
return {gain: this.gain};
}
}
serialization.registerClass(Identity);
/**
* Computes the number of input and output units for a weight shape.
* @param shape Shape of weight.
* @param dataFormat data format to use for convolution kernels.
* Note that all kernels in Keras are standardized on the
* CHANNEL_LAST ordering (even when inputs are set to CHANNEL_FIRST).
* @return An length-2 array: fanIn, fanOut.
*/
function computeFans(
shape: Shape, dataFormat: DataFormat = 'channelsLast'): number[] {
let fanIn: number;
let fanOut: number;
checkDataFormat(dataFormat);
if (shape.length === 2) {
fanIn = shape[0];
fanOut = shape[1];
} else if ([3, 4, 5].indexOf(shape.length) !== -1) {
if (dataFormat === 'channelsFirst') {
const receptiveFieldSize = arrayProd(shape, 2);
fanIn = shape[1] * receptiveFieldSize;
fanOut = shape[0] * receptiveFieldSize;
} else if (dataFormat === 'channelsLast') {
const receptiveFieldSize = arrayProd(shape, 0, shape.length - 2);
fanIn = shape[shape.length - 2] * receptiveFieldSize;
fanOut = shape[shape.length - 1] * receptiveFieldSize;
}
} else {
const shapeProd = arrayProd(shape);
fanIn = Math.sqrt(shapeProd);
fanOut = Math.sqrt(shapeProd);
}
return [fanIn, fanOut];
}
export interface VarianceScalingArgs {
/** Scaling factor (positive float). */
scale?: number;
/** Fanning mode for inputs and outputs. */
mode?: FanMode;
/** Probabilistic distribution of the values. */
distribution?: Distribution;
/** Random number generator seed. */
seed?: number;
}
export class VarianceScaling extends Initializer {
/** @nocollapse */
static className = 'VarianceScaling';
private scale: number;
private mode: FanMode;
private distribution: Distribution;
private seed: number;
/**
* Constructor of VarianceScaling.
* @throws ValueError for invalid value in scale.
*/
constructor(args: VarianceScalingArgs) {
super();
if (args.scale < 0.0) {
throw new ValueError(
`scale must be a positive float. Got: ${args.scale}`);
}
this.scale = args.scale == null ? 1.0 : args.scale;
this.mode = args.mode == null ? 'fanIn' : args.mode;
checkFanMode(this.mode);
this.distribution =
args.distribution == null ? 'normal' : args.distribution;
checkDistribution(this.distribution);
this.seed = args.seed;
}
apply(shape: Shape, dtype?: DataType): Tensor {
const fans = computeFans(shape);
const fanIn = fans[0];
const fanOut = fans[1];
let scale = this.scale;
if (this.mode === 'fanIn') {
scale /= Math.max(1, fanIn);
} else if (this.mode === 'fanOut') {
scale /= Math.max(1, fanOut);
} else {
scale /= Math.max(1, (fanIn + fanOut) / 2);
}
if (this.distribution === 'normal') {
const stddev = Math.sqrt(scale);
dtype = dtype || 'float32';
if (dtype !== 'float32' && dtype !== 'int32') {
throw new NotImplementedError(
`${this.getClassName()} does not support dType ${dtype}.`);
}
return truncatedNormal(shape, 0, stddev, dtype, this.seed);
} else {
const limit = Math.sqrt(3 * scale);
return randomUniform(shape, -limit, limit, dtype, this.seed);
}
}
override getConfig(): serialization.ConfigDict {
return {
scale: this.scale,
mode: this.mode,
distribution: this.distribution,
seed: this.seed
};
}
}
serialization.registerClass(VarianceScaling);
export interface SeedOnlyInitializerArgs {
/** Random number generator seed. */
seed?: number;
}
export class GlorotUniform extends VarianceScaling {
/** @nocollapse */
static override className = 'GlorotUniform';
/**
* Constructor of GlorotUniform
* @param scale
* @param mode
* @param distribution
* @param seed
*/
constructor(args?: SeedOnlyInitializerArgs) {
super({
scale: 1.0,
mode: 'fanAvg',
distribution: 'uniform',
seed: args == null ? null : args.seed
});
}
override getClassName(): string {
// In Python Keras, GlorotUniform is not a class, but a helper method
// that creates a VarianceScaling object. Use 'VarianceScaling' as
// class name to be compatible with that.
return VarianceScaling.className;
}
}
serialization.registerClass(GlorotUniform);
export class GlorotNormal extends VarianceScaling {
/** @nocollapse */
static override className = 'GlorotNormal';
/**
* Constructor of GlorotNormal.
* @param scale
* @param mode
* @param distribution
* @param seed
*/
constructor(args?: SeedOnlyInitializerArgs) {
super({
scale: 1.0,
mode: 'fanAvg',
distribution: 'normal',
seed: args == null ? null : args.seed
});
}
override getClassName(): string {
// In Python Keras, GlorotNormal is not a class, but a helper method
// that creates a VarianceScaling object. Use 'VarianceScaling' as
// class name to be compatible with that.
return VarianceScaling.className;
}
}
serialization.registerClass(GlorotNormal);
export class HeNormal extends VarianceScaling {
/** @nocollapse */
static override className = 'HeNormal';
constructor(args?: SeedOnlyInitializerArgs) {
super({
scale: 2.0,
mode: 'fanIn',
distribution: 'normal',
seed: args == null ? null : args.seed
});
}
override getClassName(): string {
// In Python Keras, HeNormal is not a class, but a helper method
// that creates a VarianceScaling object. Use 'VarianceScaling' as
// class name to be compatible with that.
return VarianceScaling.className;
}
}
serialization.registerClass(HeNormal);
export class HeUniform extends VarianceScaling {
/** @nocollapse */
static override className = 'HeUniform';
constructor(args?: SeedOnlyInitializerArgs) {
super({
scale: 2.0,
mode: 'fanIn',
distribution: 'uniform',
seed: args == null ? null : args.seed
});
}
override getClassName(): string {
// In Python Keras, HeUniform is not a class, but a helper method
// that creates a VarianceScaling object. Use 'VarianceScaling' as
// class name to be compatible with that.
return VarianceScaling.className;
}
}
serialization.registerClass(HeUniform);
export class LeCunNormal extends VarianceScaling {
/** @nocollapse */
static override className = 'LeCunNormal';
constructor(args?: SeedOnlyInitializerArgs) {
super({
scale: 1.0,
mode: 'fanIn',
distribution: 'normal',
seed: args == null ? null : args.seed
});
}
override getClassName(): string {
// In Python Keras, LeCunNormal is not a class, but a helper method
// that creates a VarianceScaling object. Use 'VarianceScaling' as
// class name to be compatible with that.
return VarianceScaling.className;
}
}
serialization.registerClass(LeCunNormal);
export class LeCunUniform extends VarianceScaling {
/** @nocollapse */
static override className = 'LeCunUniform';
constructor(args?: SeedOnlyInitializerArgs) {
super({
scale: 1.0,
mode: 'fanIn',
distribution: 'uniform',
seed: args == null ? null : args.seed
});
}
override getClassName(): string {
// In Python Keras, LeCunUniform is not a class, but a helper method
// that creates a VarianceScaling object. Use 'VarianceScaling' as
// class name to be compatible with that.
return VarianceScaling.className;
}
}
serialization.registerClass(LeCunUniform);
export interface OrthogonalArgs extends SeedOnlyInitializerArgs {
/**
* Multiplicative factor to apply to the orthogonal matrix. Defaults to 1.
*/
gain?: number;
}
export class Orthogonal extends Initializer {
/** @nocollapse */
static className = 'Orthogonal';
readonly DEFAULT_GAIN = 1;
readonly ELEMENTS_WARN_SLOW = 2000;
protected readonly gain: number;
protected readonly seed: number;
constructor(args?: OrthogonalArgs) {
super();
this.gain = args.gain == null ? this.DEFAULT_GAIN : args.gain;
this.seed = args.seed;
}
apply(shape: Shape, dtype?: DataType): Tensor {
return tidy(() => {
if (shape.length < 2) {
throw new NotImplementedError('Shape must be at least 2D.');
}
if (dtype !== 'int32' && dtype !== 'float32' && dtype !== undefined) {
throw new TypeError(`Unsupported data type ${dtype}.`);
}
dtype = dtype as 'int32' | 'float32' | undefined;
// flatten the input shape with the last dimension remaining its
// original shape so it works for conv2d
const numRows = util.sizeFromShape(shape.slice(0, -1));
const numCols = shape[shape.length - 1];
const numElements = numRows * numCols;
if (numElements > this.ELEMENTS_WARN_SLOW) {
console.warn(
`Orthogonal initializer is being called on a matrix with more ` +
`than ${this.ELEMENTS_WARN_SLOW} (${numElements}) elements: ` +
`Slowness may result.`);
}
const flatShape =
[Math.max(numCols, numRows), Math.min(numCols, numRows)];
// Generate a random matrix
const randNormalMat = K.randomNormal(flatShape, 0, 1, dtype, this.seed);
// Compute QR factorization
const qr = linalg.qr(randNormalMat, false);
let qMat = qr[0];
const rMat = qr[1];
// Make Q uniform
const diag = rMat.flatten().stridedSlice(
[0], [Math.min(numCols, numRows) * Math.min(numCols, numRows)],
[Math.min(numCols, numRows) + 1]);
qMat = mul(qMat, diag.sign());
if (numRows < numCols) {
qMat = qMat.transpose();
}
return mul(scalar(this.gain), qMat.reshape(shape));
});
}
override getConfig(): serialization.ConfigDict {
return {
gain: this.gain,
seed: this.seed,
};
}
}
serialization.registerClass(Orthogonal);
/** @docinline */
export type InitializerIdentifier =
'constant'|'glorotNormal'|'glorotUniform'|'heNormal'|'heUniform'|'identity'|
'leCunNormal'|'leCunUniform'|'ones'|'orthogonal'|'randomNormal'|
'randomUniform'|'truncatedNormal'|'varianceScaling'|'zeros'|string;
// Maps the JavaScript-like identifier keys to the corresponding registry
// symbols.
export const INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP:
{[identifier in InitializerIdentifier]: string} = {
'constant': 'Constant',
'glorotNormal': 'GlorotNormal',
'glorotUniform': 'GlorotUniform',
'heNormal': 'HeNormal',
'heUniform': 'HeUniform',
'identity': 'Identity',
'leCunNormal': 'LeCunNormal',
'leCunUniform': 'LeCunUniform',
'ones': 'Ones',
'orthogonal': 'Orthogonal',
'randomNormal': 'RandomNormal',
'randomUniform': 'RandomUniform',
'truncatedNormal': 'TruncatedNormal',
'varianceScaling': 'VarianceScaling',
'zeros': 'Zeros'
};
function deserializeInitializer(
config: serialization.ConfigDict,
customObjects: serialization.ConfigDict = {}): Initializer {
return deserializeKerasObject(
config, serialization.SerializationMap.getMap().classNameMap,
customObjects, 'initializer');
}
export function serializeInitializer(initializer: Initializer):
serialization.ConfigDictValue {
return serializeKerasObject(initializer);
}
export function getInitializer(identifier: InitializerIdentifier|Initializer|
serialization.ConfigDict): Initializer {
if (typeof identifier === 'string') {
const className = identifier in INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP ?
INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[identifier] :
identifier;
/* We have four 'helper' classes for common initializers that
all get serialized as 'VarianceScaling' and shouldn't go through
the deserializeInitializer pathway. */
if (className === 'GlorotNormal') {
return new GlorotNormal();
} else if (className === 'GlorotUniform') {
return new GlorotUniform();
} else if (className === 'HeNormal') {
return new HeNormal();
} else if (className === 'HeUniform') {
return new HeUniform();
} else if (className === 'LeCunNormal') {
return new LeCunNormal();
} else if (className === 'LeCunUniform') {
return new LeCunUniform();
} else {
const config: serialization.ConfigDict = {};
config['className'] = className;
config['config'] = {};
return deserializeInitializer(config);
}
} else if (identifier instanceof Initializer) {
return identifier;
} else {
return deserializeInitializer(identifier);
}
}