-
Notifications
You must be signed in to change notification settings - Fork 201
/
Copy pathneuralnetwork.pas
17303 lines (15922 loc) · 537 KB
/
neuralnetwork.pas
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
(*
neuralnetwork
Copyright (C) 2024 Joao Paulo Schwarz Schuler
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*)
unit neuralnetwork;
(*
// coded, adapted and ported by Joao Paulo Schwarz Schuler
// https://github.com/joaopauloschuler/neural-api/
----------------------------------------------
Interesting links:
http://cs.stanford.edu/people/karpathy/convnetjs/demo/cifar10.html
https://github.com/Kulbear/deep-learning-nano-foundation/wiki/ReLU-and-Softmax-Activation-Functions
Mario Werner coded examples for CIFAR-10 and MNIST:
https://bitbucket.org/108bits/cai-implementations/src/c8c027b1a0d636713f7ebb70a738f1cd7117a7a4?at=master
*)
{$include neuralnetwork.inc}
interface
uses
{$IFDEF OpenCL}
{$IFDEF FPC}
cl,
neuralopencl,
{$ELSE} // For Delphi Compiler
cl, // https://github.com/CWBudde/PasOpenCL
neuralopencl,
{$ENDIF}
{$ENDIF}
{$IFDEF FPC}
fgl,
{$ENDIF}
Classes, SysUtils, math, syncobjs, neuralvolume, neuralgeneric,
neuralbyteprediction, neuralcache, neuralab;
const
csMaxInterleavedSize: integer = 95;
csNNetMaxParameterIdx = 7;
csErrorOverflowBackpropProtection = 100;
type
TNNetLayer = class;
TNNet = class;
{ TNNetNeuron }
TNNetNeuron = class(TMObject)
protected
FWeights: TNNetVolume;
FBackInertia: TNNetVolume;
FBackInertia2: TNNetVolume;
FDelta: TNNetVolume;
FDelta2: TNNetVolume;
FParentLayer: TNNetLayer;
private
FBiasWeight: TNeuralFloat;
FBiasInertia: TNeuralFloat;
FBiasInertia2: TNeuralFloat;
FBiasDelta: TNeuralFloat;
public
constructor Create(); override;
destructor Destroy(); override;
procedure Fill(Value:TNeuralFloat); {$IFDEF Release} inline; {$ENDIF}
procedure AddInertia(); {$IFDEF Release} inline; {$ENDIF}
procedure UpdateWeights(Inertia:TNeuralFloat); {$IFDEF Release} inline; {$ENDIF}
procedure UpdateWeightsWithoutInertia(); {$IFDEF Release} inline; {$ENDIF}
procedure CalcAdamDelta();
procedure UpdateWeightsAdam(); {$IFDEF Release} inline; {$ENDIF}
function SaveToString(): string;
procedure LoadFromString(strData: string);
procedure ClearDelta; {$IFDEF Release} inline; {$ENDIF}
// Initializers
// Weight Initializer - Uniform Distribution.
procedure InitUniform(Value: TNeuralFloat = 1);
// Weight Initializer - Gaussian Distribution.
procedure InitGaussian(Value: TNeuralFloat = 1);
// Weight Initializer - LeCun 98, Efficient Backprop
// http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf
procedure InitLeCunUniform(Value: TNeuralFloat = 1);
// Weight Initializer - This implementation is inspired on:
// Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification
// Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
// https://arxiv.org/abs/1502.01852
// He initializations are also called Kaiming initializations.
procedure InitHeUniform(Value: TNeuralFloat = 1);
// Weight Initializer - same as InitHeUniform for depthwise convolutions.
procedure InitHeUniformDepthwise(Value: TNeuralFloat = 1);
// Weight Initializer - same as InitHeUniform with gaussian distribution.
procedure InitHeGaussian(Value: TNeuralFloat = 1);
// Weight Initializer - same as InitHeGaussian for depthwise convolutions.
procedure InitHeGaussianDepthwise(Value: TNeuralFloat = 1);
// Weight Initializer for SELU activation function.
procedure InitSELU(Value: TNeuralFloat = 1);
// Memory Initializer for Adam Optimizer
procedure InitAdam(ParentLayer: TNNetLayer);
property Weights: TNNetVolume read FWeights;
property Bias: TNeuralFloat read FBiasWeight;
property BackInertia: TNNetVolume read FBackInertia;
property Delta: TNNetVolume read FDelta;
end;
{$IFDEF FPC}
TNNetNeuronList = class (specialize TFPGObjectList<TNNetNeuron>)
public
{$ELSE}
TNNetNeuronList = class (TNNetList)
private
function GetItem(Index: Integer): TNNetNeuron; inline;
procedure SetItem(Index: Integer; AObject: TNNetNeuron); inline;
public
property Items[Index: Integer]: TNNetNeuron read GetItem write SetItem; default;
{$ENDIF}
// Creates the list with ElementCount elements.
constructor CreateWithElements(ElementCount: integer);
// Returns the maximum weight value.
function GetMaxWeight(): TNeuralFloat; {$IFDEF Release} inline; {$ENDIF}
// Returns the maximum absolute weight value.
function GetMaxAbsWeight(): TNeuralFloat; {$IFDEF Release} inline; {$ENDIF}
// Returns the minimum weight value.
function GetMinWeight(): TNeuralFloat; {$IFDEF Release} inline; {$ENDIF}
procedure InitForDebug();
end;
/// neural network layer
TNNetLayer = class(TMObject)
protected
FActivationFn: TNeuralActivationFunction;
FActivationFnDerivative: TNeuralActivationFunction;
FForwardTime: double;
FBackwardTime: double;
FNeurons: TNNetNeuronList;
FOutput: TNNetVolume;
FOutputRaw: TNNetGroupedVolume;
FOutputError: TNNetVolume;
FOutputErrorDeriv: TNNetVolume;
FSmoothErrorPropagation: boolean;
FBatchUpdate: boolean;
FSuppressBias: integer;
// Fast access to TNNetNeuron
FArrNeurons: array of TNNetNeuron;
FInertia: TNeuralFloat;
FPrevLayer: TNNetLayer;
FLearningRate: TNeuralFloat;
FL2Decay: TNeuralFloat;
// Adam settings
FBeta1, FBeta2, FEpsilon: TNeuralFloat;
FBeta1Decay, FBeta2Decay: TNeuralFloat;
FOneMinusBeta1Decay, FOneMinusBeta2Decay: TNeuralFloat;
FStruct: array [0..csNNetMaxParameterIdx] of integer;
FFloatSt: array [0..csNNetMaxParameterIdx] of TNeuralFloat;
//backpropagation properties
FDepartingBranchesCnt: integer;
FBackPropCallCurrentCnt: integer;
FLinkedNeurons: boolean;
FCanNormalizeDelta: boolean;
FCanSetNumWeightsForAllNeurons: boolean;
FNN: TNNet;
procedure InitStruct();
private
FLayerIdx: integer;
{$IFDEF OpenCL}
FHasOpenCL: boolean;
FShouldOpenCL: boolean;
FDotCL: TDotProductSharedKernel;
FDotProductKernel: TDotProductKernel;
{$ENDIF}
procedure ComputeL2Decay(); virtual;
procedure ComputePreviousLayerError(); virtual;
procedure SetPrevLayer(pPrevLayer: TNNetLayer); virtual;
procedure ApplyActivationFunctionToOutput(); virtual;
procedure BuildArrNeurons();
procedure AfterWeightUpdate(); virtual;
public
constructor Create(); override;
destructor Destroy(); override;
{$IFDEF OpenCL}
procedure DisableOpenCL(); virtual;
procedure EnableOpenCL(DotProductKernel: TDotProductKernel); virtual;
{$ENDIF}
// Computes the forward pass of this layer.
procedure Compute(); virtual; abstract;
// Computes the backward pass.
// You may find theoretical info at https://en.wikipedia.org/wiki/Backpropagation.
procedure Backpropagate(); virtual; abstract;
procedure ComputeOutputErrorForOneNeuron(NeuronIdx: integer; value: TNeuralFloat);
procedure ComputeOutputErrorWith(pOutput: TNNetVolume); virtual;
procedure ComputeOutputErrorForIdx(pOutput: TNNetVolume; const aIdx: array of integer); virtual;
procedure ComputeErrorDeriv(); {$IFDEF FPC}{$IFDEF Release} inline; {$ENDIF}{$ENDIF}
procedure Fill(value: TNeuralFloat); {$IFDEF Release} inline; {$ENDIF}
// Adds neurons to the layer.
procedure AddNeurons(NeuronNum: integer);
// Calculates the number of missing neurons so the layer can have
// NeuronNum neurons. The missing neurons are then added.
procedure AddMissingNeurons(NeuronNum: integer);
// Defines the number of weights for all neurons in the layer.
procedure SetNumWeightsForAllNeurons(NumWeights: integer); overload;
// Defines the number of weights for all neurons in the layer.
procedure SetNumWeightsForAllNeurons(x, y, d: integer); overload;
// Defines the number of weights for all neurons in the layer copying
// the configuration found at the Origin parameters.
procedure SetNumWeightsForAllNeurons(Origin: TNNetVolume); overload;
// Returns the maximum weight value from all neurons in the layer.
function GetMaxWeight(): TNeuralFloat; {$IFDEF Release} inline; {$ENDIF}
// Returns the maximum absolute weight value from all neurons in the layer.
function GetMaxAbsWeight(): TNeuralFloat; {$IFDEF Release} inline; {$ENDIF}
// Returns the minimum weight value from all neurons in the layer.
function GetMinWeight(): TNeuralFloat; {$IFDEF Release} inline; {$ENDIF}
function GetMaxDelta(): TNeuralFloat; {$IFDEF Release} inline; {$ENDIF}
function GetMinDelta(): TNeuralFloat; {$IFDEF Release} inline; {$ENDIF}
function ForceMaxAbsoluteDelta(vMax: TNeuralFloat): TNeuralFloat; {$IFDEF Release} inline; {$ENDIF}
function ForceMaxAbsoluteWeight(vMax: TNeuralFloat): TNeuralFloat; {$IFDEF Release} inline; {$ENDIF}
function GetMaxAbsoluteDelta(): TNeuralFloat; virtual;
function GetDeltaNorm(): TNeuralFloat; virtual;
function GetWeightNorm(): TNeuralFloat; virtual;
procedure NormalizeMaxAbsoluteDeltaPerNeuron(MaxDelta: TNeuralFloat);
procedure GetMinMaxAtDepth(pDepth: integer; var pMin, pMax: TNeuralFloat); {$IFDEF Release} inline; {$ENDIF}
// Returns the sum of all weights from all neurons in the layer.
function GetWeightSum(): TNeuralFloat; {$IFDEF Release} inline; {$ENDIF}
// Returns the sum of all biases from all neurons in the layer.
function GetBiasSum(): TNeuralFloat; {$IFDEF Release} inline; {$ENDIF}
function GetDeltaSum(): TNeuralFloat; {$IFDEF Release} inline; {$ENDIF}
function GetInertiaSum(): TNeuralFloat; {$IFDEF Release} inline; {$ENDIF}
// Returns the number of weights in the layer.
function CountWeights(): integer; {$IFDEF Release} inline; {$ENDIF}
// Returns the number of neurons in the layer.
function CountNeurons(): integer; {$IFDEF Release} inline; {$ENDIF}
// Multiplies all weights in the layer by value V.
function MulWeights(V:TNeuralFloat): TNNetLayer;
procedure MulInertia(V:TNeuralFloat); {$IFDEF Release} inline; {$ENDIF}
procedure MulDeltas(V:TNeuralFloat); {$IFDEF Release} inline; {$ENDIF}
// Clear all biases from all neurons in the layer.
procedure ClearBias(); {$IFDEF Release} inline; {$ENDIF}
procedure ClearDeltas(); {$IFDEF Release} inline; {$ENDIF}
procedure ClearInertia(); {$IFDEF Release} inline; {$ENDIF}
procedure ClearTimes(); {$IFDEF Release} inline; {$ENDIF}
procedure AddTimes(Origin: TNNetLayer); {$IFDEF Release} inline; {$ENDIF}
procedure CopyTimes(Origin: TNNetLayer); {$IFDEF Release} inline; {$ENDIF}
procedure MulMulAddWeights(Value1, Value2: TNeuralFloat; Origin: TNNetLayer); {$IFDEF Release} inline; {$ENDIF}
procedure MulMulAddInertia(Value1, Value2: TNeuralFloat; Origin: TNNetLayer); {$IFDEF Release} inline; {$ENDIF}
// Sums all weights by their corresponding weights found at Origin.
// Both layers must have the same number of weights and neurons for this
// function to work as expected.
procedure SumWeights(Origin: TNNetLayer); {$IFDEF Release} inline; {$ENDIF}
procedure SumInertia(Origin: TNNetLayer); {$IFDEF Release} inline; {$ENDIF}
procedure SumDeltas(Origin: TNNetLayer); {$IFDEF Release} inline; {$ENDIF}
procedure SumDeltasNoChecks(Origin: TNNetLayer); {$IFDEF Release} inline; {$ENDIF}
// Copies all weights by their corresponding weights found at Origin.
// Both layers must have the same number of weights and neurons for this
// function to work as expected.
procedure CopyWeights(Origin: TNNetLayer); virtual;
procedure CopyInertia(Origin: TNNetLayer); virtual;
procedure ForceRangeWeights(V:TNeuralFloat); {$IFDEF Release} inline; {$ENDIF}
procedure ForcePositiveWeights(); {$IFDEF Release} inline; {$ENDIF}
function ForceMaxOutputError(pMaxError: TNeuralFloat): TNeuralFloat;
procedure NormalizeWeights(VMax: TNeuralFloat); {$IFDEF Release} inline; {$ENDIF}
function SaveDataToString(): string; virtual;
procedure LoadDataFromString(strData: string); virtual;
// Saves the layer structure to a string so the layer can be later
// restored/reconstructed.
function SaveStructureToString(): string; virtual;
procedure SetBatchUpdate(pBatchUpdate: boolean); {$IFDEF Release} inline; {$ENDIF}
procedure UpdateWeights(); virtual;
procedure CalcAdamDelta(); virtual;
procedure UpdateWeightsAdam(); virtual;
function InitBasicPatterns(): TNNetLayer;
// Increments an internal counter that counts how many branches load
// the output of the current layer.
procedure IncDepartingBranchesCnt(); {$IFDEF Release} inline; {$ENDIF}
// Decrements an internal counter that counts how many branches load
// the output of the current layer.
procedure ResetBackpropCallCurrCnt(); {$IFDEF Release} inline; {$ENDIF}
procedure TestBackPropCallCurrCnt(); {$IFDEF Release} inline; {$ENDIF}
// Initializers
// Weight Initializer - Uniform Distribution.
function InitUniform(Value: TNeuralFloat = 1): TNNetLayer;
// Weight Initializer - LeCun 98, Efficient Backprop
// http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf
function InitLeCunUniform(Value: TNeuralFloat = 1): TNNetLayer;
// Weight Initializer - This implementation is inspired on:
// Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification
// Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
// https://arxiv.org/abs/1502.01852
// He initializations are also called Kaiming initializations.
function InitHeUniform(Value: TNeuralFloat = 1): TNNetLayer;
// Weight Initializer - same as InitHeUniform for depthwise convolutions.
function InitHeUniformDepthwise(Value: TNeuralFloat = 1): TNNetLayer;
// Weight Initializer - same as InitHeUniform with gaussian distribution.
function InitHeGaussian(Value: TNeuralFloat = 0.5): TNNetLayer;
// Weight Initializer - same as InitHeGaussian for depthwise convolutions.
function InitHeGaussianDepthwise(Value: TNeuralFloat = 0.5): TNNetLayer;
// Glorot Bengio initializations are also called Xavier initializations.
// This implementation is inspired on:
// Understanding the difficulty of training deep feedforward neural networks
// Xavier Glorot, Yoshua Bengio ; Proceedings of the Thirteenth International
// Conference on Artificial Intelligence and Statistics, PMLR 9:249-256, 2010.
// http://proceedings.mlr.press/v9/glorot10a.html
function InitGlorotBengioUniform(Value: TNeuralFloat = 1): TNNetLayer;
// Weight Initializer for SELU activation function.
function InitSELU(Value: TNeuralFloat = 1): TNNetLayer;
// Memory Initializer for Adam optimizer
function InitAdam(Beta1, Beta2, Epsilon: TNeuralFloat): TNNetLayer;
procedure InitDefault(); virtual;
property ActivationFn: TNeuralActivationFunction read FActivationFn write FActivationFn;
property ActivationFnDerivative: TNeuralActivationFunction read FActivationFnDerivative write FActivationFnDerivative;
property Neurons: TNNetNeuronList read FNeurons;
property NN:TNNet read FNN write FNN;
property Output: TNNetVolume read FOutput;
property OutputRaw: TNNetGroupedVolume read FOutputRaw;
property PrevLayer: TNNetLayer read FPrevLayer write SetPrevLayer;
property LearningRate: TNeuralFloat read FLearningRate write FLearningRate;
property L2Decay: TNeuralFloat read FL2Decay write FL2Decay;
property Inertia: TNeuralFloat read FInertia;
property OutputError: TNNetVolume read FOutputError write FOutputError;
property OutputErrorDeriv: TNNetVolume read FOutputErrorDeriv write FOutputErrorDeriv;
property LayerIdx: integer read FLayerIdx;
property SmoothErrorPropagation: boolean read FSmoothErrorPropagation write FSmoothErrorPropagation;
property BackwardTime: double read FBackwardTime write FBackwardTime;
property ForwardTime: double read FForwardTime write FForwardTime;
property LinkedNeurons: boolean read FLinkedNeurons;
{$IFDEF OpenCL}
property HasOpenCL: boolean read FHasOpenCL;
property ShouldOpenCL:boolean read FShouldOpenCL;
{$ENDIF}
end;
TNNetLayerClass = class of TNNetLayer;
/// This is a base class. Do not use it directly.
TNNetLayerConcatedWeights = class(TNNetLayer)
protected
FVectorSize, FVectorSizeBytes: integer;
FNeuronWeightList: TNNetVolumeList;
FConcatedWeights: TNNetVolume;
FConcatedWInter: TNNetVolume; // This is the same as transposed concated weights
FBiasOutput: TNNetVolume;
FShouldConcatWeights: boolean;
FShouldInterleaveWeights: boolean;
FAfterWeightUpdateHasBeenCalled:boolean;
procedure AfterWeightUpdate(); override;
procedure BuildBiasOutput(); {$IFDEF Release} inline; {$ENDIF}
public
constructor Create(); override;
destructor Destroy(); override;
procedure RefreshNeuronWeightList();
{$IFDEF OpenCL}
procedure EnableOpenCL(DotProductKernel: TDotProductKernel); override;
{$ENDIF}
end;
{$IFDEF FPC}
TNNetLayerList = specialize TFPGObjectList<TNNetLayer>;
{$ELSE}
TNNetLayerList = class (TNNetList)
private
function GetItem(Index: Integer): TNNetLayer; inline;
procedure SetItem(Index: Integer; AObject: TNNetLayer); inline;
public
property Items[Index: Integer]: TNNetLayer read GetItem write SetItem; default;
end;
{$ENDIF}
/// This is a base class. Do not use it directly.
TNNetInputBase = class(TNNetLayer)
private
procedure ComputePreviousLayerError(); override;
public
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// This is an ideal layer to be used as input layer. In the case that you
// need to backpropagate errors up to the input, call EnableErrorCollection.
TNNetInput = class(TNNetInputBase)
public
constructor Create(pSize: integer); overload;
constructor Create(pSizeX, pSizeY, pDepth: integer); overload;
constructor Create(pSizeX, pSizeY, pDepth, pError: integer); overload;
function EnableErrorCollection: TNNetInput;
function DisableErrorCollection: TNNetInput;
end;
// This layer transposes the X and Depth axis.
TNNetTransposeXD = class(TNNetLayer)
private
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
procedure Compute(); override;
procedure Backpropagate(); override;
end;
// This layer transposes the Y and Depth axis.
TNNetTransposeYD = class(TNNetLayer)
private
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// This layer copies the input to the output and can be used as a base class
// to your new layers.
TNNetIdentity = class(TNNetLayer)
private
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
procedure BackpropagateNoTest(); virtual;
public
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// This layer allows you to debug activation and backpropagation of an
TNNetDebug = class(TNNetIdentity)
public
constructor Create(hasForward, hasBackward: integer); overload;
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// Padding layer: adds padding to the input.
// This layer has no trainable parameter. Adding a padding layer may be
// more efficient than padding at the convolutional layer.
TNNetPad = class(TNNetLayer)
private
FPadding: integer;
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
constructor Create(Padding: integer); overload;
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// Padding layer: adds padding to the input.
// This layer is similar to TNNetPad except that it allows you to add distinct
// paddings to X and Y.
// This layer has no trainable parameter. Adding a padding layer may be
// more efficient than padding at the convolutional layer.
TNNetPadXY = class(TNNetLayer)
private
FPaddingX, FPaddingY: integer;
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
constructor Create(PaddingX, PaddingY: integer); overload;
procedure Compute(); override;
procedure Backpropagate(); override;
end;
{ TNNetCrop }
TNNetCrop = class(TNNetLayer)
private
FStartX, FStartY: integer;
FLenX, FLenY: integer;
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
constructor Create(StartX, StartY, LenX, LenY: integer); overload;
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// Base class to be used with layers that aren't compatible with L2
TNNetIdentityWithoutL2 = class(TNNetIdentity)
private
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
procedure ComputeL2Decay(); override;
end;
/// Base class to be used with layers that aren't compatible with L2
// and do not run the default optimizer.
TNNetIdentityWithoutL2AndOptimizer = class(TNNetIdentityWithoutL2)
public
constructor Create();
procedure InitDefault(); override;
procedure UpdateWeights(); override;
procedure CalcAdamDelta(); override;
procedure UpdateWeightsAdam(); override;
end;
/// This layer can be used when you need the forward pass but can't let
// error backpropagation to pass.
TNNetIdentityWithoutBackprop = class(TNNetIdentity)
public
procedure Backpropagate(); override;
end;
// Class of activation function layers.
TNNetActivationFunctionClass = class of TNNetIdentity;
/// This is a base/abstract class. Do not use it directly.
TNNetReLUBase = class(TNNetIdentity)
public
procedure Backpropagate(); override;
end;
TNNetDigital = class(TNNetIdentity)
private
FMiddleValue: TNeuralFloat;
FLowValue, FHighValue: TNeuralFloat;
FMiddleDist: TNeuralFloat;
public
constructor Create(LowValue, HighValue: integer); overload;
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// This is a plain Rectified Linear Unit (ReLU) layer.
// https://en.wikipedia.org/wiki/Rectifier_(neural_networks)
TNNetReLU = class(TNNetReLUBase)
public
procedure Compute(); override;
end;
/// This is almost the same as ReLU except that it doesn't
// backpropagate on zero values (Positive only)
TNNetReLUP = class(TNNetReLUBase)
public
procedure Compute(); override;
end;
/// This is a leaky ReLU with minimum and maximum values. You can
// scale leakiness via the Leaky parameter.
TNNetReLUL = class(TNNetReLUBase)
private
FScale, FLowLimit, FHighLimit: TNeuralFloat;
public
constructor Create(LowLimit, HighLimit, Leakiness: integer); overload;
procedure Compute(); override;
end;
/// This is a Relu with low limit = 0 and high limit = 6. You
// can optionally make this activation function leaky.
TNNetReLU6 = class(TNNetReLUL)
public
constructor Create(Leakiness: integer = 0); overload;
end;
/// Scaled Exponential Linear Unit
// https://arxiv.org/pdf/1706.02515.pdf
// You might need to lower your learning rate with SELU.
TNNetSELU = class(TNNetReLUBase)
private
FAlpha: TNeuralFloat;
FScale: TNeuralFloat;
FScaleAlpha: TNeuralFloat;
FThreshold: TNeuralFloat;
public
constructor Create(); override;
procedure Compute(); override;
end;
/// Swish activation function
// https://arxiv.org/abs/1710.05941
TNNetSwish = class(TNNetReLUBase)
public
procedure Compute(); override;
end;
/// Hard Swish Activation function
// https://paperswithcode.com/method/hard-swish
TNNetHardSwish = class(TNNetReLUBase)
public
procedure Compute(); override;
end;
/// Swish activation function with maximum limit of 6
TNNetSwish6 = class(TNNetReLUBase)
public
procedure Compute(); override;
end;
//Does a ReLU followed by a Square Root
TNNetReLUSqrt = class(TNNetReLUBase)
public
procedure Compute(); override;
end;
// Calculates Power(LocalPrevOutput.FData[OutputCnt], iPower).
TNNetPower = class(TNNetReLUBase)
private
FPower: TNeuralFloat;
public
constructor Create(iPower: integer); overload;
procedure Compute(); override;
end;
{ TNNetSignedSquareRoot }
TNNetSignedSquareRoot = class(TNNetReLUBase)
public
procedure Compute(); override;
end;
{ TNNetSignedSquareRoot1 }
TNNetSignedSquareRoot1 = class(TNNetReLUBase)
public
procedure Compute(); override;
end;
{ TNNetSignedSquareRootN }
TNNetSignedSquareRootN = class(TNNetReLUBase)
protected
FN: TNeuralFloat;
public
constructor Create(N: TNeuralFloat); overload;
procedure Compute(); override;
end;
/// Leaky Rectified Linear Unit (ReLU) layer.
// https://en.wikipedia.org/wiki/Rectifier_(neural_networks)
TNNetLeakyReLU = class(TNNetReLUBase)
private
FAlpha: TNeuralFloat;
FThreshold: TNeuralFloat;
public
constructor Create(); override;
procedure Compute(); override;
end;
/// Very Leaky Rectified Linear Unit (ReLU) layer.
// https://en.wikipedia.org/wiki/Rectifier_(neural_networks)
TNNetVeryLeakyReLU = class(TNNetLeakyReLU)
public
constructor Create(); override;
end;
/// This is a plain Sigmoid layer.
TNNetSigmoid = class(TNNetIdentity)
private
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
constructor Create(); override;
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// This is a plain Hyperbolic Tangent layer.
TNNetHyperbolicTangent = class(TNNetSigmoid)
public
constructor Create(); override;
end;
/// This layer multiplies the learning in previous layers. It can speed up
// learning but can also provoke overflows.
TNNetMulLearning = class(TNNetIdentity)
public
constructor Create(pMul: TNeuralFloat); overload;
procedure Backpropagate(); override;
end;
/// This layer multiplies the output by a constant.
TNNetMulByConstant = class(TNNetMulLearning)
public
// constructor Create(pMul: integer); overload;
procedure Compute(); override;
end;
// This layer multiplies the previous output by -1
TNNetNegate = class(TNNetMulByConstant)
public
constructor Create(); override;
end;
/// This is an experimental layer. Do not use it.
TNNetAddAndDiv = class(TNNetIdentity)
public
constructor Create(pAdd, pDiv: integer); overload;
procedure Compute(); override;
end;
{ TNNetAddPositionalEmbedding }
// Adds positional embedding as per paper "Attention Is All You Need".
// https://arxiv.org/abs/1706.03762 .
TNNetAddPositionalEmbedding = class(TNNetIdentity)
private
FPositionalEmbedding: TNNetVolume;
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
constructor Create(n: integer = 0); overload;
destructor Destroy(); override;
procedure Compute(); override;
end;
{ TNNetEmbedding }
// Do not use this layer. It's under construction.
TNNetEmbedding = class(TNNetLayer)
private
FVocabSize: integer;
FEmbeddingSize: integer;
FScaleEmbedding: TNeuralFloat;
FEncodeZero: boolean;
FInputTokens: array of integer;
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
constructor Create(pVocabSize, pEmbeddingSize: integer;
EncodeZero: integer = 0; ScaleEmbedding: TNeuralFloat = 0.02);
destructor Destroy; override;
procedure InitDefault(); override;
procedure Compute(); override;
procedure Backpropagate(); override;
end;
{ TNNetTokenAndPositionalEmbedding }
// Do not use this layer. It's under construction.
TNNetTokenAndPositionalEmbedding = class(TNNetEmbedding)
private
FPositionalEmbedding: TNNetVolume;
FPositionalEmbeddingN: integer;
FScalePositional: TNeuralFloat;
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
constructor Create(pVocabSize, pEmbeddingSize: integer;
EncodeZero: integer = 0;
ScaleEmbedding: TNeuralFloat = 0.02;
ScalePositional: TNeuralFloat = 0.01;
PositionalEmbeddingN: integer = 0);
destructor Destroy; override;
procedure Compute(); override;
end;
{ TNNetAddNoiseBase }
// TNNetAddNoiseBase is a base class. Do not use it directly.
TNNetAddNoiseBase = class(TNNetIdentity)
protected
FEnabled: boolean;
public
constructor Create(); override;
property Enabled:boolean read FEnabled write FEnabled;
end;
/// Dropout layer. The input parameter is the dropout rate (rate of values
// that are zeroed).
TNNetDropout = class(TNNetAddNoiseBase)
protected
FRate: integer;
FDropoutMask: TNNetVolume;
private
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
constructor Create(Rate: double; OneMaskPerbatch: integer = 1); overload;
destructor Destroy(); override;
procedure Compute(); override;
procedure Backpropagate(); override;
procedure CopyWeights(Origin: TNNetLayer); override;
procedure RefreshDropoutMask();
property DropoutMask: TNNetVolume read FDropoutMask;
end;
/// This layer adds a random addition (or bias) and amplifies (multiplies)
// randomly. Parameter 10 means changes with up to 1%. Parameter 1
// means 0.1% and 0 means no change. This layer was create to prevent
// overfitting and force generalization.
TNNetRandomMulAdd = class(TNNetAddNoiseBase)
protected
FRandomBias, FRandomMul: TNeuralFloat;
public
constructor Create(AddRate, MulRate: integer); overload;
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// This layers adds a small random bias (shift) and small
// random multiplication (scaling).
TNNetChannelRandomMulAdd = class(TNNetAddNoiseBase)
protected
FRandomBias, FRandomMul: TNNetVolume;
public
constructor Create(AddRate, MulRate: integer); overload;
destructor Destroy; override;
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// This layer does a MAX normalization. There are no trainable parameters
// in this layer.
TNNetLayerMaxNormalization = class(TNNetIdentity)
private
FLastMax: TNeuralFloat;
public
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// This layer does a standard normalization. There are no trainable parameters
// in this layer.
TNNetLayerStdNormalization = class(TNNetIdentity)
private
FLastStdDev: TNeuralFloat;
public
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// This layer does zero centering and standard normalization with trainable
// parameters.
TNNetMovingStdNormalization = class(TNNetIdentityWithoutL2AndOptimizer)
public
constructor Create();
procedure Compute(); override;
procedure Backpropagate(); override;
function GetMaxAbsoluteDelta(): TNeuralFloat; override;
end;
// This layer is experimental. Do not use.
TNNetMovingScale = class(TNNetIdentityWithoutL2AndOptimizer)
private
FChangeRate: TNeuralFloat;
FMaxTarget: TNeuralFloat;
FMultiplier: TNeuralFloat;
public
constructor Create(pMaxTarget: TNeuralFloat = 1; pChangeRate: TNeuralFloat = 1); overload;
procedure Compute(); override;
procedure Backpropagate(); override;
end;
// This is an experimental layer. Do not use it.
TNNetScaleLearning = class(TNNetIdentity)
public
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// This is a base class. Do not use it directly.
TNNetChannelTransformBase = class(TNNetIdentityWithoutL2)
private
FAuxDepth: TNNetVolume;
FOutputChannelSize: TNeuralFloat;
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
constructor Create(); override;
destructor Destroy(); override;
end;
/// This is a base class. Do not use it directly.
TNNetChannelShiftBase = class(TNNetChannelTransformBase)
public
procedure Compute(); override;
procedure InitDefault(); override;
end;
/// This layer adds a trainable bias to each channel.
TNNetChannelBias = class(TNNetChannelShiftBase)
public
procedure Backpropagate(); override;
end;
/// This layer multiplies (scales) each channel by a trainable number.
TNNetChannelMul = class(TNNetChannelTransformBase)
public
procedure Compute(); override;
procedure Backpropagate(); override;
procedure InitDefault(); override;
end;
// This is an experimental class. Do not use it.
TNNetChannelMulByLayer = class(TNNetChannelTransformBase)
private
FLayerWithChannelsIdx, FLayerMulIdx: integer;
FLayerWithChannels, FLayerMul: TNNetLayer;
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
constructor Create(LayerWithChannels, LayerMul: TNNetLayer); overload;
constructor Create(LayerWithChannelsIdx, LayerMulIdx: integer); overload;
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// This layer multiplies each cell from one branch to each cell from another
// branch.
TNNetCellMulByCell = class(TNNetChannelTransformBase)
private
FLayerAIdx, FLayerBIdx: integer;
FLayerA, FLayerB: TNNetLayer;
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
constructor Create(LayerA, LayerB: TNNetLayer); overload;
constructor Create(LayerAIdx, LayerBIdx: integer); overload;
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// This layer adds a trainable bias to each output cell. Placing
// this layer before and after convolutions can speed up learning.
// It's useless placing this layer after fully connected layers with bias.
TNNetCellBias = class(TNNetIdentityWithoutL2)
private
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
procedure Compute(); override;
procedure Backpropagate(); override;
procedure InitDefault(); override;
end;
/// This layer multiplies each output cell by a trainable number. Placing
// this layer before and after convolutions can speed up learning.
TNNetCellMul = class(TNNetIdentityWithoutL2)
private
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
procedure Compute(); override;
procedure Backpropagate(); override;
procedure InitDefault(); override;
end;
/// This layer zero centers the output. This layer placed
// before convolutional layers can speed up learning A LOT. Use
// this layer in combination with batch update or default ClipNorm
// as it can produce spikes in the learning provoking overflow.
TNNetChannelZeroCenter = class(TNNetChannelShiftBase)
public
procedure Backpropagate(); override;
procedure BackpropagateNoTest(); override;
procedure ComputeL2Decay(); override;
end;
{ TNNetChannelNorm }
// TNNetChannelNorm has not been tested. Do not use it.
// This layer does a channel normalization without zero centering and trainable parameters.
TNNetChannelNorm = class(TNNetChannelShiftBase)
private
FAuxOutput: TNNetVolume;
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
constructor Create(); override;
destructor Destroy(); override;
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// This layer does zero centering and standard normalization per channel with
// trainable parameters.
TNNetChannelStdNormalization = class(TNNetChannelZeroCenter)
private
FAuxOutput: TNNetVolume;
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
constructor Create(); override;
destructor Destroy(); override;
procedure Compute(); override;
procedure Backpropagate(); override;
procedure InitDefault(); override;
function GetMaxAbsoluteDelta(): TNeuralFloat; override;
end;
/// This layer has no trainable parameter. It does a spacial (per channel)
// local response normalization.
TNNetLocalResponseNorm2D = class(TNNetIdentity)
private
FLRN: TNNetVolume;
public
constructor Create(pSize: integer); overload;
destructor Destroy(); override;
procedure Compute(); override;
procedure Backpropagate(); override;
end;
/// This layer interleaves input channels.
TNNetInterleaveChannels = class(TNNetIdentity)
private
ToChannels: TNeuralIntegerArray;
procedure SetPrevLayer(pPrevLayer: TNNetLayer); override;
public
constructor Create(StepSize: integer); overload;