forked from zhongkaifu/TensorSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModelBase.cs
More file actions
3999 lines (3573 loc) · 182 KB
/
Copy pathModelBase.cs
File metadata and controls
3999 lines (3573 loc) · 182 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.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using TensorSharp;
using TensorSharp.Cpu;
using TensorSharp.Cuda;
using TensorSharp.GGML;
using TensorSharp.MLX;
namespace TensorSharp.Models
{
public class QuantizedWeight : IDisposable
{
private IntPtr _data;
private GCHandle _cacheKeyHandle;
public IntPtr Data => _data;
public IntPtr CacheKey { get; private set; }
public int GgmlType { get; }
public long Ne0 { get; }
public long Ne1 { get; }
public long RawBytes { get; }
private bool _ownsBuffer;
private bool _ownsCacheKeyHandle;
private object _ownerToken;
public bool HasHostData => _data != IntPtr.Zero;
public bool HasExternalHostView => _data != IntPtr.Zero && !_ownsBuffer && _ownerToken != null;
/// <summary>
/// True when the active device could not hold this weight in a single
/// backend buffer (e.g. ggml-vulkan rejects any buffer above the driver's
/// maxBufferSize; WSL's dzn layer caps it under 3 GB), so the device
/// preload was skipped and the host copy retained. Consumers must serve
/// this weight through their host-gather/dequant fallback instead of
/// device-side lookups keyed by <see cref="CacheKey"/>.
/// </summary>
public bool DevicePreloadTooLarge { get; private set; }
public QuantizedWeight(byte[] raw, int ggmlType, long ne0, long ne1)
{
GgmlType = ggmlType;
Ne0 = ne0;
Ne1 = ne1;
RawBytes = raw.Length;
_data = AllocateBuffer(raw.Length);
CacheKey = _data;
_ownsBuffer = true;
Marshal.Copy(raw, 0, _data, raw.Length);
}
public QuantizedWeight(IntPtr data, long rawBytes, int ggmlType, long ne0, long ne1)
: this(data, rawBytes, ggmlType, ne0, ne1, true, null)
{
}
private QuantizedWeight(IntPtr data, long rawBytes, int ggmlType, long ne0, long ne1, bool ownsBuffer, object ownerToken)
{
_data = data;
CacheKey = data;
RawBytes = rawBytes;
GgmlType = ggmlType;
Ne0 = ne0;
Ne1 = ne1;
_ownsBuffer = ownsBuffer;
_ownerToken = ownerToken;
}
public void Dispose()
{
ReleaseHostData();
if (_ownsCacheKeyHandle)
{
_cacheKeyHandle.Free();
_ownsCacheKeyHandle = false;
CacheKey = IntPtr.Zero;
}
}
public static QuantizedWeight CreateExternalView(IntPtr data, long rawBytes, int ggmlType, long ne0, long ne1, object ownerToken)
{
if (data == IntPtr.Zero)
throw new ArgumentException("External quantized weight view requires a non-zero data pointer.", nameof(data));
if (ownerToken == null)
throw new ArgumentNullException(nameof(ownerToken));
return new QuantizedWeight(data, rawBytes, ggmlType, ne0, ne1, false, ownerToken);
}
public static bool TryCreateConcatenatedView(out QuantizedWeight fused, params QuantizedWeight[] weights)
{
fused = null;
if (weights == null || weights.Length < 2 || weights[0] == null)
return false;
QuantizedWeight first = weights[0];
if (!first.HasHostData || first._ownsBuffer || first._ownerToken == null)
return false;
long totalBytes = 0;
long totalNe1 = 0;
long expectedAddress = first.Data.ToInt64();
for (int i = 0; i < weights.Length; i++)
{
QuantizedWeight weight = weights[i];
if (weight == null ||
weight._ownsBuffer ||
!ReferenceEquals(weight._ownerToken, first._ownerToken) ||
weight.GgmlType != first.GgmlType ||
weight.Ne0 != first.Ne0 ||
weight.Data.ToInt64() != expectedAddress)
{
return false;
}
totalBytes += weight.RawBytes;
totalNe1 += weight.Ne1;
expectedAddress += weight.RawBytes;
}
fused = new QuantizedWeight(first.Data, totalBytes, first.GgmlType, first.Ne0, totalNe1, false, first._ownerToken);
return true;
}
public static unsafe QuantizedWeight ConcatOrCreateCopy(params QuantizedWeight[] weights)
{
if (weights == null || weights.Length == 0 || weights[0] == null)
throw new ArgumentException("At least one quantized weight is required.", nameof(weights));
if (TryCreateConcatenatedView(out QuantizedWeight fused, weights))
return fused;
QuantizedWeight first = weights[0];
long totalBytes = 0;
long totalNe1 = 0;
for (int i = 0; i < weights.Length; i++)
{
QuantizedWeight weight = weights[i] ?? throw new ArgumentException("Quantized weight list cannot contain null entries.", nameof(weights));
if (!weight.HasHostData)
throw new InvalidOperationException("Cannot concatenate quantized weights after their host storage has been released.");
totalBytes += weight.RawBytes;
totalNe1 += weight.Ne1;
}
IntPtr fusedPtr = AllocateBuffer(totalBytes);
byte* fusedDst = (byte*)fusedPtr.ToPointer();
long offset = 0;
for (int i = 0; i < weights.Length; i++)
{
QuantizedWeight weight = weights[i];
Buffer.MemoryCopy(weight.Data.ToPointer(), fusedDst + offset, totalBytes - offset, weight.RawBytes);
offset += weight.RawBytes;
}
return new QuantizedWeight(fusedPtr, totalBytes, first.GgmlType, first.Ne0, totalNe1);
}
public IntPtr EnsureDeviceCacheKey()
{
if (_ownsCacheKeyHandle)
return CacheKey;
// Once flagged too-large the cache key must stay the host data
// pointer: no device-resident entry exists for this weight, and a
// native cache miss on an opaque GCHandle key would dereference it
// as if it were weight bytes.
if (DevicePreloadTooLarge)
return CacheKey;
_cacheKeyHandle = GCHandle.Alloc(this, GCHandleType.Normal);
CacheKey = GCHandle.ToIntPtr(_cacheKeyHandle);
_ownsCacheKeyHandle = true;
return CacheKey;
}
/// <summary>
/// Record that the device preload was skipped because this weight exceeds
/// the device's single-buffer size limit. Frees any GCHandle-based device
/// cache key and restores <see cref="CacheKey"/> to the host data pointer,
/// so a native call that still receives the key resolves through the
/// host-pointer path instead of dereferencing an opaque GCHandle.
/// </summary>
public void MarkDevicePreloadTooLarge()
{
DevicePreloadTooLarge = true;
if (_ownsCacheKeyHandle)
{
_cacheKeyHandle.Free();
_ownsCacheKeyHandle = false;
}
CacheKey = _data;
}
public void ReleaseHostData()
{
if (_data == IntPtr.Zero)
return;
IntPtr currentData = _data;
bool wasExternalView = !_ownsBuffer && _ownerToken != null;
if (_ownsBuffer)
FreeBuffer(currentData);
else if (wasExternalView)
AdviseExternalViewCanBePagedOut(currentData, RawBytes);
if (CacheKey == currentData)
CacheKey = IntPtr.Zero;
_data = IntPtr.Zero;
_ownsBuffer = false;
_ownerToken = null;
}
public static unsafe IntPtr AllocateBuffer(long size)
{
void* ptr = NativeMemory.AlignedAlloc((nuint)size, 64);
if (ptr == null)
throw new OutOfMemoryException($"Unable to allocate {size} bytes for quantized weight storage.");
return (IntPtr)ptr;
}
public static unsafe void FreeBuffer(IntPtr ptr)
{
if (ptr != IntPtr.Zero)
NativeMemory.AlignedFree(ptr.ToPointer());
}
private static unsafe void AdviseExternalViewCanBePagedOut(IntPtr data, long byteCount)
{
if (data == IntPtr.Zero || byteCount <= 0)
return;
if (!OperatingSystem.IsMacOS() && !OperatingSystem.IsLinux())
return;
long pageSize = Environment.SystemPageSize;
long address = data.ToInt64();
long pageMask = ~(pageSize - 1);
long alignedAddress = address & pageMask;
long prefixBytes = address - alignedAddress;
ulong length = checked((ulong)(byteCount + prefixBytes));
ulong roundedLength = (length + (ulong)pageSize - 1) & ~((ulong)pageSize - 1);
try
{
_ = madvise((void*)alignedAddress, (nuint)roundedLength, MadvDontNeed);
}
catch (DllNotFoundException)
{
}
catch (EntryPointNotFoundException)
{
}
}
private const int MadvDontNeed = 4;
[DllImport("libc", SetLastError = true, EntryPoint = "madvise")]
private static extern unsafe int madvise(void* addr, nuint len, int advice);
}
/// <summary>
/// A view of a per-layer 3D MoE expert weight tensor as stored on disk
/// (<c>[ne0, ne1, num_experts]</c> contiguous). Built when the per-expert
/// quantized weights are split out of the original 3D GGUF tensor in
/// <see cref="ModelBase.LoadWeights"/>, so it costs nothing on top of the
/// per-expert weights for mmap'd models — the base pointer is the start
/// of the original 3D block and the bytes are the same bytes the per-expert
/// views point into.
///
/// The <see cref="MoEFFNPrefillSwiGLU"/> kernel consumes this directly to
/// run an entire MoE layer's gate/up/down via three <c>ggml_mul_mat_id</c>
/// dispatches (mirroring llama.cpp's <c>build_moe_ffn</c>) instead of the
/// previous per-active-expert loop that issued thousands of dispatches per
/// pp2048 forward.
/// </summary>
public sealed class StackedExpertWeights
{
public IntPtr Data { get; }
public int GgmlType { get; }
public long PerExpertNe0 { get; }
public long PerExpertNe1 { get; }
public int NumExperts { get; }
public long TotalRawBytes { get; }
public long PerExpertRawBytes => TotalRawBytes / NumExperts;
public bool IsExternalView { get; }
// Strong reference held to keep the underlying memory alive when this
// is an external view (e.g. into a GgufFile mmap or a sibling owning
// QuantizedWeight buffer). For owned buffers this is null.
private readonly object _ownerToken;
// For the non-mmap fallback path we own a pinned native buffer and
// free it on disposal of the parent ModelBase. Tracked so the buffer
// doesn't leak when ModelBase exits.
public IntPtr OwnedBuffer { get; }
public StackedExpertWeights(
IntPtr data,
int ggmlType,
long perExpertNe0,
long perExpertNe1,
int numExperts,
long totalRawBytes,
bool isExternalView,
object ownerToken,
IntPtr ownedBuffer)
{
Data = data;
GgmlType = ggmlType;
PerExpertNe0 = perExpertNe0;
PerExpertNe1 = perExpertNe1;
NumExperts = numExperts;
TotalRawBytes = totalRawBytes;
IsExternalView = isExternalView;
_ownerToken = ownerToken;
OwnedBuffer = ownedBuffer;
}
}
public abstract class ModelBase : IModelArchitecture
{
public ModelConfig Config { get; protected set; }
public ITokenizer Tokenizer { get; protected set; }
public IMultimodalInjector MultimodalInjector { get; }
public IBackendExecutionPlan ExecutionPlan { get; }
protected readonly GgufFile _gguf;
private readonly GgmlContext _ggmlContext;
protected readonly IAllocator _allocator;
protected readonly BackendType _backend;
protected readonly Dictionary<string, Tensor> _weights = new();
protected readonly Dictionary<string, QuantizedWeight> _quantWeights = new();
/// <summary>
/// Stacked-along-experts views of MoE expert weight tensors keyed by
/// the original GGUF tensor name (e.g. <c>"blk.0.ffn_gate_exps.weight"</c>).
/// Populated in <see cref="LoadWeights"/> for any 3D <c>_exps.</c>
/// tensor. Used by <see cref="GgmlBasicOps.MoEFFNPrefillSwiGLU"/> to
/// dispatch the entire MoE FFN as a few <c>ggml_mul_mat_id</c> calls
/// per layer instead of per-active-expert. May be null/empty when the
/// model doesn't expose stacked views (e.g. some non-mmap paths).
/// </summary>
protected readonly Dictionary<string, StackedExpertWeights> _stackedExpertWeights = new();
/// <summary>
/// Names of the per-expert split views in <see cref="_quantWeights"/> that
/// were carved out of a 3D <c>_exps.</c> tensor and are also covered by a
/// <see cref="_stackedExpertWeights"/> entry (same underlying bytes). A
/// model whose CUDA path serves MoE experts exclusively through the
/// stacked-expert device buffer can consult this set (via
/// <see cref="ShouldPreloadCudaQuantWeightToDevice"/>) to skip giving each
/// per-expert view its own device copy, which would otherwise duplicate
/// every expert byte a second time in VRAM on top of the stacked copy.
/// </summary>
protected readonly HashSet<string> _stackedExpertMemberNames = new();
private bool _quantBackendReady;
private bool _cudaQuantWeightsPrepared;
private bool _mlxQuantWeightsPrepared;
protected int _cacheSeqLen;
protected int _maxContextLength;
protected float[] _logitsBuffer;
/// <summary>
/// Storage dtype for the per-layer K/V cache tensors. Captured at model
/// construction time from <see cref="KvCacheDtypeConfig.Current"/> so the
/// rest of the per-model code (cache allocation, write-on-decode,
/// attention reads, native-layer-decode bindings) can specialize without
/// repeatedly polling the global config.
/// </summary>
protected KvCacheDtype _kvCacheDtype = KvCacheDtypeConfig.Current;
/// <summary>
/// Pick a model-aligned default KV-cache dtype based on the dominant
/// weight quantization tier seen in <paramref name="quantWeights"/>.
/// Mirrors <see cref="KvCacheDtypeConfig.ApplyModelDtypeDefault"/> but
/// is callable from inside a model constructor (after LoadWeights, before
/// InitKVCache) so each model picks its own default without forcing the
/// CLI front-end to inspect every GGUF file. Honors any explicit user
/// choice (env var or <c>--kv-cache-dtype</c> flag) - we only step in
/// when the user has left the dtype unset.
/// </summary>
protected void ApplyModelAlignedKvCacheDefault(IDictionary<string, QuantizedWeight> quantWeights)
{
if (KvCacheDtypeConfig.IsExplicitlySet) return;
int dominant = 0; // GGML_TYPE_F32
if (quantWeights != null && quantWeights.Count > 0)
{
Dictionary<int, long> typeBytes = new Dictionary<int, long>();
foreach (var qw in quantWeights.Values)
{
if (qw == null) continue;
if (!typeBytes.TryGetValue(qw.GgmlType, out long bytes)) bytes = 0;
typeBytes[qw.GgmlType] = bytes + qw.RawBytes;
}
long bestBytes = 0;
foreach (var kv in typeBytes)
{
if (kv.Value > bestBytes) { bestBytes = kv.Value; dominant = kv.Key; }
}
}
KvCacheDtypeConfig.ApplyModelDtypeDefault(dominant);
_kvCacheDtype = KvCacheDtypeConfig.Current;
}
public KvCacheDtype KvCacheDtype => _kvCacheDtype;
/// <summary>
/// Map the model's KV-cache storage dtype to the codec element type
/// the paged tier's optional TurboQuant codec uses to interpret the
/// raw block bytes. Block-quantized caches (Q8_0, Q4_0) bypass the codec
/// entirely (the bytes are already quantized with their own per-block
/// scale, so re-quantizing would compound error for no real shrink).
/// Q4_0 maps onto the same passthrough handling as Q8_0 - the codec's
/// passthrough branch and <c>FromEnvironment</c> skip are keyed on the
/// Q8_0 element type, which means "already block-quantized; leave the
/// bytes untouched" regardless of the underlying 4- vs 8-bit width.
/// </summary>
public virtual KvCodecElementType KVStateElementType => _kvCacheDtype switch
{
KvCacheDtype.F32 => KvCodecElementType.Float32,
KvCacheDtype.F16 => KvCodecElementType.Float16,
KvCacheDtype.Q8_0 => KvCodecElementType.Q8_0,
KvCacheDtype.Q4_0 => KvCodecElementType.Q8_0,
_ => KvCodecElementType.Float32,
};
public int MaxContextLength => _maxContextLength;
public int CacheSeqLen => _cacheSeqLen;
/// <summary>Prefill-length hint (see <see cref="IModelArchitecture.PrepareForPrefill"/>).
/// Default no-op; models with a grow-on-demand KV cache override to pre-size it.</summary>
public virtual void PrepareForPrefill(int requiredContextTokens) { }
// Timing
protected long _linearTicks;
protected long _attnTicks;
protected long _normTicks;
protected long _embTicks, _lmHeadTicks, _logitsCopyTicks;
protected int _forwardCount;
protected Stopwatch _forwardSw = new Stopwatch();
protected ModelBase(string ggufPath, BackendType backend)
{
_backend = backend;
// The pure-C# CPU backend must never touch native (ggml P/Invoke) dequant — route
// every dequant/row-size through the managed implementation (bit-exact vs native,
// verified). Other backends keep native dequant (faster load; their runtime quant
// ops go through GgmlBasicOps, not NativeDequant). One model/backend at a time.
NativeDequant.PreferManaged = backend == BackendType.Cpu;
ExecutionPlan = new BackendExecutionPlan(backend);
MultimodalInjector = new ModelMultimodalInjector(this);
switch (backend)
{
case BackendType.GgmlCpu:
_ggmlContext = new GgmlContext(new[] { 0 }, GgmlBackendType.Cpu);
_allocator = new GgmlAllocator(_ggmlContext, 0);
break;
case BackendType.GgmlMetal:
_ggmlContext = new GgmlContext(new[] { 0 }, GgmlBackendType.Metal);
_allocator = new GgmlAllocator(_ggmlContext, 0);
break;
case BackendType.GgmlCuda:
_ggmlContext = new GgmlContext(new[] { 0 }, GgmlBackendType.Cuda);
_allocator = new GgmlAllocator(_ggmlContext, 0);
break;
case BackendType.GgmlVulkan:
_ggmlContext = new GgmlContext(new[] { 0 }, GgmlBackendType.Vulkan);
_allocator = new GgmlAllocator(_ggmlContext, 0);
break;
case BackendType.Cuda:
_allocator = new CudaAllocator(0);
break;
case BackendType.Mlx:
MlxBackend.Register();
_allocator = new MlxAllocator(0);
break;
case BackendType.Cpu:
_allocator = new CpuAllocator(BlasEnum.DotNet);
break;
default:
throw new ArgumentException($"Unsupported backend: {backend}");
}
Console.WriteLine($"Backend: {backend}");
_gguf = new GgufFile(ggufPath);
}
protected bool IsGgmlBackend => ExecutionPlan.UsesGgmlBackend;
protected void EnsureQuantBackendAvailable()
{
if (_quantBackendReady || !IsGgmlBackend)
return;
GgmlBackendType backendType = _backend switch
{
BackendType.GgmlCpu => GgmlBackendType.Cpu,
BackendType.GgmlMetal => GgmlBackendType.Metal,
BackendType.GgmlCuda => GgmlBackendType.Cuda,
BackendType.GgmlVulkan => GgmlBackendType.Vulkan,
_ => throw new InvalidOperationException($"No GGML backend is associated with {_backend}."),
};
GgmlBasicOps.EnsureBackendAvailable(backendType);
_quantBackendReady = true;
}
protected void ParseBaseConfig()
{
string arch = Config.Architecture;
Config.NumLayers = (int)_gguf.GetUint32($"{arch}.block_count");
Config.HiddenSize = (int)_gguf.GetUint32($"{arch}.embedding_length");
Config.NumHeads = (int)_gguf.GetUint32($"{arch}.attention.head_count");
Config.NumKVHeads = (int)_gguf.GetUint32($"{arch}.attention.head_count_kv", (uint)Config.NumHeads);
Config.Eps = _gguf.GetFloat32($"{arch}.attention.layer_norm_rms_epsilon");
Config.RopeBase = _gguf.GetFloat32($"{arch}.rope.freq_base");
Config.RopeScale = _gguf.GetFloat32($"{arch}.rope.scaling.factor", 1f);
Config.ChatTemplate = _gguf.GetString("tokenizer.chat_template");
Config.KeyLength = (int)_gguf.GetUint32($"{arch}.attention.key_length", 0);
Config.ValueLength = (int)_gguf.GetUint32($"{arch}.attention.value_length", 0);
Config.IntermediateSize = (int)_gguf.GetUint32($"{arch}.feed_forward_length", 0);
}
protected int ResolveConfiguredContextLength(int fallback = 4096)
{
int? explicitOverride = null;
string source;
string ctxEnv = Environment.GetEnvironmentVariable("MAX_CONTEXT");
if (!string.IsNullOrWhiteSpace(ctxEnv) && int.TryParse(ctxEnv, out int envCtx) && envCtx > 0)
explicitOverride = envCtx;
int resolved = ResolveConfiguredContextLength(
Config?.Architecture ?? _gguf.GetString("general.architecture") ?? string.Empty,
_gguf.Metadata,
fallback,
explicitOverride,
out source);
if (explicitOverride.HasValue)
Console.WriteLine($"Context length: using MAX_CONTEXT={resolved}.");
else if (source == "fallback")
Console.WriteLine($"Context length: metadata missing, falling back to {resolved} tokens.");
else
Console.WriteLine($"Context length: using GGUF metadata {source}={resolved}.");
return resolved;
}
protected int ResolveInitialCacheAllocationLength(int requestedContextLength, int gpuDefault = 8192)
{
return ResolveInitialCacheAllocationLength(_backend, requestedContextLength, gpuDefault);
}
internal static int ResolveInitialCacheAllocationLength(BackendType backend, int requestedContextLength, int gpuDefault = 8192)
{
// GPU backends can be sensitive to allocating a multi-gigabyte KV
// cache up-front when the model advertises a 256K+ context window. Cap the initial
// allocation and let the cache grow on demand when actual prompts approach the
// limit. CPU backends have no such constraint and use the full requested length.
bool isGpuBackend =
backend == BackendType.Cuda ||
backend == BackendType.Mlx ||
backend == BackendType.GgmlCuda ||
backend == BackendType.GgmlVulkan ||
backend == BackendType.GgmlMetal;
if (isGpuBackend &&
string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("MAX_CONTEXT")))
{
// Direct GPU backends benefit from a smaller initial KV allocation so
// huge advertised contexts (for example 262k) do not reserve the entire
// GPU budget before the dynamic CPU/KV cache compressor activates.
// The cache grows on demand for longer sessions; users with persistent
// long contexts can override via MAX_CONTEXT to allocate the full window
// up-front.
int effectiveDefault = backend switch
{
BackendType.Mlx => Math.Min(gpuDefault, 2048),
BackendType.Cuda => Math.Min(gpuDefault, 2048),
// GgmlMetal: cap the up-front KV allocation too. On Apple
// Silicon the GPU working set is small (e.g. ~19 GB) and a
// big model (gpt-oss 20B Q8_0 ≈ 12 GB) plus a full 8192-token
// KV cache (≈6.4 GB) sits right at the limit. Once memory is
// that tight the OS continually purges wired buffers, so the
// residency-set keep-alive thread must constantly re-request
// residency for every buffer — holding the device residency
// lock that every per-op buffer alloc/free contends on, which
// collapses long-context decode to seconds/token (GPU idle).
// A smaller initial allocation (the cache still grows on
// demand) keeps headroom so residency stays cheap.
BackendType.GgmlMetal => Math.Min(gpuDefault, 2048),
_ => gpuDefault,
};
return Math.Min(requestedContextLength, effectiveDefault);
}
return requestedContextLength;
}
// GgmlVulkan follows GgmlCuda here: the fused prefill/decode paths mask or
// overwrite every cache position they read, so zero-filling 100s of MB of
// host KV arrays on every request reset is pure waste.
protected bool ShouldZeroFillCacheTensors =>
_backend != BackendType.GgmlCuda && _backend != BackendType.Mlx &&
_backend != BackendType.GgmlVulkan;
protected void InitializeCacheTensor(Tensor tensor)
{
// First allocation still zero-fills on every backend that keeps a host
// copy (including Vulkan): the fused kernels' flash-padding may read
// never-written cache rows, which must be finite.
if (tensor != null && (ShouldZeroFillCacheTensors || _backend == BackendType.GgmlVulkan))
Ops.Fill(tensor, 0f);
}
protected void ResetCacheTensor(Tensor tensor)
{
if (tensor == null)
return;
if (ShouldZeroFillCacheTensors)
Ops.Fill(tensor, 0f);
// On GgmlVulkan keep the resident device copy VALID across resets: the
// host copy was not touched above, so host and device stay consistent
// (both hold the previous request's bytes — semantically "empty"
// because _cacheSeqLen gates every read, exactly like GgmlCuda which
// has never zero-filled). Invalidation here caused every new request's
// first prefill to free + reallocate + re-upload the ENTIRE KV cache
// (~470 MB / ~170 ms per request on gemma4-12B over PCIe), which was
// the dominant server-TTFT overhead on the Vulkan backend.
if (_backend != BackendType.GgmlVulkan)
InvalidateTensorDeviceCache(tensor);
}
internal static int ResolveConfiguredContextLength(
string architecture,
IReadOnlyDictionary<string, object> metadata,
int fallback,
int? explicitOverride,
out string source)
{
if (explicitOverride.HasValue && explicitOverride.Value > 0)
{
source = "MAX_CONTEXT";
return explicitOverride.Value;
}
foreach (string key in GetContextLengthMetadataKeys(architecture))
{
if (TryGetPositiveInt(metadata, key, out int contextLength))
{
source = key;
return contextLength;
}
}
source = "fallback";
return fallback;
}
private static IEnumerable<string> GetContextLengthMetadataKeys(string architecture)
{
if (!string.IsNullOrWhiteSpace(architecture))
{
yield return $"{architecture}.context_length";
yield return $"{architecture}.attention.context_length";
yield return $"{architecture}.max_position_embeddings";
yield return $"{architecture}.max_sequence_length";
yield return $"{architecture}.sequence_length";
yield return $"{architecture}.seq_length";
yield return $"{architecture}.n_ctx";
yield return $"{architecture}.rope.scaling.original_context_length";
}
yield return "context_length";
yield return "max_position_embeddings";
yield return "max_sequence_length";
yield return "sequence_length";
yield return "seq_length";
yield return "n_ctx";
}
private static bool TryGetPositiveInt(IReadOnlyDictionary<string, object> metadata, string key, out int value)
{
value = 0;
if (metadata == null || string.IsNullOrWhiteSpace(key) || !metadata.TryGetValue(key, out var raw) || raw == null)
return false;
try
{
switch (raw)
{
case int i when i > 0:
value = i;
return true;
case uint ui when ui > 0:
value = (int)ui;
return true;
case long l when l > 0 && l <= int.MaxValue:
value = (int)l;
return true;
case ulong ul when ul > 0 && ul <= int.MaxValue:
value = (int)ul;
return true;
case int[] ia when ia.Length > 0 && ia[0] > 0:
value = ia[0];
return true;
case uint[] ua when ua.Length > 0 && ua[0] > 0 && ua[0] <= int.MaxValue:
value = (int)ua[0];
return true;
case long[] la when la.Length > 0 && la[0] > 0 && la[0] <= int.MaxValue:
value = (int)la[0];
return true;
case ulong[] ula when ula.Length > 0 && ula[0] > 0 && ula[0] <= int.MaxValue:
value = (int)ula[0];
return true;
default:
value = Convert.ToInt32(raw);
return value > 0;
}
}
catch
{
value = 0;
return false;
}
}
/// <summary>
/// Decide whether the tokenizer should prepend a BOS token when encoding a
/// prompt with <c>addSpecial=true</c>.
///
/// Normally this mirrors the GGUF's <c>tokenizer.ggml.add_bos_token</c> flag.
/// However, some GGUF conversions (notably several Gemma 4 builds, e.g.
/// gemma-4-31B IQ2_M) set <c>add_bos_token=false</c> and instead rely on the
/// chat template's leading <c>{{ bos_token }}</c> to emit the
/// beginning-of-sequence marker. TensorSharp always renders <c>bos_token</c> as
/// an empty string (and its hardcoded chat renderers deliberately omit a literal
/// BOS to avoid a double BOS when the tokenizer owns it), so for such models the
/// rendered prompt would otherwise carry NO BOS at all. A Gemma-family model
/// with a missing BOS degenerates into repetition / off-topic output. When the
/// template declares a leading BOS but the tokenizer is configured not to add
/// one, let the tokenizer own it so the prompt still begins with exactly one BOS
/// (the empty-rendered <c>bos_token</c> guarantees we never double it).
/// </summary>
public static bool ResolveAddBosToken(bool addBosFromMetadata, int bosTokenId, string? chatTemplate)
{
if (addBosFromMetadata)
return true;
if (bosTokenId < 0)
return false;
return !string.IsNullOrEmpty(chatTemplate)
&& chatTemplate.Contains("bos_token", StringComparison.Ordinal);
}
// llama.cpp's vocabulary loader treats these control-token spellings as
// end-of-generation even when a GGUF converter only records one of them
// in tokenizer.ggml.eos_token_id. Qwen3.5 is a concrete example: its
// metadata names <|im_end|>, while <|endoftext|> is also a valid EOG.
private static readonly HashSet<string> TextualEogTokens = new(StringComparer.Ordinal)
{
"<|eot_id|>",
"<|im_end|>",
"<|end|>",
"<|return|>",
"<|call|>",
"<|flush|>",
"<|calls|>",
"<end_of_turn>",
"<|endoftext|>",
"</s>",
"<|eom_id|>",
"<EOT>",
"_<EOT>",
"[EOT]",
"[EOS]",
"<|end_of_text|>",
"<end_of_utterance>",
"<eos>",
"<turn|>",
"<|tool_response>",
"<|end▁of▁sentence|>",
};
/// <summary>
/// Augment the GGUF EOS list with llama-compatible, text-discovered EOG
/// controls. Public for tokenizer regression tests.
/// </summary>
public static int[] ResolveEogTokenIds(
IReadOnlyList<string> vocabTokens,
int eosId,
IEnumerable<int>? extraEosIds = null)
{
var ids = new HashSet<int>();
if (eosId >= 0 && eosId < vocabTokens.Count)
ids.Add(eosId);
if (extraEosIds != null)
{
foreach (int id in extraEosIds)
if (id >= 0 && id < vocabTokens.Count)
ids.Add(id);
}
for (int id = 0; id < vocabTokens.Count; id++)
{
if (TextualEogTokens.Contains(vocabTokens[id]))
ids.Add(id);
}
// Match llama.cpp's tokenizer-specific EOG workarounds. Harmony
// and Solar use <|end|> as a structural marker rather than a stop;
// Gemma4/PaddleOCR similarly use </s> as ordinary vocabulary when
// the tool-response control token is present.
int endId = -1;
int slashSId = -1;
bool hasReturn = false;
bool hasCall = false;
bool hasFlush = false;
bool hasToolResponse = false;
foreach (int id in ids)
{
switch (vocabTokens[id])
{
case "<|return|>": hasReturn = true; break;
case "<|call|>":
case "<|calls|>": hasCall = true; break;
case "<|flush|>": hasFlush = true; break;
case "<|end|>": endId = id; break;
case "<|tool_response>": hasToolResponse = true; break;
case "</s>": slashSId = id; break;
}
}
if (endId >= 0 && ((hasReturn && hasCall) || (hasCall && hasFlush)))
ids.Remove(endId);
if (slashSId >= 0 && hasToolResponse)
ids.Remove(slashSId);
var result = new int[ids.Count];
ids.CopyTo(result);
Array.Sort(result);
return result;
}
protected void ParseTokenizer()
{
var vocabTokens = _gguf.GetStringArray("tokenizer.ggml.tokens");
Config.VocabSize = vocabTokens.Length;
var tokenTypes = _gguf.GetInt32Array("tokenizer.ggml.token_type");
int bosId = (int)_gguf.GetUint32("tokenizer.ggml.bos_token_id");
int eosId = (int)_gguf.GetUint32("tokenizer.ggml.eos_token_id");
bool addBosMetadata = _gguf.GetBool("tokenizer.ggml.add_bos_token", false);
bool addEos = _gguf.GetBool("tokenizer.ggml.add_eos_token", false);
bool addBos = ResolveAddBosToken(addBosMetadata, bosId, _gguf.GetString("tokenizer.chat_template"));
if (addBos && !addBosMetadata)
{
Console.WriteLine(
" Tokenizer: add_bos_token=false but chat template emits bos_token; " +
"enabling BOS so the prompt starts with exactly one BOS.");
}
var extraEos = _gguf.GetInt32Array("tokenizer.ggml.eos_token_ids");
var eosIds = new List<int>(ResolveEogTokenIds(vocabTokens, eosId, extraEos));
string tokenizerModel = _gguf.GetString("tokenizer.ggml.model", "gpt2");
if (tokenizerModel == "llama" || tokenizerModel == "t5" || tokenizerModel == "gemma4")
{
var scores = _gguf.GetFloatArray("tokenizer.ggml.scores");
int eotId = (int)_gguf.GetUint32("tokenizer.ggml.eot_token_id", 106);
if (!eosIds.Contains(eotId))
eosIds.Add(eotId);
Tokenizer = new SentencePieceTokenizer(vocabTokens, tokenTypes, scores,
bosId, eosIds.ToArray(), addBos, addEos);
}
else
{
var merges = _gguf.GetStringArray("tokenizer.ggml.merges");
string preType = _gguf.GetString("tokenizer.ggml.pre", null);
Tokenizer = new BpeTokenizer(vocabTokens, tokenTypes, merges,
bosId, eosIds.ToArray(), addBos, addEos, preType);
}
}
protected virtual bool IsQuantizedLinearWeight(GgufTensorInfo info)
{
return ExecutionPlan.ShouldStoreWeightQuantized(info);
}
internal static bool ShouldStoreWeightQuantized(BackendType backend, GgufTensorInfo info)
{
if (info.Type == GgmlTensorType.F32)
return false;
if (backend == BackendType.Cuda && !CanStoreDirectCudaCompressedWeight(info.Type))
return false;
if (backend == BackendType.Cpu && !ManagedQuantizedOps.SupportsCpuQuantizedStorage(info.Type))
return false;
if (backend == BackendType.Mlx && !MlxQuantizedOps.SupportsQuantizedType(info.Type))
return false;
if (info.Shape.Length == 2)
return true;
return info.Shape.Length == 3 && info.Name.Contains("_exps.");
}
private static bool CanStoreDirectCudaCompressedWeight(GgmlTensorType type)
{
return type switch
{
GgmlTensorType.F16 or
GgmlTensorType.BF16 or
GgmlTensorType.Q4_0 or
GgmlTensorType.Q4_1 or
GgmlTensorType.Q5_0 or
GgmlTensorType.Q5_1 or
GgmlTensorType.Q8_0 or
GgmlTensorType.Q8_1 or
GgmlTensorType.Q2_K or
GgmlTensorType.Q3_K or
GgmlTensorType.Q4_K or
GgmlTensorType.Q5_K or
GgmlTensorType.Q6_K or
GgmlTensorType.Q8_K or
GgmlTensorType.IQ2_XXS or
GgmlTensorType.IQ2_XS or
GgmlTensorType.IQ3_XXS or
GgmlTensorType.IQ1_S or
GgmlTensorType.IQ4_NL or
GgmlTensorType.IQ3_S or
GgmlTensorType.IQ2_S or
GgmlTensorType.IQ4_XS or
GgmlTensorType.IQ1_M or
GgmlTensorType.TQ1_0 or
GgmlTensorType.TQ2_0 or
GgmlTensorType.MXFP4 => true,
_ => false,
};
}
/// <summary>
/// Whether quantized weights for this backend can be backed directly by the GGUF file
/// via memory mapping instead of being copied into freshly-allocated host buffers.
///
/// On Apple Silicon (Metal, integrated GPU, unified memory) and on the GGML CPU backend
/// the on-disk layout matches what the kernels consume verbatim, so we can skip the
/// per-tensor copy and let the OS page in / out of the file as needed. This roughly
/// halves the resident set for large quantized models (e.g. ~10 GB GGUF files no longer
/// need a second 10 GB native heap copy).
///
/// On discrete CUDA GPUs the kernels still want device-local memory, but the original
/// host pointer is needed once at preload time so the device copy is performed via
/// <see cref="PrepareCudaQuantizedWeightsForInference"/> from the file-backed view.
/// </summary>
protected bool CanUseFileMappedQuantizedWeights
=> _backend == BackendType.GgmlCuda
|| _backend == BackendType.GgmlVulkan
|| _backend == BackendType.Cuda
|| _backend == BackendType.Mlx
|| _backend == BackendType.GgmlMetal
|| _backend == BackendType.GgmlCpu;
protected void LoadWeights()
{
Console.Write("Loading model weights...");
int countF32 = 0;
int countQuant = 0;
long totalQuantBytes = 0;
long totalF32Bytes = 0;
long mappedQuantBytes = 0;
bool tryMmap = CanUseFileMappedQuantizedWeights;
foreach (var kv in _gguf.Tensors)
{