Repository navigation
Expand file tree
/
Copy pathkimi_k3.c
More file actions
5044 lines (4894 loc) Β· 253 KB
/
Copy pathkimi_k3.c
File metadata and controls
5044 lines (4894 loc) Β· 253 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
/* Kimi K3 inference engine in pure C β sibling of colibri.c (GLM-5.2) / olmoe.c /
* inkling.c, sharing st.h / json.h / tok.h / quant.h.
*
* Architecture (2.8T total / 104B active, 93 layers, hidden 7168):
* - Hybrid attention: 69 KDA (Kimi Delta Attention, linear/recurrent) +
* 24 gated MLA layers (every 4th, plus the final layer). MLA is NoPE β
* no positional encoding anywhere in the model; position lives in KDA's
* decay/conv. Both attention types carry a full-rank sigmoid output gate.
* - AttnRes (Attention Residuals) REPLACE the plain residual stream: a
* running prefix_sum plus block snapshots (layers 0,12,24,...,84), mixed
* by softmax twice per layer (before attention, before MLP) and once at
* the end. Weights: per-layer {self_attention,mlp}_res_{norm,proj}.
* - Stable LatentMoE: router (sigmoid + e_score_correction_bias, top-16 of
* 896, renormalized raw scores), shared latent down/up projections
* (7168<->3584), per-expert GLU in the 3584 latent with moe_inter 3072,
* RMSNorm on the aggregate, plus 2 fused shared experts (inter 6144) at
* full width. Activation is SiTU-GLU:
* b1*tanh(g/b1)*sigmoid(g) * b2*tanh(u/b2), b1=4, b2=25.
* - Routed experts are NATIVE MXFP4 (QAT; e2m1 nibbles + ue8m0 scale per
* 32, compressed-tensors "mxfp4-pack-quantized") and are streamed
* straight from the original HF shards β never re-encoded, never
* converted. Everything else is BF16 in the checkpoint and quantized at
* LOAD TIME into RAM (int8 per-row / int4-g64 / f32, see K3_*BITS).
*
* KDA per-head recurrence (head dim 128, 96 heads; fla fused_recurrent_kda):
* q,k,v = SiLU(ShortConv4(W{q,k,v} x)); q,k L2-normalized (eps 1e-6
* inside the sqrt), q *= 128^-0.5
* z = W_fb(W_fa x) + dt_bias (per channel, dt_bias[12288])
* gk = gmin * sigmoid(exp(A_log[h]) * z), gmin=-5; alpha = exp(gk)
* S = (I - beta k k^T) Diag(alpha) S + beta k v^T, beta = sigmoid(W_b x)
* o = S^T q; out = W_o [ sigmoid(W_g x) * RMSNorm_head(o) ]
* (checkpoint A_log is [128] = per-head [96] zero-padded, first 96 used)
*
* Model dir = the HF snapshot (config.json + model-*-of-000096.safetensors).
* tokenizer.json is synthesized once by tools/k3_tokenizer.py (the HF repo
* ships only tiktoken.model); without it the engine still runs on raw ids.
*
* ENV:
* K3_BITS=4|8|32 load-time quant of KDA/latent/shared/dense (default 4)
* K3_MLA_BITS=8|4|32 MLA projections (default 8)
* K3_HEAD_BITS=8|4|32 lm_head (default 8)
* K3_MMAP=0|1 map prepared U8 + F32 tensors read-only instead of
* copying them to private heap (default 0; CPU-only)
* K3_EXPERT_GB=N routed-expert LRU cache budget (default 8)
* COLI_VULKAN=1 (build with `make VK=1 kimi_k3`) the routed experts
* on the shared Vulkan expert tier (vk_tier.c, the
* COLI_VK_TIER* variables), the shared experts where
* COLI_VK_DENSE puts the dense matrices. CPU fallback
* everywhere; the tier's experts match K3_IDOT=0.
* COLI_VK_CHAIN=0|1|2 with COLI_VULKAN=1: every layer's dense part on the
* device, one frame per layer up to the router
* (kimi_k3_chain.h; 2: prompts only). Default: on a
* discrete GPU, off on an integrated one (not measured).
* K3_VK=0|1 the old switch, an alias: 1 = COLI_VULKAN=1, 0 = the
* device stays closed. Unset: COLI_VULKAN decides.
* K3_VK_GB=N alias of COLI_VK_TIER_GB (when that is unset)
* K3_VK_UP=N alias of COLI_VK_TIER_RATE (when that is unset);
* `auto` and K3_VK_FILL_FRAC do nothing any more
* K3_METAL=0|1 Metal tier (build with `make METAL=1 kimi_k3`; Phase 4:
* scaffolding only β dispatch hooks present, forward NOT
* IMPLEMENTED; all ops fall through to CPU).
* K3_DIRECT=0|1 O_DIRECT expert reads (default 1; buffered fallback)
* K3_IDOT=0|1 int8-activation expert matmuls (default 1; 0 = float)
* K3_PIPE=0|1 overlap expert loads with compute (default 1)
* K3_LOAD_THREADS=N loader threads for K3_PIPE (default 4)
* K3_TOPP=F keep routed experts to cumulative weight F (0 = off)
* K3_CHUNK=N prefill chunk size (default 32; 1 = token-at-a-time)
* K3_THINK=0|1 chat mode: open the think channel (default 1)
* K3_LAYERS=N truncate to first N layers (validation; skips head)
* K3_TRACE=path dump f32 hidden state after every layer (validation)
* K3_LOGITS=path dump f32 logits per PREFILL position (teacher-forced
* bit-width comparisons; use with --ngen 0)
* K3_MAXT=N KV/context capacity (default prompt+ngen)
* COLI_K3_CKPT=N OPT-IN recurrent-state checkpoints for serve: keep N
* photos of the KDA state at turn boundaries so a
* divergent prompt (agentic edit) resumes from the
* deepest valid photo instead of re-prefilling from
* token 0. Unset/0 (default) = feature off, engine
* byte-identical to before. ~434 MB per photo on the
* full model, which is why it is opt-in.
* COLI_K3_CKPT_DIR=dir park the photos in files under dir instead of RAM
* (low-RAM machines: ~0.4s of sequential I/O per
* restore against minutes of avoided re-prefill).
* Alone it implies COLI_K3_CKPT=2; an explicit
* COLI_K3_CKPT (0 included) always wins. Photos never
* outlive the process: after a restart the MLA rows
* are gone, so no restore could be valid.
* COLI_TEMP=F 0 = greedy (default), else softmax temperature
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)
#include <sys/resource.h>
#include <sys/select.h>
#include <unistd.h>
#endif
#include <pthread.h>
#include <stdatomic.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#ifdef __APPLE__
#include <sys/sysctl.h>
#include <mach/mach.h>
#endif
#include "cli_args.h"
#include "st.h"
#include "tok.h"
#include "quant.h"
#ifdef COLI_CUDA
#include "backend_cuda.h"
#endif
#include "omp_tune.h"
#include "route_trace.h"
#include "vk_tier.h" /* the shared Vulkan routed-expert tier (COLI_VULKAN=1; stubs without VK=1) */
#include "kv_prefix.h"
#include "pin_pool.h" /* coli_pin_slots_wanted: quanti scatti tenere */
#include "hybrid_split.h" /* KV prefix reuse (shared) */
#include "serve_codec.h"
#include "serve_budget.h"
#ifdef COLI_SEGMENT_ADAPTER
#include "segment_runtime.h"
#include "segment_adapters.h"
#include "segment_adapter_internal.h"
#endif
#ifdef COLI_EDGE_ADAPTER
#include "edge_runtime.h"
#include "edge_adapters.h"
#include "edge_tok_internal.h"
#endif
/* ---------- config ---------- */
typedef struct {
int hidden, n_layers, vocab, first_dense, dense_inter;
/* MLA */
int n_heads, q_lora, kv_lora, qk_nope, qk_rope, qk_head, v_head;
float attn_scale, theta;
/* KDA */
int kda_heads, kda_hd, kda_proj, conv_k;
float gate_lb;
/* MoE */
int n_experts, topk, moe_inter, latent, n_shared;
float situ_b1, situ_b2;
/* AttnRes */
int res_bs;
float eps;
int8_t is_kda[128];
int8_t idx_type[128]; /* DSA: 1=full (own Ic + top-K), 0=shared (reuse) */
int index_hd, index_nh, index_topk; /* DSA indexer dimensions */
int bos, eos[8], n_eos;
} Cfg;
/* ---------- RAM-resident or read-only mapped weight ---------- */
typedef struct { int fmt; float *f; int8_t *q8; uint8_t *q4; float *s; int O, I, gs;
void *vk; /* ColiVkTensor* once uploaded (K3_VK); NULL = CPU only */
void *metal; /* ColiMetalTensor* once registered (K3_METAL); NULL = CPU only */
st_mapped_raw data_map, scale_map;
int mapped;
/* COLI_VULKAN: how to read it back from disk (k3_w_reload), and 1 while the
* device holds it alone (COLI_VK_DENSE_HOST, the host copy dropped) */
char *vk_name; int vk_bits, vk_gone; } W;
typedef struct { /* KDA layer */
W q, k, v, o, g;
float *conv_q, *conv_k, *conv_v; /* [proj*4] depthwise taps, oldest first */
float *fa, *fb; /* decay low-rank, f32 [hd,hidden] [proj,hd] */
float *bp; /* beta proj f32 [heads,hidden] */
float *dt, *A, *onw; /* dt_bias[proj], exp(A_log)[heads], o_norm[hd] */
void *metal_fa, *metal_fb, *metal_bp; /* Metal tensor wrappers for f32 weights */
void *vk_fa, *vk_fb, *vk_bp; /* COLI_VK_DENSE_HOST: the chain's device copies, for the per-matrix path */
} Kda;
typedef struct { /* gated MLA layer */
W qa, qb, kva, kvb, o, g;
float *qa_ln, *kva_ln;
/* DSA indexer (full layers only, optional) */
W wk, wq, wp; /* [index_hd x {hidden, q_lora, index_hd}] */
float *knw, *knb; /* key layernorm [index_hd] */
float *Ic; /* indexer cache [max_t * index_hd] */
} Mla;
typedef struct { /* LatentMoE */
float *router, *rbias, *lat_norm; /* [E,hidden] f32, [E], [latent] */
void *vk_router; /* COLI_VK_DENSE_HOST: the chain's device copy, for the per-matrix path */
W lat_down, lat_up, sh_gate, sh_up, sh_down;
} Moe;
typedef struct {
int kda, sparse;
Kda a; Mla m; Moe moe;
W d_gate, d_up, d_down; /* dense layer only */
float *in_ln, *post_ln;
float *attn_sw, *mlp_sw; /* AttnRes score weights: norm.w * proj.w */
} Layer;
/* ---------- routed-expert streaming (native MXFP4 from the HF shards) ---- */
typedef struct { int fd[6]; int64_t off[6]; int contig; } ERef; /* w1p w1s w2p w2s w3p w3s */
#ifndef KIMI_K3_NO_MAIN
static char g_k3_usage[2100]; /* <snap>/.coli_usage, or COLI_USAGE */
#endif
typedef struct { int eid; uint8_t *buf, *base; uint64_t used; int pinned; } Slot;
/* pinned: seeded from .coli_usage at startup and never evicted. The LRU adapts to
* THIS session; the pin knows the history of every session before it. Capped at
* half the layer budget so the adaptive half always survives β an all-pinned cache
* that guessed wrong is slower than no pin at all (measured on GLM: 0.17 vs 0.25
* tok/s when the pins came from a single prompt). */
/* base = 4K-aligned allocation (O_DIRECT target);
* buf = expert data view inside it (= base + off%4K) */
typedef struct {
Slot *s;
int *slot_by_expert; /* expert id -> local slot, -1 if absent */
int n, cap;
} LCache;
/* One conversation's state for a multiplexed serve (KV_SLOTS>1, serve_mux below):
* every KDA layer's recurrent state and its three convolution windows, every MLA
* layer's latent caches and its index keys, their capacity and the record of the
* tokens they hold. The Model holds the conversation a prefill runs on (k3_seq_swap
* trades it for a parked one); a multiplexed decode step parks them all and reads
* each row's from its K3Row. */
typedef struct {
float **kstate, **cwq, **cwk, **cwv, **Lc, **Rc, **Ic;
int max_t;
kv_prefix kvp;
} K3Seq;
typedef struct { K3Seq *seq; int pos; } K3Row;
static int g_k3_mux_slots=1; /* KV_SLOTS: the conversations a serve decodes at once */
typedef struct {
Cfg c;
shards S;
char pfx[40]; /* "language_model." or "" */
Layer *L;
float *final_norm, *out_sw;
W lm_head;
int has_head;
Slot ws[64]; /* working set: parallel loads land here,
* then swap into the layer LRU */
/* KDA state */
float **kstate; /* [layer] -> [heads*hd*hd], S[k][v] */
float **cwq, **cwk, **cwv; /* conv windows [proj*conv_k], oldest first */
/* MLA cache */
float **Lc, **Rc; int max_t;
/* KV prefix reuse: what the current state was built from (kv_prefix.h).
* K3 has no single KV to inspect β 69 KDA layers carry a RECURRENT state
* and only the 24 MLA layers keep Lc/Rc β so an explicit record of the
* tokens fed is the only description of it that cannot drift. */
kv_prefix kvp;
/* DSA selection: per-slot k_idx arrays (shared across layers) */
int *dsa_nsel, *dsa_sel; int64_t dsa_scap; /* k_idx selection: [S] counts + [S*topk] indices */
/* experts */
ERef *eref; /* [n_layers][n_experts] (dense rows zeroed) */
LCache *ecache;
uint8_t **ehit; /* experts routed this turn, for HITS (dashboard Brain) */
int64_t e_w1p, e_w1s, e_w2p, e_w2s, e_slot;
uint64_t clock, hits, miss, ebytes;
double t_attn, t_moe, t_eload, t_head;
FILE *trace;
/* A multiplexed decode step (k3_step_rows): row t is the token at
* mux_rows[t].pos of mux_rows[t].seq; NULL in every other forward. */
const K3Row *mux_rows;
} Model;
static double now_s(void){ struct timespec t; clock_gettime(CLOCK_MONOTONIC,&t); return t.tv_sec+t.tv_nsec*1e-9; }
/* How many expert slots per layer fit a budget. PURE -- no globals, no model,
* no I/O -- so the arithmetic that #855 got wrong can be tested against the
* reported numbers without a 600 GB checkpoint. Returns the cap; writes the
* bytes left for experts through `for_experts_out` when non-NULL.
*
* reserve = page cache + activations + KV + optional recurrent checkpoints,
* all in GB. `cap_requested` is what K3_EXPERT_GB asked for: this only ever
* LOWERS it, never raises it, so an explicit small cache stays small. */
static int k3_cap_for_ram(double budget_gb, double resident_gb, double reserve_gb,
double slot_gb, int nmoe, int cap_requested,
int n_experts, double *for_experts_out){
double for_experts = budget_gb - resident_gb - reserve_gb;
if(for_experts_out) *for_experts_out = for_experts;
if(nmoe < 1) nmoe = 1;
if(!(slot_gb > 0.0)) return cap_requested;
int fits = for_experts > 0.0 ? (int)(for_experts/(slot_gb*(double)nmoe)) : 0;
if(fits > n_experts) fits = n_experts;
return fits < cap_requested ? fits : cap_requested;
}
/* Memory the OS says is still reclaimable without swapping, in GB; 0 if unknown.
* The same quantity colibri.c's cap_for_ram() budgets against -- Linux
* MemAvailable, Windows ullAvailPhys, macOS free+inactive+purgeable. #855. */
static double k3_mem_avail(void){
#ifdef _WIN32
double total=0, avail=0; compat_meminfo(&total,&avail); return avail;
#elif defined(__APPLE__)
int64_t pgsz=0; size_t sl=sizeof(pgsz);
if(sysctlbyname("hw.pagesize",&pgsz,&sl,NULL,0)||pgsz<=0) pgsz=16384;
vm_statistics64_data_t vs; mach_msg_type_number_t nc=HOST_VM_INFO64_COUNT;
if(host_statistics64(mach_host_self(),HOST_VM_INFO64,(host_info64_t)&vs,&nc)!=KERN_SUCCESS)
return 0;
return (double)(vs.free_count+vs.inactive_count+vs.purgeable_count)*(double)pgsz/1e9;
#else
FILE *f=fopen("/proc/meminfo","r"); if(!f) return 0;
char ln[256]; double kb=0;
while(fgets(ln,sizeof(ln),f)) if(sscanf(ln,"MemAvailable: %lf",&kb)==1) break;
fclose(f); return kb/1e6;
#endif
}
static double rss_gb(void){ struct rusage r; getrusage(RUSAGE_SELF,&r);
#if defined(__APPLE__)
return r.ru_maxrss/(1024.0*1024.0*1024.0);
#else
return r.ru_maxrss/(1024.0*1024.0);
#endif
}
static float *falloc(int64_t n){
if(n<0 || (uint64_t)n > SIZE_MAX/sizeof(float)){ fprintf(stderr,"alloc size overflow: %lld floats\n",(long long)n); exit(1); }
float *p=malloc((size_t)n*sizeof(float)); if(!p){fprintf(stderr,"OOM %lld floats\n",(long long)n);exit(1);} return p; }
static float *fcalloc(int64_t n){
if(n<0 || (uint64_t)n > SIZE_MAX/sizeof(float)){ fprintf(stderr,"alloc size overflow: %lld floats\n",(long long)n); exit(1); }
float *p=calloc((size_t)n,sizeof(float)); if(!p){fprintf(stderr,"OOM %lld floats\n",(long long)n);exit(1);} return p; }
/* Aligned + zeroed alloc. Metal's wrap() only takes the zero-copy (newBufferWithBytesNoCopy)
* path when the pointer AND size are 16384-aligned; otherwise it makes a private GPU copy
* that is never synced back. Buffers the GPU WRITES and must persist across tokens (KDA
* state, conv windows) therefore have to be 16 KB-aligned so GPU updates land in host memory.
* Freed with plain free(); posix_memalign memory is free()-compatible on macOS. */
static float *afcalloc(int64_t n){
#ifdef COLI_METAL
size_t sz=(size_t)n*sizeof(float); void *p=NULL;
if(posix_memalign(&p,16384,sz)){ fprintf(stderr,"OOM %lld floats\n",(long long)n); exit(1); }
memset(p,0,sz); return (float*)p;
#else
return fcalloc(n);
#endif
}
static inline float sigmoidf_(float x){ return 1.f/(1.f+expf(-x)); }
static inline float siluf_(float x){ return x/(1.f+expf(-x)); }
static void softmax_(float *x, int n){ float m=x[0]; for(int i=1;i<n;i++) if(x[i]>m)m=x[i];
float s=0; for(int i=0;i<n;i++){ x[i]=expf(x[i]-m); s+=x[i]; } for(int i=0;i<n;i++) x[i]/=s; }
static void rmsnorm_(float *out, const float *x, const float *w, int D, float eps){
double ms=0; for(int i=0;i<D;i++) ms+=(double)x[i]*x[i];
float r=1.f/sqrtf((float)(ms/D)+eps);
for(int i=0;i<D;i++) out[i]=x[i]*r*w[i];
}
/* ---------- DSA (Dictionary Sparse Attention) CPU helpers ---------- */
/* L'indexer DSA e' COSTRUITO ma non COLLEGATO (#1333): l'unica funzione che
* leggerebbe la cache Ic per scegliere le posizioni top-K, dsa_score_single qui
* sotto, non ha nessun chiamante -- una grep su tutto il repo trova solo la sua
* definizione.
*
* Finche' resta cosi' l'attenzione e' densa e il sottosistema e' lavoro pagato e
* mai letto: CINQUE tensori dal disco per ogni layer DSA (w_k, w_q, w_p, kn_w,
* kn_b -- e w_q, w_p, kn_b non sono toccati nemmeno dal codice morto), la cache
* Ic da [max_t * index_hd] float per layer, e per ogni token un matmul piu'
* rmsnorm piu' rope.
*
* Spento di default, non cancellato: quel che manca e' collegare
* dsa_score_single, e chi lo fara' ha bisogno di questi pesi. KIMI_DSA_INDEXER=1
* li ricarica. Avvertenza per chi ci mettera' mano: collegarlo CAMBIA le uscite
* -- l'attenzione diventa sparsa dove oggi e' densa -- quindi va fatto contro
* l'oracolo token-exact, non a occhio. */
static int k3_dsa_indexer_on(void){
static int cached = -1;
if(cached < 0){ const char *e = getenv("KIMI_DSA_INDEXER"); cached = e && *e=='1'; }
return cached;
}
static void dsa_rope(float *v, int pos, int qk_rope, float base_theta){
int half = qk_rope/2;
if(qk_rope > 256){ fprintf(stderr,"qk_rope=%d exceeds rope buffer (256)\n",qk_rope); exit(1); }
float in[256]; memcpy(in,v,qk_rope*sizeof(float));
for(int j=0;j<half;j++){
float inv=powf(base_theta,-2.0f*j/qk_rope), ang=pos*inv;
float cs=cosf(ang), sn=sinf(ang);
float a=in[2*j], b=in[2*j+1];
v[j] = a*cs - b*sn;
v[half+j] = b*cs + a*sn;
}
}
typedef struct { float sc; int idx; } DsaEntry;
static int dsa_entry_cmp_desc(const void *a,const void *b){
float d=((const DsaEntry*)b)->sc-((const DsaEntry*)a)->sc;
return d>0?1:d<0?-1:0;
}
/* dsa_score: multi-head cosine distance + ReLU + weight + top-K select.
* qi: [nh * index_hd] β per-head indexer query (post-RoPE, post-projection)
* Ic: [nk * index_hd] β indexer cache rows
* w32: [nh] β weight scalars from P projection
* nk: number of cache rows in context
* sel: output buffer of maxsel ints (sorted desc by score)
* Returns actual count of selected indices. Caller supplies token-local DsaEntry array. */
static int dsa_score_single(int *sel, int maxsel, const float *qi, const float *Ic, int index_hd,
const float *w32, int nh, int nk, DsaEntry *entries){
if(nk <= 0 || maxsel <= 0) return 0;
for(int t=0;t<nk;t++){
float s = 0;
for(int h=0;h<nh;h++){
float d=0;
for(int i=0;i<index_hd;i++) d += qi[(int64_t)h*index_hd+i] * Ic[(int64_t)t*index_hd+i];
s += w32[h]*(d>0?d:0); /* ReLU per-head */
}
entries[t]=(DsaEntry){s/sqrtf((float)nh), t};
}
int K = nk < maxsel ? nk : maxsel;
qsort(entries, nk, sizeof(DsaEntry), dsa_entry_cmp_desc);
for(int k=0;k<K;k++) sel[k]=entries[k].idx;
return K;
}
/* ---------- W: load-time quantization + matvec ---------- */
/* ---------- Vulkan (COLI_VULKAN=1, build with `make VK=1 kimi_k3`) ----------
* Two things on the device, each with the CPU path as its fallback:
* - the routed experts, on the shared routed-expert tier (vk_tier.c): the
* checkpoint's MXFP4 with its ue8m0 group scales, SiTU-GLU on the device, in
* the latent space (the tier's hidden is the latent, its inter moe_inter). It
* fills from the expert history and from the experts the CPU computes, and
* evicts the coldest as the routing moves (moe_forward, k3_vk_tier_start);
* - the shared experts' three matrices, where coli_vk_dense() puts the dense
* matrices (on a discrete GPU the device; on one that shares the CPU's RAM,
* the CPU while the tier is on), run by w_matmul one row at a time (S == 1).
* K3_VK, K3_VK_GB and K3_VK_UP were the switches of this engine's own tier
* before the shared one; k3_vk_aliases() reads them into the shared names. */
#ifdef COLI_VULKAN
#include "backend_vulkan.h"
#include "vk_chain.h" /* vkc_fit: how many layers the dense chain places (a partial chain) */
static int g_k3_vk=0; /* the device is open */
/* The partial chain (kimi_k3_chain.h, k3c_fit_now): the first g_k3_fit.n layers on the
* device, decided once before anything goes up and before the expert cache is sized.
* g_k3_partial: something the full chain would place stays on the CPU (layers, the head),
* so nothing more goes to the device for the per-matrix path. g_k3_dho_layers and
* g_k3_dho_head: what COLI_VK_DENSE_HOST takes off the host (the chain's layers, and the
* head only with every layer and the tail on the device). */
static VkcFit g_k3_fit;
static int g_k3_fit_done, g_k3_partial;
static int g_k3_dho_layers=1<<30, g_k3_dho_head=1;
/* COLI_VK_DENSE_HOST: the dense matrices on the device only (k3_dho_*): every W the
* chain does not run goes to the device through w_matmul, prompts included */
static int g_k3_dho=0;
static void k3_w_reload(W *w); /* below, beside w_load */
static int k3_in_par(void){
#ifdef _OPENMP
return omp_in_parallel();
#else
return 0;
#endif
}
/* Did the run ask for the device? K3_VK, when set, decides (0: never, any other
* number: yes, as COLI_VULKAN=1); unset, COLI_VULKAN does, as for every engine. */
static int k3_vk_requested(void){
const char *k=getenv("K3_VK");
if(k&&*k) return atoi(k)!=0;
const char *v=getenv("COLI_VULKAN");
return v&&*v&&atoi(v)!=0;
}
/* The old switches, read as the shared tier's (an explicit shared one wins):
* K3_VK=1 -> COLI_VULKAN=1 (K3_VK=0 keeps the device closed)
* K3_VK_GB=N -> COLI_VK_TIER_GB=N (the routed experts' budget)
* K3_VK_UP=N -> COLI_VK_TIER_RATE=N (promotions per token); `auto` and
* K3_VK_FILL_FRAC have nothing left to bound: the shared
* tier uploads on a thread of its own and never holds a step */
static void k3_vk_aliases(void){
const char *k=getenv("K3_VK"), *v=getenv("COLI_VULKAN");
if(k&&*k&&atoi(k)&&!(v&&*v&&atoi(v))){
setenv("COLI_VULKAN","1",1);
fprintf(stderr,"[VK] kimi_k3: K3_VK=%s read as COLI_VULKAN=1\n",k);
}
const char *gb=getenv("K3_VK_GB"), *tg=getenv("COLI_VK_TIER_GB");
if(gb&&*gb&&atof(gb)>0&&!(tg&&*tg)){
setenv("COLI_VK_TIER_GB",gb,1);
fprintf(stderr,"[VK] kimi_k3: K3_VK_GB=%s read as COLI_VK_TIER_GB=%s\n",gb,gb);
}
const char *up=getenv("K3_VK_UP"), *tr=getenv("COLI_VK_TIER_RATE");
if(up&&*up&&!(tr&&*tr)){
if(!strcmp(up,"auto"))
fprintf(stderr,"[VK] kimi_k3: K3_VK_UP=auto has no effect on the shared tier (its uploads never hold a step)\n");
else {
setenv("COLI_VK_TIER_RATE",up,1);
fprintf(stderr,"[VK] kimi_k3: K3_VK_UP=%s read as COLI_VK_TIER_RATE=%s\n",up,up);
}
}
}
/* the backend format of a resident W: int8 rows, int4 groups, f32 */
static int k3_vk_fmt(const W *w){ return w->fmt==1?1 : w->fmt==4?4 : w->fmt==0?10 : -1; }
static int w_vk_upload(W *w){
if(w->vk) return 1;
int fmt=k3_vk_fmt(w);
if(fmt<0||w->mapped) return 0;
const void *src=fmt==1?(const void*)w->q8 : fmt==4?(const void*)w->q4 : (const void*)w->f;
return coli_vk_tensor_ensure((ColiVkTensor**)&w->vk,src,fmt==10?NULL:w->s,fmt,w->I,w->O,fmt==4?w->gs:0);
}
#endif
/* ---------- Metal tier (K3_METAL, build with `make METAL=1 kimi_k3`) ----------
* Phase 4: scaffolding β init, dispatch hooks, feature flags.
* Not implemented; w_matmul intentionally falls through to CPU. */
static int g_k3_metal=0; /* backend live (K3_METAL env) */
/* Phase 9: layer-level validation β capture intermediates for one layer */
static int g_k3_val_layer = -1; /* K3_VALIDATE_LAYER=N (0-indexed, -1=off) */
static int g_k3_val_token = 0; /* K3_VALIDATE_TOKEN (always use 0) */
static FILE *g_k3_val_fp = NULL; /* output file for intermediate dumps */
/* Phase 10: full model validation β per-step logits (stays open across prefill+decode) */
static FILE *g_k3_val_lfp = NULL; /* K3_VAL_LOGITS: per-step logit dump */
static void val_dump(const char *name, const float *v, int n); /* forward-declare */
static FILE *g_k3_dfp = NULL; /* K3_DEBUG_OUT: Metal/CPU side-by-side per-dim comparison */
#ifdef COLI_METAL
#include "backend_metal.h"
/* Metal forward entry point β Phase 4: NOT IMPLEMENTED */
static int kimima_forward_metal(Model *m, Layer *l, int li, const float *x, int C, float *out){
(void)m; (void)l; (void)li; (void)x; (void)C; (void)out;
return 0; /* 0 = NOT IMPLEMENTED β fall through to CPU */
}
#endif
static void w_matmul(float *y, const float *x, const W *w, int S){
#ifdef COLI_METAL
if(g_k3_metal && coli_metal_available()){
if(w->fmt==0){
/* fmt=0 is raw f32, no scales needed β Metal shader handles it */
coli_metal_matmul((ColiMetalTensor**)&((W*)w)->metal, y, x, w->f, NULL, 0, S, w->I, w->O, 0);
return;
}
if(w->fmt==1){
coli_metal_matmul((ColiMetalTensor**)&((W*)w)->metal, y, x, w->q8, w->s, 1, S, w->I, w->O, 0);
return;
}
if(w->fmt==4){
coli_metal_matmul((ColiMetalTensor**)&((W*)w)->metal, y, x, w->q4, w->s, 4, S, w->I, w->O, w->gs);
return;
}
}
#endif
#ifdef COLI_VULKAN
if(g_k3_vk&&S==1&&w->vk&&!g_k3_dho&&
coli_vk_matmul((ColiVkTensor**)&((W*)w)->vk,y,x,NULL,NULL,k3_vk_fmt(w),1,w->I,w->O,w->gs))
return;
/* device only: every row count, from the main thread (one command buffer) */
if(g_k3_dho&&g_k3_vk&&w->vk&&S>=1&&S<=65535&&!k3_in_par()&&
coli_vk_matmul((ColiVkTensor**)&((W*)w)->vk,y,x,NULL,NULL,k3_vk_fmt(w),S,w->I,w->O,w->gs))
return;
if(w->vk_gone) k3_w_reload((W*)w); /* the CPU needs a matrix the device held alone (a lost device) */
#endif
if(w->fmt==0) matmul(y,x,w->f,S,w->I,w->O);
else if(w->fmt==1) matmul_q(y,x,w->q8,w->s,S,w->I,w->O);
else if(w->fmt==4) matmul_i4_grouped(y,x,w->q4,w->s,S,w->I,w->O,w->gs);
else { fprintf(stderr,"w_matmul: bad fmt %d\n",w->fmt); exit(1); }
}
/* f32 GEMM with Metal dispatch: y[S,O] = x[S,I] @ W[O,I]^T */
static void k3_matmul_f32(void *tens, float *y, const float *x, const float *W, int S, int I, int O){
#ifdef COLI_METAL
if(g_k3_metal && coli_metal_available()){
coli_metal_matmul((ColiMetalTensor**)tens, y, x, W, NULL, 0, S, I, O, 0);
return;
}
#endif
matmul(y,x,W,S,I,O);
}
/* acc[0..I) += coef * row r (MLA absorb builds q_abs from kv_b rows) */
static void w_addrow(const W *w, int r, float coef, float *acc){
int I=w->I;
if(w->fmt==0){ const float *p=w->f+(int64_t)r*I; for(int i=0;i<I;i++) acc[i]+=coef*p[i]; }
else if(w->fmt==1){ const int8_t *p=w->q8+(int64_t)r*I; float s=w->s[r]*coef;
for(int i=0;i<I;i++) acc[i]+=s*p[i]; }
else { int rb=(I+1)/2, ng=(I+w->gs-1)/w->gs; const uint8_t *p=w->q4+(int64_t)r*rb;
const float *scl=w->s+(int64_t)r*ng;
for(int g=0;g*w->gs<I;g++){ float s=scl[g]*coef; int e=(g+1)*w->gs; if(e>I)e=I;
for(int i=g*w->gs;i<e;i+=2){ uint8_t b=p[i>>1];
acc[i]+=s*(float)((int)(b&0xF)-8);
if(i+1<e) acc[i+1]+=s*(float)((int)(b>>4)-8); } } }
}
static float w_rowdot(const W *w, int r, const float *x){
int I=w->I; float a=0;
if(w->fmt==0){ const float *p=w->f+(int64_t)r*I; for(int i=0;i<I;i++) a+=x[i]*p[i]; return a; }
if(w->fmt==1){ const int8_t *p=w->q8+(int64_t)r*I; for(int i=0;i<I;i++) a+=x[i]*p[i]; return a*w->s[r]; }
{ int rb=(I+1)/2, ng=(I+w->gs-1)/w->gs; const uint8_t *p=w->q4+(int64_t)r*rb;
const float *scl=w->s+(int64_t)r*ng;
for(int g=0;g*w->gs<I;g++){ float ga=0; int e=(g+1)*w->gs; if(e>I)e=I;
for(int i=g*w->gs;i<e;i+=2){ uint8_t b=p[i>>1];
ga+=x[i]*(float)((int)(b&0xF)-8);
if(i+1<e) ga+=x[i+1]*(float)((int)(b>>4)-8); }
a+=ga*scl[g]; } }
return a;
}
#define QCHUNK 1024 /* rows per load-quantize pass */
static int g_bits_env=0; /* K3_BITS explicitly set: enables the
* int8-container -> int4 load downcast */
static int g_k3_mmap=0; /* prepared U8/F32 tensors stay file-backed */
static uint64_t g_k3_mmap_bytes=0, g_k3_mmap_views=0;
#ifdef COLI_CUDA
static int g_k3_cuda=0; /* K3_CUDA=1: MXFP4 routed experts on CUDA at decode */
#endif
static int g_k3_direct=-1; /* K3_DIRECT: O_DIRECT expert reads */
static int g_k3_idot=1; /* K3_IDOT: int8-activation expert matmuls */
static int g_k3_pipe=1; /* K3_PIPE: overlap loads with compute */
static float g_k3_topp=0.f; /* K3_TOPP: routed-expert top-p pruning */
enum { K3_CKPT_MAX = 8 };
static size_t k3_ckpt_blob_floats(const Model *m); /* def. with the ckpt block */
static double k3_ckpt_reserve_gb(const Model *m, int slots);
static int g_k3_ckpt_slots=0; /* COLI_K3_CKPT: recurrent-state checkpoint
* slots. STRICTLY OPT-IN, 0 = off (default,
* engine behaves exactly as before). */
static const char *g_k3_ckpt_dir=NULL; /* COLI_K3_CKPT_DIR: park the photos in
* files instead of RAM (low-RAM machines:
* ~0.4s of sequential I/O per restore
* against minutes of avoided re-prefill). */
static int k3_mmap_backend_allowed(int mmap_enabled, int vk_enabled, int cuda_enabled){
return !mmap_enabled || (!vk_enabled && !cuda_enabled);
}
static void w_map_prepared(Model *m, W *w, const char *name, const char *scale_name,
st_tensor *t, st_tensor *ts){
if(ts->dtype!=2){
fprintf(stderr,"K3_MMAP=1 requires F32 scale sidecars; %s is %s -- refusing\n",
scale_name,st_dtype_name(ts->dtype)); exit(1);
}
if(st_map_raw(&m->S,name,&w->data_map)!=0){
fprintf(stderr,"K3_MMAP=1 could not map %s: %s -- refusing\n",name,strerror(errno)); exit(1);
}
if(st_map_raw(&m->S,scale_name,&w->scale_map)!=0){
int saved=errno; st_unmap_raw(&w->data_map);
fprintf(stderr,"K3_MMAP=1 could not map %s: %s -- refusing\n",scale_name,strerror(saved)); exit(1);
}
if(((uintptr_t)w->scale_map.data%_Alignof(float))!=0){
st_unmap_raw(&w->scale_map); st_unmap_raw(&w->data_map);
fprintf(stderr,"K3_MMAP=1 scale sidecar %s is not float-aligned -- refusing\n",scale_name); exit(1);
}
w->mapped=1;
w->s=(float*)w->scale_map.data;
g_k3_mmap_bytes+=(uint64_t)t->nbytes+(uint64_t)ts->nbytes;
g_k3_mmap_views+=2;
}
static void w_release_host(W *w){
if(!w) return;
if(w->mapped){ st_unmap_raw(&w->scale_map); st_unmap_raw(&w->data_map); }
else { free(w->f); free(w->q8); free(w->q4); free(w->s); }
#ifdef COLI_VULKAN
free(w->vk_name);
#endif
memset(w,0,sizeof(*w));
}
static void w_load(Model *m, W *w, const char *name, int O, int I, int bits){
char nm[512]; snprintf(nm,sizeof(nm),"%s%s",m->pfx,name);
st_tensor *t=st_find(&m->S,nm);
if(!t) st_die_missing(&m->S,nm);
memset(w,0,sizeof(*w)); w->O=O; w->I=I;
#ifdef COLI_VULKAN
w->vk_name=strdup(name); w->vk_bits=bits; /* to read it back as it is read now (k3_w_reload) */
if(!w->vk_name){fprintf(stderr,"OOM weight name\n");exit(1);}
#endif
if(t->dtype==3){
/* repacked container (tools/k3_repack.py): pre-quantized U8 + .qs f32
* scales β no load-time quantization, K3_BITS is ignored for these
* (except the explicit =4 downcast below) */
char qn[560]; snprintf(qn,sizeof(qn),"%s.qs",nm);
st_tensor *ts=st_find(&m->S,qn);
if(!ts){ fprintf(stderr,"%s: quantized (U8) but no %s scale sidecar\n",nm,qn); exit(1); }
if(t->nbytes==(int64_t)O*I && ts->numel==O){ /* int8 per-row */
if(g_bits_env && bits==4 && I%64==0){
if(g_k3_mmap){
fprintf(stderr,"K3_MMAP=1 cannot combine with load-time int8-to-int4 conversion for %s; use a prepared int4 container or unset K3_BITS -- refusing\n",nm);
exit(1);
}
/* EXPLICIT K3_BITS=4 on an int8 container: downcast to int4-g64
* at load. Halves resident RAM (the 62 GB box cannot hold the
* 93-layer non-expert set at int8 next to a desktop session);
* the int8 grid is 16x finer than int4, so the double-quant
* noise ~ the direct-int4 noise. Unset K3_BITS keeps the
* container's own bits β the default is untouched. */
int gs=64, rb=I/2, ng=I/gs;
int8_t *q8=malloc((size_t)O*I); float *s8=falloc(O);
if(!q8){fprintf(stderr,"OOM int8 tmp %s\n",nm);exit(1);}
st_read_raw(&m->S,nm,q8,1); st_read_f32(&m->S,qn,s8,0);
w->fmt=4; w->gs=gs;
w->q4=malloc((int64_t)O*rb); w->s=falloc((int64_t)O*ng);
if(!w->q4){fprintf(stderr,"OOM int4 %s\n",nm);exit(1);}
for(int r=0;r<O;r++){
const int8_t *src=q8+(int64_t)r*I; float sc8=s8[r];
uint8_t *dst=w->q4+(int64_t)r*rb; float *scl=w->s+(int64_t)r*ng;
for(int g=0;g<ng;g++){ const int8_t *gp=src+g*gs;
int am=0; for(int i=0;i<gs;i++){ int a=gp[i]<0?-gp[i]:gp[i]; if(a>am)am=a; }
float s=am*sc8/7.f; if(s<1e-20f)s=1e-20f; scl[g]=s; float inv=sc8/s;
for(int i=0;i<gs;i+=2){
int v0=(int)lrintf(gp[i]*inv); if(v0>7)v0=7; if(v0<-8)v0=-8;
int v1=(int)lrintf(gp[i+1]*inv); if(v1>7)v1=7; if(v1<-8)v1=-8;
dst[(g*gs+i)>>1]=(uint8_t)((v0+8)|((v1+8)<<4)); } } }
free(q8); free(s8);
return;
}
w->fmt=1;
if(g_k3_mmap){
w_map_prepared(m,w,nm,qn,t,ts); w->q8=(int8_t*)w->data_map.data;
return;
}
w->q8=malloc((size_t)O*I);
if(!w->q8){fprintf(stderr,"OOM int8 %s\n",nm);exit(1);}
st_read_raw(&m->S,nm,w->q8,1);
w->s=falloc(O); st_read_f32(&m->S,qn,w->s,0);
} else if(I%64==0 && t->nbytes==(int64_t)O*(I/2) && ts->numel==(int64_t)O*(I/64)){
w->fmt=4; w->gs=64; /* int4-g64 */
if(g_k3_mmap){
w_map_prepared(m,w,nm,qn,t,ts); w->q4=(uint8_t*)w->data_map.data;
return;
}
w->q4=malloc((size_t)O*(I/2));
if(!w->q4){fprintf(stderr,"OOM int4 %s\n",nm);exit(1);}
st_read_raw(&m->S,nm,w->q4,1);
w->s=falloc((int64_t)O*(I/64)); st_read_f32(&m->S,qn,w->s,0);
} else {
fprintf(stderr,"%s: U8 tensor is %lld bytes / %lld scales β matches neither int8 [%d,%d] nor int4-g64, refusing (untrusted container)\n",
nm,(long long)t->nbytes,(long long)ts->numel,O,I); exit(1);
}
return;
}
if(g_k3_mmap){
fprintf(stderr,"K3_MMAP=1 requires a fully prepared U8 + F32-sidecar container; %s is %s and would need load-time conversion -- refusing\n",
nm,st_dtype_name(t->dtype)); exit(1);
}
if(t->numel!=(int64_t)O*I){ fprintf(stderr,"%s: numel %lld != %dx%d\n",nm,(long long)t->numel,O,I); exit(1); }
if(bits>=32){ w->fmt=0;
10BC8
w->f=falloc((int64_t)O*I); st_read_f32(&m->S,nm,w->f,0); return; }
int gs=64;
if(bits<=4 && I%gs){ bits=8; } /* int4-g64 wants I%64==0; fall back */
float *scr=falloc((int64_t)QCHUNK*I);
if(bits>4){ w->fmt=1; w->q8=malloc((int64_t)O*I); w->s=falloc(O);
if(!w->q8){fprintf(stderr,"OOM int8 %s\n",nm);exit(1);}
for(int r0=0;r0<O;r0+=QCHUNK){ int n=O-r0<QCHUNK?O-r0:QCHUNK;
st_read_slice_f32(&m->S,nm,(int64_t)r0*I,(int64_t)n*I,scr,1);
for(int r=0;r<n;r++){ const float *src=scr+(int64_t)r*I;
float am=0; for(int i=0;i<I;i++){ float a=fabsf(src[i]); if(a>am)am=a; }
float s=am/127.f; if(s<1e-20f)s=1e-20f; w->s[r0+r]=s; float inv=1.f/s;
int8_t *dst=w->q8+(int64_t)(r0+r)*I;
for(int i=0;i<I;i++){ int v=(int)lrintf(src[i]*inv); if(v>127)v=127; if(v<-127)v=-127; dst[i]=(int8_t)v; } } }
} else { w->fmt=4; w->gs=gs; int rb=I/2, ng=I/gs;
w->q4=malloc((int64_t)O*rb); w->s=falloc((int64_t)O*ng);
if(!w->q4){fprintf(stderr,"OOM int4 %s\n",nm);exit(1);}
for(int r0=0;r0<O;r0+=QCHUNK){ int n=O-r0<QCHUNK?O-r0:QCHUNK;
st_read_slice_f32(&m->S,nm,(int64_t)r0*I,(int64_t)n*I,scr,1);
for(int r=0;r<n;r++){ const float *src=scr+(int64_t)r*I;
uint8_t *dst=w->q4+(int64_t)(r0+r)*rb; float *scl=w->s+(int64_t)(r0+r)*ng;
for(int g=0;g<ng;g++){ const float *gp=src+g*gs;
float am=0; for(int i=0;i<gs;i++){ float a=fabsf(gp[i]); if(a>am)am=a; }
float s=am/7.f; if(s<1e-20f)s=1e-20f; scl[g]=s; float inv=1.f/s;
for(int i=0;i<gs;i+=2){
int v0=(int)lrintf(gp[i]*inv); if(v0>7)v0=7; if(v0<-8)v0=-8;
int v1=(int)lrintf(gp[i+1]*inv); if(v1>7)v1=7; if(v1<-8)v1=-8;
dst[(g*gs+i)>>1]=(uint8_t)((v0+8)|((v1+8)<<4)); } } } }
}
free(scr);
}
static float *f32_load(Model *m, const char *name, int64_t want){
char nm[512]; snprintf(nm,sizeof(nm),"%s%s",m->pfx,name);
st_tensor *t=st_find(&m->S,nm);
if(!t) st_die_missing(&m->S,nm);
if(want>0 && t->numel!=want){ fprintf(stderr,"%s: numel %lld != %lld\n",nm,(long long)t->numel,(long long)want); exit(1); }
float *p=falloc(t->numel); st_read_f32(&m->S,nm,p,0); return p;
}
#ifdef COLI_VULKAN
/* ---- the dense matrices on the device only (COLI_VK_DENSE_HOST) -----------------
* Decided once the device is open and before the expert cache is sized (k3_dho_decide),
* so the cache counts the dense weights out of RAM; placed in k3_vk_tier_start: every W
* goes up into its own vk (the chain adopts those copies), then its host copy is
* dropped, and the f32 matrices only the chain multiplies on the device (the routers,
* the KDA decay and beta projections) are dropped once the chain holds them. The CPU
* reads a matrix back from disk when it needs it after all: w_matmul after a lost
* device, the CPU MLA path's kv_b rows, the CPU KDA and router matmuls (k3_f32_need). */
static Model *g_k3_dho_model;
static size_t g_k3_dho_bytes; /* what will be dropped: RAM the expert cache may count on */
static pthread_mutex_t g_k3_dho_mx=PTHREAD_MUTEX_INITIALIZER;
static size_t k3_w_host_bytes(const W *w){
if(w->fmt==0) return w->f?(size_t)w->O*w->I*4:0;
if(w->fmt==1) return w->q8?(size_t)w->O*w->I+(size_t)w->O*4:0;
if(w->fmt==4) return w->q4?(size_t)w->O*((w->I+1)/2)+(size_t)w->O*((w->I+w->gs-1)/w->gs)*4:0;
return 0;
}
static void k3_w_reload(W *w){
pthread_mutex_lock(&g_k3_dho_mx);
if(w->vk_gone){
Model *m=g_k3_dho_model;
if(!m||!w->vk_name){fprintf(stderr,"[VK] kimi_k3: a dense matrix the device held alone cannot be read back\n");exit(1);}
W t; w_load(m,&t,w->vk_name,w->O,w->I,w->vk_bits);
if(t.fmt!=w->fmt||t.gs!=w->gs){fprintf(stderr,"[VK] kimi_k3: %s came back in another form\n",w->vk_name);exit(1);}
w->f=t.f; w->q8=t.q8; w->q4=t.q4; w->s=t.s;
free(t.vk_name);
w->vk_gone=0;
coli_vk_dense_host_reloaded(k3_w_host_bytes(w));
}
pthread_mutex_unlock(&g_k3_dho_mx);
}
/* The f32 matrices the chain holds on the device: where each lives, and its name. */
typedef struct { float **p; char name[160]; int64_t n; } K3F32Home;
static K3F32Home *g_k3_f32; static int g_k3_f32_n;
/* A dropped f32 matrix the CPU needs: read it back (NULL is "dropped": loaded ones never are). */
static void k3_f32_need(float **p){
if(*p) return;
pthread_mutex_lock(&g_k3_dho_mx);
if(!*p){
for(int i=0;i<g_k3_f32_n;i++) if(g_k3_f32[i].p==p){
*p=f32_load(g_k3_dho_model,g_k3_f32[i].name,g_k3_f32[i].n);
coli_vk_dense_host_reloaded((size_t)g_k3_f32[i].n*4);
break;
}
if(!*p){fprintf(stderr,"[VK] kimi_k3: an f32 matrix the device held alone cannot be read back\n");exit(1);}
}
pthread_mutex_unlock(&g_k3_dho_mx);
}
#define K3_F32_NEED(p) k3_f32_need(&(p))
/* y = x W^T on the device with the chain's copy of an f32 matrix (the device only: the CPU
* may hold none); 0 = the CPU multiplies, reading the matrix back first if it must. */
static int k3_f32_dev(void *t, float *y, const float *x, int S, int I, int O){
return g_k3_dho&&g_k3_vk&&t&&S>=1&&S<=65535&&!k3_in_par()&&
coli_vk_matmul((ColiVkTensor**)&t,y,x,NULL,NULL,10,S,I,O,0);
}
#define K3_F32_DEV(t,y,x,S,I,O) k3_f32_dev(t,y,x,S,I,O)
/* Every W of the model, in a fixed order (with a partial chain, its layers' and the head
* only when it goes to the device as well). */
static void k3_dho_each(Model *m, void (*f)(W *, size_t *, int *), size_t *b, int *n){
for(int i=0;i<m->c.n_layers&&i<g_k3_dho_layers;i++){
Layer *l=&m->L[i];
if(l->kda){ Kda *a=&l->a; W *ws[]={&a->q,&a->k,&a->v,&a->g,&a->o}; for(size_t k=0;k<5;k++) f(ws[k],b,n); }
else { Mla *a=&l->m; W *ws[]={&a->qa,&a->qb,&a->kva,&a->kvb,&a->o,&a->g,&a->wk,&a->wq,&a->wp}; for(size_t k=0;k<9;k++) f(ws[k],b,n); }
if(l->sparse){ Moe *o=&l->moe; W *ws[]={&o->lat_down,&o->lat_up,&o->sh_gate,&o->sh_up,&o->sh_down}; for(size_t k=0;k<5;k++) f(ws[k],b,n); }
else { W *ws[]={&l->d_gate,&l->d_up,&l->d_down}; for(size_t k=0;k<3;k++) f(ws[k],b,n); }
}
if(m->has_head&&g_k3_dho_head) f(&m->lm_head,b,n);
}
static void k3_dho_count(W *w, size_t *b, int *n){ size_t x=k3_w_host_bytes(w); if(x&&!w->mapped&&k3_vk_fmt(w)>0){ *b+=x; (*n)++; } }
/* The f32 matrices the chain multiplies on the device: the routers, the KDA decay pair and beta. */
static size_t k3_dho_f32_bytes(const Model *m){
const Cfg *c=&m->c; size_t b=0;
for(int i=0;i<c->n_layers&&i<g_k3_dho_layers;i++){
const Layer *l=&m->L[i];
if(l->sparse&&l->moe.router) b+=(size_t)c->n_experts*c->hidden*4;
if(l->kda&&l->a.fa) b+=((size_t)c->kda_hd*c->hidden+(size_t)c->kda_proj*c->kda_hd+(size_t)c->kda_heads*c->hidden)*4;
}
return b;
}
/* Once the device is open and before the expert cache is sized: the decision, with the
* chain's own decision asked silently (k3c_start prints it later). The cache counts the
* W matrices out of RAM; the f32 ones only leave once the chain has them, so it does not
* count on those. */
static int k3c_fit_now(Model *m, int tier_on, int cuda_on); /* kimi_k3_chain.h */
static void k3_dho_decide(Model *m, int tier_on, int cuda_on){
if(!g_k3_vk) return;
int chain=!cuda_on&&!k3_dsa_indexer_on()&&coli_vk_chain_decide(NULL,tier_on,COLI_VK_CHAIN_UNMEASURED)!=COLI_VK_CHAIN_OFF;
int dense_on=coli_vk_dense()||chain;
if(k3c_fit_now(m,tier_on,cuda_on)){ /* a partial chain: its layers, and the head with the tail */
g_k3_dho_layers=g_k3_fit.n; g_k3_dho_head=g_k3_fit.n==m->c.n_layers&&g_k3_fit.tail;
chain=g_k3_fit.n>0; dense_on=chain||(coli_vk_dense()&&!g_k3_partial);
}
size_t b=0; int n=0;
k3_dho_each(m,k3_dho_count,&b,&n);
int on=coli_vk_dense_host_decide("kimi_k3",dense_on,b+(chain?k3_dho_f32_bytes(m):0));
if(g_k3_fit.L>0) coli_vk_dense_host_layers(g_k3_fit.n,m->c.n_layers);
if(!on) return;
g_k3_dho=1; g_k3_dho_model=m; g_k3_dho_bytes=b;
}
#else
#define K3_F32_NEED(p) ((void)0)
#define K3_F32_DEV(t,y,x,S,I,O) 0
#endif
/* ---------- config ---------- */
static double req_num(jval *r, const char *k){
jval *v=json_get(r,k);
if(!v||v->t!=J_NUM){ fprintf(stderr,"config.json: missing or non-numeric \"%s\"\n",k); exit(1); }
return v->num;
}
static void load_cfg(Cfg *c, const char *snap){
char path[2048]; snprintf(path,sizeof(path),"%s/config.json",snap);
long n; char *buf;
{ FILE *f=fopen(path,"rb"); if(!f){perror(path);exit(1);}
fseek(f,0,SEEK_END); n=ftell(f); fseek(f,0,SEEK_SET);
if(n<0||n>(64L<<20)){ fprintf(stderr,"%s: bad size\n",path); exit(1); }
buf=malloc((size_t)n+1); if(!buf){fprintf(stderr,"OOM cfg\n");exit(1);}
if(fread(buf,1,(size_t)n,f)!=(size_t)n){ fprintf(stderr,"%s: short read\n",path); exit(1); }
buf[n]=0; fclose(f); }
char *arena=NULL; jval *root=json_parse(buf,&arena);
jval *tc=json_get(root,"text_config"); if(!tc||tc->t!=J_OBJ) tc=root;
memset(c,0,sizeof(*c));
c->hidden =(int)req_num(tc,"hidden_size");
c->n_layers =(int)req_num(tc,"num_hidden_layers");
c->vocab =(int)req_num(tc,"vocab_size");
c->first_dense =(int)req_num(tc,"first_k_dense_replace");
c->dense_inter =(int)req_num(tc,"intermediate_size");
c->n_heads =(int)req_num(tc,"num_attention_heads");
c->q_lora =(int)req_num(tc,"q_lora_rank");
c->kv_lora =(int)req_num(tc,"kv_lora_rank");
c->qk_nope =(int)req_num(tc,"qk_nope_head_dim");
c->qk_rope =(int)req_num(tc,"qk_rope_head_dim");
c->v_head =(int)req_num(tc,"v_head_dim");
c->n_experts =(int)req_num(tc,"num_experts");
c->topk =(int)req_num(tc,"num_experts_per_token");
c->moe_inter =(int)req_num(tc,"moe_intermediate_size");
c->latent =(int)req_num(tc,"routed_expert_hidden_size");
c->n_shared =(int)req_num(tc,"num_shared_experts");
c->res_bs =(int)req_num(tc,"attn_res_block_size");
c->situ_b1 =(float)req_num(tc,"activation_situ_beta");
c->situ_b2 =(float)req_num(tc,"activation_situ_linear_beta");
jval *ep=json_get(tc,"rms_norm_eps"); c->eps=ep?(float)ep->num:1e-5f;
jval *rp=json_get(tc,"rope_parameters");
if(rp&&rp->t==J_OBJ){ jval *th=json_get(rp,"rope_theta"); c->theta=th?(float)th->num:10000.f; }
else c->theta=10000.f;
c->qk_head=c->qk_nope+c->qk_rope;
c->attn_scale=1.f/sqrtf((float)c->qk_head);
jval *la=json_get(tc,"linear_attn_config");
if(!la||la->t!=J_OBJ){ fprintf(stderr,"config.json: missing linear_attn_config\n"); exit(1); }
c->kda_heads=(int)req_num(la,"num_heads");
c->kda_hd =(int)req_num(la,"head_dim");
c->conv_k =(int)req_num(la,"short_conv_kernel_size");
jval *lb=json_get(la,"gate_lower_bound"); c->gate_lb=lb?(float)lb->num:-5.f;
c->kda_proj=c->kda_heads*c->kda_hd;
if(c->hidden<1||c->hidden>65536||c->n_layers<1||c->n_layers>128||
c->n_experts<1||c->n_experts>4096||c->topk<1||c->topk>64||c->topk>c->n_experts||
c->vocab<1||c->vocab>(1<<22)||c->kda_proj<1||c->kda_proj>(1<<20)||
c->conv_k<1||c->conv_k>8||c->latent<32||c->latent%32||c->moe_inter%32||
c->res_bs<1||c->kda_hd>512||c->kv_lora>4096){
fprintf(stderr,"config.json: dimension out of range\n"); exit(1); }
jval *kl=json_get(la,"kda_layers");
if(!kl||kl->t!=J_ARR){ fprintf(stderr,"config.json: missing kda_layers\n"); exit(1); }
for(int i=0;i<kl->len;i++){ int v=(int)kl->kids[i]->num; /* 1-indexed */
if(v>=1&&v<=c->n_layers) c->is_kda[v-1]=1; }
/* DSA indexer (optional β if absent in config, DSA is disabled) */
{ jval *jn=json_get(tc,"index_hd"); c->index_hd = jn&&jn->t==J_NUM ? (int)jn->num : 0; }
{ jval *jn=json_get(tc,"index_nh"); c->index_nh = jn&&jn->t==J_NUM ? (int)jn->num : 0; }
{ jval *jn=json_get(tc,"index_topk"); c->index_topk = jn&&jn->t==J_NUM ? (int)jn->num : 0; }
if(c->index_hd > 0){
/* Default: all MLA layers are "full" DSA layers (compute own Ic + top-K) */
for(int i=0;i<c->n_layers;i++) if(!c->is_kda[i]) c->idx_type[i]=1;
jval *il=json_get(tc,"index_layers");
if(il && il->t==J_ARR){
/* Override: explicit list of 1-indexed full DSA layers */
memset(c->idx_type, 0, sizeof(c->idx_type));
for(int i=0;i<il->len;i++){ int v=(int)il->kids[i]->num;
if(v>=1&&v<=c->n_layers) c->idx_type[v-1]=1; }
}
}
/* the DSA indexer ropes the first qk_rope_head_dim floats of each of its index_hd-long
* rows (dsa_rope) */
if(c->index_hd > 0 && c->index_hd < c->qk_rope){
fprintf(stderr,"config.json: index_hd=%d is shorter than qk_rope_head_dim=%d, which the "
"indexer ropes in each of its rows\n",c->index_hd,c->qk_rope); exit(1); }
jval *b=json_get(root,"bos_token_id"); if(!b) b=json_get(tc,"bos_token_id");
c->bos = b&&b->t==J_NUM ? (int)b->num : -1;
jval *e=json_get(root,"eos_token_id"); if(!e) e=json_get(tc,"eos_token_id");
if(e&&e->t==J_NUM) c->eos[c->n_eos++]=(int)e->num;
else if(e&&e->t==J_ARR) for(int i=0;i<e->len&&c->n_eos<8;i++) c->eos[c->n_eos++]=(int)e->kids[i]->num;
free(buf); (void)arena;
}
/* ---------- init ---------- */
static void expert_table_init(Model *m){
Cfg *c=&m->c;
m->e_w1p=(int64_t)c->moe_inter*(c->latent/2); m->e_w1s=(int64_t)c->moe_inter*(c->latent/32);
m->e_w2p=(int64_t)c->latent*(c->moe_inter/2); m->e_w2s=(int64_t)c->latent*(c->moe_inter/32);
m->e_slot=2*(m->e_w1p+m->e_w1s)+m->e_w2p+m->e_w2s;
m->eref=calloc((size_t)c->n_layers*c->n_experts,sizeof(ERef));
if(!m->eref){fprintf(stderr,"OOM expert table\n");exit(1);}
const char *mat[3]={"w1","w2","w3"};
int64_t want[6]={m->e_w1p,m->e_w1s,m->e_w2p,m->e_w2s,m->e_w1p,m->e_w1s};
int missing=0;
for(int li=0;li<c->n_layers;li++){
if(!m->L[li].sparse) continue;
for(int e2=0;e2<c->n_experts;e2++){
ERef *er=&m->eref[(int64_t)li*c->n_experts+e2];
for(int k=0;k<6;k++){
char nm[512];
snprintf(nm,sizeof(nm),"%smodel.layers.%d.block_sparse_moe.experts.%d.%s.weight_%s",
m->pfx,li,e2,mat[k/2],(k&1)?"scale":"packed");
st_tensor *t=st_find(&m->S,nm);
if(!t){ missing++; er->fd[k]=-1; continue; }
if(t->nbytes!=want[k]){ fprintf(stderr,"%s: %lld bytes, expected %lld β refusing (untrusted container)\n",
nm,(long long)t->nbytes,(long long)want[k]); exit(1); }
er->fd[k]=t->fd; er->off[k]=t->off;
}
/* HF shards store the six tensors back-to-back (measured: 0 gaps
* across a whole layer) β collapse the load to ONE pread when so */
er->contig=1;
for(int k=0;k<5;k++)
if(er->fd[k]!=er->fd[k+1]||er->off[k]+want[k]!=er->off[k+1]) er->contig=0;
}
}
if(missing) fprintf(stderr,"[K3] WARNING: %d expert tensors missing (incomplete download?) β touching one aborts\n",missing);
}
static void model_init_range(Model *m, const char *snap, int layer_begin,
int layer_end, int truncate_model,
int load_boundaries, int allocate_state,
int expert_cap_override, int context_hint,
int segment_mode){
memset(m,0,sizeof(*m));
load_cfg(&m->c,snap);
Cfg *c=&m->c;
if(truncate_model&&layer_end>0&&layer_end<c->n_layers) c->n_layers=layer_end;