-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrnn.cpp
More file actions
1580 lines (1376 loc) · 57.8 KB
/
Copy pathrnn.cpp
File metadata and controls
1580 lines (1376 loc) · 57.8 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
/*
* MIT License
*
* Copyright (c) 2025 Matthew Abbott
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <iostream>
#include <vector>
#include <cmath>
#include <random>
#include <string>
#include <sstream>
#include <fstream>
#include <algorithm>
#include <limits>
#include <iomanip>
#include <cstdio>
// ========== Type Aliases ==========
using DArray = std::vector<double>;
using TDArray2D = std::vector<DArray>;
using TDArray3D = std::vector<TDArray2D>;
using TIntArray = std::vector<int>;
// ========== Enums ==========
enum TActivationType { atSigmoid, atTanh, atReLU, atLinear };
enum TLossType { ltMSE, ltCrossEntropy };
enum TCellType { ctSimpleRNN, ctLSTM, ctGRU };
enum TCommand { cmdNone, cmdCreate, cmdTrain, cmdPredict, cmdInfo, cmdHelp };
// ========== Data Structures ==========
struct TDataSplit {
TDArray2D TrainInputs, TrainTargets;
TDArray2D ValInputs, ValTargets;
};
struct TTimeStepCache {
DArray Input;
DArray H, C;
DArray PreH;
DArray F, I, CTilde, O, TanhC;
DArray Z, R, HTilde;
DArray OutVal, OutPre;
TDArray2D LayerInputs;
};
// ========== Utility Functions ==========
double ClipValue(double V, double MaxVal) {
if (V > MaxVal) return MaxVal;
if (V < -MaxVal) return -MaxVal;
return V;
}
double RandomWeight(double Scale) {
static std::mt19937 gen(std::random_device{}());
static std::uniform_real_distribution<> dis(0.0, 1.0);
return (dis(gen) - 0.5) * 2.0 * Scale;
}
void InitMatrix(TDArray2D& M, int Rows, int Cols, double Scale) {
M.resize(Rows);
for (int i = 0; i < Rows; ++i) {
M[i].resize(Cols);
for (int j = 0; j < Cols; ++j) {
M[i][j] = RandomWeight(Scale);
}
}
}
void ZeroMatrix(TDArray2D& M, int Rows, int Cols) {
M.resize(Rows);
for (int i = 0; i < Rows; ++i) {
M[i].resize(Cols);
for (int j = 0; j < Cols; ++j) {
M[i][j] = 0.0;
}
}
}
void ZeroArray(DArray& A, int Size) {
A.resize(Size);
for (int i = 0; i < Size; ++i) {
A[i] = 0.0;
}
}
DArray ConcatArrays(const DArray& A, const DArray& B) {
DArray Result(A.size() + B.size());
for (size_t i = 0; i < A.size(); ++i) {
Result[i] = A[i];
}
for (size_t i = 0; i < B.size(); ++i) {
Result[A.size() + i] = B[i];
}
return Result;
}
// ========== Activation Functions ==========
class TActivation {
public:
static double Apply(double X, TActivationType ActType) {
switch (ActType) {
case atSigmoid:
return 1.0 / (1.0 + std::exp(-std::max(-500.0, std::min(500.0, X))));
case atTanh:
return std::tanh(X);
case atReLU:
return X > 0 ? X : 0;
case atLinear:
return X;
default:
return X;
}
}
static double Derivative(double Y, TActivationType ActType) {
switch (ActType) {
case atSigmoid:
return Y * (1.0 - Y);
case atTanh:
return 1.0 - Y * Y;
case atReLU:
return Y > 0 ? 1.0 : 0.0;
case atLinear:
return 1.0;
default:
return 1.0;
}
}
static void ApplySoftmax(DArray& Arr) {
if (Arr.empty()) return;
double MaxVal = Arr[0];
for (size_t i = 1; i < Arr.size(); ++i) {
if (Arr[i] > MaxVal) MaxVal = Arr[i];
}
double Sum = 0;
for (size_t i = 0; i < Arr.size(); ++i) {
Arr[i] = std::exp(Arr[i] - MaxVal);
Sum += Arr[i];
}
for (size_t i = 0; i < Arr.size(); ++i) {
Arr[i] /= Sum;
}
}
};
// ========== Loss Functions ==========
class TLoss {
public:
static double Compute(const DArray& Pred, const DArray& Target, TLossType LossType) {
double Result = 0;
switch (LossType) {
case ltMSE:
for (size_t i = 0; i < Pred.size(); ++i) {
Result += std::pow(Pred[i] - Target[i], 2);
}
break;
case ltCrossEntropy:
for (size_t i = 0; i < Pred.size(); ++i) {
double P = std::max(1e-15, std::min(1 - 1e-15, Pred[i]));
Result -= (Target[i] * std::log(P) + (1 - Target[i]) * std::log(1 - P));
}
break;
}
return Result / Pred.size();
}
static void Gradient(const DArray& Pred, const DArray& Target, TLossType LossType, DArray& Grad) {
Grad.resize(Pred.size());
switch (LossType) {
case ltMSE:
for (size_t i = 0; i < Pred.size(); ++i) {
Grad[i] = Pred[i] - Target[i];
}
break;
case ltCrossEntropy:
for (size_t i = 0; i < Pred.size(); ++i) {
double P = std::max(1e-15, std::min(1 - 1e-15, Pred[i]));
Grad[i] = (P - Target[i]) / (P * (1 - P) + 1e-15);
}
break;
}
}
};
// ========== Simple RNN Cell ==========
class TSimpleRNNCell {
private:
int FInputSize, FHiddenSize;
TActivationType FActivation;
public:
TDArray2D Wih, Whh;
DArray Bh;
TDArray2D dWih, dWhh;
DArray dBh;
TSimpleRNNCell(int InputSize, int HiddenSize, TActivationType Activation)
: FInputSize(InputSize), FHiddenSize(HiddenSize), FActivation(Activation) {
double Scale = std::sqrt(2.0 / (InputSize + HiddenSize));
InitMatrix(Wih, HiddenSize, InputSize, Scale);
InitMatrix(Whh, HiddenSize, HiddenSize, Scale);
ZeroArray(Bh, HiddenSize);
ZeroMatrix(dWih, HiddenSize, InputSize);
ZeroMatrix(dWhh, HiddenSize, HiddenSize);
ZeroArray(dBh, HiddenSize);
}
void Forward(const DArray& Input, const DArray& PrevH, DArray& H, DArray& PreH) {
H.resize(FHiddenSize);
PreH.resize(FHiddenSize);
for (int i = 0; i < FHiddenSize; ++i) {
double Sum = Bh[i];
for (int j = 0; j < FInputSize; ++j) {
Sum += Wih[i][j] * Input[j];
}
for (int j = 0; j < FHiddenSize; ++j) {
Sum += Whh[i][j] * PrevH[j];
}
PreH[i] = Sum;
H[i] = TActivation::Apply(Sum, FActivation);
}
}
void Backward(const DArray& dH, const DArray& H, const DArray& PreH,
const DArray& PrevH, const DArray& Input, double ClipVal,
DArray& dInput, DArray& dPrevH) {
DArray dHRaw(FHiddenSize);
dInput.resize(FInputSize);
dPrevH.resize(FHiddenSize);
for (int i = 0; i < FInputSize; ++i) dInput[i] = 0;
for (int i = 0; i < FHiddenSize; ++i) dPrevH[i] = 0;
for (int i = 0; i < FHiddenSize; ++i) {
dHRaw[i] = ClipValue(dH[i] * TActivation::Derivative(H[i], FActivation), ClipVal);
}
for (int i = 0; i < FHiddenSize; ++i) {
for (int j = 0; j < FInputSize; ++j) {
dWih[i][j] += dHRaw[i] * Input[j];
dInput[j] += Wih[i][j] * dHRaw[i];
}
for (int j = 0; j < FHiddenSize; ++j) {
dWhh[i][j] += dHRaw[i] * PrevH[j];
dPrevH[j] += Whh[i][j] * dHRaw[i];
}
dBh[i] += dHRaw[i];
}
}
void ApplyGradients(double LR, double ClipVal) {
for (int i = 0; i < FHiddenSize; ++i) {
for (int j = 0; j < FInputSize; ++j) {
Wih[i][j] -= LR * ClipValue(dWih[i][j], ClipVal);
dWih[i][j] = 0;
}
for (int j = 0; j < FHiddenSize; ++j) {
Whh[i][j] -= LR * ClipValue(dWhh[i][j], ClipVal);
dWhh[i][j] = 0;
}
Bh[i] -= LR * ClipValue(dBh[i], ClipVal);
dBh[i] = 0;
}
}
void ResetGradients() {
ZeroMatrix(dWih, FHiddenSize, FInputSize);
ZeroMatrix(dWhh, FHiddenSize, FHiddenSize);
ZeroArray(dBh, FHiddenSize);
}
int GetHiddenSize() const { return FHiddenSize; }
};
// ========== LSTM Cell ==========
class TLSTMCell {
private:
int FInputSize, FHiddenSize;
TActivationType FActivation;
public:
TDArray2D Wf, Wi, Wc, Wo;
DArray Bf, Bi, Bc, Bo;
TDArray2D dWf, dWi, dWc, dWo;
DArray dBf, dBi, dBc, dBo;
TLSTMCell(int InputSize, int HiddenSize, TActivationType Activation)
: FInputSize(InputSize), FHiddenSize(HiddenSize), FActivation(Activation) {
int ConcatSize = InputSize + HiddenSize;
double Scale = 0.01;
InitMatrix(Wf, HiddenSize, ConcatSize, Scale);
InitMatrix(Wi, HiddenSize, ConcatSize, Scale);
InitMatrix(Wc, HiddenSize, ConcatSize, Scale);
InitMatrix(Wo, HiddenSize, ConcatSize, Scale);
ZeroArray(Bf, HiddenSize);
ZeroArray(Bi, HiddenSize);
ZeroArray(Bc, HiddenSize);
ZeroArray(Bo, HiddenSize);
ZeroMatrix(dWf, HiddenSize, ConcatSize);
ZeroMatrix(dWi, HiddenSize, ConcatSize);
ZeroMatrix(dWc, HiddenSize, ConcatSize);
ZeroMatrix(dWo, HiddenSize, ConcatSize);
ZeroArray(dBf, HiddenSize);
ZeroArray(dBi, HiddenSize);
ZeroArray(dBc, HiddenSize);
ZeroArray(dBo, HiddenSize);
}
void Forward(const DArray& Input, const DArray& PrevH, const DArray& PrevC,
DArray& H, DArray& C, DArray& F, DArray& I, DArray& CTilde,
DArray& O, DArray& TanhC) {
DArray Concat = ConcatArrays(Input, PrevH);
H.resize(FHiddenSize);
C.resize(FHiddenSize);
F.resize(FHiddenSize);
I.resize(FHiddenSize);
CTilde.resize(FHiddenSize);
O.resize(FHiddenSize);
TanhC.resize(FHiddenSize);
for (int k = 0; k < FHiddenSize; ++k) {
double SumF = Bf[k], SumI = Bi[k], SumC = Bc[k], SumO = Bo[k];
for (size_t j = 0; j < Concat.size(); ++j) {
SumF += Wf[k][j] * Concat[j];
SumI += Wi[k][j] * Concat[j];
SumC += Wc[k][j] * Concat[j];
SumO += Wo[k][j] * Concat[j];
}
F[k] = TActivation::Apply(SumF, atSigmoid);
I[k] = TActivation::Apply(SumI, atSigmoid);
CTilde[k] = TActivation::Apply(SumC, atTanh);
O[k] = TActivation::Apply(SumO, atSigmoid);
C[k] = F[k] * PrevC[k] + I[k] * CTilde[k];
TanhC[k] = std::tanh(C[k]);
H[k] = O[k] * TanhC[k];
}
}
void Backward(const DArray& dH, const DArray& dC, const DArray& H, const DArray& C,
const DArray& F, const DArray& I, const DArray& CTilde, const DArray& O,
const DArray& TanhC, const DArray& PrevH, const DArray& PrevC,
const DArray& Input, double ClipVal, DArray& dInput, DArray& dPrevH, DArray& dPrevC) {
DArray Concat = ConcatArrays(Input, PrevH);
int ConcatSize = Concat.size();
DArray d0(FHiddenSize), dCTotal(FHiddenSize), dF(FHiddenSize), dI(FHiddenSize), dCTilde(FHiddenSize);
dInput.resize(FInputSize);
dPrevH.resize(FHiddenSize);
dPrevC.resize(FHiddenSize);
for (int k = 0; k < FInputSize; ++k) dInput[k] = 0;
for (int k = 0; k < FHiddenSize; ++k) {
dPrevH[k] = 0;
dPrevC[k] = 0;
}
for (int k = 0; k < FHiddenSize; ++k) {
d0[k] = ClipValue(dH[k] * TanhC[k] * TActivation::Derivative(O[k], atSigmoid), ClipVal);
dCTotal[k] = ClipValue(dH[k] * O[k] * (1 - TanhC[k] * TanhC[k]) + dC[k], ClipVal);
dF[k] = ClipValue(dCTotal[k] * PrevC[k] * TActivation::Derivative(F[k], atSigmoid), ClipVal);
dI[k] = ClipValue(dCTotal[k] * CTilde[k] * TActivation::Derivative(I[k], atSigmoid), ClipVal);
dCTilde[k] = ClipValue(dCTotal[k] * I[k] * TActivation::Derivative(CTilde[k], atTanh), ClipVal);
dPrevC[k] = dCTotal[k] * F[k];
}
for (int k = 0; k < FHiddenSize; ++k) {
for (int j = 0; j < ConcatSize; ++j) {
dWf[k][j] += dF[k] * Concat[j];
dWi[k][j] += dI[k] * Concat[j];
dWc[k][j] += dCTilde[k] * Concat[j];
dWo[k][j] += d0[k] * Concat[j];
if (j < FInputSize) {
dInput[j] += Wf[k][j] * dF[k] + Wi[k][j] * dI[k] +
Wc[k][j] * dCTilde[k] + Wo[k][j] * d0[k];
} else {
dPrevH[j - FInputSize] += Wf[k][j] * dF[k] + Wi[k][j] * dI[k] +
Wc[k][j] * dCTilde[k] + Wo[k][j] * d0[k];
}
}
dBf[k] += dF[k];
dBi[k] += dI[k];
dBc[k] += dCTilde[k];
dBo[k] += d0[k];
}
}
void ApplyGradients(double LR, double ClipVal) {
int ConcatSize = FInputSize + FHiddenSize;
for (int k = 0; k < FHiddenSize; ++k) {
for (int j = 0; j < ConcatSize; ++j) {
Wf[k][j] -= LR * ClipValue(dWf[k][j], ClipVal);
Wi[k][j] -= LR * ClipValue(dWi[k][j], ClipVal);
Wc[k][j] -= LR * ClipValue(dWc[k][j], ClipVal);
Wo[k][j] -= LR * ClipValue(dWo[k][j], ClipVal);
dWf[k][j] = 0;
dWi[k][j] = 0;
dWc[k][j] = 0;
dWo[k][j] = 0;
}
Bf[k] -= LR * ClipValue(dBf[k], ClipVal);
Bi[k] -= LR * ClipValue(dBi[k], ClipVal);
Bc[k] -= LR * ClipValue(dBc[k], ClipVal);
Bo[k] -= LR * ClipValue(dBo[k], ClipVal);
dBf[k] = 0;
dBi[k] = 0;
dBc[k] = 0;
dBo[k] = 0;
}
}
void ResetGradients() {
int ConcatSize = FInputSize + FHiddenSize;
ZeroMatrix(dWf, FHiddenSize, ConcatSize);
ZeroMatrix(dWi, FHiddenSize, ConcatSize);
ZeroMatrix(dWc, FHiddenSize, ConcatSize);
ZeroMatrix(dWo, FHiddenSize, ConcatSize);
ZeroArray(dBf, FHiddenSize);
ZeroArray(dBi, FHiddenSize);
ZeroArray(dBc, FHiddenSize);
ZeroArray(dBo, FHiddenSize);
}
int GetHiddenSize() const { return FHiddenSize; }
};
// ========== GRU Cell ==========
class TGRUCell {
private:
int FInputSize, FHiddenSize;
TActivationType FActivation;
public:
TDArray2D Wz, Wr, Wh;
DArray Bz, Br, Bh;
TDArray2D dWz, dWr, dWh;
DArray dBz, dBr, dBh;
TGRUCell(int InputSize, int HiddenSize, TActivationType Activation)
: FInputSize(InputSize), FHiddenSize(HiddenSize), FActivation(Activation) {
int ConcatSize = InputSize + HiddenSize;
double Scale = std::sqrt(2.0 / ConcatSize);
InitMatrix(Wz, HiddenSize, ConcatSize, Scale);
InitMatrix(Wr, HiddenSize, ConcatSize, Scale);
InitMatrix(Wh, HiddenSize, ConcatSize, Scale);
ZeroArray(Bz, HiddenSize);
ZeroArray(Br, HiddenSize);
ZeroArray(Bh, HiddenSize);
ZeroMatrix(dWz, HiddenSize, ConcatSize);
ZeroMatrix(dWr, HiddenSize, ConcatSize);
ZeroMatrix(dWh, HiddenSize, ConcatSize);
ZeroArray(dBz, HiddenSize);
ZeroArray(dBr, HiddenSize);
ZeroArray(dBh, HiddenSize);
}
void Forward(const DArray& Input, const DArray& PrevH, DArray& H,
DArray& Z, DArray& R, DArray& HTilde) {
DArray Concat = ConcatArrays(Input, PrevH);
H.resize(FHiddenSize);
Z.resize(FHiddenSize);
R.resize(FHiddenSize);
HTilde.resize(FHiddenSize);
for (int k = 0; k < FHiddenSize; ++k) {
double SumZ = Bz[k], SumR = Br[k];
for (size_t j = 0; j < Concat.size(); ++j) {
SumZ += Wz[k][j] * Concat[j];
SumR += Wr[k][j] * Concat[j];
}
Z[k] = TActivation::Apply(SumZ, atSigmoid);
R[k] = TActivation::Apply(SumR, atSigmoid);
}
DArray ConcatR(FInputSize + FHiddenSize);
for (int k = 0; k < FInputSize; ++k) {
ConcatR[k] = Input[k];
}
for (int k = 0; k < FHiddenSize; ++k) {
ConcatR[FInputSize + k] = R[k] * PrevH[k];
}
for (int k = 0; k < FHiddenSize; ++k) {
double SumH = Bh[k];
for (size_t j = 0; j < ConcatR.size(); ++j) {
SumH += Wh[k][j] * ConcatR[j];
}
HTilde[k] = TActivation::Apply(SumH, atTanh);
H[k] = (1 - Z[k]) * PrevH[k] + Z[k] * HTilde[k];
}
}
void Backward(const DArray& dH, const DArray& H, const DArray& Z, const DArray& R,
const DArray& HTilde, const DArray& PrevH, const DArray& Input,
double ClipVal, DArray& dInput, DArray& dPrevH) {
DArray Concat = ConcatArrays(Input, PrevH);
int ConcatSize = Concat.size();
DArray ConcatR(ConcatSize);
for (int k = 0; k < FInputSize; ++k) {
ConcatR[k] = Input[k];
}
for (int k = 0; k < FHiddenSize; ++k) {
ConcatR[FInputSize + k] = R[k] * PrevH[k];
}
DArray dZ(FHiddenSize), dR(FHiddenSize), dHTilde(FHiddenSize);
dInput.resize(FInputSize);
dPrevH.resize(FHiddenSize);
for (int k = 0; k < FInputSize; ++k) dInput[k] = 0;
for (int k = 0; k < FHiddenSize; ++k) dPrevH[k] = dH[k] * (1 - Z[k]);
for (int k = 0; k < FHiddenSize; ++k) {
dHTilde[k] = ClipValue(dH[k] * Z[k] * TActivation::Derivative(HTilde[k], atTanh), ClipVal);
dZ[k] = ClipValue(dH[k] * (HTilde[k] - PrevH[k]) * TActivation::Derivative(Z[k], atSigmoid), ClipVal);
}
for (int k = 0; k < FHiddenSize; ++k) {
for (int j = 0; j < ConcatSize; ++j) {
dWh[k][j] += dHTilde[k] * ConcatR[j];
if (j < FInputSize) {
dInput[j] += Wh[k][j] * dHTilde[k];
} else {
dR[j - FInputSize] = (dR[j - FInputSize] + Wh[k][j] * dHTilde[k] * PrevH[j - FInputSize]);
dPrevH[j - FInputSize] += Wh[k][j] * dHTilde[k] * R[j - FInputSize];
}
}
dBh[k] += dHTilde[k];
}
for (int k = 0; k < FHiddenSize; ++k) {
dR[k] = ClipValue(dR[k] * TActivation::Derivative(R[k], atSigmoid), ClipVal);
}
for (int k = 0; k < FHiddenSize; ++k) {
for (int j = 0; j < ConcatSize; ++j) {
dWz[k][j] += dZ[k] * Concat[j];
dWr[k][j] += dR[k] * Concat[j];
if (j < FInputSize) {
dInput[j] += Wz[k][j] * dZ[k] + Wr[k][j] * dR[k];
} else {
dPrevH[j - FInputSize] += Wz[k][j] * dZ[k] + Wr[k][j] * dR[k];
}
}
dBz[k] += dZ[k];
dBr[k] += dR[k];
}
}
void ApplyGradients(double LR, double ClipVal) {
int ConcatSize = FInputSize + FHiddenSize;
for (int k = 0; k < FHiddenSize; ++k) {
for (int j = 0; j < ConcatSize; ++j) {
Wz[k][j] -= LR * ClipValue(dWz[k][j], ClipVal);
Wr[k][j] -= LR * ClipValue(dWr[k][j], ClipVal);
Wh[k][j] -= LR * ClipValue(dWh[k][j], ClipVal);
dWz[k][j] = 0;
dWr[k][j] = 0;
dWh[k][j] = 0;
}
Bz[k] -= LR * ClipValue(dBz[k], ClipVal);
Br[k] -= LR * ClipValue(dBr[k], ClipVal);
Bh[k] -= LR * ClipValue(dBh[k], ClipVal);
dBz[k] = 0;
dBr[k] = 0;
dBh[k] = 0;
}
}
void ResetGradients() {
int ConcatSize = FInputSize + FHiddenSize;
ZeroMatrix(dWz, FHiddenSize, ConcatSize);
ZeroMatrix(dWr, FHiddenSize, ConcatSize);
ZeroMatrix(dWh, FHiddenSize, ConcatSize);
ZeroArray(dBz, FHiddenSize);
ZeroArray(dBr, FHiddenSize);
ZeroArray(dBh, FHiddenSize);
}
int GetHiddenSize() const { return FHiddenSize; }
};
// ========== Output Layer ==========
class TOutputLayer {
private:
int FInputSize, FOutputSize;
TActivationType FActivation;
public:
TDArray2D W;
DArray B;
TDArray2D dW;
DArray dB;
TOutputLayer(int InputSize, int OutputSize, TActivationType Activation)
: FInputSize(InputSize), FOutputSize(OutputSize), FActivation(Activation) {
double Scale = std::sqrt(2.0 / InputSize);
InitMatrix(W, OutputSize, InputSize, Scale);
ZeroArray(B, OutputSize);
ZeroMatrix(dW, OutputSize, InputSize);
ZeroArray(dB, OutputSize);
}
void Forward(const DArray& Input, DArray& Output, DArray& Pre) {
Pre.resize(FOutputSize);
Output.resize(FOutputSize);
for (int i = 0; i < FOutputSize; ++i) {
double Sum = B[i];
for (int j = 0; j < FInputSize; ++j) {
Sum += W[i][j] * Input[j];
}
Pre[i] = Sum;
}
if (FActivation == atLinear) {
for (int i = 0; i < FOutputSize; ++i) {
Output[i] = Pre[i];
}
} else {
for (int i = 0; i < FOutputSize; ++i) {
Output[i] = TActivation::Apply(Pre[i], FActivation);
}
}
}
void Backward(const DArray& d0ut, const DArray& Output, const DArray& Pre,
const DArray& Input, double ClipVal, DArray& dInput) {
DArray dPre(FOutputSize);
dInput.resize(FInputSize);
for (int j = 0; j < FInputSize; ++j) dInput[j] = 0;
for (int i = 0; i < FOutputSize; ++i) {
dPre[i] = ClipValue(d0ut[i] * TActivation::Derivative(Output[i], FActivation), ClipVal);
}
for (int i = 0; i < FOutputSize; ++i) {
for (int j = 0; j < FInputSize; ++j) {
dW[i][j] += dPre[i] * Input[j];
dInput[j] += W[i][j] * dPre[i];
}
dB[i] += dPre[i];
}
}
void ApplyGradients(double LR, double ClipVal) {
for (int i = 0; i < FOutputSize; ++i) {
for (int j = 0; j < FInputSize; ++j) {
W[i][j] -= LR * ClipValue(dW[i][j], ClipVal);
dW[i][j] = 0;
}
B[i] -= LR * ClipValue(dB[i], ClipVal);
dB[i] = 0;
}
}
void ResetGradients() {
ZeroMatrix(dW, FOutputSize, FInputSize);
ZeroArray(dB, FOutputSize);
}
};
// ========== Helper Functions ==========
std::string CellTypeToStr(TCellType ct) {
switch (ct) {
case ctSimpleRNN: return "simplernn";
case ctLSTM: return "lstm";
case ctGRU: return "gru";
default: return "simplernn";
}
}
std::string ActivationToStr(TActivationType act) {
switch (act) {
case atSigmoid: return "sigmoid";
case atTanh: return "tanh";
case atReLU: return "relu";
case atLinear: return "linear";
default: return "sigmoid";
}
}
std::string LossToStr(TLossType loss) {
switch (loss) {
case ltMSE: return "mse";
case ltCrossEntropy: return "crossentropy";
default: return "mse";
}
}
TCellType ParseCellType(const std::string& s) {
std::string lower = s;
std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
if (lower == "lstm") return ctLSTM;
if (lower == "gru") return ctGRU;
return ctSimpleRNN;
}
TActivationType ParseActivation(const std::string& s) {
std::string lower = s;
std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
if (lower == "tanh") return atTanh;
if (lower == "relu") return atReLU;
if (lower == "linear") return atLinear;
return atSigmoid;
}
TLossType ParseLoss(const std::string& s) {
std::string lower = s;
std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
if (lower == "crossentropy") return ltCrossEntropy;
return ltMSE;
}
void ParseIntArrayHelper(const std::string& s, TIntArray& result) {
result.clear();
std::stringstream ss(s);
std::string token;
while (std::getline(ss, token, ',')) {
token.erase(0, token.find_first_not_of(" \t\r\n"));
token.erase(token.find_last_not_of(" \t\r\n") + 1);
result.push_back(std::stoi(token));
}
}
void ParseDoubleArrayHelper(const std::string& s, DArray& result) {
result.clear();
std::stringstream ss(s);
std::string token;
while (std::getline(ss, token, ',')) {
token.erase(0, token.find_first_not_of(" \t\r\n"));
token.erase(token.find_last_not_of(" \t\r\n") + 1);
result.push_back(std::stod(token));
}
}
void LoadDataFromCSV(const std::string& Filename, TDArray2D& Inputs, TDArray2D& Targets) {
Inputs.clear();
Targets.clear();
std::ifstream file(Filename);
std::string line;
while (std::getline(file, line)) {
if (line.empty()) continue;
DArray InputsArr, TargetsArr;
std::stringstream ss(line);
std::string token;
std::vector<double> tokens;
while (std::getline(ss, token, ',')) {
token.erase(0, token.find_first_not_of(" \t\r\n"));
token.erase(token.find_last_not_of(" \t\r\n") + 1);
tokens.push_back(std::stod(token));
}
if (tokens.size() >= 2) {
size_t splitPoint = tokens.size() / 2;
InputsArr.assign(tokens.begin(), tokens.begin() + splitPoint);
TargetsArr.assign(tokens.begin() + splitPoint, tokens.end());
Inputs.push_back(InputsArr);
Targets.push_back(TargetsArr);
}
}
file.close();
}
void SplitData(const TDArray2D& Inputs, const TDArray2D& Targets, double ValSplit, TDataSplit& Split) {
size_t N = Inputs.size();
size_t ValCount = static_cast<size_t>(N * ValSplit);
size_t TrainCount = N - ValCount;
TIntArray Indices(N);
for (size_t i = 0; i < N; ++i) {
Indices[i] = i;
}
for (int i = N - 1; i > 0; --i) {
int j = rand() % (i + 1);
std::swap(Indices[i], Indices[j]);
}
Split.TrainInputs.resize(TrainCount);
Split.TrainTargets.resize(TrainCount);
Split.ValInputs.resize(ValCount);
Split.ValTargets.resize(ValCount);
for (size_t i = 0; i < TrainCount; ++i) {
Split.TrainInputs[i] = Inputs[Indices[i]];
Split.TrainTargets[i] = Targets[Indices[i]];
}
for (size_t i = 0; i < ValCount; ++i) {
Split.ValInputs[i] = Inputs[Indices[TrainCount + i]];
Split.ValTargets[i] = Targets[Indices[TrainCount + i]];
}
}
static std::string ExtractJSONValue(const std::string& json, const std::string& key) {
std::string searchKey = "\"" + key + "\"";
size_t keyPos = json.find(searchKey);
if (keyPos == std::string::npos) return "";
size_t colonPos = json.find(':', keyPos);
if (colonPos == std::string::npos) return "";
size_t startPos = colonPos + 1;
while (startPos < json.length() && (json[startPos] == ' ' || json[startPos] == '\t'
|| json[startPos] == '\n' || json[startPos] == '\r')) {
++startPos;
}
if (startPos < json.length() && json[startPos] == '"') {
size_t quotePos1 = startPos;
size_t quotePos2 = json.find('"', quotePos1 + 1);
if (quotePos2 != std::string::npos) {
return json.substr(quotePos1 + 1, quotePos2 - quotePos1 - 1);
}
return "";
}
size_t endPos = json.find(',', startPos);
if (endPos == std::string::npos) endPos = json.find('}', startPos);
if (endPos == std::string::npos) endPos = json.find(']', startPos);
std::string result = json.substr(startPos, endPos - startPos);
size_t end = result.find_last_not_of(" \t\n\r");
if (end != std::string::npos) {
result = result.substr(0, end + 1);
}
return result;
}
// ========== Main RNN Class ==========
class TRNN {
private:
int FInputSize, FOutputSize;
TIntArray FHiddenSizes;
TCellType FCellType;
TActivationType FActivation, FOutputActivation;
TLossType FLossType;
double FLearningRate, FGradientClip;
int FBPTTSteps;
std::vector<TSimpleRNNCell*> FSimpleCells;
std::vector<TLSTMCell*> FLSTMCells;
std::vector<TGRUCell*> FGRUCells;
TOutputLayer* FOutputLayer;
public:
TRNN(int InputSize, const TIntArray& HiddenSizes, int OutputSize, TCellType CellType,
TActivationType Activation, TActivationType OutputActivation, TLossType LossType,
double LearningRate, double GradientClip, int BPTTSteps)
: FInputSize(InputSize), FOutputSize(OutputSize), FCellType(CellType),
FActivation(Activation), FOutputActivation(OutputActivation),
FLossType(LossType), FLearningRate(LearningRate), FGradientClip(GradientClip),
FBPTTSteps(BPTTSteps) {
FHiddenSizes = HiddenSizes;
int PrevSize = InputSize;
switch (CellType) {
case ctSimpleRNN:
for (size_t i = 0; i < HiddenSizes.size(); ++i) {
FSimpleCells.push_back(new TSimpleRNNCell(PrevSize, HiddenSizes[i], Activation));
PrevSize = HiddenSizes[i];
}
break;
case ctLSTM:
for (size_t i = 0; i < HiddenSizes.size(); ++i) {
FLSTMCells.push_back(new TLSTMCell(PrevSize, HiddenSizes[i], Activation));
PrevSize = HiddenSizes[i];
}
break;
case ctGRU:
for (size_t i = 0; i < HiddenSizes.size(); ++i) {
FGRUCells.push_back(new TGRUCell(PrevSize, HiddenSizes[i], Activation));
PrevSize = HiddenSizes[i];
}
break;
}
FOutputLayer = new TOutputLayer(PrevSize, OutputSize, OutputActivation);
}
~TRNN() {
switch (FCellType) {
case ctSimpleRNN:
for (auto cell : FSimpleCells) delete cell;
break;
case ctLSTM:
for (auto cell : FLSTMCells) delete cell;
break;
case ctGRU:
for (auto cell : FGRUCells) delete cell;
break;
}
delete FOutputLayer;
}
TDArray3D InitHiddenStates() {
TDArray3D Result(FHiddenSizes.size());
for (size_t i = 0; i < FHiddenSizes.size(); ++i) {
Result[i].resize(2);
ZeroArray(Result[i][0], FHiddenSizes[i]);
ZeroArray(Result[i][1], FHiddenSizes[i]);
}
return Result;
}
TDArray2D ForwardSequence(const TDArray2D& Inputs, std::vector<TTimeStepCache>& Caches,
TDArray3D& States) {
TDArray2D Result(Inputs.size());
TDArray3D NewStates = InitHiddenStates();
for (size_t t = 0; t < Inputs.size(); ++t) {
DArray X = Inputs[t];
Caches[t].Input = X;
Caches[t].LayerInputs.resize(FHiddenSizes.size() + 1);
for (size_t layer = 0; layer < FHiddenSizes.size(); ++layer) {
Caches[t].LayerInputs[layer] = X;
DArray H, C, PreH, F, I, CTilde, O, TanhC, Z, R, HTilde;
switch (FCellType) {
case ctSimpleRNN:
FSimpleCells[layer]->Forward(X, States[layer][0], H, PreH);
NewStates[layer][0] = H;
Caches[t].H = H;
Caches[t].PreH = PreH;
break;
case ctLSTM:
FLSTMCells[layer]->Forward(X, States[layer][0], States[layer][1], H, C, F, I, CTilde, O, TanhC);
NewStates[layer][0] = H;
NewStates[layer][1] = C;
Caches[t].H = H;
Caches[t].C = C;
Caches[t].F = F;
Caches[t].I = I;
Caches[t].CTilde = CTilde;
Caches[t].O = O;
Caches[t].TanhC = TanhC;
break;
case ctGRU:
FGRUCells[layer]->Forward(X, States[layer][0], H, Z, R, HTilde);
NewStates[layer][0] = H;
Caches[t].H = H;
Caches[t].Z = Z;
Caches[t].R = R;
Caches[t].HTilde = HTilde;
break;
}
X = H;
}
Caches[t].LayerInputs[FHiddenSizes.size()] = X;
DArray OutVal, OutPre;
FOutputLayer->Forward(X, OutVal, OutPre);
Caches[t].OutVal = OutVal;
Caches[t].OutPre = OutPre;