-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtensor.zig
More file actions
1867 lines (1669 loc) · 75.7 KB
/
Copy pathtensor.zig
File metadata and controls
1867 lines (1669 loc) · 75.7 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 builtin = @import("builtin");
const build_options = @import("build_options");
const backend_mod = @import("backend.zig");
const dimension_utils = @import("dimensions.zig");
const root = @import("root.zig");
const Allocator = std.mem.Allocator;
const BackendInstance = root.BackendInstance;
const BackendMatrix = backend_mod.Matrix;
const BackendType = backend_mod.BackendType;
const Activation = @import("activation.zig").Activation;
pub const max_rank: usize = 4;
/// Compute precision used by the device-oriented tensor runtime.
pub const DType = enum {
f32,
};
/// Element-wise activations available to device-resident Tensor models.
pub const ActivationKind = enum {
linear,
relu,
sigmoid,
tanh,
gelu,
};
pub const OptimizerUpdateKind = backend_mod.OptimizerUpdateKind;
pub const OptimizerUpdateConfig = backend_mod.OptimizerUpdateConfig;
/// User-facing backend selection policy.
pub const DevicePreference = enum {
cpu,
auto,
metal,
cuda,
rocm,
};
pub const Shape = struct {
rank: u3,
dims: [max_rank]usize,
len: usize,
pub fn init(requested: []const usize) !Shape {
if (requested.len == 0 or requested.len > max_rank) {
return error.InvalidRank;
}
var dims = [_]usize{1} ** max_rank;
var len: usize = 1;
for (requested, 0..) |dim, index| {
if (dim == 0) return error.InvalidDimension;
len = std.math.mul(usize, len, dim) catch return error.ShapeOverflow;
dims[index] = dim;
}
return .{
.rank = @intCast(requested.len),
.dims = dims,
.len = len,
};
}
pub fn slice(self: *const Shape) []const usize {
return self.dims[0..self.rank];
}
pub fn eql(self: Shape, other: Shape) bool {
return std.mem.eql(usize, self.dims[0..self.rank], other.dims[0..other.rank]);
}
fn matrixDimensions(self: Shape) struct { rows: usize, cols: usize } {
const cols = self.dims[self.rank - 1];
return .{ .rows = self.len / cols, .cols = cols };
}
};
/// Owns one backend instance and enforces exact selection for explicit GPU
/// requests. `auto` is the only preference permitted to fall back to CPU.
pub const Device = struct {
allocator: Allocator,
instance: BackendInstance,
preference: DevicePreference,
pub fn init(allocator: Allocator, preference: DevicePreference) !Device {
const requested: BackendType = switch (preference) {
.cpu => .CPU,
.metal => .Metal,
.cuda => .CUDA,
.rocm => .ROCm,
.auto => autoBackendType(),
};
const instance = try backend_mod.createBackend(allocator, requested);
if (preference != .auto and instance.getBackendType() != requested) {
instance.deinit();
return error.BackendUnavailable;
}
return .{
.allocator = allocator,
.instance = instance,
.preference = preference,
};
}
pub fn deinit(self: *Device) void {
self.instance.deinit();
self.* = undefined;
}
pub fn backendType(self: Device) BackendType {
return self.instance.getBackendType();
}
/// Returns the exact backend instance owned by this device. This is used
/// by long-lived inference sessions to upload parameters once and retain
/// the resulting backend-side model snapshot.
pub fn backendInstance(self: Device) BackendInstance {
return self.instance;
}
pub fn configureCpuOutputTiles(self: *Device, count: usize) !void {
try self.instance.configureCpuOutputTiles(count);
}
pub fn runtimeStats(self: Device) backend_mod.RuntimeStats {
return self.instance.runtimeStats();
}
pub fn resetRuntimeStats(self: *Device) void {
self.instance.resetRuntimeStats();
}
pub fn createTensor(self: *Device, shape: []const usize) !Tensor {
return Tensor.init(self.instance, self.allocator, shape);
}
fn autoBackendType() BackendType {
if (builtin.os.tag == .linux and build_options.enable_cuda) return .CUDA;
if (builtin.os.tag == .linux and build_options.enable_rocm) return .ROCm;
if (builtin.os.tag == .macos and build_options.enable_metal) return .Metal;
return .CPU;
}
};
/// Rank-aware f32 tensor backed by the existing backend matrix allocation.
/// Rank 1-4 tensors are flattened into a rank-2 physical allocation while the
/// logical shape remains available to neural-network operators.
pub const Tensor = struct {
matrix: *BackendMatrix,
shape: Shape,
dtype: DType = .f32,
allocator: Allocator,
pub fn init(
backend: BackendInstance,
allocator: Allocator,
requested_shape: []const usize,
) !Tensor {
const shape = try Shape.init(requested_shape);
const matrix_dims = shape.matrixDimensions();
const matrix = try BackendMatrix.init(
backend,
allocator,
matrix_dims.rows,
matrix_dims.cols,
);
return .{
.matrix = matrix,
.shape = shape,
.allocator = allocator,
};
}
pub fn fromF32(
backend: BackendInstance,
allocator: Allocator,
requested_shape: []const usize,
values: []const f32,
) !Tensor {
var result = try Tensor.init(backend, allocator, requested_shape);
errdefer result.deinit();
try result.writeF32(values);
return result;
}
pub fn deinit(self: *Tensor) void {
self.matrix.deinit();
self.* = undefined;
}
pub fn elementCount(self: Tensor) usize {
return self.shape.len;
}
pub fn backendType(self: Tensor) BackendType {
return self.matrix.backend.getBackendType();
}
pub fn writeF32(self: *Tensor, values: []const f32) !void {
try self.matrix.writeF32(values);
}
pub fn prepareInferenceWeight(self: *Tensor) !void {
try self.matrix.prepareInferenceWeight();
}
pub fn readF32(self: Tensor, values: []f32) !void {
try self.matrix.readF32(values);
}
/// Changes only logical shape metadata; storage and device contents stay
/// untouched.
pub fn reshape(self: *Tensor, requested_shape: []const usize) !void {
const next = try Shape.init(requested_shape);
if (next.len != self.shape.len) return error.DimensionMismatch;
self.shape = next;
}
pub fn fill(self: *Tensor, value: f32) void {
self.matrix.fill(@floatCast(value));
}
pub fn copy(self: Tensor) !Tensor {
return .{
.matrix = try self.matrix.copy(self.allocator),
.shape = self.shape,
.dtype = self.dtype,
.allocator = self.allocator,
};
}
};
pub const ExecutionStats = struct {
uploads: usize = 0,
upload_bytes: usize = 0,
readbacks: usize = 0,
readback_bytes: usize = 0,
kernels: usize = 0,
synchronizations: usize = 0,
};
pub const LayerNormGradients = struct {
input: Tensor,
gamma: Tensor,
beta: Tensor,
pub fn deinit(self: *LayerNormGradients) void {
self.input.deinit();
self.gamma.deinit();
self.beta.deinit();
self.* = undefined;
}
};
pub const AttentionGradients = struct {
query: Tensor,
key: Tensor,
value: Tensor,
pub fn deinit(self: *AttentionGradients) void {
self.query.deinit();
self.key.deinit();
self.value.deinit();
self.* = undefined;
}
};
/// Owns both a dropout output and the inverted dropout mask required by the
/// backward pass. The mask is device-resident after one explicit upload.
pub const DropoutResult = struct {
output: Tensor,
mask: Tensor,
pub fn deinit(self: *DropoutResult) void {
self.output.deinit();
self.mask.deinit();
self.* = undefined;
}
};
/// Sparse class targets with a token-level mask. The gradient is computed on
/// the selected device; `meanLoss` is an explicit reporting readback.
pub const MaskedSparseCrossEntropy = struct {
probabilities: Tensor,
gradient: Tensor,
targets: []usize,
token_mask: []f32,
active_weight: f32,
classes: usize,
allocator: Allocator,
pub fn meanLoss(self: MaskedSparseCrossEntropy, context: *ExecutionContext) !f32 {
const values = try self.allocator.alloc(f32, self.probabilities.shape.len);
defer self.allocator.free(values);
try context.readback(self.probabilities, values);
var total: f32 = 0;
for (self.targets, self.token_mask, 0..) |target, weight, row| {
if (weight == 0) continue;
total -= weight * @log(@max(values[row * self.classes + target], 1.0e-12));
}
return total / self.active_weight;
}
pub fn deinit(self: *MaskedSparseCrossEntropy) void {
self.probabilities.deinit();
self.gradient.deinit();
self.allocator.free(self.targets);
self.allocator.free(self.token_mask);
self.* = undefined;
}
};
/// Explicit execution boundary for tensor construction, operations, readback,
/// and instrumentation. Backend command batching can be implemented behind
/// this API without another model-code migration.
pub const ExecutionContext = struct {
device: *Device,
stats: ExecutionStats = .{},
batch_active: bool = false,
pub fn init(device: *Device) ExecutionContext {
return .{ .device = device };
}
fn requireOwned(self: ExecutionContext, tensors: []const Tensor) !void {
for (tensors) |value| {
if (!self.device.instance.sameInstance(value.matrix.backend)) {
return error.BackendMismatch;
}
}
}
pub fn createTensor(self: *ExecutionContext, shape: []const usize) !Tensor {
return self.device.createTensor(shape);
}
pub fn upload(
self: *ExecutionContext,
shape: []const usize,
values: []const f32,
) !Tensor {
var result = try self.device.createTensor(shape);
errdefer result.deinit();
try result.writeF32(values);
self.stats.uploads += 1;
self.stats.upload_bytes += values.len * @sizeOf(f32);
return result;
}
pub fn readback(self: *ExecutionContext, tensor: Tensor, values: []f32) !void {
try self.requireOwned(&.{tensor});
try tensor.readF32(values);
self.stats.readbacks += 1;
self.stats.readback_bytes += values.len * @sizeOf(f32);
}
pub fn matmul(self: *ExecutionContext, a: Tensor, b: Tensor) !Tensor {
try self.requireOwned(&.{ a, b });
if (a.shape.rank != 2 or b.shape.rank != 2) return error.InvalidRank;
if (a.shape.dims[1] != b.shape.dims[0]) return error.DimensionMismatch;
const matrix = try a.matrix.dotProduct(b.matrix, self.device.allocator);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = try Shape.init(&.{ a.shape.dims[0], b.shape.dims[1] }),
.allocator = self.device.allocator,
};
}
/// Performs `[batch, rows, inner] x [batch, inner, cols]` matrix
/// multiplication. Transpose flags affect only each logical matrix, not
/// the batch dimension.
pub fn batchedMatmul(self: *ExecutionContext, a: Tensor, b: Tensor, transpose_a: bool, transpose_b: bool) !Tensor {
try self.requireOwned(&.{ a, b });
if (a.shape.rank != 3 or b.shape.rank != 3) return error.InvalidRank;
if (a.shape.dims[0] != b.shape.dims[0]) return error.DimensionMismatch;
const a_rows = a.shape.dims[1];
const a_cols = a.shape.dims[2];
const b_rows = b.shape.dims[1];
const b_cols = b.shape.dims[2];
const inner_a = if (transpose_a) a_rows else a_cols;
const inner_b = if (transpose_b) b_cols else b_rows;
if (inner_a != inner_b) return error.DimensionMismatch;
const output_rows = if (transpose_a) a_cols else a_rows;
const output_cols = if (transpose_b) b_rows else b_cols;
const matrix = try a.matrix.batchedDotProduct(
b.matrix,
self.device.allocator,
a.shape.dims[0],
a_rows,
a_cols,
b_rows,
b_cols,
transpose_a,
transpose_b,
);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = try Shape.init(&.{ a.shape.dims[0], output_rows, output_cols }),
.allocator = self.device.allocator,
};
}
/// Splits token-major channels into head-major batches:
/// `[batch, tokens, heads, width] -> [batch * heads, tokens, width]`.
pub fn splitHeads(self: *ExecutionContext, input: Tensor) !Tensor {
try self.requireOwned(&.{input});
if (input.shape.rank != 4) return error.InvalidRank;
const batch = input.shape.dims[0];
const tokens = input.shape.dims[1];
const heads = input.shape.dims[2];
const width = input.shape.dims[3];
const matrix = try input.matrix.permuteBatchHeads(self.device.allocator, batch, tokens, heads, width, true);
self.stats.kernels += 1;
return .{ .matrix = matrix, .shape = try Shape.init(&.{ batch * heads, tokens, width }), .allocator = self.device.allocator };
}
/// Merges head-major batches back into token-major channels:
/// `[batch * heads, tokens, width] -> [batch, tokens, heads, width]`.
pub fn mergeHeads(self: *ExecutionContext, input: Tensor, batch: usize, heads: usize) !Tensor {
try self.requireOwned(&.{input});
if (input.shape.rank != 3 or batch == 0 or heads == 0 or
!dimension_utils.matches(input.shape.dims[0], &.{ batch, heads }))
{
return error.DimensionMismatch;
}
const tokens = input.shape.dims[1];
const width = input.shape.dims[2];
const matrix = try input.matrix.permuteBatchHeads(self.device.allocator, batch, tokens, heads, width, false);
self.stats.kernels += 1;
return .{ .matrix = matrix, .shape = try Shape.init(&.{ batch, tokens, heads, width }), .allocator = self.device.allocator };
}
pub fn add(self: *ExecutionContext, a: Tensor, b: Tensor) !Tensor {
try self.requireOwned(&.{ a, b });
if (!a.shape.eql(b.shape)) return error.DimensionMismatch;
const matrix = try a.matrix.add(b.matrix, self.device.allocator);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = a.shape,
.allocator = self.device.allocator,
};
}
pub fn subtract(self: *ExecutionContext, a: Tensor, b: Tensor) !Tensor {
try self.requireOwned(&.{ a, b });
if (!a.shape.eql(b.shape)) return error.DimensionMismatch;
const matrix = try a.matrix.subtract(b.matrix, self.device.allocator);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = a.shape,
.allocator = self.device.allocator,
};
}
pub fn multiply(self: *ExecutionContext, a: Tensor, b: Tensor) !Tensor {
try self.requireOwned(&.{ a, b });
if (!a.shape.eql(b.shape)) return error.DimensionMismatch;
const matrix = try a.matrix.elementWiseMultiply(b.matrix, self.device.allocator);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = a.shape,
.allocator = self.device.allocator,
};
}
pub fn scale(self: *ExecutionContext, input: Tensor, scalar: f32) !Tensor {
try self.requireOwned(&.{input});
const matrix = try input.matrix.scale(scalar, self.device.allocator);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = input.shape,
.allocator = self.device.allocator,
};
}
pub fn transpose(self: *ExecutionContext, input: Tensor) !Tensor {
try self.requireOwned(&.{input});
if (input.shape.rank != 2) return error.InvalidRank;
const matrix = try input.matrix.transpose(self.device.allocator);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = try Shape.init(&.{ input.shape.dims[1], input.shape.dims[0] }),
.allocator = self.device.allocator,
};
}
pub fn sumRows(self: *ExecutionContext, input: Tensor) !Tensor {
try self.requireOwned(&.{input});
if (input.shape.rank != 2) return error.InvalidRank;
const matrix = try input.matrix.sumRows(self.device.allocator);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = try Shape.init(&.{ 1, input.shape.dims[1] }),
.allocator = self.device.allocator,
};
}
/// Returns a device-resident `[1, 1]` Tensor containing the sum of every
/// squared element, regardless of the input's logical rank.
pub fn sumSquares(self: *ExecutionContext, input: Tensor) !Tensor {
var matrix_view = input;
matrix_view.shape = try Shape.init(&.{ input.matrix.rows, input.matrix.cols });
var squared = try self.multiply(matrix_view, matrix_view);
defer squared.deinit();
var column_sums = try self.sumRows(squared);
defer column_sums.deinit();
var column_vector = try self.transpose(column_sums);
defer column_vector.deinit();
return self.sumRows(column_vector);
}
pub fn optimizerUpdate(
self: *ExecutionContext,
parameter: *Tensor,
gradient: Tensor,
first_moment: *Tensor,
second_moment: *Tensor,
total_squares: Tensor,
config: OptimizerUpdateConfig,
) !void {
try self.requireOwned(&.{ parameter.*, gradient, first_moment.*, second_moment.*, total_squares });
if (!parameter.shape.eql(gradient.shape) or
!parameter.shape.eql(first_moment.shape) or
!parameter.shape.eql(second_moment.shape) or
total_squares.shape.rank != 2 or total_squares.shape.dims[0] != 1 or
total_squares.shape.dims[1] != 1)
{
return error.DimensionMismatch;
}
try parameter.matrix.optimizerUpdate(
gradient.matrix,
first_moment.matrix,
second_moment.matrix,
total_squares.matrix,
config,
);
self.stats.kernels += 1;
}
pub fn addRowBias(self: *ExecutionContext, input: Tensor, bias: Tensor) !Tensor {
try self.requireOwned(&.{ input, bias });
if (input.shape.rank != 2 or bias.shape.rank != 2) return error.InvalidRank;
if (bias.shape.dims[0] != 1 or bias.shape.dims[1] != input.shape.dims[1]) return error.DimensionMismatch;
const matrix = try input.matrix.addRowBias(bias.matrix, self.device.allocator);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = input.shape,
.allocator = self.device.allocator,
};
}
pub fn linear(self: *ExecutionContext, input: Tensor, weights: Tensor, bias: Tensor) !Tensor {
var projected = try self.matmul(input, weights);
defer projected.deinit();
return self.addRowBias(projected, bias);
}
pub fn linearGelu(self: *ExecutionContext, input: Tensor, weights: Tensor, bias: Tensor) !Tensor {
try self.requireOwned(&.{ input, weights, bias });
if (input.shape.rank != 2 or weights.shape.rank != 2 or bias.shape.rank != 2) return error.InvalidRank;
if (input.shape.dims[1] != weights.shape.dims[0] or
bias.shape.dims[0] != 1 or bias.shape.dims[1] != weights.shape.dims[1])
{
return error.DimensionMismatch;
}
const matrix = try input.matrix.linearBiasGelu(weights.matrix, bias.matrix, self.device.allocator);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = try Shape.init(&.{ input.shape.dims[0], weights.shape.dims[1] }),
.allocator = self.device.allocator,
};
}
pub fn activate(self: *ExecutionContext, input: Tensor, kind: ActivationKind) !Tensor {
try self.requireOwned(&.{input});
const function = activationFunction(kind);
const matrix = try input.matrix.applyActivation(function, self.device.allocator);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = input.shape,
.allocator = self.device.allocator,
};
}
pub fn activationDerivative(self: *ExecutionContext, input: Tensor, kind: ActivationKind) !Tensor {
try self.requireOwned(&.{input});
const function = activationDerivativeFunction(kind);
const matrix = try input.matrix.applyActivation(function, self.device.allocator);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = input.shape,
.allocator = self.device.allocator,
};
}
pub fn gelu(self: *ExecutionContext, input: Tensor) !Tensor {
return self.activate(input, .gelu);
}
pub fn geluDerivative(self: *ExecutionContext, input: Tensor) !Tensor {
return self.activationDerivative(input, .gelu);
}
pub fn layerNorm(self: *ExecutionContext, input: Tensor, gamma: Tensor, beta: Tensor, epsilon: f32) !Tensor {
try self.requireOwned(&.{ input, gamma, beta });
if (input.shape.rank != 2 or gamma.shape.rank != 2 or beta.shape.rank != 2) return error.InvalidRank;
if (gamma.shape.dims[0] != 1 or beta.shape.dims[0] != 1 or
gamma.shape.dims[1] != input.shape.dims[1] or beta.shape.dims[1] != input.shape.dims[1])
{
return error.DimensionMismatch;
}
const matrix = try input.matrix.layerNorm(gamma.matrix, beta.matrix, epsilon, self.device.allocator);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = input.shape,
.allocator = self.device.allocator,
};
}
pub fn layerNormBackward(self: *ExecutionContext, input: Tensor, gamma: Tensor, output_gradient: Tensor, epsilon: f32) !LayerNormGradients {
try self.requireOwned(&.{ input, gamma, output_gradient });
if (input.shape.rank != 2 or gamma.shape.rank != 2 or output_gradient.shape.rank != 2) return error.InvalidRank;
if (!input.shape.eql(output_gradient.shape) or gamma.shape.dims[0] != 1 or gamma.shape.dims[1] != input.shape.dims[1]) {
return error.DimensionMismatch;
}
const gradients = try input.matrix.layerNormBackward(gamma.matrix, output_gradient.matrix, epsilon, self.device.allocator);
self.stats.kernels += 1;
return .{
.input = .{ .matrix = gradients.input, .shape = input.shape, .allocator = self.device.allocator },
.gamma = .{ .matrix = gradients.gamma, .shape = gamma.shape, .allocator = self.device.allocator },
.beta = .{ .matrix = gradients.beta, .shape = gamma.shape, .allocator = self.device.allocator },
};
}
pub fn causalSelfAttention(self: *ExecutionContext, query: Tensor, key: Tensor, value: Tensor, heads: usize) !Tensor {
try self.requireOwned(&.{ query, key, value });
if (query.shape.rank != 2 or key.shape.rank != 2 or value.shape.rank != 2) return error.InvalidRank;
if (!query.shape.eql(key.shape) or !query.shape.eql(value.shape) or
heads == 0 or query.shape.dims[1] % heads != 0)
{
return error.DimensionMismatch;
}
const matrix = try query.matrix.causalSelfAttention(key.matrix, value.matrix, heads, self.device.allocator);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = query.shape,
.allocator = self.device.allocator,
};
}
pub fn causalSelfAttentionBackward(self: *ExecutionContext, query: Tensor, key: Tensor, value: Tensor, output_gradient: Tensor, heads: usize) !AttentionGradients {
try self.requireOwned(&.{ query, key, value, output_gradient });
if (query.shape.rank != 2 or key.shape.rank != 2 or value.shape.rank != 2 or output_gradient.shape.rank != 2) return error.InvalidRank;
if (!query.shape.eql(key.shape) or !query.shape.eql(value.shape) or !query.shape.eql(output_gradient.shape) or
heads == 0 or query.shape.dims[1] % heads != 0)
{
return error.DimensionMismatch;
}
const gradients = try query.matrix.causalSelfAttentionBackward(key.matrix, value.matrix, output_gradient.matrix, heads, self.device.allocator);
self.stats.kernels += 2;
return .{
.query = .{ .matrix = gradients.query, .shape = query.shape, .allocator = self.device.allocator },
.key = .{ .matrix = gradients.key, .shape = key.shape, .allocator = self.device.allocator },
.value = .{ .matrix = gradients.value, .shape = value.shape, .allocator = self.device.allocator },
};
}
pub fn embedding(self: *ExecutionContext, table: Tensor, indices: Tensor) !Tensor {
try self.requireOwned(&.{ table, indices });
if (table.shape.rank != 2 or indices.shape.rank != 2 or indices.shape.dims[1] != 1) return error.InvalidRank;
const matrix = try table.matrix.embeddingLookup(indices.matrix, self.device.allocator);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = try Shape.init(&.{ indices.shape.dims[0], table.shape.dims[1] }),
.allocator = self.device.allocator,
};
}
pub fn embeddingBackward(self: *ExecutionContext, indices: Tensor, output_gradient: Tensor, vocabulary_size: usize) !Tensor {
try self.requireOwned(&.{ indices, output_gradient });
if (indices.shape.rank != 2 or output_gradient.shape.rank != 2 or indices.shape.dims[1] != 1 or
indices.shape.dims[0] != output_gradient.shape.dims[0])
{
return error.DimensionMismatch;
}
const matrix = try output_gradient.matrix.embeddingGradient(indices.matrix, vocabulary_size, self.device.allocator);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = try Shape.init(&.{ vocabulary_size, output_gradient.shape.dims[1] }),
.allocator = self.device.allocator,
};
}
pub fn cachedSelfAttention(self: *ExecutionContext, query: Tensor, key: Tensor, value: Tensor, key_cache: *Tensor, value_cache: *Tensor, position: usize, heads: usize) !Tensor {
try self.requireOwned(&.{ query, key, value, key_cache.*, value_cache.* });
if (query.shape.rank != 2 or !query.shape.eql(key.shape) or !query.shape.eql(value.shape) or query.shape.dims[0] != 1 or
key_cache.shape.rank != 2 or !key_cache.shape.eql(value_cache.shape) or key_cache.shape.dims[1] != query.shape.dims[1] or
position >= key_cache.shape.dims[0] or heads == 0 or query.shape.dims[1] % heads != 0)
{
return error.DimensionMismatch;
}
const matrix = try query.matrix.cachedSelfAttention(key.matrix, value.matrix, key_cache.matrix, value_cache.matrix, position, heads, self.device.allocator);
self.stats.kernels += 1;
return .{ .matrix = matrix, .shape = query.shape, .allocator = self.device.allocator };
}
pub fn softmax(self: *ExecutionContext, input: Tensor) !Tensor {
try self.requireOwned(&.{input});
if (input.shape.rank != 2) return error.InvalidRank;
const matrix = try input.matrix.applySoftmax(self.device.allocator);
self.stats.kernels += 1;
return .{
.matrix = matrix,
.shape = input.shape,
.allocator = self.device.allocator,
};
}
/// Row-wise softmax over the final dimension. Zero mask entries receive
/// exactly zero probability, including rows where every entry is masked.
pub fn maskedSoftmax(self: *ExecutionContext, input: Tensor, mask: Tensor) !Tensor {
try self.requireOwned(&.{ input, mask });
if (input.shape.rank < 2 or input.shape.rank > 3) return error.InvalidRank;
if (!input.shape.eql(mask.shape)) return error.DimensionMismatch;
var ones = try self.createTensor(input.shape.slice());
defer ones.deinit();
ones.fill(1);
var mask_offset = try self.subtract(mask, ones);
defer mask_offset.deinit();
var penalty = try self.scale(mask_offset, 1.0e9);
defer penalty.deinit();
var masked_scores = try self.add(input, penalty);
defer masked_scores.deinit();
var matrix_view = masked_scores;
matrix_view.shape = try Shape.init(&.{ input.shape.len / input.shape.dims[input.shape.rank - 1], input.shape.dims[input.shape.rank - 1] });
var probabilities = try self.softmax(matrix_view);
errdefer probabilities.deinit();
probabilities.shape = input.shape;
const result = try self.multiply(probabilities, mask);
probabilities.deinit();
return result;
}
/// Jacobian-vector product for `maskedSoftmax`, evaluated entirely with
/// device tensor operations.
pub fn maskedSoftmaxBackward(self: *ExecutionContext, probabilities: Tensor, output_gradient: Tensor, mask: Tensor) !Tensor {
try self.requireOwned(&.{ probabilities, output_gradient, mask });
if (probabilities.shape.rank < 2 or probabilities.shape.rank > 3) return error.InvalidRank;
if (!probabilities.shape.eql(output_gradient.shape) or !probabilities.shape.eql(mask.shape)) return error.DimensionMismatch;
const cols = probabilities.shape.dims[probabilities.shape.rank - 1];
const rows = probabilities.shape.len / cols;
var probabilities_view = probabilities;
probabilities_view.shape = try Shape.init(&.{ rows, cols });
var gradient_view = output_gradient;
gradient_view.shape = probabilities_view.shape;
var weighted = try self.multiply(probabilities_view, gradient_view);
defer weighted.deinit();
var weighted_t = try self.transpose(weighted);
defer weighted_t.deinit();
var row_sums_t = try self.sumRows(weighted_t);
defer row_sums_t.deinit();
var row_sums = try self.transpose(row_sums_t);
defer row_sums.deinit();
var ones = try self.createTensor(&.{ 1, cols });
defer ones.deinit();
ones.fill(1);
var broadcast_sums = try self.matmul(row_sums, ones);
defer broadcast_sums.deinit();
var centered = try self.subtract(gradient_view, broadcast_sums);
defer centered.deinit();
var jacobian_product = try self.multiply(probabilities_view, centered);
defer jacobian_product.deinit();
var mask_view = mask;
mask_view.shape = probabilities_view.shape;
var result = try self.multiply(jacobian_product, mask_view);
result.shape = probabilities.shape;
return result;
}
/// Applies inverted dropout. Supplying a seed makes the mask reproducible,
/// which keeps learning experiments and gradient tests deterministic.
pub fn dropout(self: *ExecutionContext, input: Tensor, probability: f32, seed: u64, training: bool) !DropoutResult {
try self.requireOwned(&.{input});
if (probability < 0 or probability >= 1) return error.InvalidProbability;
const values = try self.device.allocator.alloc(f32, input.shape.len);
defer self.device.allocator.free(values);
if (!training or probability == 0) {
@memset(values, 1);
} else {
var prng = std.Random.DefaultPrng.init(seed);
const random = prng.random();
const inverse_keep = 1.0 / (1.0 - probability);
for (values) |*value| {
value.* = if (random.float(f32) < probability) 0 else inverse_keep;
}
}
var mask = try self.upload(input.shape.slice(), values);
errdefer mask.deinit();
const output = try self.multiply(input, mask);
return .{ .output = output, .mask = mask };
}
pub fn dropoutBackward(self: *ExecutionContext, output_gradient: Tensor, mask: Tensor) !Tensor {
return self.multiply(output_gradient, mask);
}
/// Computes mean sparse cross-entropy over active tokens. Sparse target
/// indices are expanded once at the upload boundary; probabilities and the
/// training gradient remain device-resident.
pub fn maskedSparseCrossEntropy(self: *ExecutionContext, logits: Tensor, targets: []const usize, token_mask: []const f32) !MaskedSparseCrossEntropy {
try self.requireOwned(&.{logits});
if (logits.shape.rank < 2 or logits.shape.rank > 3) return error.InvalidRank;
const classes = logits.shape.dims[logits.shape.rank - 1];
const rows = logits.shape.len / classes;
if (targets.len != rows or token_mask.len != rows) return error.DimensionMismatch;
var active_weight: f32 = 0;
const dense_targets = try self.device.allocator.alloc(f32, logits.shape.len);
defer self.device.allocator.free(dense_targets);
@memset(dense_targets, 0);
const dense_mask = try self.device.allocator.alloc(f32, logits.shape.len);
defer self.device.allocator.free(dense_mask);
for (targets, token_mask, 0..) |target, weight, row| {
if (target >= classes or weight < 0) return error.InvalidTarget;
dense_targets[row * classes + target] = 1;
@memset(dense_mask[row * classes .. (row + 1) * classes], weight);
active_weight += weight;
}
if (active_weight <= 0) return error.EmptyMask;
const owned_targets = try self.device.allocator.dupe(usize, targets);
errdefer self.device.allocator.free(owned_targets);
const owned_mask = try self.device.allocator.dupe(f32, token_mask);
errdefer self.device.allocator.free(owned_mask);
var targets_tensor = try self.upload(logits.shape.slice(), dense_targets);
defer targets_tensor.deinit();
var mask_tensor = try self.upload(logits.shape.slice(), dense_mask);
defer mask_tensor.deinit();
var logits_view = logits;
logits_view.shape = try Shape.init(&.{ rows, classes });
var probabilities = try self.softmax(logits_view);
errdefer probabilities.deinit();
probabilities.shape = logits.shape;
var difference = try self.subtract(probabilities, targets_tensor);
defer difference.deinit();
var masked_gradient = try self.multiply(difference, mask_tensor);
defer masked_gradient.deinit();
const gradient = try self.scale(masked_gradient, 1.0 / active_weight);
return .{
.probabilities = probabilities,
.gradient = gradient,
.targets = owned_targets,
.token_mask = owned_mask,
.active_weight = active_weight,
.classes = classes,
.allocator = self.device.allocator,
};
}
pub fn beginBatch(self: *ExecutionContext) !void {
if (self.batch_active) return error.BatchAlreadyActive;
try self.device.instance.beginBatch();
self.batch_active = true;
}
pub fn endBatch(self: *ExecutionContext) !void {
if (!self.batch_active) return error.NoActiveBatch;
self.device.instance.endBatch() catch |err| {
self.batch_active = false;
return err;
};
self.batch_active = false;
self.stats.synchronizations += 1;
}
pub fn synchronize(self: *ExecutionContext) !void {
try self.device.instance.synchronize();
self.stats.synchronizations += 1;
}
pub fn resetStats(self: *ExecutionContext) void {
self.stats = .{};
self.device.resetRuntimeStats();
}
pub fn executionStats(self: ExecutionContext) ExecutionStats {
return self.stats;
}
pub fn backendStats(self: ExecutionContext) backend_mod.RuntimeStats {
return self.device.runtimeStats();
}
};
fn activationFunction(kind: ActivationKind) *const fn (f64) f64 {
return switch (kind) {
.linear => Activation.linear,
.relu => Activation.relu,
.sigmoid => Activation.sigmoid,
.tanh => Activation.tanh,
.gelu => Activation.gelu,
};
}
fn activationDerivativeFunction(kind: ActivationKind) *const fn (f64) f64 {
return switch (kind) {
.linear => Activation.linear_derivative,
.relu => Activation.relu_derivative,
.sigmoid => Activation.sigmoid_derivative,
.tanh => Activation.tanh_derivative,
.gelu => Activation.gelu_derivative,
};
}
fn referenceMaskedSoftmaxObjective(scores: []const f32, mask: []const f32, upstream: []const f32) f32 {
var max_score = -std.math.inf(f32);
for (scores, mask) |score, active| if (active != 0) {
max_score = @max(max_score, score);
};
var denominator: f32 = 0;
for (scores, mask) |score, active| if (active != 0) {
denominator += @exp(score - max_score);
};
if (denominator == 0) return 0;
var objective: f32 = 0;
for (scores, mask, upstream) |score, active, gradient| if (active != 0) {
objective += @exp(score - max_score) / denominator * gradient;
};
return objective;
}
fn referenceLayerNormObjective(input: []const f32, gamma: []const f32, beta: []const f32, output_gradient: []const f32, rows: usize, cols: usize, epsilon: f32) f32 {
var objective: f32 = 0;
for (0..rows) |row| {
const offset = row * cols;
var mean: f32 = 0;
for (0..cols) |col| mean += input[offset + col];
mean /= @as(f32, @floatFromInt(cols));
var variance: f32 = 0;
for (0..cols) |col| {
const centered = input[offset + col] - mean;
variance += centered * centered;
}
variance /= @as(f32, @floatFromInt(cols));
const inverse_std = 1.0 / @sqrt(variance + epsilon);
for (0..cols) |col| {
const normalized = (input[offset + col] - mean) * inverse_std;
objective += (normalized * gamma[col] + beta[col]) * output_gradient[offset + col];
}
}
return objective;
}
fn referenceAttentionObjective(query: []const f32, key: []const f32, value: []const f32, output_gradient: []const f32, tokens: usize, channels: usize, heads: usize) f32 {
std.debug.assert(tokens <= 16);
var scores: [16]f32 = undefined;
const head_width = channels / heads;
const attention_scale = 1.0 / @sqrt(@as(f32, @floatFromInt(head_width)));
var objective: f32 = 0;
for (0..heads) |head| {
const channel_offset = head * head_width;
for (0..tokens) |query_position| {
var max_score = -std.math.inf(f32);
for (0..query_position + 1) |key_position| {
var score: f32 = 0;
for (0..head_width) |channel| {
score += query[query_position * channels + channel_offset + channel] *
key[key_position * channels + channel_offset + channel];
}
scores[key_position] = score * attention_scale;