-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlayer.zig
More file actions
1705 lines (1424 loc) · 69 KB
/
Copy pathlayer.zig
File metadata and controls
1705 lines (1424 loc) · 69 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
const std = @import("std");
const matrix_mod = @import("matrix.zig");
const Matrix = matrix_mod.Matrix;
const backend_mod = @import("backend.zig");
const BackendMatrix = backend_mod.Matrix;
const Activation = @import("activation.zig").Activation;
const Network = @import("network.zig").Network;
const testing = std.testing;
/// Generates one standard-normal sample with a Box-Muller transform. Using
/// `1 - U` keeps the logarithm input in `(0, 1]`, including when the random
/// source produces exactly zero.
fn standardNormal(random: std.Random) f64 {
const radius_sample = 1.0 - random.float(f64);
const angle_sample = random.float(f64);
return @sqrt(-2.0 * @log(radius_sample)) * @cos(2.0 * std.math.pi * angle_sample);
}
fn addBackendBias(weighted_sum: *const BackendMatrix, bias: *const BackendMatrix, allocator: std.mem.Allocator) !*BackendMatrix {
return weighted_sum.addRowBias(bias, allocator);
}
fn replaceCpuMatrixFromBackend(target: *Matrix, source: *const BackendMatrix, allocator: std.mem.Allocator) !void {
const replacement = try source.toMatrix(allocator);
target.deinit();
target.* = replacement;
}
fn softmaxWeightedGradientBackend(output_gradient: *const BackendMatrix, output: *const BackendMatrix, allocator: std.mem.Allocator) !*BackendMatrix {
if (output_gradient.rows != output.rows or output_gradient.cols != output.cols) {
return error.DimensionMismatch;
}
const result = try BackendMatrix.init(output_gradient.backend, allocator, output_gradient.rows, output_gradient.cols);
errdefer result.deinit();
for (0..output_gradient.rows) |row| {
var weighted_dot: f64 = 0.0;
for (0..output_gradient.cols) |col| {
weighted_dot += output_gradient.get(row, col) * output.get(row, col);
}
for (0..output_gradient.cols) |col| {
const y = output.get(row, col);
const g = output_gradient.get(row, col);
result.set(row, col, y * (g - weighted_dot));
}
}
return result;
}
/// Neural network layer implementation supporting both standard and gated architectures
/// This module provides two types of layers:
/// 1. Layer: Standard neural network layer with weights, biases, and activation function
/// 2. GatedLayer: Advanced layer with gating mechanism (GLU/SwiGLU) for controlled information flow
///
/// Mathematical foundations:
/// - Standard layer: output = activation(W·x + b)
/// - Gated layer: output = (W₁·x + b₁) ⊗ activation(W₂·x + b₂)
/// Where:
/// - W, W₁, W₂ are weight matrices
/// - b, b₁, b₂ are bias vectors
/// - x is the input vector
/// - ⊗ is element-wise multiplication
/// Standard neural network layer with full connectivity
/// Implements forward and backward propagation for training
/// Maintains state for backpropagation by storing intermediate values
pub const Layer = struct {
weights: Matrix, // Weight matrix W
bias: Matrix, // Bias vector b
activation_fn: *const fn (f64) f64, // Activation function σ(x)
activation_derivative_fn: *const fn (f64) f64, // Derivative σ'(x)
allocator: std.mem.Allocator,
// Cached values for backpropagation
last_input: ?Matrix, // Input x
last_output: ?Matrix, // Output y = σ(W·x + b)
last_weighted_sum: ?Matrix, // Pre-activation z = W·x + b
last_backend_input: ?*BackendMatrix,
last_backend_output: ?*BackendMatrix,
last_backend_weighted_sum: ?*BackendMatrix,
last_backend_weights: ?*BackendMatrix,
last_backend_bias: ?*BackendMatrix,
/// Initializes a new fully connected layer
/// Mathematical initialization:
/// - W ∈ ℝ^(input_size × output_size), initialized uniformly in [-0.5, 0.5]
/// - b ∈ ℝ^output_size, initialized uniformly in [-0.5, 0.5]
///
/// Parameters:
/// - allocator: Memory allocator for matrices
/// - input_size: Number of input features
/// - output_size: Number of neurons in this layer
/// - activation_fn: Activation function σ(x)
/// - activation_derivative_fn: Derivative of activation function σ'(x)
///
/// Time complexity: O(input_size * output_size)
/// Memory complexity: O(input_size * output_size)
pub fn init(
allocator: std.mem.Allocator,
input_size: usize,
output_size: usize,
activation_fn: *const fn (f64) f64,
activation_derivative_fn: *const fn (f64) f64,
) !Layer {
var prng = std.Random.DefaultPrng.init(matrix_mod.randomSeed());
return initWithRandom(
allocator,
input_size,
output_size,
activation_fn,
activation_derivative_fn,
prng.random(),
);
}
/// Initializes a fully connected layer from a caller-provided random
/// stream so model construction can be reproduced exactly.
pub fn initWithRandom(
allocator: std.mem.Allocator,
input_size: usize,
output_size: usize,
activation_fn: *const fn (f64) f64,
activation_derivative_fn: *const fn (f64) f64,
random: std.Random,
) !Layer {
if (input_size == 0 or output_size == 0) {
return error.InvalidLayerDimensions;
}
var weights = try Matrix.init(allocator, input_size, output_size);
errdefer weights.deinit();
var bias = try Matrix.init(allocator, 1, output_size);
errdefer bias.deinit();
// Xavier/Glorot initialization with adjustments for activation function
var scale: f64 = undefined;
if (activation_fn == Activation.relu) {
scale = @sqrt(2.0 / @as(f64, @floatFromInt(input_size)));
} else if (activation_fn == Activation.softmax) {
// For softmax, use a smaller scale to prevent initial outputs from being too extreme
scale = @sqrt(0.1 / @as(f64, @floatFromInt(input_size)));
} else {
scale = @sqrt(1.0 / @as(f64, @floatFromInt(input_size)));
}
// Initialize weights with scaled normal distribution
for (0..input_size) |i| {
for (0..output_size) |j| {
try weights.set(i, j, standardNormal(random) * scale);
}
}
// Initialize biases
if (activation_fn == Activation.softmax) {
// For softmax, initialize biases to zero to maintain initial class probabilities close to uniform
bias.fill(0.0);
} else {
// For other activations, small random values
bias.randomizeWith(random, -0.1, 0.1);
}
return Layer{
.weights = weights,
.bias = bias,
.activation_fn = activation_fn,
.activation_derivative_fn = activation_derivative_fn,
.allocator = allocator,
.last_input = null,
.last_output = null,
.last_weighted_sum = null,
.last_backend_input = null,
.last_backend_output = null,
.last_backend_weighted_sum = null,
.last_backend_weights = null,
.last_backend_bias = null,
};
}
fn clearBackendCaches(self: *Layer) void {
if (self.last_backend_input) |input| {
input.deinit();
self.last_backend_input = null;
}
if (self.last_backend_output) |output| {
output.deinit();
self.last_backend_output = null;
}
if (self.last_backend_weighted_sum) |weighted_sum| {
weighted_sum.deinit();
self.last_backend_weighted_sum = null;
}
if (self.last_backend_weights) |weights| {
weights.deinit();
self.last_backend_weights = null;
}
if (self.last_backend_bias) |bias| {
bias.deinit();
self.last_backend_bias = null;
}
}
/// Frees all allocated memory
/// Includes weights, biases, and cached matrices for backpropagation
/// Time complexity: O(1)
pub fn deinit(self: Layer) void {
self.weights.deinit();
self.bias.deinit();
// Clean up stored matrices if they exist
if (self.last_input) |input| {
input.deinit();
}
if (self.last_output) |output| {
output.deinit();
}
if (self.last_weighted_sum) |weighted_sum| {
weighted_sum.deinit();
}
if (self.last_backend_input) |input| {
input.deinit();
}
if (self.last_backend_output) |output| {
output.deinit();
}
if (self.last_backend_weighted_sum) |weighted_sum| {
weighted_sum.deinit();
}
if (self.last_backend_weights) |weights| {
weights.deinit();
}
if (self.last_backend_bias) |bias| {
bias.deinit();
}
}
/// Performs forward propagation through the layer
/// Mathematical formula: y = σ(W·x + b)
/// Where:
/// - x is the input matrix (batch_size × input_size)
/// - W is the weight matrix (input_size × output_size)
/// - b is the bias vector (1 × output_size)
/// - σ is the activation function
///
/// Parameters:
/// - input: Input matrix x with shape (batch_size × input_size)
/// Returns: Output matrix y with shape (batch_size × output_size)
///
/// Time complexity: O(batch_size * input_size * output_size)
/// Memory complexity: O(batch_size * output_size)
pub fn forward(self: *Layer, input: Matrix) !Matrix {
// Build the next set of training caches before replacing the current
// set. If any allocation fails, the existing caches remain valid.
var next_input = try Matrix.copy(input, self.allocator);
errdefer next_input.deinit();
// Calculate weighted sum z = W·x
var weighted_sum = try input.dotProduct(self.weights, self.allocator);
defer weighted_sum.deinit();
// Add bias to each row (broadcast bias to match batch size)
var biased = try Matrix.init(self.allocator, weighted_sum.rows, weighted_sum.cols);
defer biased.deinit();
for (0..weighted_sum.rows) |i| {
for (0..weighted_sum.cols) |j| {
try biased.set(i, j, (try weighted_sum.get(i, j)) + (try self.bias.get(0, j)));
}
}
var next_weighted_sum = try Matrix.copy(biased, self.allocator);
errdefer next_weighted_sum.deinit();
// Apply activation function y = σ(z)
var output = if (self.activation_fn == Activation.softmax)
// For softmax, we need to apply it row-wise
try Activation.applySoftmax(biased, self.allocator)
else
try Activation.apply(biased, self.activation_fn, self.allocator);
errdefer output.deinit();
var next_output = try Matrix.copy(output, self.allocator);
errdefer next_output.deinit();
if (self.last_input) |last_input| last_input.deinit();
if (self.last_weighted_sum) |last_weighted_sum| last_weighted_sum.deinit();
if (self.last_output) |last_output| last_output.deinit();
self.last_input = next_input;
self.last_weighted_sum = next_weighted_sum;
self.last_output = next_output;
return output;
}
/// Performs backend-aware inference without updating training caches.
pub fn forwardBackend(self: *Layer, input: *const BackendMatrix) !*BackendMatrix {
if (input.cols != self.getInputSize()) {
return error.InvalidInputDimensions;
}
const backend_instance = input.backend;
const weights = try BackendMatrix.fromMatrix(backend_instance, self.weights, self.allocator);
defer weights.deinit();
const bias = try BackendMatrix.fromMatrix(backend_instance, self.bias, self.allocator);
defer bias.deinit();
const weighted_sum = try input.dotProduct(weights, self.allocator);
defer weighted_sum.deinit();
const biased = try addBackendBias(weighted_sum, bias, self.allocator);
defer biased.deinit();
if (self.activation_fn == Activation.softmax) {
return biased.applySoftmax(self.allocator);
}
return biased.applyActivation(self.activation_fn, self.allocator);
}
/// Performs backend-aware forward propagation and stores backend caches for training.
pub fn forwardBackendTrain(self: *Layer, input: *const BackendMatrix) !*BackendMatrix {
if (input.cols != self.getInputSize()) {
return error.InvalidInputDimensions;
}
self.clearBackendCaches();
errdefer self.clearBackendCaches();
const backend_instance = input.backend;
self.last_backend_input = try input.copy(self.allocator);
self.last_backend_weights = try BackendMatrix.fromMatrix(backend_instance, self.weights, self.allocator);
self.last_backend_bias = try BackendMatrix.fromMatrix(backend_instance, self.bias, self.allocator);
const weighted_sum = try input.dotProduct(self.last_backend_weights.?, self.allocator);
defer weighted_sum.deinit();
const biased = try addBackendBias(weighted_sum, self.last_backend_bias.?, self.allocator);
defer biased.deinit();
self.last_backend_weighted_sum = try biased.copy(self.allocator);
const output = if (self.activation_fn == Activation.softmax)
try biased.applySoftmax(self.allocator)
else
try biased.applyActivation(self.activation_fn, self.allocator);
errdefer output.deinit();
self.last_backend_output = try output.copy(self.allocator);
return output;
}
/// Performs backpropagation through the layer
/// Implements gradient descent update step
/// Mathematical formulas:
/// 1. δz = δy ⊗ σ'(z) [element-wise]
/// 2. δW = xᵀ·δz
/// 3. δb = sum(δz, axis=0)
/// 4. δx = δz·Wᵀ
/// 5. W = W - η·δW
/// 6. b = b - η·δb
/// Where:
/// - δy is the output gradient
/// - z is the pre-activation (weighted sum)
/// - σ' is the activation derivative
/// - η is the learning rate
///
/// Parameters:
/// - output_gradient: Gradient δy with respect to layer output
/// - learning_rate: Learning rate η for gradient descent
/// Returns: Input gradient δx for backpropagating to previous layer
///
/// Time complexity: O(batch_size * input_size * output_size)
/// Memory complexity: O(batch_size * max(input_size, output_size))
pub fn backward(self: *Layer, output_gradient: Matrix, learning_rate: f64) !Matrix {
if (self.last_input == null or self.last_output == null or self.last_weighted_sum == null) {
return error.NoForwardPassPerformed;
}
var weighted_sum_gradient: Matrix = undefined;
if (self.activation_fn == Activation.softmax) {
// For softmax, multiply the incoming dL/dy by the full row-wise
// Jacobian: dL/dz_j = y_j * (g_j - sum_k(g_k * y_k)).
const output = self.last_output.?;
weighted_sum_gradient = try Matrix.init(self.allocator, output_gradient.rows, output_gradient.cols);
errdefer weighted_sum_gradient.deinit();
for (0..output_gradient.rows) |i| {
var weighted_dot: f64 = 0.0;
for (0..output_gradient.cols) |j| {
weighted_dot += (try output_gradient.get(i, j)) * (try output.get(i, j));
}
for (0..output_gradient.cols) |j| {
const y = try output.get(i, j);
const g = try output_gradient.get(i, j);
try weighted_sum_gradient.set(i, j, y * (g - weighted_dot));
}
}
} else {
// Calculate activation derivative σ'(z)
var activation_derivative = try Matrix.init(self.allocator, self.last_weighted_sum.?.rows, self.last_weighted_sum.?.cols);
defer activation_derivative.deinit();
for (0..self.last_weighted_sum.?.rows) |i| {
for (0..self.last_weighted_sum.?.cols) |j| {
const value = try self.last_weighted_sum.?.get(i, j);
try activation_derivative.set(i, j, self.activation_derivative_fn(value));
}
}
// Calculate δz = δy ⊗ σ'(z)
weighted_sum_gradient = try output_gradient.elementWiseMultiply(activation_derivative, self.allocator);
}
// Calculate δW = xᵀ·δz
var transposed_input = try self.last_input.?.transpose(self.allocator);
defer transposed_input.deinit();
var weights_gradient = try transposed_input.dotProduct(weighted_sum_gradient, self.allocator);
defer weights_gradient.deinit();
// Calculate δb = sum(δz, axis=0)
var bias_gradient = try weighted_sum_gradient.sumRows(self.allocator);
defer bias_gradient.deinit();
// Calculate δx = δz·Wᵀ
var transposed_weights = try self.weights.transpose(self.allocator);
defer transposed_weights.deinit();
const input_gradient = try weighted_sum_gradient.dotProduct(transposed_weights, self.allocator);
defer weighted_sum_gradient.deinit();
// Update weights: W = W - η·δW
var scaled_weights_gradient = try weights_gradient.scale(learning_rate, self.allocator);
defer scaled_weights_gradient.deinit();
const new_weights = try self.weights.subtract(scaled_weights_gradient, self.allocator);
self.weights.deinit();
self.weights = new_weights;
// Update bias: b = b - η·δb
var scaled_bias_gradient = try bias_gradient.scale(learning_rate, self.allocator);
defer scaled_bias_gradient.deinit();
const new_bias = try self.bias.subtract(scaled_bias_gradient, self.allocator);
self.bias.deinit();
self.bias = new_bias;
return input_gradient;
}
/// Performs backend-aware backpropagation and writes updated parameters back to CPU storage.
pub fn backwardBackend(self: *Layer, output_gradient: *const BackendMatrix, learning_rate: f64) !*BackendMatrix {
if (self.last_backend_input == null or self.last_backend_output == null or self.last_backend_weighted_sum == null) {
return error.NoForwardPassPerformed;
}
defer self.clearBackendCaches();
const weighted_sum_gradient = if (self.activation_fn == Activation.softmax) blk: {
break :blk try softmaxWeightedGradientBackend(output_gradient, self.last_backend_output.?, self.allocator);
} else blk: {
const activation_derivative = try self.last_backend_weighted_sum.?.applyActivation(self.activation_derivative_fn, self.allocator);
defer activation_derivative.deinit();
break :blk try output_gradient.elementWiseMultiply(activation_derivative, self.allocator);
};
defer weighted_sum_gradient.deinit();
const weights = self.last_backend_weights.?;
const bias = self.last_backend_bias.?;
const transposed_input = try self.last_backend_input.?.transpose(self.allocator);
defer transposed_input.deinit();
const weights_gradient = try transposed_input.dotProduct(weighted_sum_gradient, self.allocator);
defer weights_gradient.deinit();
const bias_gradient = try weighted_sum_gradient.sumRows(self.allocator);
defer bias_gradient.deinit();
const transposed_weights = try weights.transpose(self.allocator);
defer transposed_weights.deinit();
const input_gradient = try weighted_sum_gradient.dotProduct(transposed_weights, self.allocator);
errdefer input_gradient.deinit();
const scaled_weights_gradient = try weights_gradient.scale(learning_rate, self.allocator);
defer scaled_weights_gradient.deinit();
const new_weights = try weights.subtract(scaled_weights_gradient, self.allocator);
defer new_weights.deinit();
try replaceCpuMatrixFromBackend(&self.weights, new_weights, self.allocator);
const scaled_bias_gradient = try bias_gradient.scale(learning_rate, self.allocator);
defer scaled_bias_gradient.deinit();
const new_bias = try bias.subtract(scaled_bias_gradient, self.allocator);
defer new_bias.deinit();
try replaceCpuMatrixFromBackend(&self.bias, new_bias, self.allocator);
return input_gradient;
}
/// Returns the number of input features the layer accepts
pub fn getInputSize(self: Layer) usize {
return self.weights.rows;
}
/// Returns the number of neurons (outputs) in the layer
pub fn getOutputSize(self: Layer) usize {
return self.weights.cols;
}
};
/// Advanced neural network layer with gating mechanism
/// Implements either GLU (Gated Linear Unit) or SwiGLU variant
/// GLU and SwiGLU are particularly effective in transformer architectures
/// Mathematical formula:
/// - GLU: output = (W₁·x + b₁) ⊗ sigmoid(W₂·x + b₂)
/// - SwiGLU: output = (W₁·x + b₁) ⊗ swish(W₂·x + b₂)
pub const GatedLayer = struct {
// Linear transformation parameters
linear_weights: Matrix, // W₁
linear_bias: Matrix, // b₁
// Gating transformation parameters
gate_weights: Matrix, // W₂
gate_bias: Matrix, // b₂
// Configuration
use_swiglu: bool, // Whether to use SwiGLU (true) or GLU (false)
allocator: std.mem.Allocator,
// Cached values for backpropagation
last_input: ?Matrix, // Input x
last_linear_output: ?Matrix, // Linear part: W₁·x + b₁
last_gate_output: ?Matrix, // Gate part: W₂·x + b₂
last_output: ?Matrix, // Final output
last_backend_input: ?*BackendMatrix,
last_backend_linear_output: ?*BackendMatrix,
last_backend_gate_output: ?*BackendMatrix,
last_backend_output: ?*BackendMatrix,
last_backend_linear_weights: ?*BackendMatrix,
last_backend_linear_bias: ?*BackendMatrix,
last_backend_gate_weights: ?*BackendMatrix,
last_backend_gate_bias: ?*BackendMatrix,
/// Initializes a new gated layer (GLU or SwiGLU)
/// Mathematical initialization:
/// - W₁, W₂ ∈ ℝ^(input_size × output_size), initialized uniformly in [-0.5, 0.5]
/// - b₁, b₂ ∈ ℝ^output_size, initialized uniformly in [-0.5, 0.5]
///
/// Parameters:
/// - allocator: Memory allocator for matrices
/// - input_size: Number of input features
/// - output_size: Number of neurons in this layer
/// - use_swiglu: Whether to use SwiGLU (true) or GLU (false)
///
/// Time complexity: O(input_size * output_size)
/// Memory complexity: O(input_size * output_size)
pub fn init(
allocator: std.mem.Allocator,
input_size: usize,
output_size: usize,
use_swiglu: bool,
) !GatedLayer {
if (input_size == 0 or output_size == 0) {
return error.InvalidLayerDimensions;
}
// Initialize two sets of weights and biases
var linear_weights = try Matrix.init(allocator, input_size, output_size);
errdefer linear_weights.deinit();
var linear_bias = try Matrix.init(allocator, 1, output_size);
errdefer linear_bias.deinit();
var gate_weights = try Matrix.init(allocator, input_size, output_size);
errdefer gate_weights.deinit();
var gate_bias = try Matrix.init(allocator, 1, output_size);
errdefer gate_bias.deinit();
// Xavier/Glorot initialization for both linear and gate weights
const fan_sum = @as(f64, @floatFromInt(input_size)) + @as(f64, @floatFromInt(output_size));
const scale = @sqrt(2.0 / fan_sum);
// Initialize weights with scaled normal distribution
var prng = std.Random.DefaultPrng.init(matrix_mod.randomSeed());
const rand = prng.random();
// Initialize linear weights
for (0..input_size) |i| {
for (0..output_size) |j| {
try linear_weights.set(i, j, standardNormal(rand) * scale);
}
}
// Initialize gate weights
for (0..input_size) |i| {
for (0..output_size) |j| {
try gate_weights.set(i, j, standardNormal(rand) * scale);
}
}
// Initialize biases to small values close to zero
linear_bias.randomize(-0.1, 0.1);
gate_bias.randomize(-0.1, 0.1);
return GatedLayer{
.linear_weights = linear_weights,
.linear_bias = linear_bias,
.gate_weights = gate_weights,
.gate_bias = gate_bias,
.use_swiglu = use_swiglu,
.allocator = allocator,
.last_input = null,
.last_linear_output = null,
.last_gate_output = null,
.last_output = null,
.last_backend_input = null,
.last_backend_linear_output = null,
.last_backend_gate_output = null,
.last_backend_output = null,
.last_backend_linear_weights = null,
.last_backend_linear_bias = null,
.last_backend_gate_weights = null,
.last_backend_gate_bias = null,
};
}
fn clearBackendCaches(self: *GatedLayer) void {
if (self.last_backend_input) |input| {
input.deinit();
self.last_backend_input = null;
}
if (self.last_backend_linear_output) |output| {
output.deinit();
self.last_backend_linear_output = null;
}
if (self.last_backend_gate_output) |output| {
output.deinit();
self.last_backend_gate_output = null;
}
if (self.last_backend_output) |output| {
output.deinit();
self.last_backend_output = null;
}
if (self.last_backend_linear_weights) |weights| {
weights.deinit();
self.last_backend_linear_weights = null;
}
if (self.last_backend_linear_bias) |bias| {
bias.deinit();
self.last_backend_linear_bias = null;
}
if (self.last_backend_gate_weights) |weights| {
weights.deinit();
self.last_backend_gate_weights = null;
}
if (self.last_backend_gate_bias) |bias| {
bias.deinit();
self.last_backend_gate_bias = null;
}
}
/// Frees all allocated memory
/// Includes both sets of weights and biases, and cached matrices
/// Time complexity: O(1)
pub fn deinit(self: GatedLayer) void {
self.linear_weights.deinit();
self.linear_bias.deinit();
self.gate_weights.deinit();
self.gate_bias.deinit();
// Clean up stored matrices
if (self.last_input) |input| {
input.deinit();
}
if (self.last_linear_output) |output| {
output.deinit();
}
if (self.last_gate_output) |output| {
output.deinit();
}
if (self.last_output) |output| {
output.deinit();
}
if (self.last_backend_input) |input| {
input.deinit();
}
if (self.last_backend_linear_output) |output| {
output.deinit();
}
if (self.last_backend_gate_output) |output| {
output.deinit();
}
if (self.last_backend_output) |output| {
output.deinit();
}
if (self.last_backend_linear_weights) |weights| {
weights.deinit();
}
if (self.last_backend_linear_bias) |bias| {
bias.deinit();
}
if (self.last_backend_gate_weights) |weights| {
weights.deinit();
}
if (self.last_backend_gate_bias) |bias| {
bias.deinit();
}
}
/// Forward propagation through the gated layer
pub fn forward(self: *GatedLayer, input: Matrix) !Matrix {
// Build a complete replacement cache set before releasing the current
// one, so an allocation failure cannot leave dangling cache entries.
var next_input = try Matrix.copy(input, self.allocator);
errdefer next_input.deinit();
// Calculate linear part: input * linear_weights + linear_bias
var linear_weighted_sum = try input.dotProduct(self.linear_weights, self.allocator);
defer linear_weighted_sum.deinit();
// Add linear bias to each row (broadcast bias to match batch size)
var linear_biased = try Matrix.init(self.allocator, linear_weighted_sum.rows, linear_weighted_sum.cols);
defer linear_biased.deinit();
for (0..linear_weighted_sum.rows) |i| {
for (0..linear_weighted_sum.cols) |j| {
try linear_biased.set(i, j, (try linear_weighted_sum.get(i, j)) + (try self.linear_bias.get(0, j)));
}
}
var next_linear_output = try Matrix.copy(linear_biased, self.allocator);
errdefer next_linear_output.deinit();
// Calculate gating part: input * gate_weights + gate_bias
var gate_weighted_sum = try input.dotProduct(self.gate_weights, self.allocator);
defer gate_weighted_sum.deinit();
// Add gate bias to each row (broadcast bias to match batch size)
var gate_biased = try Matrix.init(self.allocator, gate_weighted_sum.rows, gate_weighted_sum.cols);
defer gate_biased.deinit();
for (0..gate_weighted_sum.rows) |i| {
for (0..gate_weighted_sum.cols) |j| {
try gate_biased.set(i, j, (try gate_weighted_sum.get(i, j)) + (try self.gate_bias.get(0, j)));
}
}
var next_gate_output = try Matrix.copy(gate_biased, self.allocator);
errdefer next_gate_output.deinit();
// Apply GLU or SwiGLU
var output = if (self.use_swiglu)
try Activation.applySwiGLU(linear_biased, gate_biased, self.allocator)
else
try Activation.applyGLU(linear_biased, gate_biased, self.allocator);
errdefer output.deinit();
var next_output = try Matrix.copy(output, self.allocator);
errdefer next_output.deinit();
if (self.last_input) |last_input| last_input.deinit();
if (self.last_linear_output) |last_linear_output| last_linear_output.deinit();
if (self.last_gate_output) |last_gate_output| last_gate_output.deinit();
if (self.last_output) |last_output| last_output.deinit();
self.last_input = next_input;
self.last_linear_output = next_linear_output;
self.last_gate_output = next_gate_output;
self.last_output = next_output;
return output;
}
/// Performs backend-aware gated inference without updating training caches.
pub fn forwardBackend(self: *GatedLayer, input: *const BackendMatrix) !*BackendMatrix {
if (input.cols != self.getInputSize()) {
return error.InvalidInputDimensions;
}
const backend_instance = input.backend;
const linear_weights = try BackendMatrix.fromMatrix(backend_instance, self.linear_weights, self.allocator);
defer linear_weights.deinit();
const linear_bias = try BackendMatrix.fromMatrix(backend_instance, self.linear_bias, self.allocator);
defer linear_bias.deinit();
const gate_weights = try BackendMatrix.fromMatrix(backend_instance, self.gate_weights, self.allocator);
defer gate_weights.deinit();
const gate_bias = try BackendMatrix.fromMatrix(backend_instance, self.gate_bias, self.allocator);
defer gate_bias.deinit();
const linear_weighted_sum = try input.dotProduct(linear_weights, self.allocator);
defer linear_weighted_sum.deinit();
const linear_biased = try addBackendBias(linear_weighted_sum, linear_bias, self.allocator);
defer linear_biased.deinit();
const gate_weighted_sum = try input.dotProduct(gate_weights, self.allocator);
defer gate_weighted_sum.deinit();
const gate_biased = try addBackendBias(gate_weighted_sum, gate_bias, self.allocator);
defer gate_biased.deinit();
if (self.use_swiglu) {
return linear_biased.applySwiGLU(gate_biased, self.allocator);
}
return linear_biased.applyGLU(gate_biased, self.allocator);
}
/// Performs backend-aware gated forward propagation and stores backend caches for training.
pub fn forwardBackendTrain(self: *GatedLayer, input: *const BackendMatrix) !*BackendMatrix {
if (input.cols != self.getInputSize()) {
return error.InvalidInputDimensions;
}
self.clearBackendCaches();
errdefer self.clearBackendCaches();
const backend_instance = input.backend;
self.last_backend_input = try input.copy(self.allocator);
self.last_backend_linear_weights = try BackendMatrix.fromMatrix(backend_instance, self.linear_weights, self.allocator);
self.last_backend_linear_bias = try BackendMatrix.fromMatrix(backend_instance, self.linear_bias, self.allocator);
self.last_backend_gate_weights = try BackendMatrix.fromMatrix(backend_instance, self.gate_weights, self.allocator);
self.last_backend_gate_bias = try BackendMatrix.fromMatrix(backend_instance, self.gate_bias, self.allocator);
const linear_weighted_sum = try input.dotProduct(self.last_backend_linear_weights.?, self.allocator);
defer linear_weighted_sum.deinit();
self.last_backend_linear_output = try addBackendBias(linear_weighted_sum, self.last_backend_linear_bias.?, self.allocator);
const gate_weighted_sum = try input.dotProduct(self.last_backend_gate_weights.?, self.allocator);
defer gate_weighted_sum.deinit();
self.last_backend_gate_output = try addBackendBias(gate_weighted_sum, self.last_backend_gate_bias.?, self.allocator);
const output = if (self.use_swiglu)
try self.last_backend_linear_output.?.applySwiGLU(self.last_backend_gate_output.?, self.allocator)
else
try self.last_backend_linear_output.?.applyGLU(self.last_backend_gate_output.?, self.allocator);
errdefer output.deinit();
self.last_backend_output = try output.copy(self.allocator);
return output;
}
/// Backpropagation through the gated layer
/// output_gradient: gradient of the loss with respect to the layer's output
/// learning_rate: how fast the network learns
/// Returns: gradient of the loss with respect to the layer's input
pub fn backward(self: *GatedLayer, output_gradient: Matrix, learning_rate: f64) !Matrix {
if (self.last_input == null or self.last_linear_output == null or
self.last_gate_output == null or self.last_output == null)
{
return error.NoForwardPassPerformed;
}
// Gradients for GLU or SwiGLU
var linear_gradient: Matrix = undefined;
var gate_gradient: Matrix = undefined;
if (self.use_swiglu) {
// SwiGLU: output = linear * swish(gate)
// Compute gradients for SwiGLU
var swish_gate = try Activation.apply(self.last_gate_output.?, Activation.swish, self.allocator);
defer swish_gate.deinit();
var swish_derivative = try Activation.apply(self.last_gate_output.?, Activation.swish_derivative, self.allocator);
defer swish_derivative.deinit();
// Gradient with respect to linear part
linear_gradient = try swish_gate.elementWiseMultiply(output_gradient, self.allocator);
// Gradient with respect to gate part
var linear_times_gradient = try self.last_linear_output.?.elementWiseMultiply(output_gradient, self.allocator);
defer linear_times_gradient.deinit();
gate_gradient = try linear_times_gradient.elementWiseMultiply(swish_derivative, self.allocator);
} else {
// GLU: output = linear * sigmoid(gate)
// Compute gradients for GLU
var sigmoid_gate = try Activation.apply(self.last_gate_output.?, Activation.sigmoid, self.allocator);
defer sigmoid_gate.deinit();
var sigmoid_derivative = try Activation.apply(self.last_gate_output.?, Activation.sigmoid_derivative, self.allocator);
defer sigmoid_derivative.deinit();
// Gradient with respect to linear part
linear_gradient = try sigmoid_gate.elementWiseMultiply(output_gradient, self.allocator);
// Gradient with respect to gate part
var linear_times_gradient = try self.last_linear_output.?.elementWiseMultiply(output_gradient, self.allocator);
defer linear_times_gradient.deinit();
gate_gradient = try linear_times_gradient.elementWiseMultiply(sigmoid_derivative, self.allocator);
}
defer linear_gradient.deinit();
defer gate_gradient.deinit();
// Calculate gradients with respect to weights and biases
var transposed_input = try self.last_input.?.transpose(self.allocator);
defer transposed_input.deinit();
// Linear weights gradient
var linear_weights_gradient = try transposed_input.dotProduct(linear_gradient, self.allocator);
defer linear_weights_gradient.deinit();
// Gate weights gradient
var gate_weights_gradient = try transposed_input.dotProduct(gate_gradient, self.allocator);
defer gate_weights_gradient.deinit();
// Linear bias gradient (sum along batch dimension)
var linear_bias_gradient = try linear_gradient.sumRows(self.allocator);
defer linear_bias_gradient.deinit();
// Gate bias gradient (sum along batch dimension)
var gate_bias_gradient = try gate_gradient.sumRows(self.allocator);
defer gate_bias_gradient.deinit();
// Calculate gradient with respect to input
var transposed_linear_weights = try self.linear_weights.transpose(self.allocator);
defer transposed_linear_weights.deinit();
var transposed_gate_weights = try self.gate_weights.transpose(self.allocator);
defer transposed_gate_weights.deinit();
var linear_input_gradient = try linear_gradient.dotProduct(transposed_linear_weights, self.allocator);
defer linear_input_gradient.deinit();
var gate_input_gradient = try gate_gradient.dotProduct(transposed_gate_weights, self.allocator);
defer gate_input_gradient.deinit();
const input_gradient = try linear_input_gradient.add(gate_input_gradient, self.allocator);
// Update weights and biases
// Scale gradients by learning rate
var scaled_linear_weights_gradient = try linear_weights_gradient.scale(learning_rate, self.allocator);
defer scaled_linear_weights_gradient.deinit();
var scaled_gate_weights_gradient = try gate_weights_gradient.scale(learning_rate, self.allocator);
defer scaled_gate_weights_gradient.deinit();
var scaled_linear_bias_gradient = try linear_bias_gradient.scale(learning_rate, self.allocator);
defer scaled_linear_bias_gradient.deinit();
var scaled_gate_bias_gradient = try gate_bias_gradient.scale(learning_rate, self.allocator);
defer scaled_gate_bias_gradient.deinit();
// Update linear weights
const new_linear_weights = try self.linear_weights.subtract(scaled_linear_weights_gradient, self.allocator);
self.linear_weights.deinit();
self.linear_weights = new_linear_weights;
// Update gate weights
const new_gate_weights = try self.gate_weights.subtract(scaled_gate_weights_gradient, self.allocator);
self.gate_weights.deinit();
self.gate_weights = new_gate_weights;
// Update linear bias
const new_linear_bias = try self.linear_bias.subtract(scaled_linear_bias_gradient, self.allocator);
self.linear_bias.deinit();
self.linear_bias = new_linear_bias;
// Update gate bias
const new_gate_bias = try self.gate_bias.subtract(scaled_gate_bias_gradient, self.allocator);
self.gate_bias.deinit();
self.gate_bias = new_gate_bias;
return input_gradient;
}
/// Performs backend-aware gated backpropagation and writes updated parameters back to CPU storage.
pub fn backwardBackend(self: *GatedLayer, output_gradient: *const BackendMatrix, learning_rate: f64) !*BackendMatrix {
if (self.last_backend_input == null or self.last_backend_linear_output == null or
self.last_backend_gate_output == null or self.last_backend_output == null)
{
return error.NoForwardPassPerformed;
}
defer self.clearBackendCaches();
var linear_gradient: *BackendMatrix = undefined;
var gate_gradient: *BackendMatrix = undefined;
if (self.use_swiglu) {
const swish_gate = try self.last_backend_gate_output.?.applyActivation(Activation.swish, self.allocator);
defer swish_gate.deinit();
const swish_derivative = try self.last_backend_gate_output.?.applyActivation(Activation.swish_derivative, self.allocator);
defer swish_derivative.deinit();
linear_gradient = try swish_gate.elementWiseMultiply(output_gradient, self.allocator);
const linear_times_gradient = try self.last_backend_linear_output.?.elementWiseMultiply(output_gradient, self.allocator);
defer linear_times_gradient.deinit();
gate_gradient = try linear_times_gradient.elementWiseMultiply(swish_derivative, self.allocator);
} else {
const sigmoid_gate = try self.last_backend_gate_output.?.applyActivation(Activation.sigmoid, self.allocator);
defer sigmoid_gate.deinit();
const sigmoid_derivative = try self.last_backend_gate_output.?.applyActivation(Activation.sigmoid_derivative, self.allocator);
defer sigmoid_derivative.deinit();
linear_gradient = try sigmoid_gate.elementWiseMultiply(output_gradient, self.allocator);
const linear_times_gradient = try self.last_backend_linear_output.?.elementWiseMultiply(output_gradient, self.allocator);
defer linear_times_gradient.deinit();
gate_gradient = try linear_times_gradient.elementWiseMultiply(sigmoid_derivative, self.allocator);