-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathggml-backend.cpp
More file actions
3581 lines (3112 loc) · 146 KB
/
Copy pathggml-backend.cpp
File metadata and controls
3581 lines (3112 loc) · 146 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
// Note: porting this file to C++ is a work in progress
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#ifndef NOMINMAX
# define NOMINMAX
#endif
#include <windows.h>
#endif
#include "ggml-backend.h"
#include "ggml-backend-impl.h"
#include "ggml-alloc.h"
#include "ggml-impl.h"
#include <assert.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <fstream>
#include <future>
#include <mutex>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>
#ifdef __APPLE__
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#ifdef _WIN32
namespace {
struct optane_moe_entry {
uint64_t q_base = 0;
size_t expert_bytes = 0;
int q_parity = 0;
int expert_count = 0;
};
struct optane_moe_location {
int pack_slot = -1;
uint64_t offset = 0;
size_t bytes = 0;
};
struct optane_moe_tensor_locations {
std::vector<optane_moe_location> experts;
};
struct optane_moe_pack {
int id = -1;
std::string label;
std::string path;
HANDLE file = INVALID_HANDLE_VALUE;
HANDLE mapping = nullptr;
const uint8_t * data = nullptr;
uint64_t bytes = 0;
};
class optane_moe_sources {
public:
optane_moe_sources() {
const char * index_path = getenv("OPTANE_MOE_INDEX");
if (!index_path || !index_path[0]) return;
std::ifstream index(index_path);
if (!index) {
fprintf(stderr, "optane_moe: cannot open runtime index: %s\n", index_path);
return;
}
std::vector<std::string> lines;
std::string line;
while (std::getline(index, line)) {
if (!line.empty()) lines.push_back(line);
}
const bool v2 = std::find(lines.begin(), lines.end(), "# optane-moe-index-v2") != lines.end();
try {
if (v2) {
parse_v2(lines);
} else {
parse_v1(lines);
}
} catch (const std::exception & error) {
fprintf(stderr, "optane_moe: invalid runtime index %s: %s\n", index_path, error.what());
clear();
return;
}
if (packs.empty() || (v2 ? locations.empty() : legacy_entries.empty())) {
fprintf(stderr, "optane_moe: runtime index is empty: %s\n", index_path);
clear();
return;
}
if (!open_packs()) {
clear();
return;
}
trace = getenv("OPTANE_MOE_TRACE") != nullptr;
uint64_t total_bytes = 0;
for (const auto & pack : packs) total_bytes += pack.bytes;
fprintf(stderr, "optane_moe: enabled index-v%d with %zu tensors, %zu packs, %.3f GiB mapped\n",
v2 ? 2 : 1, v2 ? locations.size() : legacy_entries.size(), packs.size(),
total_bytes / 1073741824.0);
}
~optane_moe_sources() {
clear();
}
const uint8_t * resolve(const char * tensor_name, int expert_id, size_t expert_bytes,
const uint8_t * original_source, bool & from_pack, bool emit_trace = true,
int * source_group = nullptr) const {
from_pack = false;
if (source_group) *source_group = -1;
optane_moe_location location;
if (!lookup(tensor_name, expert_id, expert_bytes, location)) return original_source;
const optane_moe_pack & pack = packs[location.pack_slot];
from_pack = true;
if (source_group) *source_group = location.pack_slot;
if (trace && emit_trace) {
trace_pack(pack, tensor_name, expert_id, expert_bytes, location.offset);
}
return pack.data + location.offset;
}
void trace_prefetched_pack(const char * tensor_name, int expert_id, size_t expert_bytes) const {
if (!trace) return;
optane_moe_location location;
if (!lookup(tensor_name, expert_id, expert_bytes, location)) return;
trace_pack(packs[location.pack_slot], tensor_name, expert_id, expert_bytes, location.offset);
}
private:
static std::vector<std::string> split_tabs(const std::string & line) {
std::vector<std::string> fields;
std::istringstream input(line);
std::string field;
while (std::getline(input, field, '\t')) fields.push_back(field);
return fields;
}
static std::wstring utf8_to_wide(const std::string & value) {
if (value.empty()) return {};
const int count = MultiByteToWideChar(
CP_UTF8, MB_ERR_INVALID_CHARS, value.data(), static_cast<int>(value.size()), nullptr, 0);
if (count <= 0) throw std::runtime_error("pack path is not valid UTF-8");
std::wstring result(static_cast<size_t>(count), L'\0');
if (MultiByteToWideChar(
CP_UTF8, MB_ERR_INVALID_CHARS, value.data(), static_cast<int>(value.size()),
&result[0], count) != count) {
throw std::runtime_error("failed to convert UTF-8 pack path");
}
return result;
}
void parse_v1(const std::vector<std::string> & lines) {
const char * pack_path = getenv("OPTANE_MOE_Q_PACK");
if (!pack_path || !pack_path[0]) {
throw std::runtime_error("v1 index requires OPTANE_MOE_Q_PACK");
}
optane_moe_pack pack;
pack.id = 0;
pack.label = "legacy-Q";
pack.path = pack_path;
packs.push_back(std::move(pack));
for (const std::string & row : lines) {
if (row.empty() || row[0] == '#') continue;
std::istringstream fields(row);
std::string name;
optane_moe_entry entry;
if (std::getline(fields, name, '\t') &&
fields >> entry.q_base >> entry.expert_bytes >> entry.q_parity >> entry.expert_count) {
legacy_entries.emplace(std::move(name), entry);
}
}
}
void parse_v2(const std::vector<std::string> & lines) {
std::unordered_map<int, int> pack_slots;
for (const std::string & row : lines) {
if (row.empty() || row[0] == '#') continue;
const std::vector<std::string> fields = split_tabs(row);
if (fields.empty()) continue;
if (fields[0] == "@pack") {
if (fields.size() != 4) throw std::runtime_error("@pack requires id, label, and path");
optane_moe_pack pack;
pack.id = std::stoi(fields[1]);
pack.label = fields[2];
pack.path = fields[3];
if (pack_slots.count(pack.id)) throw std::runtime_error("duplicate pack id");
pack_slots.emplace(pack.id, static_cast<int>(packs.size()));
packs.push_back(std::move(pack));
continue;
}
if (fields.size() != 5) throw std::runtime_error("expert row requires five fields");
const std::string & name = fields[0];
const int expert_id = std::stoi(fields[1]);
const int pack_id = std::stoi(fields[2]);
const uint64_t offset = std::stoull(fields[3]);
const size_t bytes = static_cast<size_t>(std::stoull(fields[4]));
auto slot = pack_slots.find(pack_id);
if (expert_id < 0 || slot == pack_slots.end() || bytes == 0) {
throw std::runtime_error("invalid expert id, pack id, or byte length");
}
auto & tensor = locations[name];
if (tensor.experts.size() <= static_cast<size_t>(expert_id)) {
tensor.experts.resize(static_cast<size_t>(expert_id) + 1);
}
if (tensor.experts[expert_id].pack_slot >= 0) throw std::runtime_error("duplicate expert row");
tensor.experts[expert_id] = {slot->second, offset, bytes};
}
}
bool open_packs() {
for (auto & pack : packs) {
const std::wstring wide_path = utf8_to_wide(pack.path);
pack.file = CreateFileW(wide_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS, nullptr);
if (pack.file == INVALID_HANDLE_VALUE) {
fprintf(stderr, "optane_moe: cannot open pack %s: %s (winerr=%lu)\n",
pack.label.c_str(), pack.path.c_str(), GetLastError());
return false;
}
LARGE_INTEGER size{};
if (!GetFileSizeEx(pack.file, &size) || size.QuadPart <= 0) return false;
pack.bytes = static_cast<uint64_t>(size.QuadPart);
pack.mapping = CreateFileMappingA(pack.file, nullptr, PAGE_READONLY, 0, 0, nullptr);
if (!pack.mapping) return false;
pack.data = static_cast<const uint8_t *>(MapViewOfFile(pack.mapping, FILE_MAP_READ, 0, 0, 0));
if (!pack.data) return false;
}
for (const auto & tensor : locations) {
for (const auto & location : tensor.second.experts) {
if (location.pack_slot < 0) continue;
const auto & pack = packs[location.pack_slot];
if (location.offset + location.bytes > pack.bytes) {
fprintf(stderr, "optane_moe: entry exceeds pack %s\n", pack.label.c_str());
return false;
}
}
}
return true;
}
bool lookup(const char * tensor_name, int expert_id, size_t expert_bytes,
optane_moe_location & result) const {
if (expert_id < 0) return false;
auto found = locations.find(tensor_name);
if (found != locations.end() && static_cast<size_t>(expert_id) < found->second.experts.size()) {
const auto & location = found->second.experts[expert_id];
if (location.pack_slot >= 0 && location.bytes == expert_bytes) {
result = location;
return true;
}
}
auto legacy = legacy_entries.find(tensor_name);
if (legacy == legacy_entries.end()) return false;
const optane_moe_entry & entry = legacy->second;
if (entry.expert_bytes != expert_bytes || expert_id >= entry.expert_count ||
(expert_id & 1) != entry.q_parity) return false;
result.pack_slot = 0;
result.offset = entry.q_base + static_cast<uint64_t>(expert_id / 2) * entry.expert_bytes;
result.bytes = expert_bytes;
if (result.offset + expert_bytes > packs[0].bytes) return false;
return true;
}
void clear() {
for (auto & pack : packs) {
if (pack.data) UnmapViewOfFile(pack.data);
if (pack.mapping) CloseHandle(pack.mapping);
if (pack.file != INVALID_HANDLE_VALUE) CloseHandle(pack.file);
pack.data = nullptr;
pack.mapping = nullptr;
pack.file = INVALID_HANDLE_VALUE;
}
packs.clear();
locations.clear();
legacy_entries.clear();
}
void trace_pack(const optane_moe_pack & pack, const char * tensor_name,
int expert_id, size_t expert_bytes, uint64_t offset) const {
if (trace) {
const int n = trace_lines.fetch_add(1, std::memory_order_relaxed);
if (n < 96) {
fprintf(stderr, "optane_moe: pack=%s tensor=%s expert=%d offset=%llu bytes=%zu\n",
pack.label.c_str(), tensor_name, expert_id,
static_cast<unsigned long long>(offset), expert_bytes);
}
}
}
bool trace = false;
std::vector<optane_moe_pack> packs;
std::unordered_map<std::string, optane_moe_tensor_locations> locations;
std::unordered_map<std::string, optane_moe_entry> legacy_entries;
mutable std::atomic<int> trace_lines{0};
};
static const optane_moe_sources & get_optane_moe_sources() {
static const optane_moe_sources sources;
return sources;
}
static int optane_moe_layer(const char * name) {
int layer = -1;
return name && sscanf(name, "blk.%d.ffn_", &layer) == 1 ? layer : -1;
}
struct optane_prefetch_tensor {
std::string name;
const uint8_t * p_base = nullptr;
uint8_t * d_base = nullptr;
size_t expert_size = 0;
int n_expert = 0;
int n_gpu_slots = 0;
};
struct optane_prefetch_item {
std::string tensor_name;
int expert_id = -1;
int gpu_slot_id = -1;
int source_group = -1;
size_t host_offset = 0;
size_t expert_size = 0;
size_t copy_size = 0;
uint8_t * d_target = nullptr;
bool from_q = false;
};
class optane_cuda_runtime {
public:
using stream_t = void *;
using set_device_fn = int (__cdecl *)(int);
using stream_create_fn = int (__cdecl *)(stream_t *, unsigned int);
using memcpy_async_fn = int (__cdecl *)(void *, const void *, size_t, int, stream_t);
using memset_async_fn = int (__cdecl *)(void *, int, size_t, stream_t);
using host_register_fn = int (__cdecl *)(void *, size_t, unsigned int);
using stream_sync_fn = int (__cdecl *)(stream_t);
bool load() {
if (attempted) return module != nullptr;
attempted = true;
module = LoadLibraryA("cudart64_12.dll");
if (!module) return false;
set_device = reinterpret_cast<set_device_fn>(GetProcAddress(module, "cudaSetDevice"));
stream_create = reinterpret_cast<stream_create_fn>(GetProcAddress(module, "cudaStreamCreateWithFlags"));
memcpy_async = reinterpret_cast<memcpy_async_fn>(GetProcAddress(module, "cudaMemcpyAsync"));
memset_async = reinterpret_cast<memset_async_fn>(GetProcAddress(module, "cudaMemsetAsync"));
host_register = reinterpret_cast<host_register_fn>(GetProcAddress(module, "cudaHostRegister"));
stream_sync = reinterpret_cast<stream_sync_fn>(GetProcAddress(module, "cudaStreamSynchronize"));
return set_device && stream_create && memcpy_async && memset_async && host_register && stream_sync;
}
bool make_stream(stream_t & stream) {
return load() && set_device(device_ordinal()) == 0 && stream_create(&stream, 1) == 0;
}
bool copy_async(void * dst, const void * src, size_t bytes, int kind, stream_t stream) {
return set_device(device_ordinal()) == 0 && memcpy_async(dst, src, bytes, kind, stream) == 0;
}
bool synchronize(stream_t stream) {
return set_device(device_ordinal()) == 0 && stream_sync(stream) == 0;
}
bool zero_async(void * dst, size_t bytes, stream_t stream) {
return set_device(device_ordinal()) == 0 && memset_async(dst, 0, bytes, stream) == 0;
}
bool register_span(const void * address, size_t bytes) {
if (!load() || !address || bytes == 0 || set_device(device_ordinal()) != 0) return false;
const uintptr_t first = reinterpret_cast<uintptr_t>(address);
const uintptr_t last = first + bytes;
uintptr_t current = first;
while (current < last) {
MEMORY_BASIC_INFORMATION mbi{};
if (!VirtualQuery(reinterpret_cast<const void *>(current), &mbi, sizeof(mbi))) return false;
const uintptr_t region_begin = reinterpret_cast<uintptr_t>(mbi.BaseAddress);
const uintptr_t region_end = region_begin + mbi.RegionSize;
const size_t chunk = 2ull * 1024 * 1024;
const uintptr_t chunk_begin = region_begin + ((current - region_begin) / chunk) * chunk;
const uintptr_t chunk_end = std::min<uintptr_t>(chunk_begin + chunk, region_end);
{
std::lock_guard<std::mutex> lock(registration_mutex);
if (registrations.find(chunk_begin) == registrations.end()) {
if (registrations.size() >= 4096) return false;
const int rc = host_register(reinterpret_cast<void *>(chunk_begin),
chunk_end - chunk_begin, 0);
// 712 is cudaErrorHostMemoryAlreadyRegistered.
if (rc != 0 && rc != 712) return false;
registrations.emplace(chunk_begin, chunk_end - chunk_begin);
}
}
current = chunk_end;
}
return true;
}
private:
int device_ordinal() const {
const char * value = getenv("OPTANE_MOE_CUDA_DEVICE");
return value ? atoi(value) : 0;
}
bool attempted = false;
HMODULE module = nullptr;
set_device_fn set_device = nullptr;
stream_create_fn stream_create = nullptr;
memcpy_async_fn memcpy_async = nullptr;
memset_async_fn memset_async = nullptr;
host_register_fn host_register = nullptr;
stream_sync_fn stream_sync = nullptr;
std::mutex registration_mutex;
std::unordered_map<uintptr_t, size_t> registrations;
};
class optane_moe_pipeline {
public:
bool enabled() const {
const char * value = getenv("OPTANE_MOE_PIPELINE");
return value && value[0] && strcmp(value, "0") != 0 && !disabled;
}
void remember_route(int layer, const std::vector<int32_t> & route) {
if (!enabled() || layer < 0 || route.empty()) return;
std::vector<int32_t> merged;
const char * value = getenv("OPTANE_MOE_PREDICT_EXPERTS");
const size_t limit = value ? std::max(8, atoi(value)) : 12;
merged.reserve(limit);
auto append_unique = [&](const std::vector<int32_t> & ids) {
for (int32_t id : ids) {
if (merged.size() >= limit) break;
if (std::find(merged.begin(), merged.end(), id) == merged.end()) merged.push_back(id);
}
};
append_unique(route);
auto previous = history.find(layer);
if (previous != history.end()) append_unique(previous->second);
history[layer] = std::move(merged);
}
bool launch(int layer, int copy_id, ggml_backend_t backend,
const std::vector<optane_prefetch_tensor> & tensors) {
if (!enabled() || layer < 0 || tensors.empty()) return false;
auto found = history.find(layer);
if (found == history.end() || found->second.empty()) return false;
if (!ensure_buffers(backend)) return false;
slot & s = slots[layer & 1];
finish_job(s);
if (s.stream) cuda.synchronize(s.stream);
s.layer = layer;
s.copy_id = copy_id;
s.items.clear();
s.ready = false;
const std::vector<int32_t> predicted = found->second;
const uint64_t launched_ns = now_ns();
s.job = std::async(std::launch::async,
[this, &s, layer, copy_id, backend, tensors, predicted, launched_ns]() {
if (!cuda.load() || !s.stream) return;
if (s.compute_done) ggml_backend_event_synchronize(s.compute_done);
std::vector<copy_task> tasks;
size_t cursor = 0;
for (const auto & tensor : tensors) {
for (int32_t expert_id : predicted) {
if (expert_id < 0 || expert_id >= tensor.n_expert) continue;
const size_t expert_offset = static_cast<size_t>(expert_id) * tensor.expert_size;
const size_t padding = expert_id < tensor.n_expert - 1 ?
std::min<size_t>(tensor.expert_size, 512) : 0;
const uint8_t * p_source = tensor.p_base + expert_offset;
bool from_q = false;
const uint8_t * source = get_optane_moe_sources().resolve(
tensor.name.c_str(), expert_id, tensor.expert_size, p_source, from_q, false);
const size_t copy_size = tensor.expert_size + padding;
cursor = (cursor + 255) & ~size_t(255);
if (cursor + copy_size > slot_bytes) continue;
optane_prefetch_item item;
item.tensor_name = tensor.name;
item.expert_id = expert_id;
item.host_offset = cursor;
item.expert_size = tensor.expert_size;
item.copy_size = copy_size;
item.d_target = tensor.d_base + expert_offset;
item.from_q = from_q;
tasks.push_back({item, source, padding});
cursor += copy_size;
}
}
for (auto & task : tasks) {
const size_t direct_bytes = task.item.from_q ? task.item.expert_size : task.item.copy_size;
task.direct = cuda.register_span(task.source, direct_bytes);
}
auto copy_group = [&s, &tasks](bool q_group) {
for (auto & task : tasks) {
if (task.direct || task.item.from_q != q_group) continue;
uint8_t * dst = s.host_base + task.item.host_offset;
memcpy(dst, task.source, task.item.expert_size);
if (task.padding) {
if (task.item.from_q) memset(dst + task.item.expert_size, 0, task.padding);
else memcpy(dst + task.item.expert_size,
task.source + task.item.expert_size, task.padding);
}
}
};
std::thread p_reader(copy_group, false);
std::thread q_reader(copy_group, true);
p_reader.join();
q_reader.join();
bool ok = true;
for (const auto & task : tasks) {
if (task.direct) {
const size_t direct_bytes = task.item.from_q ? task.item.expert_size : task.item.copy_size;
ok = cuda.copy_async(task.item.d_target, task.source,
direct_bytes, 1, s.stream) && ok;
if (task.item.from_q && task.padding) {
ok = cuda.zero_async(task.item.d_target + task.item.expert_size,
task.padding, s.stream) && ok;
}
direct_dax_bytes.fetch_add(direct_bytes, std::memory_order_relaxed);
} else {
ok = cuda.copy_async(task.item.d_target,
s.host_base + task.item.host_offset, task.item.copy_size, 1, s.stream) && ok;
staged_bytes.fetch_add(task.item.copy_size, std::memory_order_relaxed);
}
}
s.items.reserve(tasks.size());
for (const auto & task : tasks) s.items.push_back(task.item);
s.ready = ok;
s.launched_ns = launched_ns;
s.enqueued_ns = now_ns();
prefetch_jobs.fetch_add(1, std::memory_order_relaxed);
prefetch_bytes.fetch_add(cursor, std::memory_order_relaxed);
});
return true;
}
void wait_for_layer(int layer, int copy_id) {
if (!enabled()) return;
slot & s = slots[layer & 1];
if (s.compute_done) ggml_backend_event_synchronize(s.compute_done);
if (s.layer != layer || s.copy_id != copy_id) return;
const uint64_t begin = now_ns();
finish_job(s);
if (s.ready && s.stream) {
cuda.synchronize(s.stream);
const uint64_t end = now_ns();
const uint64_t wait = end - begin;
const uint64_t total = end > s.launched_ns ? end - s.launched_ns : 0;
wait_ns.fetch_add(wait, std::memory_order_relaxed);
overlap_ns.fetch_add(total > wait ? total - wait : 0, std::memory_order_relaxed);
}
}
bool is_hit(int layer, int copy_id, const char * tensor_name, int expert_id,
size_t expert_size, uint8_t * d_target, bool & from_q) {
from_q = false;
if (!enabled()) return false;
slot & s = slots[layer & 1];
if (!s.ready || s.layer != layer || s.copy_id != copy_id) {
misses.fetch_add(1, std::memory_order_relaxed);
return false;
}
for (const auto & item : s.items) {
if (item.expert_id == expert_id && item.expert_size == expert_size &&
item.d_target == d_target && item.tensor_name == tensor_name) {
from_q = item.from_q;
hits.fetch_add(1, std::memory_order_relaxed);
hit_bytes.fetch_add(item.copy_size, std::memory_order_relaxed);
if (from_q) get_optane_moe_sources().trace_prefetched_pack(tensor_name, expert_id, expert_size);
return true;
}
}
misses.fetch_add(1, std::memory_order_relaxed);
return false;
}
void mark_compute_done(int layer, ggml_backend_t backend) {
if (!enabled()) return;
slot & s = slots[layer & 1];
if (s.compute_done) ggml_backend_event_record(s.compute_done, backend);
}
void report() const {
if (!enabled()) return;
fprintf(stderr,
"optane_moe_pipeline: jobs=%llu prefetched=%.3f MiB direct_dax=%.3f MiB staged=%.3f MiB hits=%llu misses=%llu hit_bytes=%.3f MiB h2d_wait=%.3f ms overlapped=%.3f ms\n",
static_cast<unsigned long long>(prefetch_jobs.load()), prefetch_bytes.load() / 1048576.0,
direct_dax_bytes.load() / 1048576.0, staged_bytes.load() / 1048576.0,
static_cast<unsigned long long>(hits.load()), static_cast<unsigned long long>(misses.load()),
hit_bytes.load() / 1048576.0, wait_ns.load() / 1.0e6, overlap_ns.load() / 1.0e6);
}
private:
static constexpr size_t slot_bytes = 128ull * 1024 * 1024;
struct copy_task {
optane_prefetch_item item;
const uint8_t * source = nullptr;
size_t padding = 0;
bool direct = false;
};
struct slot {
ggml_backend_buffer_t host_buffer = nullptr;
uint8_t * host_base = nullptr;
optane_cuda_runtime::stream_t stream = nullptr;
ggml_backend_event_t compute_done = nullptr;
std::future<void> job;
std::vector<optane_prefetch_item> items;
int layer = -1;
int copy_id = -1;
bool ready = false;
uint64_t launched_ns = 0;
uint64_t enqueued_ns = 0;
};
static uint64_t now_ns() {
return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count());
}
void finish_job(slot & s) {
if (s.job.valid()) s.job.get();
}
bool ensure_buffers(ggml_backend_t backend) {
if (initialized) return !disabled;
initialized = true;
if (!cuda.load()) {
fprintf(stderr, "optane_moe_pipeline: cudart64_12.dll API unavailable; pipeline disabled\n");
disabled = true;
return false;
}
ggml_backend_buffer_type_t host_buft = ggml_backend_dev_host_buffer_type(ggml_backend_get_device(backend));
if (!host_buft) {
fprintf(stderr, "optane_moe_pipeline: CUDA pinned host buffer unavailable; pipeline disabled\n");
disabled = true;
return false;
}
for (slot & s : slots) {
s.host_buffer = ggml_backend_buft_alloc_buffer(host_buft, slot_bytes);
s.host_base = s.host_buffer ? static_cast<uint8_t *>(ggml_backend_buffer_get_base(s.host_buffer)) : nullptr;
s.compute_done = ggml_backend_event_new(ggml_backend_get_device(backend));
if (!s.host_base || !s.compute_done || !cuda.make_stream(s.stream)) {
fprintf(stderr, "optane_moe_pipeline: double-buffer allocation failed; pipeline disabled\n");
disabled = true;
return false;
}
}
fprintf(stderr, "optane_moe_pipeline: enabled, 2 x 128 MiB pinned host buffers, two scheduler GPU slots, dual P/Q readers, two copy streams\n");
return true;
}
bool initialized = false;
bool disabled = false;
optane_cuda_runtime cuda;
std::array<slot, 2> slots;
std::unordered_map<int, std::vector<int32_t>> history;
std::atomic<uint64_t> prefetch_jobs{0};
std::atomic<uint64_t> prefetch_bytes{0};
std::atomic<uint64_t> direct_dax_bytes{0};
std::atomic<uint64_t> staged_bytes{0};
std::atomic<uint64_t> hits{0};
std::atomic<uint64_t> misses{0};
std::atomic<uint64_t> hit_bytes{0};
std::atomic<uint64_t> wait_ns{0};
std::atomic<uint64_t> overlap_ns{0};
};
class optane_moe_pipeline_lookahead {
public:
bool enabled() const {
const char * value = getenv("OPTANE_MOE_PIPELINE");
return value && value[0] && strcmp(value, "0") != 0 && !disabled;
}
void remember_route(int layer, const std::vector<int32_t> & route) {
if (!enabled() || layer < 0 || route.empty()) return;
history[layer] = route;
}
bool prefetch_host(int layer, ggml_backend_t backend,
const std::vector<optane_prefetch_tensor> & tensors) {
if (!enabled() || layer < 0 || tensors.empty()) return false;
auto found = history.find(layer);
if (found == history.end() || found->second.empty()) return false;
if (!ensure_buffers(backend)) return false;
host_slot & hs = host_slots[layer & 7];
finish_host_job(hs);
gpu_slot & gs = gpu_slots[layer & 1];
if (gs.stream) cuda.synchronize(gs.stream);
hs.layer = layer;
hs.ready = false;
hs.items.clear();
hs.launched_ns = now_ns();
const std::vector<int32_t> predicted = found->second;
const size_t segment_offset = static_cast<size_t>((layer >> 1) & 3) * segment_bytes;
hs.host_base = host_bases[layer & 1] + segment_offset;
hs.job = std::async(std::launch::async, [this, &hs, tensors, predicted]() {
std::vector<host_task> tasks;
size_t cursor = 0;
for (const auto & tensor : tensors) {
int gpu_slot_id = 0;
for (int32_t expert_id : predicted) {
if (expert_id < 0 || expert_id >= tensor.n_expert) continue;
if (gpu_slot_id >= tensor.n_gpu_slots) break;
const size_t expert_offset = static_cast<size_t>(expert_id) * tensor.expert_size;
const uint8_t * p_source = tensor.p_base + expert_offset;
bool from_q = false;
int source_group = -1;
const uint8_t * source = get_optane_moe_sources().resolve(
tensor.name.c_str(), expert_id, tensor.expert_size, p_source, from_q, false,
&source_group);
const size_t copy_size = tensor.expert_size;
cursor = (cursor + 255) & ~size_t(255);
if (cursor + copy_size > segment_bytes) continue;
optane_prefetch_item item;
item.tensor_name = tensor.name;
item.expert_id = expert_id;
item.gpu_slot_id = gpu_slot_id++;
item.host_offset = cursor;
item.expert_size = tensor.expert_size;
item.copy_size = copy_size;
item.from_q = from_q;
item.source_group = source_group;
tasks.push_back({item, source, 0});
cursor += copy_size;
}
}
std::vector<int> source_groups;
for (const auto & task : tasks) {
if (std::find(source_groups.begin(), source_groups.end(), task.item.source_group) ==
source_groups.end()) {
source_groups.push_back(task.item.source_group);
}
}
auto copy_group = [&hs, &tasks](int source_group) {
for (auto & task : tasks) {
if (task.item.source_group != source_group) continue;
uint8_t * dst = hs.host_base + task.item.host_offset;
memcpy(dst, task.source, task.item.expert_size);
}
};
std::vector<std::thread> readers;
readers.reserve(source_groups.size());
for (int source_group : source_groups) {
readers.emplace_back(copy_group, source_group);
}
for (auto & reader : readers) reader.join();
hs.items.reserve(tasks.size());
for (const auto & task : tasks) hs.items.push_back(task.item);
hs.ready = true;
hs.completed_ns = now_ns();
host_jobs.fetch_add(1, std::memory_order_relaxed);
host_bytes.fetch_add(cursor, std::memory_order_relaxed);
});
return true;
}
bool launch_h2d(int layer, int copy_id, ggml_backend_t backend,
const std::vector<optane_prefetch_tensor> & tensors) {
if (!enabled() || layer < 0 || tensors.empty() || !ensure_buffers(backend)) return false;
host_slot & hs = host_slots[layer & 7];
const uint64_t host_wait_begin = now_ns();
finish_host_job(hs);
host_wait_ns.fetch_add(now_ns() - host_wait_begin, std::memory_order_relaxed);
if (!hs.ready || hs.layer != layer) return false;
gpu_slot & gs = gpu_slots[layer & 1];
if (gs.stream) cuda.synchronize(gs.stream);
if (gs.compute_done) ggml_backend_event_synchronize(gs.compute_done);
gs.layer = layer;
gs.copy_id = copy_id;
gs.items.clear();
gs.ready = false;
gs.launched_ns = now_ns();
std::unordered_map<std::string, const optane_prefetch_tensor *> destinations;
for (const auto & tensor : tensors) destinations[tensor.name] = &tensor;
bool ok = true;
for (auto item : hs.items) {
auto found = destinations.find(item.tensor_name);
if (found == destinations.end()) continue;
const optane_prefetch_tensor & tensor = *found->second;
if (item.gpu_slot_id < 0 || item.gpu_slot_id >= tensor.n_gpu_slots) continue;
item.d_target = tensor.d_base + static_cast<size_t>(item.gpu_slot_id) * item.expert_size;
ok = cuda.copy_async(item.d_target, hs.host_base + item.host_offset,
item.copy_size, 1, gs.stream) && ok;
gs.items.push_back(std::move(item));
}
gs.ready = ok;
h2d_jobs.fetch_add(1, std::memory_order_relaxed);
return ok;
}
void wait_for_layer(int layer, int copy_id) {
if (!enabled()) return;
gpu_slot & gs = gpu_slots[layer & 1];
if (gs.compute_done) ggml_backend_event_synchronize(gs.compute_done);
if (!gs.ready || gs.layer != layer || gs.copy_id != copy_id) return;
const uint64_t begin = now_ns();
cuda.synchronize(gs.stream);
const uint64_t end = now_ns();
const uint64_t wait = end - begin;
const uint64_t total = end > gs.launched_ns ? end - gs.launched_ns : 0;
h2d_wait_ns.fetch_add(wait, std::memory_order_relaxed);
overlap_ns.fetch_add(total > wait ? total - wait : 0, std::memory_order_relaxed);
}
bool is_hit(int layer, int copy_id, const char * tensor_name, int expert_id,
size_t expert_size, uint8_t * d_target, bool & from_q) {
from_q = false;
if (!enabled()) return false;
gpu_slot & gs = gpu_slots[layer & 1];
if (!gs.ready || gs.layer != layer || gs.copy_id != copy_id) {
misses.fetch_add(1, std::memory_order_relaxed);
miss_bytes.fetch_add(expert_size, std::memory_order_relaxed);
return false;
}
for (const auto & item : gs.items) {
if (item.expert_id == expert_id && item.expert_size == expert_size &&
item.d_target == d_target && item.tensor_name == tensor_name) {
from_q = item.from_q;
hits.fetch_add(1, std::memory_order_relaxed);
hit_bytes.fetch_add(item.copy_size, std::memory_order_relaxed);
if (from_q) get_optane_moe_sources().trace_prefetched_pack(tensor_name, expert_id, expert_size);
return true;
}
}
misses.fetch_add(1, std::memory_order_relaxed);
miss_bytes.fetch_add(expert_size, std::memory_order_relaxed);
return false;
}
int prefetched_slot(int layer, int copy_id, int expert_id) const {
if (!enabled()) return -1;
const gpu_slot & gs = gpu_slots[layer & 1];
if (!gs.ready || gs.layer != layer || gs.copy_id != copy_id) return -1;
for (const auto & item : gs.items) {
if (item.expert_id == expert_id && item.gpu_slot_id >= 0) {
return item.gpu_slot_id;
}
}
return -1;
}
void mark_compute_done(int layer, ggml_backend_t backend) {
if (!enabled()) return;
gpu_slot & gs = gpu_slots[layer & 1];
if (gs.compute_done) ggml_backend_event_record(gs.compute_done, backend);
}
void report() const {
if (!enabled()) return;
fprintf(stderr,
"optane_moe_pipeline: host_jobs=%llu h2d_jobs=%llu prefetched=%.3f MiB hits=%llu misses=%llu hit_bytes=%.3f MiB miss_bytes=%.3f MiB host_wait=%.3f ms h2d_wait=%.3f ms overlapped=%.3f ms\n",
static_cast<unsigned long long>(host_jobs.load()),
static_cast<unsigned long long>(h2d_jobs.load()), host_bytes.load() / 1048576.0,
static_cast<unsigned long long>(hits.load()), static_cast<unsigned long long>(misses.load()),
hit_bytes.load() / 1048576.0, miss_bytes.load() / 1048576.0,
host_wait_ns.load() / 1.0e6,
h2d_wait_ns.load() / 1.0e6, overlap_ns.load() / 1.0e6);
}
private:
// DeepSeek4 IQ3/MXFP4 expert bundles are roughly 8-10 MiB each. A 128 MiB
// segment holds the six routed experts plus six lookahead candidates.
static constexpr size_t segment_bytes = 128ull * 1024 * 1024;
static constexpr size_t buffer_bytes = 4 * segment_bytes;
struct host_task {
optane_prefetch_item item;
const uint8_t * source = nullptr;
size_t padding = 0;
};
struct host_slot {
std::future<void> job;
std::vector<optane_prefetch_item> items;
uint8_t * host_base = nullptr;
int layer = -1;
bool ready = false;
uint64_t launched_ns = 0;
uint64_t completed_ns = 0;
};
struct gpu_slot {
optane_cuda_runtime::stream_t stream = nullptr;
ggml_backend_event_t compute_done = nullptr;
std::vector<optane_prefetch_item> items;
int layer = -1;
int copy_id = -1;
bool ready = false;
uint64_t launched_ns = 0;
};
static uint64_t now_ns() {
return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count());
}
static void finish_host_job(host_slot & hs) {
if (hs.job.valid()) hs.job.get();
}
bool ensure_buffers(ggml_backend_t backend) {
if (initialized) return !disabled;
initialized = true;
if (!cuda.load()) {
fprintf(stderr, "optane_moe_pipeline: CUDA runtime unavailable; pipeline disabled\n");
disabled = true;
return false;
}
ggml_backend_buffer_type_t host_buft = ggml_backend_dev_host_buffer_type(ggml_backend_get_device(backend));
if (!host_buft) {
disabled = true;
return false;
}
for (int i = 0; i < 2; ++i) {
host_buffers[i] = ggml_backend_buft_alloc_buffer(host_buft, buffer_bytes);
host_bases[i] = host_buffers[i] ?
static_cast<uint8_t *>(ggml_backend_buffer_get_base(host_buffers[i])) : nullptr;
gpu_slots[i].compute_done = ggml_backend_event_new(ggml_backend_get_device(backend));
if (!host_bases[i] || !gpu_slots[i].compute_done || !cuda.make_stream(gpu_slots[i].stream)) {
fprintf(stderr, "optane_moe_pipeline: lookahead double-buffer allocation failed\n");
disabled = true;
return false;
}
}
fprintf(stderr,
"optane_moe_pipeline: enabled, 2 x 512 MiB pinned host ring (8 layer slots), two scheduler GPU buffers, lookahead=4, predictor=12\n");
return true;
}
bool initialized = false;
bool disabled = false;
optane_cuda_runtime cuda;
std::array<ggml_backend_buffer_t, 2> host_buffers{};
std::array<uint8_t *, 2> host_bases{};
std::array<host_slot, 8> host_slots;
std::array<gpu_slot, 2> gpu_slots;
std::unordered_map<int, std::vector<int32_t>> history;
std::atomic<uint64_t> host_jobs{0};
std::atomic<uint64_t> h2d_jobs{0};
std::atomic<uint64_t> host_bytes{0};
std::atomic<uint64_t> hits{0};
std::atomic<uint64_t> misses{0};
std::atomic<uint64_t> hit_bytes{0};
std::atomic<uint64_t> miss_bytes{0};
std::atomic<uint64_t> host_wait_ns{0};
std::atomic<uint64_t> h2d_wait_ns{0};
std::atomic<uint64_t> overlap_ns{0};
};
static optane_moe_pipeline_lookahead & get_optane_moe_pipeline() {
static optane_moe_pipeline_lookahead pipeline;
return pipeline;
}
} // namespace
#endif
// backend buffer type
const char * ggml_backend_buft_name(ggml_backend_buffer_type_t buft) {
GGML_ASSERT(buft);
return buft->iface.get_name(buft);
}
ggml_backend_buffer_t ggml_backend_buft_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
GGML_ASSERT(buft);
if (size == 0) {
// return a dummy buffer for zero-sized allocations
return ggml_backend_buffer_init(buft, {}, NULL, 0);
}
return buft->iface.alloc_buffer(buft, size);
}
size_t ggml_backend_buft_get_alignment(ggml_backend_buffer_type_t buft) {
GGML_ASSERT(buft);
return buft->iface.get_alignment(buft);