File size: 46,501 Bytes
e8a992b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
"""Native Windows + NVIDIA CUDA (headerless NVRTC) runtime for WebBrain-LingLoop-8B-A1.3B (bailingmoe3_loop).

Supports:
- Direct loading of Q6_K / Q8_0 / F16 / F32 tensors from GGUF onto GPU (~6.35 GiB VRAM on RTX 4070 Ti)
- 100% GPU-resident decode using custom Q6_K GEMV, Q6_K MoE fused Gate+Up+SwiGLU + Down, and KDA step CUDA kernels
- Fast absorbed-latent MLA attention (`kv_lora_rank=512, qk_rope_head_dim=64`) with interleaved RoPE (`rope_theta=6e6`)
- Exact 2-pass CrossPassLoopAdapter (core layers 4..19, isolated KV/KDA cache slots 0..39) + Coda layers 20..23
- Optional runtime Dual-Subspace WSP adapter (FP32 loop gate deltas + Coda rank-r LoRA, with optional tool_gated mode)
- Zero nvcc / triton / fla / einops dependencies.
"""

from __future__ import annotations

import json
import math
import os
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple

import gguf
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from safetensors.torch import load_file as load_safetensors

from .cuda_gguf_kernels import (
    Q6_K_BYTES,
    Q8_0_BYTES,
    QK_K,
    dequantize_q6_k_cuda,
    dequantize_q8_0_cuda,
    kda_step_cuda,
    naive_chunk_kda_torch,
    naive_recurrent_kda_torch,
    q6_k_gemv_cuda,
    q6_k_switch_gate_up_swiglu_cuda,
    q6_k_switch_gemv_cuda,
)


GGML_TYPE_F32 = 0
GGML_TYPE_F16 = 1
GGML_TYPE_Q8_0 = 8
GGML_TYPE_Q6_K = 14


