-
Notifications
You must be signed in to change notification settings - Fork 1
/
graph.ts
1284 lines (1104 loc) · 39 KB
/
graph.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
import type { AmeoActivationIdentifier } from '../../nn/customRNN';
import { nativeFusedInterpolatedAmeoImplInner } from '../../nn/ameoActivation/native';
import * as GVB from 'graphviz-builder';
import { writable, type Writable } from 'svelte/store';
import type { InputSeqGenerator } from '../nodeViz/NodeViz';
export interface RNNCellWeights {
initialState: Float32Array;
stateSize: number;
outputSize: number;
recurrentTreeWeights: Float32Array;
recurrentTreeBias?: Float32Array;
outputTreeWeights: Float32Array;
outputTreeBias?: Float32Array;
outputActivation: AmeoActivationIdentifier;
recurrentActivation: AmeoActivationIdentifier;
}
export interface PostLayerWeights {
inputDim: number;
outputDim: number;
weights: Float32Array;
bias?: Float32Array;
activation: AmeoActivationIdentifier | 'linear' | 'tanh';
}
export interface RNNGraphParams {
clipThreshold: number;
/**
* Weights are quantized to the nearest multiple of `quantizationInterval`
*/
quantizationInterval: number;
}
const DefaultRNNGraphParams: { [K in keyof RNNGraphParams]: NonNullable<RNNGraphParams[K]> } = {
clipThreshold: 0.1,
quantizationInterval: 1,
};
const mergeNonNullable = <T>(a: T, b: Partial<T>): T => {
const result = { ...a };
for (const key in b) {
if (b[key] !== undefined) {
result[key] = b[key]!;
}
}
return result;
};
export interface SparseWeight {
weight: number;
/**
* Index of the neuron in the previous layer
*/
index: number;
inputNeuron: SparseNeuron;
}
export class SparseNeuron {
public weights: SparseWeight[];
public bias: number;
public name: string;
private activationID: AmeoActivationIdentifier | 'linear' | 'tanh';
public activation: (x: number) => number = x => x;
private curOutputCache: number | null = null;
constructor(
weights: SparseWeight[],
bias: number,
name: string,
activationID: AmeoActivationIdentifier | 'linear' | 'tanh' = 'linear'
) {
this.weights = weights;
this.bias = bias;
this.name = name;
this.activationID = activationID;
const activation = buildActivation(activationID);
if (activation) {
this.activation = activation;
}
}
public getOutput(): number {
if (this.curOutputCache !== null) {
return this.curOutputCache;
}
const weightedSum = this.weights.reduce((sum, { weight, inputNeuron }) => {
const output = inputNeuron.getOutput();
return sum + weight * output;
}, this.bias);
const output = this.activation(weightedSum);
this.curOutputCache = output;
return output;
}
public advanceSequence() {
this.curOutputCache = null;
}
public serialize(): SerializedSparseNeuron {
return {
weights: this.weights.map(({ weight, index }) => ({ weight, index })),
bias: this.bias,
name: this.name,
activation: this.activationID,
};
}
public static deserialize(
serialized: SerializedSparseNeuron,
prevLayer: GraphRNNLayer,
_index: number
) {
const { weights, bias, name, activation } = serialized;
const neuron = new SparseNeuron(
weights.map(({ weight, index }) => {
const inputNeuron = prevLayer.getNeuron(index);
if (!inputNeuron) {
throw new Error(`No input neuron for neuron ${name} with index ${index}`);
}
return { weight, index, inputNeuron };
}),
bias,
name,
activation
);
return neuron;
}
public reset() {
this.curOutputCache = null;
}
}
export class InputNeuron extends SparseNeuron {
public index: number;
private inputSequence: Float32Array[] = [];
constructor(index: number) {
const name = `input_${index}`;
super([], 0, name);
this.index = index;
}
public setInputSequence(inputSequence: Float32Array[]) {
this.inputSequence = inputSequence;
}
public getOutput(): number {
if (!this.inputSequence.length) {
throw new Error('Input sequence is empty');
}
const input = this.inputSequence[0];
if (typeof input[this.index] !== 'number') {
throw new Error(`Input sequence is missing index ${this.index}`);
}
return input[this.index];
}
public advanceSequence() {
this.inputSequence.shift();
}
public serialize(): SerializedSparseNeuron {
return {
name: this.name,
activation: 'linear',
weights: [],
bias: 0,
};
}
public static deserialize(
serialized: SerializedSparseNeuron,
_prevLayer: GraphRNNLayer,
index: number
) {
const { name } = serialized;
const neuron = new InputNeuron(index);
neuron.name = name;
return neuron;
}
}
export class OutputNeuron extends SparseNeuron {
public index: number;
constructor(index: number, prevLayer: GraphRNNLayer) {
const inputNeuron = prevLayer.getNeuron(index);
const weights = [];
if (!inputNeuron) {
console.error(`No input neuron for output neuron ${index}`, { prevLayer, index });
} else {
weights.push({ index, inputNeuron, weight: 1 });
}
const name = `output_${index}`;
super(weights, 0, name);
this.index = index;
}
public serialize(): SerializedSparseNeuron {
return {
name: this.name,
activation: 'linear',
weights: this.weights.map(({ weight, index }) => ({ weight, index })),
bias: this.bias,
};
}
public static deserialize(
serialized: ReturnType<OutputNeuron['serialize']>,
prevLayer: GraphRNNLayer
) {
const { name, weights, bias } = serialized;
const neuron = new OutputNeuron(weights[0].index, prevLayer);
neuron.name = name;
neuron.bias = bias;
return neuron;
}
}
export class StateNeuron extends SparseNeuron {
public layerIx: number;
public index: number;
public initialState: number;
private state: number;
/**
* When advancing the sequence, we compute next states by pulling through the graph from
* connected neurons to this state. However, we have to be sure to wait until all the
* neurons have computed new states before we update the state of this neuron so that the other
* state neurons computing new states will have the correct previous state to pull through.
*
* This variable holds the new state that we will update to after all the neurons have computed
* their new states.
*/
private pendingNewState = 0;
constructor(layerIx: number, index: number, initialState: number) {
const name = `layer_${layerIx}_state_${index}`;
super([], 0, name);
this.layerIx = layerIx;
this.index = index;
this.initialState = initialState;
this.state = initialState;
}
public getOutput(): number {
return this.state;
}
public computeNewState() {
const newState = SparseNeuron.prototype.getOutput.call(this);
this.pendingNewState = newState;
}
public commitNewState() {
this.state = this.pendingNewState;
}
public reset() {
this.state = this.initialState;
}
/**
* Adds the recurrent connection to the recurrent layer. This is called after
* the layer has been fully populated so we have access to all the neurons.
*/
public connect(index: number, recurrentNeuron: SparseNeuron) {
this.weights.push({ index, inputNeuron: recurrentNeuron, weight: 1 });
}
public serialize(): SerializedSparseNeuron {
return {
bias: this.initialState,
name: this.name,
activation: 'linear',
weights: this.weights.map(({ weight, index }) => ({ weight, index })),
};
}
public static deserialize(serialized: SerializedSparseNeuron, prevLayer: GraphRNNLayer) {
const { name, weights, bias } = serialized;
const neuron = new StateNeuron(0, 0, bias);
neuron.name = name;
neuron.weights = weights.map(({ weight, index }) => {
const inputNeuron = prevLayer.getNeuron(index);
if (!inputNeuron) {
throw new Error(`No input neuron for state neuron ${name} with index ${index}`);
}
return { weight, index, inputNeuron };
});
return neuron;
}
}
export abstract class GraphRNNLayer {
abstract outputDim: number;
abstract getNeuron(outputIx: number): SparseNeuron | undefined;
abstract advanceSequence(): void;
abstract serialize(): Record<string, any>;
static deserialize: (serialized: Record<string, any>) => GraphRNNLayer;
}
export class GraphRNNInputLayer implements GraphRNNLayer {
public inputDim: number;
public outputDim: number;
public neurons: InputNeuron[] = [];
private inputSequence: Float32Array[] = [];
constructor(inputDim: number) {
this.inputDim = inputDim;
this.outputDim = inputDim;
for (let i = 0; i < inputDim; i += 1) {
this.neurons.push(new InputNeuron(i));
}
}
public setInputSequence(inputSequence: Float32Array[]) {
this.inputSequence = inputSequence;
this.neurons.forEach(neuron => neuron.setInputSequence([...inputSequence]));
}
getNeuron(outputIx: number): SparseNeuron | undefined {
return this.neurons[outputIx];
}
public get size(): number {
return this.neurons.length;
}
public advanceSequence() {
this.neurons.forEach(neuron => neuron.advanceSequence());
}
public serialize(): SerializedGraphRNNInputLayer {
return { neurons: serializeSparseNeurons(this.neurons) };
}
public static deserialize(serialized: SerializedGraphRNNInputLayer): GraphRNNInputLayer {
const { neurons } = serialized;
const layer = new GraphRNNInputLayer(neurons.length);
layer.neurons = new Array(neurons.length);
for (let i = 0; i < neurons.length; i += 1) {
const neuron = neurons[i];
if (neuron) {
layer.neurons[i] = InputNeuron.deserialize(neuron, layer, i);
}
}
return layer;
}
}
const serializeSparseNeurons = (neurons: SparseNeuron[]): (SerializedSparseNeuron | null)[] => {
const serializedNeurons: (SerializedSparseNeuron | null)[] = [];
for (let i = 0; i < neurons.length; i += 1) {
serializedNeurons.push(neurons[i]?.serialize() ?? null);
}
return serializedNeurons;
};
interface SerializedGraphRNNInputLayer {
neurons: (SerializedSparseNeuron | null)[];
}
/**
* Represents the output tensor of a GraphRNN
*/
export class GraphRNNOutputs implements GraphRNNLayer {
public outputDim: number;
public neurons: OutputNeuron[] = [];
constructor(outputDim: number, prevLayer: GraphRNNLayer) {
this.outputDim = outputDim;
for (let i = 0; i < outputDim; i += 1) {
this.neurons.push(new OutputNeuron(i, prevLayer));
}
}
getNeuron(outputIx: number): SparseNeuron | undefined {
return this.neurons[outputIx];
}
public get size(): number {
return this.neurons.length;
}
public advanceSequence(): void {
this.neurons.forEach(neuron => neuron.advanceSequence());
}
public reset(): void {
this.neurons.forEach(neuron => neuron.reset());
}
public serialize(): SerializedRNNOutputLayer {
return { neurons: serializeSparseNeurons(this.neurons) };
}
public static deserialize(serialized: SerializedRNNOutputLayer, prevLayer: GraphRNNLayer) {
const { neurons } = serialized;
const layer = new GraphRNNOutputs(neurons.length, prevLayer);
layer.neurons = new Array(neurons.length);
for (let i = 0; i < neurons.length; i += 1) {
const neuron = neurons[i];
if (!neuron) {
continue;
}
layer.neurons[i] = OutputNeuron.deserialize(neuron, prevLayer);
}
return layer;
}
}
interface SerializedRNNOutputLayer {
neurons: (SerializedSparseNeuron | null)[];
}
const buildActivation = (
id: AmeoActivationIdentifier | 'linear' | 'tanh'
): ((x: number) => number) => {
if (id === 'linear') {
return x => x;
} else if (id === 'tanh') {
return x => Math.tanh(x);
}
if (typeof id === 'string') {
throw new Error('Unimplemented');
}
switch (id.type) {
case 'leakyAmeo':
return x => nativeFusedInterpolatedAmeoImplInner(1, x, id.leakyness ?? 0);
case 'interpolatedAmeo':
return x => nativeFusedInterpolatedAmeoImplInner(id.factor, x, id.leakyness ?? 0);
default:
throw new Error(`Unknown activation type ${id.type}`);
}
};
export class GraphRNNCell implements GraphRNNLayer {
public outputDim: number;
public recurrentNeurons: SparseNeuron[] = [];
public outputNeurons: SparseNeuron[] = [];
public stateNeurons: StateNeuron[] = [];
constructor(outputDim: number) {
this.outputDim = outputDim;
}
public static fromWeights(
layerIx: number,
weights: RNNCellWeights,
params: RNNGraphParams,
prevLayer: GraphRNNLayer
) {
const layer = new GraphRNNCell(weights.outputSize);
layer.outputDim = weights.outputSize;
const recurrentWeightsData = clipAndQuantizeWeights(weights.recurrentTreeWeights, params);
const recurrentBiasData = weights.recurrentTreeBias
? clipAndQuantizeWeights(weights.recurrentTreeBias, params)
: null;
const outputWeightsData = clipAndQuantizeWeights(weights.outputTreeWeights, params);
const outputBiasData = weights.outputTreeBias
? clipAndQuantizeWeights(weights.outputTreeBias, params)
: null;
const initialStateData = clipAndQuantizeWeights(weights.initialState, params);
if (initialStateData.length !== weights.stateSize) {
console.error({ weights, initialStateData });
throw new Error(
`Unexpected initial state length; expected=${weights.stateSize} actual=${initialStateData.length}`
);
}
const getInputNeuron = (outputIx: number): SparseNeuron | undefined => {
// Inputs to the output and recurrent tree are created by concatenating the inputs and the state
if (outputIx < prevLayer.outputDim) {
return prevLayer.getNeuron(outputIx);
}
const stateIx = outputIx - prevLayer.outputDim;
if (!layer.stateNeurons[stateIx]) {
const initialState = initialStateData[stateIx];
if (initialState === undefined) {
throw new Error(`Unexpected undefined initial state; stateIx=${stateIx}`);
}
const stateNeuron = new StateNeuron(layerIx, stateIx, initialState);
layer.stateNeurons[stateIx] = stateNeuron;
}
return layer.stateNeurons[stateIx];
};
// (input_shape[-1] + self.state_size, self.output_dim)
const outputKernelShape = [prevLayer.outputDim + weights.stateSize, weights.outputSize];
for (let outputNeuronIx = 0; outputNeuronIx < weights.outputSize; outputNeuronIx += 1) {
const weightsForNeuron: SparseWeight[] = [];
for (let weightIx = 0; weightIx < outputKernelShape[0]; weightIx += 1) {
const tensorIx = weightIx * outputKernelShape[1]! + outputNeuronIx;
const weight = outputWeightsData[tensorIx];
if (weight === undefined) {
throw new Error(
`Unexpected undefined weight in output kernel; tensorIx=${tensorIx}. shape=${outputKernelShape}`
);
}
if (weight === 0) {
continue;
}
const inputNeuron = getInputNeuron(weightIx);
if (!inputNeuron) {
continue;
}
weightsForNeuron.push({ weight, index: weightIx, inputNeuron });
}
if (weightsForNeuron.length === 0 && outputBiasData?.[outputNeuronIx] === 0) {
continue;
}
const name = `layer_${layerIx}_output_${outputNeuronIx}`;
const neuron = new SparseNeuron(
weightsForNeuron,
outputBiasData?.[outputNeuronIx] ?? 0,
name,
weights.outputActivation
);
layer.outputNeurons[outputNeuronIx] = neuron;
}
// (input_shape[-1] + self.state_size, self.state_size)
const recurrentKernelShape = [prevLayer.outputDim + weights.stateSize, weights.stateSize];
for (let recurrentNeuronIx = 0; recurrentNeuronIx < weights.stateSize; recurrentNeuronIx += 1) {
const weightsForNeuron: SparseWeight[] = [];
for (let weightIx = 0; weightIx < recurrentKernelShape[0]; weightIx += 1) {
const tensorIx = weightIx * recurrentKernelShape[1]! + recurrentNeuronIx;
const weight = recurrentWeightsData[tensorIx];
if (weight === undefined) {
throw new Error(
`Unexpected undefined weight in recurrent kernel; tensorIx=${tensorIx}; shape=${recurrentKernelShape}`
);
}
if (weight === 0) {
continue;
}
const inputNeuron = getInputNeuron(weightIx);
if (!inputNeuron) {
continue;
}
weightsForNeuron.push({ weight, index: weightIx, inputNeuron });
}
if (weightsForNeuron.length === 0 && !recurrentBiasData?.[recurrentNeuronIx]) {
continue;
}
const name = `layer_${layerIx}_recurrent_${recurrentNeuronIx}`;
const neuron = new SparseNeuron(
weightsForNeuron,
recurrentBiasData?.[recurrentNeuronIx] ?? 0,
name,
weights.recurrentActivation
);
layer.recurrentNeurons[recurrentNeuronIx] = neuron;
}
// Now that we have populated all neurons, we can add in the recurrent connections between the
// recurrent tree and the state
layer.stateNeurons.forEach((neuron, index) => {
const recurrentNeuron = layer.recurrentNeurons[index];
if (!recurrentNeuron) {
return;
}
neuron.connect(index, recurrentNeuron);
});
return layer;
}
getNeuron(outputIx: number): SparseNeuron | undefined {
return this.outputNeurons[outputIx];
}
public advanceSequence(): void {
this.stateNeurons.forEach(neuron => {
neuron.computeNewState();
neuron.advanceSequence();
});
this.recurrentNeurons.forEach(neuron => neuron.advanceSequence());
this.outputNeurons.forEach(neuron => neuron.advanceSequence());
}
/**
* Resets all state back to initial values
*/
public reset(): void {
this.stateNeurons.forEach(neuron => neuron.reset());
this.outputNeurons.forEach(neuron => neuron.reset());
this.recurrentNeurons.forEach(neuron => neuron.reset());
}
public serialize(): SerializedGraphRNNCell {
const outputNeurons = serializeSparseNeurons(this.outputNeurons);
const recurrentNeurons = serializeSparseNeurons(this.recurrentNeurons);
const stateNeurons = serializeSparseNeurons(this.stateNeurons);
return { outputNeurons, recurrentNeurons, stateNeurons, outputDim: this.outputDim };
}
public static deserialize(
layerIx: number,
serialized: SerializedGraphRNNCell,
prevLayer: GraphRNNLayer
): GraphRNNCell {
const layer = new GraphRNNCell(serialized.outputDim);
for (let i = 0; i < serialized.outputNeurons.length; i += 1) {
const serializedNeuron = serialized.outputNeurons[i];
if (!serializedNeuron) {
continue;
}
// We can't deserialize directly since neurons might depend recursively on other neurons in this
// layer that haven't been deserialized yet
const neuron = new SparseNeuron(
[],
serializedNeuron.bias,
serializedNeuron.name,
serializedNeuron.activation
);
layer.outputNeurons[i] = neuron;
}
for (let i = 0; i < serialized.recurrentNeurons.length; i += 1) {
const serializedNeuron = serialized.recurrentNeurons[i];
if (!serializedNeuron) {
continue;
}
const neuron = new SparseNeuron(
[],
serializedNeuron.bias,
serializedNeuron.name,
serializedNeuron.activation
);
layer.recurrentNeurons[i] = neuron;
}
for (let i = 0; i < serialized.stateNeurons.length; i += 1) {
const serializedNeuron = serialized.stateNeurons[i];
if (!serializedNeuron) {
continue;
}
const neuron = new StateNeuron(layerIx, i, serializedNeuron.bias);
layer.stateNeurons[i] = neuron;
}
const getInputNeuron = (outputIx: number): SparseNeuron | undefined => {
// Inputs to the output and recurrent tree are created by concatenating the previous layer's outputs and the state
if (outputIx < prevLayer.outputDim) {
return prevLayer.getNeuron(outputIx);
}
const stateIx = outputIx - prevLayer.outputDim;
if (!layer.stateNeurons[stateIx]) {
throw new Error(
`Unexpected undefined state neuron; should have been populated already. stateIx=${stateIx}`
);
}
return layer.stateNeurons[stateIx];
};
const fillConnections = (
neurons: SparseNeuron[],
serializedNeurons: (SerializedSparseNeuron | null)[]
) => {
neurons.forEach((neuron, index) => {
const serializedNeuron = serializedNeurons[index];
if (!serializedNeuron) {
throw new Error(`Unexpected undefined serialized neuron; index=${index}`);
}
serializedNeuron.weights.forEach(weight => {
const inputNeuron = getInputNeuron(weight.index);
if (!inputNeuron) {
throw new Error(`Unexpected undefined input neuron; index=${weight.index}`);
}
neuron.weights.push({ weight: weight.weight, index: weight.index, inputNeuron });
});
});
};
// Now that we have populated all neurons, fill in their connections
fillConnections(layer.outputNeurons, serialized.outputNeurons);
fillConnections(layer.recurrentNeurons, serialized.recurrentNeurons);
// State neurons are special in that they always have only one connection to the corresponding neuron
// in the recurrent tree, if one exists.
layer.stateNeurons.forEach((neuron, index) => {
const recurrentNeuron = layer.recurrentNeurons[index];
if (!recurrentNeuron) {
return;
}
neuron.weights.push({
weight: 1,
index,
inputNeuron: recurrentNeuron,
});
});
return layer;
}
}
interface SerializedSparseWeight {
weight: number;
index: number;
}
interface SerializedSparseNeuron {
weights: SerializedSparseWeight[];
bias: number;
name: string;
activation: AmeoActivationIdentifier | 'linear' | 'tanh';
}
interface SerializedGraphRNNCell {
outputNeurons: (SerializedSparseNeuron | null)[];
recurrentNeurons: (SerializedSparseNeuron | null)[];
stateNeurons: (SerializedSparseNeuron | null)[];
outputDim: number;
}
export class GraphRNNPostLayer implements GraphRNNLayer {
public outputDim: number;
public neurons: SparseNeuron[] = [];
constructor(outputDim: number, neurons: SparseNeuron[]) {
this.outputDim = outputDim;
this.neurons = neurons;
}
public static fromWeights(
weights: PostLayerWeights,
params: RNNGraphParams,
prevLayer: GraphRNNLayer,
outputDim: number
): GraphRNNPostLayer {
const layer = new GraphRNNPostLayer(outputDim, []);
const weightsData = clipAndQuantizeWeights(weights.weights, params);
const biasData = weights.bias ? clipAndQuantizeWeights(weights.bias, params) : undefined;
const getInputNeuron = (outputIx: number): SparseNeuron | undefined =>
prevLayer.getNeuron(outputIx);
// (input_shape[-1] + self.state_size, self.output_dim)
const kernelShape = [weights.inputDim, weights.outputDim];
for (let outputNeuronIx = 0; outputNeuronIx < outputDim; outputNeuronIx += 1) {
const weightsForNeuron: SparseWeight[] = [];
for (let weightIx = 0; weightIx < kernelShape[0]; weightIx += 1) {
const tensorIx = weightIx * kernelShape[1]! + outputNeuronIx;
const weight = weightsData[tensorIx];
if (weight === undefined) {
throw new Error(
`Unexpected undefined weight in post layer; tensorIx=${tensorIx}; shape=${kernelShape}`
);
}
if (weight === 0) {
continue;
}
const inputNeuron = getInputNeuron(weightIx);
if (!inputNeuron) {
continue;
}
weightsForNeuron.push({ weight, index: weightIx, inputNeuron });
}
if (weightsForNeuron.length === 0 && biasData?.[outputNeuronIx] === 0) {
continue;
}
const name = `post_layer_output_${outputNeuronIx}`;
const neuron = new SparseNeuron(
weightsForNeuron,
biasData?.[outputNeuronIx] ?? 0,
name,
weights.activation
);
layer.neurons[outputNeuronIx] = neuron;
}
return layer;
}
public reset() {
this.neurons.forEach(neuron => neuron.reset());
}
advanceSequence(): void {
this.neurons.forEach(neuron => neuron.advanceSequence());
}
getNeuron(outputIx: number): SparseNeuron | undefined {
return this.neurons[outputIx];
}
public serialize(): SerializedGraphRNNPostLayer {
return { neurons: serializeSparseNeurons(this.neurons), outputDim: this.outputDim };
}
public static deserialize(
serialized: SerializedGraphRNNPostLayer,
prevLayer: GraphRNNLayer
): GraphRNNPostLayer {
const { neurons: serializedNeurons, outputDim } = serialized;
const neurons: SparseNeuron[] = [];
for (let i = 0; i < outputDim; i += 1) {
const neuron = serializedNeurons[i];
if (!neuron) {
continue;
}
neurons[i] = SparseNeuron.deserialize(neuron, prevLayer, i);
}
return new GraphRNNPostLayer(outputDim, neurons);
}
}
interface SerializedGraphRNNPostLayer {
neurons: (SerializedSparseNeuron | null)[];
outputDim: number;
}
/**
* Sets weights to 0 if their magnitude is less than or equal to `clipThreshold`.
*/
const clipAndQuantizeWeights = (weights: Float32Array, params: RNNGraphParams): Float32Array => {
const { clipThreshold, quantizationInterval } = params;
const newWeights = new Float32Array(weights.length);
for (let i = 0; i < weights.length; i += 1) {
if (Math.abs(weights[i]) <= clipThreshold) {
newWeights[i] = 0;
} else {
newWeights[i] = weights[i];
}
}
if (!quantizationInterval) {
return newWeights;
}
// Quantize weights to nearest multiple of `quantizationInterval`
for (let i = 0; i < newWeights.length; i += 1) {
newWeights[i] = Math.round(newWeights[i] / quantizationInterval) * quantizationInterval;
}
return newWeights;
};
export class RNNGraph {
public inputLayer: GraphRNNInputLayer;
private outputs: GraphRNNOutputs;
private cells: GraphRNNCell[] = [];
private postLayers: GraphRNNPostLayer[] = [];
public allConnectedNeuronsByID: Map<string, SparseNeuron>;
/**
* Records the output of each neuron for each step of the sequence.
*/
public neuronOutputHistory: Map<string, number[]> = new Map();
public currentTimestep: Writable<number> = writable(0);
public inputSeqGenerator: InputSeqGenerator | null = null;
constructor(
inputLayer: GraphRNNInputLayer,
outputs: GraphRNNOutputs,
cells: GraphRNNCell[],
postLayers: GraphRNNPostLayer[],
initialInputSeq?: Float32Array[] | InputSeqGenerator
) {
this.inputLayer = inputLayer;
this.outputs = outputs;
this.cells = cells;
this.postLayers = postLayers;
this.allConnectedNeuronsByID = new Map();
if (initialInputSeq && !Array.isArray(initialInputSeq)) {
this.inputSeqGenerator = initialInputSeq;
}
this.pruneUnconnectedNeurons();
const inputSeq = initialInputSeq
? Array.isArray(initialInputSeq)
? initialInputSeq
: [initialInputSeq.next()]
: [new Float32Array(this.inputLayer.inputDim).map(() => (Math.random() > 0.5 ? 1 : -1))];
this.setInputSequence(inputSeq);
for (const neuron of this.allConnectedNeuronsByID.values()) {
this.neuronOutputHistory.set(neuron.name, [neuron.getOutput()]);
}
}
private pruneUnconnectedNeurons() {
// Walk the full connected graph and remove any un-connected neurons
const allConnectedNeuronsByID: Map<string, SparseNeuron> = new Map();
const addNeuron = (neuron: SparseNeuron): void => {
if (allConnectedNeuronsByID.has(neuron.name)) {
return;
}
allConnectedNeuronsByID.set(neuron.name, neuron);
for (const weight of neuron.weights) {
addNeuron(weight.inputNeuron);
}
};
for (const output of this.outputs.neurons) {
if (!output?.weights.length) {
continue;
}
addNeuron(output);
}
function filterNeurons<T extends { name: string }>(neurons: T[]): T[] {
for (let i = 0; i < neurons.length; i += 1) {
const neuron = neurons[i];
if (!neuron) {
continue;
}
if (!allConnectedNeuronsByID.has(neuron.name)) {
delete neurons[i];
}
}
return neurons;
}
this.outputs.neurons = filterNeurons(this.outputs.neurons);
for (const cell of this.cells) {
cell.recurrentNeurons = filterNeurons(cell.recurrentNeurons);
cell.stateNeurons = filterNeurons(cell.stateNeurons);
cell.outputNeurons = filterNeurons(cell.outputNeurons);
}
for (const postLayer of this.postLayers) {
postLayer.neurons = filterNeurons(postLayer.neurons);
}
this.inputLayer.neurons = filterNeurons(this.inputLayer.neurons);
this.allConnectedNeuronsByID = allConnectedNeuronsByID;
}
public static fromWeights(
inputDim: number,
outputDim: number,
rnnCells: RNNCellWeights[],
postLayerWeights: PostLayerWeights[],
rawParams?: Partial<RNNGraphParams>
) {
const params = rawParams
? mergeNonNullable(DefaultRNNGraphParams, rawParams)
: { ...DefaultRNNGraphParams };
const inputLayer = new GraphRNNInputLayer(inputDim);
const cells: GraphRNNCell[] = [];
const postLayers: GraphRNNPostLayer[] = [];
let prevLayer: GraphRNNLayer = inputLayer;
for (let layerIx = 0; layerIx < rnnCells.length; layerIx += 1) {
const cell = rnnCells[layerIx];
const cellLayer = GraphRNNCell.fromWeights(layerIx, cell, params, prevLayer);
cells.push(cellLayer);
prevLayer = cellLayer;
}
for (let postLayerIx = 0; postLayerIx < postLayerWeights.length; postLayerIx += 1) {
const weights = postLayerWeights[postLayerIx];
const postLayer = GraphRNNPostLayer.fromWeights(weights, params, prevLayer, outputDim);
postLayers.push(postLayer);
prevLayer = postLayer;
}
const outputs = new GraphRNNOutputs(outputDim, prevLayer);
return new RNNGraph(inputLayer, outputs, cells, postLayers);
}
public get inputDim(): number {
return this.inputLayer.inputDim;
}