-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathth.cpp
4353 lines (3714 loc) · 138 KB
/
th.cpp
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 "th.hpp"
#include "th-llama.hpp" // For kUniformsSize
#include "math.h"
#include <vector>
#include <chrono>
#include <cstring>
#include <cinttypes>
#include <numeric>
namespace th {
std::string get_TensorType_name(TensorType dt) {
switch (dt) {
case TensorType_F16: return "TensorTypeF16";
case TensorType_F32: return "TensorTypeF32";
default: assert(false);
}
return "TensorType_Unknown";
}
double get_time_seconds() {
auto t0 = std::chrono::high_resolution_clock::now();
auto nanosec = t0.time_since_epoch();
return (nanosec.count() / 1000000000.0);
}
static double percentile(const std::vector<double>& sortedValues, double percent) {
if(sortedValues.empty()) return 0;
if (percent <= 0) return sortedValues[0];
else if (percent >= 1) return sortedValues.back();
double index = (sortedValues.size() - 1) * percent;
size_t lower = std::floor(index);
size_t upper = std::ceil(index);
double weight = index - lower;
if(upper >= sortedValues.size()) return sortedValues[lower];
return (1 - weight) * sortedValues[lower] + weight * sortedValues[upper];
}
void print_descriptive_stats(std::vector<double> runTimes, const std::string& dataType) {
// Calculate mean
double sum = std::accumulate(runTimes.begin(), runTimes.end(), 0.0);
double mean = sum / runTimes.size();
// Sort the runtimes for median and percentile calculations
std::sort(runTimes.begin(), runTimes.end());
// Calculate median
size_t size = runTimes.size();
double median = (size % 2 == 0) ?
(runTimes[size / 2 - 1] + runTimes[size / 2]) / 2.0 :
runTimes[size / 2];
// Calculate mode
double mode = *std::max_element(runTimes.begin(), runTimes.end(),
[&runTimes](double a, double b){
return std::count(runTimes.begin(), runTimes.end(), a) <
std::count(runTimes.begin(), runTimes.end(), b);
});
// Calculate standard deviation
double sq_sum = std::inner_product(runTimes.begin(), runTimes.end(), runTimes.begin(), 0.0);
double std_dev = std::sqrt(sq_sum / runTimes.size() - mean * mean);
// Output results
printf("\n");
printf("Mean: %8.2f%s\n", mean, dataType.c_str());
printf("Median: %8.2f%s\n", median, dataType.c_str());
printf("Mode: %8.2f%s\n", mode, dataType.c_str());
printf("StdDev: %8.2f%s\n", std_dev, dataType.c_str());
// Calculate percentiles
double percentile99 = percentile(runTimes, 0.99);
double percentile95 = percentile(runTimes, 0.95);
double percentile5 = percentile(runTimes, 0.05);
double percentile1 = percentile(runTimes, 0.01);
printf("99th Percentile: %8.2f%s\n", percentile99, dataType.c_str());
printf("95th Percentile: %8.2f%s\n", percentile95, dataType.c_str());
printf("5th Percentile: %8.2f%s\n", percentile5, dataType.c_str());
printf("1st Percentile: %8.2f%s\n", percentile1, dataType.c_str());
}
static void store_pipeline_validation(
ComputePipeline& pipeline,
const TensorBuffer* A,
const TensorBuffer* B = nullptr,
const TensorBuffer* C = nullptr) {
if (A) { pipeline.sa = A->shape; pipeline.ta = A->type; }
if (B) { pipeline.sb = B->shape; pipeline.tb = B->type; }
if (C) { pipeline.sc = C->shape; pipeline.tc = C->type; }
}
static bool validate_pipeline(
const ComputePipeline& pipeline,
const TensorBuffer* A,
const TensorBuffer* B = nullptr,
const TensorBuffer* C = nullptr) {
if (A) {
if (!(pipeline.sa == A->shape) || pipeline.ta != A->type) {
assert(false);
return false;
}
}
if (B) {
if (pipeline.sb != B->shape || pipeline.tb != B->type) {
assert(false);
return false;
}
}
if (C) {
if (pipeline.sc != C->shape || pipeline.tc != C->type) {
assert(false);
return false;
}
}
return true;
}
bool are_pipelines_similar(const ComputePipeline& a, const ComputePipeline& b) {
if (a.sa != b.sa || a.sb != b.sb || a.sc != b.sc) {
return false;
}
if (a.ta != b.ta || a.tb != b.tb || a.tc != b.tc) {
return false;
}
return true;
}
bool are_mat_mul_pipelines_the_same(const ComputePipeline& a, float scaleA, bool transposeA,
const ComputePipeline& b, float scaleB, bool transposeB) {
if (!are_pipelines_similar(a, b)) {
return false;
}
if (scaleA != scaleB) {
return false;
}
if (transposeA != transposeB) {
return false;
}
return true;
}
TensorBuffer::TensorBuffer(TensorShape shapeIn, TensorType typeIn, WGPUDevice device, WGPUBufferUsageFlags usage) {
this->shape = shapeIn;
this->type = typeIn;
this->originalShape = shape;
if (device) { allocate_gpu_memory(device, usage); }
}
TensorBuffer::TensorBuffer(const void* data, TensorShape shapeIn, TensorType type, bool backup, WGPUDevice device, WGPUQueue queue, WGPUBufferUsageFlags usage) {
this->shape = shapeIn;
this->type = type;
if (backup) {
size_t size = this->get_size_bytes();
this->cpuBackup.resize(size);
memcpy(this->cpuBackup.data(), data, size);
}
this->originalShape = shape;
if (device) { allocate_gpu_memory(device, usage); }
if (queue) { upload_data_to_gpu(queue, data); }
}
TensorBuffer& TensorBuffer::operator=(TensorBuffer&& other) noexcept {
if (this != &other) {
free_buffers();
this->shape = other.shape;
this->type = other.type;
this->gpu = other.gpu;
this->cpuOnly = other.cpuOnly;
this->gpu = other.gpu;
this->originalShape = other.originalShape;
this->cpuBackup = other.cpuBackup;
this->name = other.name;
other.gpu = nullptr;
other.cpuBackup.clear();
}
return *this;
}
TensorBuffer::TensorBuffer(TensorBuffer&& other) noexcept
: shape(other.shape)
, type(other.type)
, cpuOnly(other.cpuOnly)
, cpuBackup(other.cpuBackup)
, gpu(other.gpu)
, originalShape(other.originalShape)
, name(other.name)
{
other.gpu = nullptr;
other.cpuBackup.clear();
}
size_t TensorBuffer::get_size_bytes() const {
assert(this->type != TensorType_Unknown);
int64_t elementSize = get_TensorType_size(this->type);
int64_t size = shape.get_total_num_elements();
return size * elementSize;
}
void TensorBuffer::upload_data_to_gpu(WGPUQueue queue, const void* data) {
assert(this->gpu);
wgpuQueueWriteBuffer(queue, this->gpu, 0, data, this->get_size_bytes());
}
void TensorBuffer::allocate_gpu_memory(WGPUDevice device, WGPUBufferUsageFlags usage) {
// TODO Adjust size of buffer if we have a format that is less than 8 bits.
// get_TensorType_size
assert(!this->gpu);
assert(this->type != TensorType_Unknown);
size_t size = get_size_bytes();
WGPUBufferDescriptor bufferDesc = {};
bufferDesc.usage = usage;
bufferDesc.size = size;
this->gpu = wgpuDeviceCreateBuffer(device, &bufferDesc);
}
void TensorBuffer::reset_shape() {
this->shape = this->originalShape;
}
ComputePipeline create_compute_pipeline(
WGPUDevice device,
const char* wgslSource,
std::vector<WGPUBindGroupLayoutEntry> layoutEntries,
const char* label)
{
ComputePipeline out{};
WGPUShaderModule cs;
{
WGPUShaderModuleWGSLDescriptor wgsl = {};
wgsl.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor;
wgsl.source = wgslSource;
WGPUShaderModuleDescriptor desc = {};
desc.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&wgsl);
desc.label = label;
cs = wgpuDeviceCreateShaderModule(device, &desc);
}
WGPUBindGroupLayoutDescriptor bglDesc = {};
bglDesc.entryCount = layoutEntries.size();
bglDesc.entries = layoutEntries.data();
out.bindGroupLayout = wgpuDeviceCreateBindGroupLayout(device, &bglDesc);
// pipeline layout (used by the render pipeline, released after its creation)
WGPUPipelineLayoutDescriptor layoutDesc = {};
layoutDesc.bindGroupLayoutCount = 1;
layoutDesc.bindGroupLayouts = &out.bindGroupLayout;
WGPUPipelineLayout pipelineLayout = wgpuDeviceCreatePipelineLayout(device, &layoutDesc);
WGPUProgrammableStageDescriptor stageDesc{};
stageDesc.module = cs;
stageDesc.entryPoint = "main";
stageDesc.constantCount = 0;
stageDesc.constants = nullptr;
WGPUComputePipelineDescriptor pipelineDesc{};
pipelineDesc.label = label;
pipelineDesc.layout = pipelineLayout;
pipelineDesc.compute = stageDesc;
out.pipeline = wgpuDeviceCreateComputePipeline(device, &pipelineDesc);
wgpuShaderModuleRelease(cs);
wgpuPipelineLayoutRelease(pipelineLayout);
return out;
}
void print_TensorBuffer(TensorBuffer* buffer, const char* bufferName) {
const auto & shape = buffer->shape;
int64_t size = buffer->get_size_bytes();
fprintf(stdout, "\n");
fprintf(stdout, "GPU buffer info (%s):\n", bufferName);
fprintf(stdout, " size = %" PRId64 "\n", size);
fprintf(stdout, " shape = l:%" PRId64 " b:%" PRId64 " r:%" PRId64 " c:%" PRId64 "\n", shape.l, shape.b, shape.r, shape.c);
fprintf(stdout, " type = %s\n", get_TensorType_name(buffer->type).c_str());
}
// Originally from llama.cpp
// FP16 <-> FP32
// ref: https://github.com/Maratyszcza/FP16
float fp32_from_bits(uint32_t w) {
union {
uint32_t as_bits;
float as_value;
} fp32;
fp32.as_bits = w;
return fp32.as_value;
}
uint32_t fp32_to_bits(float f) {
union {
float as_value;
uint32_t as_bits;
} fp32;
fp32.as_value = f;
return fp32.as_bits;
}
float ggml_compute_fp16_to_fp32(ggml_fp16_t h) {
const uint32_t w = (uint32_t) h << 16;
const uint32_t sign = w & UINT32_C(0x80000000);
const uint32_t two_w = w + w;
const uint32_t exp_offset = UINT32_C(0xE0) << 23;
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) || defined(__GNUC__) && !defined(__STRICT_ANSI__)
const float exp_scale = 0x1.0p-112f;
#else
const float exp_scale = fp32_from_bits(UINT32_C(0x7800000));
#endif
const float normalized_value = fp32_from_bits((two_w >> 4) + exp_offset) * exp_scale;
const uint32_t magic_mask = UINT32_C(126) << 23;
const float magic_bias = 0.5f;
const float denormalized_value = fp32_from_bits((two_w >> 17) | magic_mask) - magic_bias;
const uint32_t denormalized_cutoff = UINT32_C(1) << 27;
const uint32_t result = sign |
(two_w < denormalized_cutoff ? fp32_to_bits(denormalized_value) : fp32_to_bits(normalized_value));
return fp32_from_bits(result);
}
ggml_fp16_t ggml_compute_fp32_to_fp16(float f) {
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) || defined(__GNUC__) && !defined(__STRICT_ANSI__)
const float scale_to_inf = 0x1.0p+112f;
const float scale_to_zero = 0x1.0p-110f;
#else
const float scale_to_inf = fp32_from_bits(UINT32_C(0x77800000));
const float scale_to_zero = fp32_from_bits(UINT32_C(0x08800000));
#endif
float base = (fabsf(f) * scale_to_inf) * scale_to_zero;
const uint32_t w = fp32_to_bits(f);
const uint32_t shl1_w = w + w;
const uint32_t sign = w & UINT32_C(0x80000000);
uint32_t bias = shl1_w & UINT32_C(0xFF000000);
if (bias < UINT32_C(0x71000000)) {
bias = UINT32_C(0x71000000);
}
base = fp32_from_bits((bias >> 1) + UINT32_C(0x07800000)) + base;
const uint32_t bits = fp32_to_bits(base);
const uint32_t exp_bits = (bits >> 13) & UINT32_C(0x00007C00);
const uint32_t mantissa_bits = bits & UINT32_C(0x00000FFF);
const uint32_t nonsign = exp_bits + mantissa_bits;
return (sign >> 16) | (shl1_w > UINT32_C(0xFF000000) ? UINT16_C(0x7E00) : nonsign);
}
static const char* wgsl_fp16_to_fp32 = R"(
// Takes a u32 that contains two f16's, and an index to the f16
// in the u32.
fn compute_fp16_to_fp32(h_in : u32, f16_part : u32) -> f32 {
var h : u32 = h_in >> (16 * f16_part); // Select correct 16 bits.
h = h & u32(0xFFFF); // Mask off upper 16 bits.
let w : u32 = h << 16;
let sign : u32 = w & u32(0x80000000);
let two_w : u32 = w + w;
let exp_offset : u32 = u32(0xE0) << 23;
//const float exp_scale = 0x1.0p-112f;
let exp_scale : f32 = bitcast<f32>(u32(0x7800000));
let normalized_value : f32 = bitcast<f32>((two_w >> 4) + exp_offset) * exp_scale;
let magic_mask : u32 = u32(126) << 23;
//let magic_mask : u32 = u32(126) << 20;
let magic_bias : f32 = 0.5f;
let denormalized_value : f32 = bitcast<f32>((two_w >> 17) | magic_mask) - magic_bias;
let denormalized_cutoff : u32 = u32(1) << 27;
var result : u32;
if (two_w < denormalized_cutoff) {
result = bitcast<u32>(denormalized_value);
} else {
result = bitcast<u32>(normalized_value);
}
result = sign | result;
return bitcast<f32>(result);
}
)";
static const char* wgsl_gemm_header = R"(
// Note that bindings similar to the below exist:
//@group(0) @binding(0) var<storage,read> a : array<f32>; // [M, K]
//@group(0) @binding(1) var<storage,read> b : array<f32>; // [K, N]
//@group(0) @binding(2) var<storage,read_write> c : array<f32>;
const kSharedMemDimX : u32 = kWorkgroupX * kTileSizeX;
const kSharedMemDimY : u32 = kWorkgroupY * kTileSizeY;
var<workgroup> aShared : array<f32, kSharedMemDimX*kSharedMemDimY>;
var<workgroup> bShared : array<f32, kSharedMemDimX*kSharedMemDimY>;
fn isOutOfBounds(rows : u32, cols : u32, x : u32, y : u32) -> bool {
return (x >= cols || y >= rows);
}
@compute @workgroup_size(kWorkgroupX, kWorkgroupY, 1u)
fn main(
@builtin(workgroup_id) workGroupID : vec3<u32>,
@builtin(local_invocation_id) localInvocationId : vec3<u32>
)
{
)";
static const char* wgsl_gemm_body = R"(
let matStrideA : u32 = M * K * workGroupID.z;
let matStrideB : u32 = K * N * workGroupID.z;
let matStrideOut : u32 = M * N * workGroupID.z;
// Each thread loads 4x4 tile into the shared workgroup memory.
let outputIndexA = vec2<u32>(
workGroupID.xy * vec2<u32>(kSharedMemDimX, kSharedMemDimY) +
localInvocationId.xy * vec2<u32>(kTileSizeX, kTileSizeY));
var suma : array<array<f32,kTileSizeY>, kTileSizeX>;
for (var j : u32 = 0; j < kTileSizeY; j = j + 1) {
for (var i : u32 = 0; i < kTileSizeX; i = i + 1) {
suma[i][j] = 0.0;
}
}
var numLoopsNeeded : u32 = K / kSharedMemDimX;
if (K % kSharedMemDimX != 0) {
numLoopsNeeded = numLoopsNeeded + 1;
}
var bRows : u32 = K;
var bCols : u32 = N;
if (kTransposeB == 1) {
bRows = N;
bCols = K;
}
for (var highi : u32 = 0; highi < numLoopsNeeded; highi = highi + 1) {
// The idea here: workGroupID specifies the 'block' within the matrix
// that we are working on (will receive our results). highi represents
// how far we are along the 'x' axis of 'A' and 'y' axis of 'B'.
let a_row = workGroupID.y * kSharedMemDimY + localInvocationId.y * kTileSizeY;
let a_col = highi * kSharedMemDimX + localInvocationId.x * kTileSizeX;
var b_row = highi * kSharedMemDimY + localInvocationId.y * kTileSizeY;
var b_col = workGroupID.x * kSharedMemDimX + localInvocationId.x * kTileSizeX;
if (kTransposeB == 1) {
b_row = workGroupID.x * kSharedMemDimX + localInvocationId.x * kTileSizeX;
b_col = highi * kSharedMemDimY + localInvocationId.y * kTileSizeY;
}
for (var row : u32 = 0; row < kTileSizeY; row = row + 1) {
let rowPos = (localInvocationId.y * kTileSizeY + row) * kSharedMemDimX + localInvocationId.x * kTileSizeX;
for (var col : u32 = 0; col < kTileSizeX; col = col + 1) {
let ax = a_col + col;
let ay = a_row + row;
let bx = b_col + col;
let by = b_row + row;
if (!isOutOfBounds(M, K, ax, ay))
{
aShared[rowPos + col] = a[matStrideA + ay * K + ax];
}
else
{
aShared[rowPos + col] = 0.0; // MUST
}
if (!isOutOfBounds(bRows, bCols, bx, by))
{
// TODO Transpose b when placing in shared memory. Leads to better smem locality.
if (is_b_f16) {
let b_index : u32 = by * (bCols/2) + bx / 2;
let f16_part = bx % 2;
bShared[rowPos + col] = compute_fp16_to_fp32(u32(b[matStrideB + b_index]), f16_part); // f16
} else {
bShared[rowPos + col] = f32(b[matStrideB + by * bCols + bx]);
}
}
else
{
bShared[rowPos + col] = 0.0; // We must set this to 0, otherwise we need conditionals below.
}
}
}
// Required to ensure shared memory is correctly populated before proceeding.
workgroupBarrier();
// Calculate all values in our 4x4 tile.
for (var j : u32 = 0; j < kTileSizeY; j = j + 1) {
for (var i : u32 = 0; i < kTileSizeX; i = i + 1) {
var row = localInvocationId.y * kTileSizeY + j;
var col = localInvocationId.x * kTileSizeX + i;
var sum : f32 = 0.0;
for (var k : u32 = 0; k < kSharedMemDimX; k = k + 1) {
// Note: Even if we transpose the matrix, we still need to
// maintain the same row/col multiplication order in the
// sub-blocks to ensure we 'transpose' sub-blocks.
sum = sum + aShared[row * kSharedMemDimX + k] * bShared[k * kSharedMemDimX + col];
}
// It's 'okay' to do a non-atomic update of C. We are guaranteed
// to be the only thread touching it.
suma[i][j] = suma[i][j] + sum;
}
}
// This barrier is absolutely necessary to avoid other threads updating the shared
// memory before we are done with it.
workgroupBarrier();
}
for (var j : u32 = 0; j < kTileSizeY; j = j + 1) {
for (var i : u32 = 0; i < kTileSizeX; i = i + 1) {
if (do_scale) {
suma[i][j] = suma[i][j] * scale;
}
if (!isOutOfBounds(M, N, outputIndexA.x + i, outputIndexA.y + j))
{
let outIndex : u32 = (outputIndexA.y + j) * N + outputIndexA.x + i;
c[matStrideOut + outIndex] = suma[i][j];
}
}
}
}
)";
static bool validate_mat_mul(
const TensorBuffer& A,
const TensorBuffer& B,
const TensorBuffer& C) {
if (A.type != TensorType_F32) {
fprintf(stderr, "cmdbuf_mat_mul: A.type != TensorType_F32\n");
assert(false);
return false;
}
if (!(B.type == TensorType_F32 || B.type == TensorType_F16)) {
fprintf(stderr, "cmdbuf_mat_mul: B.type != TensorType_F32 or TensorType_F16\n");
assert(false);
return false;
}
if (C.type != TensorType_F32) {
fprintf(stderr, "cmdbuf_mat_mul: C.type != TensorType_F32\n");
assert(false);
return false;
}
if (A.shape.c != B.shape.r) {
fprintf(stderr, "cmdbuf_mat_mul: Num rows in A not equal to columns in B\n");
assert(false);
return false;
}
if (A.shape.r == 0 || A.shape.c == 0) {
fprintf(stderr, "cmdbuf_mat_mul: one of the dimensions of A is zero.\n");
assert(false);
return false;
}
if (B.shape.r == 0 || B.shape.c == 0) {
printf("cmdbuf_mat_mul: one of the dimensions of B is zero.\n");
assert(false);
return false;
}
if (A.shape.b > 1) {
if (A.shape.b != B.shape.b) {
printf("cmdbuf_mat_mul: A.shape.b != B.shape.b\n");
assert(false);
return false;
}
if (A.shape.b != C.shape.b) {
printf("cmdbuf_mat_mul: A.shape.b != C.shape.b\n");
assert(false);
return false;
}
}
if (C.shape.r != A.shape.r) {
printf("cmdbuf_mat_mul: C's number of rows do not match A's\n");
assert(false);
return false;
}
if (C.shape.c != B.shape.c) {
printf("cmdbuf_mat_mul: C's number of columns do not match B's\n");
assert(false);
return false;
}
return true;
}
// Note workgroup size (gWorkgroupX*gWorkgroupY) shouldn't exceed 256.
static const int64_t kMatMulWorkgroupX = 8;
static const int64_t kMatMulWorkgroupY = 8;
static const int64_t kMatMulTileSizeX = 1; // 1
static const int64_t kMatMulTileSizeY = 1; // 1
ComputePipeline pipeline_mat_mul(
WGPUDevice device,
const TensorBuffer& A,
const TensorBuffer& B,
const TensorBuffer& C,
int transposeB,
bool useUniforms) {
if (!validate_mat_mul(A,B,C)) {
return {};
}
const char* label = "mat_mul";
std::vector<WGPUBindGroupLayoutEntry> bglEntries = {
WGPUBindGroupLayoutEntry{
// Binding 0: Input matrix
.binding = 0,
.visibility = WGPUShaderStage_Compute,
.buffer = WGPUBufferBindingLayout{
.type = WGPUBufferBindingType_ReadOnlyStorage,
.hasDynamicOffset = false,
},
},
WGPUBindGroupLayoutEntry{
// Binding 1: Weight matrix.
.binding = 1,
.visibility = WGPUShaderStage_Compute,
.buffer = WGPUBufferBindingLayout{
.type = WGPUBufferBindingType_ReadOnlyStorage,
.hasDynamicOffset = false,
},
},
WGPUBindGroupLayoutEntry{
// Binding 2: Output matrix
.binding = 2,
.visibility = WGPUShaderStage_Compute,
.buffer = WGPUBufferBindingLayout{
.type = WGPUBufferBindingType_Storage,
.hasDynamicOffset = false,
},
},
};
if (useUniforms) {
bglEntries.push_back(
WGPUBindGroupLayoutEntry{
// Binding 3:
.binding = 3,
.visibility = WGPUShaderStage_Compute,
.buffer = WGPUBufferBindingLayout{
.type = WGPUBufferBindingType_Uniform,
.hasDynamicOffset = false,
},
});
}
int64_t M = A.shape.r;
int64_t N = B.shape.c;
int64_t K = A.shape.c;
bool is_f16 = (B.type == TensorType_F16);
std::string is_f16_str = "false";
if (is_f16) { is_f16_str = "true"; }
// Add embedding dims.
std::string code = "\nconst kEmbeddingSize = " + std::to_string(K) + ";\n";
code += "\nconst kNumTokens = " + std::to_string(M) + ";\n";
if (!useUniforms) {
code += "\nconst M = " + std::to_string(M) + ";\n";
code += "\nconst N = " + std::to_string(N) + ";\n";
code += "\nconst K = " + std::to_string(K) + ";\n";
} else {
code += R"ARR(
struct Uniforms {
A_B : u32,
A_M : u32,
A_N : u32,
scale : f32,
B_B : u32,
B_M : u32,
B_N : u32,
offset : f32
};
@group(0) @binding(3) var<uniform> uniforms : Uniforms;
)ARR";
}
code += "\nconst kWorkgroupX : u32 = " + std::to_string(kMatMulWorkgroupX) + ";\n";
code += "\nconst kWorkgroupY : u32 = " + std::to_string(kMatMulWorkgroupY) + ";\n";
code += "\nconst kTileSizeX : u32 = " + std::to_string(kMatMulTileSizeX) + ";\n";
code += "\nconst kTileSizeY : u32 = " + std::to_string(kMatMulTileSizeY) + ";\n";
code += "\nconst kTransposeB : u32 = " + std::to_string(transposeB) + ";\n";
code += "\nconst is_b_f16 : bool = " + is_f16_str + ";\n";
if (is_f16) {
code += R"(
@group(0) @binding(0) var<storage,read> a : array<f32>; // [M, K]
@group(0) @binding(1) var<storage,read> b : array<u32>; // [K, N] (f16)
@group(0) @binding(2) var<storage,read_write> c : array<f32>;
)";
} else {
code += R"(
@group(0) @binding(0) var<storage,read> a : array<f32>; // [M, K]
@group(0) @binding(1) var<storage,read> b : array<f32>; // [K, N]
@group(0) @binding(2) var<storage,read_write> c : array<f32>;
)";
}
code += std::string(wgsl_fp16_to_fp32);
code += std::string(wgsl_gemm_header);
if (useUniforms) {
// This code is the same as:
// int64_t M = A.shape.r;
// int64_t N = B.shape.c;
// int64_t K = A.shape.c;
code += R"ARR(
let M : u32 = uniforms.A_M;
let N : u32 = uniforms.B_N;
let K : u32 = uniforms.A_N;
let scale : f32 = uniforms.scale;
let do_scale : bool = true;
)ARR";
} else {
code += "\nlet scale : f32 = 1.0;\n";
code += "\nlet do_scale : bool = false;\n";
}
code += std::string(wgsl_gemm_body);
ComputePipeline pipeline =
create_compute_pipeline(device, code.c_str(), bglEntries, label);
store_pipeline_validation(pipeline, &A, &B, &C);
return pipeline;
}
CommandBuffer cmdbuf_mat_mul(
WGPUDevice device,
WGPUCommandEncoder encoder,
WGPUComputePassEncoder pass,
ComputePipeline* pipeline,
const TensorBuffer& A,
const TensorBuffer& B,
const TensorBuffer& C,
int transposeB,
WGPUBuffer uniforms)
{
if (!validate_mat_mul(A,B,C)) {
return {};
}
bool useUniforms = (uniforms != nullptr);
// The following allows construction of pipelines and avoids high-level code duplication.
ComputePipeline pipelineTemp{}; // Memory of this local variable is referenced throughout the function.
if (!pipeline || !pipeline->is_valid()) {
pipelineTemp = pipeline_mat_mul(device, A, B, C, transposeB, uniforms);
if (pipeline && pipeline->buildPipelineFlag) {
*pipeline = std::move(pipelineTemp);
return {};
}
pipeline = &pipelineTemp;
} else if (!useUniforms) {
if (!validate_pipeline(*pipeline, &A, &B, &C)) {
printf("create_rms_norm: Pipeline validation failed.\n");
assert(false);
return {};
}
}
std::vector<WGPUBindGroupEntry> bgEntries = {
WGPUBindGroupEntry{
.binding = 0,
.buffer = A.gpu,
.offset = 0,
.size = (uint32_t)A.get_size_bytes(),
},
WGPUBindGroupEntry{
.binding = 1,
.buffer = B.gpu,
.offset = 0,
.size = (uint32_t)B.get_size_bytes(),
},
WGPUBindGroupEntry{
.binding = 2,
.buffer = C.gpu,
.offset = 0,
.size = (uint32_t)C.get_size_bytes(),
},
};
if (useUniforms) {
bgEntries.push_back(
WGPUBindGroupEntry{
.binding = 3,
.buffer = uniforms,
.offset = 0,
.size = kLlamaUniformsSize
});
}
WGPUBindGroupDescriptor bgDesc = {
.layout = pipeline->bindGroupLayout,
.entryCount = (uint32_t)bgEntries.size(),
.entries = bgEntries.data(),
};
WGPUBindGroup bindGroup = wgpuDeviceCreateBindGroup(device, &bgDesc);
int64_t M = A.shape.r;
int64_t N = B.shape.c;
int64_t divisorX = (kMatMulWorkgroupX * kMatMulTileSizeX);
int64_t divisorY = (kMatMulWorkgroupY * kMatMulTileSizeY);
int64_t workgroupsX = N / divisorX;
int64_t workgroupsY = M / divisorY;
int64_t workgroupsZ = A.shape.b == 0 ? 1: A.shape.b;
if (N % divisorX != 0) { workgroupsX = workgroupsX + 1; }
if (M % divisorY != 0) { workgroupsY = workgroupsY + 1; }
CommandBuffer out{};
bool hasEncoder = (encoder != nullptr);
bool hasPass = (pass != nullptr);
if (!hasEncoder && !hasPass) {
encoder = wgpuDeviceCreateCommandEncoder(device, nullptr);
}
if (!hasPass) {
pass = wgpuCommandEncoderBeginComputePass(encoder, nullptr);
}
wgpuComputePassEncoderSetPipeline(pass, pipeline->pipeline);
wgpuComputePassEncoderSetBindGroup(pass, 0, bindGroup, 0, nullptr);
wgpuComputePassEncoderDispatchWorkgroups(pass, workgroupsX, workgroupsY, workgroupsZ);
if (!hasPass) {
wgpuComputePassEncoderEnd(pass);
wgpuComputePassEncoderRelease(pass); // There is a question whether we should release before building command buffer.
}
if (!hasEncoder && !hasPass) {
out.cmdBuffer = wgpuCommandEncoderFinish(encoder, nullptr);
wgpuCommandEncoderRelease(encoder);
}
wgpuBindGroupRelease(bindGroup);
return out;
}
int64_t kTransposeWorkgroupX = 8;
int64_t kTransposeWorkgroupY = 8;
// I only need two transpose functions:
// 1) A basic 2D matrix transpose.
// 2) A 3D matrix transpose where we transpose the batches and rows. This can be used in combination with 1) to transpose batches and columns.
// B - Number of batches.
// M - Number of rows.
// N - Number of columns.
// kWorkgroupX - Size of the workgroup along X dimension.
// kWorkgroupY - Size of the workgroup along Y dimension.
// let do_zy : bool = False;
static const char* wgsl_transpose_header_f32 = R"(
@group(0) @binding(0) var<storage,read> a : array<f32>; // f32 [B, M, N]
@group(0) @binding(1) var<storage,read_write> c : array<f32>; // f32 [B, M, N]
fn isOutOfBounds(rows : u32, cols : u32, x : u32, y : u32) -> bool {
return (x >= cols || y >= rows);
}
@compute @workgroup_size(kWorkgroupX, kWorkgroupY, 1u)
fn main(
@builtin(workgroup_id) workGroupID : vec3<u32>,
@builtin(local_invocation_id) localInvocationId : vec3<u32>)
{
)";
static const char* wgsl_transpose_body_f32 = R"(
let zb : u32 = M*N;
let yb : u32 = N;
let index_z = workGroupID.z + localInvocationId.z;
let index_y = (workGroupID.y*kWorkgroupY) + localInvocationId.y;
let index_x = (workGroupID.x*kWorkgroupX) + localInvocationId.x;
if (isOutOfBounds(M, N, index_x, index_y)) {
return;
}
if (do_zy) {
let zbt : u32 = B*N;
let ybt : u32 = N;
c[index_y*zbt + index_z*ybt + index_x] = a[index_z*zb + index_y*yb + index_x];
} else {
let zbt : u32 = M*N;
let ybt : u32 = M;
c[index_z*zbt + index_x*ybt + index_y] = a[index_z*zb + index_y*yb + index_x];
}
}
)";
static bool validate_transpose(
const TensorBuffer& A,
const TensorBuffer& B,
bool zy) {
if (zy) {
if ( A.shape.r != B.shape.b
|| A.shape.c != B.shape.c
|| A.shape.b != B.shape.r) {
printf("cmdbuf_transpose: zy: input shape doesn't match expected transpose of output.\n");
assert(false);
return false;
}
} else {
if ( A.shape.r != B.shape.c
|| A.shape.c != B.shape.r
|| A.shape.b != B.shape.b) {
printf("cmdbuf_transpose: yx: input shape doesn't match expected transpose of output.\n");
assert(false);
return false;
}
}
return true;
}
static ComputePipeline pipeline_transpose(
WGPUDevice device,
const TensorBuffer& A,
const TensorBuffer& B,
bool zy,
bool useUniforms,
int64_t M, int64_t N) {
const char* label = "transpose";
int64_t numBatches = A.shape.b;
if (numBatches <= 0) { numBatches = 1; }
std::vector<WGPUBindGroupLayoutEntry> bglEntries = {
WGPUBindGroupLayoutEntry{
.binding = 0,
.visibility = WGPUShaderStage_Compute,
.buffer = WGPUBufferBindingLayout{
.type = WGPUBufferBindingType_ReadOnlyStorage,
.hasDynamicOffset = false,
},
},
WGPUBindGroupLayoutEntry{
.binding = 1,
.visibility = WGPUShaderStage_Compute,
.buffer = WGPUBufferBindingLayout{
.type = WGPUBufferBindingType_Storage,
.hasDynamicOffset = false,
},
},
};
if (useUniforms) {
bglEntries.push_back(
WGPUBindGroupLayoutEntry{
.binding = 2,
.visibility = WGPUShaderStage_Compute,
.buffer = WGPUBufferBindingLayout{
.type = WGPUBufferBindingType_Uniform,
.hasDynamicOffset = false,
},
});
}
int64_t kWorkgroupX = kTransposeWorkgroupX;
int64_t kWorkgroupY = kTransposeWorkgroupY;
if (M == 1 && numBatches == 1) {
kWorkgroupX = 256;
kWorkgroupY = 1;
}
std::string code = "";
if (zy) {
code += "\nconst do_zy = true;\n";
} else {
code += "\nconst do_zy = false;\n";
}
if (!useUniforms) {
code += "\nconst B : u32 = " + std::to_string(numBatches) + ";\n";
code += "\nconst M : u32 = " + std::to_string(M) + ";\n";
code += "\nconst N : u32 = " + std::to_string(N) + ";\n";
} else {