forked from antirez/ds4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathds4_cuda.cu
More file actions
10761 lines (10304 loc) · 460 KB
/
Copy pathds4_cuda.cu
File metadata and controls
10761 lines (10304 loc) · 460 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.h>
#include <cuda_fp16.h>
#include <mma.h>
#include <cublas_v2.h>
#include <cub/block/block_radix_sort.cuh>
#include <stdint.h>
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <unordered_map>
#include <vector>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define CUDA_QK_K 256
#define DS4_CUDA_UNUSED __attribute__((unused))
enum {
/* attention_decode_mixed_kernel stores raw-window scores plus visible
* compressed scores in shared memory. The host routes larger unmasked
* decode calls to the online attention kernel so this fixed buffer never
* becomes an out-of-bounds write at long context. */
DS4_CUDA_ATTENTION_SCORE_CAP = 8192u,
DS4_CUDA_ATTENTION_RAW_SCORE_CAP = 256u,
DS4_CUDA_TOPK_MERGE_GROUP = 8u
};
struct ds4_gpu_tensor {
void *ptr;
uint64_t bytes;
int owner;
};
typedef struct {
uint8_t scales[CUDA_QK_K / 16];
uint8_t qs[CUDA_QK_K / 4];
uint16_t d;
uint16_t dmin;
} cuda_block_q2_K;
typedef struct {
uint16_t d;
uint16_t dmin;
uint8_t scales[12];
uint8_t qs[CUDA_QK_K / 2];
} cuda_block_q4_K;
typedef struct {
float d;
int8_t qs[CUDA_QK_K];
int16_t bsums[CUDA_QK_K / 16];
} cuda_block_q8_K;
typedef struct {
uint16_t d;
uint16_t qs[CUDA_QK_K / 8];
} cuda_block_iq2_xxs;
#include "ds4_iq2_tables_cuda.inc"
static const void *g_model_host_base;
static const char *g_model_device_base;
static uint64_t g_model_registered_size;
static int g_model_registered;
static int g_model_device_owned;
static int g_model_range_mapping_supported = 1;
static int g_model_hmm_direct;
static int g_model_fd = -1;
static const void *g_model_fd_host_base;
static int g_model_direct_fd = -1;
static uint64_t g_model_direct_align = 1;
static uint64_t g_model_file_size;
static int g_model_cache_full;
static cudaStream_t g_model_prefetch_stream;
static cudaStream_t g_model_upload_stream;
static cublasHandle_t g_cublas;
static int g_cublas_ready;
static int g_quality_mode;
struct cuda_model_range {
const void *host_base;
uint64_t offset;
uint64_t bytes;
char *device_ptr;
void *registered_base;
char *registered_device_base;
uint64_t registered_bytes;
int host_registered;
int arena_allocated;
};
struct cuda_model_arena {
char *device_ptr;
uint64_t bytes;
uint64_t used;
};
struct cuda_q8_f16_range {
const void *host_base;
uint64_t offset;
uint64_t weight_bytes;
uint64_t in_dim;
uint64_t out_dim;
__half *device_ptr;
};
struct cuda_q8_f32_range {
const void *host_base;
uint64_t offset;
uint64_t weight_bytes;
uint64_t in_dim;
uint64_t out_dim;
float *device_ptr;
};
static std::vector<cuda_model_range> g_model_ranges;
static std::vector<cuda_model_arena> g_model_arenas;
static std::unordered_map<uint64_t, size_t> g_model_range_by_offset;
static std::vector<cuda_q8_f16_range> g_q8_f16_ranges;
static std::unordered_map<uint64_t, size_t> g_q8_f16_by_offset;
static std::vector<cuda_q8_f32_range> g_q8_f32_ranges;
static std::unordered_map<uint64_t, size_t> g_q8_f32_by_offset;
static uint64_t g_model_range_bytes;
static uint64_t g_q8_f16_bytes;
static uint64_t g_q8_f32_bytes;
static int g_q8_f16_disabled_after_oom;
static int g_q8_f16_budget_notice_printed;
static uint64_t g_model_load_progress_next;
static double g_model_load_progress_last;
static int g_model_load_progress_started;
static int g_model_load_progress_tty;
static void *g_cuda_tmp;
static uint64_t g_cuda_tmp_bytes;
static void *g_model_stage_raw[4];
static void *g_model_stage[4];
static cudaEvent_t g_model_stage_event[4];
static uint64_t g_model_stage_bytes;
static int cuda_ok(cudaError_t err, const char *what);
static const char *cuda_model_range_ptr_from_fd(
const void *model_map,
uint64_t offset,
uint64_t bytes,
const char *what);
__global__ static void dequant_q8_0_to_f16_kernel(
__half *out,
const unsigned char *w,
uint64_t in_dim,
uint64_t out_dim,
uint64_t blocks);
__global__ static void dequant_q8_0_to_f32_kernel(
float *out,
const unsigned char *w,
uint64_t in_dim,
uint64_t out_dim,
uint64_t blocks);
static void *cuda_tmp_alloc(uint64_t bytes, const char *what) {
if (bytes == 0) return NULL;
if (g_cuda_tmp_bytes >= bytes) return g_cuda_tmp;
if (g_cuda_tmp) {
(void)cudaFree(g_cuda_tmp);
g_cuda_tmp = NULL;
g_cuda_tmp_bytes = 0;
}
void *ptr = NULL;
cudaError_t err = cudaMalloc(&ptr, (size_t)bytes);
if (err != cudaSuccess) {
fprintf(stderr, "ds4: CUDA temp alloc failed for %s (%.2f MiB): %s\n",
what ? what : "scratch", (double)bytes / 1048576.0, cudaGetErrorString(err));
(void)cudaGetLastError();
return NULL;
}
g_cuda_tmp = ptr;
g_cuda_tmp_bytes = bytes;
return g_cuda_tmp;
}
static int cuda_attention_score_buffer_fits(uint32_t n_comp) {
return n_comp <= DS4_CUDA_ATTENTION_SCORE_CAP - DS4_CUDA_ATTENTION_RAW_SCORE_CAP;
}
static const char *cuda_model_ptr(const void *model_map, uint64_t offset) {
if (model_map == g_model_host_base && g_model_device_base) return g_model_device_base + offset;
return (const char *)model_map + offset;
}
static const char *cuda_model_range_ptr(const void *model_map, uint64_t offset, uint64_t bytes, const char *what) {
if (bytes == 0) return cuda_model_ptr(model_map, offset);
if (g_model_device_owned || g_model_registered) return cuda_model_ptr(model_map, offset);
if (g_model_hmm_direct &&
getenv("DS4_CUDA_WEIGHT_CACHE") == NULL &&
getenv("DS4_CUDA_WEIGHT_PRELOAD") == NULL) {
return cuda_model_ptr(model_map, offset);
}
const char *direct_env = getenv("DS4_CUDA_DIRECT_MODEL");
if (direct_env && direct_env[0]) return cuda_model_ptr(model_map, offset);
const uint64_t end = offset + bytes;
auto exact = g_model_range_by_offset.find(offset);
if (exact != g_model_range_by_offset.end()) {
const cuda_model_range &r = g_model_ranges[exact->second];
if (r.host_base == model_map && end >= offset && bytes <= r.bytes) return r.device_ptr;
}
for (const cuda_model_range &r : g_model_ranges) {
if (r.host_base == model_map && offset >= r.offset && end >= offset && end <= r.offset + r.bytes) {
return r.device_ptr + (offset - r.offset);
}
if (r.host_base == model_map && r.host_registered && r.registered_base && r.registered_device_base) {
const uintptr_t h0 = (uintptr_t)((const char *)model_map + offset);
const uintptr_t h1 = h0 + bytes;
const uintptr_t r0 = (uintptr_t)r.registered_base;
const uintptr_t r1 = r0 + r.registered_bytes;
if (h1 >= h0 && h0 >= r0 && h1 <= r1) return r.registered_device_base + (h0 - r0);
}
}
if (getenv("DS4_CUDA_NO_FD_CACHE") == NULL) {
const char *fd_ptr = cuda_model_range_ptr_from_fd(model_map, offset, bytes, what);
if (fd_ptr) return fd_ptr;
}
cudaError_t err = cudaSuccess;
if (g_model_range_mapping_supported) {
const long page_sz_l = sysconf(_SC_PAGESIZE);
const uint64_t page_sz = page_sz_l > 0 ? (uint64_t)page_sz_l : 4096u;
const uintptr_t host_addr = (uintptr_t)((const char *)model_map + offset);
const uintptr_t reg_addr = host_addr & ~(uintptr_t)(page_sz - 1u);
const uint64_t reg_delta = (uint64_t)(host_addr - reg_addr);
const uint64_t reg_bytes = (reg_delta + bytes + page_sz - 1u) & ~(page_sz - 1u);
void *reg_dev = NULL;
err = cudaHostRegister((void *)reg_addr,
(size_t)reg_bytes,
cudaHostRegisterMapped | cudaHostRegisterReadOnly);
if (err == cudaSuccess) {
err = cudaHostGetDevicePointer(®_dev, (void *)reg_addr, 0);
if (err == cudaSuccess && reg_dev) {
char *dev_ptr = (char *)reg_dev + reg_delta;
g_model_ranges.push_back({model_map, offset, bytes, dev_ptr, (void *)reg_addr, (char *)reg_dev, reg_bytes, 1, 0});
g_model_range_by_offset[offset] = g_model_ranges.size() - 1u;
if (getenv("DS4_CUDA_WEIGHT_CACHE_VERBOSE")) {
fprintf(stderr, "ds4: CUDA mapped %s %.2f MiB\n",
what ? what : "weights",
(double)bytes / 1048576.0);
}
return dev_ptr;
}
fprintf(stderr, "ds4: CUDA model range map pointer failed for %s: %s\n",
what ? what : "weights", cudaGetErrorString(err));
(void)cudaHostUnregister((void *)reg_addr);
(void)cudaGetLastError();
} else {
if (err == cudaErrorNotSupported || err == cudaErrorInvalidValue) g_model_range_mapping_supported = 0;
(void)cudaGetLastError();
}
}
void *dev = NULL;
err = cudaMalloc(&dev, (size_t)bytes);
if (err != cudaSuccess) {
(void)cudaGetLastError();
fprintf(stderr, "ds4: CUDA model range alloc failed for %s (%.2f MiB): %s\n",
what ? what : "weights", (double)bytes / 1048576.0, cudaGetErrorString(err));
return NULL;
}
const char *src = (const char *)model_map + offset;
const uint64_t chunk = 64ull * 1024ull * 1024ull;
for (uint64_t done = 0; done < bytes; done += chunk) {
uint64_t n = bytes - done < chunk ? bytes - done : chunk;
err = cudaMemcpy((char *)dev + done, src + done, (size_t)n, cudaMemcpyHostToDevice);
if (err != cudaSuccess) {
fprintf(stderr, "ds4: CUDA model range copy failed for %s at %.2f/%.2f MiB: %s\n",
what ? what : "weights",
(double)done / 1048576.0,
(double)bytes / 1048576.0,
cudaGetErrorString(err));
(void)cudaFree(dev);
(void)cudaGetLastError();
return NULL;
}
}
g_model_ranges.push_back({model_map, offset, bytes, (char *)dev, NULL, NULL, 0, 0, 0});
g_model_range_by_offset[offset] = g_model_ranges.size() - 1u;
g_model_range_bytes += bytes;
if (getenv("DS4_CUDA_WEIGHT_CACHE_VERBOSE")) {
fprintf(stderr, "ds4: CUDA cached %s %.2f MiB (total %.2f GiB)\n",
what ? what : "weights",
(double)bytes / 1048576.0,
(double)g_model_range_bytes / 1073741824.0);
}
return (const char *)dev;
}
static int cuda_model_range_is_cached(const void *model_map, uint64_t offset, uint64_t bytes) {
if (bytes == 0) return 1;
if (g_model_device_owned || g_model_registered) return 1;
const uint64_t end = offset + bytes;
if (end < offset) return 0;
for (const cuda_model_range &r : g_model_ranges) {
if (r.host_base == model_map &&
offset >= r.offset &&
end <= r.offset + r.bytes) {
return 1;
}
if (r.host_base == model_map &&
r.host_registered &&
r.registered_base &&
r.registered_device_base) {
const uintptr_t h0 = (uintptr_t)((const char *)model_map + offset);
const uintptr_t h1 = h0 + bytes;
const uintptr_t r0 = (uintptr_t)r.registered_base;
const uintptr_t r1 = r0 + r.registered_bytes;
if (h1 >= h0 && h0 >= r0 && h1 <= r1) return 1;
}
}
return 0;
}
static void cuda_q8_f16_cache_release_all(void) {
for (const cuda_q8_f16_range &r : g_q8_f16_ranges) {
(void)cudaFree(r.device_ptr);
}
g_q8_f16_ranges.clear();
g_q8_f16_by_offset.clear();
g_q8_f16_bytes = 0;
}
static uint64_t cuda_parse_mib_env(const char *name, int *present) {
const char *env = getenv(name);
if (present) *present = 0;
if (!env || !env[0]) return 0;
char *end = NULL;
unsigned long long v = strtoull(env, &end, 10);
if (end == env || *end != '\0') return 0;
if (present) *present = 1;
if (v > UINT64_MAX / 1048576ull) return UINT64_MAX;
return (uint64_t)v * 1048576ull;
}
static uint64_t cuda_q8_f16_cache_limit_bytes(void) {
int present = 0;
const uint64_t limit = cuda_parse_mib_env("DS4_CUDA_Q8_F16_CACHE_MB", &present);
return present ? limit : UINT64_MAX;
}
static uint64_t cuda_q8_f16_cache_reserve_bytes(uint64_t total_bytes) {
int present = 0;
const uint64_t reserve = cuda_parse_mib_env("DS4_CUDA_Q8_F16_CACHE_RESERVE_MB", &present);
if (present) return reserve;
if (total_bytes >= 112ull * 1024ull * 1024ull * 1024ull) {
return 512ull * 1048576ull;
}
/* The expanded Q8->F16 cache is only an acceleration path. Keep enough
* device memory free for cuBLAS workspaces, transient graph buffers, and
* driver bookkeeping instead of letting optional cached weights consume the
* last few GiB on 96 GiB cards. */
const uint64_t min_reserve = 4096ull * 1048576ull;
const uint64_t pct_reserve = total_bytes / 20u; /* 5% */
return pct_reserve > min_reserve ? pct_reserve : min_reserve;
}
static void cuda_q8_f16_cache_budget_notice(
const char *reason,
uint64_t request_bytes,
uint64_t free_bytes,
uint64_t total_bytes,
uint64_t reserve_bytes,
uint64_t limit_bytes) {
if (g_q8_f16_budget_notice_printed && getenv("DS4_CUDA_WEIGHT_CACHE_VERBOSE") == NULL) return;
g_q8_f16_budget_notice_printed = 1;
if (limit_bytes != UINT64_MAX && free_bytes == 0 && total_bytes == 0 && reserve_bytes == 0) {
fprintf(stderr,
"ds4: CUDA q8 fp16 cache %s; using q8 kernels "
"(request=%.2f MiB cached=%.2f GiB limit=%.2f GiB)\n",
reason,
(double)request_bytes / 1048576.0,
(double)g_q8_f16_bytes / 1073741824.0,
(double)limit_bytes / 1073741824.0);
} else if (limit_bytes == UINT64_MAX) {
fprintf(stderr,
"ds4: CUDA q8 fp16 cache %s; using q8 kernels "
"(request=%.2f MiB cached=%.2f GiB free=%.2f GiB reserve=%.2f GiB total=%.2f GiB)\n",
reason,
(double)request_bytes / 1048576.0,
(double)g_q8_f16_bytes / 1073741824.0,
(double)free_bytes / 1073741824.0,
(double)reserve_bytes / 1073741824.0,
(double)total_bytes / 1073741824.0);
} else {
fprintf(stderr,
"ds4: CUDA q8 fp16 cache %s; using q8 kernels "
"(request=%.2f MiB cached=%.2f GiB limit=%.2f GiB free=%.2f GiB reserve=%.2f GiB total=%.2f GiB)\n",
reason,
(double)request_bytes / 1048576.0,
(double)g_q8_f16_bytes / 1073741824.0,
(double)limit_bytes / 1073741824.0,
(double)free_bytes / 1073741824.0,
(double)reserve_bytes / 1073741824.0,
(double)total_bytes / 1073741824.0);
}
}
static int cuda_q8_f16_cache_has_budget(uint64_t request_bytes, const char *label) {
(void)label;
const uint64_t limit = cuda_q8_f16_cache_limit_bytes();
if (limit == 0) return 0;
if (g_q8_f16_bytes > limit || request_bytes > limit - g_q8_f16_bytes) {
cuda_q8_f16_cache_budget_notice("limit reached", request_bytes, 0, 0, 0, limit);
return 0;
}
size_t free_b = 0;
size_t total_b = 0;
cudaError_t err = cudaMemGetInfo(&free_b, &total_b);
if (err != cudaSuccess) {
fprintf(stderr, "ds4: CUDA q8 fp16 cache memory query failed: %s; using q8 kernels\n",
cudaGetErrorString(err));
(void)cudaGetLastError();
return 0;
}
const uint64_t free_bytes = (uint64_t)free_b;
const uint64_t total_bytes = (uint64_t)total_b;
const uint64_t reserve_bytes = cuda_q8_f16_cache_reserve_bytes(total_bytes);
if (request_bytes > free_bytes ||
free_bytes - request_bytes < reserve_bytes) {
cuda_q8_f16_cache_budget_notice("budget exhausted", request_bytes,
free_bytes, total_bytes,
reserve_bytes, limit);
return 0;
}
return 1;
}
static void cuda_q8_f16_cache_disable_after_failure(const char *what, uint64_t request_bytes) {
if (!g_q8_f16_disabled_after_oom) {
fprintf(stderr,
"ds4: CUDA q8 fp16 cache disabled after %s "
"(request=%.2f MiB cached=%.2f GiB); using q8 kernels\n",
what ? what : "allocation failure",
(double)request_bytes / 1048576.0,
(double)g_q8_f16_bytes / 1073741824.0);
}
g_q8_f16_disabled_after_oom = 1;
if (!g_q8_f16_ranges.empty()) {
(void)cudaDeviceSynchronize();
cuda_q8_f16_cache_release_all();
}
(void)cudaGetLastError();
}
static int cuda_q8_f16_cache_allowed(const char *label, uint64_t in_dim, uint64_t out_dim) {
if (g_quality_mode) return 0;
if (g_q8_f16_disabled_after_oom) return 0;
if (getenv("DS4_CUDA_NO_Q8_F16_CACHE") != NULL) return 0;
if (cuda_q8_f16_cache_limit_bytes() == 0) return 0;
if (getenv("DS4_CUDA_Q8_F16_ALL") != NULL) return 1;
if (!label) return 0;
if (strstr(label, "attn_output_a") != NULL ||
strstr(label, "attn_output_b") != NULL ||
strstr(label, "attention_output_a") != NULL ||
strstr(label, "attention_output_b") != NULL) {
return getenv("DS4_CUDA_NO_ATTENTION_OUTPUT_F16_CACHE") == NULL;
}
if (strstr(label, "attn_q_b") != NULL) {
return getenv("DS4_CUDA_NO_ATTN_Q_B_F16_CACHE") == NULL;
}
if (strstr(label, "ffn_gate_shexp") != NULL ||
strstr(label, "ffn_up_shexp") != NULL ||
strstr(label, "ffn_down_shexp") != NULL) {
return 1;
}
return (in_dim == 4096u && out_dim == 2048u) ||
(in_dim == 2048u && out_dim == 4096u) ||
(in_dim == 4096u && out_dim == 1024u) ||
(in_dim == 4096u && out_dim == 512u) ||
(getenv("DS4_CUDA_NO_ATTN_Q_B_F16_CACHE") == NULL &&
in_dim == 1024u && out_dim == 32768u);
}
static int cuda_q8_label_is_attention_output(const char *label) {
return label &&
(strstr(label, "attn_output_a") != NULL ||
strstr(label, "attn_output_b") != NULL ||
strstr(label, "attention_output_a") != NULL ||
strstr(label, "attention_output_b") != NULL);
}
static int cuda_q8_use_dp4a(void) {
return getenv("DS4_CUDA_NO_Q8_DP4A") == NULL;
}
static int cuda_q8_f16_preload_allowed(const char *label, uint64_t in_dim, uint64_t out_dim) {
if (cuda_q8_label_is_attention_output(label) &&
getenv("DS4_CUDA_ATTENTION_OUTPUT_PRELOAD") == NULL &&
getenv("DS4_CUDA_Q8_F16_ALL") == NULL) {
return 0;
}
return cuda_q8_f16_cache_allowed(label, in_dim, out_dim);
}
static int cuda_q8_f32_cache_allowed(const char *label, uint64_t in_dim, uint64_t out_dim) {
if (getenv("DS4_CUDA_NO_Q8_F32_CACHE") != NULL) return 0;
if (getenv("DS4_CUDA_Q8_F32_ALL") != NULL) return 1;
if (label && strstr(label, "attn_q_b") != NULL) {
return getenv("DS4_CUDA_ATTN_Q_B_F32_CACHE") != NULL;
}
return getenv("DS4_CUDA_Q8_F32_LARGE") != NULL &&
in_dim == 1024u && out_dim == 32768u;
}
static const __half *cuda_q8_f16_ptr(
const void *model_map,
uint64_t offset,
uint64_t weight_bytes,
uint64_t in_dim,
uint64_t out_dim,
const char *label) {
auto exact = g_q8_f16_by_offset.find(offset);
if (exact != g_q8_f16_by_offset.end()) {
const cuda_q8_f16_range &r = g_q8_f16_ranges[exact->second];
if (r.host_base == model_map && r.weight_bytes == weight_bytes &&
r.in_dim == in_dim && r.out_dim == out_dim) {
return r.device_ptr;
}
}
if (!cuda_q8_f16_cache_allowed(label, in_dim, out_dim)) return NULL;
const char *q8 = cuda_model_range_ptr(model_map, offset, weight_bytes, "q8_0");
if (!q8) return NULL;
if (in_dim != 0 && out_dim > UINT64_MAX / in_dim / sizeof(__half)) return NULL;
const uint64_t out_bytes = in_dim * out_dim * sizeof(__half);
if (!cuda_q8_f16_cache_has_budget(out_bytes, label)) return NULL;
__half *dev = NULL;
cudaError_t err = cudaMalloc(&dev, (size_t)out_bytes);
if (err != cudaSuccess) {
fprintf(stderr, "ds4: CUDA q8 fp16 cache alloc failed (%.2f MiB): %s\n",
(double)out_bytes / 1048576.0, cudaGetErrorString(err));
cuda_q8_f16_cache_disable_after_failure("allocation failure", out_bytes);
return NULL;
}
const uint64_t blocks = (in_dim + 31) / 32;
const uint64_t n = in_dim * out_dim;
dequant_q8_0_to_f16_kernel<<<(n + 255) / 256, 256>>>(dev,
(const unsigned char *)q8,
in_dim,
out_dim,
blocks);
if (!cuda_ok(cudaGetLastError(), "q8 fp16 dequant launch")) {
(void)cudaFree(dev);
cuda_q8_f16_cache_disable_after_failure("dequant launch failure", out_bytes);
return NULL;
}
g_q8_f16_ranges.push_back({model_map, offset, weight_bytes, in_dim, out_dim, dev});
g_q8_f16_by_offset[offset] = g_q8_f16_ranges.size() - 1u;
g_q8_f16_bytes += out_bytes;
if (getenv("DS4_CUDA_WEIGHT_CACHE_VERBOSE")) {
fprintf(stderr, "ds4: CUDA cached q8 fp16 %.2f MiB (total %.2f GiB)\n",
(double)out_bytes / 1048576.0,
(double)g_q8_f16_bytes / 1073741824.0);
}
return dev;
}
static float *cuda_q8_f32_ptr(
const void *model_map,
uint64_t offset,
uint64_t weight_bytes,
uint64_t in_dim,
uint64_t out_dim,
const char *label) {
auto exact = g_q8_f32_by_offset.find(offset);
if (exact != g_q8_f32_by_offset.end()) {
const cuda_q8_f32_range &r = g_q8_f32_ranges[exact->second];
if (r.host_base == model_map && r.weight_bytes == weight_bytes &&
r.in_dim == in_dim && r.out_dim == out_dim) {
return r.device_ptr;
}
}
if (!cuda_q8_f32_cache_allowed(label, in_dim, out_dim)) return NULL;
const char *q8 = cuda_model_range_ptr(model_map, offset, weight_bytes, label ? label : "q8_0");
if (!q8) return NULL;
const uint64_t out_bytes = in_dim * out_dim * sizeof(float);
float *dev = NULL;
cudaError_t err = cudaMalloc(&dev, (size_t)out_bytes);
if (err != cudaSuccess) {
fprintf(stderr, "ds4: CUDA q8 fp32 cache alloc failed (%.2f MiB): %s\n",
(double)out_bytes / 1048576.0, cudaGetErrorString(err));
(void)cudaGetLastError();
return NULL;
}
const uint64_t blocks = (in_dim + 31) / 32;
const uint64_t n = in_dim * out_dim;
dequant_q8_0_to_f32_kernel<<<(n + 255) / 256, 256>>>(dev,
(const unsigned char *)q8,
in_dim,
out_dim,
blocks);
if (!cuda_ok(cudaGetLastError(), "q8 fp32 dequant launch")) {
(void)cudaFree(dev);
return NULL;
}
g_q8_f32_ranges.push_back({model_map, offset, weight_bytes, in_dim, out_dim, dev});
g_q8_f32_by_offset[offset] = g_q8_f32_ranges.size() - 1u;
g_q8_f32_bytes += out_bytes;
if (getenv("DS4_CUDA_WEIGHT_CACHE_VERBOSE")) {
fprintf(stderr, "ds4: CUDA cached q8 fp32 %.2f MiB (total %.2f GiB)\n",
(double)out_bytes / 1048576.0,
(double)g_q8_f32_bytes / 1073741824.0);
}
return dev;
}
static int cuda_ok(cudaError_t err, const char *what) {
if (err == cudaSuccess) return 1;
fprintf(stderr, "ds4: CUDA %s failed: %s\n", what, cudaGetErrorString(err));
return 0;
}
static double cuda_wall_sec(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (double)ts.tv_sec + (double)ts.tv_nsec * 1.0e-9;
}
static int cuda_model_load_progress_enabled(void) {
if (getenv("DS4_CUDA_WEIGHT_CACHE_VERBOSE") != NULL) return 0;
return 1;
}
static void cuda_model_load_progress_reset(void) {
g_model_load_progress_next = 0;
g_model_load_progress_last = 0.0;
g_model_load_progress_started = 0;
g_model_load_progress_tty = 0;
}
static void cuda_model_load_progress_note(uint64_t cached_bytes) {
if (!cuda_model_load_progress_enabled()) return;
const double now = cuda_wall_sec();
if (!g_model_load_progress_started) {
g_model_load_progress_started = 1;
g_model_load_progress_tty = isatty(STDERR_FILENO) != 0;
g_model_load_progress_next = (g_model_load_progress_tty ? 2ull : 16ull) *
1024ull * 1024ull * 1024ull;
g_model_load_progress_last = now;
if (g_model_load_progress_tty) {
fprintf(stderr, "ds4: CUDA loading model tensors into device cache: 0.00 GiB");
} else {
fprintf(stderr, "ds4: CUDA loading model tensors into device cache\n");
}
}
if (cached_bytes < g_model_load_progress_next &&
now - g_model_load_progress_last < (g_model_load_progress_tty ? 2.0 : 10.0)) {
return;
}
if (g_model_load_progress_tty) {
fprintf(stderr, "\rds4: CUDA loading model tensors into device cache: %.2f GiB",
(double)cached_bytes / 1073741824.0);
} else {
fprintf(stderr, "ds4: CUDA loading model tensors %.2f GiB cached\n",
(double)cached_bytes / 1073741824.0);
}
fflush(stderr);
g_model_load_progress_last = now;
const uint64_t step = (g_model_load_progress_tty ? 2ull : 16ull) *
1024ull * 1024ull * 1024ull;
while (g_model_load_progress_next <= cached_bytes) {
g_model_load_progress_next += step;
}
}
static int cuda_model_prefetch_range(const void *model_map, uint64_t model_size, uint64_t map_offset, uint64_t map_size) {
if (!model_map || map_size == 0 || map_offset > model_size || map_size > model_size - map_offset) return 0;
if (getenv("DS4_CUDA_NO_MODEL_PREFETCH") != NULL ||
getenv("DS4_CUDA_COPY_MODEL") != NULL ||
getenv("DS4_CUDA_WEIGHT_CACHE") != NULL ||
getenv("DS4_CUDA_WEIGHT_PRELOAD") != NULL) {
return 0;
}
int device = 0;
if (cudaGetDevice(&device) != cudaSuccess) {
(void)cudaGetLastError();
return 0;
}
int pageable = 0;
cudaError_t err = cudaDeviceGetAttribute(&pageable, cudaDevAttrPageableMemoryAccess, device);
if (err != cudaSuccess || !pageable) {
(void)cudaGetLastError();
return 0;
}
cudaMemLocation loc;
memset(&loc, 0, sizeof(loc));
loc.type = cudaMemLocationTypeDevice;
loc.id = device;
const long page_sz_l = sysconf(_SC_PAGESIZE);
const uint64_t page_sz = page_sz_l > 0 ? (uint64_t)page_sz_l : 4096u;
const uintptr_t host_addr = (uintptr_t)((const char *)model_map + map_offset);
const uintptr_t pre_addr = host_addr & ~(uintptr_t)(page_sz - 1u);
const uint64_t pre_delta = (uint64_t)(host_addr - pre_addr);
const uint64_t pre_bytes = (pre_delta + map_size + page_sz - 1u) & ~(page_sz - 1u);
void *pre_ptr = (void *)pre_addr;
const double t0 = cuda_wall_sec();
err = cudaMemAdvise(pre_ptr, (size_t)pre_bytes, cudaMemAdviseSetReadMostly, loc);
if (err != cudaSuccess) {
fprintf(stderr, "ds4: CUDA model read-mostly advise skipped: %s\n", cudaGetErrorString(err));
(void)cudaGetLastError();
return 0;
}
err = cudaMemAdvise(pre_ptr, (size_t)pre_bytes, cudaMemAdviseSetPreferredLocation, loc);
if (err != cudaSuccess) {
fprintf(stderr, "ds4: CUDA model preferred-location advise skipped: %s\n", cudaGetErrorString(err));
(void)cudaGetLastError();
return 0;
}
if (!g_model_prefetch_stream) {
err = cudaStreamCreateWithFlags(&g_model_prefetch_stream, cudaStreamNonBlocking);
if (err != cudaSuccess) {
fprintf(stderr, "ds4: CUDA model prefetch stream creation skipped: %s\n", cudaGetErrorString(err));
(void)cudaGetLastError();
return 0;
}
}
err = cudaMemPrefetchAsync(pre_ptr, (size_t)pre_bytes, loc, 0, g_model_prefetch_stream);
if (err != cudaSuccess) {
fprintf(stderr, "ds4: CUDA model prefetch skipped: %s\n", cudaGetErrorString(err));
(void)cudaGetLastError();
return 0;
}
if (getenv("DS4_CUDA_MODEL_PREFETCH_SYNC") != NULL) {
err = cudaStreamSynchronize(g_model_prefetch_stream);
if (err != cudaSuccess) {
fprintf(stderr, "ds4: CUDA model prefetch sync failed: %s\n", cudaGetErrorString(err));
(void)cudaGetLastError();
return 0;
}
}
const double t1 = cuda_wall_sec();
fprintf(stderr,
"ds4: CUDA ATS/HMM prefetch queued %.2f GiB of model tensors in %.3fs\n",
(double)map_size / 1073741824.0,
t1 - t0);
g_model_hmm_direct = 1;
return 1;
}
static uint64_t cuda_model_copy_chunk_bytes(void) {
uint64_t mb = 64;
const char *env = getenv("DS4_CUDA_MODEL_COPY_CHUNK_MB");
if (env && env[0]) {
char *end = NULL;
unsigned long long v = strtoull(env, &end, 10);
if (end != env && v > 0) mb = (uint64_t)v;
}
if (mb < 16) mb = 16;
if (mb > 4096) mb = 4096;
return mb * 1048576ull;
}
static void cuda_model_discard_source_pages(const void *model_map, uint64_t model_size, uint64_t offset, uint64_t bytes) {
#if defined(POSIX_MADV_DONTNEED)
if (getenv("DS4_CUDA_KEEP_MODEL_PAGES") != NULL || !model_map || bytes == 0 || offset > model_size) return;
if (bytes > model_size - offset) bytes = model_size - offset;
const long page_sz_l = sysconf(_SC_PAGESIZE);
const uint64_t page_sz = page_sz_l > 0 ? (uint64_t)page_sz_l : 4096u;
const uintptr_t h0 = (uintptr_t)((const char *)model_map + offset);
const uintptr_t h1 = h0 + bytes;
const uintptr_t p0 = h0 & ~(uintptr_t)(page_sz - 1u);
const uintptr_t p1 = (h1 + page_sz - 1u) & ~(uintptr_t)(page_sz - 1u);
if (p1 > p0) (void)posix_madvise((void *)p0, (size_t)(p1 - p0), POSIX_MADV_DONTNEED);
#else
(void)model_map;
(void)model_size;
(void)offset;
(void)bytes;
#endif
}
static void cuda_model_drop_file_pages(uint64_t offset, uint64_t bytes) {
#if defined(POSIX_FADV_DONTNEED)
if (g_model_fd < 0 || getenv("DS4_CUDA_KEEP_MODEL_PAGES") != NULL || bytes == 0) return;
(void)posix_fadvise(g_model_fd, (off_t)offset, (off_t)bytes, POSIX_FADV_DONTNEED);
#else
(void)offset;
(void)bytes;
#endif
}
static uint64_t cuda_round_down(uint64_t v, uint64_t align) {
if (align <= 1) return v;
return (v / align) * align;
}
static uint64_t cuda_round_up(uint64_t v, uint64_t align) {
if (align <= 1) return v;
const uint64_t rem = v % align;
return rem == 0 ? v : v + (align - rem);
}
static void *cuda_align_ptr(void *ptr, uint64_t align) {
if (align <= 1) return ptr;
uintptr_t p = (uintptr_t)ptr;
uintptr_t a = (uintptr_t)align;
return (void *)(((p + a - 1u) / a) * a);
}
static int cuda_model_stage_pool_alloc(uint64_t bytes) {
if (g_model_stage_bytes >= bytes) return 1;
for (size_t i = 0; i < 4; i++) {
if (g_model_stage_event[i]) {
(void)cudaEventDestroy(g_model_stage_event[i]);
g_model_stage_event[i] = NULL;
}
if (g_model_stage_raw[i]) {
(void)cudaFreeHost(g_model_stage_raw[i]);
g_model_stage_raw[i] = NULL;
g_model_stage[i] = NULL;
}
}
g_model_stage_bytes = 0;
if (!g_model_upload_stream) {
cudaError_t err = cudaStreamCreateWithFlags(&g_model_upload_stream, cudaStreamNonBlocking);
if (err != cudaSuccess) {
fprintf(stderr, "ds4: CUDA model upload stream creation failed: %s\n", cudaGetErrorString(err));
(void)cudaGetLastError();
return 0;
}
}
for (size_t i = 0; i < 4; i++) {
cudaError_t err = cudaMallocHost(&g_model_stage_raw[i], (size_t)bytes);
if (err != cudaSuccess) {
fprintf(stderr, "ds4: CUDA pinned model staging allocation failed: %s\n", cudaGetErrorString(err));
(void)cudaGetLastError();
return 0;
}
g_model_stage[i] = cuda_align_ptr(g_model_stage_raw[i], g_model_direct_align);
err = cudaEventCreateWithFlags(&g_model_stage_event[i], cudaEventDisableTiming);
if (err != cudaSuccess) {
fprintf(stderr, "ds4: CUDA model staging event creation failed: %s\n", cudaGetErrorString(err));
(void)cudaGetLastError();
return 0;
}
}
g_model_stage_bytes = bytes;
return 1;
}
static int cuda_pread_full(int fd, void *buf, uint64_t bytes, uint64_t offset) {
uint64_t done = 0;
while (done < bytes) {
const size_t n_req = (bytes - done > (uint64_t)SSIZE_MAX) ? (size_t)SSIZE_MAX : (size_t)(bytes - done);
ssize_t n = pread(fd, (char *)buf + done, n_req, (off_t)(offset + done));
if (n < 0) {
if (errno == EINTR) continue;
return 0;
}
if (n == 0) return 0;
done += (uint64_t)n;
}
return 1;
}
static int cuda_model_stage_read(void *stage, uint64_t stage_bytes,
uint64_t offset, uint64_t bytes,
const char **payload) {
*payload = (const char *)stage;
#if defined(__linux__) && defined(O_DIRECT)
if (g_model_direct_fd >= 0 && g_model_direct_align > 1 && g_model_file_size != 0) {
const uint64_t aligned_off = cuda_round_down(offset, g_model_direct_align);
const uint64_t delta = offset - aligned_off;
uint64_t read_size = cuda_round_up(delta + bytes, g_model_direct_align);
if (aligned_off <= g_model_file_size &&
read_size <= stage_bytes &&
read_size <= g_model_file_size - aligned_off) {
const int saved_errno = errno;
errno = 0;
if (cuda_pread_full(g_model_direct_fd, stage, read_size, aligned_off)) {
*payload = (const char *)stage + delta;
errno = saved_errno;
return 1;
}
const int direct_errno = errno;
if (direct_errno == EINVAL || direct_errno == EFAULT || direct_errno == ENOTSUP || direct_errno == EOPNOTSUPP) {
if (getenv("DS4_CUDA_WEIGHT_CACHE_VERBOSE")) {
fprintf(stderr, "ds4: CUDA direct model read disabled: %s\n", strerror(direct_errno));
}
(void)close(g_model_direct_fd);
g_model_direct_fd = -1;
g_model_direct_align = 1;
}
errno = direct_errno;
}
}
#else
(void)stage_bytes;
#endif
return cuda_pread_full(g_model_fd, stage, bytes, offset);
}
static uint64_t cuda_model_cache_limit_bytes(void) {
uint64_t gb = 0;
const char *env = getenv("DS4_CUDA_WEIGHT_CACHE_LIMIT_GB");
if (env && env[0]) {
char *end = NULL;
unsigned long long v = strtoull(env, &end, 10);
if (end != env) gb = (uint64_t)v;
}
if (gb == 0) return UINT64_MAX;
return gb * 1073741824ull;
}
static uint64_t cuda_model_arena_chunk_bytes(uint64_t need) {
uint64_t mb = 1792;
const char *env = getenv("DS4_CUDA_WEIGHT_ARENA_CHUNK_MB");
if (env && env[0]) {
char *end = NULL;
unsigned long long v = strtoull(env, &end, 10);
if (end != env && v > 0) mb = (uint64_t)v;
}
if (mb < 256) mb = 256;
if (mb > 8192) mb = 8192;
uint64_t bytes = mb * 1048576ull;
if (bytes < need) {
const uint64_t align = 256ull * 1048576ull;
bytes = (need + align - 1u) & ~(align - 1u);
}
return bytes;
}
static char *cuda_model_arena_alloc(uint64_t bytes, const char *what) {
if (bytes == 0) return NULL;
if (g_model_cache_full) return NULL;
const uint64_t align = 256u;
const uint64_t aligned = (bytes + align - 1u) & ~(align - 1u);
for (cuda_model_arena &a : g_model_arenas) {
const uint64_t used = (a.used + align - 1u) & ~(align - 1u);
if (used <= a.bytes && aligned <= a.bytes - used) {
char *ptr = a.device_ptr + used;
a.used = used + aligned;
return ptr;
}
}
const uint64_t limit = cuda_model_cache_limit_bytes();
if (g_model_range_bytes > limit || aligned > limit - g_model_range_bytes) return NULL;
const uint64_t chunk = cuda_model_arena_chunk_bytes(aligned);
void *dev = NULL;
cudaError_t err = cudaMalloc(&dev, (size_t)chunk);
if (err != cudaSuccess) {
fprintf(stderr, "ds4: CUDA model arena alloc failed for %s (%.2f MiB chunk): %s\n",
what ? what : "weights",
(double)chunk / 1048576.0,
cudaGetErrorString(err));
(void)cudaGetLastError();
g_model_cache_full = 1;
return NULL;
}
g_model_arenas.push_back({(char *)dev, chunk, aligned});
if (getenv("DS4_CUDA_WEIGHT_CACHE_VERBOSE")) {
uint64_t arena_bytes = 0;
for (const cuda_model_arena &a : g_model_arenas) arena_bytes += a.bytes;
fprintf(stderr, "ds4: CUDA model arena allocated %.2f MiB (arenas %.2f GiB)\n",
(double)chunk / 1048576.0,
(double)arena_bytes / 1073741824.0);
}
return (char *)dev;
}
static const char *cuda_model_range_ptr_from_fd(
const void *model_map,
uint64_t offset,