def rms_norm_fp32(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
    xf = x.float()
    return xf * torch.rsqrt(xf.pow(2).mean(dim=-1, keepdim=True) + eps)


def apply_rms_norm_weight(x: torch.Tensor, weight: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
    xf = x.float()
    y = xf * torch.rsqrt(xf.pow(2).mean(dim=-1, keepdim=True) + eps)
    return (y * weight.float()).to(x.dtype)


def rotate_half(x: torch.Tensor) -> torch.Tensor:
    d2 = x.shape[-1] // 2
    return torch.cat((-x[..., d2:], x[..., :d2]), dim=-1)


def apply_rotary_pos_emb_interleave(
    q: torch.Tensor,
    k: torch.Tensor,
    cos: torch.Tensor,
    sin: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
    # cos, sin: (B, S, D_rot) -> unsqueeze(1) -> (B, 1, S, D_rot)
    cos_u = cos.unsqueeze(1)
    sin_u = sin.unsqueeze(1)
    b, hq, s, d = q.shape
    qr = q.view(b, hq, s, d // 2, 2).transpose(4, 3).reshape(b, hq, s, d)
    bk, hk, sk, dk = k.shape
    kr = k.view(bk, hk, sk, dk // 2, 2).transpose(4, 3).reshape(bk, hk, sk, dk)
    q_embed = (qr * cos_u) + (rotate_half(qr) * sin_u)
    k_embed = (kr * cos_u) + (rotate_half(kr) * sin_u)
    return q_embed, k_embed


@dataclass
class LingLoopConfig:
    hidden_size: int = 1536
    intermediate_size: int = 4608
    first_k_dense_replace: int = 1
    num_hidden_layers: int = 24
    layer_group_size: int = 4
    num_attention_heads: int = 16
    num_key_value_heads: int = 16
    head_dim: int = 128
    q_lora_rank: int = 256
    kv_lora_rank: int = 512
    qk_nope_head_dim: int = 128
    qk_rope_head_dim: int = 64
    qk_head_dim: int = 192
    v_head_dim: int = 128
    rope_theta: float = 6000000.0
    rope_interleave: bool = True
    rms_norm_eps: float = 1e-6
    num_experts: int = 128
    num_experts_per_tok: int = 8
    n_group: int = 8
    topk_group: int = 4
    moe_intermediate_size: int = 512
    moe_shared_expert_intermediate_size: int = 512
    routed_scaling_factor: float = 2.5
    vocab_size: int = 157184
    eos_token_id: int = 156895
    pad_token_id: int = 156892
    short_conv_kernel_size: int = 4
    kda_lower_bound: float = -5.0
    loop_core_start: int = 4
    loop_core_end: int = 20
    loop_num_passes: int = 2
    loop_gate_rank: int = 64

    @classmethod
    def from_json(cls, path: str) -> "LingLoopConfig":
        with open(path, "r", encoding="utf-8") as f:
            d = json.load(f)
        valid = {k: v for k, v in d.items() if k in cls.__dataclass_fields__}
        return cls(**valid)


@dataclass
class QuantLinear:
    """GPU-resident weight linear layer supporting Q6_K, Q8_0, F16, and F32 + optional rank-r LoRA overlay."""
    in_features: int
    out_features: int
    qtype: int
    data: torch.Tensor  # uint8 bytes (Q6_K / Q8_0) or float16/float32 (out, in)
    lora_a: Optional[torch.Tensor] = None  # (r, in) fp16
    lora_b: Optional[torch.Tensor] = None  # (out, r) fp16
    lora_scale: float = 0.0
    lora_tool_scale: Optional[float] = None

    def set_lora(
        self,
        a: torch.Tensor,
        b: torch.Tensor,
        scale: float = 1.0,
        tool_scale: Optional[float] = None,
    ) -> None:
        self.lora_a = a.to(device=self.data.device, dtype=torch.float16).contiguous()
        self.lora_b = b.to(device=self.data.device, dtype=torch.float16).contiguous()
        self.lora_scale = float(scale)
        self.lora_tool_scale = None if tool_scale is None else float(tool_scale)

    def clear_lora(self) -> None:
        self.lora_a = None
        self.lora_b = None
        self.lora_scale = 0.0
        self.lora_tool_scale = None

    def to_fp16(self) -> torch.Tensor:
        if self.qtype == GGML_TYPE_Q6_K:
            return dequantize_q6_k_cuda(self.data, (self.out_features, self.in_features), torch.float16)
        if self.qtype == GGML_TYPE_Q8_0:
            return dequantize_q8_0_cuda(self.data, (self.out_features, self.in_features), torch.float16)
        if self.qtype == GGML_TYPE_F16:
            return self.data
        if self.qtype == GGML_TYPE_F32:
            return self.data.to(torch.float16)
        raise ValueError(f"Unsupported qtype {self.qtype}")

    def forward(self, x: torch.Tensor, active_tool_mode: bool = False) -> torch.Tensor:
        orig_shape = x.shape[:-1]
        m = x.numel() // self.in_features
        x_2d = x.reshape(m, self.in_features)
        if x_2d.dtype != torch.float16:
            x_2d_h = x_2d.to(torch.float16)
        else:
            x_2d_h = x_2d

        if self.qtype == GGML_TYPE_Q6_K and m <= 8 and not x.requires_grad:
            out = q6_k_gemv_cuda(x_2d_h.contiguous(), self.data, self.in_features, self.out_features)
        elif self.qtype == GGML_TYPE_F16:
            out = F.linear(x_2d_h, self.data)
        elif self.qtype == GGML_TYPE_F32:
            out = F.linear(x_2d.float(), self.data).to(torch.float16)
        else:
            w = self.to_fp16()
            out = F.linear(x_2d_h, w)

        if self.lora_a is not None and self.lora_b is not None:
            sc = self.lora_tool_scale if (active_tool_mode and self.lora_tool_scale is not None) else self.lora_scale
            if sc != 0.0:
                delta = F.linear(F.linear(x_2d_h, self.lora_a), self.lora_b) * sc
                out = out + delta

        return out.view(*orig_shape, self.out_features)


def _dequantize_q6_k_rows_torch(rows_u8: torch.Tensor, in_features: int) -> torch.Tensor:
    """Fast GPU/vectorized dequantization of gathered Q6_K rows (N, n_blocks * 210) -> (N, in_features) fp16."""
    n_rows = rows_u8.shape[0]
    n_blocks = in_features // QK_K
    b = rows_u8.view(n_rows, n_blocks, Q6_K_BYTES)
    ql = b[..., :128]
    qh = b[..., 128:192]
    sc = b[..., 192:208].to(torch.int8).to(torch.float32)
    d = b[..., 208:210].contiguous().view(torch.float16).to(torch.float32)  # (N, nb, 1)

    # Reshape ql -> (N, nb, 2, 64) for 2 halves of 128 elements each
    ql_2 = ql.view(n_rows, n_blocks, 2, 64)
    qh_2 = qh.view(n_rows, n_blocks, 2, 32)
    sc_2 = sc.view(n_rows, n_blocks, 2, 8)

    # Low 4 bits
    lo_0 = (ql_2[..., :32] & 0x0F).to(torch.int16)
    lo_1 = (ql_2[..., 32:64] & 0x0F).to(torch.int16)
    lo_2 = (ql_2[..., :32] >> 4).to(torch.int16)
    lo_3 = (ql_2[..., 32:64] >> 4).to(torch.int16)

    # High 2 bits from qh
    hi_0 = ((qh_2 >> 0) & 3).to(torch.int16) << 4
    hi_1 = ((qh_2 >> 2) & 3).to(torch.int16) << 4
    hi_2 = ((qh_2 >> 4) & 3).to(torch.int16) << 4
    hi_3 = ((qh_2 >> 6) & 3).to(torch.int16) << 4

    q0 = ((lo_0 | hi_0) - 32).to(torch.float32)  # (N, nb, 2, 32) -> l=0..31 -> scale is = l//16 (0 or 1)
    q1 = ((lo_1 | hi_1) - 32).to(torch.float32)  # -> y[l+32] -> is+2
    q2 = ((lo_2 | hi_2) - 32).to(torch.float32)  # -> y[l+64] -> is+4
    q3 = ((lo_3 | hi_3) - 32).to(torch.float32)  # -> y[l+96] -> is+6

    # Split 32 into (2, 16) so scale indexing matches sc_2[..., is + (l//16)]
    def _scale(q_part: torch.Tensor, s_off: int) -> torch.Tensor:
        q_s = q_part.view(n_rows, n_blocks, 2, 2, 16)
        s0 = sc_2[..., s_off + 0]
        s1 = sc_2[..., s_off + 1]
        s_pair = torch.stack([s0, s1], dim=-1).unsqueeze(-1)  # (N, nb, 2, 2, 1)
        return (d.unsqueeze(-1).unsqueeze(-1) * s_pair * q_s).reshape(n_rows, n_blocks, 2, 32)

    y0 = _scale(q0, 0)
    y1 = _scale(q1, 2)
    y2 = _scale(q2, 4)
    y3 = _scale(q3, 6)
    out = torch.cat([y0, y1, y2, y3], dim=-1)  # (N, nb, 2, 128)
    return out.reshape(n_rows, in_features).to(torch.float16)


class KDACacheSlot:
    def __init__(self, conv_q: torch.Tensor, conv_k: torch.Tensor, conv_v: torch.Tensor, state: torch.Tensor):
        self.conv_q = conv_q
        self.conv_k = conv_k
        self.conv_v = conv_v
        self.state = state


class MLACacheSlot:
    def __init__(self, max_seq: int, kv_lora_rank: int, rope_dim: int, device: torch.device, dtype: torch.dtype):
        self.k_a = torch.empty((1, max_seq, kv_lora_rank), device=device, dtype=dtype)
        self.k_rot = torch.empty((1, max_seq, rope_dim), device=device, dtype=dtype)
        self.seq_len = 0

    def append_and_view(self, new_ka: torch.Tensor, new_krot: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
        s = new_ka.shape[1]
        end = self.seq_len + s
        if end > self.k_a.shape[1]:
            new_max = max(end, self.k_a.shape[1] * 2)
            ka_big = torch.empty((1, new_max, self.k_a.shape[-1]), device=self.k_a.device, dtype=self.k_a.dtype)
            kr_big = torch.empty((1, new_max, self.k_rot.shape[-1]), device=self.k_rot.device, dtype=self.k_rot.dtype)
            ka_big[:, : self.seq_len] = self.k_a[:, : self.seq_len]
            kr_big[:, : self.seq_len] = self.k_rot[:, : self.seq_len]
            self.k_a, self.k_rot = ka_big, kr_big
        self.k_a[:, self.seq_len : end] = new_ka
        self.k_rot[:, self.seq_len : end] = new_krot
        self.seq_len = end
        return self.k_a[:, :end], self.k_rot[:, :end]


class LingLoopCache:
    """Isolated 40-slot hybrid cache (0..3 prelude, 4..19 Pass 0, 20..23 coda, 24..39 Pass 1)."""
    def __init__(self, cfg: LingLoopConfig, device: torch.device, max_seq: int = 8192):
        self.cfg = cfg
        self.device = device
        self.max_seq = max_seq
        total_slots = cfg.num_hidden_layers + (cfg.loop_num_passes - 1) * (cfg.loop_core_end - cfg.loop_core_start)
        self.slots: List[Optional[object]] = [None] * total_slots

    def reset(self) -> None:
        for i in range(len(self.slots)):
            if isinstance(self.slots[i], MLACacheSlot):
                self.slots[i].seq_len = 0
            else:
                self.slots[i] = None

    def get_seq_length(self, mla_slot: int = 3) -> int:
        s = self.slots[mla_slot]
        if isinstance(s, MLACacheSlot):
            return s.seq_len
        return 0


class KimiDeltaAttentionBlock:
    def __init__(self, cfg: LingLoopConfig):
        self.cfg = cfg
        self.attn_q: QuantLinear
        self.attn_k: QuantLinear
        self.attn_v: QuantLinear
        self.attn_output: QuantLinear
        self.ssm_f_a: QuantLinear
        self.ssm_g_a: QuantLinear
        self.ssm_beta: QuantLinear
        self.ssm_conv1d_q: torch.Tensor  # (2048, 1, 4) f32
        self.ssm_conv1d_k: torch.Tensor
        self.ssm_conv1d_v: torch.Tensor
        self.ssm_a: torch.Tensor  # (16,) f32 (A_log)
        self.ssm_dt_bias: torch.Tensor  # (2048,) f32
        self.ssm_norm: torch.Tensor  # (128,) f32
        self.conv_ksize = cfg.short_conv_kernel_size

    def _causal_conv1d_silu(
        self,
        x_proj: torch.Tensor,  # (B, S, 2048)
        w: torch.Tensor,       # (2048, 1, 4) f32
        conv_state: Optional[torch.Tensor],
        use_cache: bool,
    ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
        # x_c: (B, 2048, S)
        x_c = x_proj.transpose(1, 2).float()
        b, c, s = x_c.shape
        k_prev = self.conv_ksize - 1  # 3
        if conv_state is None:
            padded = F.pad(x_c, (k_prev, 0))
        else:
            padded = torch.cat([conv_state.float(), x_c], dim=-1)
        new_state = padded[:, :, -k_prev:].to(torch.float16).contiguous() if use_cache else None
        if s == 1:
            out = (padded * w.squeeze(1).unsqueeze(0)).sum(dim=-1, keepdim=True)
        else:
            out = F.conv1d(padded, w, bias=None, padding=0, groups=c)
        out = F.silu(out).transpose(1, 2).to(x_proj.dtype)
        return out, new_state

    def forward(
        self,
        hidden_states: torch.Tensor,
        cache: Optional[LingLoopCache],
        slot: int,
        active_tool_mode: bool = False,
    ) -> torch.Tensor:
        b, s, _ = hidden_states.shape
        h_dim = self.cfg.head_dim  # 128
        n_heads = self.cfg.num_attention_heads  # 16

        slot_obj = cache.slots[slot] if cache is not None else None
        cq = ck = cv = r_state = None
        if isinstance(slot_obj, KDACacheSlot):
            cq, ck, cv, r_state = slot_obj.conv_q, slot_obj.conv_k, slot_obj.conv_v, slot_obj.state

        q_raw = self.attn_q.forward(hidden_states, active_tool_mode)
        k_raw = self.attn_k.forward(hidden_states, active_tool_mode)
        v_raw = self.attn_v.forward(hidden_states, active_tool_mode)

        q_c, new_cq = self._causal_conv1d_silu(q_raw, self.ssm_conv1d_q, cq, cache is not None)
        k_c, new_ck = self._causal_conv1d_silu(k_raw, self.ssm_conv1d_k, ck, cache is not None)
        v_c, new_cv = self._causal_conv1d_silu(v_raw, self.ssm_conv1d_v, cv, cache is not None)

        f_raw = self.ssm_f_a.forward(hidden_states, active_tool_mode)
        beta = torch.sigmoid(self.ssm_beta.forward(hidden_states, active_tool_mode).float())  # (B, S, 16)

        q = q_c.view(b, s, n_heads, h_dim)
        k = k_c.view(b, s, n_heads, h_dim)
        v = v_c.view(b, s, n_heads, h_dim)
        f = f_raw.view(b, s, n_heads, h_dim).float()

        # Exact lowerbound KDA gate (GGUF ssm_a already stores exp(A_log))
        a_exp = self.ssm_a.view(1, 1, n_heads, 1)
        dt_b = self.ssm_dt_bias.view(1, 1, n_heads, h_dim)
        g_log = self.cfg.kda_lower_bound * torch.sigmoid(a_exp * (f + dt_b))

        # Exact L2 norm + 1/sqrt(d) scaling
        q_norm = F.normalize(q.float(), p=2, dim=-1) * (h_dim ** -0.5)
        k_norm = F.normalize(k.float(), p=2, dim=-1)

        if r_state is None:
            r_state = torch.zeros((b, n_heads, h_dim, h_dim), device=hidden_states.device, dtype=torch.float32)
        else:
            r_state = r_state.float().contiguous()

        if s == 1 and not hidden_states.requires_grad and cache is not None:
            # Fast single CUDA kernel decode step updating r_state in place
            o = kda_step_cuda(
                q_norm,
                k_norm,
                v,
                g_log,
                beta,
                r_state,
            )
            new_state = r_state
        elif s <= 8 and not hidden_states.requires_grad:
            o, new_state = naive_recurrent_kda_torch(q_norm, k_norm, v, g_log, beta, initial_state=r_state)
        else:
            o, new_state = naive_chunk_kda_torch(q_norm, k_norm, v, g_log, beta, initial_state=r_state, chunk_size=16)

        if cache is not None:
            cache.slots[slot] = KDACacheSlot(new_cq, new_ck, new_cv, new_state.detach())

        g_out = self.ssm_g_a.forward(hidden_states, active_tool_mode).view(b, s, n_heads, h_dim)
        # FusedRMSNormGated(activation='sigmoid')
        o_normed = apply_rms_norm_weight(o.float(), self.ssm_norm, self.cfg.rms_norm_eps)
        o_gated = (o_normed.float() * torch.sigmoid(g_out.float())).to(hidden_states.dtype)
        o_flat = o_gated.reshape(b, s, n_heads * h_dim)
        return self.attn_output.forward(o_flat, active_tool_mode)


class MultiLatentAttentionBlock:
    def __init__(self, cfg: LingLoopConfig):
        self.cfg = cfg
        self.attn_q_a: QuantLinear
        self.attn_q_a_norm: torch.Tensor  # (256,) f32
        self.attn_q_b: QuantLinear
        self.attn_kv_a_mqa: QuantLinear
        self.attn_kv_a_norm: torch.Tensor  # (512,) f32
        self.attn_k_b_w: torch.Tensor      # (16, 512, 128) fp16
        self.attn_v_b_w: torch.Tensor      # (16, 128, 512) fp16
        self.attn_gate: QuantLinear
        self.attn_output: QuantLinear
        self.scaling = cfg.qk_head_dim ** -0.5

    def forward(
        self,
        hidden_states: torch.Tensor,
        cos: torch.Tensor,
        sin: torch.Tensor,
        cache: Optional[LingLoopCache],
        slot: int,
        active_tool_mode: bool = False,
    ) -> torch.Tensor:
        b, s_q, _ = hidden_states.shape
        n_h = self.cfg.num_attention_heads
        d_nope = self.cfg.qk_nope_head_dim  # 128
        d_rope = self.cfg.qk_rope_head_dim  # 64
        kv_rank = self.cfg.kv_lora_rank     # 512

        q_lat = apply_rms_norm_weight(
            self.attn_q_a.forward(hidden_states, active_tool_mode), self.attn_q_a_norm, self.cfg.rms_norm_eps
        )
        q_all = self.attn_q_b.forward(q_lat, active_tool_mode).view(b, s_q, n_h, d_nope + d_rope).transpose(1, 2)
        q_pass, q_rot = torch.split(q_all, [d_nope, d_rope], dim=-1)

        kv_comp = self.attn_kv_a_mqa.forward(hidden_states, active_tool_mode)
        k_a_raw, k_rot = torch.split(kv_comp, [kv_rank, d_rope], dim=-1)
        k_a = apply_rms_norm_weight(k_a_raw, self.attn_kv_a_norm, self.cfg.rms_norm_eps)  # (B, S_q, 512)
        k_rot = k_rot.view(b, 1, s_q, d_rope)

        q_rot, k_rot = apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin)
        k_rot_sq = k_rot.squeeze(1)  # (B, S_q, 64)

        if cache is not None:
            slot_obj = cache.slots[slot]
            if not isinstance(slot_obj, MLACacheSlot):
                slot_obj = MLACacheSlot(cache.max_seq, kv_rank, d_rope, hidden_states.device, hidden_states.dtype)
                cache.slots[slot] = slot_obj
            k_a_all, k_rot_all = slot_obj.append_and_view(k_a, k_rot_sq)
            past_len = k_a_all.shape[1] - s_q
        else:
            k_a_all, k_rot_all = k_a, k_rot_sq
            past_len = 0

        s_kv = k_a_all.shape[1]

        # Absorbed MLA: exact algebraic equivalence to expanded (B, 16, S_kv, 128) K_pass & V!
        if b == 1 and not hidden_states.requires_grad:
            q_pass_abs = torch.bmm(q_pass[0].to(torch.float16), self.attn_k_b_w.transpose(-2, -1)).unsqueeze(0)
        else:
            q_pass_abs = torch.einsum("bhsn,hdn->bhsd", q_pass.float(), self.attn_k_b_w.float()).to(hidden_states.dtype)
        scores = (
            torch.matmul(q_pass_abs, k_a_all.unsqueeze(1).transpose(-2, -1))
            + torch.matmul(q_rot, k_rot_all.unsqueeze(1).transpose(-2, -1))
        ) * self.scaling

        if s_q > 1:
            q_idx = torch.arange(past_len, past_len + s_q, device=scores.device).unsqueeze(1)
            k_idx = torch.arange(s_kv, device=scores.device).unsqueeze(0)
            causal = k_idx > q_idx
            scores = scores.masked_fill(causal.unsqueeze(0).unsqueeze(0), float("-inf"))

        probs = F.softmax(scores.float(), dim=-1).to(hidden_states.dtype)  # (B, 16, S_q, S_kv)
        ctx_lat = torch.matmul(probs, k_a_all.unsqueeze(1))  # (B, 16, S_q, 512)
        if b == 1 and not hidden_states.requires_grad:
            attn_out = torch.bmm(ctx_lat[0].to(torch.float16), self.attn_v_b_w.transpose(-2, -1)).transpose(0, 1).unsqueeze(0)
        else:
            attn_out = torch.einsum("bhsd,hnd->bshn", ctx_lat.float(), self.attn_v_b_w.float()).to(hidden_states.dtype)

        # Head-wise sigmoid gate
        gate = torch.sigmoid(self.attn_gate.forward(hidden_states, active_tool_mode).float()).to(hidden_states.dtype)
        attn_out = attn_out * gate.unsqueeze(-1)
        attn_flat = attn_out.reshape(b, s_q, n_h * self.cfg.v_head_dim)
        return self.attn_output.forward(attn_flat, active_tool_mode)


class MoEBlock:
    def __init__(self, cfg: LingLoopConfig):
        self.cfg = cfg
        self.gate_inp: torch.Tensor        # (128, 1536) f32
        self.exp_probs_bias: torch.Tensor  # (128,) f32
        self.gate_exps_bytes: torch.Tensor # (128, 512, 1260) uint8
        self.up_exps_bytes: torch.Tensor   # (128, 512, 1260) uint8
        self.down_exps_bytes: torch.Tensor # (128, 1536, 420) uint8
        self.gate_shexp: QuantLinear
        self.up_shexp: QuantLinear
        self.down_shexp: QuantLinear

    def _route(self, x_2d: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
        n_tok = x_2d.shape[0]
        logits = F.linear(x_2d.float(), self.gate_inp)
        scores = torch.sigmoid(logits)
        scores_bias = scores + self.exp_probs_bias.unsqueeze(0)

        group_scores = scores_bias.view(n_tok, self.cfg.n_group, -1).topk(2, dim=-1)[0].sum(dim=-1)
        group_idx = torch.topk(group_scores, k=self.cfg.topk_group, dim=-1, sorted=False)[1]
        group_mask = torch.zeros_like(group_scores)
        group_mask.scatter_(1, group_idx, 1.0)
        score_mask = (
            group_mask.unsqueeze(-1)
            .expand(n_tok, self.cfg.n_group, self.cfg.num_experts // self.cfg.n_group)
            .reshape(n_tok, -1)
        )
        masked = scores_bias.masked_fill(~score_mask.bool(), float("-inf"))
        _, topk_idx = torch.topk(masked, k=self.cfg.num_experts_per_tok, dim=-1)
        topk_s = torch.gather(scores, dim=1, index=topk_idx)
        topk_w = (topk_s / (topk_s.sum(dim=-1, keepdim=True) + 1e-20)) * self.cfg.routed_scaling_factor
        return topk_idx, topk_w

    def forward(self, hidden_states: torch.Tensor, active_tool_mode: bool = False) -> torch.Tensor:
        orig_shape = hidden_states.shape
        x_2d = hidden_states.view(-1, self.cfg.hidden_size)
        n_tok = x_2d.shape[0]

        sh_h = F.silu(self.gate_shexp.forward(x_2d, active_tool_mode).float()) * self.up_shexp.forward(x_2d, active_tool_mode).float()
        sh_out = self.down_shexp.forward(sh_h.to(hidden_states.dtype), active_tool_mode)

        topk_idx, topk_w = self._route(x_2d)

        if not hidden_states.requires_grad and n_tok == 1:
            # Fast single-token CUDA MoE path!
            idx_i32 = topk_idx.to(torch.int32).contiguous()  # (1, 8)
            h_act = q6_k_switch_gate_up_swiglu_cuda(
                x_2d.to(torch.float16).contiguous(),
                idx_i32,
                self.gate_exps_bytes,
                self.up_exps_bytes,
                self.cfg.hidden_size,
                self.cfg.moe_intermediate_size,
                k_rep=self.cfg.num_experts_per_tok,
            )
            e_out = q6_k_switch_gemv_cuda(
                h_act,
                idx_i32,
                self.down_exps_bytes,
                self.cfg.moe_intermediate_size,
                self.cfg.hidden_size,
                k_rep=self.cfg.num_experts_per_tok,
                x_per_pair=True,
            )  # (1, 8, D)
            routed_out = (e_out.float() * topk_w.unsqueeze(-1)).sum(dim=1).to(hidden_states.dtype)
            return (routed_out + sh_out).view(orig_shape)

        # Prefill / autograd batched expert dispatch (grouped by unique expert index)
        flat_idx = topk_idx.view(-1)
        flat_w = topk_w.view(-1)
        tok_ids = torch.arange(n_tok, device=x_2d.device).unsqueeze(1).expand(-1, self.cfg.num_experts_per_tok).reshape(-1)
        acc = torch.zeros((n_tok, self.cfg.hidden_size), device=x_2d.device, dtype=torch.float32)

        unique_e = torch.unique(flat_idx)
        for e_id_t in unique_e.tolist():
            mask = flat_idx == e_id_t
            t_sel = tok_ids[mask]
            w_sel = flat_w[mask].unsqueeze(-1)
            xe = x_2d[t_sel].to(torch.float16)
            wg = dequantize_q6_k_cuda(
                self.gate_exps_bytes[e_id_t], (self.cfg.moe_intermediate_size, self.cfg.hidden_size), torch.float16
            )
            wu = dequantize_q6_k_cuda(
                self.up_exps_bytes[e_id_t], (self.cfg.moe_intermediate_size, self.cfg.hidden_size), torch.float16
            )
            wd = dequantize_q6_k_cuda(
                self.down_exps_bytes[e_id_t], (self.cfg.hidden_size, self.cfg.moe_intermediate_size), torch.float16
            )
            h_e = F.silu(F.linear(xe, wg).float()) * F.linear(xe, wu).float()
            y_e = F.linear(h_e.to(torch.float16), wd).float() * w_sel
            acc.index_add_(0, t_sel, y_e)

        return (acc.to(hidden_states.dtype) + sh_out).view(orig_shape)


class DenseMLPBlock:
    def __init__(self):
        self.ffn_gate: QuantLinear
        self.ffn_up: QuantLinear
        self.ffn_down: QuantLinear

    def forward(self, hidden_states: torch.Tensor, active_tool_mode: bool = False) -> torch.Tensor:
        g = F.silu(self.ffn_gate.forward(hidden_states, active_tool_mode).float())
        u = self.ffn_up.forward(hidden_states, active_tool_mode).float()
        return self.ffn_down.forward((g * u).to(hidden_states.dtype), active_tool_mode)


class CrossPassLayerGates:
    """Loop adapter weights for one core layer (attn & mlp DepthAttentionReader + CrossPassGate in FP32)."""
    def __init__(
        self,
        msg_q: torch.Tensor,      # (2, D) f32
        attn_down: torch.Tensor,  # (64, 2D) f32
        attn_forget: torch.Tensor,# (D, 64) f32
        attn_gain: torch.Tensor,  # (D, 64) f32
        ffn_down: torch.Tensor,   # (64, 2D) f32
        ffn_forget: torch.Tensor, # (D, 64) f32
        ffn_gain: torch.Tensor,   # (D, 64) f32
    ):
        self.msg_q = msg_q
        self.attn_down = attn_down
        self.attn_forget = attn_forget
        self.attn_gain = attn_gain
        self.ffn_down = ffn_down
        self.ffn_forget = ffn_forget
        self.ffn_gain = ffn_gain
        self.deltas: Dict[str, Tuple[torch.Tensor, float, Optional[float]]] = {}

    def _w(self, name: str, base: torch.Tensor, active_tool_mode: bool) -> torch.Tensor:
        item = self.deltas.get(name)
        if item is None:
            return base
        delta, sc, tool_sc = item
        s = tool_sc if (active_tool_mode and tool_sc is not None) else sc
        return base + s * delta

    def apply_attn(
        self, h: torch.Tensor, prev_states: torch.Tensor, eps: float, active_tool_mode: bool = False
    ) -> torch.Tensor:
        mq = self._w("loop_msg_query.weight", self.msg_q, active_tool_mode)[0]
        ad = self._w("loop_attn_ctrl_down.weight", self.attn_down, active_tool_mode)
        af = self._w("loop_attn_ctrl_forget.weight", self.attn_forget, active_tool_mode)
        ag = self._w("loop_attn_ctrl_gain.weight", self.attn_gain, active_tool_mode)
        return self._gate(h, prev_states, mq, ad, af, ag, eps)

    def apply_mlp(
        self, h: torch.Tensor, prev_states: torch.Tensor, eps: float, active_tool_mode: bool = False
    ) -> torch.Tensor:
        mq = self._w("loop_msg_query.weight", self.msg_q, active_tool_mode)[1]
        fd = self._w("loop_ffn_ctrl_down.weight", self.ffn_down, active_tool_mode)
        ff = self._w("loop_ffn_ctrl_forget.weight", self.ffn_forget, active_tool_mode)
        fg = self._w("loop_ffn_ctrl_gain.weight", self.ffn_gain, active_tool_mode)
        return self._gate(h, prev_states, mq, fd, ff, fg, eps)

    @staticmethod
    def _gate(
        x: torch.Tensor,
        prev_states: torch.Tensor,  # (B, S, L, D)
        q_vec: torch.Tensor,        # (D,)
        w_down: torch.Tensor,       # (r, 2D)
        w_forget: torch.Tensor,     # (D, r)
        w_gain: torch.Tensor,       # (D, r)
        eps: float,
    ) -> torch.Tensor:
        keys = rms_norm_fp32(prev_states, eps)
        scores = (keys * q_vec).sum(dim=-1) / math.sqrt(x.shape[-1])
        weights = F.softmax(scores, dim=-1)
        msg = (weights.unsqueeze(-1) * prev_states.float()).sum(dim=-2)  # (B, S, D)
        cat = torch.cat([rms_norm_fp32(x, eps), rms_norm_fp32(msg, eps)], dim=-1)
        h_g = F.linear(cat, w_down)
        forget = torch.tanh(F.linear(h_g, w_forget))
        gain = torch.tanh(F.linear(h_g, w_gain))
        delta = (-forget * x.float() + gain * msg).to(x.dtype)
        return x + delta


class LingLoopLayer:
    def __init__(self, idx: int, cfg: LingLoopConfig):
        self.idx = idx
        self.cfg = cfg
        self.is_mla = (idx % cfg.layer_group_size) == (cfg.layer_group_size - 1)
        self.is_dense = idx < cfg.first_k_dense_replace
        self.input_layernorm: torch.Tensor
        self.post_attention_layernorm: torch.Tensor
        self.attn: object  # KimiDeltaAttentionBlock or MultiLatentAttentionBlock
        self.mlp: object   # DenseMLPBlock or MoEBlock
        self.loop_gates: Optional[CrossPassLayerGates] = None

    def forward(
        self,
        h: torch.Tensor,
        cos: torch.Tensor,
        sin: torch.Tensor,
        cache: Optional[LingLoopCache],
        slot: int,
        prev_states: Optional[torch.Tensor] = None,
        active_tool_mode: bool = False,
    ) -> torch.Tensor:
        if prev_states is not None and self.loop_gates is not None:
            h_attn_in = self.loop_gates.apply_attn(h, prev_states, self.cfg.rms_norm_eps, active_tool_mode)
        else:
            h_attn_in = h

        norm_in = apply_rms_norm_weight(h_attn_in, self.input_layernorm, self.cfg.rms_norm_eps)
        if self.is_mla:
            attn_out = self.attn.forward(norm_in, cos, sin, cache, slot, active_tool_mode)
        else:
            attn_out = self.attn.forward(norm_in, cache, slot, active_tool_mode)
        h = h + attn_out

        if prev_states is not None and self.loop_gates is not None:
            h_mlp_in = self.loop_gates.apply_mlp(h, prev_states, self.cfg.rms_norm_eps, active_tool_mode)
        else:
            h_mlp_in = h

        norm_mlp = apply_rms_norm_weight(h_mlp_in, self.post_attention_layernorm, self.cfg.rms_norm_eps)
        mlp_out = self.mlp.forward(norm_mlp, active_tool_mode)
        return h + mlp_out


class LingLoopCudaModel:
    def __init__(self, cfg: LingLoopConfig, device: torch.device = torch.device("cuda:0")):
        self.cfg = cfg
        self.device = device
        self.token_embd_bytes: torch.Tensor
        self.output_norm: torch.Tensor
        self.output_weight: torch.Tensor  # (V, D) fp16
        self.layers: List[LingLoopLayer] = []
        self.linears_by_name: Dict[str, QuantLinear] = {}

        # Precompute inv_freq for RoPE
        half = cfg.qk_rope_head_dim // 2
        idx = torch.arange(0, cfg.qk_rope_head_dim, 2, device=device, dtype=torch.float32)
        self.inv_freq = 1.0 / (cfg.rope_theta ** (idx / cfg.qk_rope_head_dim))

    @classmethod
    def from_gguf(
        cls,
        gguf_path: str,
        config_path: str,
        device: torch.device = torch.device("cuda:0"),
        lm_head_fp16: bool = True,
    ) -> "LingLoopCudaModel":
        cfg = LingLoopConfig.from_json(config_path)
        model = cls(cfg, device=device)
        reader = gguf.GGUFReader(gguf_path, "r")
        tmap = {t.name: t for t in reader.tensors}

        def _raw_gpu_bytes(name: str, expected_rows: Optional[int] = None) -> torch.Tensor:
            t = tmap[name]
            arr = np.array(t.data, copy=True)
            ten = torch.from_numpy(arr).to(device=device)
            return ten

        def _f32_gpu(name: str, shape: Tuple[int, ...]) -> torch.Tensor:
            t = tmap[name]
            q = int(t.tensor_type)
            if q == GGML_TYPE_F32:
                arr = np.array(t.data, copy=True).reshape(shape)
                return torch.from_numpy(arr).to(device=device, dtype=torch.float32)
            if q == GGML_TYPE_F16:
                arr = np.array(t.data, copy=True).view(np.float16).reshape(shape)
                return torch.from_numpy(arr).to(device=device, dtype=torch.float32)
            raise ValueError(f"Expected F32/F16 for {name}, got {q}")

        def _qlinear(name: str, out_f: int, in_f: int) -> QuantLinear:
            t = tmap[name]
            q = int(t.tensor_type)
            arr = np.array(t.data, copy=True)
            if q == GGML_TYPE_Q6_K:
                data = torch.from_numpy(arr).to(device=device)
            elif q == GGML_TYPE_F16:
                data = torch.from_numpy(arr.view(np.float16).reshape(out_f, in_f)).to(device=device)
            elif q == GGML_TYPE_F32:
                data = torch.from_numpy(arr.reshape(out_f, in_f)).to(device=device, dtype=torch.float32)
            elif q == GGML_TYPE_Q8_0:
                data = torch.from_numpy(arr).to(device=device)
            else:
                raise ValueError(f"Unsupported qtype {q} for {name}")
            ql = QuantLinear(in_f, out_f, q, data)
            model.linears_by_name[name] = ql
            return ql

        # Globals
        model.token_embd_bytes = _raw_gpu_bytes("token_embd.weight")
        model.output_norm = _f32_gpu("output_norm.weight", (cfg.hidden_size,))
        out_t = tmap["output.weight"]
        out_arr = np.array(out_t.data, copy=True)
        if int(out_t.tensor_type) == GGML_TYPE_F32:
            out_ten = torch.from_numpy(out_arr.reshape(cfg.vocab_size, cfg.hidden_size))
            model.output_weight = out_ten.to(device=device, dtype=torch.float16 if lm_head_fp16 else torch.float32)
        else:
            model.output_weight = torch.from_numpy(out_arr.view(np.float16).reshape(cfg.vocab_size, cfg.hidden_size)).to(device=device)

        d = cfg.hidden_size
        kda_dim = cfg.num_attention_heads * cfg.head_dim  # 2048

        for l_idx in range(cfg.num_hidden_layers):
            layer = LingLoopLayer(l_idx, cfg)
            p = f"blk.{l_idx}"
            layer.input_layernorm = _f32_gpu(f"{p}.attn_norm.weight", (d,))
            layer.post_attention_layernorm = _f32_gpu(f"{p}.ffn_norm.weight", (d,))

            if layer.is_mla:
                att = MultiLatentAttentionBlock(cfg)
                att.attn_q_a = _qlinear(f"{p}.attn_q_a.weight", cfg.q_lora_rank, d)
                att.attn_q_a_norm = _f32_gpu(f"{p}.attn_q_a_norm.weight", (cfg.q_lora_rank,))
                att.attn_q_b = _qlinear(f"{p}.attn_q_b.weight", cfg.num_attention_heads * cfg.qk_head_dim, cfg.q_lora_rank)
                att.attn_kv_a_mqa = _qlinear(f"{p}.attn_kv_a_mqa.weight", cfg.kv_lora_rank + cfg.qk_rope_head_dim, d)
                att.attn_kv_a_norm = _f32_gpu(f"{p}.attn_kv_a_norm.weight", (cfg.kv_lora_rank,))

                kb_raw = _raw_gpu_bytes(f"{p}.attn_k_b.weight")
                kb_q = int(tmap[f"{p}.attn_k_b.weight"].tensor_type)
                if kb_q == GGML_TYPE_Q8_0:
                    att.attn_k_b_w = dequantize_q8_0_cuda(
                        kb_raw, (cfg.num_attention_heads, cfg.kv_lora_rank, cfg.qk_nope_head_dim), torch.float16
                    )
                else:
                    att.attn_k_b_w = dequantize_q6_k_cuda(
                        kb_raw, (cfg.num_attention_heads, cfg.kv_lora_rank, cfg.qk_nope_head_dim), torch.float16
                    )

                vb_raw = _raw_gpu_bytes(f"{p}.attn_v_b.weight")
                vb_q = int(tmap[f"{p}.attn_v_b.weight"].tensor_type)
                if vb_q == GGML_TYPE_Q6_K:
                    att.attn_v_b_w = dequantize_q6_k_cuda(
                        vb_raw, (cfg.num_attention_heads, cfg.v_head_dim, cfg.kv_lora_rank), torch.float16
                    )
                else:
                    att.attn_v_b_w = dequantize_q8_0_cuda(
                        vb_raw, (cfg.num_attention_heads, cfg.v_head_dim, cfg.kv_lora_rank), torch.float16
                    )

                att.attn_gate = _qlinear(f"{p}.attn_gate.weight", cfg.num_attention_heads, d)
                att.attn_output = _qlinear(f"{p}.attn_output.weight", d, cfg.num_attention_heads * cfg.v_head_dim)
                layer.attn = att
            else:
                att = KimiDeltaAttentionBlock(cfg)
                att.attn_q = _qlinear(f"{p}.attn_q.weight", kda_dim, d)
                att.attn_k = _qlinear(f"{p}.attn_k.weight", kda_dim, d)
                att.attn_v = _qlinear(f"{p}.attn_v.weight", kda_dim, d)
                att.attn_output = _qlinear(f"{p}.attn_output.weight", d, kda_dim)
                att.ssm_conv1d_q = _f32_gpu(f"{p}.ssm_conv1d_q.weight", (kda_dim, 1, cfg.short_conv_kernel_size))
                att.ssm_conv1d_k = _f32_gpu(f"{p}.ssm_conv1d_k.weight", (kda_dim, 1, cfg.short_conv_kernel_size))
                att.ssm_conv1d_v = _f32_gpu(f"{p}.ssm_conv1d_v.weight", (kda_dim, 1, cfg.short_conv_kernel_size))
                att.ssm_f_a = _qlinear(f"{p}.ssm_f_a.weight", kda_dim, d)
                att.ssm_g_a = _qlinear(f"{p}.ssm_g_a.weight", kda_dim, d)
                att.ssm_beta = _qlinear(f"{p}.ssm_beta.weight", cfg.num_attention_heads, d)
                att.ssm_a = _f32_gpu(f"{p}.ssm_a", (cfg.num_attention_heads,))
                att.ssm_dt_bias = _f32_gpu(f"{p}.ssm_dt.bias", (kda_dim,))
                att.ssm_norm = _f32_gpu(f"{p}.ssm_norm.weight", (cfg.head_dim,))
                layer.attn = att

            if layer.is_dense:
                mlp = DenseMLPBlock()
                mlp.ffn_gate = _qlinear(f"{p}.ffn_gate.weight", cfg.intermediate_size, d)
                mlp.ffn_up = _qlinear(f"{p}.ffn_up.weight", cfg.intermediate_size, d)
                mlp.ffn_down = _qlinear(f"{p}.ffn_down.weight", d, cfg.intermediate_size)
                layer.mlp = mlp
            else:
                mlp = MoEBlock(cfg)
                mlp.gate_inp = _f32_gpu(f"{p}.ffn_gate_inp.weight", (cfg.num_experts, d))
                mlp.exp_probs_bias = _f32_gpu(f"{p}.exp_probs_b.bias", (cfg.num_experts,))
                mlp.gate_exps_bytes = _raw_gpu_bytes(f"{p}.ffn_gate_exps.weight").view(
                    cfg.num_experts, cfg.moe_intermediate_size, -1
                )
                mlp.up_exps_bytes = _raw_gpu_bytes(f"{p}.ffn_up_exps.weight").view(
                    cfg.num_experts, cfg.moe_intermediate_size, -1
                )
                mlp.down_exps_bytes = _raw_gpu_bytes(f"{p}.ffn_down_exps.weight").view(
                    cfg.num_experts, d, -1
                )
                mlp.gate_shexp = _qlinear(f"{p}.ffn_gate_shexp.weight", cfg.moe_shared_expert_intermediate_size, d)
                mlp.up_shexp = _qlinear(f"{p}.ffn_up_shexp.weight", cfg.moe_shared_expert_intermediate_size, d)
                mlp.down_shexp = _qlinear(f"{p}.ffn_down_shexp.weight", d, cfg.moe_shared_expert_intermediate_size)
                layer.mlp = mlp

            if cfg.loop_core_start <= l_idx < cfg.loop_core_end:
                layer.loop_gates = CrossPassLayerGates(
                    msg_q=_f32_gpu(f"{p}.loop_msg_query.weight", (2, d)),
                    attn_down=_f32_gpu(f"{p}.loop_attn_ctrl_down.weight", (cfg.loop_gate_rank, 2 * d)),
                    attn_forget=_f32_gpu(f"{p}.loop_attn_ctrl_forget.weight", (d, cfg.loop_gate_rank)),
                    attn_gain=_f32_gpu(f"{p}.loop_attn_ctrl_gain.weight", (d, cfg.loop_gate_rank)),
                    ffn_down=_f32_gpu(f"{p}.loop_ffn_ctrl_down.weight", (cfg.loop_gate_rank, 2 * d)),
                    ffn_forget=_f32_gpu(f"{p}.loop_ffn_ctrl_forget.weight", (d, cfg.loop_gate_rank)),
                    ffn_gain=_f32_gpu(f"{p}.loop_ffn_ctrl_gain.weight", (d, cfg.loop_gate_rank)),
                )

            model.layers.append(layer)

        return model

    def clear_wsp_adapter(self) -> None:
        for ql in self.linears_by_name.values():
            ql.clear_lora()
        for layer in self.layers:
            if layer.loop_gates is not None:
                layer.loop_gates.deltas.clear()

    def apply_wsp_adapter(
        self,
        adapter_path: str,
        scale: float = 1.0,
        tool_scale: Optional[float] = None,
    ) -> Dict[str, int]:
        self.clear_wsp_adapter()
        st = load_safetensors(adapter_path, device=str(self.device))
        loop_applied = 0
        lora_applied = 0

        # 1. FP32 loop gate deltas: keys like "loop_delta.blk.16.loop_attn_ctrl_gain.weight"
        for k, v in st.items():
            if k.startswith("loop_delta."):
                raw_name = k[len("loop_delta.") :]
                parts = raw_name.split(".", 2)  # blk, 16, tensor_name
                l_idx = int(parts[1])
                t_name = parts[2]
                lg = self.layers[l_idx].loop_gates
                if lg is not None:
                    lg.deltas[t_name] = (v.to(device=self.device, dtype=torch.float32), float(scale), tool_scale)
                    loop_applied += 1

        # 2. Coda LoRA pairs: keys like "lora.blk.20.attn_output.weight.lora_A" & ".lora_B"
        for k in list(st.keys()):
            if k.startswith("lora.") and k.endswith(".lora_A"):
                t_name = k[len("lora.") : -len(".lora_A")]
                b_key = f"lora.{t_name}.lora_B"
                if b_key in st and t_name in self.linears_by_name:
                    self.linears_by_name[t_name].set_lora(st[k], st[b_key], scale=scale, tool_scale=tool_scale)
                    lora_applied += 1

        return {"loop_deltas": loop_applied, "lora_pairs": lora_applied}

    def embed_tokens(self, input_ids: torch.Tensor) -> torch.Tensor:
        b, s = input_ids.shape
        flat = input_ids.reshape(-1)
        rows = self.token_embd_bytes[flat]
        emb = _dequantize_q6_k_rows_torch(rows, self.cfg.hidden_size)
        return emb.view(b, s, self.cfg.hidden_size)

    def rope_cos_sin(self, position_ids: torch.Tensor, dtype: torch.dtype) -> Tuple[torch.Tensor, torch.Tensor]:
        inv = self.inv_freq[None, :, None].expand(position_ids.shape[0], -1, 1)
        pos = position_ids[:, None, :].float()
        freqs = torch.matmul(inv, pos).transpose(1, 2)  # (B, S, 32)
        emb = torch.cat((freqs, freqs), dim=-1)
        return emb.cos().to(dtype), emb.sin().to(dtype)

    @torch.no_grad()
    def forward_logits(
        self,
        input_ids: torch.Tensor,
        cache: Optional[LingLoopCache] = None,
        num_passes: Optional[int] = None,
        active_tool_mode: bool = False,
        last_token_only: bool = True,
    ) -> torch.Tensor:
        b, s = input_ids.shape
        past_len = cache.get_seq_length(self.cfg.layer_group_size - 1) if cache is not None else 0
        pos_ids = torch.arange(past_len, past_len + s, device=self.device, dtype=torch.long).unsqueeze(0).expand(b, -1)

        h = self.embed_tokens(input_ids)
        cos, sin = self.rope_cos_sin(pos_ids, h.dtype)

        cs = self.cfg.loop_core_start
        ce = self.cfg.loop_core_end
        core_len = ce - cs
        n_phys = self.cfg.num_hidden_layers
        passes = self.cfg.loop_num_passes if num_passes is None else num_passes

        # 1. Prelude (0..3)
        for l_idx in range(cs):
            h = self.layers[l_idx].forward(h, cos, sin, cache, l_idx, None, active_tool_mode)
        h_prelude = h

        # 2. Looped Core (4..19) x passes
        prev_states: Optional[torch.Tensor] = None
        for p_idx in range(passes):
            hp = h_prelude
            cur_states: List[torch.Tensor] = []
            for i, l_idx in enumerate(range(cs, ce)):
                slot = l_idx if p_idx == 0 else n_phys + (p_idx - 1) * core_len + i
                hp = self.layers[l_idx].forward(
                    hp, cos, sin, cache, slot, prev_states if p_idx >= 1 else None, active_tool_mode
                )
                cur_states.append(hp)
            prev_states = torch.stack(cur_states, dim=-2)  # (B, S, 16, D)
            h = hp

        # 3. Coda (20..23)
        for l_idx in range(ce, n_phys):
            h = self.layers[l_idx].forward(h, cos, sin, cache, l_idx, None, active_tool_mode)

        h_out = h[:, -1:, :] if last_token_only else h
        h_norm = apply_rms_norm_weight(h_out, self.output_norm, self.cfg.rms_norm_eps)
        if self.output_weight.dtype != h_norm.dtype:
            logits = F.linear(h_norm.to(self.output_weight.dtype), self.output_weight)
        else:
            logits = F.linear(h_norm, self.output_weight)
        return logits.float()

    @torch.no_grad()
    def generate(
        self,
        input_ids: List[int],
        max_new_tokens: int = 1024,
        temperature: float = 0.0,
        top_p: float = 1.0,
        stop_token_ids: Optional[List[int]] = None,
        active_tool_mode: bool = False,
        cache: Optional[LingLoopCache] = None,
    ) -> Tuple[List[int], float]:
        import time

        t0 = time.perf_counter()
        if cache is None:
            cache = LingLoopCache(self.cfg, self.device, max_seq=max(2048, len(input_ids) + max_new_tokens + 64))
        else:
            cache.reset()

        stops = set(stop_token_ids or [])
        stops.add(self.cfg.eos_token_id)

        inp = torch.tensor([input_ids], device=self.device, dtype=torch.long)
        logits = self.forward_logits(inp, cache=cache, active_tool_mode=active_tool_mode, last_token_only=True)

        generated: List[int] = []
        t_dec0 = time.perf_counter()
        for step in range(max_new_tokens):
            nxt_logits = logits[0, 0]
            if temperature <= 0.0:
                nxt_id = int(torch.argmax(nxt_logits).item())
            else:
                scaled = nxt_logits / max(temperature, 1e-5)
                probs = F.softmax(scaled, dim=-1)
                if top_p < 1.0:
                    sorted_p, sorted_i = torch.sort(probs, descending=True)
                    cdf = torch.cumsum(sorted_p, dim=-1)
                    mask = (cdf - sorted_p) > top_p
                    sorted_p = sorted_p.masked_fill(mask, 0.0)
                    probs = torch.zeros_like(probs).scatter_(0, sorted_i, sorted_p)
                    probs = probs / probs.sum()
                nxt_id = int(torch.multinomial(probs, num_samples=1).item())

            if nxt_id in stops:
                break
            generated.append(nxt_id)
            if step + 1 >= max_new_tokens:
                break
            step_t = torch.tensor([[nxt_id]], device=self.device, dtype=torch.long)
            logits = self.forward_logits(step_t, cache=cache, active_tool_mode=active_tool_mode, last_token_only=True)

        dt = max(1e-6, time.perf_counter() - t0)
        tok_s = len(generated) / dt
        return generated, tok_s