forked from zhongkaifu/TensorSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathggml_ops_core.cpp
More file actions
2406 lines (2153 loc) · 96.7 KB
/
Copy pathggml_ops_core.cpp
File metadata and controls
2406 lines (2153 loc) · 96.7 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
// Copyright (c) Zhongkai Fu. All rights reserved.
// https://github.com/zhongkaifu/TensorSharp
//
// This file is part of TensorSharp.
//
// TensorSharp is licensed under the BSD-3-Clause license found in the LICENSE file in the root directory of this source tree.
//
// TensorSharp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the BSD-3-Clause License for more details.
#include "ggml_ops_internal.h"
#if defined(__APPLE__) || defined(__linux__)
#include <sys/mman.h>
#include <unistd.h>
#endif
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#endif
#if defined(GGML_USE_CUDA)
#include "ggml-cuda.h"
#endif
#if defined(GGML_USE_VULKAN)
#include "ggml-vulkan.h"
#endif
#include <cstdio>
#include <thread>
// ============================================================================
// ggml_pool implementation
// ============================================================================
namespace ggml_pool
{
static std::mutex g_pool_mutex;
static std::vector<PoolEntry> g_pool;
static void* pool_alloc(std::size_t size)
{
if (size == 0 || size > k_pool_buffer_size)
return nullptr;
void* ptr = std::malloc(size);
return ptr;
}
static void pool_free(void* ptr)
{
if (ptr != nullptr)
std::free(ptr);
}
PoolEntry acquire(std::size_t required_size)
{
if (required_size == 0 || required_size > k_pool_buffer_size)
return {};
std::lock_guard<std::mutex> lock(g_pool_mutex);
for (auto it = g_pool.begin(); it != g_pool.end(); ++it)
{
if (it->size >= required_size)
{
PoolEntry e = *it;
g_pool.erase(it);
return e;
}
}
void* ptr = pool_alloc(k_pool_buffer_size);
if (ptr == nullptr)
return {};
return { ptr, k_pool_buffer_size };
}
void release(PoolEntry e)
{
if (e.ptr == nullptr)
return;
std::lock_guard<std::mutex> lock(g_pool_mutex);
if (static_cast<int>(g_pool.size()) < k_pool_max_count)
{
g_pool.push_back(e);
}
else
{
pool_free(e.ptr);
}
}
void ensure_initial_pool()
{
std::lock_guard<std::mutex> lock(g_pool_mutex);
for (int i = static_cast<int>(g_pool.size()); i < k_pool_initial_count; ++i)
{
void* ptr = pool_alloc(k_pool_buffer_size);
if (ptr == nullptr)
break;
g_pool.push_back({ ptr, k_pool_buffer_size });
}
}
}
// ============================================================================
// tsg namespace: global state definitions and helper implementations
// ============================================================================
namespace tsg
{
// --- Global state definitions ---
thread_local std::string g_last_error;
std::once_flag g_backend_init_once;
ggml_backend_t g_backend = nullptr;
int g_backend_type = 0;
// Vulkan device index requested via TSGgml_SetVulkanDeviceIndex. Must be set
// before the first backend init (create_backend_instance runs once under
// g_backend_init_once); later calls with a different index fail. Indices are
// positions in ggml-vulkan's enumeration order (after any
// GGML_VK_VISIBLE_DEVICES filtering applied at process launch).
std::atomic<int> g_vulkan_device_index{0};
std::mutex g_host_buffer_cache_mutex;
std::unordered_map<void*, CachedHostBuffer> g_host_buffer_cache;
std::mutex g_preloaded_buffer_cache_mutex;
std::unordered_map<void*, CachedHostBuffer> g_preloaded_buffer_cache;
// MoE expert weight offload state — see ggml_ops_internal.h for the contract.
std::unordered_set<void*> g_offloadable_keys;
std::list<void*> g_offloadable_lru;
std::unordered_map<void*, std::list<void*>::iterator> g_offloadable_lru_map;
std::int64_t g_offloadable_resident_bytes = 0;
std::int64_t g_offloadable_budget = 0;
// Device-copy VRAM budget — see ggml_ops_internal.h for the contract.
std::int64_t g_device_copy_resident_bytes = 0;
std::int64_t g_device_copy_budget_bytes = 0;
// Async dispatch state. The defaults keep the legacy (eager-sync) behaviour;
// C# enables async at backend init time via TSGgml_SetAsyncCompute(1).
std::atomic<bool> g_async_compute_enabled{false};
std::atomic<bool> g_pending_gpu_work{false};
static bool is_truthy_env(const char* value)
{
return value != nullptr &&
(std::strcmp(value, "1") == 0 ||
std::strcmp(value, "true") == 0 ||
std::strcmp(value, "TRUE") == 0 ||
std::strcmp(value, "True") == 0 ||
std::strcmp(value, "yes") == 0 ||
std::strcmp(value, "YES") == 0 ||
std::strcmp(value, "on") == 0 ||
std::strcmp(value, "ON") == 0);
}
static void filtered_ggml_log(enum ggml_log_level level, const char* text, void* user_data)
{
(void) user_data;
if (level == GGML_LOG_LEVEL_DEBUG)
return;
std::fputs(text, stderr);
std::fflush(stderr);
}
static void configure_ggml_logging()
{
ggml_log_set(filtered_ggml_log, nullptr);
}
// --- Error helpers ---
void set_last_error(const std::string& message)
{
g_last_error = message;
}
void clear_last_error()
{
g_last_error.clear();
}
// --- VRAM allocation diagnostics (TS_GGML_LOG_VRAM=1) ---
bool vram_log_enabled()
{
static const bool enabled = []{
const char* e = std::getenv("TS_GGML_LOG_VRAM");
return e != nullptr && e[0] == '1';
}();
return enabled;
}
void vram_log(const char* tag, std::int64_t bytes)
{
if (!vram_log_enabled())
return;
std::size_t free_b = 0, total_b = 0;
if (g_backend != nullptr)
{
ggml_backend_dev_t dev = ggml_backend_get_device(g_backend);
if (dev != nullptr)
ggml_backend_dev_memory(dev, &free_b, &total_b);
}
std::fprintf(stderr, "[TSVRAM] %-32s %9.1f MB | dev free %9.1f / %9.1f MB\n",
tag, bytes / (1024.0 * 1024.0),
free_b / (1024.0 * 1024.0), total_b / (1024.0 * 1024.0));
std::fflush(stderr);
}
// --- Backend management ---
ggml_backend_t create_backend_instance(int backend_type)
{
if (backend_type == BACKEND_TYPE_METAL)
{
#if defined(TSG_GGML_USE_METAL)
ggml_backend_t backend = ggml_backend_metal_init();
if (backend == nullptr)
set_last_error("ggml-metal backend initialization failed.");
return backend;
#else
set_last_error("The ggml-metal backend is not available in this build.");
return nullptr;
#endif
}
if (backend_type == BACKEND_TYPE_CPU)
{
ggml_backend_t backend = ggml_backend_cpu_init();
if (backend == nullptr)
set_last_error("ggml-cpu backend initialization failed.");
return backend;
}
if (backend_type == BACKEND_TYPE_CUDA)
{
#if defined(GGML_USE_CUDA)
ggml_backend_dev_t device = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU);
if (device == nullptr)
{
set_last_error("No GGML GPU device is available for ggml-cuda.");
return nullptr;
}
ggml_backend_t backend = ggml_backend_dev_init(device, nullptr);
if (backend == nullptr)
set_last_error("ggml-cuda backend initialization failed.");
return backend;
#else
set_last_error("The ggml-cuda backend is not available in this build.");
return nullptr;
#endif
}
if (backend_type == BACKEND_TYPE_VULKAN)
{
#if defined(GGML_USE_VULKAN)
// Init by the Vulkan-specific API rather than dev_by_type(GPU): when
// several GPU backends are compiled into one binary (CUDA + Vulkan),
// dev_by_type returns the first registered GPU device, which is
// ggml-cuda's. The CUDA branch above keeps that behaviour; here the
// Vulkan device must be picked explicitly.
const int device_count = ggml_backend_vk_get_device_count();
if (device_count <= 0)
{
set_last_error("No Vulkan device is available for ggml-vulkan.");
return nullptr;
}
const int device_index = g_vulkan_device_index.load(std::memory_order_acquire);
if (device_index < 0 || device_index >= device_count)
{
set_last_error("Vulkan device index " + std::to_string(device_index) +
" is out of range: " + std::to_string(device_count) + " Vulkan device(s) available.");
return nullptr;
}
ggml_backend_t backend = ggml_backend_vk_init(static_cast<size_t>(device_index));
if (backend == nullptr)
set_last_error("ggml-vulkan backend initialization failed.");
return backend;
#else
set_last_error("The ggml-vulkan backend is not available in this build.");
return nullptr;
#endif
}
set_last_error("Unknown GGML backend type requested.");
return nullptr;
}
void initialize_backend()
{
clear_last_error();
configure_ggml_logging();
g_backend = create_backend_instance(g_backend_type);
if (g_backend == nullptr)
return;
ggml_pool::ensure_initial_pool();
}
bool ensure_backend(int backend_type)
{
if (backend_type != BACKEND_TYPE_METAL &&
backend_type != BACKEND_TYPE_CPU &&
backend_type != BACKEND_TYPE_CUDA &&
backend_type != BACKEND_TYPE_VULKAN)
{
set_last_error("Invalid GGML backend type.");
return false;
}
if (g_backend_type == 0)
g_backend_type = backend_type;
else if (g_backend_type != backend_type)
{
set_last_error("A different GGML backend was already initialized in this process.");
return false;
}
std::call_once(g_backend_init_once, initialize_backend);
return g_backend != nullptr;
}
bool ensure_backend()
{
const int backend_type = (g_backend_type == 0) ? BACKEND_TYPE_METAL : g_backend_type;
return ensure_backend(backend_type);
}
bool can_initialize_backend(int backend_type)
{
// Lightweight availability check: report only compile-time support so we
// don't spin up the actual GGML device (Metal MTLDevice / CUDA driver) at
// process start — important when a non-GGML backend (MLX, direct CUDA) is
// selected, otherwise the unrelated GGML init logs leak into that run.
// Real init still happens lazily via ensure_backend when a GGML backend
// is actually selected, and surfaces a clear error then if it fails.
clear_last_error();
if (backend_type == BACKEND_TYPE_CPU)
return true;
if (backend_type == BACKEND_TYPE_METAL)
{
#if defined(TSG_GGML_USE_METAL)
return true;
#else
set_last_error("The ggml-metal backend is not available in this build.");
return false;
#endif
}
if (backend_type == BACKEND_TYPE_CUDA)
{
#if defined(GGML_USE_CUDA)
return true;
#else
set_last_error("The ggml-cuda backend is not available in this build.");
return false;
#endif
}
if (backend_type == BACKEND_TYPE_VULKAN)
{
#if defined(GGML_USE_VULKAN)
return true;
#else
set_last_error("The ggml-vulkan backend is not available in this build.");
return false;
#endif
}
set_last_error("Invalid GGML backend type.");
return false;
}
bool backend_supports_op(ggml_tensor* op)
{
return op != nullptr && g_backend != nullptr && ggml_backend_supports_op(g_backend, op);
}
// --- Size / layout queries ---
std::size_t required_raw_bytes(const TensorView2DDesc& desc)
{
const std::int64_t max_offset =
(static_cast<std::int64_t>(desc.dim0) - 1) * desc.stride0 +
(static_cast<std::int64_t>(desc.dim1) - 1) * desc.stride1;
return static_cast<std::size_t>((max_offset + 1) * sizeof(float));
}
std::size_t required_raw_bytes(const TensorView3DDesc& desc)
{
const std::int64_t max_offset =
(static_cast<std::int64_t>(desc.dim0) - 1) * desc.stride0 +
(static_cast<std::int64_t>(desc.dim1) - 1) * desc.stride1 +
(static_cast<std::int64_t>(desc.dim2) - 1) * desc.stride2;
return static_cast<std::size_t>((max_offset + 1) * sizeof(float));
}
std::size_t required_raw_bytes(const TensorView4DDesc& desc)
{
const std::int64_t max_offset =
(static_cast<std::int64_t>(desc.ne0) - 1) +
(static_cast<std::int64_t>(desc.ne1) - 1) * (desc.nb1 / static_cast<std::int64_t>(sizeof(float))) +
(static_cast<std::int64_t>(desc.ne2) - 1) * (desc.nb2 / static_cast<std::int64_t>(sizeof(float))) +
(static_cast<std::int64_t>(desc.ne3) - 1) * (desc.nb3 / static_cast<std::int64_t>(sizeof(float)));
return static_cast<std::size_t>((max_offset + 1) * sizeof(float));
}
std::size_t logical_bytes(const TensorView2DDesc& desc)
{
return static_cast<std::size_t>(desc.dim0) * desc.dim1 * sizeof(float);
}
std::size_t logical_row_bytes(const TensorView2DDesc& desc)
{
return static_cast<std::size_t>(desc.dim1) * sizeof(float);
}
std::size_t logical_bytes(const TensorView3DDesc& desc)
{
return static_cast<std::size_t>(desc.dim0) * desc.dim1 * desc.dim2 * sizeof(float);
}
std::size_t logical_bytes(const TensorView4DDesc& desc)
{
return static_cast<std::size_t>(desc.ne0) * desc.ne1 * desc.ne2 * desc.ne3 * sizeof(float);
}
std::size_t raw_row_bytes(const TensorView2DDesc& desc)
{
TensorView2DDesc row_desc = desc;
row_desc.dim0 = 1;
return required_raw_bytes(row_desc);
}
TensorView2DDesc slice_rows_2d(const TensorView2DDesc& desc, int row_start, int row_count)
{
TensorView2DDesc slice = desc;
slice.data = static_cast<char*>(desc.data) +
static_cast<std::size_t>(row_start) *
static_cast<std::size_t>(desc.stride0) *
sizeof(float);
slice.dim0 = row_count;
slice.raw_bytes = static_cast<std::int64_t>(required_raw_bytes(slice));
return slice;
}
int limit_rows_for_cuda_copy(int current_limit, const TensorView2DDesc& desc)
{
if (current_limit <= 0)
return 0;
const std::size_t per_row_bytes = std::max(logical_row_bytes(desc), raw_row_bytes(desc));
if (per_row_bytes == 0 || per_row_bytes > k_ggml_cuda_max_copy_bytes)
return 0;
const int limit = static_cast<int>(k_ggml_cuda_max_copy_bytes / per_row_bytes);
return std::min(current_limit, std::max(1, limit));
}
// --- Validation ---
bool validate_desc(const TensorView2DDesc& desc, const char* name)
{
if (desc.data == nullptr)
{
set_last_error(std::string("Null pointer passed for ") + name + '.');
return false;
}
if (desc.dim0 <= 0 || desc.dim1 <= 0)
{
set_last_error(std::string("Invalid tensor shape passed for ") + name + '.');
return false;
}
if (desc.stride0 < 0 || desc.stride1 < 0)
{
set_last_error(std::string("Negative tensor strides are not supported for ") + name + '.');
return false;
}
if (desc.raw_bytes <= 0 || (desc.raw_bytes % static_cast<std::int64_t>(sizeof(float))) != 0)
{
set_last_error(std::string("Invalid raw byte size passed for ") + name + '.');
return false;
}
if (static_cast<std::size_t>(desc.raw_bytes) < required_raw_bytes(desc))
{
set_last_error(std::string("Raw byte span is too small for ") + name + '.');
return false;
}
return true;
}
bool validate_desc(const TensorView3DDesc& desc, const char* name)
{
if (desc.data == nullptr)
{
set_last_error(std::string("Null pointer passed for ") + name + '.');
return false;
}
if (desc.dim0 <= 0 || desc.dim1 <= 0 || desc.dim2 <= 0)
{
set_last_error(std::string("Invalid tensor shape passed for ") + name + '.');
return false;
}
if (desc.stride0 < 0 || desc.stride1 < 0 || desc.stride2 < 0)
{
set_last_error(std::string("Negative tensor strides are not supported for ") + name + '.');
return false;
}
if (desc.raw_bytes <= 0 || (desc.raw_bytes % static_cast<std::int64_t>(sizeof(float))) != 0)
{
set_last_error(std::string("Invalid raw byte size passed for ") + name + '.');
return false;
}
if (static_cast<std::size_t>(desc.raw_bytes) < required_raw_bytes(desc))
{
set_last_error(std::string("Raw byte span is too small for ") + name + '.');
return false;
}
return true;
}
bool validate_desc(const TensorView4DDesc& desc, const char* name)
{
if (desc.data == nullptr)
{
set_last_error(std::string("Null pointer passed for ") + name + '.');
return false;
}
if (desc.ne0 <= 0 || desc.ne1 <= 0 || desc.ne2 <= 0 || desc.ne3 <= 0)
{
set_last_error(std::string("Invalid tensor shape passed for ") + name + '.');
return false;
}
if (desc.nb1 <= 0 || desc.nb2 <= 0 || desc.nb3 <= 0)
{
set_last_error(std::string("Invalid tensor strides passed for ") + name + '.');
return false;
}
if ((desc.nb1 % static_cast<std::int64_t>(sizeof(float))) != 0
|| (desc.nb2 % static_cast<std::int64_t>(sizeof(float))) != 0
|| (desc.nb3 % static_cast<std::int64_t>(sizeof(float))) != 0)
{
set_last_error(std::string("Tensor byte strides must be multiples of sizeof(float) for ") + name + '.');
return false;
}
if (desc.raw_bytes <= 0 || (desc.raw_bytes % static_cast<std::int64_t>(sizeof(float))) != 0)
{
set_last_error(std::string("Invalid raw byte size passed for ") + name + '.');
return false;
}
if (static_cast<std::size_t>(desc.raw_bytes) < required_raw_bytes(desc))
{
set_last_error(std::string("Raw byte span is too small for ") + name + '.');
return false;
}
return true;
}
bool validate_desc(const ContiguousTensorDesc& desc, const char* name)
{
if (desc.data == nullptr)
{
set_last_error(std::string("Null pointer passed for ") + name + '.');
return false;
}
if (desc.element_count <= 0)
{
set_last_error(std::string("Invalid element count passed for ") + name + '.');
return false;
}
if (desc.element_type != TSG_DTYPE_F32 && desc.element_type != TSG_DTYPE_I32)
{
set_last_error(std::string("Unsupported contiguous tensor element type passed for ") + name + '.');
return false;
}
return true;
}
bool read_i32_values(std::vector<std::int32_t>& output, const ContiguousTensorDesc& desc, const char* name)
{
output.resize(static_cast<std::size_t>(desc.element_count));
if (desc.element_type == TSG_DTYPE_I32)
{
const std::int32_t* raw = static_cast<const std::int32_t*>(desc.data);
std::copy(raw, raw + output.size(), output.begin());
return true;
}
if (desc.element_type == TSG_DTYPE_F32)
{
const float* raw = static_cast<const float*>(desc.data);
for (std::size_t i = 0; i < output.size(); ++i)
output[i] = static_cast<std::int32_t>(raw[i]);
return true;
}
set_last_error(std::string("Unsupported element type for ") + name + '.');
return false;
}
// --- Layout queries ---
bool can_map_standard_view(const TensorView2DDesc& desc)
{
return desc.stride1 == 1 &&
is_non_overlapping_fast_to_slow<2>({ desc.dim1, desc.dim0 }, { desc.stride1, desc.stride0 });
}
bool can_map_standard_view(const TensorView3DDesc& desc)
{
return desc.stride2 == 1 &&
is_non_overlapping_fast_to_slow<3>({ desc.dim2, desc.dim1, desc.dim0 }, { desc.stride2, desc.stride1, desc.stride0 });
}
bool can_map_standard_view(const TensorView4DDesc& desc)
{
const auto stride1 = static_cast<int>(desc.nb1 / static_cast<std::int64_t>(sizeof(float)));
const auto stride2 = static_cast<int>(desc.nb2 / static_cast<std::int64_t>(sizeof(float)));
const auto stride3 = static_cast<int>(desc.nb3 / static_cast<std::int64_t>(sizeof(float)));
return is_non_overlapping_fast_to_slow<4>({ desc.ne0, desc.ne1, desc.ne2, desc.ne3 }, { 1, stride1, stride2, stride3 });
}
bool can_map_m2_direct(const TensorView2DDesc& desc)
{
return desc.stride0 == 1 &&
desc.stride1 >= desc.dim0 &&
is_non_overlapping_fast_to_slow<2>({ desc.dim0, desc.dim1 }, { desc.stride0, desc.stride1 });
}
bool can_map_m2_direct(const TensorView3DDesc& desc)
{
return desc.stride1 == 1 &&
desc.stride2 >= desc.dim1 &&
is_non_overlapping_fast_to_slow<3>({ desc.dim1, desc.dim2, desc.dim0 }, { desc.stride1, desc.stride2, desc.stride0 });
}
// --- Pointer / buffer utilities ---
bool is_pointer_aligned(const void* ptr, std::size_t alignment)
{
return ptr != nullptr && (alignment <= 1 || (reinterpret_cast<std::uintptr_t>(ptr) % alignment) == 0);
}
std::size_t get_host_ptr_alignment(ggml_backend_t backend, ggml_backend_dev_t dev)
{
if (dev != nullptr)
{
if (ggml_backend_buffer_type_t buft = ggml_backend_dev_buffer_type(dev))
return ggml_backend_buft_get_alignment(buft);
}
return 16384;
}
DeviceStaticProps get_device_static_props(ggml_backend_dev_t dev)
{
static std::mutex s_mutex;
static std::unordered_map<ggml_backend_dev_t, DeviceStaticProps> s_cache;
std::lock_guard<std::mutex> lock(s_mutex);
auto it = s_cache.find(dev);
if (it != s_cache.end())
return it->second;
ggml_backend_dev_props props;
ggml_backend_dev_get_props(dev, &props);
DeviceStaticProps s{ props.type, props.caps.buffer_from_host_ptr };
s_cache.emplace(dev, s);
return s;
}
bool prefers_device_local_cache(ggml_backend_dev_t dev)
{
if (dev == nullptr)
return false;
// Upstream ggml's ggml_backend_dev_props has no `integrated` field (that was an
// ollama-fork extension). On the backends we use the field was effectively always
// 0 anyway -- the Metal backend reports type=GPU and never set it -- so the
// discrete-GPU test reduces to "is this a GPU device".
//
// NOTE: This governs the binding policy for *read-write* tensors
// (activations, KV cache). For those, even on unified-memory Metal we
// keep the device-local + explicit upload/download path because the
// zero-copy host-ptr path for read-write tensors is not exercised on
// Metal (it relies on a lazy-sync model that the per-op activation
// bindings here don't fully honour). Large *read-only weights* are
// handled separately and ARE wrapped zero-copy on Metal -- see the
// unified-memory weight branch in try_get_cacheable_tensor_buffer,
// which is where the model-weight memory duplication is avoided.
//
// Integrated GPUs count as GPUs here. Upstream ggml now reports them as
// GGML_BACKEND_DEVICE_TYPE_IGPU (ggml-vulkan for iGPUs behind e.g.
// --gpu-device, ggml-cuda for Tegra). Excluding IGPU broke the preload
// contract: TSGgml_PreloadQuantizedWeight early-returns success when
// this predicate is false WITHOUT caching anything, the managed side
// then releases the host weight copies, and the first forward's cache
// miss dereferenced the opaque GCHandle cache key as if it were weight
// bytes -> access violation on Intel iGPUs (their UMA device buffers
// work exactly like discrete ones for our binding purposes).
const enum ggml_backend_dev_type type = get_device_static_props(dev).type;
return type == GGML_BACKEND_DEVICE_TYPE_GPU || type == GGML_BACKEND_DEVICE_TYPE_IGPU;
}
// Capability-only test: can this host pointer be wrapped as a device-visible
// buffer at all (backend supports buffer_from_host_ptr and the pointer meets
// the buffer-type alignment)? Unlike can_use_host_ptr_buffer this does NOT
// consult prefers_device_local_cache, so it returns true on unified-memory
// Metal. Used by the read-only-weight zero-copy path; read-write activation
// bindings continue to gate on can_use_host_ptr_buffer.
bool host_ptr_buffer_capable(ggml_backend_t backend, ggml_backend_dev_t dev, const void* ptr, std::size_t size)
{
if (dev == nullptr || ptr == nullptr || size == 0)
return false;
if (!get_device_static_props(dev).buffer_from_host_ptr)
return false;
const std::size_t alignment = get_host_ptr_alignment(backend, dev);
return is_pointer_aligned(ptr, alignment);
}
bool can_use_host_ptr_buffer(ggml_backend_t backend, ggml_backend_dev_t dev, const void* ptr, std::size_t size)
{
if (prefers_device_local_cache(dev))
return false;
return host_ptr_buffer_capable(backend, dev, ptr, size);
}
// Hint to the OS that the given file-backed mmap region is no longer
// needed. Pairs with offloadable LRU eviction: once Metal's MTLBuffer
// wrapper has been freed, calling MADV_DONTNEED tells the kernel it
// may immediately reclaim those pages without waiting for memory
// pressure. On the next access the pages page-fault back in from SSD.
// The range is rounded outward to whole page boundaries; for our use
// case (GGUF tensors aligned on 32-byte block boundaries in a file
// mmap'd read-only) the rounding may overlap adjacent tensors, which
// is fine — they're also file-backed and will page back in on next
// touch. Safe on Apple Silicon (16 KB pages) and Linux.
void advise_pages_dont_need(void* data, std::size_t bytes)
{
#if defined(__APPLE__) || defined(__linux__)
if (data == nullptr || bytes == 0)
return;
const long page_size = sysconf(_SC_PAGESIZE);
if (page_size <= 0)
return;
const std::uintptr_t addr = reinterpret_cast<std::uintptr_t>(data);
const std::uintptr_t aligned_addr = addr & ~(static_cast<std::uintptr_t>(page_size) - 1);
const std::size_t prefix = static_cast<std::size_t>(addr - aligned_addr);
const std::size_t total = bytes + prefix;
const std::size_t mask = static_cast<std::size_t>(page_size) - 1;
const std::size_t rounded = (total + mask) & ~mask;
(void)madvise(reinterpret_cast<void*>(aligned_addr), rounded, MADV_DONTNEED);
#else
(void)data;
(void)bytes;
#endif
}
// --- Device-copy budget accounting (caller holds g_host_buffer_cache_mutex) ---
static void device_copy_account_remove_locked(const CachedHostBuffer& entry)
{
if (entry.mode != CachedBufferMode::DeviceCopy)
return;
const std::int64_t sz = static_cast<std::int64_t>(entry.buffer_size);
g_device_copy_resident_bytes = g_device_copy_resident_bytes >= sz
? g_device_copy_resident_bytes - sz : 0;
}
// --- Offloadable LRU helpers (caller holds g_host_buffer_cache_mutex) ---
void offloadable_lru_remove_locked(void* key)
{
auto it = g_offloadable_lru_map.find(key);
if (it == g_offloadable_lru_map.end())
return;
g_offloadable_lru.erase(it->second);
g_offloadable_lru_map.erase(it);
}
void offloadable_lru_touch_locked(void* key)
{
auto it = g_offloadable_lru_map.find(key);
if (it == g_offloadable_lru_map.end())
return;
g_offloadable_lru.erase(it->second);
g_offloadable_lru.push_front(key);
it->second = g_offloadable_lru.begin();
}
void offloadable_lru_insert_front_locked(void* key)
{
offloadable_lru_remove_locked(key);
g_offloadable_lru.push_front(key);
g_offloadable_lru_map[key] = g_offloadable_lru.begin();
}
// Drop an offloadable LRU entry: removes the cache entry, frees the
// backend buffer wrapper (releasing Metal's claim on the underlying
// host pages), and hints the OS that the pages can be reclaimed now.
// Returns the number of bytes freed.
std::size_t offloadable_evict_one_locked()
{
if (g_offloadable_lru.empty())
return 0;
void* key = g_offloadable_lru.back();
g_offloadable_lru.pop_back();
g_offloadable_lru_map.erase(key);
auto cit = g_host_buffer_cache.find(key);
if (cit == g_host_buffer_cache.end())
return 0;
std::size_t freed = cit->second.bytes;
device_copy_account_remove_locked(cit->second);
ggml_backend_buffer_free(cit->second.buffer);
g_host_buffer_cache.erase(cit);
advise_pages_dont_need(key, freed);
if (g_offloadable_resident_bytes >= static_cast<std::int64_t>(freed))
g_offloadable_resident_bytes -= static_cast<std::int64_t>(freed);
else
g_offloadable_resident_bytes = 0;
return freed;
}
void offloadable_evict_to_budget_locked()
{
if (g_offloadable_budget <= 0)
return;
while (g_offloadable_resident_bytes > g_offloadable_budget && !g_offloadable_lru.empty())
{
if (offloadable_evict_one_locked() == 0)
break;
}
}
void invalidate_cached_buffer(void* data)
{
if (data == nullptr)
return;
{
std::lock_guard<std::mutex> lock(g_preloaded_buffer_cache_mutex);
auto it = g_preloaded_buffer_cache.find(data);
if (it != g_preloaded_buffer_cache.end())
{
ggml_backend_buffer_free(it->second.buffer);
g_preloaded_buffer_cache.erase(it);
return;
}
}
{
std::lock_guard<std::mutex> lock(g_host_buffer_cache_mutex);
auto it = g_host_buffer_cache.find(data);
if (it == g_host_buffer_cache.end())
return;
offloadable_lru_remove_locked(data);
if (g_offloadable_keys.count(data))
{
if (g_offloadable_resident_bytes >= static_cast<std::int64_t>(it->second.bytes))
g_offloadable_resident_bytes -= static_cast<std::int64_t>(it->second.bytes);
else
g_offloadable_resident_bytes = 0;
}
device_copy_account_remove_locked(it->second);
ggml_backend_buffer_free(it->second.buffer);
g_host_buffer_cache.erase(it);
}
}
bool try_get_host_ptr_buffer(
ggml_backend_t backend, ggml_backend_dev_t dev,
void* data, std::size_t bytes, bool cacheable,
ggml_backend_buffer_t& out_buffer,
bool allow_unified_weight)
{
out_buffer = nullptr;
const bool capable = allow_unified_weight
? host_ptr_buffer_capable(backend, dev, data, bytes)
: can_use_host_ptr_buffer(backend, dev, data, bytes);
if (!capable)
return false;
if (cacheable)
{
std::lock_guard<std::mutex> lock(g_host_buffer_cache_mutex);
auto it = g_host_buffer_cache.find(data);
if (it != g_host_buffer_cache.end() &&
it->second.bytes == bytes &&
it->second.mode == CachedBufferMode::HostPtr)
{
out_buffer = it->second.buffer;
if (g_offloadable_keys.count(data))
offloadable_lru_touch_locked(data);
return true;
}
}
out_buffer = ggml_backend_dev_buffer_from_host_ptr(dev, data, bytes, bytes);
if (out_buffer == nullptr)
return false;
if (cacheable)
{
std::lock_guard<std::mutex> lock(g_host_buffer_cache_mutex);
g_host_buffer_cache[data] = {
out_buffer, bytes,
ggml_backend_buffer_get_size(out_buffer),
CachedBufferMode::HostPtr
};
if (g_offloadable_keys.count(data))
{
offloadable_lru_insert_front_locked(data);
g_offloadable_resident_bytes += static_cast<std::int64_t>(bytes);
// Evict from the tail of the LRU; the just-inserted entry is
// at the front and is safe (it's the one the caller will use
// for the in-progress graph build). Eviction of other tail
// entries frees their MTLBuffer wrappers; any kernel whose
// graph computed earlier has already released the references
// it captured at build time.
offloadable_evict_to_budget_locked();
}
}
return true;
}
bool try_get_cacheable_tensor_buffer(
ggml_backend_t backend, ggml_backend_dev_t dev,
ggml_tensor* tensor, void* data, std::size_t bytes,
ggml_backend_buffer_t& out_buffer, void*& out_addr, bool& out_needs_upload,
enum ggml_backend_buffer_usage usage)
{
out_buffer = nullptr;
out_addr = nullptr;
out_needs_upload = false;
if (backend == nullptr || dev == nullptr || tensor == nullptr || data == nullptr || bytes == 0)
return false;
// Read-only model weights on a unified-memory backend (Metal on Apple
// Silicon) are wrapped zero-copy around their host/mmap pointer rather
// than copied into a device-local buffer. This is THE fix for model
// weight memory blow-up: a 12 GB Q8_0 model otherwise pays ~12 GB of
// dirty anonymous device copies ON TOP of the 12 GB GGUF mmap (~24 GB,
// swapping on a 24 GB box). The weight bytes are read-only and the
// GGUF mmap stays alive for the model's lifetime, so the wrap is safe.
//
// Restricted to USAGE_WEIGHTS: small read-write tensors (KV cache,
// activations) are bound with USAGE_COMPUTE and keep the device-local
// copy path, whose explicit upload/download is what the Metal kernels
// here rely on for correctness.
const bool unified_weight =
usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS &&
g_backend_type == BACKEND_TYPE_METAL &&
host_ptr_buffer_capable(backend, dev, data, bytes);
const bool use_device_copy = prefers_device_local_cache(dev) && !unified_weight;
{
std::lock_guard<std::mutex> lock(g_preloaded_buffer_cache_mutex);
auto it = g_preloaded_buffer_cache.find(data);
if (it != g_preloaded_buffer_cache.end())
{
const std::size_t required_size = ggml_backend_buffer_get_alloc_size(it->second.buffer, tensor);
if (it->second.bytes == bytes &&
required_size <= it->second.buffer_size)
{
out_buffer = it->second.buffer;
out_addr = ggml_backend_buffer_get_base(out_buffer);
return true;
}
ggml_backend_buffer_free(it->second.buffer);
g_preloaded_buffer_cache.erase(it);
}
}
{
std::lock_guard<std::mutex> lock(g_host_buffer_cache_mutex);
auto it = g_host_buffer_cache.find(data);
if (it != g_host_buffer_cache.end())
{
const bool mode_matches =
(use_device_copy && it->second.mode == CachedBufferMode::DeviceCopy) ||
(!use_device_copy && it->second.mode == CachedBufferMode::HostPtr);
const std::size_t required_size = ggml_backend_buffer_get_alloc_size(it->second.buffer, tensor);
if (mode_matches &&
it->second.bytes == bytes &&
required_size <= it->second.buffer_size)
{
out_buffer = it->second.buffer;
out_addr = use_device_copy ? ggml_backend_buffer_get_base(out_buffer) : data;
return true;
}
device_copy_account_remove_locked(it->second);
ggml_backend_buffer_free(it->second.buffer);
g_host_buffer_cache.erase(it);
}
}
if (use_device_copy)
{
ggml_backend_buffer_type_t buft = ggml_backend_get_default_buffer_type(backend);
if (buft == nullptr)