-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathndarray.zig
More file actions
1469 lines (1287 loc) · 80.1 KB
/
ndarray.zig
File metadata and controls
1469 lines (1287 loc) · 80.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pub const std = @import("std");
pub const ndvec = @import("ndarray/vec_ops.zig");
pub const gemm = @import("ndarray/gemm.zig");
pub const max_dims = 4;
const FixedBufSliceAlloc = struct {
fba: std.heap.FixedBufferAllocator = undefined,
pub fn init(buf: []u8) @This() {
return @This(){
.fba = std.heap.FixedBufferAllocator.init(buf),
};
}
pub fn alloc(self: *@This(), comptime Type: type, n: usize) []usize {
return (self.fba.allocator().alloc(Type, n) catch unreachable);
}
pub fn dupe(self: *@This(), comptime T: type, m: []const T) []T {
return (self.fba.allocator().dupe(T, m) catch unreachable);
}
};
pub fn shapeProd(shape: []usize) usize {
var size_prod: usize = 1;
for (shape) |s| {
size_prod *= s;
}
return size_prod;
}
pub fn compareShapes(a: []usize, b: []usize) bool {
if (a.len != b.len) {
return false;
}
for (a, b) |ad, bd| {
if (ad != bd) {
return false;
}
}
return true;
}
pub fn inferShape(alloc: std.mem.Allocator, old_shape: []usize, shape: anytype) []usize {
const info = @typeInfo(@TypeOf(shape));
if (info == .Struct) {
if (!info.Struct.is_tuple) {
@compileError("Expected input idx to be a tuple-type");
}
const new_shape = alloc.alloc(usize, shape.len) catch unreachable;
var unknown_idx: ?usize = null;
var shape_prod: usize = 1;
inline for (shape, 0..) |shape_i, i| {
if (shape_i == -1) {
std.debug.assert(unknown_idx == null); // only one unknown -1 size allowed
unknown_idx = i;
} else {
new_shape[i] = shape_i;
shape_prod *= shape_i;
}
}
// Infer unknown size
if (unknown_idx) |idx| {
new_shape[idx] = shapeProd(old_shape) / shape_prod;
}
return new_shape;
} else {
return alloc.dupe(usize, shape) catch unreachable;
}
}
pub const TransposeOpts = struct {
axes: ?[]const usize = null,
};
pub const Conv2dOpts = struct {
stride: usize = 1,
pad: usize = 0,
};
pub const Conv2dGrads = struct {
dw: Ndarray(f32),
dx: Ndarray(f32),
};
pub const Maxpool2dRes = struct {
out: Ndarray(f32),
idx: []const u8,
};
pub const AddMmOpts = struct {
transpose_a: bool = false,
transpose_b: bool = false,
alpha: f32 = 1, // GEMM alpha*(A @ B)
beta: f32 = 1, // GEMM beta (C *= beta)
};
pub fn Ndarray(comptime Dtype: type) type {
return struct {
buf: []Dtype,
strides: []usize,
shape: []usize,
offs: usize,
contiguous: bool,
const Iter = struct {
pub const Opts = struct {
shape: ?[]usize = null, // broadcast to
};
pub fn next(self: *@This()) ?*Dtype {
if (self.index >= self.size) {
return null;
}
self.index += 1;
const ptr: *Dtype = @ptrFromInt(@intFromPtr(self.arr.buf.ptr) + self.data_ptr * @sizeOf(Dtype));
var ii = self.nd_m1;
while (ii >= 0) : (ii -= 1) {
const i: usize = @intCast(ii);
if (self.coords[i] < self.dims_m1[i]) {
self.coords[i] += 1;
self.data_ptr += self.strides[i];
break;
} else {
self.coords[i] = 0;
self.data_ptr -= self.backstrides[i];
}
}
return ptr;
}
// Private
arr: *const Ndarray(Dtype),
nd_m1: isize,
index: usize, // iteration index, upto size
size: usize, // broadcasted size
data_ptr: usize,
contiguous: bool,
strides: [max_dims]usize = undefined,
backstrides: [max_dims]usize = undefined,
dims_m1: [max_dims]usize = undefined,
coords: [max_dims]usize = .{0} ** max_dims,
};
pub fn equalShapes(a: @This(), b: @This()) bool {
return compareShapes(a.shape, b.shape);
}
pub fn iterator(self: *const @This(), opts: Iter.Opts) Iter {
var shape = self.shape;
var diff = @as(usize, 0);
if (opts.shape) |bcast| {
std.debug.assert(self.shape.len <= bcast.len);
diff = bcast.len - self.shape.len;
var i: usize = 0;
var j = diff;
var compatible = true;
while (i < self.shape.len) : ({
i += 1;
j += 1;
}) {
if (self.shape[i] == 1) {
continue;
}
if (self.shape[i] != bcast[j]) {
compatible = false;
break;
}
}
std.debug.assert(compatible); // incompatible shapes for broadcast
shape = bcast;
}
const nd: isize = @intCast(self.shape.len);
var ret = Iter{
.size = undefined,
.contiguous = self.contiguous,
.index = 0,
.nd_m1 = nd - 1,
.arr = self,
.data_ptr = self.offset(.{}),
};
var size_prod: usize = 1;
for (shape, 0..) |dim_i, i| {
ret.dims_m1[i] = dim_i - 1;
var k: isize = @intCast(i);
k -= @intCast(diff);
if (k < 0 or self.shape[@intCast(k)] != shape[i]) {
ret.contiguous = false;
ret.strides[i] = 0; // stretch the dim
} else {
ret.strides[i] = self.strides[@intCast(k)];
}
ret.backstrides[i] = ret.strides[i] * ret.dims_m1[i];
size_prod *= shape[i];
}
ret.size = size_prod;
return ret;
}
fn initStrides(strides: []usize, shape: []const usize) usize {
var stride_prod: usize = 1;
var size_prod: usize = 1;
for (0..shape.len) |i| {
const irev = shape.len - 1 - i;
strides[irev] = stride_prod;
size_prod *= shape[irev];
stride_prod *= shape[irev];
}
return stride_prod;
}
pub fn init(alloc: std.mem.Allocator, shape: []const usize) @This() {
const strides = alloc.alloc(usize, shape.len) catch unreachable;
const stride_prod = @This().initStrides(strides, shape);
return @This(){
.buf = alloc.alloc(Dtype, stride_prod) catch unreachable,
.shape = alloc.dupe(usize, shape) catch unreachable,
.strides = strides,
.offs = 0,
.contiguous = true,
};
}
pub fn clone(self: @This(), alloc: std.mem.Allocator) @This() {
var dst = self.emptyLike(alloc);
dst.assign(self);
return dst;
}
// TODO an allocator-less init would be cool too for read-only inputs
// TODO shape should be inferable from 'init' value
pub fn initFromSlice1d(alloc: std.mem.Allocator, initial: []const f32) @This() {
var arr = @This().init(alloc, &[_]usize{initial.len});
for (initial, 0..) |v, i| {
arr.buf[i] = v;
}
return arr;
}
// TODO an allocator-less init would be cool too for read-only inputs
// TODO shape should be inferable from 'init' value
pub fn initFromSlice2d(alloc: std.mem.Allocator, initial: []const []const f32) @This() {
var arr = @This().init(alloc, &[_]usize{ initial.len, initial[0].len });
var c: usize = 0;
for (0..arr.shape[0]) |i| {
for (0..arr.shape[1]) |j| {
arr.buf[c] = initial[i][j];
c += 1;
}
}
return arr;
}
pub fn emptyLike(self: *const Ndarray(Dtype), alloc: std.mem.Allocator) @This() {
return @This().init(alloc, self.shape);
}
pub fn zerosLike(self: *const Ndarray(Dtype), alloc: std.mem.Allocator) @This() {
const arr = self.emptyLike(alloc);
@memset(arr.buf, 0);
return arr;
}
pub fn onesLike(self: *const Ndarray(Dtype), alloc: std.mem.Allocator) @This() {
const arr = self.emptyLike(alloc);
@memset(arr.buf, 1);
return arr;
}
pub fn scalar(alloc: std.mem.Allocator, v: Dtype) @This() {
var arr = @This().init(alloc, &[_]usize{});
arr.buf[0] = v;
return arr;
}
// idx can be either a tuple like .{ 0, 3} or a []usize slice.
pub fn offset(self: *const @This(), idx: anytype) usize {
const info = @typeInfo(@TypeOf(idx));
var offs: usize = self.offs;
if (info == .Struct) {
if (!info.Struct.is_tuple) {
@compileError("Expected input idx to be a tuple-type");
}
inline for (idx, 0..) |idx_i, i| {
offs += idx_i * self.strides[i];
}
return offs;
}
// Not a tuple, assume it's a slice.
for (idx, 0..) |idx_i, i| {
offs += idx_i * self.strides[i];
}
return offs;
}
pub fn get(self: *const @This(), idx: anytype) @This() {
const offs = self.offset(idx);
return @This(){
.strides = self.strides[idx.len..],
.shape = self.shape[idx.len..],
.offs = 0,
.contiguous = self.contiguous,
.buf = self.buf[offs..(offs + shapeProd(self.shape[idx.len..]))],
};
}
pub fn getItem(self: *const @This(), idx: anytype) Dtype {
std.debug.assert(idx.len == self.shape.len);
const offs = self.offset(idx);
return self.buf[offs];
}
pub fn getContigousSlice(self: *const @This(), idx: anytype) []Dtype {
const offs = self.offset(idx);
std.debug.assert(self.contiguous);
return self.buf[offs..(offs + shapeProd(self.shape[idx.len..]))];
}
pub fn setItem(self: *const @This(), idx: anytype, v: Dtype) void {
self.buf[self.offset(idx)] = v;
}
pub fn set(self: *const @This(), dst_idx: anytype, src: @This()) void {
var view = self.get(dst_idx);
std.debug.assert(view.equalShapes(src));
view.assign(src);
}
pub fn assign(self: *@This(), other: @This()) void {
if (self.contiguous and other.contiguous and self.equalShapes(other)) {
@memcpy(self.buf, other.buf);
return;
}
// Detect transpose fast path, it goes often together with matmuls so perf matters.
// Transposes done through strides are typically made contiguous with the .clone()
// method that calls here -- in this case self/dest is always contiguous.
if (self.contiguous and self.equalShapes(other) and self.strides[1] == other.strides[0] and other.strides[1] == self.shape[0]) {
std.debug.assert(self.strides[1] == 1);
std.debug.assert(other.strides[0] == 1);
ndvec.transpose2dStrided(self.getContigousSlice(.{}), self.shape[0], self.shape[1], other.buf[other.offset(.{})..], other.strides[0], other.strides[1]);
return;
}
var dst_it = self.iterator(.{});
var src_it = other.iterator(.{ .shape = self.shape });
while (dst_it.next()) |dst| {
const src = src_it.next() orelse unreachable;
dst.* = src.*;
}
}
pub fn item(self: *const @This()) Dtype {
std.debug.assert(self.shape.len == 0 or (self.shape.len == 1 and self.shape[0] == 1));
return self.buf[self.offs];
}
pub fn fill(self: *const @This(), v: Dtype) void {
if (self.contiguous) {
@memset(self.buf[self.offs..], v);
return;
}
var it = self.iterator(.{});
while (it.next()) |d| {
d.* = v;
}
}
fn broadcastShape(alloc: std.mem.Allocator, shape_a: []const usize, shape_b: []const usize) []usize {
var new_shape = alloc.alloc(usize, @max(shape_a.len, shape_b.len)) catch unreachable;
var ai: isize = @intCast(shape_a.len);
ai -= 1;
var bi: isize = @intCast(shape_b.len);
bi -= 1;
for (0..new_shape.len) |ii| {
const i = new_shape.len - 1 - ii;
const s0 = if (ai >= 0) shape_a[@intCast(ai)] else 1;
const s1 = if (bi >= 0) shape_b[@intCast(bi)] else 1;
new_shape[i] = @max(s0, s1);
ai -= 1;
bi -= 1;
}
return new_shape;
}
fn binop(comptime op: ndvec.Binop, alloc: std.mem.Allocator, a: @This(), b: @This()) @This() {
if (a.contiguous and b.contiguous and a.equalShapes(b)) {
const dst = a.emptyLike(alloc);
if (op == .add) {
ndvec.addContiguous(dst.buf, shapeProd(dst.shape), a.buf[a.offs..], b.buf[b.offs..]);
} else {
ndvec.binop(op, dst.buf, 1, shapeProd(dst.shape), a.buf[a.offs..], 1, b.buf[b.offs..], 1);
}
return dst;
}
const shape = broadcastShape(alloc, a.shape, b.shape);
var dst = @This().init(alloc, shape);
var dst_it = dst.iterator(.{});
var a_it = a.iterator(.{ .shape = shape });
var b_it = b.iterator(.{ .shape = shape });
while (dst_it.next()) |dp| {
const ap = a_it.next() orelse unreachable;
const bp = b_it.next() orelse unreachable;
dp.* = ndvec.binopScalar(op, ap.*, bp.*);
}
return dst;
}
fn binop_(comptime op: ndvec.Binop, dst: @This(), src: @This()) void {
const same_shape = dst.equalShapes(src);
if (dst.contiguous and src.contiguous and same_shape) {
if (op == .add) {
ndvec.addContiguous_(dst.buf[dst.offs..], shapeProd(dst.shape), src.buf[src.offs..]);
} else {
ndvec.binop_(op, dst.buf[dst.offs..], 1, shapeProd(dst.shape), src.buf[src.offs..], 1);
}
return;
}
if (same_shape and dst.shape.len == 1) {
ndvec.binop_(op, dst.buf[dst.offs..], dst.strides[0], shapeProd(dst.shape), src.buf[src.offs..], src.strides[0]);
return;
}
if (same_shape and dst.shape.len == 2) {
var outer_d = dst.offs;
var outer_s = src.offs;
for (0..dst.shape[0]) |_| {
ndvec.binop_(op, dst.buf[outer_d..], dst.strides[1], dst.shape[1], src.buf[outer_s..], src.strides[1]);
outer_d += dst.strides[0];
outer_s += src.strides[0];
}
return;
}
var dst_it = dst.iterator(.{});
var src_it = src.iterator(.{ .shape = dst.shape });
while (dst_it.next()) |dp| {
const ap = src_it.next() orelse unreachable;
dp.* = ndvec.binopScalar(op, dp.*, ap.*);
}
}
pub fn add(alloc: std.mem.Allocator, a: @This(), b: @This()) @This() {
return binop(ndvec.Binop.add, alloc, a, b);
}
pub fn add_(self: @This(), other: @This()) void {
binop_(ndvec.Binop.add, self, other);
}
pub fn sub(alloc: std.mem.Allocator, a: @This(), b: @This()) @This() {
return binop(ndvec.Binop.sub, alloc, a, b);
}
pub fn sub_(self: @This(), other: @This()) void {
binop_(ndvec.Binop.sub, self, other);
}
pub fn mul(alloc: std.mem.Allocator, a: @This(), b: @This()) @This() {
return binop(ndvec.Binop.mul, alloc, a, b);
}
pub fn mul_(self: @This(), other: @This()) void {
binop_(ndvec.Binop.mul, self, other);
}
pub fn div(alloc: std.mem.Allocator, a: @This(), b: @This()) @This() {
return binop(ndvec.Binop.div, alloc, a, b);
}
pub fn div_(self: @This(), other: @This()) void {
binop_(ndvec.Binop.div, self, other);
}
pub fn reluBackwards(self: @This(), alloc: std.mem.Allocator, data: @This()) @This() {
return binop(ndvec.Binop.relu_bw, alloc, data, self);
}
pub fn unop(comptime op: ndvec.Unop, alloc: std.mem.Allocator, src: @This()) @This() {
var dst = src.emptyLike(alloc);
if (src.contiguous) {
ndvec.unop(op, dst.buf, 1, shapeProd(dst.shape), src.buf[src.offs..], 1);
return dst;
}
var dst_it = dst.iterator(.{});
var src_it = src.iterator(.{});
while (dst_it.next()) |d| {
const s = src_it.next() orelse unreachable;
d.* = ndvec.unopScalar(op, s.*);
}
return dst;
}
pub fn neg(self: @This(), alloc: std.mem.Allocator) @This() {
return unop(ndvec.Unop.neg, alloc, self);
}
pub fn clipMin(self: @This(), alloc: std.mem.Allocator, min: Dtype) @This() {
var dst = self.emptyLike(alloc);
if (self.contiguous) {
ndvec.clipMin(dst.buf, 1, shapeProd(dst.shape), self.buf[self.offs..], 1, min);
return dst;
}
var dst_it = dst.iterator(.{});
var src_it = self.iterator(.{});
while (dst_it.next()) |d| {
const s = src_it.next() orelse unreachable;
d.* = @max(min, s.*);
}
return dst;
}
pub fn exp(self: @This(), alloc: std.mem.Allocator) @This() {
return unop(ndvec.Unop.exp, alloc, self);
}
pub fn log(self: @This(), alloc: std.mem.Allocator) @This() {
return unop(ndvec.Unop.log, alloc, self);
}
pub fn argmax(self: @This()) usize {
std.debug.assert(self.shape.len == 1); // TODO this actually can't correctly return n-dim index
var it = self.iterator(.{});
var max_idx: usize = 0;
var idx: usize = 0;
var m = -std.math.inf(f32);
while (it.next()) |src| : (idx += 1) {
const val = src.*;
if (val > m) {
m = val;
max_idx = idx;
}
}
return max_idx;
}
pub fn sumOverAxis(self: @This(), alloc: std.mem.Allocator, axis: usize, keep_dims: bool) @This() {
const axis_len = self.shape[axis];
const axis_stride = self.strides[axis];
var buf: [max_dims * 8 * @sizeOf(usize)]u8 = undefined;
var fba = FixedBufSliceAlloc.init(&buf);
std.debug.assert(self.shape.len != 0);
const ndim = self.shape.len;
const ndim_m1 = ndim -| 1;
var backstrides = fba.alloc(usize, ndim_m1);
var strides = fba.alloc(usize, ndim_m1);
var shape = fba.alloc(usize, ndim_m1);
var coords = fba.alloc(usize, ndim_m1);
@memset(coords, 0);
var count: usize = 0;
for (0..ndim) |i| {
if (i != axis) {
strides[count] = self.strides[i];
shape[count] = self.shape[i];
backstrides[count] = strides[count] * (shape[count] - 1);
count += 1;
}
}
var dst_shape = shape;
if (keep_dims) {
dst_shape = fba.dupe(usize, self.shape);
dst_shape[axis] = 1;
}
var dst = Ndarray(f32).init(alloc, dst_shape);
var size: usize = shapeProd(self.shape) / axis_len;
var data_ptr: usize = self.offset(.{});
var dst_it = dst.iterator(.{});
while (size != 0) : (size -= 1) {
// Perform a sum over 'axis'.
const total = ndvec.sum(self.buf[data_ptr..], axis_stride, axis_len);
(dst_it.next() orelse unreachable).* = total;
// Iterate all the other dims that are not 'axis'
for (0..coords.len) |ii| {
const i = coords.len - 1 - ii;
if (coords[i] < shape[i] - 1) {
coords[i] += 1;
data_ptr += strides[i];
break;
} else {
coords[i] = 0;
data_ptr -= backstrides[i];
}
}
}
return dst;
}
pub const SumOpts = struct {
axis: ?usize = null,
keep_dims: bool = false,
};
pub fn sum(self: @This(), alloc: std.mem.Allocator, extra_args: SumOpts) @This() {
if (extra_args.axis) |axis| {
return self.sumOverAxis(alloc, axis, extra_args.keep_dims);
} else {
if (self.contiguous) {
const tot = ndvec.sum(self.buf[self.offs..], 1, shapeProd(self.shape));
return Ndarray(f32).scalar(alloc, tot);
}
var src_it = self.iterator(.{});
var s: Dtype = 0;
while (src_it.next()) |src| {
s += src.*;
}
return Ndarray(f32).scalar(alloc, s);
}
}
// TODO this should be implemented in with gemm
pub fn dot(alloc: std.mem.Allocator, a: @This(), b: @This()) @This() {
if (a.shape.len == 1 and (b.shape.len == 0 or b.shape.len == 1)) {
if (a.shape.len == b.shape.len) {
std.debug.assert(@This().equalShapes(a, b));
}
std.debug.assert(a.shape[0] == b.shape[0]);
var a_it = a.iterator(.{});
var b_it = b.iterator(.{ .shape = a.shape });
var s: Dtype = 0;
while (a_it.next()) |av| {
const bv = b_it.next() orelse unreachable;
s += av.* * bv.*;
}
return @This().scalar(alloc, s);
} else if (a.shape.len == 2 and b.shape.len == 1) {
// TODO could do this with GEMM too
std.debug.assert(compareShapes(a.shape[1..], b.shape));
var dst = @This().init(alloc, &[_]usize{a.shape[0]});
for (0..a.shape[0]) |i| {
const aa = a.get(.{i});
const s = ndvec.innerProduct(aa.buf, aa.strides[0], aa.shape[0], b.buf, b.strides[0]);
dst.setItem(.{i}, s);
}
return dst;
} else if (a.shape.len == 2 and b.shape.len == 2) {
// TODO b transposed is common
var dst = @This().init(alloc, &[_]usize{ a.shape[0], b.shape[1] });
const a_lin = if (a.contiguous) a else a.clone(alloc);
const b_lin = if (b.contiguous) b else b.clone(alloc);
dst.addmm_(a_lin, b_lin, .{ .beta = 0 });
return dst;
}
std.debug.print("a b {any} {any}\n", .{ a.shape, b.shape });
unreachable; // TODO unimplemented
}
pub fn addmm_(dest: @This(), a: @This(), b: @This(), opts: AddMmOpts) void {
const M = if (opts.transpose_a) a.shape[1] else a.shape[0];
const N = if (opts.transpose_b) b.shape[0] else b.shape[1];
const K = if (opts.transpose_a) a.shape[0] else a.shape[1];
const A = a.buf[a.offset(.{})..];
const B = b.buf[b.offset(.{})..];
const C = dest.buf[dest.offset(.{})..];
std.debug.assert(dest.shape[0] == M and dest.shape[1] == N);
std.debug.assert(a.strides[1] == 1 and b.strides[1] == 1);
const lda = a.strides[0];
const ldb = b.strides[0];
const ldc = dest.strides[0];
gemm.gemm(opts.transpose_a, opts.transpose_b, M, N, K, opts.alpha, A, lda, B, ldb, opts.beta, C, ldc);
}
// Shape can be either a []usize slice or a tuple. Tuple allows specifying
// one axis as "unknown" with -1 in which case its size will be inferred.
//
// Only the tuple path supports -1 since it's not convenient to make the shape
// type signed integer.
pub fn reshape(self: @This(), alloc: std.mem.Allocator, shape: anytype) @This() {
var new_arr: @This() = self;
new_arr.shape = inferShape(alloc, self.shape, shape);
new_arr.strides = alloc.alloc(usize, shape.len) catch unreachable;
const stride_prod = @This().initStrides(new_arr.strides, new_arr.shape);
std.debug.assert(stride_prod == new_arr.buf.len);
return new_arr;
}
pub fn transpose(self: *const @This(), alloc: std.mem.Allocator, opts: TransposeOpts) @This() {
var new_arr: @This() = undefined;
new_arr = self.*;
new_arr.shape = alloc.alloc(usize, self.shape.len) catch unreachable;
new_arr.strides = alloc.alloc(usize, self.shape.len) catch unreachable;
new_arr.contiguous = false;
if (opts.axes) |permute| {
for (0..self.shape.len) |i| {
new_arr.strides[i] = self.strides[permute[i]];
new_arr.shape[i] = self.shape[permute[i]];
}
} else {
for (0..self.shape.len) |i| {
const rev = self.shape.len - 1 - i;
new_arr.strides[i] = self.strides[rev];
new_arr.shape[i] = self.shape[rev];
}
}
return new_arr;
}
pub fn padForConv2d(self: *const @This(), alloc: std.mem.Allocator, padding: usize) @This() {
_ = alloc;
// implement zero padding like: np.pad(x, ((0, 0), (0, 0), (pad, pad), (pad, pad)), mode='constant')
std.debug.assert(padding == 0); // TODO pad all sides
return self.*;
}
pub fn unfold(x: @This(), alloc: std.mem.Allocator, kw: usize, kh: usize, opts: Conv2dOpts) @This() {
std.debug.assert(x.shape.len == 3); // only single sample support
std.debug.assert(kw == 3 and kh == 3); // only 3x3 support for now
const H = x.shape[1];
const W = x.shape[2];
const C = x.shape[0];
const stride = opts.stride;
const h_out = 1 + (H + 2 * opts.pad - kh) / stride;
const w_out = 1 + (W + 2 * opts.pad - kw) / stride;
const out = @This().init(alloc, &[_]usize{ kh * kw * x.shape[0], h_out * w_out });
const xp_n = x.getContigousSlice(.{});
for (0..h_out) |i| {
for (0..w_out) |j| {
// Collect pixels for dot product between image patch and the filter kernel.
var xtmpd = out.getContigousSlice(.{ 0, j + w_out * i }).ptr;
const col_stride = out.strides[0]; // TODO minibatch dim xmat is sized for N matrices
var xpd = xp_n.ptr + (i * stride) * x.strides[1] + (j * stride);
const xpd_stride = x.strides[0] - x.strides[1] * 2;
// unfold 3x3 patch -> linear output
for (0..C) |_| {
xtmpd[0] = xpd[0];
xtmpd += col_stride;
xtmpd[0] = xpd[1];
xtmpd += col_stride;
xtmpd[0] = xpd[2];
xtmpd += col_stride;
xpd += x.strides[1];
xtmpd[0] = xpd[0];
xtmpd += col_stride;
xtmpd[0] = xpd[1];
xtmpd += col_stride;
xtmpd[0] = xpd[2];
xtmpd += col_stride;
xpd += x.strides[1];
xtmpd[0] = xpd[0];
xtmpd += col_stride;
xtmpd[0] = xpd[1];
xtmpd += col_stride;
xtmpd[0] = xpd[2];
xtmpd += col_stride;
xpd += xpd_stride;
}
}
}
return out;
}
pub fn fold(x: @This(), alloc: std.mem.Allocator, output_size: []const usize, kw: usize, kh: usize, opts: Conv2dOpts) @This() {
std.debug.assert(x.shape.len == 2); // only single sample support
std.debug.assert(kw == 3 and kh == 3); // only 3x3 support for now
const C = x.shape[0] / (kh * kw);
const stride = opts.stride;
const h_out = 1 + (output_size[0] + 2 * opts.pad - kh) / stride;
const w_out = 1 + (output_size[1] + 2 * opts.pad - kw) / stride;
const out = @This().init(alloc, &[_]usize{ C, output_size[0], output_size[1] });
out.fill(0);
const dst = out.getContigousSlice(.{});
for (0..h_out) |i| {
for (0..w_out) |j| {
// Collect pixels for dot product between image patch and the filter kernel.
var srcp = x.getContigousSlice(.{ 0, j + w_out * i }).ptr;
const src_col_stride = x.strides[0];
var dstp = dst.ptr + (i * stride) * out.strides[1] + (j * stride);
const out_stride = out.strides[0] - out.strides[1] * 2;
for (0..C) |_| {
dstp[0] += srcp[0];
srcp += src_col_stride;
dstp[1] += srcp[0];
srcp += src_col_stride;
dstp[2] += srcp[0];
srcp += src_col_stride;
dstp += out.strides[1];
dstp[0] += srcp[0];
srcp += src_col_stride;
dstp[1] += srcp[0];
srcp += src_col_stride;
dstp[2] += srcp[0];
srcp += src_col_stride;
dstp += out.strides[1];
dstp[0] += srcp[0];
srcp += src_col_stride;
dstp[1] += srcp[0];
srcp += src_col_stride;
dstp[2] += srcp[0];
srcp += src_col_stride;
dstp += out_stride;
}
}
}
return out;
}
// x: Input (shape: N, C, H, W)
// w: Weights (shape: F, C, HH, WW)
pub fn conv2d(alloc: std.mem.Allocator, x: @This(), w: @This(), opts: Conv2dOpts) @This() {
std.debug.assert(x.shape.len == 4);
const N = x.shape[0];
const C = x.shape[1];
const H = x.shape[2];
const W = x.shape[3];
const C_out = w.shape[0];
const C_in = w.shape[1];
std.debug.assert(C_in == C);
const kh = w.shape[2];
const kw = w.shape[3];
const stride = opts.stride;
const h_out = 1 + (H + 2 * opts.pad - kh) / stride;
const w_out = 1 + (W + 2 * opts.pad - kw) / stride;
// Try to tell the compiler that all the loops are non-zero length.
if (N == 0 or C_out == 0 or C == 0 or h_out == 0 or w_out == 0 or kh == 0 or kw == 0) {
unreachable;
}
const x_padded = x.padForConv2d(alloc, opts.pad);
var out = @This().init(alloc, &[_]usize{ N, C_out, h_out, w_out });
std.debug.assert(x_padded.strides[3] == 1);
const w_col = w.reshape(alloc, &[_]usize{ C_out, w.shape[1] * w.shape[2] * w.shape[3] });
for (0..N) |n| {
const xmat = x_padded.get(.{n}).unfold(alloc, kw, kh, opts);
const out_view = out.get(.{n}).reshape(alloc, &[_]usize{ C_out, h_out * w_out });
out_view.addmm_(w_col, xmat, .{ .beta = 0 });
}
return out;
}
// x: Input (shape: N, C, H, W)
// w: Weights (shape: F, C, HH, WW)
pub fn conv2dBackwards(alloc: std.mem.Allocator, x: @This(), w: @This(), dout: @This(), opts: Conv2dOpts) Conv2dGrads {
std.debug.assert(x.shape.len == 4);
const N = x.shape[0];
const C = x.shape[1];
const C_out = w.shape[0];
const C_in = w.shape[1];
std.debug.assert(C_in == C);
const kh = w.shape[2];
const kw = w.shape[3];
const x_padded = x.padForConv2d(alloc, opts.pad);
const dx = x_padded.zerosLike(alloc);
var dw = w.zerosLike(alloc);
std.debug.assert(x_padded.strides[3] == 1);
// Try to tell the compiler that all the loops are non-zero length.
if (N == 0 or C_out == 0 or C == 0 or kh == 0 or kw == 0) {
unreachable;
}
const dw_col = @This().init(alloc, &[_]usize{ C_out, w.shape[1] * w.shape[2] * w.shape[3] });
dw_col.fill(0);
const w_col = w.reshape(alloc, &[_]usize{ C_out, w.shape[1] * w.shape[2] * w.shape[3] });
const dx_col = @This().init(alloc, &[_]usize{ w.shape[1] * w.shape[2] * w.shape[3], dout.shape[2] * dout.shape[3] });
for (0..N) |n| {
const x_col = x_padded.get(.{n}).unfold(alloc, kw, kh, opts);
const doutr = dout.get(.{n}).reshape(alloc, &[_]usize{ dout.shape[1], dout.shape[2] * dout.shape[3] });
dw_col.addmm_(doutr, x_col, .{ .transpose_b = true });
dx_col.addmm_(w_col, doutr, .{ .transpose_a = true, .beta = 0 });
const dxtmp = dx_col.fold(alloc, x.shape[2..], kw, kh, opts);
dx.get(.{n}).add_(dxtmp);
}
dw.add_(dw_col.reshape(alloc, &[_]usize{ dw_col.shape[0], C, kh, kw }));
return Conv2dGrads{
.dw = dw,
.dx = dx,
};
}
// x: Input (shape: N, C, H, W)
// hardcoded to kernel size 2, stride 2
pub fn avgpool2d(alloc: std.mem.Allocator, x: @This()) @This() {
std.debug.assert(x.shape.len == 4);
const N = x.shape[0];
const C = x.shape[1];
const H = x.shape[2];
const W = x.shape[3];
const h_out = H / 2;
const w_out = W / 2;
const out = @This().init(alloc, &[_]usize{ N, C, h_out, w_out });
for (0..N) |n| {
for (0..C) |c| {
for (0..h_out) |i| {
for (0..w_out) |j| {
var total: f32 = 0;
total += x.getItem(.{ n, c, i * 2, j * 2 });
total += x.getItem(.{ n, c, i * 2, j * 2 + 1 });
total += x.getItem(.{ n, c, i * 2 + 1, j * 2 });
total += x.getItem(.{ n, c, i * 2 + 1, j * 2 + 1 });
out.setItem(.{ n, c, i, j }, total * 0.25);
}
}
}
}
return out;
}
// x: Input (shape: N, C, H, W)
pub fn avgpool2dBackwards(alloc: std.mem.Allocator, x: @This(), dout: @This()) @This() {
std.debug.assert(x.shape.len == 4);
const N = dout.shape[0];
const C = dout.shape[1];
const H = dout.shape[2];
const W = dout.shape[3];
const out = @This().init(alloc, &[_]usize{ N, C, x.shape[2], x.shape[3] });
for (0..N) |n| {
for (0..C) |c| {
for (0..H) |i| {
for (0..W) |j| {
const v = dout.getItem(.{ n, c, i, j }) * 0.25;
out.setItem(.{ n, c, i * 2, j * 2 }, v);
out.setItem(.{ n, c, i * 2 + 1, j * 2 }, v);
out.setItem(.{ n, c, i * 2, j * 2 + 1 }, v);
out.setItem(.{ n, c, i * 2 + 1, j * 2 + 1 }, v);
}
}
}
}
return out;
}
// x: Input (shape: N, C, H, W)
// idx: Idx of the max element in 2x2 blocks of input
// hardcoded to kernel size 2, stride 2
pub fn maxpool2d(alloc: std.mem.Allocator, x: @This()) Maxpool2dRes {
std.debug.assert(x.shape.len == 4);
const N = x.shape[0];
const C = x.shape[1];
const H = x.shape[2];
const W = x.shape[3];
const h_out = H / 2;
const w_out = W / 2;
const out = @This().init(alloc, &[_]usize{ N, C, h_out, w_out });
const idx = alloc.alloc(u8, N * C * h_out * w_out) catch unreachable;
var out_slice = out.getContigousSlice(.{});
var out_idx: usize = 0;
for (0..N) |n| {
for (0..C) |c| {
for (0..h_out) |ii| {
var src = x.getContigousSlice(.{ n, c, ii * 2 }).ptr;
for (0..w_out) |jj| {
var i: u8 = 0;
var a = src[0];
const s01 = if (jj * 2 + 1 < W) src[1] else -std.math.inf(f32);
const s10 = if (ii * 2 + 1 < H) src[x.strides[2]] else -std.math.inf(f32);
const s11 = if (jj * 2 + 1 < W and ii * 2 + 1 < H) src[1 + x.strides[2]] else -std.math.inf(f32);
if (s01 > a) {
a = s01;
i = 1;
}
if (s10 > a) {
a = s10;
i = 2;
}
if (s11 > a) {
a = s11;
i = 3;
}