Repository navigation
Expand file tree
/
Copy pathengine.cpp
More file actions
8192 lines (7919 loc) · 409 KB
/
Copy pathengine.cpp
File metadata and controls
8192 lines (7919 loc) · 409 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
// src/poly/engine.cpp - see the header. What every architecture shares: the files, the weights' way to VRAM, the
// routed experts (the cache, the CPU, a prompt batch), the sequence's state, and the calls that feed tokens.
#include "engine.hpp"
#include "stage_copy.hpp"
#include "deepseek4.hpp"
#include "gemma4.hpp"
#include "glm5next.hpp"
#include "kolibri1.hpp"
#include "lfm2moe.hpp"
#include "flint.hpp"
#include "inkling2.hpp" // its kernels: inkling2.cu, and metal/src/poly/inkling.cpp on Metal
#if !defined(STRATA_GPU_METAL)
#include "laguna.hpp" // CUDA and HIP: its YaRN turn and softplus gate have no Metal kernels yet
#include "expert_card.hpp"
#endif
#include "mmq.hpp"
#include "qwen35.hpp"
#include "runtime.hpp"
#include "strata/poly/kernels.hpp"
#if defined(STRATA_GPU_METAL)
#include "strata/core/conversation_memory.hpp"
#include "strata/gpu/metal.hpp"
#endif
#include "strata/kernels/native_mmvq.hpp"
#include "strata/kernels/pdl.hpp"
#include "strata/platform/memory.hpp"
#include "gguf_types.hpp"
#include <cuda.h>
#include <cuda_runtime.h>
#include <algorithm>
#include <atomic>
#include <bit>
#include <chrono>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <filesystem>
#include <immintrin.h>
#include <new>
#include <numeric>
#include <stdexcept>
#include <thread>
#include <unordered_map>
#ifdef __linux__
#include <sched.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <unistd.h>
#endif
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <malloc.h>
#include <psapi.h>
#endif
#if defined(__APPLE__)
#include <sys/mman.h>
#endif
namespace strata::poly {
namespace {
// pdl_scope() for a whole pass's recording: CUDA's and HIP's (verify_kernels.cu); the Metal build has no PDL launches
// and does not build that file, so there it is a flag nothing reads
bool& whole_pdl_scope() {
#if defined(STRATA_GPU_METAL)
static thread_local bool off = false;
return off;
#else
return kernels::pdl_scope();
#endif
}
void drop_file_pages(const void* p, size_t n) {
#if defined(__APPLE__)
constexpr uintptr_t kPage = 16384;
const uintptr_t a = ((uintptr_t) p + kPage - 1) & ~(kPage - 1);
const uintptr_t b = ((uintptr_t) p + n) & ~(kPage - 1);
if (b > a) (void) msync((void*) a, b - a, MS_INVALIDATE);
#else
(void) p;
(void) n;
#endif
}
// A launch's tiles are as wide as the most rows one of its matrices has, up to 128, and every matrix in it
// computes whole tiles. So a prompt batch's cached experts go by how many rows they have (moe_rows()): a launch
// for the experts of up to 32 rows, one for those of up to 128, and one for the experts with more. Narrower
// widths saved less work than their launches cost.
constexpr int kTile[] = {32, 128};
constexpr int kClasses = (int) (sizeof(kTile) / sizeof(kTile[0])) + 1;
constexpr int kMaxStagedTiles = 8; // the most size classes STRATA_POLY_STAGED_TILES makes of the staged experts
int tile_class(int rows) {
int c = 0;
while (c < kClasses - 1 && rows > kTile[c]) ++c;
return c;
}
// A container's CPU quota is not in the affinity mask: a 25-CPU pod on a 208-thread host shows 208.
// `quota` is set when there is one.
int usable_cpus(bool* quota_set = nullptr) {
long long n = (long long) std::thread::hardware_concurrency();
#ifdef __linux__
cpu_set_t set;
if (sched_getaffinity(0, sizeof(set), &set) == 0) n = CPU_COUNT(&set);
long long quota = -1, period = 0;
if (FILE* f = std::fopen("/sys/fs/cgroup/cpu.max", "r")) { // "max 100000" when there is no quota
if (std::fscanf(f, "%lld %lld", "a, &period) != 2) quota = -1;
std::fclose(f);
} else if (FILE* q = std::fopen("/sys/fs/cgroup/cpu/cpu.cfs_quota_us", "r")) {
if (std::fscanf(q, "%lld", "a) != 1) quota = -1;
std::fclose(q);
if (FILE* p = std::fopen("/sys/fs/cgroup/cpu/cpu.cfs_period_us", "r")) {
if (std::fscanf(p, "%lld", &period) != 1) period = 0;
std::fclose(p);
}
}
if (quota > 0 && period > 0) {
n = std::min(n, std::max(1LL, quota / period));
if (quota_set) *quota_set = true;
}
#else
(void) quota_set;
#endif
return (int) std::max(n, 1LL);
}
// The CPU threads when --threads names none: 70% of the usable CPUs, so that the PC's other programs keep the
// rest. With a thread for every CPU the CPU was 90 to 94% busy while an answer was written, on 16 cores of a
// Xeon beside a card held to 8 GB; 22 threads of 32 left it 66% busy, wrote as fast, and 19 to 23% faster
// beside another program's load on 8 CPUs, since a layer waits for its slowest thread and a thread that has to
// share its CPU is the slowest. A container with a CPU quota keeps them all: that is a server with no desktop
// to leave CPU to, and GLM 5.3 Flash's CPU experts there take 15 ms a token with 18 threads where 12.8 with 24.
int default_threads() {
bool quota = false;
const int n = usable_cpus("a);
return quota ? n : std::max(1, (n * 7 + 5) / 10);
}
// On a machine with several NUMA nodes the file cache's pages are on the node whose CPU read them first, and the
// CPU reads the experts at the speed of memory: from the other node that is slower (29.4 against 22.5 ms of CPU
// experts a token on a two-socket Xeon). `spans` are the experts in the mapped files. When most of their pages
// are on one node, and the process may use `threads` CPUs of it, this thread is kept on that node's CPUs, and so
// are the threads it starts from then on. Returns the node, or -1 when nothing was changed.
void drop_pages(const uint8_t* p, size_t n);
int stay_near(const std::vector<std::pair<const uint8_t*, size_t>>& spans, const std::vector<std::string>& files,
int threads, double& share) {
#ifdef __linux__
if (access("/sys/devices/system/node/node1", F_OK) != 0) return -1; // one node
// A page shows in numa_maps once it is mapped: touch a few thousand, spread over the experts.
size_t total = 0;
for (const auto& s : spans) total += s.second;
const size_t step = std::max<size_t>(total / 4096, 4096);
volatile uint8_t seen = 0;
for (const auto& s : spans)
for (size_t at = 0; at < s.second; at += step) seen = (uint8_t) (seen + s.first[at]);
std::vector<std::string> real;
for (const std::string& f : files)
if (char* r = realpath(f.c_str(), nullptr)) {
real.emplace_back(r);
std::free(r);
}
std::vector<long long> pages; // per node, of the model's files
if (FILE* f = std::fopen("/proc/self/numa_maps", "r")) {
char* line = nullptr;
size_t cap = 0;
while (getline(&line, &cap, f) > 0) {
const char* file = std::strstr(line, " file=");
if (!file) continue;
file += 6;
const size_t len = std::strcspn(file, " \n");
bool ours = false;
for (const std::string& r : real) ours = ours || (r.size() == len && r.compare(0, len, file, len) == 0);
for (const char* p = file + len; ours && (p = std::strstr(p, " N")) != nullptr; ++p) {
int node = 0;
long long n = 0;
if (std::sscanf(p, " N%d=%lld", &node, &n) != 2 || node < 0 || node > 1023) continue;
if ((size_t) node >= pages.size()) pages.resize((size_t) node + 1, 0);
pages[(size_t) node] += n;
}
}
std::free(line);
std::fclose(f);
}
// The touches mapped 64 KiB around each (the fault-around), 256 MiB of LFM2.5's experts on the RTX 5090 pod,
// which stayed with every expert in VRAM. They go again; the CPU's experts come back by map_pages().
for (const auto& s : spans)
for (size_t at = 0; at < s.second; at += step) {
const uintptr_t b = (uintptr_t) s.first, e = b + s.second;
const uintptr_t lo = std::max(b, (b + at) & ~(uintptr_t) 0xFFFF), hi = std::min(e, lo + 0x10000);
drop_pages((const uint8_t*) lo, (size_t) (hi - lo));
}
long long all = 0;
for (long long n : pages) all += n;
if (all == 0) return -1;
const int best = (int) (std::max_element(pages.begin(), pages.end()) - pages.begin());
share = (double) pages[(size_t) best] / (double) all;
if (share < 0.6) return -1; // split between the nodes: one is as good as another
cpu_set_t may, node;
CPU_ZERO(&node);
const std::string list = "/sys/devices/system/node/node" + std::to_string(best) + "/cpulist";
if (FILE* f = std::fopen(list.c_str(), "r")) { // "52-103,156-207"
int a = 0, b = 0;
while (std::fscanf(f, "%d", &a) == 1) {
b = a;
int c = std::fgetc(f);
if (c == '-' && std::fscanf(f, "%d", &b) == 1) c = std::fgetc(f);
for (int i = a; i <= b && i < CPU_SETSIZE; ++i) CPU_SET(i, &node);
if (c != ',') break;
}
std::fclose(f);
}
if (sched_getaffinity(0, sizeof(may), &may) != 0) return -1;
CPU_AND(&node, &node, &may);
if (CPU_COUNT(&node) < threads || sched_setaffinity(0, sizeof(node), &node) != 0) return -1;
return best;
#else
(void) spans, (void) files, (void) threads, (void) share;
return -1;
#endif
}
#ifdef _WIN32
// The spans' bytes read through the file cache, 16 MiB a request, into a buffer that is thrown away. A span that
// is not in the model's files (a draft's own file) or a read that fails is left to map_pages()'s faults.
void read_cached(const std::vector<std::pair<const uint8_t*, size_t>>& spans, const Shards& model,
const std::atomic<bool>& quit) {
constexpr size_t kPiece = size_t(1) << 24;
std::vector<HANDLE> files(model.paths().size(), INVALID_HANDLE_VALUE);
std::vector<uint8_t> buf(kPiece);
for (const auto& s : spans) {
const auto [file, off] = model.place(s.first);
if (file < 0) continue;
HANDLE& h = files[(size_t) file];
if (h == INVALID_HANDLE_VALUE)
h = CreateFileA(model.paths()[(size_t) file].c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
if (h == INVALID_HANDLE_VALUE) continue;
for (size_t at = 0; at < s.second && !quit.load(std::memory_order_relaxed); at += kPiece) {
OVERLAPPED o{};
o.Offset = (DWORD) (off + at);
o.OffsetHigh = (DWORD) ((off + at) >> 32);
DWORD got = 0;
if (!ReadFile(h, buf.data(), (DWORD) std::min(kPiece, s.second - at), &got, &o)) break;
}
}
for (HANDLE h : files)
if (h != INVALID_HANDLE_VALUE) CloseHandle(h);
}
#endif
// A byte of every page of a span of the mapped files, read: its pages come into this process.
void touch_pages(const uint8_t* p, size_t n) {
volatile uint8_t seen = 0;
for (size_t at = 0; at < n; at += 4096) seen = (uint8_t) (seen + p[at]);
if (n > 0) seen = (uint8_t) (seen + p[n - 1]); // its last page, when it starts in one
}
// The mapped file's pages come into this process's page table as they are first read, a fault every few pages,
// and an expert read through those faults arrives at half the speed: 21.0 against 11.0 ms a token for GLM 5.3
// Flash's CPU experts on the two-socket Xeon, while every expert a token meets is new to the process. So one
// thread reads a byte of every page of the CPU's experts, once, beside whatever the engine is doing: the 100 GiB of a
// model that the file cache holds take it 4 s. What the cache does not hold is read from the disk here, not
// while a token waits.
//
// On Windows a fault reads only a few pages from the disk: 1.3 GB/s from a laptop's SSD, so the 10 GiB of experts
// the file cache did not hold took 10 s, and an answer asked meanwhile came at half speed. The same bytes read
// through the file cache come at 3.2 GB/s (it reads ahead in large requests), and the mapping shares the cache's
// pages, so a second thread reads the spans from the file (read_cached()) while this one touches them: from an
// empty cache it runs ahead and the touches find the pages in memory. When the cache holds them it only copies
// what it reads, beside the touches. PrefetchVirtualMemory() returns at once and brings nothing in.
void map_pages(const std::vector<std::pair<const uint8_t*, size_t>>& spans, const Shards& model,
const std::atomic<bool>& quit) {
#ifdef _WIN32
std::jthread reader(read_cached, std::cref(spans), std::cref(model), std::cref(quit));
#else
(void) model;
#endif
constexpr size_t kLook = size_t(1) << 24; // `quit` is looked at every 16 MiB
for (const auto& s : spans)
for (size_t at = 0; at < s.second; at += kLook) {
if (quit.load(std::memory_order_relaxed)) return;
touch_pages(s.first + at, std::min(kLook, s.second - at));
}
}
// The whole pages of a span of the mapped files leave this process's memory, for what the card has a copy of and
// the CPU does not read. The file cache keeps them (the standby list on Windows, the page cache on Linux): the
// machine counts them as available and takes them for whatever needs memory, and a read that comes after finds
// them there without the disk. After a 32K prompt on the laptop the engine held all 15.9 GiB of Qwen3.6's file,
// 4.2 GiB of it dense weights and experts the card had; with those dropped, the 11.7 GiB of experts the CPU reads.
size_t page_bytes() {
static const size_t page = [] {
#ifdef _WIN32
SYSTEM_INFO si;
GetSystemInfo(&si);
return (size_t) si.dwPageSize;
#else
return (size_t) sysconf(_SC_PAGESIZE);
#endif
}();
return page;
}
void drop_pages(const uint8_t* p, size_t n) {
const size_t page = page_bytes();
const uintptr_t a = ((uintptr_t) p + page - 1) / page * page, b = ((uintptr_t) p + n) / page * page;
if (!p || b <= a) return;
#ifdef _WIN32
VirtualUnlock((void*) a, b - a); // pages that are not locked leave the working set (and it returns FALSE)
#else
madvise((void*) a, b - a, MADV_DONTNEED); // a private mapping that is never written reads the file again
#endif
}
#ifndef _WIN32
// A file's handle whose reads skip the file cache: O_DIRECT (whole 4 KiB blocks into aligned memory), F_NOCACHE on
// macOS; -1 where neither is there.
int open_uncached(const char* path) {
#if defined(O_DIRECT)
return ::open(path, O_RDONLY | O_CLOEXEC | O_DIRECT);
#elif defined(F_NOCACHE)
const int fd = ::open(path, O_RDONLY | O_CLOEXEC);
if (fd >= 0 && fcntl(fd, F_NOCACHE, 1) != 0) {
::close(fd);
return -1;
}
return fd;
#else
(void) path;
return -1;
#endif
}
// n bytes at off of open_uncached()'s fd into dst: the blocks around them into a buffer of the thread's, then dst.
// macOS serves an F_NOCACHE read from the file cache all the same unless it is in whole 16 KiB pages.
bool read_uncached(int fd, uint8_t* dst, uint64_t off, size_t n) {
#if defined(__APPLE__)
constexpr size_t kBlock = 16384;
#else
constexpr size_t kBlock = 4096;
#endif
struct Buf {
uint8_t* p = nullptr;
size_t n = 0;
~Buf() { std::free(p); }
};
thread_local Buf b;
const uint64_t lo = off / kBlock * kBlock, hi = (off + n + kBlock - 1) / kBlock * kBlock;
const size_t span = (size_t) (hi - lo), need = (size_t) (off + n - lo);
if (b.n < span) {
std::free(b.p);
b.p = (uint8_t*) std::aligned_alloc(kBlock, span);
b.n = b.p ? span : 0;
if (!b.p) return false;
}
size_t done = 0;
while (done < need) { // the file's last block may end short of hi
const ssize_t got = ::pread(fd, b.p + done, span - done, (off_t) (lo + done));
if (got <= 0) return false;
done += (size_t) got;
}
std::memcpy(dst, b.p + (off - lo), n);
return true;
}
#endif
// Options::lock_experts: a span's pages locked into RAM, where the file cache cannot hand them to another program,
// reading in the ones it had already dropped; false when the system refuses (Linux past `ulimit -l`, Windows past
// the working-set minimum lock_outside() raised). Unlocking takes the span's whole pages only: one it shares with
// a neighbour stays as the neighbour has it.
bool lock_pages(const uint8_t* p, size_t n, bool lock) {
if (lock) {
#ifdef _WIN32
return VirtualLock((void*) p, n) != 0;
#else
return mlock(p, n) == 0;
#endif
}
const size_t page = page_bytes();
const uintptr_t a = ((uintptr_t) p + page - 1) / page * page, b = ((uintptr_t) p + n) / page * page;
if (b <= a) return true;
#ifdef _WIN32
return VirtualUnlock((void*) a, b - a) != 0;
#else
return munlock((void*) a, b - a) == 0;
#endif
}
// `ulimit -l` as the shell prints it (KiB) for the --lock-experts lines: "" where there is none, or no limit.
std::string memlock_kib() {
#ifdef _WIN32
return {};
#else
rlimit r{};
if (getrlimit(RLIMIT_MEMLOCK, &r) != 0 || r.rlim_cur == RLIM_INFINITY) return {};
return std::to_string((unsigned long long) (r.rlim_cur >> 10));
#endif
}
#if !defined(STRATA_GPU_METAL) && !defined(STRATA_USE_HIP)
// The mirror's lock line: the NVIDIA driver pins past RLIMIT_MEMLOCK (under `ulimit -l 8192` it pinned 3.3 GiB of
// Qwen3.6's experts, driver 580 on Linux).
std::string memlock_note() {
const std::string kib = memlock_kib();
return kib.empty() ? std::string() : "; `ulimit -l` (" + kib + " here) does not limit it";
}
// Host memory for the pinned mirror, aligned to 2 MiB. Not asked for in huge pages (MADV_HUGEPAGE): on
// lab-pro6000, whose memory others had fragmented, the kernel compacted memory for each fault, the mirror took
// minutes and an answer meanwhile came at 4 tokens/s.
uint8_t* host_alloc(size_t bytes) {
constexpr size_t kAlign = size_t(2) << 20;
const size_t n = (bytes + kAlign - 1) / kAlign * kAlign;
#ifdef _WIN32
return (uint8_t*) _aligned_malloc(n, kAlign);
#else
return (uint8_t*) std::aligned_alloc(kAlign, n);
#endif
}
void host_free(void* p) {
#ifdef _WIN32
_aligned_free(p);
#else
std::free(p);
#endif
}
#endif
void free_pieces(std::vector<MirrorPiece>& pieces) {
#if !defined(STRATA_GPU_METAL) && !defined(STRATA_USE_HIP)
for (const MirrorPiece& p : pieces) {
if (!p.base) continue;
if (p.registered) {
cudaHostUnregister(p.base);
host_free(p.base);
} else {
cudaFreeHost(p.base);
}
}
#endif
pieces.clear();
}
// cuBLAS's libraries: loaded at start, they stayed in the working set after that (135 MiB on the laptop, 68 MiB
// under Linux), though a request runs little of them. Their pages leave it as drop_pages()'s do, and what a
// request runs comes back from the file cache. Not the engine's own image: under Linux its code went to the disk
// with MADV_PAGEOUT and came back from it on the next request, 4 ms of a short prompt's 85.
void drop_images() {
#ifdef _WIN32
const HANDLE self = GetCurrentProcess();
HMODULE mods[1024];
DWORD got = 0;
if (!EnumProcessModules(self, mods, sizeof mods, &got)) return;
for (DWORD i = 0; i < std::min<DWORD>(got / sizeof(HMODULE), 1024); ++i) {
char name[MAX_PATH];
if (!GetModuleBaseNameA(self, mods[i], name, sizeof name) || _strnicmp(name, "cublas", 6) != 0) continue;
MODULEINFO mi{};
if (!GetModuleInformation(self, mods[i], &mi, sizeof mi)) continue;
const uint8_t* p = (const uint8_t*) mi.lpBaseOfDll;
const uint8_t* end = p + mi.SizeOfImage;
MEMORY_BASIC_INFORMATION r;
while (p < end && VirtualQuery(p, &r, sizeof r) == sizeof r) { // one call a region: they differ in rights
if (r.State == MEM_COMMIT) VirtualUnlock(r.BaseAddress, r.RegionSize);
p = (const uint8_t*) r.BaseAddress + r.RegionSize;
}
}
#else
// Their code only: it is never written, so MADV_DONTNEED leaves it in the file cache. Their other read-only
// pages may be relocated private copies, which MADV_DONTNEED would throw away.
FILE* f = std::fopen("/proc/self/maps", "r");
if (!f) return;
char line[4352];
while (std::fgets(line, sizeof line, f)) {
unsigned long a = 0, b = 0;
char rights[8] = {};
if (std::sscanf(line, "%lx-%lx %7s", &a, &b, rights) == 3 && std::strcmp(rights, "r-xp") == 0 &&
std::strstr(line, "/libcublas"))
madvise((void*) a, b - a, MADV_DONTNEED);
}
std::fclose(f);
#endif
}
// Experts [e0, e1) of L in the mapped file, to f(start, bytes): their gates and ups (one span where the file keeps
// an expert's two in one tensor), and their downs.
template <class F> void expert_bytes(const Layer& L, int e0, int e1, F&& f) {
const size_t n = (size_t) (e1 - e0);
f(L.exp_gate + (size_t) e0 * L.gu_stride, n * L.gu_stride);
if (L.gu_stride == L.gu_bytes) f(L.exp_up + (size_t) e0 * L.u_stride, n * L.u_stride);
f(L.exp_down + (size_t) e0 * L.d_bytes, n * L.d_bytes);
}
// expert_bytes() of each run of L's experts that take() takes, a run of neighbours in one call
template <class P, class F> void expert_runs(const Layer& L, int n_expert, P&& take, F&& f) {
for (int e = 0; e < n_expert;) {
if (!take(e)) {
++e;
continue;
}
int g = e + 1;
while (g < n_expert && take(g)) ++g;
expert_bytes(L, e, g, f);
e = g;
}
}
// Lines of "layer expert count". A missing file is not an error: the first run writes it.
void read_profile(const std::string& path, int n_layer, int n_expert, std::vector<int64_t>& out) {
FILE* f = std::fopen(path.c_str(), "r");
if (!f) return;
out.assign((size_t) n_layer * n_expert, 0);
int il = 0, e = 0;
long long n = 0;
while (std::fscanf(f, "%d %d %lld", &il, &e, &n) == 3)
if (il >= 0 && il < n_layer && e >= 0 && e < n_expert && n > 0) out[(size_t) il * n_expert + e] = n;
std::fclose(f);
}
void cu_ck(CUresult r, const char* what) {
if (r == CUDA_SUCCESS) return;
const char* s = nullptr;
cuGetErrorString(r, &s);
throw std::runtime_error(std::string(what) + ": " + (s ? s : "a CUDA driver error"));
}
size_t up_to(size_t n, size_t grain) { return (n + grain - 1) / grain * grain; }
// The largest of n values, as eight maxima side by side: one best-so-far is a chain every compare waits on, and
// a vocabulary is 150,000 values.
constexpr int kLanes = 8;
float largest(const float* x, int n) {
float mx[kLanes];
std::fill(mx, mx + kLanes, -INFINITY);
int i = 0;
for (; i + kLanes <= n; i += kLanes)
for (int j = 0; j < kLanes; ++j) mx[j] = std::max(mx[j], x[i + j]);
float best = -INFINITY;
for (int j = 0; j < kLanes; ++j) best = std::max(best, mx[j]);
for (; i < n; ++i) best = std::max(best, x[i]);
return best;
}
// The CUDA calls of a card's engine go to its card: a split's engines share the caller's thread (but in read()),
// and the card is the thread's. Back to the caller's card at the end. One engine alone changes nothing.
class OnCard {
public:
OnCard(int device, bool split) : split_(split) {
if (!split_) return;
cudaGetDevice(&was_);
cudaSetDevice(device); // a failure shows in the calls that follow
}
~OnCard() {
if (split_) cudaSetDevice(was_);
}
OnCard(const OnCard&) = delete;
OnCard& operator=(const OnCard&) = delete;
private:
bool split_;
int was_ = 0;
};
// Work on a thread of its own, whose exception wait() throws. Going out of scope it waits and drops the exception.
class Behind {
public:
Behind() = default;
Behind(const Behind&) = delete;
Behind& operator=(const Behind&) = delete;
~Behind() {
if (th_.joinable()) th_.join();
}
void go(std::function<void()> work) {
th_ = std::thread([this, work = std::move(work)] {
try {
work();
} catch (...) {
err_ = std::current_exception();
}
});
}
void wait() {
if (th_.joinable()) th_.join();
if (err_) std::rethrow_exception(std::exchange(err_, nullptr));
}
private:
std::thread th_;
std::exception_ptr err_;
};
// The first layer of each card's share of n_layer layers, for Options::layer_split on `cards` cards; empty: no
// split. "auto" shares the layers' bytes out by each card's free VRAM, less what every card's engine takes beside
// its layers and, on the last card, the output and the draft block. Then every card caches about the same share
// of its layers' experts, which is where a byte of VRAM on one is worth as much as on another.
std::vector<int> layer_starts(const std::string& split, const Shards& file, int n_layer, int cards) {
if (split.empty() || cards < 2) return {};
std::vector<int> starts{0};
if (split != "auto") {
for (size_t at = 0; at < split.size();) {
const size_t comma = std::min(split.find(',', at), split.size());
const std::string s = split.substr(at, comma - at);
char* end = nullptr;
const long v = std::strtol(s.c_str(), &end, 10);
// the last card keeps two layers at least: Gemma 4's draft model reads the last two layers' caches
if (s.empty() || *end || v <= starts.back() || v > n_layer - 2)
throw std::runtime_error("--layer-split " + split + ": the first layer of each later card, rising, "
"between 1 and " + std::to_string(n_layer - 2) + " (\"auto\" shares them "
"out by each card's free VRAM)");
starts.push_back((int) v);
at = comma + 1;
}
if ((int) starts.size() > cards)
throw std::runtime_error("--layer-split " + split + " is for " + std::to_string(starts.size()) +
" cards; this process sees " + std::to_string(cards));
return starts;
}
if (n_layer < 2 * cards) throw std::runtime_error("the model has too few layers to split them on " + std::to_string(cards) + " cards");
std::vector<double> before((size_t) n_layer + 1, 0.0); // the bytes of the layers before each one
double head = 0;
file.each([&](const TensorInfo& t) {
int il = -1;
if (std::sscanf(t.name.c_str(), "blk.%d.", &il) == 1 && il >= 0 && il < n_layer)
before[(size_t) il + 1] += (double) file.payload(t);
else if (il >= n_layer || t.name == "output.weight") // the draft block, the output
head += (double) file.payload(t);
});
if (!file.find("output.weight") && file.find("token_embd.weight")) // the output is the token table
head += (double) file.payload(*file.find("token_embd.weight"));
for (int il = 0; il < n_layer; ++il) before[(size_t) il + 1] += before[(size_t) il];
constexpr double kBeside = 1.5 * double(1ull << 30); // scratch, the staging buffer and the reserve, about
std::vector<double> room((size_t) cards);
double all_room = 0;
for (int d = 0; d < cards; ++d) {
size_t free_b = 0, total_b = 0;
ck(cudaSetDevice(d), "cudaSetDevice");
ck(cudaMemGetInfo(&free_b, &total_b), "cudaMemGetInfo");
room[(size_t) d] = std::max((double) free_b - kBeside - (d == cards - 1 ? head : 0.0), double(1ull << 28));
all_room += room[(size_t) d];
}
double share = 0;
for (int d = 1; d < cards; ++d) {
share += room[(size_t) d - 1] / all_room;
int il = starts.back() + 1; // card d starts where the layers before it pass the cards before it's share
while (il < n_layer - 2 * (cards - d) && before[(size_t) il] < share * before[(size_t) n_layer]) ++il;
starts.push_back(il);
}
return starts;
}
// The reserve when none is asked for: a thirty-second of the card, 256 to 768 MiB. When the machine's RAM is
// tight for the model, a sixteenth, 512 to 1,024: on an 8 GB laptop with 32 GB, Ornith's APEX-I-Quality (23 GB)
// read a 24,000-token prompt at 1,392 and 1,138 tokens/s with 256 MiB kept free and at 1,532 and 1,451 with 512,
// in turns with the build that kept 512 (1,496 and 1,311); the smaller files read as fast either way. Under
// Windows what the card is short of moves to the system's RAM, which the file then has less of.
int default_reserve_mib(size_t total_b, bool ram_tight) {
if (ram_tight) return (int) std::clamp<size_t>(total_b >> 24, 512, 1024);
return (int) std::clamp<size_t>(total_b >> 25, 256, 768);
}
#ifdef __linux__
// A cgroup's memory limit is not in /proc/meminfo: a container, or a systemd scope, with one shows the host's RAM.
// The room under the tightest limit on the way to the root: each limit less what its group holds that the kernel
// cannot drop (its file pages it can). SIZE_MAX when no group has a limit.
size_t cgroup_room() {
std::string path;
if (FILE* f = std::fopen("/proc/self/cgroup", "r")) {
char line[512];
while (std::fgets(line, sizeof(line), f))
if (std::strncmp(line, "0::", 3) == 0) {
path = line + 3;
break;
}
std::fclose(f);
}
while (!path.empty() && path.back() == '\n') path.pop_back();
if (path.empty() || path[0] != '/') return SIZE_MAX; // cgroup v1 only
size_t room = SIZE_MAX;
for (;;) {
const std::string dir = "/sys/fs/cgroup" + (path == "/" ? std::string() : path);
unsigned long long max = 0, cur = 0, file = 0;
bool limited = false; // "max" when there is no limit
if (FILE* f = std::fopen((dir + "/memory.max").c_str(), "r")) {
limited = std::fscanf(f, "%llu", &max) == 1;
std::fclose(f);
}
if (limited) {
if (FILE* f = std::fopen((dir + "/memory.current").c_str(), "r")) {
if (std::fscanf(f, "%llu", &cur) != 1) cur = 0;
std::fclose(f);
}
if (FILE* f = std::fopen((dir + "/memory.stat").c_str(), "r")) {
char key[64];
unsigned long long v = 0;
while (std::fscanf(f, "%63s %llu", key, &v) == 2)
if (std::strcmp(key, "file") == 0) {
file = v;
break;
}
std::fclose(f);
}
const unsigned long long held = cur > file ? cur - file : 0;
room = std::min(room, max > held ? (size_t) (max - held) : 0);
}
if (path == "/") break;
const size_t cut = path.find_last_of('/');
path = cut == 0 ? "/" : path.substr(0, cut);
}
return room;
}
#endif
// The RAM the machine has free for the model's file, or 0 when it cannot tell: under a cgroup's limit, what that
// leaves if it is less, and then *own is true.
size_t ram_available(bool* own = nullptr) {
if (own) *own = false;
#if defined(STRATA_GPU_METAL)
return strata::core::available_host_bytes().value_or(0);
#elif defined(_WIN32)
MEMORYSTATUSEX st{};
st.dwLength = sizeof(st);
return GlobalMemoryStatusEx(&st) ? (size_t) st.ullAvailPhys : 0;
#else
size_t kb = 0;
if (FILE* f = std::fopen("/proc/meminfo", "r")) {
char line[128];
while (std::fgets(line, sizeof(line), f))
if (std::sscanf(line, "MemAvailable: %zu kB", &kb) == 1) break;
std::fclose(f);
}
#ifdef __linux__
const size_t group = cgroup_room();
if (own) *own = group < (kb << 10);
return std::min(kb << 10, group);
#else
return kb << 10;
#endif
#endif
}
} // namespace
// One expert on its way into the cache. The engine's thread asks, the follower copies and sends, and the engine's
// thread gives it the slot once the upload has arrived.
struct Engine::Swap {
enum { kFree, kAsked, kSent };
std::atomic<int> at{kFree};
int il = 0, e = 0;
uint8_t* slot = nullptr; // where it goes in VRAM: the slot of the expert it replaces
bool adds = false; // the slot was empty (grow_cache()): the cache holds one more
cudaEvent_t done = nullptr; // marks its upload
int32_t from = -1; // the pool_ slot it is copied from, held (pool_pin_) until it has arrived
bool mapped = true; // else read from the files
int64_t takes = -1; // the expert (layer * n_expert + expert) given its place in kept_, or -1
int64_t gets = -1; // the expert given `from` once it has arrived, or -1
const uint8_t* mirror = nullptr; // its slot in the mirror, uploaded from there; given back once it has arrived
uint8_t* spare = nullptr; // a spare mirror slot the expert it replaces is copied back into, or null
int64_t out = -1; // that expert (layer * n_expert + expert)
cudaEvent_t freed = nullptr; // card_far_: the expert it replaces is in its spare already, copied on st_
bool wait_freed = false;
};
Engine::Engine() = default;
Engine::~Engine() {
next_.reset();
OnCard here(device_, split_);
map_quit_.store(true);
if (mapper_.joinable()) mapper_.join();
{
std::lock_guard<std::mutex> l(pool_m_);
pool_quit_ = true;
}
pool_cv_.notify_all();
for (std::thread& t : pool_threads_) t.join();
if (follower_.joinable()) {
{
std::lock_guard<std::mutex> l(swap_m_);
swap_quit_ = true;
}
swap_cv_.notify_all();
follower_.join();
}
if (lock_thread_.joinable()) {
{
std::lock_guard<std::mutex> l(lock_m_);
lock_quit_ = true;
}
lock_cv_.notify_all();
lock_thread_.join();
}
if (swap_st_) cudaStreamSynchronize(cs(swap_st_));
if (up_) cudaStreamSynchronize(cs(up_));
if (rs_) cudaStreamSynchronize(cs(rs_));
if (st_) cudaStreamSynchronize(cs(st_));
aside_.reset();
workers_.reset();
mmq_.reset();
#if defined(STRATA_GPU_METAL)
// Metal recordings retain their resources. Retire them before releasing the allocation owners.
for (void* g : graphs_) cudaGraphExecDestroy((cudaGraphExec_t) g);
graphs_.clear();
#endif
free_pieces(mirror_blocks_);
free_pieces(lock_blocks_);
for (void* e : gather_ev_)
if (e) cudaEventDestroy((cudaEvent_t) e);
for (void* p : dev_allocs_) cudaFree(p);
for (Kv& k : kv_) vmm_free(k);
for (Seq& q : seqs_) {
for (Kv& k : q.kv) vmm_free(k);
// The fp16 twins of the int8 caches (Gemma 4's --kv int8) are the sequences'.
if (q.twin_k.base) vmm_free(q.twin_k);
if (q.twin_v.base) vmm_free(q.twin_v);
}
vmm_free(arena_);
vmm_free(stage_map_);
vmm_free(carry_map_);
vmm_free(prompt_map_);
vmm_free(work_map_);
for (unsigned long long h : vpool_) cuMemRelease(h); // the pool goes back to the card with the engine
vpool_.clear();
for (void* p : host_allocs_) cudaFreeHost(p);
for (void* e : {ev_stage_[0], ev_stage_[1], ev_ahead_, ev_free_, ev_in_[0], ev_in_[1], ev_out_[0], ev_out_[1], ev_hr_,
ev_saved_, ev_bell_})
if (e) cudaEventDestroy((cudaEvent_t) e);
for (void* e : swap_pin_ev_)
if (e) cudaEventDestroy((cudaEvent_t) e);
for (void* e : ev_row_)
if (e) cudaEventDestroy((cudaEvent_t) e);
for (const Ahead& g : ahead_) {
for (void* e : {g.up, g.read})
if (e) cudaEventDestroy((cudaEvent_t) e);
for (void* e : g.arrived)
if (e) cudaEventDestroy((cudaEvent_t) e);
}
for (int j = 0; j < n_swap_; ++j)
for (cudaEvent_t e : {swap_[(size_t) j].done, swap_[(size_t) j].freed})
if (e) cudaEventDestroy(e);
for (void* g : graphs_) cudaGraphExecDestroy((cudaGraphExec_t) g);
blas_destroy(blas_);
if (swap_st_) cudaStreamDestroy(cs(swap_st_));
if (up_) cudaStreamDestroy(cs(up_));
if (rs_) cudaStreamDestroy(cs(rs_));
if (st_) cudaStreamDestroy(cs(st_));
}
void* Engine::dmalloc(size_t bytes, const char* what) {
void* p = nullptr;
const cudaError_t e = cudaMalloc(&p, std::max<size_t>(bytes, 256));
if (e != cudaSuccess) {
cudaGetLastError(); // as ck() does
throw std::runtime_error("no VRAM for " + std::string(what) + " (" + std::to_string(bytes >> 20) +
" MiB): " + cudaGetErrorString(e));
}
dev_allocs_.push_back(p);
return p;
}
void* Engine::hmalloc(size_t bytes, const char* what) {
void* p = nullptr;
const std::string why = std::string(what) + " (" + std::to_string(bytes) + " bytes)";
// A container at its memory limit refused pinned memory with "invalid argument" five times in five minutes
// while a download filled its page cache; a moment later the kernel has reclaimed some.
cudaError_t e = cudaSuccess;
for (int tries = 0; tries < 4; ++tries) {
e = cudaMallocHost(&p, std::max<size_t>(bytes, 256));
if (e == cudaSuccess) break;
cudaGetLastError();
std::fprintf(stderr, "strata-poly: %s: %s, trying again\n", why.c_str(), cudaGetErrorString(e));
std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
ck(e, why.c_str());
host_allocs_.push_back(p);
return p;
}
// What hmalloc() gave, given back. Null is nothing.
void Engine::hfree(void* p) {
if (!p) return;
host_allocs_.erase(std::find(host_allocs_.begin(), host_allocs_.end(), p));
ck(cudaFreeHost(p), "freeing pinned memory");
}
// A write into VRAM and a run of zeros in it, both on st_.
//
// They used to be plain cudaMemcpy()/cudaMemset(), which run on the implicit (legacy) stream. That stream is
// NOT ordered against this engine's - every one of them is created with cudaStreamNonBlocking - so none of the
// cudaStreamSynchronize(cs(st_)) that guard VRAM waits for those copies. The load fills the expert cache with
// them, and the first request whose prompt is longer than kKvGrow reaches cover() with rows to map: cover()
// asks shrink_cache() for the VRAM, and shrink_cache() gives pieces back (vmm_unmap, "the card must be done
// with them") while the load's last copies are still writing them. The card then says
// "rms_norm: an illegal memory access" at the first token of the prompt - for any prompt over kKvGrow tokens, on
// any architecture (LFM2.5 and Qwen3.6 alike), and never for a shorter one, whose cover() has nothing to map
// and so never gives VRAM back. On st_ the same copies are behind the syncs that were already there.
void Engine::h2d(void* dst, const void* src, size_t bytes) {
ck(cudaMemcpyAsync(dst, src, bytes, cudaMemcpyHostToDevice, cs(st_)), "a copy into VRAM");
}
void Engine::zero_vram(void* dst, size_t bytes) {
ck(cudaMemsetAsync(dst, 0, bytes, cs(st_)), "zeroing VRAM");
}
// A container whose memory is not much more than the model's files. The file cache cannot hold them beside
// the engine, so an answer reads experts from the disk: on a pod with 80 GiB and two RTX 3080s, GLM REAP50's
// 79 GB file wrote at 6 tokens/s where 20. And the pod ended the engine with SIGKILL in half of its long reads,
// within 2% of the limit, with no OOM kill counted by the kernel. Said once at load; the remedy is RAM.
void Engine::mind_memory() {
#ifdef __linux__
if (split_ && lo_ > 0) return; // the first card's engine says it for all of them
static const char* const files[] = {"/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"};
unsigned long long limit = 0;
for (const char* path : files) {
FILE* f = std::fopen(path, "r");
if (!f) continue;
if (std::fscanf(f, "%llu", &limit) != 1) limit = 0; // "max" when there is none
std::fclose(f);
break;
}
if (limit == 0 || limit >= (1ULL << 50)) return; // none, or one beyond any machine's RAM
const uint64_t file = gg_->bytes() + (dg_ ? dg_->bytes() : 0);
if (file + (8ULL << 30) <= limit) return; // the engine and the rest of the container take a few GiB
std::fprintf(stderr, "strata-poly: the model's files are %.1f GiB and the container has %.1f GiB: the file "
"cache cannot hold them beside the engine, so answers will read experts from the disk, "
"and the container may end the engine\n",
(double) file / (1 << 30), (double) limit / (1 << 30));
#endif
}
#ifdef STRATA_VMM_EQUAL_PIECES
// Whether a reservation's pieces must all be of one size (hip_compat/cuda.h): under WSL2, where ROCm reaches the card
// through librocdxg (/dev/dxg, and no /dev/kfd). STRATA_VMM_EQUAL_PIECES=1 or 0 says it for any Linux HIP build.
static bool vmm_equal_pieces() {
static const bool on = [] {
if (const char* v = std::getenv("STRATA_VMM_EQUAL_PIECES"); v && v[0]) return v[0] != '0';
std::error_code ec;
return std::filesystem::exists("/dev/dxg", ec) && !std::filesystem::exists("/dev/kfd", ec);
}();
return on;
}
// The unit such pieces are made of, 2 MiB like the pool's handles: vmm_reserve() reserves a whole number of them.
static size_t vmm_unit(size_t grain) { return up_to(size_t(2) << 20, grain); }
// The size of every piece of a reservation of `reserved` bytes: `first`, the size of the piece it has, or for its
// first map the most units that divide the reservation and are no more than the piece asked for and the map's bytes.
// A map then covers a whole number of pieces, and the last one is no shorter than the others.
static size_t vmm_piece(size_t reserved, size_t first, size_t bytes, size_t piece, size_t unit) {
if (first) return first;
const size_t most = std::min(up_to(std::min(piece, reserved), unit), up_to(bytes, unit)) / unit;
size_t k = std::max<size_t>(most, 1);
while (k > 1 && (reserved / unit) % k != 0) --k;
return k * unit;
}
#endif
void Engine::vmm_reserve(Mapped& m, size_t bytes) {
CUdeviceptr p = 0;
#ifdef STRATA_VMM_EQUAL_PIECES
// with equal pieces, a whole number of their units
m.reserved = up_to(std::max<size_t>(bytes, 1), pool_on_ ? pg_ : vmm_equal_pieces() ? vmm_unit(grain_) : grain_);
#else
m.reserved = up_to(std::max<size_t>(bytes, 1), pool_on_ ? pg_ : grain_); // a whole number of pool handles
#endif
cu_ck(cuMemAddressReserve(&p, m.reserved, 0, 0, 0), "reserving addresses for VRAM");
m.base = p;
}
// The pool: `bytes` of VRAM as handles of pg_ bytes, kept until the engine ends. Creating a handle takes its VRAM
// (measured on Windows HIP: the card's free figure drops at the create, before anything is mapped), so what is
// claimed here is the engine's from now on. The card may have less: the pool is what it could give.
void Engine::vpool_claim(size_t bytes) {
CUmemAllocationProp prop = {};
prop.type = CU_MEM_ALLOCATION_TYPE_PINNED;
prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
prop.location.id = device_;
vpool_.reserve(vpool_.size() + bytes / pg_ + 1);
for (size_t got = 0; got + pg_ <= bytes; got += pg_) {
CUmemGenericAllocationHandle h = 0;
if (cuMemCreate(&h, pg_, &prop, 0) != CUDA_SUCCESS) {
(void) cudaGetLastError();
break;
}
vpool_.push_back(h);
}