Repository navigation
Expand file tree
/
Copy pathML.Graph.pas
More file actions
2430 lines (2102 loc) · 76.1 KB
/
Copy pathML.Graph.pas
File metadata and controls
2430 lines (2102 loc) · 76.1 KB
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
unit ML.Graph;
{$R-} // Disable range checking for performance - we do manual bounds checking
interface
uses
System.SysUtils,
System.Generics.Collections,
System.Classes,
System.Math,
ML.Arena,
ML.Tensor,
ML.Ops;
type
PSingleArray = ^TSingleArray;
TSingleArray = array[0..MaxInt div SizeOf(Single) - 1] of Single;
type
TParamData = record
Shape: TArray<Integer>;
Data: TArray<Single>;
end;
TModelData = record
Version: Integer;
ParamCount: Integer;
Params: TArray<TParamData>;
end;
type
TOpType = (
opInput, // Input data (from user)
opParam, // Trainable parameter (weights, biases)
opAdd, // Element-wise addition
opMul, // Element-wise multiplication
opMatMul, // Matrix multiplication
opReLU, // ReLU activation
opLeakyReLU, // LeakyReLU activation
opSigmoid, // Sigmoid activation
opTanh, // Tanh activation
opSoftmax, // Softmax normalization
opMSE, // Mean Squared Error loss
opCrossEntropy, // Cross Entropy loss
opConv2D, // 2D Convolution
opReshape, // Reshape tensor (view operation)
opBatchNorm, // Batch Normalization
opMatMulAdd, // Fused MatMul + Add (MatMul with bias)
opAddReLU, // Fused Add + ReLU
opMatMulReLU, // Fused MatMul + ReLU
opMaxPool2D, // Max Pooling 2D
opDropout // Dropout regularization
);
// A node in the computation graph
TNode = record
Op: TOpType;
Result: TTensor;
Parents: array[0..2] of Integer; // Max 3 parents (for BatchNorm: Input, Gamma, Beta)
ParentCount: Integer;
RequiresGrad: Boolean;
end;
// Memory monitoring types
TGraphMemoryStats = record
ArenaUsage: TArenaStats;
ParameterCount: Integer;
ParameterBytes: Integer;
ActivationBytes: Integer;
GradientBytes: Integer;
end;
TGraph = class
private
FArena: TArena;
FNodes: TArray<TNode>;
FNodeCount: Integer;
FNodeCapacity: Integer;
// Savepoint for separating params from activations
FParamSavePoint: Integer;
FParamNodeCount: Integer;
// Conv2D parameters storage (Padding, Stride) - indexed by node index
FConv2DPadding: TArray<Integer>;
FConv2DStride: TArray<Integer>;
// Shape inference and validation
FShapeValidationEnabled: Boolean;
// BatchNorm running statistics (per BatchNorm node)
FBatchNormRunningMean: TArray<TArray<Single>>;
FBatchNormRunningVar: TArray<TArray<Single>>;
FBatchNormEpsilon: TArray<Single>;
FBatchNormMomentum: TArray<Single>;
FIsTraining: Boolean;
// MaxPool2D indices storage (per node)
FMaxPoolIndices: TArray<TArray<Integer>>;
FMaxPoolSize: TArray<Integer>;
FMaxPoolStride: TArray<Integer>;
// Dropout mask storage (per node)
FDropoutMasks: TArray<TArray<Byte>>;
FDropoutRates: TArray<Single>;
// Adam optimizer state
FAdamM: TArray<TArray<Single>>; // Momentum (first moment)
FAdamV: TArray<TArray<Single>>; // Velocity (second moment)
FAdamBeta1: Single;
FAdamBeta2: Single;
FAdamEpsilon: Single;
FAdamStep: Integer;
FUseAdam: Boolean;
// Gradient checking
FGradientCheckEnabled: Boolean;
FGradientCheckEpsilon: Single;
FGradientCheckTolerance: Single;
FGradientCheckDone: Boolean; // Track if we've done gradient check for this backward pass
function AddNode(const ANode: TNode): Integer;
procedure EnsureCapacity;
procedure AllocGradIfNeeded(NodeIdx: Integer);
function InferShape(Op: TOpType; const InputShapes: array of TArray<Integer>;
Padding: Integer = 0; Stride: Integer = 1; const NewShape: TArray<Integer> = nil): TArray<Integer>;
procedure ValidateShape(NodeIdx: Integer; const InferredShape, ActualShape: TArray<Integer>);
public
constructor Create(ArenaSizeMB: Integer = 256);
destructor Destroy; override;
// Reset the graph and arena (full reset)
procedure Reset;
// Mark current position as end of parameters
procedure MarkParamsEnd;
// Reset only activations, keep parameters intact
procedure ResetActivations;
// Forward building - returns node index
function Input(const AShape: array of Integer): Integer;
function Param(const AShape: array of Integer): Integer;
function Add(A, B: Integer): Integer;
function Mul(A, B: Integer): Integer;
function MatMul(A, B: Integer): Integer;
function ReLU(A: Integer): Integer;
function LeakyReLU(A: Integer; Alpha: Single = 0.01): Integer;
function Sigmoid(A: Integer): Integer;
function Tanh(A: Integer): Integer;
function Softmax(A: Integer): Integer;
function MSE(Pred, Target: Integer): Integer;
function CrossEntropy(Pred, Target: Integer): Integer;
function Conv2D(Input, Weight: Integer; Padding, Stride: Integer): Integer;
function Reshape(InputIdx: Integer; const NewShape: array of Integer): Integer;
function BatchNorm(InputIdx: Integer; Epsilon: Single = 1e-5; Momentum: Single = 0.1): Integer;
function MatMulAdd(A, B, Bias: Integer): Integer;
function AddReLU(A, B: Integer): Integer;
function MatMulReLU(A, B: Integer): Integer;
function MaxPool2D(Input: Integer; PoolSize, Stride: Integer): Integer;
function Dropout(Input: Integer; DropRate: Single): Integer;
// Training mode control
procedure SetTrainingMode(IsTraining: Boolean);
// Backward pass
procedure Backward(LossNode: Integer);
// Optimizer
procedure Step(LearningRate: Single; GradClip: Single = 5.0); // SGD
procedure StepAdam(LearningRate: Single; GradClip: Single = 5.0); // Adam optimizer
procedure ZeroGrad;
procedure SetOptimizer(UseAdam: Boolean; Beta1: Single = 0.9; Beta2: Single = 0.999; Epsilon: Single = 1e-8);
// Access
property Arena: TArena read FArena;
function GetNode(Idx: Integer): TNode;
function GetNodeCount: Integer;
// Helper methods for setting input values and getting outputs
procedure SetInputValue(InputIdx: Integer; const Values: TArray<Single>);
function GetOutputValue(OutputIdx: Integer): Single;
function GetOutputValues(OutputIdx: Integer; Count: Integer): TArray<Single>;
// Model persistence
function ExportParams: TModelData;
procedure ImportParams(const ModelData: TModelData; Reinitialize: Boolean = False);
procedure SaveModel(const FileName: string);
procedure LoadModel(const FileName: string);
// Shape inference and validation
function ValidateShapes: Boolean;
property EnableShapeValidation: Boolean read FShapeValidationEnabled write FShapeValidationEnabled;
// Gradient checking
procedure EnableGradientCheck(Enabled: Boolean; Epsilon: Single = 1e-5; Tolerance: Single = 1e-4);
function CheckGradients(LossNode: Integer): Boolean;
property GradientCheckEnabled: Boolean read FGradientCheckEnabled;
// Memory monitoring
function GetMemoryStats: TGraphMemoryStats;
procedure LogMemoryStats;
end;
implementation
// Helper to create tensor with same shape as another
function CreateTensorSameShape(Arena: TArena; const Source: TTensor;
RequiresGrad: Boolean): TTensor;
var
i: Integer;
begin
SetLength(Result.Shape, Length(Source.Shape));
for i := 0 to High(Source.Shape) do
Result.Shape[i] := Source.Shape[i];
Result.Strides := ComputeStrides(Result.Shape);
Result.DataPtr := Arena.Alloc(Result.ElementCount);
Result.GradPtr := -1;
Result.RequiresGrad := RequiresGrad;
end;
constructor TGraph.Create(ArenaSizeMB: Integer);
begin
FArena := TArena.Create(ArenaSizeMB);
FNodeCapacity := 1024;
SetLength(FNodes, FNodeCapacity);
SetLength(FConv2DPadding, FNodeCapacity);
SetLength(FConv2DStride, FNodeCapacity);
FNodeCount := 0;
FShapeValidationEnabled := False; // Disabled by default for performance (enable for debugging)
FIsTraining := True; // Default to training mode
SetLength(FBatchNormRunningMean, 0);
SetLength(FBatchNormRunningVar, 0);
SetLength(FBatchNormEpsilon, 0);
SetLength(FBatchNormMomentum, 0);
FUseAdam := False; // Default to SGD
FAdamBeta1 := 0.9;
FAdamBeta2 := 0.999;
FAdamEpsilon := 1e-8;
FAdamStep := 0;
SetLength(FAdamM, 0);
SetLength(FAdamV, 0);
end;
destructor TGraph.Destroy;
begin
FArena.Free;
inherited;
end;
procedure TGraph.EnsureCapacity;
begin
if FNodeCount >= FNodeCapacity then
begin
FNodeCapacity := FNodeCapacity * 2;
SetLength(FNodes, FNodeCapacity);
end;
end;
function TGraph.AddNode(const ANode: TNode): Integer;
begin
EnsureCapacity;
Result := FNodeCount;
FNodes[Result] := ANode;
Inc(FNodeCount);
end;
procedure TGraph.AllocGradIfNeeded(NodeIdx: Integer);
var
Node: TNode;
GradPtr: TMemPtr;
PGrad: PSingleArray;
i, ElementCount: Integer;
begin
if (NodeIdx < 0) or (NodeIdx >= FNodeCount) then
Exit;
Node := FNodes[NodeIdx];
ElementCount := Node.Result.ElementCount;
if Node.RequiresGrad and (Node.Result.GradPtr < 0) and (ElementCount > 0) then
begin
GradPtr := FArena.Alloc(ElementCount);
FNodes[NodeIdx].Result.GradPtr := GradPtr;
// Zero initialize gradients
PGrad := PSingleArray(FArena.GetPtr(GradPtr));
for i := 0 to ElementCount - 1 do
PGrad^[i] := 0;
end;
end;
procedure TGraph.Reset;
begin
FArena.Reset;
FNodeCount := 0;
FParamSavePoint := 0;
FParamNodeCount := 0;
// Conv2D parameters are reset automatically when FNodeCount is reset
end;
procedure TGraph.MarkParamsEnd;
begin
// Call this after all Param() calls to mark the boundary
// between persistent parameters and temporary activations
FParamSavePoint := FArena.GetSavePoint;
FParamNodeCount := FNodeCount;
end;
procedure TGraph.ResetActivations;
begin
// Reset only activations, keep parameters intact
// More efficient than full Reset + SaveParameters + RestoreParameters
FArena.Restore(FParamSavePoint);
FNodeCount := FParamNodeCount;
end;
function TGraph.Input(const AShape: array of Integer): Integer;
var
Node: TNode;
begin
Node.Op := opInput;
Node.Result := TTensor.Create(FArena, AShape, False);
Node.ParentCount := 0;
Node.RequiresGrad := False;
Result := AddNode(Node);
end;
function TGraph.Param(const AShape: array of Integer): Integer;
var
Node: TNode;
PData, PGrad: PSingleArray;
i, Count, TotalDims: Integer;
Scale: Single;
begin
Node.Op := opParam;
Node.Result := TTensor.Create(FArena, AShape, True);
Node.ParentCount := 0;
Node.RequiresGrad := True;
Count := Node.Result.ElementCount;
// Initialize with random values (He initialization for ReLU/LeakyReLU)
// Fan_in is the product of all dimensions except the first (output channels)
PData := PSingleArray(Node.Result.RawData(FArena));
// For conv weights [OutCh, InCh, KH, KW], fan_in = InCh * KH * KW
// For dense weights [OutFeat, InFeat], fan_in = InFeat
// For bias [N], fan_in = N (not critical since bias is typically small)
if Length(AShape) >= 2 then
begin
// Product of all dims except first
TotalDims := 1;
for i := 1 to High(AShape) do
TotalDims := TotalDims * AShape[i];
end
else if Length(AShape) = 1 then
TotalDims := AShape[0]
else
TotalDims := 1;
// He initialization: sqrt(2.0 / fan_in) for ReLU-based networks
Scale := Sqrt(2.0 / TotalDims);
// Random initialization in range [-scale, +scale]
for i := 0 to Count - 1 do
PData^[i] := (Random * 2.0 - 1.0) * Scale;
// Pre-allocate gradients for params so they persist across ResetActivations
// This is critical: gradients must be allocated BEFORE MarkParamsEnd()
Node.Result.GradPtr := FArena.Alloc(Count);
PGrad := PSingleArray(FArena.GetPtr(Node.Result.GradPtr));
for i := 0 to Count - 1 do
PGrad^[i] := 0;
Result := AddNode(Node);
end;
function TGraph.Add(A, B: Integer): Integer;
var
Node: TNode;
TensorA, TensorB: TTensor;
OutShape: TArray<Integer>;
i: Integer;
ShapeAStr, ShapeBStr: string;
begin
TensorA := FNodes[A].Result;
TensorB := FNodes[B].Result;
// Debug: Build shape strings
ShapeAStr := '[';
for i := 0 to High(TensorA.Shape) do
begin
if i > 0 then ShapeAStr := ShapeAStr + ', ';
ShapeAStr := ShapeAStr + IntToStr(TensorA.Shape[i]);
end;
ShapeAStr := ShapeAStr + ']';
ShapeBStr := '[';
for i := 0 to High(TensorB.Shape) do
begin
if i > 0 then ShapeBStr := ShapeBStr + ', ';
ShapeBStr := ShapeBStr + IntToStr(TensorB.Shape[i]);
end;
ShapeBStr := ShapeBStr + ']';
// Check if shapes are broadcastable
if not CanBroadcast(TensorA.Shape, TensorB.Shape) then
raise Exception.CreateFmt('Add: Shapes are not broadcastable. ShapeA=%s, ShapeB=%s', [ShapeAStr, ShapeBStr]);
// Compute broadcast output shape
OutShape := BroadcastShapes(TensorA.Shape, TensorB.Shape);
Node.Op := opAdd;
// Create output with broadcast shape
SetLength(Node.Result.Shape, Length(OutShape));
for i := 0 to High(OutShape) do
Node.Result.Shape[i] := OutShape[i];
Node.Result.Strides := ComputeStrides(Node.Result.Shape);
Node.Result.DataPtr := FArena.Alloc(Node.Result.ElementCount);
Node.Result.GradPtr := -1;
Node.Result.RequiresGrad := FNodes[A].RequiresGrad or FNodes[B].RequiresGrad;
Node.Parents[0] := A;
Node.Parents[1] := B;
Node.ParentCount := 2;
Node.RequiresGrad := Node.Result.RequiresGrad;
TOps.Add(FArena, TensorA, TensorB, Node.Result);
Result := AddNode(Node);
// Validate shape if enabled
if FShapeValidationEnabled then
begin
var InputShapes: array of TArray<Integer>;
SetLength(InputShapes, 2);
InputShapes[0] := TensorA.Shape;
InputShapes[1] := TensorB.Shape;
var InferredShape := InferShape(opAdd, InputShapes);
ValidateShape(Result, InferredShape, Node.Result.Shape);
end;
end;
function TGraph.Mul(A, B: Integer): Integer;
var
Node: TNode;
TensorA, TensorB: TTensor;
OutShape: TArray<Integer>;
i: Integer;
begin
TensorA := FNodes[A].Result;
TensorB := FNodes[B].Result;
// Check if shapes are broadcastable
if not CanBroadcast(TensorA.Shape, TensorB.Shape) then
raise Exception.Create('Mul: Shapes are not broadcastable');
// Compute broadcast output shape
OutShape := BroadcastShapes(TensorA.Shape, TensorB.Shape);
Node.Op := opMul;
// Create output with broadcast shape
SetLength(Node.Result.Shape, Length(OutShape));
for i := 0 to High(OutShape) do
Node.Result.Shape[i] := OutShape[i];
Node.Result.Strides := ComputeStrides(Node.Result.Shape);
Node.Result.DataPtr := FArena.Alloc(Node.Result.ElementCount);
Node.Result.GradPtr := -1;
Node.Result.RequiresGrad := FNodes[A].RequiresGrad or FNodes[B].RequiresGrad;
Node.Parents[0] := A;
Node.Parents[1] := B;
Node.ParentCount := 2;
Node.RequiresGrad := Node.Result.RequiresGrad;
TOps.Mul(FArena, TensorA, TensorB, Node.Result);
Result := AddNode(Node);
// Validate shape if enabled
if FShapeValidationEnabled then
begin
var InputShapes: array of TArray<Integer>;
SetLength(InputShapes, 2);
InputShapes[0] := TensorA.Shape;
InputShapes[1] := TensorB.Shape;
var InferredShape := InferShape(opMul, InputShapes);
ValidateShape(Result, InferredShape, Node.Result.Shape);
end;
end;
function TGraph.MatMul(A, B: Integer): Integer;
var
Node: TNode;
TensorA, TensorB: TTensor;
ANdim, BNdim, OutNdim: Integer;
OutShape: TArray<Integer>;
i: Integer;
begin
TensorA := FNodes[A].Result;
TensorB := FNodes[B].Result;
ANdim := TensorA.NDim;
BNdim := TensorB.NDim;
if (ANdim < 2) or (BNdim < 2) then
raise Exception.Create('MatMul: Tensors must have at least 2 dimensions');
// Check inner dimensions match: A[..., M, K] @ B[..., K, N]
if TensorA.Shape[ANdim - 1] <> TensorB.Shape[BNdim - 2] then
raise Exception.CreateFmt('MatMul: Inner dimension mismatch: %d != %d',
[TensorA.Shape[ANdim - 1], TensorB.Shape[BNdim - 2]]);
// For N-D tensors, batch dimensions must match
if (ANdim > 2) or (BNdim > 2) then
begin
// Both must have same number of dimensions for batched matmul
if ANdim <> BNdim then
raise Exception.Create('MatMul: Batch dimension count must match for N-D tensors');
// Check all batch dimensions match
for i := 0 to ANdim - 3 do
if TensorA.Shape[i] <> TensorB.Shape[i] then
raise Exception.CreateFmt('MatMul: Batch dimension %d mismatch: %d vs %d',
[i, TensorA.Shape[i], TensorB.Shape[i]]);
end;
// Compute output shape: [batch..., M, N]
OutNdim := ANdim;
SetLength(OutShape, OutNdim);
// Copy batch dimensions from A
for i := 0 to OutNdim - 3 do
OutShape[i] := TensorA.Shape[i];
// Last two dimensions: M from A, N from B
OutShape[OutNdim - 2] := TensorA.Shape[ANdim - 2]; // M
OutShape[OutNdim - 1] := TensorB.Shape[BNdim - 1]; // N
Node.Op := opMatMul;
SetLength(Node.Result.Shape, OutNdim);
for i := 0 to OutNdim - 1 do
Node.Result.Shape[i] := OutShape[i];
Node.Result.Strides := ComputeStrides(Node.Result.Shape);
Node.Result.DataPtr := FArena.Alloc(Node.Result.ElementCount);
Node.Result.GradPtr := -1;
Node.Result.RequiresGrad := FNodes[A].RequiresGrad or FNodes[B].RequiresGrad;
Node.Parents[0] := A;
Node.Parents[1] := B;
Node.ParentCount := 2;
Node.RequiresGrad := Node.Result.RequiresGrad;
TOps.MatMul(FArena, TensorA, TensorB, Node.Result);
Result := AddNode(Node);
// Validate shape if enabled
if FShapeValidationEnabled then
begin
var InputShapes: array of TArray<Integer>;
SetLength(InputShapes, 2);
InputShapes[0] := TensorA.Shape;
InputShapes[1] := TensorB.Shape;
var InferredShape := InferShape(opMatMul, InputShapes);
ValidateShape(Result, InferredShape, Node.Result.Shape);
end;
end;
function TGraph.ReLU(A: Integer): Integer;
var
Node: TNode;
TensorA: TTensor;
begin
TensorA := FNodes[A].Result;
Node.Op := opReLU;
Node.Result := CreateTensorSameShape(FArena, TensorA, FNodes[A].RequiresGrad);
Node.Parents[0] := A;
Node.ParentCount := 1;
Node.RequiresGrad := Node.Result.RequiresGrad;
TOps.ReLU(FArena, TensorA, Node.Result);
Result := AddNode(Node);
end;
function TGraph.LeakyReLU(A: Integer; Alpha: Single): Integer;
var
Node: TNode;
TensorA: TTensor;
begin
TensorA := FNodes[A].Result;
Node.Op := opLeakyReLU;
Node.Result := CreateTensorSameShape(FArena, TensorA, FNodes[A].RequiresGrad);
Node.Parents[0] := A;
Node.ParentCount := 1;
Node.RequiresGrad := Node.Result.RequiresGrad;
TOps.LeakyReLU(FArena, TensorA, Node.Result, Alpha);
Result := AddNode(Node);
end;
function TGraph.Sigmoid(A: Integer): Integer;
var
Node: TNode;
TensorA: TTensor;
begin
TensorA := FNodes[A].Result;
Node.Op := opSigmoid;
Node.Result := CreateTensorSameShape(FArena, TensorA, FNodes[A].RequiresGrad);
Node.Parents[0] := A;
Node.ParentCount := 1;
Node.RequiresGrad := Node.Result.RequiresGrad;
TOps.Sigmoid(FArena, TensorA, Node.Result);
Result := AddNode(Node);
end;
function TGraph.Tanh(A: Integer): Integer;
var
Node: TNode;
TensorA: TTensor;
begin
TensorA := FNodes[A].Result;
Node.Op := opTanh;
Node.Result := CreateTensorSameShape(FArena, TensorA, FNodes[A].RequiresGrad);
Node.Parents[0] := A;
Node.ParentCount := 1;
Node.RequiresGrad := Node.Result.RequiresGrad;
TOps.Tanh(FArena, TensorA, Node.Result);
Result := AddNode(Node);
end;
function TGraph.Softmax(A: Integer): Integer;
var
Node: TNode;
TensorA: TTensor;
begin
TensorA := FNodes[A].Result;
Node.Op := opSoftmax;
Node.Result := CreateTensorSameShape(FArena, TensorA, FNodes[A].RequiresGrad);
Node.Parents[0] := A;
Node.ParentCount := 1;
Node.RequiresGrad := Node.Result.RequiresGrad;
TOps.Softmax(FArena, TensorA, Node.Result);
Result := AddNode(Node);
end;
function TGraph.MSE(Pred, Target: Integer): Integer;
var
Node: TNode;
TensorPred, TensorTarget: TTensor;
Loss: Single;
begin
TensorPred := FNodes[Pred].Result;
TensorTarget := FNodes[Target].Result;
if not TensorPred.SameShape(TensorTarget) then
raise Exception.Create('MSE: Shape mismatch');
Loss := TOps.MSE(FArena, TensorPred, TensorTarget);
// Create a scalar tensor for the loss
Node.Op := opMSE;
Node.Result := TTensor.Create(FArena, [1], FNodes[Pred].RequiresGrad or FNodes[Target].RequiresGrad);
Node.Parents[0] := Pred;
Node.Parents[1] := Target;
Node.ParentCount := 2;
Node.RequiresGrad := Node.Result.RequiresGrad;
// Store loss value
var PLoss: PSingleArray;
PLoss := PSingleArray(Node.Result.RawData(FArena));
PLoss^[0] := Loss;
Result := AddNode(Node);
end;
function TGraph.CrossEntropy(Pred, Target: Integer): Integer;
var
Node: TNode;
TensorPred, TensorTarget: TTensor;
Loss: Single;
begin
TensorPred := FNodes[Pred].Result;
TensorTarget := FNodes[Target].Result;
if not TensorPred.SameShape(TensorTarget) then
raise Exception.Create('CrossEntropy: Shape mismatch');
Loss := TOps.CrossEntropy(FArena, TensorPred, TensorTarget);
// Create a scalar tensor for the loss
Node.Op := opCrossEntropy;
Node.Result := TTensor.Create(FArena, [1], FNodes[Pred].RequiresGrad or FNodes[Target].RequiresGrad);
Node.Parents[0] := Pred;
Node.Parents[1] := Target;
Node.ParentCount := 2;
Node.RequiresGrad := Node.Result.RequiresGrad;
// Store loss value
var PLoss: PSingleArray;
PLoss := PSingleArray(Node.Result.RawData(FArena));
PLoss^[0] := Loss;
Result := AddNode(Node);
end;
function TGraph.Conv2D(Input, Weight: Integer; Padding, Stride: Integer): Integer;
var
Node: TNode;
TensorInput, TensorWeight: TTensor;
Batch, InCh, InH, InW: Integer;
OutCh, KernelH, KernelW: Integer;
OutH, OutW: Integer;
OutShape: TArray<Integer>;
begin
TensorInput := FNodes[Input].Result;
TensorWeight := FNodes[Weight].Result;
// Validate shapes
if TensorInput.NDim <> 4 then
raise Exception.Create('Conv2D: Input must be 4D tensor [Batch, InChannels, InH, InW]');
if TensorWeight.NDim <> 4 then
raise Exception.Create('Conv2D: Weight must be 4D tensor [OutChannels, InChannels, KernelH, KernelW]');
Batch := TensorInput.Shape[0];
InCh := TensorInput.Shape[1];
InH := TensorInput.Shape[2];
InW := TensorInput.Shape[3];
OutCh := TensorWeight.Shape[0];
if TensorWeight.Shape[1] <> InCh then
raise Exception.CreateFmt('Conv2D: Input channels mismatch: input has %d, weight expects %d',
[InCh, TensorWeight.Shape[1]]);
KernelH := TensorWeight.Shape[2];
KernelW := TensorWeight.Shape[3];
// Compute output dimensions
OutH := (InH + 2 * Padding - KernelH) div Stride + 1;
OutW := (InW + 2 * Padding - KernelW) div Stride + 1;
if (OutH <= 0) or (OutW <= 0) then
raise Exception.CreateFmt('Conv2D: Invalid output dimensions: OutH=%d, OutW=%d', [OutH, OutW]);
// Create output shape
SetLength(OutShape, 4);
OutShape[0] := Batch;
OutShape[1] := OutCh;
OutShape[2] := OutH;
OutShape[3] := OutW;
Node.Op := opConv2D;
Node.Result := TTensor.Create(FArena, OutShape, FNodes[Input].RequiresGrad or FNodes[Weight].RequiresGrad);
Node.Parents[0] := Input;
Node.Parents[1] := Weight;
Node.ParentCount := 2;
Node.RequiresGrad := Node.Result.RequiresGrad;
// Store padding and stride in node (we'll need them for backward pass)
// For now, we'll pass them directly to the backward operation
// Note: We need to store these values somewhere. Let's use a simple approach:
// Store in a temporary way - we'll access them from the operation parameters
TOps.Conv2D(FArena, TensorInput, TensorWeight, Padding, Stride, Node.Result);
Result := AddNode(Node);
// Store padding and stride for backward pass
if Result >= Length(FConv2DPadding) then
begin
SetLength(FConv2DPadding, FNodeCapacity);
SetLength(FConv2DStride, FNodeCapacity);
end;
FConv2DPadding[Result] := Padding;
FConv2DStride[Result] := Stride;
end;
function TGraph.MaxPool2D(Input: Integer; PoolSize, Stride: Integer): Integer;
var
Node: TNode;
TensorInput: TTensor;
Batch, Channels, InH, InW: Integer;
OutH, OutW: Integer;
OutShape: TArray<Integer>;
begin
TensorInput := FNodes[Input].Result;
if TensorInput.NDim <> 4 then
raise Exception.Create('MaxPool2D: Input must be 4D tensor [Batch, Channels, H, W]');
Batch := TensorInput.Shape[0];
Channels := TensorInput.Shape[1];
InH := TensorInput.Shape[2];
InW := TensorInput.Shape[3];
OutH := (InH - PoolSize) div Stride + 1;
OutW := (InW - PoolSize) div Stride + 1;
if (OutH <= 0) or (OutW <= 0) then
raise Exception.CreateFmt('MaxPool2D: Invalid output dimensions: OutH=%d, OutW=%d', [OutH, OutW]);
SetLength(OutShape, 4);
OutShape[0] := Batch;
OutShape[1] := Channels;
OutShape[2] := OutH;
OutShape[3] := OutW;
Node.Op := opMaxPool2D;
Node.Result := TTensor.Create(FArena, OutShape, FNodes[Input].RequiresGrad);
Node.Parents[0] := Input;
Node.ParentCount := 1;
Node.RequiresGrad := Node.Result.RequiresGrad;
// Ensure storage arrays are sized
if FNodeCount >= Length(FMaxPoolIndices) then
begin
SetLength(FMaxPoolIndices, FNodeCapacity);
SetLength(FMaxPoolSize, FNodeCapacity);
SetLength(FMaxPoolStride, FNodeCapacity);
end;
TOps.MaxPool2D(FArena, TensorInput, PoolSize, Stride, Node.Result, FMaxPoolIndices[FNodeCount]);
Result := AddNode(Node);
FMaxPoolSize[Result] := PoolSize;
FMaxPoolStride[Result] := Stride;
end;
function TGraph.Dropout(Input: Integer; DropRate: Single): Integer;
var
Node: TNode;
TensorInput: TTensor;
begin
TensorInput := FNodes[Input].Result;
Node.Op := opDropout;
Node.Result := TTensor.Create(FArena, TensorInput.Shape, FNodes[Input].RequiresGrad);
Node.Parents[0] := Input;
Node.ParentCount := 1;
Node.RequiresGrad := Node.Result.RequiresGrad;
// Ensure storage arrays are sized
if FNodeCount >= Length(FDropoutMasks) then
begin
SetLength(FDropoutMasks, FNodeCapacity);
SetLength(FDropoutRates, FNodeCapacity);
end;
TOps.Dropout(FArena, TensorInput, DropRate, FIsTraining, Node.Result, FDropoutMasks[FNodeCount]);
Result := AddNode(Node);
FDropoutRates[Result] := DropRate;
end;
function TGraph.Reshape(InputIdx: Integer; const NewShape: array of Integer): Integer;
var
Node: TNode;
TensorInput: TTensor;
i: Integer;
NewCount, OldCount: Integer;
begin
TensorInput := FNodes[InputIdx].Result;
// Validate element count matches
OldCount := TensorInput.ElementCount;
NewCount := 1;
for i := 0 to High(NewShape) do
begin
if NewShape[i] < 0 then
raise Exception.Create('Reshape: Negative dimensions not supported');
NewCount := NewCount * NewShape[i];
end;
if NewCount <> OldCount then
raise Exception.CreateFmt('Reshape: Cannot reshape [%d] elements to [%d] elements',
[OldCount, NewCount]);
// Create reshape node - this is a view operation, no data copy
Node.Op := opReshape;
Node.Result := TensorInput.Reshape(NewShape); // Use tensor's Reshape method (view operation)
Node.Parents[0] := InputIdx;
Node.ParentCount := 1;
Node.RequiresGrad := FNodes[InputIdx].RequiresGrad;
Result := AddNode(Node);
end;
procedure TGraph.SetTrainingMode(IsTraining: Boolean);
begin
FIsTraining := IsTraining;
end;
function TGraph.BatchNorm(InputIdx: Integer; Epsilon: Single; Momentum: Single): Integer;
var
Node: TNode;
TensorInput: TTensor;
Channels: Integer;
GammaIdx, BetaIdx: Integer;
TensorGamma, TensorBeta: TTensor;
BNIdx: Integer;
c: Integer;
PGamma, PBeta: PSingleArray;
begin
TensorInput := FNodes[InputIdx].Result;
// BatchNorm expects input shape [Batch, Channels, ...] (at least 2D)
if TensorInput.NDim < 2 then
raise Exception.Create('BatchNorm: Input must have at least 2 dimensions');
Channels := TensorInput.Shape[1];
// Create gamma (scale) and beta (shift) parameters
GammaIdx := Param([Channels]);
BetaIdx := Param([Channels]);
TensorGamma := FNodes[GammaIdx].Result;
TensorBeta := FNodes[BetaIdx].Result;
// Initialize gamma to 1, beta to 0
PGamma := PSingleArray(FArena.GetPtr(TensorGamma.DataPtr));
PBeta := PSingleArray(FArena.GetPtr(TensorBeta.DataPtr));
for c := 0 to Channels - 1 do
begin
PGamma^[c] := 1.0; // Start with identity transformation
PBeta^[c] := 0.0;
end;
// Ensure running statistics arrays are large enough
BNIdx := FNodeCount; // This will be the node index after AddNode
if BNIdx >= Length(FBatchNormRunningMean) then
begin
SetLength(FBatchNormRunningMean, FNodeCapacity);
SetLength(FBatchNormRunningVar, FNodeCapacity);
SetLength(FBatchNormEpsilon, FNodeCapacity);
SetLength(FBatchNormMomentum, FNodeCapacity);
end;
// Initialize running statistics for this BatchNorm node
SetLength(FBatchNormRunningMean[BNIdx], Channels);
SetLength(FBatchNormRunningVar[BNIdx], Channels);
for c := 0 to Channels - 1 do
begin
FBatchNormRunningMean[BNIdx][c] := 0;
FBatchNormRunningVar[BNIdx][c] := 1; // Initialize variance to 1
end;
FBatchNormEpsilon[BNIdx] := Epsilon;
FBatchNormMomentum[BNIdx] := Momentum;
// Create BatchNorm node
Node.Op := opBatchNorm;
Node.Result := CreateTensorSameShape(FArena, TensorInput, FNodes[InputIdx].RequiresGrad);
Node.Parents[0] := InputIdx;
Node.Parents[1] := GammaIdx;
Node.Parents[2] := BetaIdx;
Node.ParentCount := 3; // Input, Gamma, Beta
Node.RequiresGrad := Node.Result.RequiresGrad;
// Execute BatchNorm forward pass
TOps.BatchNorm(FArena, TensorInput, TensorGamma, TensorBeta,
Epsilon, FIsTraining,
FBatchNormRunningMean[BNIdx], FBatchNormRunningVar[BNIdx],
Momentum, Node.Result);
Result := AddNode(Node);
end;
function TGraph.MatMulAdd(A, B, Bias: Integer): Integer;
var
Node: TNode;
TensorA, TensorB, TensorBias: TTensor;
OutShape: TArray<Integer>;
i: Integer;
ANdim, BNdim, OutNdim: Integer;
begin
TensorA := FNodes[A].Result;
TensorB := FNodes[B].Result;
TensorBias := FNodes[Bias].Result;
// Compute output shape from MatMul
ANdim := TensorA.NDim;
BNdim := TensorB.NDim;
if (ANdim < 2) or (BNdim < 2) then
raise Exception.Create('MatMulAdd: Tensors must have at least 2 dimensions');
if TensorA.Shape[ANdim - 1] <> TensorB.Shape[BNdim - 2] then
raise Exception.CreateFmt('MatMulAdd: Inner dimension mismatch: %d != %d',
[TensorA.Shape[ANdim - 1], TensorB.Shape[BNdim - 2]]);
OutNdim := Max(ANdim, BNdim);
SetLength(OutShape, OutNdim);
for i := 0 to OutNdim - 3 do
OutShape[i] := TensorA.Shape[i];
OutShape[OutNdim - 2] := TensorA.Shape[ANdim - 2];
OutShape[OutNdim - 1] := TensorB.Shape[BNdim - 1];
Node.Op := opMatMulAdd;
SetLength(Node.Result.Shape, OutNdim);
for i := 0 to OutNdim - 1 do
Node.Result.Shape[i] := OutShape[i];
Node.Result.Strides := ComputeStrides(Node.Result.Shape);