-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenelm.cu
1518 lines (1270 loc) · 51.9 KB
/
openelm.cu
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
/*
nvcc -o openelm_cu openelm.cu -lm
./openelm_cu
seconds:7.500000s tokens:256 achieved tok/s: 34.133333
nvcc -o openelm_cu -O3 openelm.cu -lm
./openelm_cu
seconds:8.782000s tokens:256 achieved tok/s: 29.150535
python generate_openelm.py --device=cuda --max_length=256
Generation took 4.44 seconds.
256 tokens.
57.7 tokens/s.
*/
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdint.h>
extern "C" {
void c_init(int batch, int max_seq_len);
int* c_openelm_forward(int batch, int seq_len, int *data, int pos);
void c_generate(int batch, int seq_len, int *data, int steps);
void c_chat ();
}
typedef struct {
int ffn_dim_divisor;
float ffn_multipliers[16];
int head_dim;
int max_context_length;
int model_dim;
int num_gqa_groups;
int num_kv_heads[16];
int num_query_heads[16];
int num_transformer_layers;
float qkv_multipliers[2];
int rope_freq_constant;
int rope_max_length;
int vocab_size;
int max_qkv_proj_dim;
int max_intermediate_dim;
} OpenELMConfig;
typedef struct {
float *token_embeddings; // transformer.token_embeddings.weight
float *attn_norm; // transformer.layers.{i}.attn_norm.weight
float *qkv_proj; // transformer.layers.{i}.attn.qkv_proj.weight
float *q_norm; // transformer.layers.{i}.attn.q_norm.weight
float *k_norm; // transformer.layers.{i}.attn.k_norm.weight
float *out_proj; // transformer.layers.{i}.attn.out_proj.weight
float *proj_1; // transformer.layers.{i}.ffn.proj_1.weight
float *proj_2; // transformer.layers.{i}.ffn.proj_2.weight
float *ffn_norm; // transformer.layers.{i}.ffn_norm.weight
float *norm; // transformer.norm.weight
} OpenELMWeights;
typedef struct {
float *x;
float *xb;
float *xb2;
float *x_qkv_proj;
float *ihb;
float *ihb2;
float *hb;
float *att;
float *logits;
int *next;
int *token;
int *next_cpu;
float *q;
float *key_cache;
float *value_cache;
int batch;
int seq_len;
int max_seq_len;
int qkv_proj_offset;
int out_proj_offset;
int proj_1_offset;
int proj_2_offset;
int max_q_heads;
int max_kv_heads;
} RunState;
typedef struct {
OpenELMConfig config;
RunState state;
OpenELMWeights weights;
OpenELMWeights weights_cu;
int num_parameters;
float *params_memory;
} OpenELM;
void malloc_run_state(RunState* s, OpenELMConfig* p) {
int seq_len = s->max_seq_len;
cudaMalloc((void**)&s->x, s->batch * p->model_dim * sizeof(float));
cudaMalloc((void**)&s->xb2, s->batch * p->model_dim * sizeof(float));
int q_heads = 0;
int k_heads = 0;
int v_heads = 0;
for (int i = 0; i < p->num_transformer_layers; i++) {
if (p->num_query_heads[i] > q_heads) {
q_heads = p->num_query_heads[i];
}
if (p->num_kv_heads[i] > k_heads) {
k_heads = p->num_kv_heads[i];
}
v_heads = k_heads;
}
s->max_q_heads = q_heads;
s->max_kv_heads = k_heads;
int max_xb_dim = p->model_dim;
if (max_xb_dim < q_heads * p->head_dim) {
max_xb_dim = q_heads * p->head_dim;
}
cudaMalloc((void**)&s->xb, s->batch * max_xb_dim * sizeof(float));
cudaMalloc((void**)&s->att, s->batch * q_heads * seq_len * sizeof(float));
cudaMalloc((void**)&s->ihb, s->batch * 2 * p->max_intermediate_dim * sizeof(float));
cudaMalloc((void**)&s->ihb2, s->batch * p->max_intermediate_dim * sizeof(float));
cudaMalloc((void**)&s->hb, s->batch * p->model_dim * sizeof(float));
cudaMalloc((void**)&s->logits, s->batch * p->vocab_size * sizeof(float));
cudaMalloc((void**)&s->next, s->batch * sizeof(int));
cudaMalloc((void**)&s->token, s->batch * sizeof(int));
s->next_cpu = (int*)malloc(s->batch * sizeof(int));
cudaMalloc((void**)&s->q, s->batch * q_heads * p->head_dim * sizeof(float));
cudaMalloc((void**)&s->key_cache, s->batch * p->num_transformer_layers * seq_len * k_heads * p->head_dim * sizeof(float));
cudaMalloc((void**)&s->value_cache, s->batch * p->num_transformer_layers * seq_len * v_heads * p->head_dim * sizeof(float));
}
void free_run_state(RunState* s) {
cudaFree(s->x);
cudaFree(s->xb);
cudaFree(s->xb2);
}
void memory_map_weights(OpenELMWeights *w, OpenELMConfig* p, float* ptr) {
int ll;
cudaMemcpy(&ll, ptr, sizeof(int), cudaMemcpyDeviceToHost);
// printf("++++++++++++--------%d\n", ll);
ptr += 1;
w->token_embeddings = ptr;
ptr += ll;
cudaMemcpy(&ll, ptr, sizeof(int), cudaMemcpyDeviceToHost);
// printf("++++++++++++--------%d\n", ll);
ptr += 1;
w->attn_norm = ptr;
ptr += ll;
cudaMemcpy(&ll, ptr, sizeof(int), cudaMemcpyDeviceToHost);
ptr += 1;
// printf("++++++++++++--------%d\n", ll);
w->qkv_proj = ptr;
ptr += ll;
cudaMemcpy(&ll, ptr, sizeof(int), cudaMemcpyDeviceToHost);
ptr += 1;
w->q_norm = ptr;
ptr += ll;
cudaMemcpy(&ll, ptr, sizeof(int), cudaMemcpyDeviceToHost);
ptr += 1;
w->k_norm = ptr;
ptr += ll;
cudaMemcpy(&ll, ptr, sizeof(int), cudaMemcpyDeviceToHost);
ptr += 1;
w->out_proj = ptr;
ptr += ll;
cudaMemcpy(&ll, ptr, sizeof(int), cudaMemcpyDeviceToHost);
ptr += 1;
w->ffn_norm = ptr;
ptr += ll;
cudaMemcpy(&ll, ptr, sizeof(int), cudaMemcpyDeviceToHost);
ptr += 1;
w->proj_1 = ptr;
ptr += ll;
cudaMemcpy(&ll, ptr, sizeof(int), cudaMemcpyDeviceToHost);
ptr += 1;
w->proj_2 = ptr;
ptr += ll;
cudaMemcpy(&ll, ptr, sizeof(int), cudaMemcpyDeviceToHost);
// printf("++++++++++++--------%d\n", ll);
ptr += 1;
w->norm = ptr;
}
void openelm_build_from_checkpoint(OpenELM *model, const char* checkpoint_path) {
FILE *model_file = fopen(checkpoint_path, "rb");
if (model_file == NULL) {
printf("Error opening model file\n");
}
size_t file_size = 0;
fseek(model_file, 0, SEEK_END);
file_size = ftell(model_file);
fseek(model_file, 0, SEEK_SET);
printf("file_size is: %ld\n", file_size);
int model_magic;
fread(&model_magic, sizeof(int), 1, model_file);
if (model_magic != 20240426) {
printf("Bad magic model file\n");
}
printf("model magic is: %d\n", model_magic);
fread(&model->config, sizeof(int), sizeof(model->config) / sizeof(int), model_file);
printf("config ffn_dim_divisor is: %d\n", model->config.ffn_dim_divisor);
printf("config ffn_multipliers is: ");
for (int i = 0; i < 16; i++) {
printf("%f ", model->config.ffn_multipliers[i]);
}
printf("\n");
printf("config head_dim is: %d\n", model->config.head_dim);
printf("config model_dim is: %d\n", model->config.model_dim);
printf("config num_gqa_groups is: %d\n", model->config.num_gqa_groups);
printf("config num_kv_heads is: ");
for (int i = 0; i < 16; i++) {
printf("%d ", model->config.num_kv_heads[i]);
}
printf("\n");
printf("config num_query_heads is: ");
for (int i = 0; i < 16; i++) {
printf("%d ", model->config.num_query_heads[i]);
}
printf("\n");
printf("config num_transformer_layers is: %d\n", model->config.num_transformer_layers);
printf("config qkv_multipliers is: ");
for (int i = 0; i < 2; i++) {
printf("%f ", model->config.qkv_multipliers[i]);
}
printf("\n");
printf("config rope_freq_constant is: %d\n", model->config.rope_freq_constant);
printf("config rope_max_length is: %d\n", model->config.rope_max_length);
printf("config vocab_size is: %d\n", model->config.vocab_size);
printf("config max_qkv_proj_dim is: %d\n", model->config.max_qkv_proj_dim);
printf("config max_intermediate_dim is: %d\n", model->config.max_intermediate_dim);
size_t model_size = file_size - sizeof(model->config) - sizeof(int);
model->num_parameters = model_size / sizeof(float);
printf("num_parameters: %d\n", model->num_parameters);
model->params_memory = (float*)malloc(model_size);
fread(model->params_memory, sizeof(float), model->num_parameters, model_file);
// for (int i = 0; i < 64; i++) {
// printf("weight: %f ", *(model->params_memory+i));
// }
// model->weights.token_embedding_table = model->params_memory;
void *device_memory;
cudaMalloc((void**)&device_memory, model_size);
cudaMemcpy(device_memory, model->params_memory, model_size, cudaMemcpyHostToDevice);
memory_map_weights(&model->weights, &model->config, (float*)device_memory);
}
typedef struct {
} Context;
typedef struct {
int batch;
int length;
int* data;
} Prompt;
void read_prompt(Prompt *prompt, const char* prompt_path) {
FILE *prompt_file = fopen(prompt_path, "rb");
if (prompt_file == NULL) {
printf("Error opening prompt file\n");
}
int headers[2];
fread(headers, sizeof(int), 2, prompt_file);
prompt->batch = headers[0];
prompt->length = headers[1];
printf("prompt shape: %d %d\n", prompt->batch, prompt->length);
prompt->data = (int*)malloc(prompt->batch * prompt->length * sizeof(float));
fread(prompt->data, sizeof(float), prompt->batch * prompt->length, prompt_file);
// for (int i = 0; i < prompt->batch * prompt->length; i++) {
// printf("%d ", *(prompt->data + i));
// }
}
__device__ bool thread0() {
return (!threadIdx.x && !threadIdx.y && !threadIdx.z) && (!blockIdx.x && !blockIdx.y && !blockIdx.z);
}
// https://pytorch.org/docs/stable/generated/torch.nn.Linear.html
__global__
void linear_forward(float* output, float* input, float *weight, float* bias, int batch, int in_features, int out_features) {
int b = blockIdx.x;
int bidy = blockIdx.y;
int tid = threadIdx.x;
int kNThreads = blockDim.x;
int out = bidy * kNThreads + tid;
int offset_out = b * out_features + out;
int offset_bias = out;
float value = 0.0f;
for (int in = 0; in < in_features; in++) {
int offset_in = b * in_features + in;
int offset_weight = out * in_features + in;
value += input[offset_in] * weight[offset_weight];
}
output[offset_out] = value;
if (bias != NULL) {
output[offset_out] += bias[offset_bias];
}
// if (thread0()) {
// printf("linear:\n");
// for (int b = 0; b < batch; b++) {
// printf("[");
// for (int i = 0; i < out_features; i++) {
// printf("%f, ", output[b * out_features + i]);
// }
// printf("]\n");
// }
// printf("]\n");
// }
}
// // https://arxiv.org/pdf/1910.07467
// __global__
// void rmsnorm_forward(float* o, float* x, float *weight, int batch, int dim) {
// // printf("rmsnorm_forward N:%d seq_len:%d dim:%d\n", batch, seq_len, dim);
// // int b = 0;
// // #pragma omp parallel for private(b)
// int bidx = blockIdx.x; // batch
// int bidy = blockIdx.y;
// int tid = threadIdx.x; // thread id
// int lid = tid % 32; // lane id
// int wid = tid / 32; // warp id
// int kWarp = blockDim.x / 32;
// extern __shared__ float smem_[];
// // 计算ss
// //
// float ss = 0.0f;
// int offset = bidx * dim;
// #pragma unroll
// for (int i = tid; i < dim; i += blockDim.x) {
// ss += x[offset + i] * x[offset + i];
// }
// #pragma unroll
// for (int mask = 32 / 2; mask > 0; mask /= 2) {
// ss += __shfl_down_sync(uint32_t(-1), ss, mask);
// }
// if (lid == 0) {
// int offset_warp = bidx * kWarp + wid;
// smem_[offset_warp] = ss;
// }
// __syncthreads();
// ss = 0.0f;
// for (int i = 0; i < kWarp; i++) {
// ss += smem_[bidx * kWarp + i];
// }
// ss /= dim;
// ss += 1e-6f;
// ss = 1.0f / sqrtf(ss);
// int offset_x = bidx * dim + bidy * blockDim.x + tid;
// int offset_w = bidy * blockDim.x + tid;
// int offset_o = bidx * dim + bidy * blockDim.x + tid;
// o[offset_o] = x[offset_x] * ss * weight[offset_w];
// // if (thread0()) {
// // printf("rmsnorm:\n");
// // for (int b = 0; b < batch; b++) {
// // int offset = b * dim;
// // printf("[");
// // for (int d = 0; d < dim; d++) {
// // printf("%f, ", o[offset + d]);
// // }
// // printf("],\n");
// // }
// // }
// }
// https://arxiv.org/pdf/1910.07467
__global__
void rmsnorm_forward(float* o, float* x, float *weight, int batch, int dim) {
// printf("rmsnorm_forward N:%d seq_len:%d dim:%d\n", batch, seq_len, dim);
// int b = 0;
// #pragma omp parallel for private(b)
int b = blockIdx.x; // batch
int bidy = blockIdx.y;
int tid = threadIdx.x; // thread id
int lid = tid % 32; // lane id
int wid = tid / 32; // warp id
int kWarp = blockDim.x / 32;
int kNThreads = blockDim.x;
extern __shared__ float smem_[];
// 计算ss
//
int offset = b * dim;
float ss = 0.0f;
for (int d = 0; d < dim; d++) {
ss += x[offset + d] * x[ offset + d];
}
ss /= dim;
ss += 1e-6f;
ss = 1.0f / sqrtf(ss);
for (int d = 0; d < dim; d++) {
o[offset + d] = x[offset + d] * ss * weight[d];
}
// if (thread0()) {
// printf("rmsnorm:\n");
// for (int b = 0; b < batch; b++) {
// int offset = b * dim;
// printf("[");
// for (int d = 0; d < dim; d++) {
// printf("%f, ", o[offset + d]);
// }
// printf("],\n");
// }
// }
}
__global__
void qkv_forward(float* input, float *q, float *qkv_proj, float *q_norm, float *k_norm,
float *key_cache, float *value_cache, int qkv_proj_offset, int rope_freq_constant_,
int batch, int q_heads, int k_heads, int v_heads, int head_dim, int model_dim, int max_kv_heads,
int max_seq_len, int num_transformer_layers, int layer_idx, int pos) {
int b = blockIdx.x; // batch
int bidy = blockIdx.y;
int tid = threadIdx.x; // thread id
int kNThreads = blockDim.x;
int out = bidy * kNThreads + tid;
int offset_q = b * q_heads * head_dim;
int offset_v = b * num_transformer_layers * max_seq_len * max_kv_heads * head_dim
+ layer_idx * max_seq_len * max_kv_heads * head_dim
+ pos * max_kv_heads * head_dim;
// int offset_bias = out;
float value = 0.0f;
for (int in = 0; in < model_dim; in++) {
int offset_in = b * model_dim + in;
int offset_weight = out * model_dim + in;
value += input[offset_in] * (qkv_proj + qkv_proj_offset)[offset_weight];
}
if (out < q_heads * head_dim) {
q[offset_q + out] = value;
} else if (out < (q_heads + k_heads) * head_dim) {
int offset_k = b * num_transformer_layers * max_seq_len * max_kv_heads * head_dim
+ layer_idx * max_seq_len * max_kv_heads * head_dim
+ pos * max_kv_heads * head_dim;
// if (offset_k + out - q_heads * head_dim == 0) {
// printf("batch:%d, num_transformer_layers:%d, max_seq_len:%d, kv_dim:%d, offset_k:%d pos:%d value=%f\n", batch, p->num_transformer_layers, s->max_seq_len, s->max_kv_heads * head_dim, offset_k, pos, value);
// }
key_cache[offset_k + out - q_heads * head_dim] = value;
} else if (out < (q_heads + k_heads + v_heads) * head_dim) {
value_cache[offset_v + out - (q_heads + k_heads) * head_dim] = value;
}
// if (thread0()) {
// // printf qeury
// printf("query:\n");
// for (int b = 0; b < batch; b++) {
// printf("[");
// for (int h = 0; h < q_heads; h++) {
// printf("[");
// int offset = b * q_heads * head_dim + h * head_dim;
// for (int hd = 0; hd < head_dim; hd++) {
// printf("%f,", q[offset + hd]);
// }
// printf("],\n");
// }
// printf("],\n");
// }
// // printf key
// printf("key:\n");
// for (int b = 0; b < batch; b++) {
// printf("[");
// for (int h = 0; h < k_heads; h++) {
// printf("[");
// int offset = b * num_transformer_layers * max_seq_len * max_kv_heads * head_dim
// + layer_idx * max_seq_len * max_kv_heads * head_dim
// + pos * max_kv_heads * head_dim
// + h * head_dim;
// printf("offset=%d ", offset);
// for (int hd = 0; hd < head_dim; hd++) {
// printf("%f,", key_cache[offset + hd]);
// }
// printf("],\n");
// }
// printf("],\n");
// }
// // printf value
// printf("value:\n");
// for (int b = 0; b < batch; b++) {
// printf("[");
// for (int h = 0; h < v_heads; h++) {
// printf("[");
// int offset = b * num_transformer_layers * max_seq_len * max_kv_heads * head_dim
// + layer_idx * max_seq_len * max_kv_heads * head_dim
// + pos * max_kv_heads * head_dim + h * head_dim;
// printf("offset=%d ", offset);
// for (int hd = 0; hd < head_dim; hd++) {
// printf("%f,", value_cache[offset + hd]);
// }
// printf("],\n");
// }
// printf("],\n");
// }
// }
}
// __global__
// void query_rope_forward(float *q, float *q_norm, int rope_freq_constant_, int batch, int q_heads, int head_dim, int layer_idx, int pos) {
// float rope_freq_constant = (float)rope_freq_constant_;
// int b = blockIdx.x;
// int h = blockIdx.y;
// int tid = threadIdx.x;
// int lid = tid % 32;
// int wid = tid / 32;
// int offset = b * q_heads * head_dim + h * head_dim;
// int kNThreads = blockDim.x;
// int kWarps = kNThreads / 32;
// extern __shared__ float smem_[];
// float ss = 0.0f;
// #pragma unroll
// for (int i = tid; i < head_dim; i += kNThreads) {
// ss += q[offset + i] * q[ offset + i];
// }
// #pragma unroll
// for (int mask = 32 / 2; mask > 0; mask /= 2) {
// ss += __shfl_down_sync(uint32_t(-1), ss, mask);
// }
// if (lid == 0) {
// int offset_warp = b * kWarps + wid;
// smem_[offset_warp] = ss;
// }
// __syncthreads();
// ss = 0.0f;
// for (int i = 0; i < kWarps; i++) {
// ss += smem_[b * kWarps + i];
// }
// // __syncthreads();
// ss /= head_dim;
// ss += 1e-6f;
// ss = 1.0f / sqrtf(ss);
// for (int hd = tid; hd < head_dim; hd += kNThreads) {
// q[offset + hd] = q[offset + hd] * ss * (q_norm + layer_idx * head_dim)[hd];
// }
// for (int hd = tid; hd < head_dim / 2; hd += kNThreads) {
// float v0 = q[offset + hd];
// float v1 = q[offset + hd + head_dim / 2];
// float freq = 1.0f / powf(rope_freq_constant, ((float)(2 * hd) / head_dim));
// // printf("sl=%d %d=%f ", sl, hd, sl * freq);
// float cos_val = cosf(pos * freq);
// float sin_val = sinf(pos * freq);
// // printf("sl=%d %d=%f ", sl, hd, sin_val);
// q[offset + hd] = v0 * cos_val - v1 * sin_val;
// q[offset + head_dim / 2 + hd] = v1 * cos_val + v0 * sin_val;
// // s->x_qkv_proj[offset + hd + head_dim / 2] = v0 * sin_val + v1 * cos_val;
// // printf("batch=%d seq_len=%d heads=%d %d=%f %f v=%f %f cos_sin=%f %f\n", b, sl, h, hd, s->x_qkv_proj[offset + hd], s->x_qkv_proj[offset + head_dim / 2 + hd],
// // v0, v1, cos_val, sin_val);
// // printf("batch=%d seq_len=%d heads=%d %d=%f %f\n", b, sl, h, hd, s->x_qkv_proj[offset + hd], s->x_qkv_proj[offset + head_dim / 2 + hd]);
// // printf("batch=%d seq_len=%d heads=%d %d=%f %f v=%f %f cos_sin=%f %f\n", b, sl, h, hd, s->x_qkv_proj[offset + hd], s->x_qkv_proj[offset + head_dim / 2 + hd], v0, v1, cos_val, sin_val);
// }
// // // printf query
// // if (thread0()) {
// // for (int b = 0; b < batch; b++) {
// // printf("[");
// // for (int h = 0; h < q_heads; h++) {
// // printf("[");
// // int offset = b * q_heads * head_dim + h * head_dim;
// // for (int hd = 0; hd < head_dim; hd++) {
// // printf("%f,", q[offset + hd]);
// // }
// // printf("],\n");
// // }
// // printf("],\n");
// // }
// // }
// }
__global__
void query_rope_forward(float *q, float *q_norm, int rope_freq_constant_, int batch, int q_heads, int head_dim, int layer_idx, int pos) {
float rope_freq_constant = (float)rope_freq_constant_;
int b = blockIdx.x;
int h = blockIdx.y;
int tid = threadIdx.x;
int lid = tid % 32;
int wid = tid / 32;
int offset = b * q_heads * head_dim + h * head_dim;
int kNThreads = blockDim.x;
int kWarps = kNThreads / 32;
extern __shared__ float smem_[];
float ss = 0.0f;
#pragma unroll
for (int i = 0; i < head_dim; i++) {
ss += q[offset + i] * q[ offset + i];
}
ss /= head_dim;
ss += 1e-6f;
ss = 1.0f / sqrtf(ss);
for (int hd = 0; hd < head_dim; hd++) {
q[offset + hd] = q[offset + hd] * ss * (q_norm + layer_idx * head_dim)[hd];
}
for (int hd = 0; hd < head_dim / 2; hd++) {
float v0 = q[offset + hd];
float v1 = q[offset + hd + head_dim / 2];
float freq = 1.0f / powf(rope_freq_constant, ((float)(2 * hd) / head_dim));
// printf("sl=%d %d=%f ", sl, hd, sl * freq);
float cos_val = cosf(pos * freq);
float sin_val = sinf(pos * freq);
// printf("sl=%d %d=%f ", sl, hd, sin_val);
q[offset + hd] = v0 * cos_val - v1 * sin_val;
q[offset + head_dim / 2 + hd] = v1 * cos_val + v0 * sin_val;
// s->x_qkv_proj[offset + hd + head_dim / 2] = v0 * sin_val + v1 * cos_val;
// printf("batch=%d seq_len=%d heads=%d %d=%f %f v=%f %f cos_sin=%f %f\n", b, sl, h, hd, s->x_qkv_proj[offset + hd], s->x_qkv_proj[offset + head_dim / 2 + hd],
// v0, v1, cos_val, sin_val);
// printf("batch=%d seq_len=%d heads=%d %d=%f %f\n", b, sl, h, hd, s->x_qkv_proj[offset + hd], s->x_qkv_proj[offset + head_dim / 2 + hd]);
// printf("batch=%d seq_len=%d heads=%d %d=%f %f v=%f %f cos_sin=%f %f\n", b, sl, h, hd, s->x_qkv_proj[offset + hd], s->x_qkv_proj[offset + head_dim / 2 + hd], v0, v1, cos_val, sin_val);
}
// // printf query
// if (thread0()) {
// for (int b = 0; b < batch; b++) {
// printf("[");
// for (int h = 0; h < q_heads; h++) {
// printf("[");
// int offset = b * q_heads * head_dim + h * head_dim;
// for (int hd = 0; hd < head_dim; hd++) {
// printf("%f,", q[offset + hd]);
// }
// printf("],\n");
// }
// printf("],\n");
// }
// }
}
// __global__
// void key_rope_forward(float *key_cache, float *k_norm, int rope_freq_constant_,
// int batch, int k_heads, int head_dim, int max_kv_heads,
// int max_seq_len, int num_transformer_layers, int layer_idx, int pos) {
// float rope_freq_constant = (float)rope_freq_constant_;
// int b = blockIdx.x;
// int h = blockIdx.y;
// int tid = threadIdx.x;
// int lid = tid % 32;
// int wid = tid / 32;
// int offset = b * num_transformer_layers * max_seq_len * max_kv_heads * head_dim
// + layer_idx * max_seq_len * max_kv_heads * head_dim + pos * max_kv_heads * head_dim + h * head_dim;
// int kNThreads = blockDim.x;
// int kWarps = kNThreads / 32;
// extern __shared__ float smem_[];
// float ss = 0.0f;
// #pragma unroll
// for (int i = tid; i < head_dim; i += kNThreads) {
// ss += key_cache[offset + i] * key_cache[ offset + i];
// }
// #pragma unroll
// for (int mask = 32 / 2; mask > 0; mask /= 2) {
// ss += __shfl_down_sync(uint32_t(-1), ss, mask);
// }
// if (lid == 0) {
// int offset_warp = b * kWarps + wid;
// smem_[offset_warp] = ss;
// }
// __syncthreads();
// ss = 0.0f;
// for (int i = 0; i < kWarps; i++) {
// ss += smem_[b * kWarps + i];
// }
// // __syncthreads();
// ss /= head_dim;
// ss += 1e-6f;
// ss = 1.0f / sqrtf(ss);
// for (int hd = tid; hd < head_dim; hd += kNThreads) {
// key_cache[offset + hd] = key_cache[offset + hd] * ss * (k_norm + layer_idx * head_dim)[hd];
// }
// for (int hd = tid; hd < head_dim / 2; hd += kNThreads) {
// float v0 = key_cache[offset + hd];
// float v1 = key_cache[offset + hd + head_dim / 2];
// float freq = 1.0f / powf(rope_freq_constant, ((float)(2 * hd) / head_dim));
// // printf("sl=%d %d=%f ", sl, hd, sl * freq);
// float cos_val = cosf(pos * freq);
// float sin_val = sinf(pos * freq);
// // printf("sl=%d %d=%f ", sl, hd, sin_val);
// key_cache[offset + hd] = v0 * cos_val - v1 * sin_val;
// key_cache[offset + head_dim / 2 + hd] = v1 * cos_val + v0 * sin_val;
// }
// // if (thread0()) {
// // for (int b = 0; b < batch; b++) {
// // printf("[");
// // for (int h = 0; h < k_heads; h++) {
// // printf("[");
// // int offset = b * num_transformer_layers * max_seq_len * max_kv_heads * head_dim
// // + layer_idx * max_seq_len * max_kv_heads * head_dim + 0 * max_kv_heads * head_dim
// // + h * head_dim;
// // printf("offset=%d ", offset);
// // for (int hd = 0; hd < head_dim; hd++) {
// // printf("%f,", key_cache[offset + hd]);
// // }
// // printf("],\n");
// // }
// // printf("],\n");
// // }
// // }
// }
__global__
void key_rope_forward(float *key_cache, float *k_norm, int rope_freq_constant_,
int batch, int k_heads, int head_dim, int max_kv_heads,
int max_seq_len, int num_transformer_layers, int layer_idx, int pos) {
float rope_freq_constant = (float)rope_freq_constant_;
int b = blockIdx.x;
int h = blockIdx.y;
int tid = threadIdx.x;
int lid = tid % 32;
int wid = tid / 32;
int offset = b * num_transformer_layers * max_seq_len * max_kv_heads * head_dim
+ layer_idx * max_seq_len * max_kv_heads * head_dim + pos * max_kv_heads * head_dim + h * head_dim;
int kNThreads = blockDim.x;
int kWarps = kNThreads / 32;
extern __shared__ float smem_[];
float ss = 0.0f;
#pragma unroll
for (int i = 0; i < head_dim; i++) {
ss += key_cache[offset + i] * key_cache[ offset + i];
}
ss /= head_dim;
ss += 1e-6f;
ss = 1.0f / sqrtf(ss);
for (int hd = 0; hd < head_dim; hd++) {
key_cache[offset + hd] = key_cache[offset + hd] * ss * (k_norm + layer_idx * head_dim)[hd];
}
for (int hd = 0; hd < head_dim / 2; hd++) {
float v0 = key_cache[offset + hd];
float v1 = key_cache[offset + hd + head_dim / 2];
float freq = 1.0f / powf(rope_freq_constant, ((float)(2 * hd) / head_dim));
// printf("sl=%d %d=%f ", sl, hd, sl * freq);
float cos_val = cosf(pos * freq);
float sin_val = sinf(pos * freq);
// printf("sl=%d %d=%f ", sl, hd, sin_val);
key_cache[offset + hd] = v0 * cos_val - v1 * sin_val;
key_cache[offset + head_dim / 2 + hd] = v1 * cos_val + v0 * sin_val;
}
// if (thread0()) {
// for (int b = 0; b < batch; b++) {
// printf("[");
// for (int h = 0; h < k_heads; h++) {
// printf("[");
// int offset = b * num_transformer_layers * max_seq_len * max_kv_heads * head_dim
// + layer_idx * max_seq_len * max_kv_heads * head_dim + 0 * max_kv_heads * head_dim
// + h * head_dim;
// printf("offset=%d ", offset);
// for (int hd = 0; hd < head_dim; hd++) {
// printf("%f,", key_cache[offset + hd]);
// }
// printf("],\n");
// }
// printf("],\n");
// }
// }
}
__global__
void rmsnorm_rope_forward(float* input, float *q, float *qkv_proj, float *q_norm, float *k_norm,
float *key_cache, float *value_cache, int qkv_proj_offset, int rope_freq_constant_,
int batch, int q_heads, int k_heads, int v_heads, int head_dim, int model_dim, int max_kv_heads,
int max_seq_len, int num_transformer_layers, int layer_idx, int pos) {
}
// __global__
// void group_attention_forward(float* output, float *q, float *key_cache, float *value_cache, float *att,
// int batch, int q_heads, int k_heads, int head_dim, int max_q_heads, int max_kv_heads, int max_seq_len,
// int num_transformer_layers, int layer_idx, int pos) {
// int num_groups = q_heads / k_heads;
// int b = blockIdx.x;
// int h = blockIdx.y;
// int tid = threadIdx.x;
// int kNThreads = blockDim.x;
// int kWarps = kNThreads / 32;
// int lid = tid % 32; // lane id
// int wid = tid / 32; // warp id
// extern __shared__ float smem_[];
// int offset_att = b * max_q_heads * max_seq_len + h * max_seq_len;
// int offset_q = b * q_heads * head_dim + h * head_dim;
// for (int lk = tid; lk < pos + 1; lk += kNThreads) {
// int offset_k = b * num_transformer_layers * max_seq_len * max_kv_heads * head_dim
// + layer_idx * max_seq_len * max_kv_heads * head_dim
// + lk * max_kv_heads * head_dim
// + (h / num_groups) * head_dim;
// float score = 0.0f;
// for (int i = 0; i < head_dim; i++) {
// score += q[offset_q + i] * key_cache[offset_k + i];
// // if (h == 0 && lk == 0) {
// // printf("offset_k:%d batch:%d, i:%d, q:%f, k:%f\n", offset_k, b, i, s->q[offset_q+i], s->key_cache[offset_k + i]);
// // }
// }
// score /= sqrtf((float)head_dim);
// att[offset_att + lk] = score;
// // printf("%f ", score);
// }
// // printf("\n");
// float max_val = att[offset_att];
// for (int lk = tid; lk < pos + 1; lk += kNThreads) {
// if (att[offset_att + lk] > max_val) {
// max_val = att[offset_att + lk];
// }
// }
// #pragma unroll
// for (int mask = 32 / 2; mask > 0; mask /= 2) {
// float shfl_max = __shfl_down_sync(uint32_t(-1), max_val, mask);
// if (shfl_max > max_val) {
// max_val = shfl_max;
// }
// }
// if (lid == 0) {
// int offset_warp = b * kWarps + wid;
// smem_[offset_warp] = max_val;
// }
// __syncthreads();
// for (int i = 0; i < kWarps; i++) {
// if (max_val < smem_[b * kWarps + i]) {
// max_val = smem_[b * kWarps + i];
// }
// }
// // __syncthreads();
// float ss = 0.0f;
// #pragma unroll
// for (int lk = tid; lk < pos + 1; lk += kNThreads) {
// ss += expf(att[offset_att + lk] - max_val);
// }
// #pragma unroll
// for (int mask = 32 / 2; mask > 0; mask /= 2) {
// ss += __shfl_down_sync(uint32_t(-1), ss, mask);
// }
// if (lid == 0) {
// int offset_warp = b * kWarps + wid;
// smem_[offset_warp] = ss;
// }
// __syncthreads();
// ss = 0.0f;
// for (int i = 0; i < kWarps; i++) {
// ss += smem_[b * kWarps + i];
// }
// for (int lk = tid; lk < pos + 1; lk += kNThreads) {
// att[offset_att + lk] = expf(att[offset_att + lk] - max_val) / ss;
// }
// int offset_o = b * q_heads * head_dim + h * head_dim;
// for (int lv = tid; lv < head_dim; lv += kNThreads){
// float sv = 0.0f;
// for (int k = 0; k < pos + 1; k++) {
// int offset_v = b * num_transformer_layers * max_seq_len * max_kv_heads * head_dim
// + layer_idx * max_seq_len * max_kv_heads * head_dim
// + k * max_kv_heads * head_dim
// + (h / num_groups) * head_dim;
// sv += att[offset_att + k] * (value_cache[offset_v + lv]);
// }
// output[offset_o + lv] = sv;
// }
// // if (thread0()) {
// // printf("group_attention:\n");
// // for (int b = 0; b < batch; b++) {
// // printf("[");
// // for (int d = 0; d < q_heads * head_dim; d++) {
// // int offset = b * q_heads * head_dim;
// // printf("%f, ",output[offset + d]);
// // }
// // printf("],\n");
// // }
// // }
// }
__global__
void group_attention_forward(float* output, float *q, float *key_cache, float *value_cache, float *att,
int batch, int q_heads, int k_heads, int head_dim, int max_q_heads, int max_kv_heads, int max_seq_len,
int num_transformer_layers, int layer_idx, int pos) {
int num_groups = q_heads / k_heads;
int b = blockIdx.x;
int h = blockIdx.y;
int tid = threadIdx.x;
int kNThreads = blockDim.x;
int kWarps = kNThreads / 32;
int lid = tid % 32; // lane id
int wid = tid / 32; // warp id
extern __shared__ float smem_[];
int offset_att = b * max_q_heads * max_seq_len + h * max_seq_len;
int offset_q = b * q_heads * head_dim + h * head_dim;
for (int lk = 0; lk < pos + 1; lk++) {
int offset_k = b * num_transformer_layers * max_seq_len * max_kv_heads * head_dim
+ layer_idx * max_seq_len * max_kv_heads * head_dim
+ lk * max_kv_heads * head_dim