Repository navigation
Expand file tree
/
Copy pathexpert_source.cpp
More file actions
6758 lines (6540 loc) · 350 KB
/
Copy pathexpert_source.cpp
File metadata and controls
6758 lines (6540 loc) · 350 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/core/expert_source.cpp - the adapter. See the header for the three clauses of the contract.
#include "strata/core/expert_source.hpp"
#include "strata/core/expert_nibble.hpp"
#include "strata/core/conversation_memory.hpp"
#include "strata/core/foresight_swap.hpp"
#include "strata/core/on_device.hpp"
#include "strata/core/ple_residency.hpp"
#include "strata/core/resident_ram_copy.hpp"
#include "strata/platform/aux_cpus.hpp"
#include "strata/core/remote_experts.hpp"
#include "strata/core/peer_experts.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
#include "strata/kernels/window_limits.hpp"
#include "strata/artifact/gguf_reader.hpp"
#include "strata/core/pinned.hpp"
#include "strata/platform/memory.hpp"
#include "strata/kernels/elementwise.hpp"
#include "strata/kernels/quantize_act.hpp"
#include "strata/kernels/s2_expert_grouped.hpp"
#include "strata/kernels/cpu/kq_avx1.hpp"
#include "strata/kernels/cpu/kq_avx2.hpp"
#include "strata/kernels/cpu/pool.hpp"
#include <cuda_runtime.h>
#ifndef _WIN32
#include <signal.h>
#include <unistd.h>
#endif
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cerrno>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <fstream>
#include <filesystem>
#include <iterator>
#include <sstream>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <thread>
#include <utility>
#include <vector>
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#ifndef NOMINMAX
#define NOMINMAX // std::numeric_limits<T>::max() below
#endif
#include <windows.h>
#else
#include <fcntl.h>
#if defined(__APPLE__)
#include <mach/mach.h> // host_statistics64: the available memory
#endif
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#if defined(__linux__)
#include <cerrno>
#include <linux/aio_abi.h> // the kernel's own asynchronous reads (io_submit): no library, allowed by Docker's seccomp
#include <sched.h>
#include <sys/syscall.h>
#endif
// a 64-bit seek (as in pinned.cu): the 32-bit `fseek` wraps past 4 GiB, and the spelling differs per platform
#ifndef STRATA_FSEEK64
#ifdef _WIN32
#define STRATA_FSEEK64(f, o) _fseeki64((f), (long long) (o), SEEK_SET)
#else
#define STRATA_FSEEK64(f, o) fseeko((f), (off_t) (o), SEEK_SET)
#endif
#endif
// The pid of this process and whether a pid still exists (the shared arena's reader election, both OSes)
static uint64_t arena_this_pid() {
#ifdef _WIN32
return (uint64_t) GetCurrentProcessId();
#else
return (uint64_t) getpid();
#endif
}
static bool arena_pid_alive(uint64_t pid) {
#ifdef _WIN32
HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, (DWORD) pid);
if (h == nullptr) return GetLastError() == ERROR_ACCESS_DENIED; // (denied: it exists; invalid parameter: it does not)
DWORD code = 0;
const bool alive = GetExitCodeProcess(h, &code) && code == STILL_ACTIVE;
CloseHandle(h);
return alive;
#else
return !(kill((pid_t) pid, 0) != 0 && errno == ESRCH);
#endif
}
namespace strata::core {
namespace detail {
bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64_t& bytes) {
bytes = 0;
if (!stat.valid) return false;
// memory.stat's counters can race memory.current, so bound them to charged usage first. The whole clean page
// cache is reclaimable (149: MemAvailable counts active file pages too); the kernel keeps a low-watermark share.
uint64_t reclaimable = std::min(std::max(stat.file, stat.inactive_file), stat.current);
reclaimable = stat.file_dirty >= reclaimable ? 0 : reclaimable - stat.file_dirty;
reclaimable = stat.file_writeback >= reclaimable ? 0 : reclaimable - stat.file_writeback;
reclaimable -= std::min(reclaimable / 2, limit / 64);
// Reclaiming clean file pages reduces usage; saturating subtraction also handles a transient over-limit read.
const uint64_t usage_after_reclaim = stat.current - reclaimable;
bytes = usage_after_reclaim < limit ? limit - usage_after_reclaim : 0;
return true;
}
uint64_t clamp_resident_budget(uint64_t requested, uint64_t physical, uint64_t commit, uint64_t headroom) {
const uint64_t available = std::min(physical, commit);
const uint64_t room = available > headroom ? available - headroom : 0;
if (requested <= room) return requested;
const uint64_t margin = 256ull << 20;
return room > margin ? room - margin : 0;
}
bool pin_depends_on_reclaim(uint64_t free_now, uint64_t bytes, uint64_t reserve) {
return bytes > 0 && free_now < bytes + reserve;
}
bool wait_for_ram(uint64_t need, double max_wait_s, double step_s, double note_s,
const std::function<bool(uint64_t&)>& sample, const std::function<void(double)>& sleep,
const std::function<void(double, uint64_t)>& progress, double& waited, uint64_t& available) {
waited = 0.0;
if (!sample(available)) return false;
double next_note = 0.0;
while (available < need && waited < max_wait_s) {
if (progress && waited >= next_note) {
progress(waited, available);
next_note = waited + note_s;
}
sleep(step_s);
waited += step_s;
if (!sample(available)) return false;
}
return available >= need;
}
bool pin_step_fits(uint64_t available, uint64_t step, uint64_t reserve) {
return available >= step + reserve;
}
uint64_t meminfo_bytes(const std::string& meminfo_text, const std::string& key) {
std::istringstream in(meminfo_text);
std::string line;
const std::string want = key + ":";
while (std::getline(in, line)) {
std::istringstream fields(line);
std::string k, unit;
uint64_t value = 0;
if (fields >> k >> value && k == want) {
fields >> unit;
return unit == "kB" ? value * 1024 : value;
}
}
return 0;
}
uint64_t numa_pin_free(uint64_t global_free, const std::vector<uint64_t>& node_free) {
if (node_free.size() < 2) return global_free;
const uint64_t smallest = *std::min_element(node_free.begin(), node_free.end());
return std::min<uint64_t>(global_free, smallest * (uint64_t) node_free.size());
}
std::array<std::pair<uint64_t, uint64_t>, 3> numa_slice_ranges(uint64_t slot_off, const uint64_t role_bytes[3],
int slice, uint64_t page) {
assert(slice == 0 || slice == 1);
std::array<std::pair<uint64_t, uint64_t>, 3> out{};
uint64_t start = slot_off;
for (int r = 0; r < 3; ++r) {
const uint64_t mid = start + role_bytes[r] / 2, end = start + role_bytes[r];
if (slice == 0) {
out[r] = {start / page * page, (mid + page - 1) / page * page};
} else {
const uint64_t lo = (mid + page - 1) / page * page, hi = end / page * page;
out[r] = hi > lo ? std::make_pair(lo, hi) : std::make_pair(lo, lo);
}
start = end;
}
return out;
}
std::string page_cache_hint(const std::string& meminfo_text) {
const uint64_t cache = meminfo_bytes(meminfo_text, "Cached") + meminfo_bytes(meminfo_text, "Buffers");
if (cache < (1ull << 30)) return "";
char msg[420];
std::snprintf(msg, sizeof msg,
"; %.1f GiB of the RAM is file cache (earlier runs' model files, which Linux gives back on demand - "
"'free' showing little is normal). If the start still fails, free it with: "
"sync; echo 1 | sudo tee /proc/sys/vm/drop_caches (or start strata serve with "
"STRATA_DROP_CACHE_ON_EXIT=1 so it releases its model files when it stops)",
(double) cache / 1073741824.0);
return msg;
}
bool make_cache_complement_plan(
int64_t n_layers, int64_t n_expert, const std::vector<uint64_t>& layer_blob_bytes,
const std::vector<std::pair<int32_t, int32_t>>& primary_gpu_pairs,
const std::vector<std::pair<int32_t, int32_t>>& additional_gpu_pairs,
std::vector<uint64_t>& offsets, uint64_t& bytes, std::string& err) {
offsets.clear();
bytes = 0;
err.clear();
if (n_layers <= 0 || n_expert <= 0 || layer_blob_bytes.size() != (size_t) n_layers) {
err = "FileExpertSource: invalid geometry for the cache complement plan";
return false;
}
if ((uint64_t) n_layers > (uint64_t) std::numeric_limits<size_t>::max() / (uint64_t) n_expert) {
err = "FileExpertSource: cache complement index table is too large";
return false;
}
const size_t count = (size_t) n_layers * (size_t) n_expert;
std::vector<uint8_t> omitted(count, 0);
auto mark_pairs = [&](const std::vector<std::pair<int32_t, int32_t>>& pairs, uint8_t bit,
const char* label) -> bool {
for (const auto& pair : pairs) {
if (pair.first < 0 || pair.second < 0 || pair.first >= n_layers || pair.second >= n_expert) {
err = std::string("FileExpertSource: ") + label + " pair is outside the expert geometry";
return false;
}
const size_t index = (size_t) pair.first * (size_t) n_expert + (size_t) pair.second;
if ((omitted[index] & bit) != 0) {
err = std::string("FileExpertSource: duplicate ") + label + " pair in the cache complement plan";
return false;
}
if (bit == 2 && (omitted[index] & 1) != 0) {
err = "FileExpertSource: the primary and additional GPU expert tiers overlap";
return false;
}
omitted[index] |= bit;
}
return true;
};
if (!mark_pairs(primary_gpu_pairs, 1, "primary GPU") ||
!mark_pairs(additional_gpu_pairs, 2, "additional GPU")) return false;
for (uint64_t blob_bytes : layer_blob_bytes) {
if (blob_bytes == 0) {
err = "FileExpertSource: cache complement layer has zero-sized expert blobs";
return false;
}
}
offsets.assign(count, kNoCacheComplement);
for (int64_t layer = 0; layer < n_layers; ++layer) {
const uint64_t blob_bytes = layer_blob_bytes[(size_t) layer];
for (int64_t expert = 0; expert < n_expert; ++expert) {
const size_t index = (size_t) layer * (size_t) n_expert + (size_t) expert;
if (omitted[index] != 0) continue;
if (bytes > std::numeric_limits<uint64_t>::max() - blob_bytes) {
offsets.clear();
bytes = 0;
err = "FileExpertSource: cache complement size overflows";
return false;
}
offsets[index] = bytes;
bytes += blob_bytes;
}
}
if (bytes > (uint64_t) std::numeric_limits<size_t>::max()) {
offsets.clear();
bytes = 0;
err = "FileExpertSource: cache complement exceeds the host address space";
return false;
}
return true;
}
const uint8_t* cache_complement_blob_or_fallback(
size_t index, const std::vector<uint64_t>& offsets, const uint8_t* complement_host,
const uint8_t* mapped_fallback) {
if (complement_host != nullptr && index < offsets.size() && offsets[index] != kNoCacheComplement)
return complement_host + (size_t) offsets[index];
return mapped_fallback;
}
int64_t choose_resident_keep_from(const std::vector<uint64_t>& slot_bytes, uint64_t base_bytes, uint64_t budget,
int64_t lend_from) {
if (base_bytes > budget) return -1;
const int64_t slots = (int64_t) slot_bytes.size();
if (lend_from < 0 || lend_from > slots) lend_from = slots; // no lend region: only the experts no slot holds
int64_t keep = slots;
uint64_t bytes = base_bytes;
while (keep > lend_from) {
const uint64_t b = slot_bytes[(size_t) keep - 1];
if (b > budget - bytes) break;
bytes += b;
--keep;
}
return keep;
}
int64_t append_stage_lend_regions(int64_t n_layers, int64_t n_expert, const std::vector<uint64_t>& layer_blob_bytes,
std::vector<uint64_t>& offsets, uint64_t& bytes, uint64_t cap_bytes,
const std::vector<std::vector<std::pair<int32_t, int32_t>>>& regions,
std::string& err) {
const size_t blobs = (size_t) (n_layers * n_expert);
if (n_layers <= 0 || n_expert <= 0 || layer_blob_bytes.size() != (size_t) n_layers || offsets.size() != blobs) {
err = "append_stage_lend_regions: the plan does not match the geometry";
return -1;
}
std::vector<std::pair<int32_t, int32_t>> sorted;
for (const auto& region : regions) { // validate the whole request before touching the plan
for (const auto& pair : region)
if (pair.first < 0 || pair.first >= n_layers || pair.second < 0 || pair.second >= n_expert) {
err = "append_stage_lend_regions: a lend-region expert is outside the model";
return -1;
}
sorted = region;
std::sort(sorted.begin(), sorted.end());
for (size_t i = 1; i < sorted.size(); ++i)
if (sorted[i] == sorted[i - 1]) {
err = "append_stage_lend_regions: a stage's lend region repeats an expert";
return -1;
}
}
int64_t kept = 0;
for (const auto& region : regions) {
for (const auto& pair : region) {
const size_t index = (size_t) pair.first * (size_t) n_expert + (size_t) pair.second;
if (offsets[index] != kNoCacheComplement) continue; // already in the copy: the complement, or a
// CUDA0 lend slot the region is asked to skip
const uint64_t b = layer_blob_bytes[(size_t) pair.first];
if (b > cap_bytes - bytes) break; // this stage's rest keeps the file fallback
offsets[index] = bytes;
bytes += b;
++kept;
}
}
return kept;
}
bool exchange_cache_complement(std::vector<uint64_t>& offsets, size_t in, size_t out) {
if (in == out || in >= offsets.size() || out >= offsets.size() || offsets[in] == kNoCacheComplement ||
offsets[out] != kNoCacheComplement) return false;
offsets[out] = offsets[in];
offsets[in] = kNoCacheComplement;
return true;
}
} // namespace detail
namespace {
#if defined(__linux__)
bool read_cgroup_memory_stat(const std::filesystem::path& path, uint64_t current,
detail::CgroupMemoryStat& stat) {
std::ifstream input(path / "memory.stat");
if (!input) return false;
bool inactive_file = false, file_dirty = false, file_writeback = false, file = false;
std::string line;
while (std::getline(input, line)) {
std::istringstream fields(line);
std::string key;
uint64_t value = 0;
if (!(fields >> key >> value)) return false;
fields >> std::ws;
if (!fields.eof()) return false;
if (key == "inactive_file") {
if (inactive_file) return false;
inactive_file = true;
stat.inactive_file = value;
} else if (key == "file_dirty") {
if (file_dirty) return false;
file_dirty = true;
stat.file_dirty = value;
} else if (key == "file_writeback") {
if (file_writeback) return false;
file_writeback = true;
stat.file_writeback = value;
} else if (key == "file") { // 149: optional (every v2 kernel has it); 0 = inactive_file alone
if (file) return false;
file = true;
stat.file = value;
}
}
if (!input.eof() || !inactive_file || !file_dirty || !file_writeback) return false;
stat.current = current;
stat.valid = true;
return true;
}
#endif
} // namespace
namespace detail {
bool host_available_memory(HostMemory& m, const std::string& meminfo, const std::string& self_cgroup,
const std::string& cgroup_root) {
m = HostMemory{};
#if defined(_WIN32)
(void) meminfo; (void) self_cgroup; (void) cgroup_root;
MEMORYSTATUSEX status{};
status.dwLength = sizeof(status);
if (!GlobalMemoryStatusEx(&status)) return false;
m.available = (uint64_t) status.ullAvailPhys;
m.commit = (uint64_t) status.ullAvailPageFile;
return m.available > 0;
#elif defined(__linux__)
// MemAvailable includes reclaimable page cache, unlike _SC_AVPHYS_PAGES.
std::ifstream info(meminfo);
std::string line;
uint64_t bytes = 0;
while (std::getline(info, line)) {
std::istringstream fields(line);
std::string key, unit;
uint64_t value = 0;
if (fields >> key >> value >> unit && key == "MemAvailable:" && unit == "kB" &&
value <= std::numeric_limits<uint64_t>::max() / 1024) bytes = value * 1024;
}
if (bytes == 0) return false;
// Account for the tightest cgroup ancestor limit when its normal mount is visible.
// This is a point-in-time guard, not a reservation against concurrent allocations.
std::ifstream groups(self_cgroup);
if (!groups) return false;
const std::filesystem::path root(cgroup_root);
bool v2 = false;
std::string v1_path; // the memory controller's group (cgroup v1), when there is no v2 line
while (std::getline(groups, line)) {
if (line.rfind("0::/", 0) != 0) {
// v1: "N:controller[,controller]:/path"
const size_t c1 = line.find(':'), c2 = c1 == std::string::npos ? c1 : line.find(':', c1 + 1);
if (c2 == std::string::npos) continue;
std::istringstream ctl(line.substr(c1 + 1, c2 - c1 - 1));
for (std::string c; std::getline(ctl, c, ',');)
if (c == "memory") v1_path = line.substr(c2 + 1);
continue;
}
auto path = (root / line.substr(4)).lexically_normal();
if (path.string().rfind(root.string(), 0) != 0 || !std::filesystem::is_directory(path)) return false;
v2 = true;
while (path.string().rfind(root.string(), 0) == 0) {
std::ifstream limit_file(path / "memory.max"), current_file(path / "memory.current");
std::string limit;
uint64_t current = 0;
const bool readable = bool(limit_file >> limit) && bool(current_file >> current);
// The host's root cgroup has no memory.max; ordinary child groups must expose their limits.
if (!readable && !(path == root && !std::filesystem::exists(path / "memory.max") &&
std::filesystem::exists(path / "cgroup.controllers"))) return false;
if (readable && limit != "max") {
try {
size_t consumed = 0;
const uint64_t cap = std::stoull(limit, &consumed);
if (consumed != limit.size()) return false;
CgroupMemoryStat stat;
if (!read_cgroup_memory_stat(path, current, stat)) return false;
uint64_t cgroup_available = 0;
if (!cgroup_available_bytes(cap, stat, cgroup_available)) return false;
bytes = std::min(bytes, cgroup_available);
m.cgroup_limit = std::min(m.cgroup_limit, cap);
} catch (...) { return false; }
}
if (path == root) break;
path = path.parent_path();
}
}
if (!v2 && !v1_path.empty()) {
// #633: cgroup v1 (older Docker hosts, RHEL 7/8): the memory controller's group and its ancestors. An
// unlimited group says a number near 2^63 (rounded to its page size); a group whose files are not
// visible (no mount in this namespace) is skipped - MemAvailable alone, as with no cgroup at all.
const std::filesystem::path mroot = root / "memory";
auto path = (mroot / v1_path.substr(v1_path.rfind('/', 0) == 0 ? 1 : 0)).lexically_normal();
while (path.string().rfind(mroot.string(), 0) == 0) {
std::ifstream limit_file(path / "memory.limit_in_bytes"), usage_file(path / "memory.usage_in_bytes");
uint64_t cap = 0, usage = 0;
if (limit_file >> cap && usage_file >> usage && cap < (1ull << 62)) {
bytes = std::min(bytes, usage < cap ? cap - usage : 0);
m.cgroup_limit = std::min(m.cgroup_limit, cap);
}
if (path == mroot) break;
path = path.parent_path();
}
}
m.available = bytes;
return true;
#elif defined(__APPLE__)
// macOS: free + inactive + purgeable pages (what the OS can hand out without swapping), as vm_stat reports them
(void) meminfo; (void) self_cgroup; (void) cgroup_root;
vm_statistics64_data_t vs{};
mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
vm_size_t page_bytes = 0;
if (host_page_size(mach_host_self(), &page_bytes) != KERN_SUCCESS ||
host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t) &vs, &count) != KERN_SUCCESS) return false;
m.available = ((uint64_t) vs.free_count + vs.inactive_count + vs.purgeable_count) * (uint64_t) page_bytes;
return m.available > 0;
#else
(void) meminfo; (void) self_cgroup; (void) cgroup_root;
const long pages = sysconf(_SC_AVPHYS_PAGES);
const long page_bytes = sysconf(_SC_PAGESIZE);
if (pages <= 0 || page_bytes <= 0 ||
(uint64_t) pages > std::numeric_limits<uint64_t>::max() / (uint64_t) page_bytes) return false;
m.available = (uint64_t) pages * (uint64_t) page_bytes;
return m.available > 0;
#endif
}
} // namespace detail
namespace {
bool available_memory_bytes(uint64_t& bytes, uint64_t* commit = nullptr) {
detail::HostMemory m;
if (!detail::host_available_memory(m)) return false;
bytes = m.available;
if (commit != nullptr) *commit = m.commit;
return bytes > 0;
}
/// #1250: the pages that are really free (MemFree), not the reclaimable cache MemAvailable counts; false when unknown.
bool free_memory_bytes(uint64_t& bytes) {
#if defined(__linux__)
std::ifstream info("/proc/meminfo");
if (!info) return false;
std::stringstream text;
text << info.rdbuf();
bytes = detail::meminfo_bytes(text.str(), "MemFree");
if (bytes == 0) return false;
// 0.1.42: a multi-socket host's nodes each have their own free pages; judge by the emptiest one too
std::vector<uint64_t> nodes;
for (int n = 0; n < 64; ++n) {
std::ifstream node("/sys/devices/system/node/node" + std::to_string(n) + "/meminfo");
if (!node) break;
std::string line;
while (std::getline(node, line)) {
std::istringstream f(line);
std::string a, id, key;
uint64_t kb = 0;
if (f >> a >> id >> key >> kb && key == "MemFree:") { nodes.push_back(kb * 1024); break; }
}
}
bytes = detail::numa_pin_free(bytes, nodes);
return bytes > 0;
#else
bytes = 0;
return false;
#endif
}
void log_complement_memory(const char* stage, uint64_t requested) {
#if defined(_WIN32)
MEMORYSTATUSEX status{};
status.dwLength = sizeof(status);
if (!GlobalMemoryStatusEx(&status)) {
std::fprintf(stderr, "FileExpertSource: %s: GlobalMemoryStatusEx failed (error %lu)\n", stage, GetLastError());
return;
}
std::fprintf(stderr, "FileExpertSource: %s: requested %.2f GiB, available RAM %.2f GiB, available commit %.2f GiB "
"(limit %.2f GiB), available virtual address space %.2f GiB\n",
stage, (double) requested / 1073741824.0, (double) status.ullAvailPhys / 1073741824.0,
(double) status.ullAvailPageFile / 1073741824.0, (double) status.ullTotalPageFile / 1073741824.0,
(double) status.ullAvailVirtual / 1073741824.0);
#else
(void) stage;
(void) requested;
#endif
}
#if defined(__linux__)
/// STRATA_NUMA_SPLIT step B: each NUMA slice of every complement slot (numa_slice_ranges) is first-touched by a helper
/// thread pinned to one core of that slice's node, so the default local policy puts its pages there (no mbind: ~113k
/// ranges would split the arena into more VMAs than vm.max_map_count allows). Inactive (`place` false) unless the
/// live pool split on real nodes; then the paced fault loop hands it each step to touch.
struct NumaComplementPlacement {
bool place = false;
int nodes[2] = {-1, -1};
int core[2] = {-1, -1};
std::vector<std::pair<uint64_t, uint64_t>> ranges[2]; ///< page-aligned, sorted, coalesced, arena offsets
uint64_t slice_bytes[2] = {0, 0};
std::vector<uint64_t> free_before; ///< MemFree per node before the allocation
std::vector<uint64_t> free_after; ///< the same after the model files' pages are released
std::atomic<bool> pin_failed{false};
std::chrono::steady_clock::time_point t0;
static std::vector<uint64_t> node_free() {
// CBA: stops at the first missing node directory (as free_memory_bytes does), sparse node ids give a false
// "at risk 0.00" line only; list the node directory if a sparse-id host ever shows it
std::vector<uint64_t> out;
for (int n = 0; n < 64; ++n) {
std::ifstream node("/sys/devices/system/node/node" + std::to_string(n) + "/meminfo");
if (!node) break;
std::string line;
uint64_t kb = 0;
while (std::getline(node, line)) {
std::istringstream f(line);
std::string a, id, key;
if (f >> a >> id >> key >> kb && key == "MemFree:") break;
kb = 0;
}
out.push_back(kb * 1024);
}
return out;
}
static std::string free_text(const std::vector<uint64_t>& free) {
std::string s;
char buf[64];
for (size_t n = 0; n < free.size(); ++n) {
std::snprintf(buf, sizeof buf, "%snode %zu %.2f GiB", n ? ", " : "", n, (double) free[n] / 1073741824.0);
s += buf;
}
return s;
}
/// Decides from the live pool's plan; false with a logged reason when the split is on but placement cannot run.
void init(const std::vector<uint64_t>& offsets, int64_t n_expert, const std::vector<uint64_t>& blob_bytes,
const std::vector<uint64_t>& role_bytes) {
// relies on the pool being built first (generate.cpp: the ExpertPool at ~5632, the complement at ~7690)
const auto& plan = strata::kernels::cpu::active_numa_split();
if (!plan.on || plan.test) return;
free_before = node_free();
const char* why = nullptr;
if (role_bytes.size() != 3 * blob_bytes.size()) why = "this pack has no per-role byte sizes (not a GGUF-mapped native pack)";
for (size_t l = 0; why == nullptr && l < blob_bytes.size(); ++l)
if (role_bytes[3 * l] + role_bytes[3 * l + 1] + role_bytes[3 * l + 2] != blob_bytes[l])
why = "the role sizes do not add up to the expert blob";
for (int k = 0; why == nullptr && k < 2; ++k)
if (plan.cores[k].empty()) why = "a slice has no core";
else if (plan.nodes[k] < 0 || plan.nodes[k] >= 64) why = "a node id is out of range";
if (why != nullptr) {
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement FAILED: %s; the complement is placed by "
"first touch as usual (the split runs with remote reads)\n", why);
return;
}
for (int k = 0; k < 2; ++k) {
nodes[k] = plan.nodes[k];
core[k] = plan.cores[k].front(); // workers come before the host core in the plan
std::vector<std::pair<uint64_t, uint64_t>> all;
for (size_t i = 0; i < offsets.size(); ++i) {
if (offsets[i] == detail::kNoCacheComplement) continue;
const size_t l = i / (size_t) n_expert;
for (const auto& r : detail::numa_slice_ranges(offsets[i], &role_bytes[3 * l], k))
if (r.second > r.first) all.push_back(r);
}
std::sort(all.begin(), all.end());
for (const auto& r : all) { // coalesce: ends become monotonic, so a step finds its first range by bisection
if (!ranges[k].empty() && r.first <= ranges[k].back().second)
ranges[k].back().second = std::max(ranges[k].back().second, r.second);
else ranges[k].push_back(r);
}
for (const auto& r : ranges[k]) slice_bytes[k] += r.second - r.first;
}
place = true;
t0 = std::chrono::steady_clock::now();
std::fprintf(stderr, "FileExpertSource: NUMA placement of the complement: slice 0 -> node %d (%.2f GiB, toucher "
"CPU %d), slice 1 -> node %d (%.2f GiB, toucher CPU %d), 4 KiB pages; free before: %s\n",
nodes[0], (double) slice_bytes[0] / 1073741824.0, core[0], nodes[1],
(double) slice_bytes[1] / 1073741824.0, core[1], free_text(free_before).c_str());
}
/// Touches one byte per page of each slice's ranges clipped to [lo, hi), one pinned thread per slice; then the
/// calling thread touches the step's other pages (outside every slice: slot tails, the arena end). The caller
/// must not re-touch slice pages: with automatic NUMA balancing on, its access faults would migrate them to its node.
void touch_step(uint8_t* arena, uint64_t lo, uint64_t hi) {
// CBA: two threads spawned per 1 GiB step (~50 spawns per start); long-lived touchers if the spawn ever shows
auto touch = [&](int k) {
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(core[k], &set);
if (sched_setaffinity(0, sizeof set, &set) != 0) pin_failed = true;
const auto& rs = ranges[k];
auto it = std::partition_point(rs.begin(), rs.end(), [&](const auto& r) { return r.second <= lo; });
for (; it != rs.end() && it->first < hi; ++it)
for (uint64_t at = std::max(it->first, lo); at < std::min(it->second, hi); at += 4096)
((volatile uint8_t*) arena)[at] = 0;
};
// CBA: a failed spawn terminates; fall back to an unpinned touch if it ever happens
std::thread a(touch, 0), b(touch, 1);
a.join();
b.join();
size_t c[2] = {0, 0}; // the pages no slice holds, as the default loop touches them
for (uint64_t at = lo; at < hi; at += 4096) {
bool covered = false;
for (int k = 0; k < 2; ++k) {
while (c[k] < ranges[k].size() && ranges[k][c[k]].second <= at) ++c[k];
covered = covered || (c[k] < ranges[k].size() && ranges[k][c[k]].first <= at);
}
if (!covered) ((volatile uint8_t*) arena)[at] = 0;
}
}
/// After the drop: a node whose free memory cannot take its slice plus `reserve_share` will spill to the other node
/// (no local reclaim); named up front, the 95 % check stays the verdict.
void check_room(uint64_t reserve_share) const {
for (int k = 0; k < 2; ++k) {
const uint64_t room = (size_t) nodes[k] < free_after.size() ? free_after[(size_t) nodes[k]] : 0;
if (room < slice_bytes[k] + reserve_share)
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement at risk: node %d has %.2f GiB free for its "
"%.2f GiB slice plus %.2f GiB of reserve\n",
nodes[k], (double) room / 1073741824.0, (double) slice_bytes[k] / 1073741824.0,
(double) reserve_share / 1073741824.0);
}
}
/// Samples one page in 64 of each slice with move_pages (null node list: returns each page's node) and logs the
/// share on the intended node, once the arena is registered (its final state); `got < bytes` means the paced loop
/// stopped early, `registered < bytes` that the driver did not page-lock all of it: the placement then fails.
void report(const uint8_t* arena, uint64_t got, uint64_t registered, uint64_t bytes, const char* stop) const {
const double secs = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
uint64_t on_node[2] = {0, 0}, sampled[2] = {0, 0}, per_node[2][64] = {}, absent[2] = {0, 0};
constexpr int kNotSampled = -100000; // outside any per-page status (a node id, or -errno)
int sys_errno[2] = {0, 0}; // first errno of a failed move_pages batch, per slice
size_t batches[2] = {0, 0}, failed[2] = {0, 0};
std::vector<void*> pages;
std::vector<int> status;
for (int k = 0; k < 2; ++k) {
uint64_t n = 0;
pages.clear();
for (const auto& r : ranges[k])
for (uint64_t at = r.first; at < r.second; at += 4096, ++n)
if (n % 64 == 0) pages.push_back((void*) (arena + at));
status.assign(pages.size(), -1);
for (size_t b = 0; b < pages.size(); b += 4096) {
const size_t cnt = std::min<size_t>(4096, pages.size() - b);
++batches[k];
if (syscall(SYS_move_pages, 0, (unsigned long) cnt, pages.data() + b, nullptr, status.data() + b, 0) != 0) {
if (sys_errno[k] == 0) sys_errno[k] = errno;
++failed[k];
for (size_t i = b; i < b + cnt; ++i) status[i] = kNotSampled; // the syscall failed: no sample, unlike a page's own -errno
}
}
for (int s : status) {
if (s == kNotSampled) continue;
++sampled[k];
if (s >= 0 && s < 64) ++per_node[k][s];
else ++absent[k];
}
on_node[k] = nodes[k] >= 0 && nodes[k] < 64 ? per_node[k][nodes[k]] : 0;
}
double share[2];
for (int k = 0; k < 2; ++k) share[k] = sampled[k] > 0 ? 100.0 * (double) on_node[k] / (double) sampled[k] : 0.0;
char what[2][96]; // a slice whose move_pages batches all failed has no share to print
for (int k = 0; k < 2; ++k) {
if (batches[k] > 0 && failed[k] == batches[k]) std::snprintf(what[k], sizeof what[k], "not verified");
else std::snprintf(what[k], sizeof what[k], "%.2f GiB (%.1f %% of its slices)",
share[k] / 100.0 * (double) slice_bytes[k] / 1073741824.0, share[k]);
}
std::fprintf(stderr, "FileExpertSource: NUMA placement: node %d %s, node %d %s; free before: %s; after the drop: %s; "
"pages taken and page-locked in %.1f s since the placement started\n",
nodes[0], what[0], nodes[1], what[1], free_text(free_before).c_str(), free_text(free_after).c_str(), secs);
if (got < bytes)
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement FAILED: the paced loop stopped at %.2f of %.2f "
"GiB (%s); the rest is first-touched by unpinned copy threads (memory not placed on its node: the split runs with remote reads)\n",
(double) got / 1073741824.0, (double) bytes / 1073741824.0, stop != nullptr ? stop : "?");
else if (registered < bytes)
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement FAILED: only %.2f of %.2f GiB page-locked (%s); "
"the unregistered pages can be migrated by NUMA balancing (memory not placed on its node: the split runs with remote reads)\n",
(double) registered / 1073741824.0, (double) bytes / 1073741824.0, stop != nullptr ? stop : "?");
if (pin_failed)
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement: a toucher could not be pinned to its core\n");
for (int k = 0; k < 2; ++k) {
if (batches[k] > 0 && failed[k] == batches[k]) {
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement could not be verified: move_pages failed "
"(errno %d: %s) for slice %d (node %d)\n", sys_errno[k], std::strerror(sys_errno[k]), k, nodes[k]);
continue;
}
if (failed[k] > 0)
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement: move_pages failed (errno %d: %s) for %zu of %zu "
"batches of slice %d; judged on the other samples\n", sys_errno[k],
std::strerror(sys_errno[k]), failed[k], batches[k], k);
if (share[k] < 95.0)
std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement FAILED: slice %d has %.1f %% of its pages "
"on node %d (< 95 %%; of %llu sampled: node %d %llu, node %d %llu, not present %llu)\n",
k, share[k], nodes[k], (unsigned long long) sampled[k], nodes[0],
(unsigned long long) per_node[k][nodes[0]], nodes[1], (unsigned long long) per_node[k][nodes[1]],
(unsigned long long) absent[k]);
}
}
};
#endif
/// #286: an unbuffered file handle - a HANDLE on Windows, an O_DIRECT descriptor (as a pointer-sized integer) on Linux.
void close_direct(void* h) {
#if defined(_WIN32)
CloseHandle((HANDLE) h);
#else
::close((int) (intptr_t) h);
#endif
}
#if defined(__linux__)
/// #3237: how fast this drive serves the experts' reads the two ways the file tier can take them - O_DIRECT preads of
/// 1 MiB at random places on 8 threads (the unbuffered tier's I/O threads) against first touches of the pages of random
/// 1 MiB pieces of a mapping on 3 threads (the cached tier: the pool's threads faulting the page cache in). Regions the
/// page cache already holds are skipped, and the probed ranges are dropped from the cache again. The best of two
/// rounds each; a few hundred MiB read, under two seconds per pass. Done once per process. false: not measurable.
struct TierProbeResult { bool done = false, ok = false; double direct_bps = 0, cached_bps = 0; };
bool file_tier_probe(const std::vector<std::string>& paths, double& direct_bps, double& cached_bps) {
static std::mutex mu;
static TierProbeResult memo;
std::lock_guard<std::mutex> lk(mu);
if (memo.done) { direct_bps = memo.direct_bps; cached_bps = memo.cached_bps; return memo.ok; }
memo.done = true;
const std::string* best = nullptr;
uint64_t size = 0;
for (const std::string& p : paths) {
struct stat st{};
if (::stat(p.c_str(), &st) == 0 && (uint64_t) st.st_size > size) { size = (uint64_t) st.st_size; best = &p; }
}
constexpr uint64_t kRegion = 1ull << 20;
constexpr int kPerPass = 96, kRounds = 2;
constexpr int kDirectThreads = 8, kCachedThreads = 3;
if (best == nullptr || size < 8ull * kPerPass * kRegion * 2) return false;
const int fd_d = ::open(best->c_str(), O_RDONLY | O_DIRECT | O_CLOEXEC);
const int fd_b = ::open(best->c_str(), O_RDONLY | O_CLOEXEC);
void* map = fd_b >= 0 ? mmap(nullptr, (size_t) size, PROT_READ, MAP_SHARED, fd_b, 0) : MAP_FAILED;
auto cleanup = [&] {
if (map != MAP_FAILED) munmap(map, (size_t) size);
if (fd_d >= 0) ::close(fd_d);
if (fd_b >= 0) ::close(fd_b);
};
if (fd_d < 0 || map == MAP_FAILED) { cleanup(); return false; }
const uint8_t* base = static_cast<const uint8_t*>(map);
uint64_t seed = (uint64_t) std::chrono::steady_clock::now().time_since_epoch().count() * 6364136223846793005ull + 1442695040888963407ull;
std::vector<uint64_t> used;
auto pick = [&](std::vector<uint64_t>& out) { // kPerPass distinct 1 MiB pieces the page cache does not hold
out.clear();
std::vector<unsigned char> vec(kRegion / 4096);
for (int tries = 0; (int) out.size() < kPerPass && tries < kPerPass * 40; ++tries) {
seed = seed * 6364136223846793005ull + 1442695040888963407ull;
const uint64_t off = ((seed >> 20) % (size / kRegion)) * kRegion;
if (std::find(used.begin(), used.end(), off) != used.end()) continue;
if (mincore((void*) (base + off), (size_t) kRegion, vec.data()) != 0) continue;
int res = 0;
for (unsigned char c : vec) res += c & 1;
if (res * 4 > (int) vec.size()) continue;
used.push_back(off);
out.push_back(off);
}
return (int) out.size() >= kPerPass / 2;
};
auto preadn = [&](uint8_t* dst, uint64_t off) {
uint64_t done = 0;
while (done < kRegion) {
const ssize_t r = ::pread(fd_d, dst + done, (size_t) (kRegion - done), (off_t) (off + done));
if (r < 0) { if (errno == EINTR) continue; return false; }
if (r == 0) return false;
done += (uint64_t) r;
}
return true;
};
double best_d = 0, best_c = 0;
bool ok = true;
for (int round = 0; round < kRounds && ok; ++round) {
for (int mode = 0; mode < 2 && ok; ++mode) { // 0: direct, 1: cached
std::vector<uint64_t> offs;
if (!pick(offs)) { ok = false; break; }
std::atomic<size_t> next{0};
std::atomic<uint64_t> bytes{0};
std::atomic<int> failed{0};
const auto t0 = std::chrono::steady_clock::now();
const auto deadline = t0 + std::chrono::milliseconds(1500);
std::vector<std::thread> th;
const int nthreads = mode == 0 ? kDirectThreads : kCachedThreads;
for (int t = 0; t < nthreads; ++t) {
th.emplace_back([&] {
void* buf = nullptr;
if (mode == 0 && posix_memalign(&buf, 4096, kRegion) != 0) { failed = 1; return; }
volatile uint8_t sink = 0;
for (;;) {
const size_t i = next.fetch_add(1);
if (i >= offs.size() || std::chrono::steady_clock::now() > deadline) break;
if (mode == 0) {
if (!preadn((uint8_t*) buf, offs[i])) { failed = 1; break; }
} else {
for (uint64_t pg = 0; pg < kRegion; pg += 4096) sink = (uint8_t) (sink + base[offs[i] + pg]);
}
bytes.fetch_add(kRegion);
}
std::free(buf);
});
}
for (std::thread& x : th) x.join();
const double secs = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
if (failed.load() != 0 || bytes.load() == 0 || secs <= 0) { ok = false; break; }
const double bps = (double) bytes.load() / secs;
(mode == 0 ? best_d : best_c) = std::max(mode == 0 ? best_d : best_c, bps);
for (uint64_t off : offs) { // leave the page cache as it was
(void) madvise((void*) (base + off), (size_t) kRegion, MADV_DONTNEED);
(void) posix_fadvise(fd_b, (off_t) off, (off_t) kRegion, POSIX_FADV_DONTNEED);
}
}
}
cleanup();
memo.ok = ok && best_d > 0 && best_c > 0;
memo.direct_bps = best_d;
memo.cached_bps = best_c;
direct_bps = best_d;
cached_bps = best_c;
return memo.ok;
}
#endif
/// #286/#577: whether the file tier reads its `read_bytes` unbuffered, beside `arena_bytes` of RAM copy still to be
/// taken. Windows times probe reads too (experts_unbuffered); on Linux the same rule as its `cache_counts = false`
/// arm decides: whether the file cache could keep those bytes at all, from MemAvailable and the tightest cgroup
/// limit (host_available_memory). STRATA_UNBUFFERED_LOAD=1 / 0 forces it either way, as on Windows.
bool file_tier_unbuffered(const std::vector<std::string>& paths, uint64_t arena_bytes, uint64_t read_bytes,
std::string& why) {
#if defined(_WIN32)
return experts_unbuffered(paths, arena_bytes, why, /*cache_counts=*/false, read_bytes);
#elif defined(__linux__)
(void) paths;
if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0') {
why = std::string("STRATA_UNBUFFERED_LOAD=") + env;
return env[0] != '0';
}
uint64_t avail = 0;
if (!available_memory_bytes(avail)) {
why = "the available RAM is unknown";
return false;
}
// The room the file cache can really have (on by default; STRATA_FILE_TIER_HONEST=0 turns it off; an I/O-path change only). available_memory_bytes credits the group's whole `file`
// counter as reclaimable (cgroup_available_bytes), and on a RAM-budget config that credit includes pages the engine itself holds
// (P2003, v31, 22 GiB RAM copy: the room read 18.7 GiB while the group had limit 36 GiB, current 24.8 GiB, i.e. 11 GiB left). The re-check
// after the copy then saw held >= 0.5, skipped the drive probe and switched the file tier to the cache: 2-3x slower prompts. The
// conversation cache's sampler (only the clean inactive file cache is credited) is the honest figure; the smaller of the two decides.
// The operator cap (--memory-limit-mib) is NOT applied: it bounds the engine's own allocations, not the page cache (counting it sent IQ3_S
// unbuffered and cut its decode 2-3x).
if (const char* ho = std::getenv("STRATA_FILE_TIER_HONEST"); ho == nullptr || ho[0] != '0') {
if (const auto honest = strata::core::sample_host_memory(strata::core::MemoryProbePaths{}, 0); honest && honest->available < avail) avail = honest->available;
}
// #1194: the experts read from the files are a skewed set: a cache holding a twentieth of them (at least 1.5 GiB)
// serves most of the repeats, and beat the unbuffered reads at every room measured (it reads 2 to 7 times less from
// the drive). `avail` already has what this process and the cgroup hold taken off, so 1 GiB is left for the rest.
// #1752 (KevinX8): ROCm queues are suspended while the kernel reclaims around the process's HMM-tracked arena
// (#1691) on an MI50 (gfx906): the cached reads churn the page cache and reclaim unmaps the arena, so the gfx906
// backend keeps the old room >= read_bytes rule. Other HIP cards (gfx1201 measured: not affected) keep the new
// rule; STRATA_FILE_CACHE_OLD_RULE=1 / 0 forces the old rule on / off on any Linux build.
bool old_rule = false;
#if defined(STRATA_HIP_GFX906)
old_rule = true;
#endif
if (const char* r = std::getenv("STRATA_FILE_CACHE_OLD_RULE"); r != nullptr && r[0] != '\0') old_rule = r[0] != '0';
const bool keepable = old_rule
? strata::platform::file_cache_keeps(avail, arena_bytes, read_bytes)
: strata::platform::file_cache_keeps(avail, arena_bytes, read_bytes, 1ull << 30, 0.05, 3ull << 29);
char msg[256];
std::snprintf(msg, sizeof msg, "%.1f GiB available, %.1f GiB of it still to be taken by the RAM copy, %.1f GiB "
"of experts read from the files: the file cache %s keep the ones that come back",
(double) avail / (1ull << 30), (double) arena_bytes / (1ull << 30), (double) read_bytes / (1ull << 30),
keepable ? "can" : "cannot");
why = msg;
// #3237: the room rule says the cache can keep the experts that come back, but when it holds under half of the read
// set, whether it pays depends on the drive: on a PCIe 5 NVMe (8 GB/s direct) the cached path read prompts at half
// the speed and decoded 3-4x slower than unbuffered reads, on a 1.7-2.5 GB/s NVMe the cache decodes faster. So time
// both paths once at start and read unbuffered only when the drive is fast and serves direct reads clearly faster
// (platform::file_tier_prefers_direct). STRATA_FILE_TIER_PROBE=0 keeps the room rule alone.
if (keepable && !old_rule && read_bytes > 0) {
const char* pe = std::getenv("STRATA_FILE_TIER_PROBE");
const uint64_t margin = 1ull << 30;
const double room = avail > arena_bytes + margin ? (double) (avail - arena_bytes - margin) : 0.0;
const double held = room / (double) read_bytes;
if (!(pe != nullptr && pe[0] == '0') && held < 0.5) {
double d = 0, c = 0;
char pm[256];
if (file_tier_probe(paths, d, c)) {
const bool direct = strata::platform::file_tier_prefers_direct(held, d, c);
std::snprintf(pm, sizeof pm, "; the cache holds %.0f%% of the read set, direct reads %.2f GB/s, cached-path reads "
"%.2f GB/s (%.2fx): %s", held * 100.0, d / 1e9, c / 1e9, d / c,
direct ? "the file tier reads unbuffered" : "the file cache stays");
why += pm;
return direct;
}
why += "; the drive probe could not run, the file cache stays";
}
}
return !keepable;
#else
(void) paths; (void) arena_bytes; (void) read_bytes;
why = "through the file cache (no unbuffered reads on this platform)";
return false;
#endif
}
} // namespace
// ================================ THE FILE-BACKED SOURCE ================================
FileExpertSource::~FileExpertSource() { close(); }
#if defined(__linux__)
namespace {
/// Bytes of [p, p + n) whose pages are in the page cache (mincore, page-granular); 0 when the call fails.