-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathGptOssModel.cs
More file actions
2733 lines (2463 loc) · 128 KB
/
Copy pathGptOssModel.cs
File metadata and controls
2733 lines (2463 loc) · 128 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.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using TensorSharp;
using TensorSharp.Cuda;
using TensorSharp.GGML;
using TensorSharp.MLX;
namespace TensorSharp.Models
{
/// <summary>
/// GPT OSS (Mixture-of-Experts) transformer model.
/// Key features:
/// - MoE FFN with TopK routing + softmax on selected experts
/// - Alternating SWA (even layers) / full causal (odd layers) attention
/// - Attention sinks for SWA layers
/// - SiLU with alpha scaling and clamping (SiLUAlphaLimit)
/// - RoPE NeoX with yarn scaling
/// - Bias on all attention and FFN projections
/// Optimizations:
/// - Fused QKV projection (3 matmuls -> 1)
/// - Expert batching in MoE (N*K matmuls -> up to numExperts batched matmuls)
/// - Pre-computed weight name strings (zero allocation per forward)
/// - Cached attention sinks arrays
/// - SIMD-vectorized bias addition and activation
/// </summary>
public partial class GptOssModel : ModelBase
{
// Bound the MLX lazy-graph depth across the per-layer dispatch loop.
// Override via TS_MLX_EVAL_EVERY_N_LAYERS. GptOss has 24 layers; eval=16
// means one boundary at layer 16.
private static readonly int MlxEvalEveryNLayers = ResolveMlxEvalEveryNLayers();
private static int ResolveMlxEvalEveryNLayers()
{
string env = Environment.GetEnvironmentVariable("TS_MLX_EVAL_EVERY_N_LAYERS");
if (!string.IsNullOrWhiteSpace(env) && int.TryParse(env, out int v) && v > 0)
return v;
return 16;
}
// Minimum total sequence length to use the MLX device-side decode
// attention with sinks. Default 1 (always-on). Empirically the
// device-side kernel beats the host SIMD CPU path even at short
// kvLen (~300) on M-series — measured +23% decode tok/s on
// gpt-oss-20B Q8_0 — and the win grows with kvLen since the host
// path scales linearly with kvLen on the multi-GB cache download.
// Override via TS_MLX_SINKS_ATTN_MIN_KV_LEN if a workload regresses.
private static readonly int MlxSinksAttnMinKvLen = ResolveMlxSinksAttnMinKvLen();
private static int ResolveMlxSinksAttnMinKvLen()
{
string env = Environment.GetEnvironmentVariable("TS_MLX_SINKS_ATTN_MIN_KV_LEN");
if (!string.IsNullOrWhiteSpace(env) && int.TryParse(env, out int v) && v > 0)
return v;
return 1;
}
// Decode (seqLen == 1) reuses the fused on-device attention-layer kernel
// (TSGgml_GptOssAttentionLayerPrefill) instead of the legacy per-op path
// whose attention runs on the host CPU (KV-cache pull + CPU softmax per
// layer). The fused kernel collapses RMSNorm + QKV + RoPE + KV append +
// masked softmax-with-sinks + attention + O-proj + residual into ONE GGML
// graph dispatch with GPU flash-attention — the biggest gpt-oss decode
// lever, since Metal decode is dispatch-overhead bound. It re-uploads the
// KV prefix [0,startPos) per call, so it is gated by context length to
// keep that O(context) upload cheap relative to the compute it saves;
// longer contexts fall back to the proven host path. Both knobs are
// env-tunable (TS_GPTOSS_FUSED_DECODE=0 disables; TS_GPTOSS_FUSED_DECODE_MAX_CTX).
private static readonly bool FusedDecodeAttnEnabled =
!string.Equals(Environment.GetEnvironmentVariable("TS_GPTOSS_FUSED_DECODE"), "0", StringComparison.Ordinal);
private static readonly int FusedDecodeAttnMaxContext = ResolveFusedDecodeMaxContext();
private static int ResolveFusedDecodeMaxContext()
{
string env = Environment.GetEnvironmentVariable("TS_GPTOSS_FUSED_DECODE_MAX_CTX");
if (!string.IsNullOrWhiteSpace(env) && int.TryParse(env, out int v) && v > 0)
return v;
return 4096;
}
// Maximum seqLen the fused on-device attention-layer kernel
// (TSGgml_GptOssAttentionLayerPrefill) is dispatched at. Above this,
// Forward() chunks the prompt into <=this-many-token sub-batches so the
// attention always runs on the fused path. The legacy per-op fallback
// builds an O(seqLen^2) host scores tensor per layer (e.g. a 1253-token
// prompt = ~200 MB/layer x 24 layers) which is both ~8x slower than the
// fused kernel AND saturates the Metal working set on Apple Silicon,
// triggering kIOGPUCommandBufferCallbackErrorOutOfMemory. Tunable via
// TS_GPTOSS_FUSED_ATTN_MAX_SEQ for A/B testing.
private static readonly int FusedAttnMaxSeqLen = ResolveFusedAttnMaxSeqLen();
private static int ResolveFusedAttnMaxSeqLen()
{
string env = Environment.GetEnvironmentVariable("TS_GPTOSS_FUSED_ATTN_MAX_SEQ");
if (!string.IsNullOrWhiteSpace(env) && int.TryParse(env, out int v) && v > 0)
return v;
return 256;
}
// MLX batched MoE FFN via mlx_gather_qmm over the stacked experts
// (TryMoEMlxGatherQmm): 3 grouped-GEMM dispatches + 2 fused kernels
// per layer instead of the per-active-expert ExpertFFN loop (K
// experts x {gate_up matmul, host SwiGLU with 2 device->host syncs,
// down matmul} per token). TS_GPTOSS_MLX_MOE_GQMM=0 restores the
// per-expert path for an A/B (process restart required — stacked
// weights and preload decisions are made once at load).
// Mode: 1 (default) batched path on; 0 fully off (legacy per-expert
// path with eager per-expert preload — the pre-existing behavior);
// 2 diagnostic: preload veto + stacked build as in mode 1 but the
// batched compute disabled, so the legacy path runs with lazily
// converted per-expert weights.
private static readonly int MlxMoeGqmmMode = ResolveMlxMoeGqmmMode();
private static int ResolveMlxMoeGqmmMode()
{
string env = Environment.GetEnvironmentVariable("TS_GPTOSS_MLX_MOE_GQMM");
if (int.TryParse(env, out int v) && v >= 0 && v <= 2)
return v;
return 1;
}
private static readonly bool MlxMoeGatherQmmEnabled = MlxMoeGqmmMode != 0;
private Tensor[] _kvCacheK;
private Tensor[] _kvCacheV;
private int _numExperts;
private int _numExpertsUsed;
private int _slidingWindow;
private int _expertFfnLength;
private const float SiluAlpha = 1.702f;
private const float SiluLimit = 7.0f;
private string[][] _layerNames;
private string[][][] _expertNames;
private float[][] _layerSinks;
// Per-layer MLX-backed 1D Float32 [numHeads] tensor mirror of
// _layerSinks for the device-side decode path. Lazily populated on
// first use; reused across decode calls.
private Tensor[] _layerSinksMlx;
private int _qDim, _kDim;
private bool _isQkvFused;
private int[] _moeExpertCounts;
private int[] _moeExpertOffsets;
private int[] _moeTokenMap;
private float[] _moeWeightMap;
// Pooled per-call scratch for MoE routing. Reallocated lazily when the
// current request needs a larger seqLen (prefill). Decode reuses the
// same buffers across all layers/steps, eliminating the per-call
// float[]/int[] allocation in MoERoute().
private float[] _moeRoutingWeightsScratch;
private int[] _moeSelectedExpertsScratch;
private int[] _moeTopKScratch;
// Per-layer stacked-along-experts views into the original `ffn_gate_exps.weight`,
// `ffn_up_exps.weight`, `ffn_down_exps.weight` 3D blocks (loaded into
// `ModelBase._stackedExpertWeights`). Used by the fused MoE prefill kernel
// (TryMoEPrefillFused) to dispatch one ggml_cgraph per layer (with
// ggml_mul_mat_id + ggml_add_id + swiglu_oai) instead of looping over
// active experts per token. FuseExpertGateUpWeights leaves these
// per-expert SLICED `_quantWeights` entries gone but the underlying
// 3D stacked storage is untouched (FuseExpertGateUpWeights only
// disposes the per-expert *views*, not the bulk buffer).
private StackedExpertWeights[] _layerStackedGate;
private StackedExpertWeights[] _layerStackedUp;
private StackedExpertWeights[] _layerStackedDown;
// Per-layer stacked biases for the fused MoE prefill kernel. Layout is
// contiguous [bias_dim, num_experts] f32 so that the kernel can hand
// them directly to ggml_add_id (which expects ne0=bias_dim, ne1=num_experts).
// Built once at init time from `ffn_gate_up_exps.{e}.bias` (already
// gate || up concatenated by FuseExpertGateUpWeights, size 2*n_ff) and
// `ffn_down_exps.{e}.bias` (hidden_dim).
private float[][] _layerGateUpBiasStacked; // shape [2*n_ff * num_experts] per layer
private float[][] _layerDownBiasStacked; // shape [hidden_dim * num_experts] per layer
private int _layerStackedReady; // 1 once InitMoeStackedWeights has run
// Per-layer MLX-resident stacked expert biases for the batched MLX MoE
// path (TryMoEMlxGatherQmm): gate/up [E, n_ff] split out of
// _layerGateUpBiasStacked, down [E, hidden] from _layerDownBiasStacked.
// Lazily built on first use per layer; reused across decode steps.
private Tensor[] _moeGateBiasMlx;
private Tensor[] _moeUpBiasMlx;
private Tensor[] _moeDownBiasMlx;
public GptOssModel(string ggufPath, BackendType backend, int tpDegree = 1, ITensorParallelGroup tpGroup = null)
: base(ggufPath, backend, tpDegree, tpGroup)
{
string arch = _gguf.GetString("general.architecture") ?? "gpt-oss";
Config = new ModelConfig { Architecture = arch };
ParseBaseConfig();
_numExperts = (int)_gguf.GetUint32($"{arch}.expert_count", 0);
_numExpertsUsed = (int)_gguf.GetUint32($"{arch}.expert_used_count", 0);
_slidingWindow = (int)_gguf.GetUint32($"{arch}.attention.sliding_window", 128);
_expertFfnLength = (int)_gguf.GetUint32($"{arch}.expert_feed_forward_length", 0);
Config.NumExperts = _numExperts;
Config.NumExpertsUsed = _numExpertsUsed;
Config.SlidingWindow = _slidingWindow;
Config.OriginalContextLength = (int)_gguf.GetUint32($"{arch}.rope.scaling.original_context_length", 4096);
ParseTokenizer();
Console.WriteLine($"Model: {arch}, Layers={Config.NumLayers}, Hidden={Config.HiddenSize}, " +
$"Heads={Config.NumHeads}, KVHeads={Config.NumKVHeads}, HeadDim={Config.HeadDim}, Vocab={Config.VocabSize}");
Console.WriteLine($"RoPE base={Config.RopeBase}, scale={Config.RopeScale}, eps={Config.Eps}");
Console.WriteLine($"MoE: {_numExperts} experts, {_numExpertsUsed} used, " +
$"SlidingWindow={_slidingWindow}, ExpertFFN={_expertFfnLength}");
LoadWeights();
SplitExpertBiases();
// Snapshot the gate/up biases per expert BEFORE FuseExpertGateUpWeights
// disposes them — we need them in their original split shape to build
// the stacked-by-expert bias tables for the fused MoE prefill kernel.
float[][] preFuseGateBias = SnapshotPerExpertBiases("ffn_gate_exps", _expertFfnLength);
float[][] preFuseUpBias = SnapshotPerExpertBiases("ffn_up_exps", _expertFfnLength);
FuseExpertGateUpWeights();
FuseQKVWeights();
// Before the TP sharding, not after: whole-expert partitioning is
// built from these stacked tensors, so the sharder has to be able to
// ask whether they exist (see BuildGptOssExpertParallelShards).
InitMoeStackedWeights(preFuseGateBias, preFuseUpBias);
if (IsTensorParallel)
{
ValidateGptOssTpConstraints();
ShardGptOssWeightsForTP();
PrepareCudaQuantizedWeightsForInferenceTP();
}
else
{
PrepareCudaQuantizedWeightsForInference();
PrepareMlxStackedMoeWeights();
}
int maxContextLength = ResolveConfiguredContextLength();
int initialCacheLength = ResolveInitialCacheAllocationLength(maxContextLength);
if (initialCacheLength < maxContextLength)
Console.WriteLine($"Initial {_backend} KV cache allocation: {initialCacheLength} tokens (grows on demand up to {maxContextLength}).");
if (IsTensorParallel)
InitGptOssTpKVCache(initialCacheLength, maxContextLength);
else
InitKVCache(initialCacheLength, maxContextLength);
PrecomputeConstants();
}
// Build a per-(layer,expert) snapshot of bias arrays before FuseExpertGateUpWeights
// collapses them. Returns float[layer][expert*biasDim + d]. Caller is
// responsible for dimension consistency. Returns null if no biases found
// for the first layer (some MoE models don't ship gate/up biases).
private float[][] SnapshotPerExpertBiases(string kind, int biasDim)
{
int numLayers = Config.NumLayers;
float[][] result = new float[numLayers][];
bool any = false;
for (int l = 0; l < numLayers; l++)
{
float[] perLayer = new float[biasDim * _numExperts];
bool layerHasAny = false;
for (int e = 0; e < _numExperts; e++)
{
string biasName = $"blk.{l}.{kind}.{e}.bias";
if (_weights.TryGetValue(biasName, out var biasTensor) && biasTensor != null)
{
float[] biasData = TensorToFloatArray(biasTensor);
int copyLen = Math.Min(biasData.Length, biasDim);
Array.Copy(biasData, 0, perLayer, e * biasDim, copyLen);
layerHasAny = true;
}
}
result[l] = layerHasAny ? perLayer : null;
any |= layerHasAny;
}
return any ? result : null;
}
// Build per-layer stacked weight + bias views for the fused MoE prefill
// kernel (TryMoEPrefillFused). Stacked weights are zero-cost views into
// the original 3D `_exps.weight` blocks loaded by ModelBase. Stacked
// biases are small contiguous f32 arrays built once from the per-expert
// biases captured prior to FuseExpertGateUpWeights.
private unsafe void InitMoeStackedWeights(float[][] preFuseGateBias, float[][] preFuseUpBias)
{
int numLayers = Config.NumLayers;
int hidden = Config.HiddenSize;
int nFf = _expertFfnLength;
_layerStackedGate = new StackedExpertWeights[numLayers];
_layerStackedUp = new StackedExpertWeights[numLayers];
_layerStackedDown = new StackedExpertWeights[numLayers];
_layerGateUpBiasStacked = new float[numLayers][];
_layerDownBiasStacked = new float[numLayers][];
int gotWeights = 0;
int gotBiases = 0;
for (int l = 0; l < numLayers; l++)
{
string p = $"blk.{l}.";
_stackedExpertWeights.TryGetValue(p + "ffn_gate_exps.weight", out _layerStackedGate[l]);
_stackedExpertWeights.TryGetValue(p + "ffn_up_exps.weight", out _layerStackedUp[l]);
_stackedExpertWeights.TryGetValue(p + "ffn_down_exps.weight", out _layerStackedDown[l]);
if (_layerStackedGate[l] != null && _layerStackedUp[l] != null && _layerStackedDown[l] != null)
gotWeights++;
if (preFuseGateBias != null && preFuseUpBias != null
&& preFuseGateBias[l] != null && preFuseUpBias[l] != null)
{
// Stack gate || up bias per expert into a contiguous
// [2*n_ff, num_experts] f32 array (gate first n_ff, then up).
// ggml_add_id reads bias[d, ids[u, t]] so layout must match
// expert e occupying offset e * (2*n_ff).
float[] fused = new float[2 * nFf * _numExperts];
for (int e = 0; e < _numExperts; e++)
{
int dst = e * 2 * nFf;
Array.Copy(preFuseGateBias[l], e * nFf, fused, dst, nFf);
Array.Copy(preFuseUpBias[l], e * nFf, fused, dst + nFf, nFf);
}
_layerGateUpBiasStacked[l] = fused;
gotBiases++;
}
// Down biases live in `_weights[blk.{l}.ffn_down_exps.{e}.bias]`
// as f32 [1, hidden_dim]. Stack them across experts for the kernel.
bool hasDownBias = false;
float[] downStack = new float[hidden * _numExperts];
for (int e = 0; e < _numExperts; e++)
{
string downBiasName = $"blk.{l}.ffn_down_exps.{e}.bias";
if (_weights.TryGetValue(downBiasName, out var bt) && bt != null)
{
float[] bd = TensorToFloatArray(bt);
Array.Copy(bd, 0, downStack, e * hidden, Math.Min(bd.Length, hidden));
hasDownBias = true;
}
}
if (hasDownBias)
_layerDownBiasStacked[l] = downStack;
}
_layerStackedReady = (gotWeights == numLayers) ? 1 : 0;
if (gotWeights > 0)
{
Console.WriteLine($" Fused MoE prefill: stacked weights ready for {gotWeights}/{numLayers} layers, " +
$"stacked gate/up biases for {gotBiases}/{numLayers} layers");
}
}
#region Weight Fusion and Pre-computation
private void SplitExpertBiases()
{
int split = 0;
for (int l = 0; l < Config.NumLayers; l++)
{
foreach (string kind in new[] { "ffn_gate_exps", "ffn_up_exps", "ffn_down_exps" })
{
string biasName = $"blk.{l}.{kind}.bias";
if (!_weights.TryGetValue(biasName, out var biasTensor))
continue;
int numExp = (int)biasTensor.Sizes[0];
int biasDim = (int)biasTensor.Sizes[1];
float[] biasData = TensorToFloatArray(biasTensor);
for (int e = 0; e < numExp; e++)
{
float[] expertBias = new float[biasDim];
for (int d = 0; d < biasDim; d++)
expertBias[d] = biasData[e * biasDim + d];
_weights[$"blk.{l}.{kind}.{e}.bias"] = CreateFloatTensor(expertBias, 1, biasDim);
}
_weights.Remove(biasName);
biasTensor.Dispose();
split++;
}
}
if (split > 0)
Console.WriteLine($" Split expert biases: {split} tensors");
}
private unsafe void FuseExpertGateUpWeights()
{
int fused = 0;
for (int l = 0; l < Config.NumLayers; l++)
{
for (int e = 0; e < _numExperts; e++)
{
string gateName = $"blk.{l}.ffn_gate_exps.{e}.weight";
string upName = $"blk.{l}.ffn_up_exps.{e}.weight";
string fusedName = $"blk.{l}.ffn_gate_up_exps.{e}.weight";
if (_quantWeights.TryGetValue(gateName, out var gw) &&
_quantWeights.TryGetValue(upName, out var uw) &&
gw.GgmlType == uw.GgmlType && gw.Ne0 == uw.Ne0)
{
// ExpertFFN expects a fused gate_up tensor at fusedName. If
// MLX view-fusion fails (gate/up not contiguous in GGUF),
// fall back to copy — same rationale as FuseGateUpWeights.
if (!TryCreateFusedQuantizedWeight(out QuantizedWeight fusedWeight, gw, uw))
fusedWeight = QuantizedWeight.ConcatOrCreateCopy(gw, uw);
_quantWeights[fusedName] = fusedWeight;
_quantWeights.Remove(gateName); gw.Dispose();
_quantWeights.Remove(upName); uw.Dispose();
fused++;
}
else if (_weights.TryGetValue(gateName, out var gf) &&
_weights.TryGetValue(upName, out var uf))
{
int gateDim = (int)gf.Sizes[0], upDim = (int)uf.Sizes[0];
int inDim = (int)gf.Sizes[1];
var fusedTensor = new Tensor(_allocator, DType.Float32, gateDim + upDim, inDim);
using (var s0 = fusedTensor.Narrow(0, 0, gateDim)) Ops.Copy(s0, gf);
using (var s1 = fusedTensor.Narrow(0, gateDim, upDim)) Ops.Copy(s1, uf);
_weights[fusedName] = fusedTensor;
_weights.Remove(gateName); gf.Dispose();
_weights.Remove(upName); uf.Dispose();
fused++;
}
string gateBias = $"blk.{l}.ffn_gate_exps.{e}.bias";
string upBias = $"blk.{l}.ffn_up_exps.{e}.bias";
string fusedBias = $"blk.{l}.ffn_gate_up_exps.{e}.bias";
if (_weights.TryGetValue(gateBias, out var gb) &&
_weights.TryGetValue(upBias, out var ub))
{
int gbDim = (int)gb.Sizes[1], ubDim = (int)ub.Sizes[1];
float[] gbData = TensorToFloatArray(gb);
float[] ubData = TensorToFloatArray(ub);
float[] fusedData = new float[gbDim + ubDim];
Array.Copy(gbData, 0, fusedData, 0, gbDim);
Array.Copy(ubData, 0, fusedData, gbDim, ubDim);
_weights[fusedBias] = CreateFloatTensor(fusedData, 1, gbDim + ubDim);
_weights.Remove(gateBias); gb.Dispose();
_weights.Remove(upBias); ub.Dispose();
}
}
}
if (fused > 0)
Console.WriteLine($" Fused expert Gate+Up projections: {fused}");
}
/// <summary>
/// Decide whether load-time QKV fusion can run for EVERY layer, so the
/// model-wide <c>_isQkvFused</c> flag stays truthful. Community/UD
/// requants pick quant types per tensor (unsloth's gpt-oss Q4_K_M keeps
/// attn_v at Q8_0 on half the layers while the rest are Q5_0), so a
/// per-layer fusion decision produced a model where blk.3 only had
/// attn_qkv.weight while the layer-name table — keyed off blk.0, which
/// did NOT fuse — asked for blk.3.attn_q.weight: a null projection and
/// an abort (exit 134) on the first forward. Fusing all layers or none
/// removes that mixed state. Static and type-driven so the policy is
/// unit-testable without a model file.
/// </summary>
internal static bool CanFuseAllQkvLayers(
int numLayers,
Func<int, (int ggmlType, long ne0)?> quantInfo, // per (layer, proj 0=q/1=k/2=v)
Func<int, bool> floatTripletPresent)
{
for (int l = 0; l < numLayers; l++)
{
var q = quantInfo(l * 3 + 0);
var k = quantInfo(l * 3 + 1);
var v = quantInfo(l * 3 + 2);
bool quantFusable = q.HasValue && k.HasValue && v.HasValue &&
q.Value.ggmlType == k.Value.ggmlType && k.Value.ggmlType == v.Value.ggmlType &&
q.Value.ne0 == k.Value.ne0 && k.Value.ne0 == v.Value.ne0;
if (!quantFusable && !floatTripletPresent(l))
return false;
}
return true;
}
private unsafe void FuseQKVWeights()
{
// All-or-nothing: see CanFuseAllQkvLayers. Note the bias fusion below
// must ride along with the weight fusion — fusing the biases of an
// UNfused layer removes attn_q/k/v.bias, and the separate-QKV forward
// (which looks the biases up by name and treats "missing" as "none")
// then silently drops every attention projection bias. GPT-OSS has a
// bias on all projections, so that degenerates the model into
// template-token loops on every backend.
bool allFusable = CanFuseAllQkvLayers(
Config.NumLayers,
idx =>
{
int l = idx / 3;
string[] names = { $"blk.{l}.attn_q.weight", $"blk.{l}.attn_k.weight", $"blk.{l}.attn_v.weight" };
return _quantWeights.TryGetValue(names[idx % 3], out var w)
? (w.GgmlType, w.Ne0)
: ((int, long)?)null;
},
l => _weights.ContainsKey($"blk.{l}.attn_q.weight") &&
_weights.ContainsKey($"blk.{l}.attn_k.weight") &&
_weights.ContainsKey($"blk.{l}.attn_v.weight"));
if (!allFusable)
{
if (_quantWeights.ContainsKey("blk.0.attn_q.weight") || _weights.ContainsKey("blk.0.attn_q.weight"))
Console.WriteLine(" QKV fusion skipped: per-layer quant types differ (community requant); keeping separate Q/K/V projections and biases.");
return;
}
int fused = 0;
for (int l = 0; l < Config.NumLayers; l++)
{
string qName = $"blk.{l}.attn_q.weight";
string kName = $"blk.{l}.attn_k.weight";
string vName = $"blk.{l}.attn_v.weight";
string qkvName = $"blk.{l}.attn_qkv.weight";
bool layerFused = false;
if (_quantWeights.TryGetValue(qName, out var qw) &&
_quantWeights.TryGetValue(kName, out var kw) &&
_quantWeights.TryGetValue(vName, out var vw) &&
qw.GgmlType == kw.GgmlType && kw.GgmlType == vw.GgmlType &&
qw.Ne0 == kw.Ne0 && kw.Ne0 == vw.Ne0)
{
if (!TryCreateFusedQuantizedWeight(out QuantizedWeight fusedWeight, qw, kw, vw))
continue;
_quantWeights[qkvName] = fusedWeight;
_quantWeights.Remove(qName); qw.Dispose();
_quantWeights.Remove(kName); kw.Dispose();
_quantWeights.Remove(vName); vw.Dispose();
fused++;
layerFused = true;
}
else if (_weights.TryGetValue(qName, out var qf) &&
_weights.TryGetValue(kName, out var kf) &&
_weights.TryGetValue(vName, out var vf))
{
int qDim = (int)qf.Sizes[0], kDim = (int)kf.Sizes[0], vDim = (int)vf.Sizes[0];
int inDim = (int)qf.Sizes[1];
var fusedTensor = new Tensor(_allocator, DType.Float32, qDim + kDim + vDim, inDim);
using (var s0 = fusedTensor.Narrow(0, 0, qDim)) Ops.Copy(s0, qf);
using (var s1 = fusedTensor.Narrow(0, qDim, kDim)) Ops.Copy(s1, kf);
using (var s2 = fusedTensor.Narrow(0, qDim + kDim, vDim)) Ops.Copy(s2, vf);
_weights[qkvName] = fusedTensor;
_weights.Remove(qName); qf.Dispose();
_weights.Remove(kName); kf.Dispose();
_weights.Remove(vName); vf.Dispose();
fused++;
layerFused = true;
}
// Fuse the biases ONLY when this layer's weights fused: an
// orphaned attn_qkv.bias next to separate attn_q/k/v weights is
// invisible to the separate-QKV forward, which drops the biases.
if (!layerFused)
continue;
string qBias = $"blk.{l}.attn_q.bias";
string kBias = $"blk.{l}.attn_k.bias";
string vBias = $"blk.{l}.attn_v.bias";
string qkvBias = $"blk.{l}.attn_qkv.bias";
if (_weights.TryGetValue(qBias, out var qb) &&
_weights.TryGetValue(kBias, out var kb) &&
_weights.TryGetValue(vBias, out var vb))
{
int qbDim = (int)qb.ElementCount();
int kbDim = (int)kb.ElementCount();
int vbDim = (int)vb.ElementCount();
float[] qbData = TensorToFloatArray(qb);
float[] kbData = TensorToFloatArray(kb);
float[] vbData = TensorToFloatArray(vb);
float[] fusedData = new float[qbDim + kbDim + vbDim];
Array.Copy(qbData, 0, fusedData, 0, qbDim);
Array.Copy(kbData, 0, fusedData, qbDim, kbDim);
Array.Copy(vbData, 0, fusedData, qbDim + kbDim, vbDim);
_weights[qkvBias] = CreateFloatTensor(fusedData, 1, qbDim + kbDim + vbDim);
_weights.Remove(qBias); qb.Dispose();
_weights.Remove(kBias); kb.Dispose();
_weights.Remove(vBias); vb.Dispose();
}
}
if (fused > 0)
Console.WriteLine($" Fused projections: {fused} QKV");
}
private void PrecomputeConstants()
{
int numLayers = Config.NumLayers;
_qDim = Config.NumHeads * Config.HeadDim;
_kDim = Config.NumKVHeads * Config.HeadDim;
// Also check the TP-sharded dictionaries: under tensor parallelism the
// fused attn_qkv has already been moved out of _quantWeights into
// _tpQuantWeights before this runs, so a plain lookup would wrongly
// report the (always-fused) GptOss QKV as separate and the forward
// would ask for the nonexistent attn_q.weight.
_isQkvFused = _quantWeights.ContainsKey("blk.0.attn_qkv.weight") ||
_weights.ContainsKey("blk.0.attn_qkv.weight") ||
_tpQuantWeights.ContainsKey("blk.0.attn_qkv.weight") ||
_tpWeights.ContainsKey("blk.0.attn_qkv.weight");
_layerNames = new string[numLayers][];
for (int l = 0; l < numLayers; l++)
{
string p = $"blk.{l}.";
if (_isQkvFused)
{
_layerNames[l] = new[]
{
p + "attn_norm.weight", // 0
p + "attn_qkv.weight", // 1
p + "attn_qkv.bias", // 2
p + "attn_output.weight", // 3
p + "attn_output.bias", // 4
p + "post_attention_norm.weight", // 5
p + "ffn_gate_inp.weight", // 6
p + "ffn_gate_inp.bias", // 7
};
}
else
{
_layerNames[l] = new[]
{
p + "attn_norm.weight", // 0
p + "attn_q.weight", // 1
p + "attn_q.bias", // 2
p + "attn_output.weight", // 3
p + "attn_output.bias", // 4
p + "post_attention_norm.weight", // 5
p + "ffn_gate_inp.weight", // 6
p + "ffn_gate_inp.bias", // 7
p + "attn_k.weight", // 8
p + "attn_k.bias", // 9
p + "attn_v.weight", // 10
p + "attn_v.bias", // 11
};
}
}
_expertNames = new string[numLayers][][];
for (int l = 0; l < numLayers; l++)
{
_expertNames[l] = new string[_numExperts][];
string p = $"blk.{l}.";
for (int e = 0; e < _numExperts; e++)
{
_expertNames[l][e] = new[]
{
p + $"ffn_gate_up_exps.{e}.weight", // 0
p + $"ffn_gate_up_exps.{e}.bias", // 1
p + $"ffn_down_exps.{e}.weight", // 2
p + $"ffn_down_exps.{e}.bias", // 3
};
}
}
_layerSinks = new float[numLayers][];
for (int l = 0; l < numLayers; l++)
{
string sinksKey = $"blk.{l}.attn_sinks.weight";
if (_weights.TryGetValue(sinksKey, out var sinksTensor))
_layerSinks[l] = TensorToFloatArray(sinksTensor);
}
int maxBatchTokens = 4096 * _numExpertsUsed;
_moeExpertCounts = new int[_numExperts];
_moeExpertOffsets = new int[_numExperts];
_moeTokenMap = new int[maxBatchTokens];
_moeWeightMap = new float[maxBatchTokens];
_moeTopKScratch = new int[_numExpertsUsed];
}
#endregion
private int _kvCacheCapacity;
private void InitKVCache(int initialSeqLen, int maxSeqLen)
{
_maxContextLength = maxSeqLen;
_kvCacheCapacity = initialSeqLen;
int numKVHeads = Config.NumKVHeads;
int headDim = Config.HeadDim;
// Pick model-aligned default. For F16-quantised GPT-OSS this gives
// an F16 KV cache (halves cache memory + bandwidth, byte-identical
// outputs at 1e-3). The fused prefill kernel and the F16-aware
// decode loop (AttentionDecodeWithSinksF16 below) handle it
// natively. The legacy per-op prefill path (used only when
// seqLen > FusedAttnMaxSeqLen, i.e. ubatches > 256) doesn't yet
// read F16 cache directly via AddmmBatch, so for that path we'd
// either need to convert on the fly or keep the cache F32. The
// CLI always uses ubatches that hit the fused path on every
// shipping GGUF, so the F16 default is safe for benchmark and
// chat workloads.
ApplyModelAlignedKvCacheDefault(_quantWeights);
DType kvDtype = _kvCacheDtype.ToDType();
_kvCacheK = new Tensor[Config.NumLayers];
_kvCacheV = new Tensor[Config.NumLayers];
for (int l = 0; l < Config.NumLayers; l++)
{
_kvCacheK[l] = new Tensor(_allocator, kvDtype, numKVHeads, initialSeqLen, headDim);
_kvCacheV[l] = new Tensor(_allocator, kvDtype, numKVHeads, initialSeqLen, headDim);
InitializeCacheTensor(_kvCacheK[l]);
InitializeCacheTensor(_kvCacheV[l]);
}
_cacheSeqLen = 0;
}
private void EnsureCacheCapacity(int requiredSeqLen)
{
if (requiredSeqLen <= _kvCacheCapacity)
return;
if (requiredSeqLen > _maxContextLength)
throw new InvalidOperationException($"Requested sequence length {requiredSeqLen} exceeds configured max context {_maxContextLength}.");
// Growth copies the cache through host memory and hands every layer a
// NEW host pointer, so the device windows (keyed by the old pointer)
// must be flushed back first and then released — otherwise the rows a
// fused decode only ever wrote on-device are lost and the old windows
// leak their VRAM.
EnsureKvCacheHostSynchronized();
ResetFusedModelDecodeCache();
int newCapacity = Math.Max(_kvCacheCapacity, 1);
while (newCapacity < requiredSeqLen)
newCapacity = Math.Min(_maxContextLength, newCapacity * 2);
int numKVHeads = Config.NumKVHeads;
int headDim = Config.HeadDim;
DType kvDtype = _kvCacheDtype.ToDType();
for (int l = 0; l < Config.NumLayers; l++)
{
var newK = new Tensor(_allocator, kvDtype, numKVHeads, newCapacity, headDim);
var newV = new Tensor(_allocator, kvDtype, numKVHeads, newCapacity, headDim);
InitializeCacheTensor(newK);
InitializeCacheTensor(newV);
if (_cacheSeqLen > 0)
{
using var srcK = _kvCacheK[l].Narrow(1, 0, _cacheSeqLen);
using var dstK = newK.Narrow(1, 0, _cacheSeqLen);
Ops.Copy(dstK, srcK);
using var srcV = _kvCacheV[l].Narrow(1, 0, _cacheSeqLen);
using var dstV = newV.Narrow(1, 0, _cacheSeqLen);
Ops.Copy(dstV, srcV);
}
InvalidateTensorDeviceCache(_kvCacheK[l]);
InvalidateTensorDeviceCache(_kvCacheV[l]);
_kvCacheK[l].Dispose();
_kvCacheV[l].Dispose();
_kvCacheK[l] = newK;
_kvCacheV[l] = newV;
}
_kvCacheCapacity = newCapacity;
Console.WriteLine($"Expanded GPT-OSS attention cache to {newCapacity} tokens.");
}
protected override void ResetKVCacheCore()
{
// Setting _cacheSeqLen = 0 is the functional reset. Under TP the non-TP
// _kvCacheK/_kvCacheV arrays are null (TP uses _tpKvCacheK/_tpKvCacheV,
// overwritten on the next forward), so guard the tensor loop against null.
_cacheSeqLen = 0;
// The device rows are logically gone; nothing to flush, and the
// persistent decode graph pins the KV windows the reset invalidates.
_kvCacheHostDirty = false;
ResetFusedModelDecodeCache();
_linearTicks = _attnTicks = _normTicks = _embTicks = _lmHeadTicks = _logitsCopyTicks = 0;
_forwardCount = 0;
_forwardSw.Reset();
if (_kvCacheK == null) return;
for (int l = 0; l < Config.NumLayers; l++)
{
ResetCacheTensor(_kvCacheK[l]);
ResetCacheTensor(_kvCacheV[l]);
}
}
protected override void TruncateKVCacheCore(int tokenCount)
{
// Flush device-only rows before the invalidation below drops the
// windows: the retained prefix has to survive in host memory.
EnsureKvCacheHostSynchronized();
base.TruncateKVCacheCore(tokenCount);
_kvCacheHostDirty = false;
ResetFusedModelDecodeCache();
if (_kvCacheK == null) return;
for (int l = 0; l < Config.NumLayers; l++)
{
InvalidateTensorDeviceCache(_kvCacheK[l]);
InvalidateTensorDeviceCache(_kvCacheV[l]);
}
}
public override bool SupportsKVStateSnapshot => _kvCacheK != null && _kvCacheV != null;
public override string KVStateFingerprint =>
$"gptoss|arch={Config.Architecture}|L={Config.NumLayers}|H={Config.NumHeads}|KV={Config.NumKVHeads}|D={Config.HeadDim}|dtype={_kvCacheDtype.ToShortString()}";
public override long ComputeKVBlockByteSize(int tokenCount)
=> KvBlockTransfer.ComputeBlockByteSize(_kvCacheK, _kvCacheV, tokenCount);
public override bool TryExtractKVBlock(int startToken, int tokenCount, Span<byte> destination)
{
if (!SupportsKVStateSnapshot)
return false;
EnsureKvCacheHostSynchronized();
return KvBlockTransfer.Extract(
_allocator, _kvCacheK, _kvCacheV, _cacheSeqLen,
startToken, tokenCount, destination);
}
public override bool TryInjectKVBlock(int destToken, int tokenCount, ReadOnlySpan<byte> source)
{
if (!SupportsKVStateSnapshot)
return false;
// The injected block lands in host memory and the device windows are
// dropped below, so whatever only lived on-device has to come back
// first or the re-upload would resurrect stale rows around it.
EnsureKvCacheHostSynchronized();
EnsureCacheCapacity(destToken + tokenCount);
if (!KvBlockTransfer.Inject(
_allocator, _kvCacheK, _kvCacheV, _cacheSeqLen,
destToken, tokenCount, source))
{
return false;
}
_cacheSeqLen = destToken + tokenCount;
_kvCacheHostDirty = false;
ResetFusedModelDecodeCache();
for (int l = 0; l < Config.NumLayers; l++)
{
InvalidateTensorDeviceCache(_kvCacheK[l]);
InvalidateTensorDeviceCache(_kvCacheV[l]);
}
return true;
}
// Chunk size for ForwardRefill: long prompts are processed in this-many-token
// chunks so the per-layer attention-score allocation stays bounded.
// Override with TS_PREFILL_CHUNK when tuning.
private int ResolvePrefillChunkSize()
{
string env = Environment.GetEnvironmentVariable("TS_PREFILL_CHUNK");
if (!string.IsNullOrEmpty(env) && int.TryParse(env, out int v) && v > 0)
return v;
return PrefillChunkCap();
}
protected override float[] ForwardRefillCore(int[] tokens)
{
if (tokens == null || tokens.Length <= 1)
return ForwardCore(tokens);
// The chunked prefill path (PrefillWithoutLogits) uses the non-TP
// TransformerBlock and non-sharded weights, which are unavailable
// under tensor parallelism. Route through ForwardCore → ForwardTP.
if (IsTensorParallel)
return ForwardCore(tokens);
int chunkSize = ResolvePrefillChunkSize();
int lastIdx = tokens.Length - 1;
if (tokens.Length <= chunkSize)
return ForwardCore(tokens);
for (int pos = 0; pos < lastIdx; pos += chunkSize)
{
int chunkLen = Math.Min(chunkSize, lastIdx - pos);
var chunk = new int[chunkLen];
Array.Copy(tokens, pos, chunk, 0, chunkLen);
PrefillWithoutLogits(chunk);
}
return ForwardCore(new[] { tokens[lastIdx] });
}
private void PrefillWithoutLogits(int[] tokens)
{
if (tokens == null || tokens.Length == 0)
return;
_forwardSw.Start();
int seqLen = tokens.Length;
int startPos = _cacheSeqLen;
EnsureCacheCapacity(startPos + seqLen);
// A prefill grows the ggml-cuda compute pool, which moves the scratch
// addresses the captured decode graph pinned.
ResetFusedModelDecodeCache();
long t1 = Stopwatch.GetTimestamp();
Tensor hidden = Embedding(tokens);
_embTicks += Stopwatch.GetTimestamp() - t1;
// Intermediate chunks only need their KV rows, which the whole-model
// prefill graph writes exactly the same way; its logits are ignored.
if (WillUseFusedModelPrefill(seqLen) && TryFusedModelPrefill(hidden, startPos, seqLen))
{
hidden.Dispose();
_cacheSeqLen += seqLen;
_forwardSw.Stop();
return;
}
EnsureKvCacheHostSynchronized();
for (int layer = 0; layer < Config.NumLayers; layer++)
{
bool isLastLayer = (layer == Config.NumLayers - 1);
hidden = TransformerBlock(hidden, layer, seqLen, startPos, isLastLayer);
if (_backend == BackendType.Mlx && (layer + 1) % MlxEvalEveryNLayers == 0
&& !isLastLayer && hidden != null)
{
MlxFusedOps.TryAsyncEvaluate(hidden);
}
}
hidden.Dispose();
_cacheSeqLen += seqLen;
_forwardSw.Stop();
}
/// <summary>
/// Tokens per prefill pass.
///
/// The 256 floor belongs to the per-layer path, whose attention builds an
/// O(seqLen^2) score tensor per layer: a larger chunk there fell off the
/// fused attention kernel onto the per-op host path (~8x slower, and it
/// OOMs the Metal command buffer). The whole-model prefill graph has no
/// such tensor — flash attention over a windowed cache — so when it is
/// available the chunk is sized for GEMM efficiency instead. Tunable via
/// TS_GPTOSS_PREFILL_CHUNK.
/// </summary>
private int PrefillChunkCap()
{
string env = Environment.GetEnvironmentVariable("TS_GPTOSS_PREFILL_CHUNK");
if (!string.IsNullOrWhiteSpace(env) && int.TryParse(env, out int v) && v > 0)
return v;
return WillUseFusedModelPrefill(2) ? 2048 : FusedAttnMaxSeqLen;
}
protected override float[] ForwardCore(int[] tokens)
{
if (IsTensorParallel)
return ForwardTP(tokens);
// Long prompts (seqLen > the fused-attention cap) are chunked so the
// attention always runs on the fused on-device kernel rather than the
// per-op host path that builds an O(seqLen^2) scores tensor per layer
// (8x slower + Metal OOM, see FusedAttnMaxSeqLen). The server's
// scheduler hands whole prompt chunks (up to SoloPrefillChunkSize ~=
// 4096) straight to Forward, so the cap MUST be enforced here, not
// only in ForwardRefill. Chunked prefill is mathematically identical
// to a single pass (causal attention + KV cache), so the returned
// last-token logits are unchanged. Decode (seqLen == 1) and short
// prompts (<= cap) skip the loop and run a single pass.
int chunkCap = PrefillChunkCap();
if (tokens != null && tokens.Length > chunkCap && IsGgmlBackend)
{
int cap = chunkCap;
int total = tokens.Length;
int pos = 0;
// All but the final (<= cap) chunk only append KV; the last chunk
// produces the logits for the prompt's final token.
while (total - pos > cap)
{
var chunk = new int[cap];
Array.Copy(tokens, pos, chunk, 0, cap);
PrefillWithoutLogits(chunk);
pos += cap;
}
var lastChunk = new int[total - pos];
Array.Copy(tokens, pos, lastChunk, 0, total - pos);
return ForwardSingle(lastChunk);
}
return ForwardSingle(tokens);
}
private float[] ForwardSingle(int[] tokens)
{
_forwardSw.Start();
int seqLen = tokens.Length;
int startPos = _cacheSeqLen;
EnsureCacheCapacity(startPos + seqLen);
// Whole-model fused decode: all layers + MoE + final norm + LM head as
// ONE graph dispatch. Only the per-op / per-layer fallbacks read the KV
// cache from host memory, so the host sync is skipped when this path
// will run (it would copy the whole cache back every token).
bool useFusedModelDecode = WillUseFusedModelDecode(seqLen);