Repository navigation
Expand file tree
/
Copy pathtrain_unet.cu
More file actions
5074 lines (4534 loc) · 182 KB
/
Copy pathtrain_unet.cu
File metadata and controls
5074 lines (4534 loc) · 182 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
#include <cuda_runtime_api.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "utils.cuh"
#include <curand_kernel.h>
#include <cooperative_groups.h>
#include <amd_common.cuh>
#ifndef BUILD_AMD
#include <cooperative_groups/reduce.h>
#include <cuda_device_runtime_api.h>
#endif
#include <string.h>
#include <sys/stat.h> // For mkdir
#include <sys/types.h> // For mode_t
namespace cg = cooperative_groups;
// ------------------------------------------------------------------------------------------------
// Linear layer
typedef struct {
float* w; // OC, C
float* b; // OC
} LinearParams;
typedef struct {
float* inp; // N, C
float* out; // N, OC
} LinearActs;
void linear_set_param_ptrs(
LinearParams* params,
float* params_memory,
int C, int OC
) {
params->w = params_memory;
params_memory += OC * C;
params->b = params_memory;
}
inline size_t linear_count_params(int C, int OC) {
return OC * C + OC;
}
// ---------------------------------------------
// kernels
// copy the matmul forward and backward kernels from llm.c
// is there no better way other than just adding bias with a whole separate kernel?
// this is a highly memory-bound operation, should be fused into the matmul kernel
// but i can't seem to find a cuBLAS function that does this
__global__ void add_bias(float* out, const float* bias, int N, int OC) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int stride = blockDim.x * gridDim.x;
for (int i = idx; i < N * OC; i += stride) {
int col = i % OC;
out[i] += bias[col];
}
}
// kernel 2 calls cuBLAS, which should be very efficient
void matmul_forward2(cublasHandle_t cublas_handle,
float* out,
const float* inp, const float* weight, const float* bias,
int N, int C, int OC,
const int block_size) {
// for reference API is:
// cublasStatus_t cublasSgemm(cublasHandle_t handle,
// cublasOperation_t transa, cublasOperation_t transb,
// int m, int n, int k,
// const float *alpha,
// const float *A, int lda,
// const float *B, int ldb,
// const float *beta,
// float *C, int ldc)
// for us, inp is (B*T, C), weight is (OC, C), out is (B*T, OC)
// cuBLAS does C = alpha * A * B + beta * C
// where A is mxk, B is kxn, C is mxn
// now, because we use row-major storage, cuBLAS (which is column-major) sees our matrices transposed.
// algorithmically / in e.g. PyTorch we want to do: out = inp @ weight.T
// but because cuBLAS is column-major, we actually want to get it to calculate out.T . Mathematically, this is:
// out.T = weight @ inp.T
// but again, our variables look transposed, so using the actual weight/inp we have here in this function, this becomes
// out.T = weight.T @ inp
// so we need to get cuBLAS to calculate weight.T @ inp (the variables here are the actual ones in this function)
// => need to call cuBLAS with A = weight, B = inp
// => need to call cuBLAS with transa = CUBLAS_OP_T, transb = CUBLAS_OP_N
const float alpha = 1.0f;
const float beta = 0.0f;
cublasCheck(cublasSgemm(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_N, OC, N, C, &alpha, weight, C, inp, C, &beta, out, OC));
// and now we still have to add the bias... (ew)
if (bias != NULL) {
int grid_size = ceil_div(OC * N, block_size);
add_bias<<<grid_size, block_size>>>(out, bias, N, OC);
cudaCheck(cudaGetLastError());
}
}
// use shared memory and coarsening + reductions
__global__ void matmul_backward_bias_kernel_faster(float* dbias, const float* dout, int N, int OC) {
extern __shared__ float shared[];
int o = blockIdx.x; // range [0, OC)
int tid = threadIdx.x; // range [0, block_size)
int block_size = blockDim.x;
const float* x = dout + o;
// thread coarsening
double sum = 0.0;
for (int i = tid; i < N; i += block_size) {
sum += x[i * OC];
}
shared[tid] = (float) sum;
__syncthreads();
// reductions
for (int stride = block_size / 2; stride >= 1; stride /= 2) {
__syncthreads();
if (tid < stride) {
shared[tid] += shared[tid + stride];
}
}
// write the final result (at thread 0) to global memory
if (tid == 0) {
dbias[o] = shared[0];
}
}
// version1: simple cuBLAS calls
void matmul_backward1(cublasHandle_t cublas_handle,
float* dinp, float* dweight, float* dbias,
float* dout, float* inp, float* weight,
int N, int C, int OC) {
float alpha = 1.0f;
float beta = 0.0f; // note we must use beta = 1.0 so that we do a +=, as we should, because gradients add
// for reference the API is:
// cublasStatus_t cublasSgemm(cublasHandle_t handle,
// cublasOperation_t transa, cublasOperation_t transb,
// int m, int n, int k,
// const float *alpha,
// const float *A, int lda,
// const float *B, int ldb,
// const float *beta,
// float *C, int ldc)
// recall the forward pass was calculated with alpha = 1.0f, beta = 0.0f as:
// cublasSgemm(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_N, OC, B*T, C, &alpha, weight, C, inp, C, &beta, out, OC);
// backward to input
cublasCheck(cublasSgemm(cublas_handle, CUBLAS_OP_N, CUBLAS_OP_N, C, N, OC, &alpha, weight, C, dout, OC, &beta, dinp, C));
// backward to weight
cublasCheck(cublasSgemm(cublas_handle, CUBLAS_OP_N, CUBLAS_OP_T, C, OC, N, &alpha, inp, C, dout, OC, &beta, dweight, C));
// backward to bias, if given
if (dbias != NULL) {
// sum over B,T using matrix vector multiplication with cuBLAS
// for reference this API is:
// cublasStatus_t cublasSgemv(cublasHandle_t handle, cublasOperation_t trans,
// int m, int n,
// const float *alpha,
// const float *A, int lda,
// const float *x, int incx,
// const float *beta,
// float *y, int incy)
// dout is (B,T,OC), or in 2D terms (B*T, OC)
// cublasCheck(cublasSgemv(cublas_handle, CUBLAS_OP_N, B*T, OC, &alpha, dout, B*T, ones, 1, &beta, dbias, 1));
// cublasCheck(cublasSgemv(cublas_handle, CUBLAS_OP_T, OC, B*T, &alpha, dout, OC, ones, 1, &beta, dbias, 1));
// ugh the above isn't working...
// let's just do naive calculation for now, fix later
// const int block_size=128;
// const int grid_size=(OC + block_size - 1) / block_size;
// matmul_backward_bias_kernel<<<grid_size, block_size>>>(dbias, dout, B, T, OC);
// bit faster
const int block_size=512;
dim3 block_dim(block_size);
dim3 grid_dim(OC);
size_t shared_mem_size = block_size * sizeof(float);
matmul_backward_bias_kernel_faster<<<grid_dim, block_dim, shared_mem_size>>>(dbias, dout, N, OC);
}
}
// ------------------------------------------------------------------------------------------------
// Broadcast tensor layer
// kernel to broadcast a tensor from shape (B, C) to (B, C, H, W)
// Assuming one thread per pixel
__global__ void broadcast_last_dims_forward_kernel(
const float* x,
float* out,
int N, int H, int W, int n_bk_per_img
) {
int n = blockIdx.x / n_bk_per_img;
__shared__ float x_sh[1];
if (threadIdx.x == 0) {
x_sh[0] = x[n];
}
__syncthreads();
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < N * H * W) {
out[idx] = x_sh[0];
}
}
void broadcast_last_dims_forward(
const float* x,
float* out,
int N, int H, int W, int block_size
) {
block_size = min_int(block_size, H * W);
int n_bk_per_img = ceil_div(H * W, block_size);
broadcast_last_dims_forward_kernel<<<N * n_bk_per_img, block_size>>>(x, out, N, H, W, n_bk_per_img);
};
// backwards for broadcast
// use one warp per image
__global__ void broadcast_last_dims_backward_kernel(
const float* dout,
float* dx,
int N, int H, int W
) {
cg::thread_block block = cg::this_thread_block();
cg::thread_block_tile<32> warp = cg::tiled_partition<32>(block);
int idx = blockIdx.x * warp.meta_group_size() + warp.meta_group_rank();
if (idx >= N) { return; }
int img_size = H * W;
dout += idx * img_size;
dx += idx;
float sum = 0.0f;
for (int i = warp.thread_rank(); i < img_size; i += warp.size()) {
sum += dout[i];
}
sum = cg::reduce(warp, sum, cg::plus<float>());
if (warp.thread_rank() == 0) {
dx[0] = sum;
}
}
void broadcast_last_dims_backward(
const float* dout,
float* dx,
int N, int H, int W, int block_size
) {
block_size = min_int(block_size, H * W);
assert(block_size % 32 == 0);
int warps_per_block = block_size / 32;
int gridDim = ceil_div(N, warps_per_block);
broadcast_last_dims_backward_kernel<<<gridDim, block_size>>>(dout, dx, N, H, W);
};
// ------------------------------------------------------------------------------------------------
// Add layer
__global__ void add_forward_kernel(
const float* a, const float* b,
float* out,
int N
) {
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < N) {
out[idx] = a[idx] + b[idx];
}
}
void add_forward(
const float* a, const float* b,
float* out,
int N, int block_size
) {
int n_blk = ceil_div(N, block_size);
add_forward_kernel<<<n_blk, block_size>>>(a, b, out, N);
}
// add A and B in place, and store result in B
__global__ void add_inplace_forward_kernel(
const float* a, float* b,
int N
) {
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < N) {
b[idx] += a[idx];
}
}
void add_inplace_forward(
const float* a, float* b,
int N, int block_size
) {
int n_blk = ceil_div(N, block_size);
add_inplace_forward_kernel<<<n_blk, block_size>>>(a, b, N);
}
// ------------------------------------------------------------------------------------------------
// SiLU layer
typedef struct {
float* x;
float* out;
} SiluActs;
// ----------------------------------------------
// kernels
__global__ void silu_forward_kernel(
const float* x,
float* out,
int N
) {
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx >= N) {
return;
}
float x_val = x[idx];
out[idx] = x_val / (1.0f + expf(-x_val));
}
void silu_forward(
const float* x,
float* out,
int N, int block_size
) {
int n_blk = ceil_div(N, block_size);
silu_forward_kernel<<<n_blk, block_size>>>(x, out, N);
}
__global__ void silu_backward_kernel(
const float* dout, const float* x,
float* dx,
int N
) {
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx >= N) {
return;
}
float out_val = dout[idx];
float x_val = x[idx];
float expx = expf(-x_val);
float grad_silu = (1.0f + x_val * expx / (1.0f + expx)) / (1.0f + expx);
dx[idx] = out_val * grad_silu;
}
void silu_backward(
const float* dout, const float* x,
float* dx,
int N, int block_size
) {
int n_blk = ceil_div(N, block_size);
silu_backward_kernel<<<n_blk, block_size>>>(dout, x, dx, N);
}
// ------------------------------------------------------------------------------------------------
// Upsample
typedef struct {
float* x;
float* out;
} UpsampleActs;
// one thread per pixel
__global__ void upsample_forward_kernel(
const float* x,
float* out,
int B, int C, int H, int W
) {
int flat_idx = blockDim.x * blockIdx.x + threadIdx.x;
int img_size = H * W;
if (flat_idx >= B * C * img_size) {
return;
}
int H_out = H*2;
int W_out = W*2;
int img_out_size = H_out * W_out;
int b = flat_idx / (C * img_size);
int c = (flat_idx / img_size) % C;
int i = (flat_idx / W) % H;
int j = flat_idx % W;
// move pointers
x += b * C * img_size + c * img_size + i * W + j;
out += b * C * img_out_size + c * img_out_size + 2 * i * W_out + 2 * j;
float x_val = x[0];
for (int ii = 0; ii < 2; ii++) {
for (int jj = 0; jj < 2; jj++) {
out[ii * W_out + jj] = x_val;
}
}
}
void upsample_forward1(
float* out,
const float* x,
int B, int C, int H, int W,
int block_size
) {
int gridDim = ceil_div(B * C * H * W, block_size);
upsample_forward_kernel<<<gridDim, block_size>>>(x, out, B, C, H, W);
cudaCheck(cudaGetLastError());
}
// number of threads equals the number of pixels
// in downsampled image
__global__ void upsample_backward_kernel(
const float* dout,
float* dx,
int B, int C, int H, int W
) {
int flat_idx = blockDim.x * blockIdx.x + threadIdx.x;
int img_in_size = H * W;
if (flat_idx >= B * C * img_in_size) {
return;
}
int H_out = H*2;
int W_out = W*2;
int img_out_size = H_out * W_out;
int b = flat_idx / (C * img_in_size);
int c = (flat_idx / img_in_size) % C;
int i = (flat_idx / W) % H;
int j = flat_idx % W;
// move pointers
dx += b * C * img_in_size + c * img_in_size + i * W + j;
dout += b * C * img_out_size + c * img_out_size + 2 * i * W_out + 2 * j;
float dout_sum = 0.0f;
for (int ii = 0; ii < 2; ii++) {
for (int jj = 0; jj < 2; jj++) {
dout_sum += dout[ii * W_out + jj];
}
}
dx[0] = dout_sum;
}
void upsample_backward1(
float* dx,
const float* dout,
int B, int C, int H, int W,
int block_size
) {
int gridDim = ceil_div(B * C * H * W, block_size);
upsample_backward_kernel<<<gridDim, block_size>>>(dout, dx, B, C, H, W);
cudaCheck(cudaGetLastError());
}
// ------------------------------------------------------------------------------------------------
// Avgpool layer
typedef struct {
float* x;
float* out;
} AvgpoolActs;
__global__ void avgpool_2d_forward_kernel(
const float* x, // (B, C, H, W)
float* out, // (B, C, H/2, W/2)
int B, int C, int H, int W
) {
//printf("started kernel\n");
int flat_idx = blockDim.x * blockIdx.x + threadIdx.x;
int H_2 = H / 2;
int W_2 = W / 2;
int img_out_size = H_2 * W_2;
if (flat_idx >= B * C * img_out_size) {
return;
}
int img_size = H * W;
int b = flat_idx / (C * img_out_size);
int c = (flat_idx / img_out_size) % C;
int i = (flat_idx / W_2) % H_2;
int j = flat_idx % W_2;
// move pointers
x += b * C * img_size + c * img_size + 2 * i * W + 2 * j;
out += b * C * img_out_size + c * img_out_size + i * W_2 + j;
float sum = 0.0f;
for (int ii = 0; ii < 2; ii++) {
for (int jj = 0; jj < 2; jj++) {
sum += x[ii * W + jj];
}
}
out[0] = sum / 4.0f;
}
void avgpool_2d_forward1(
float* out,
const float* x,
int B, int C, int H, int W,
const int block_size
) {
int gridDim = ceil_div(B * C * (H / 2) * (W / 2), block_size);
avgpool_2d_forward_kernel<<<gridDim, block_size>>>(x, out, B, C, H, W);
cudaCheck(cudaGetLastError());
}
__global__ void avgpool_2d_backward_kernel(
const float* dout,
float* dx,
int B, int C, int H_out, int W_out // H_out and W_out are the shape of the output from forward, i.e. half the original sizes
) {
int flat_idx = blockDim.x * blockIdx.x + threadIdx.x;
int img_out_size = H_out * W_out;
if (flat_idx >= B * C * img_out_size) {
return;
}
int H_in = H_out * 2;
int W_in = W_out * 2;
int img_in_size = H_in * W_in;
int b = flat_idx / (C * img_out_size);
int c = (flat_idx / img_out_size) % C;
int i = (flat_idx / W_out) % H_out;
int j = flat_idx % W_out;
// move pointers
dout += b * C * img_out_size + c * img_out_size + i * W_out + j;
dx += b * C * img_in_size + c * img_in_size + 2 * i * W_in + 2 * j;
float d = dout[0] / 4.0f;
for (int ii = 0; ii < 2; ii++) {
for (int jj = 0; jj < 2; jj++) {
dx[ii * W_in + jj] = d;
}
}
}
void avgpool_2d_backward1(
const float* dout,
float* dx,
int B, int C, int H, int W,
const int block_size
) {
int H_out = H / 2;
int W_out = W / 2;
int gridDim = ceil_div(B * C * H_out * W_out, block_size);
avgpool_2d_backward_kernel<<<gridDim, block_size>>>(dout, dx, B, C, H_out, W_out);
cudaCheck(cudaGetLastError());
}
// ------------------------------------------------------------------------------------------------
// Concat channel layer
// used to concat unet skip connections in the channel dimension
typedef struct {
float* x1;
float* x2;
float* out;
} ConcatChannelActs;
__global__ void concat_channel_forward_kernel(
const float* x1, const float* x2,
float* out,
int B, int C1, int C2, int H, int W
) {
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < B * C1 * H * W) {
// copy input from x1
int b = idx / (C1 * H * W);
int c = (idx / H / W) % C1;
int h = (idx / W) % H;
int w = idx % W;
int out_idx = b * (C1 + C2) * H * W + c * H * W + h * W + w;
out[out_idx] = x1[idx];
}
if (idx < B * C2 * H * W) {
// copy input from x2
// move over from x1
int b = idx / (C2 * H * W);
int c = (idx / H / W) % C2;
int h = (idx / W) % H;
int w = idx % W;
int out_idx = b * (C1 + C2) * H * W + (C1 + c) * H * W + h * W + w;
out[out_idx] = x2[idx];
}
}
void concat_channel_forward(
const float* x1, const float* x2,
float* out,
int B, int C1, int C2, int H, int W, int block_size
) {
int N = B * max_int(C1, C2) * H * W;
int n_blk = ceil_div(N, block_size);
concat_channel_forward_kernel<<<n_blk, block_size>>>(x1, x2, out, B, C1, C2, H, W);
}
__global__ void concat_channel_backward_kernel(
const float* dout,
float* dx1, float* dx2,
int B, int C1, int C2, int H, int W
) {
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < B * C1 * H * W) {
int b = idx / (C1 * H * W);
int c = (idx / H / W) % C1;
int h = (idx / W) % H;
int w = idx % W;
int out_idx = b * (C1 + C2) * H * W + c * H * W + h * W + w;
dx1[idx] = dout[out_idx];
}
if (idx < B * C2 * H * W) {
int b = idx / (C2 * H * W);
int c = (idx / H / W) % C2;
int h = (idx / W) % H;
int w = idx % W;
int out_idx = b * (C1 + C2) * H * W + (C1 + c) * H * W + h * W + w;
dx2[idx] = dout[out_idx];
}
}
void concat_channel_backward(
const float* dout,
float* dx1, float* dx2,
int B, int C1, int C2, int H, int W, int block_size
) {
int N = B * max_int(C1, C2) * H * W;
int n_blk = ceil_div(N, block_size);
concat_channel_backward_kernel<<<n_blk, block_size>>>(dout, dx1, dx2, B, C1, C2, H, W);
}
// ------------------------------------------------------------------------------------------------
// Conv2d 1x1 layer
template <const int BO, const int BH, const int TO, const int TH>
__global__ void conv2d_k1_forward_kernel(
const float* x, const float* weight, const float* bias,
float* out,
int B, int C, int H, int W, int O
) {
// constants
const int BC = 16;
assert(O % BO == 0);
assert(C % BC == 0);
assert(H * W % BH == 0);
// n_threads per block = (BO * BH) / (TO * TH) = 256
// n_blocks = B * (O / BO) * (H * W / BH)
// set gridDim to (BxHxW / BH, O / BO)
const int block_row = blockIdx.y;
const int blocks_per_col = H * W / BH;
assert(gridDim.x == B * blocks_per_col);
const int block_col = blockIdx.x % blocks_per_col;
const int batch = blockIdx.x / blocks_per_col;
const int threads_per_col = BH / TH;
const int thread_col = threadIdx.x % threads_per_col;
const int thread_row = threadIdx.x / threads_per_col;
// shared mem for weight and x
const int weight_s_sz = BO * BC;
const int x_s_sz = BC * BH;
__shared__ float w_s[weight_s_sz];
__shared__ float x_s[x_s_sz];
// local registers for results;
float thread_results[TO * TH] = {0.0};
float reg_w[TO] = {0.0};
float reg_x[TH] = {0.0};
// get offsets to x and weight
int x_block_offset = batch * C * H * W + block_col * BH;
int w_block_offset = block_row * BO * C;
for (int c_idx = 0; c_idx < C; c_idx += BC) {
int x_inner_offset = c_idx * H * W;
int w_inner_offset = c_idx;
// load weights to smem
for (int i = threadIdx.x; i < weight_s_sz; i += blockDim.x) {
int w_i = i / BC;
int w_j = i % BC;
int w_abs_idx = w_block_offset + w_inner_offset + w_i * C + w_j;
w_s[w_i * BC + w_j] = weight[w_abs_idx];
}
for (int i = threadIdx.x; i < x_s_sz; i += blockDim.x) {
int x_i = i / BH;
int x_j = i % BH;
int x_abs_idx = x_block_offset + x_inner_offset + x_i * H * W + x_j;
x_s[x_i * BH + x_j] = x[x_abs_idx];
}
__syncthreads();
// calculate thread results
for (int dot_idx = 0; dot_idx < BC; dot_idx++) {
for (int i = 0; i < TO; i++) {
reg_w[i] = w_s[(thread_row * TO + i) * BC + dot_idx];
}
for (int j = 0; j < TH; j++) {
reg_x[j] = x_s[dot_idx * BH + thread_col * TH + j];
}
for (int i = 0; i < TO; i++) {
for (int j = 0; j < TH; j++) {
thread_results[i * TH + j] += reg_w[i] * reg_x[j];
}
}
}
__syncthreads();
}
// write out results
// set out and bias directly to thread offset
int out_block_offset = batch * O * H * W + block_row * BO * H * W + block_col * BH;
int bias_offset = block_row * BO;
for (int i = 0; i < TO; i++) {
for (int j = 0; j < TH; j++) {
int bias_idx = bias_offset + thread_row * TO + i;
float out_val = thread_results[i * TH + j] + bias[bias_idx];
int out_idx = out_block_offset + thread_row * TO * H * W + thread_col * TH + i * H * W + j;
atomicAdd(out + out_idx, out_val);
}
}
}
void conv2d_k1_forward2(
const float* x, const float* weight, const float* bias,
float* out,
int B, int C_in, int H, int W, int C_out
) {
cudaCheck(cudaMemset(out, 0, B * C_out * H * W * sizeof(float)));
const int BO = 64;
const int BH = 64;
const int TO = 4;
const int TH = 4;
dim3 gridDim(B * H * W / BH, C_out / BO);
dim3 blockDim((BO * BH) / (TO * TH));
conv2d_k1_forward_kernel<BO, BH, TO, TH><<<gridDim, blockDim>>>(x, weight, bias, out, B, C_in, H, W, C_out);
}
__global__ void permute_dout_x_kernel(
const float* x, const float* dout,
float* x_perm, float* dout_perm,
int B, int C_in, int C_out, int H, int W
) {
int flat_idx = blockIdx.x * blockDim.x + threadIdx.x;
int img_size = H * W;
int h = (flat_idx / W) % H;
int w = flat_idx % W;
if (flat_idx < B * C_in * H * W) {
// permute x
int b = flat_idx / (C_in * img_size);
int c = (flat_idx / img_size) % C_in;
int out_ind = c * B * img_size + b * img_size + h * W + w;
x_perm[out_ind] = x[flat_idx];
}
if (flat_idx < B * C_out * H * W) {
// permute dout
int b = flat_idx / (C_out * img_size);
int c = (flat_idx / img_size) % C_out;
int out_ind = c * B * img_size + b * img_size + h * W + w;
dout_perm[out_ind] = dout[flat_idx];
}
}
__global__ void permute_dx_kernel(
const float* dx_perm,
float* dx,
int B, int C_in, int H, int W
) {
int flat_idx = blockIdx.x * blockDim.x + threadIdx.x;
int img_size = H * W;
if (flat_idx < B * C_in * img_size) {
int c = flat_idx / (B * img_size);
int b = (flat_idx / img_size) % B;
int h = (flat_idx / W) % H;
int w = flat_idx % W;
int out_ind = b * C_in * img_size + c * img_size + h * W + w;
dx[out_ind] = dx_perm[flat_idx];
}
}
// we want to sum the B, H, W dimensions of dout
// since dout_perm is shaped as (C_out, B, H, W)
// we will have each block take care of one entry of C_out
// and the threads in each block will use coorperative_groups to do the sum
__global__ void dbias_kernel(
const float* dout_perm, // shape (C_out, B, H, W)
float* dbias,
int B, int C_out, int H, int W
) {
int bhw = B * H * W;
extern __shared__ float shared[];
// move dout_perm to the C_out index
if (threadIdx.x < bhw) {
dout_perm += blockIdx.x * B * H * W;
float th_sum = 0.0f;
for (int i = threadIdx.x; i < bhw; i += blockDim.x) {
th_sum += dout_perm[i];
}
shared[threadIdx.x] = th_sum;
}
__syncthreads();
// reduce the shared memory
for (int stride = blockDim.x / 2; stride > 0; stride /= 2) {
if (threadIdx.x < stride) {
shared[threadIdx.x] += shared[threadIdx.x + stride];
}
__syncthreads();
}
if (threadIdx.x == 0) {
dbias[blockIdx.x] = shared[0];
}
}
// uses cublas
void conv2d_k1_backward1(
cublasHandle_t cublas_handle,
const float* dout, const float* x, const float* weight,
float* dx, float* dweight, float* dbias,
int B, int C_in, int C_out, int H, int W,
int block_size
) {
// shapes:
// x, dx: (B, C_in, H, W)
// weight: (C_out, C_in)
// bias: (C_out,)
// dout: (B, C_out, H, W)
// plan (the shapes are raw array shapes, note that cublas interprets the arrays as transposed):
// 1. transpose x to x_perm of shape (C_in, B*H*W), and dout to dout_perm of shape (C_out, B*H*W)
// 2. do one sgemm call to get dw = x.T @ dout_perm, and another call to get dx_perm = dout @ w.T
// 3. dx_perm is of shape (C_in, B*H*W), so call a kernel to permute it
// 4. reduce to get dbias
float *x_perm, *dout_perm, *dx_perm;
cudaCheck(cudaMalloc(&x_perm, C_in * B * H * W * sizeof(float)));
cudaCheck(cudaMalloc(&dout_perm, C_out * B * H * W * sizeof(float)));
cudaCheck(cudaMalloc(&dx_perm, C_in * B * H * W * sizeof(float)));
// 1. permute x and dout
int total_th1 = (C_in > C_out) ? C_in * B * H * W : C_out * B * H * W;
int n_blk1 = ceil_div(total_th1, block_size);
permute_dout_x_kernel<<<n_blk1, block_size>>>(x, dout, x_perm, dout_perm, B, C_in, C_out, H, W);
// 2.a sgemm call for dw = x_perm.T @ dout_perm
const float alpha = 1.0f;
const float beta = 0.0f;
int non_C_dim = B * H * W;
cublasCheck(cublasSgemm(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_N, C_in, C_out, non_C_dim, &alpha, x_perm, non_C_dim, dout_perm, non_C_dim, &beta, dweight, C_in));
// 2.b sgemm call for dx_perm = dout_perm @ weight.T
cublasCheck(cublasSgemm(cublas_handle, CUBLAS_OP_N, CUBLAS_OP_T, non_C_dim, C_in, C_out, &alpha, dout_perm, non_C_dim, weight, C_in, &beta, dx_perm, non_C_dim));
// 3. permute dx_perm from (C_out, B, H, W) to (B, C_out, H, W)
int total_th2 = C_in * B * H * W;
int n_blk2 = ceil_div(total_th2, block_size);
permute_dx_kernel<<<n_blk2, block_size>>>(dx_perm, dx, B, C_in, H, W);
// 4. reduce dout to get dbias
dbias_kernel<<<C_out, block_size, block_size * sizeof(float)>>>(dout_perm, dbias, B, C_out, H, W);
// free memory
cudaCheck(cudaFree(x_perm));
cudaCheck(cudaFree(dout_perm));
cudaCheck(cudaFree(dx_perm));
}
// ------------------------------------------------------------------------------------------------
// Conv2d 3x3 layer
typedef struct {
float* w;
float* b;
} ConvK3Params;
inline void convk3_set_param_ptrs(
ConvK3Params* params,
float* params_memory,
int C_in, int C_out
) {
params->w = params_memory;
params->b = params->w + C_in * C_out * 9;
}
inline size_t convk3_count_params(int C_in, int C_out) {
return C_in * C_out * 9 + C_out;
}
typedef struct {
float* inp;
float* out;
} ConvK3Acts;
// ---------------------------------------------
// kernels
// this kernel will roughly follow kernel 5 here: https://github.com/siboehm/SGEMM_CUDA, with a few differences
// the main operation is convolving the input X with the weights
// weights are shaped (O, Cx9), and X is shaped (B, C, HxW)
// We are morally doing a matmul with dimensions O, C, HxW
template <const int BO, const int BH, const int BC, const int TO, const int TH>
__global__ void conv2d_k3_forward_kernel2(
const float* x, const float* weight, const float* bias,
float* out,
const int B, const int C, const int O, const int H, const int W
) {
// constants
const int C9 = C * 9;
const int weight_size = O * C * 9;
const int x_size = B * C * H * W;
// n_threads / block = (BO * BH) / (TO * TH) = 256
// n_blocks = B * (O / BO) * (H * W / BH)
// we will set gridDim to (BxHxW / BH, O / BO)
const int block_row = blockIdx.y;
const int blocks_per_col = H * W / BH;
assert(gridDim.x == B * blocks_per_col);
const int batch = blockIdx.x / blocks_per_col;
const int block_col = blockIdx.x % blocks_per_col;
// for compute step, to determine which of the size TOxTH block the thread is responsible for
const int threads_per_col = ceil_div(BH, TH);
const int thread_col = threadIdx.x % threads_per_col;
const int thread_row = threadIdx.x / threads_per_col;
// shared mem for loading weights and X
const int w_s_sz = BO * BC * 9;
const int w_s_width = BC * 9;
const int x_s_sz = BC * BH;
__shared__ float w_s[w_s_sz];
__shared__ float x_s[x_s_sz];
// registers to store local results
float thread_results[TO * TH * 9] = {0.0};
// registers for weights and x
float reg_w[TO] = {0.0};
float reg_x[TH] = {0.0};
// calculate offset in x for bounds checking later
const int x_block_offset = batch * C * H * W + block_col * BH;
// calculate weight offset for bounds checking
const int w_block_offset = block_row * BO * C9;
// outer loop over BC size blocks of channel C
for (int c_idx = 0; c_idx < C; c_idx += BC) {
// x and weight offsets for this block
int x_inner_offset = c_idx * H * W;
int w_inner_offset = c_idx * 9;
// load weight into smem
int w_abs_idx;
for (int i = threadIdx.x; i < w_s_sz; i += blockDim.x) {
int w_i = i / w_s_width;
int w_j = i % w_s_width;
w_abs_idx = w_block_offset + w_inner_offset + w_i * C9 + w_j;
if (w_abs_idx < weight_size) {
w_s[w_j * BO + w_i] = weight[w_abs_idx];
}
}
// load x into smem
int x_abs_idx;
for (int i = threadIdx.x; i < x_s_sz; i += blockDim.x) {
int x_i = i / BH;
int x_j = i % BH;
x_abs_idx = x_block_offset + x_inner_offset + x_i * H * W + x_j;
if (x_abs_idx < x_size) {
x_s[x_i * BH + x_j] = x[x_abs_idx];
}
}
__syncthreads();
// calculate per thread results
for (int dot_idx = 0; dot_idx < BC; dot_idx++) {
// load x_s into registers
for (int j = 0; j < TH; j++) {
reg_x[j] = x_s[dot_idx * BH + thread_col * TH + j];
}
for (int conv_idx = 0; conv_idx < 9; conv_idx++) {
for (int i = 0; i < TO; i++) {
reg_w[i] = w_s[(dot_idx * 9 + conv_idx) * BO + thread_row * TO + i];
}
for (int i = 0; i < TO; i++) {
for (int j = 0; j < TH; j++) {
float val = reg_w[i] * reg_x[j];
thread_results[conv_idx * TO * TH + i * TH + j] += val;
}
}
}
}
__syncthreads();
}
// write out results
// need to be careful here: for each pixel at (h_abs, w_abs) and its product with kernel k (k < 9)
// There are 2 options
// 1. the product should be added to some pixel, then do an atomiAdd