Repository navigation
Expand file tree
/
Copy pathcache.py
More file actions
1950 lines (1818 loc) · 81.5 KB
/
Copy pathcache.py
File metadata and controls
1950 lines (1818 loc) · 81.5 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
"""Physical anchor-plus-delta Cross-Loop KV cache.
This module never stores a four-loop BF16 prompt cache once construction returns.
Its Torch gather path is a correctness reference; GPU serving uses the fused reader.
"""
from __future__ import annotations
from typing import Callable, Sequence
import torch
from .packing import (
Packed4Bit,
pack_k_per_channel,
pack_v_per_token,
)
from .kivi_backend import (
KiviPacked4Bit,
kivi_cross_loop_pv,
kivi_cross_loop_qk,
kivi_fused_cross_loop_pv,
kivi_fused_cross_loop_qk,
kivi_fused_dense_source_attention,
kivi_fused_sparse_attention_delta,
kivi_outer_gemv,
kivi_selected_pv,
kivi_selected_qk,
load_kivi_outer_extension,
outer_matmul_reference,
pack_kivi_k_per_channel,
pack_kivi_v_per_token,
)
PackedKV = Packed4Bit | KiviPacked4Bit
_DENSE_SPLIT_CONTEXT_TOKENS = 2048
def _packed_attention_schedule(path: str, selected_rows: int) -> str:
"""Choose the measured A100 schedule for a packed attention reader.
Dense readers cross over at 2K tokens because the fused online-softmax
kernel serializes token tiles within one program per head. Long dense
reads use split-KV online softmax: independent token tiles followed by a
stable merge, avoiding materialized logits and weights. The default sparse
sparse path remains fused: its isolated split-KV kernel is faster at 8K,
but the extra system overhead regressed whole-model decode.
"""
if path == "dense":
return (
"split_kv"
if int(selected_rows) >= _DENSE_SPLIT_CONTEXT_TOKENS
else "fused"
)
if path == "sparse":
return "fused"
raise ValueError(f"unknown packed attention path: {path}")
def _tensor_bytes(value: torch.Tensor) -> int:
return int(value.numel() * value.element_size())
def _pack_key(
values: torch.Tensor,
group_size: int,
reader_backend: str = "triton_row",
) -> PackedKV:
if reader_backend == "kivi_outer":
return pack_kivi_k_per_channel(values, group_size=group_size)
if reader_backend != "triton_row":
raise ValueError("unknown KV reader backend")
if values.is_cuda and values.shape[-1] == 128 and int(group_size) == 64:
from .kernels.quantization import triton_pack_4bit
packed = triton_pack_4bit(values, axis="per_channel", group_size=group_size)
else:
packed = pack_k_per_channel(values, group_size=group_size)
if packed.row_groups is not None:
return packed
row_groups = torch.div(
torch.arange(
packed.original_shape[2],
device=packed.payload.device,
dtype=torch.int32,
),
int(group_size),
rounding_mode="floor",
)
return Packed4Bit(
payload=packed.payload,
minimum=packed.minimum,
scale=packed.scale,
original_shape=packed.original_shape,
original_dtype=packed.original_dtype,
axis=packed.axis,
group_size=packed.group_size,
row_groups=row_groups,
)
def _pack_value(
values: torch.Tensor,
group_size: int,
reader_backend: str = "triton_row",
) -> PackedKV:
if reader_backend == "kivi_outer":
return pack_kivi_v_per_token(values, group_size=group_size)
if reader_backend != "triton_row":
raise ValueError("unknown KV reader backend")
if values.is_cuda and values.shape[-1] == 128 and int(group_size) == 64:
from .kernels.quantization import triton_pack_4bit
return triton_pack_4bit(values, axis="per_token", group_size=group_size)
return pack_v_per_token(values, group_size=group_size)
def _decode_packed(packed: PackedKV) -> torch.Tensor:
"""Decode a CUDA stream with one kernel instead of Torch tensor plumbing."""
if isinstance(packed, Packed4Bit) and packed.payload.is_cuda:
from .kernels.quantization import triton_gather_dequantize
indices = torch.arange(
packed.original_shape[2],
device=packed.payload.device,
dtype=torch.int32,
)
return triton_gather_dequantize(
packed,
indices,
validate_indices=False,
)
return packed.decode()
def _decode_rows(packed: PackedKV, indices: torch.Tensor) -> torch.Tensor:
"""Reference-only logical row gather for audits and cache rollover."""
if isinstance(packed, Packed4Bit):
return packed.decode_rows(indices)
return packed.decode().index_select(2, indices.long())
def _concat_packed(left: PackedKV | None, right: PackedKV | None) -> PackedKV | None:
if left is None:
return right
if right is None:
return left
if isinstance(left, KiviPacked4Bit) or isinstance(right, KiviPacked4Bit):
if not isinstance(left, KiviPacked4Bit) or not isinstance(right, KiviPacked4Bit):
raise ValueError("cannot concatenate different packed KV layouts")
if (
left.axis != right.axis
or left.group_size != right.group_size
or left.original_dtype != right.original_dtype
or left.original_shape[:2] != right.original_shape[:2]
or left.original_shape[3] != right.original_shape[3]
):
raise ValueError("cannot concatenate incompatible packed streams")
left_tokens = int(left.original_shape[2])
right_tokens = int(right.original_shape[2])
# Decode rollover always appends a complete token group. KIVI's K
# payload is output-packed along tokens and its affine metadata is
# grouped along tokens, so a group/pack-aligned boundary can be joined
# directly. V is independently quantized per token and is therefore
# directly appendable at every token boundary. Avoiding decode +
# full-prefix repack makes rollover O(new_group) instead of O(context).
directly_appendable = left.axis == "per_token" or (
left_tokens % left.group_size == 0 and left_tokens % 8 == 0
)
if directly_appendable:
token_dimension = 2 if left.axis == "per_channel" else 3
return KiviPacked4Bit(
payload=torch.cat(
(left.payload, right.payload), dim=token_dimension
).contiguous(),
minimum=torch.cat(
(left.minimum, right.minimum), dim=token_dimension
).contiguous(),
scale=torch.cat(
(left.scale, right.scale), dim=token_dimension
).contiguous(),
original_shape=(
left.original_shape[0],
left.original_shape[1],
left_tokens + right_tokens,
left.original_shape[3],
),
original_dtype=left.original_dtype,
axis=left.axis,
group_size=left.group_size,
)
merged = torch.cat((left.decode(), right.decode()), dim=2)
if left.axis == "per_channel":
return pack_kivi_k_per_channel(merged, group_size=left.group_size)
return pack_kivi_v_per_token(merged, group_size=left.group_size)
if (
left.axis != right.axis
or left.group_size != right.group_size
or left.original_dtype != right.original_dtype
or left.original_shape[:2] != right.original_shape[:2]
or left.original_shape[3] != right.original_shape[3]
):
raise ValueError("cannot concatenate incompatible packed streams")
row_groups = None
if left.axis == "per_channel":
left_groups = left.row_groups
if left_groups is None:
left_groups = torch.div(
torch.arange(left.original_shape[2], device=left.payload.device),
left.group_size,
rounding_mode="floor",
).to(torch.int32)
right_groups = right.row_groups
if right_groups is None:
right_groups = torch.div(
torch.arange(right.original_shape[2], device=right.payload.device),
right.group_size,
rounding_mode="floor",
).to(torch.int32)
offset = int(left.minimum.shape[2])
row_groups = torch.cat([left_groups, right_groups + offset], dim=0).contiguous()
return Packed4Bit(
payload=torch.cat([left.payload, right.payload], dim=2).contiguous(),
minimum=torch.cat([left.minimum, right.minimum], dim=2).contiguous(),
scale=torch.cat([left.scale, right.scale], dim=2).contiguous(),
original_shape=(
left.original_shape[0],
left.original_shape[1],
left.original_shape[2] + right.original_shape[2],
left.original_shape[3],
),
original_dtype=left.original_dtype,
axis=left.axis,
group_size=left.group_size,
row_groups=row_groups,
)
def _concat_optional_tensor(
left: torch.Tensor | None,
right: torch.Tensor | None,
) -> torch.Tensor | None:
if left is None:
return right
if right is None:
return left
if (
left.dtype != right.dtype
or left.device != right.device
or left.shape[:2] != right.shape[:2]
or left.shape[3:] != right.shape[3:]
):
raise ValueError("cannot concatenate incompatible absolute override streams")
return torch.cat([left, right], dim=2).contiguous()
def _validate_loop_tensors(
keys: Sequence[torch.Tensor],
values: Sequence[torch.Tensor],
) -> tuple[int, int, int, int]:
if len(keys) != 4 or len(values) != 4:
raise ValueError("exactly four loop K/V tensors are required")
shape = tuple(int(value) for value in keys[0].shape)
if len(shape) != 4 or shape[0] != 1:
raise ValueError("the first engine release requires [1, heads, tokens, channels]")
if any(tuple(tensor.shape) != shape for tensor in (*keys, *values)):
raise ValueError("all loop K/V tensors must have the same shape")
if any(tensor.dtype != keys[0].dtype for tensor in (*keys, *values)):
raise ValueError("all loop K/V tensors must have the same dtype")
if any(tensor.device != keys[0].device for tensor in (*keys, *values)):
raise ValueError("all loop K/V tensors must share a device")
return shape
def _rank_map(tokens: int, positions: torch.Tensor, device: torch.device) -> torch.Tensor:
result = torch.full((tokens,), -1, dtype=torch.int32, device=device)
if positions.numel():
result[positions.long()] = torch.arange(
positions.numel(),
dtype=torch.int32,
device=device,
)
return result
def _normalize_logical_indices(
indices: torch.Tensor,
*,
batch: int,
heads: int,
tokens: int,
device: torch.device,
validate_bounds: bool = True,
) -> torch.Tensor:
if indices.ndim == 1:
indices = indices[None, None, :].expand(batch, heads, -1)
elif indices.ndim == 4 and indices.shape[-2] == 1:
indices = indices.squeeze(-2)
if indices.ndim != 3 or tuple(indices.shape[:2]) != (batch, heads):
raise ValueError("indices must have shape [selected] or [batch, heads, selected]")
normalized = indices.to(device=device, dtype=torch.int32).contiguous()
if validate_bounds and normalized.numel() and (
int(normalized.min().item()) < 0 or int(normalized.max().item()) >= tokens
):
raise IndexError("cache index is outside the logical sequence")
return normalized
class CrossLoopKVLayerBuilder:
"""Build one physical cache layer without retaining a dense Loop-1 prefix.
The regular one-shot constructor is convenient for tests, but it forces the
prefill path to keep the complete Loop-1 and Loop-2 BF16 caches alive at the
same time. This staged builder packs Loop 1 immediately, adds Loop 2 as a
packed delta, and only then installs the compact Loop-3/4 overrides.
"""
def __init__(self) -> None:
self.group_size = 0
self.residual_length = 0
self.packed_tokens = 0
self._shape: tuple[int, int, int, int] = (0, 0, 0, 0)
self._dtype = torch.float16
self._device = torch.device("cpu")
self._packed_keys: list[PackedKV | None] = [None] * 4
self._packed_values: list[PackedKV | None] = [None] * 4
self._absolute_keys: list[torch.Tensor | None] = [None] * 4
self._absolute_values: list[torch.Tensor | None] = [None] * 4
self._tail_keys: list[torch.Tensor] = []
self._tail_values: list[torch.Tensor] = []
self._has_loop2 = False
self.absolute_late_overrides = False
self.absolute_override_dtype = "int4"
self.reader_backend = "triton_row"
@classmethod
def from_loop1(
cls,
loop1_key: torch.Tensor,
loop1_value: torch.Tensor,
*,
group_size: int = 64,
residual_length: int = 64,
absolute_late_overrides: bool = False,
absolute_override_dtype: str = "int4",
reader_backend: str = "triton_row",
) -> "CrossLoopKVLayerBuilder":
shape = tuple(int(value) for value in loop1_key.shape)
if len(shape) != 4 or shape[0] != 1 or loop1_value.shape != loop1_key.shape:
raise ValueError("Loop-1 K/V must match [1, heads, tokens, channels]")
if (
loop1_value.dtype != loop1_key.dtype
or loop1_value.device != loop1_key.device
):
raise ValueError("Loop-1 K/V must share dtype and device")
group_size = int(group_size)
residual_length = int(residual_length)
if group_size <= 0 or residual_length < 0:
raise ValueError("invalid group_size or residual_length")
result = cls()
result.group_size = group_size
result.residual_length = residual_length
result._shape = shape
result._dtype = loop1_key.dtype
result._device = loop1_key.device
result.absolute_late_overrides = bool(absolute_late_overrides)
if absolute_override_dtype not in {"int4", "bf16"}:
raise ValueError("absolute_override_dtype must be 'int4' or 'bf16'")
if absolute_override_dtype == "bf16" and not result.absolute_late_overrides:
raise ValueError("bf16 absolute overrides require absolute_late_overrides=True")
result.absolute_override_dtype = absolute_override_dtype
if reader_backend not in {"kivi_outer", "triton_row"}:
raise ValueError("unknown KV reader backend")
if reader_backend == "kivi_outer" and result.absolute_late_overrides:
raise ValueError("kivi_outer does not support absolute late overrides")
result.reader_backend = reader_backend
tokens = shape[2]
result.packed_tokens = max(
0, ((tokens - residual_length) // group_size) * group_size
)
if result.packed_tokens:
result._packed_keys[0] = _pack_key(
loop1_key[:, :, : result.packed_tokens, :], group_size, reader_backend
)
result._packed_values[0] = _pack_value(
loop1_value[:, :, : result.packed_tokens, :], group_size, reader_backend
)
result._tail_keys = [loop1_key[:, :, result.packed_tokens :, :].clone()]
result._tail_values = [loop1_value[:, :, result.packed_tokens :, :].clone()]
return result
@property
def retains_dense_loop1_prefix(self) -> bool:
"""Audit flag used by the prefill memory regression test."""
return False
def _validate_dense_pair(
self, key: torch.Tensor, value: torch.Tensor, *, label: str
) -> None:
if tuple(key.shape) != self._shape or value.shape != key.shape:
raise ValueError(f"{label} K/V shape differs from Loop 1")
if key.dtype != self._dtype or value.dtype != self._dtype:
raise ValueError(f"{label} K/V dtype differs from Loop 1")
if key.device != self._device or value.device != self._device:
raise ValueError(f"{label} K/V device differs from Loop 1")
def add_loop2(self, loop2_key: torch.Tensor, loop2_value: torch.Tensor) -> None:
if self._has_loop2:
raise RuntimeError("Loop 2 is already installed")
self._validate_dense_pair(loop2_key, loop2_value, label="Loop-2")
if self.packed_tokens:
anchor_key = self._packed_keys[0]
anchor_value = self._packed_values[0]
assert anchor_key is not None and anchor_value is not None
reconstructed_key = _decode_packed(anchor_key)
self._packed_keys[1] = _pack_key(
loop2_key[:, :, : self.packed_tokens, :] - reconstructed_key,
self.group_size,
self.reader_backend,
)
del reconstructed_key
reconstructed_value = _decode_packed(anchor_value)
self._packed_values[1] = _pack_value(
loop2_value[:, :, : self.packed_tokens, :] - reconstructed_value,
self.group_size,
self.reader_backend,
)
del reconstructed_value
self._tail_keys.append(loop2_key[:, :, self.packed_tokens :, :].clone())
self._tail_values.append(loop2_value[:, :, self.packed_tokens :, :].clone())
self._has_loop2 = True
def _validate_sparse_updates(
self,
positions: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
*,
label: str,
) -> torch.Tensor:
logical = positions.to(device=self._device, dtype=torch.int32).contiguous()
if logical.ndim != 1 or (
logical.numel() > 1
and not bool(torch.all(logical[1:] > logical[:-1]).item())
):
raise ValueError(f"{label} positions must be strictly sorted")
tokens = self._shape[2]
if logical.numel() and (
int(logical.min().item()) < 0 or int(logical.max().item()) >= tokens
):
raise IndexError(f"{label} update is outside the prompt")
expected = (self._shape[0], self._shape[1], int(logical.numel()), self._shape[3])
if tuple(key.shape) != expected or value.shape != key.shape:
raise ValueError(f"{label} compact K/V shape differs from its positions")
if key.dtype != self._dtype or value.dtype != self._dtype:
raise ValueError(f"{label} compact K/V dtype differs from Loop 1")
if key.device != self._device or value.device != self._device:
raise ValueError(f"{label} compact K/V device differs from Loop 1")
return logical
def _install_sparse_streams(
self,
*,
packed: list[PackedKV | None],
absolute: list[torch.Tensor | None],
targets: tuple[torch.Tensor, torch.Tensor],
prefix_positions: tuple[torch.Tensor, torch.Tensor],
prefix_update_ranks: tuple[torch.Tensor, torch.Tensor],
pack: Callable[[torch.Tensor, int], PackedKV],
) -> None:
if self.absolute_late_overrides:
for stream_index in (2, 3):
compact = prefix_update_ranks[stream_index - 2]
if compact.numel():
target = targets[stream_index - 2].index_select(2, compact)
if self.absolute_override_dtype == "bf16":
absolute[stream_index] = target.to(torch.bfloat16).contiguous()
else:
packed[stream_index] = pack(target, self.group_size)
return
anchor = packed[0]
delta2 = packed[1]
assert anchor is not None and delta2 is not None
reconstructed = _decode_packed(anchor) + _decode_packed(delta2)
decoded3: torch.Tensor | None = None
for stream_index in (2, 3):
logical = prefix_positions[stream_index - 2]
compact = prefix_update_ranks[stream_index - 2]
if not logical.numel():
continue
target = targets[stream_index - 2].index_select(2, compact)
base = reconstructed.index_select(2, logical.long())
if stream_index == 3:
assert decoded3 is not None
ranks_in_loop3 = torch.searchsorted(prefix_positions[0], logical).long()
base = base + decoded3.index_select(2, ranks_in_loop3)
packed[stream_index] = pack(target - base, self.group_size)
if stream_index == 2:
assert packed[2] is not None
decoded3 = _decode_packed(packed[2])
def finalize(
self,
*,
loop3_positions: torch.Tensor,
loop3_keys: torch.Tensor,
loop3_values: torch.Tensor,
loop4_positions: torch.Tensor,
loop4_keys: torch.Tensor,
loop4_values: torch.Tensor,
) -> "CrossLoopKVLayer":
if not self._has_loop2:
raise RuntimeError("Loop 2 must be installed before finalization")
positions3 = self._validate_sparse_updates(
loop3_positions, loop3_keys, loop3_values, label="Loop-3"
)
positions4 = self._validate_sparse_updates(
loop4_positions, loop4_keys, loop4_values, label="Loop-4"
)
if positions4.numel():
ranks4 = torch.searchsorted(positions3, positions4)
valid = ranks4 < positions3.numel()
matched = torch.zeros_like(valid)
matched[valid] = positions3[ranks4[valid]] == positions4[valid]
if not bool(matched.all().item()):
raise ValueError("Loop-4 positions must be nested in Loop-3 positions")
prefix_update_ranks = tuple(
torch.nonzero(logical < self.packed_tokens, as_tuple=False).flatten()
for logical in (positions3, positions4)
)
prefix_positions = tuple(
logical.index_select(0, compact)
for logical, compact in zip(
(positions3, positions4), prefix_update_ranks, strict=True
)
)
if self.packed_tokens:
self._install_sparse_streams(
packed=self._packed_keys,
absolute=self._absolute_keys,
targets=(loop3_keys, loop4_keys),
prefix_positions=prefix_positions, # type: ignore[arg-type]
prefix_update_ranks=prefix_update_ranks, # type: ignore[arg-type]
pack=lambda values, group: _pack_key(
values, group, self.reader_backend
),
)
self._install_sparse_streams(
packed=self._packed_values,
absolute=self._absolute_values,
targets=(loop3_values, loop4_values),
prefix_positions=prefix_positions, # type: ignore[arg-type]
prefix_update_ranks=prefix_update_ranks, # type: ignore[arg-type]
pack=lambda values, group: _pack_value(
values, group, self.reader_backend
),
)
result = CrossLoopKVLayer()
result.group_size = self.group_size
result.residual_length = self.residual_length
result.quantized_tokens = self.packed_tokens
result._shape_prefix = (self._shape[0], self._shape[1], self._shape[3])
result._dtype = self._dtype
result._device = self._device
result.absolute_late_overrides = self.absolute_late_overrides
result.absolute_override_dtype = self.absolute_override_dtype
result.reader_backend = self.reader_backend
result._packed_keys = self._packed_keys
result._packed_values = self._packed_values
result._absolute_keys = self._absolute_keys
result._absolute_values = self._absolute_values
result.override_indices = prefix_positions # type: ignore[assignment]
result.rank_maps = tuple(
_rank_map(self.packed_tokens, logical, self._device)
for logical in prefix_positions
) # type: ignore[assignment]
tail_keys = list(self._tail_keys)
tail_values = list(self._tail_values)
for logical, target_key, target_value in (
(positions3, loop3_keys, loop3_values),
(positions4, loop4_keys, loop4_values),
):
tail_key = tail_keys[-1].clone()
tail_value = tail_values[-1].clone()
compact = torch.nonzero(
logical >= self.packed_tokens, as_tuple=False
).flatten()
if compact.numel():
tail_positions = (
logical.index_select(0, compact).long() - self.packed_tokens
)
tail_key.index_copy_(
2, tail_positions, target_key.index_select(2, compact)
)
tail_value.index_copy_(
2, tail_positions, target_value.index_select(2, compact)
)
tail_keys.append(tail_key)
tail_values.append(tail_value)
tail_masks = []
for logical in (positions3, positions4):
mask = torch.zeros(
(1, self._shape[2] - self.packed_tokens),
dtype=torch.bool,
device=self._device,
)
selected = logical[logical >= self.packed_tokens].long() - self.packed_tokens
if selected.numel():
mask[:, selected] = True
tail_masks.append(mask)
result._install_tail_storage(
tail_keys, tail_values, tail_masks[0], tail_masks[1]
)
return result
class CrossLoopKVLayer:
"""One physical layer's packed recurrent cache."""
def __init__(self) -> None:
self.group_size = 0
self.residual_length = 0
self.quantized_tokens = 0
self.absolute_late_overrides = False
self.absolute_override_dtype = "int4"
self.reader_backend = "triton_row"
self._packed_keys: list[PackedKV | None] = [None] * 4
self._packed_values: list[PackedKV | None] = [None] * 4
self._absolute_keys: list[torch.Tensor | None] = [None] * 4
self._absolute_values: list[torch.Tensor | None] = [None] * 4
self._tail_keys: list[torch.Tensor] = []
self._tail_values: list[torch.Tensor] = []
self._tail_active: tuple[torch.Tensor, torch.Tensor] = (
torch.empty(0, dtype=torch.bool),
torch.empty(0, dtype=torch.bool),
)
self._tail_length = 0
self._tail_capacity = 0
self.override_indices: tuple[torch.Tensor, torch.Tensor]
self.rank_maps: tuple[torch.Tensor, torch.Tensor]
self._shape_prefix: tuple[int, int, int] = (0, 0, 0)
self._dtype: torch.dtype = torch.float16
self._device = torch.device("cpu")
self._split_kv_workspaces: dict[
tuple[int, int, int], tuple[torch.Tensor, torch.Tensor, torch.Tensor]
] = {}
def _split_kv_workspace(
self, total_rows: int, *, split_rows: int = 128
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Reuse per-layer online-softmax partials across decode steps."""
from .kernels.quantization import _split_kv_geometry
batch, heads, channels = self._shape_prefix
num_splits, _ = _split_kv_geometry(total_rows, split_rows=split_rows)
key = (batch * heads, num_splits, channels)
workspace = self._split_kv_workspaces.get(key)
if workspace is None:
maximum = torch.empty(
(batch * heads, num_splits),
device=self._device,
dtype=torch.float32,
)
denominator = torch.empty_like(maximum)
accumulator = torch.empty(
(batch * heads, num_splits, channels),
device=self._device,
dtype=torch.float32,
)
workspace = (maximum, denominator, accumulator)
self._split_kv_workspaces[key] = workspace
return workspace
def _install_tail_storage(
self,
keys: Sequence[torch.Tensor],
values: Sequence[torch.Tensor],
active3: torch.Tensor,
active4: torch.Tensor,
) -> None:
length = int(keys[0].shape[2])
if any(int(tensor.shape[2]) != length for tensor in (*keys, *values)):
raise ValueError("tail K/V streams must share their token length")
self._tail_keys = [
tensor.clone(memory_format=torch.contiguous_format) for tensor in keys
]
self._tail_values = [
tensor.clone(memory_format=torch.contiguous_format) for tensor in values
]
self._tail_active = (active3.clone(), active4.clone())
self._tail_length = length
self._tail_capacity = length
def _ensure_tail_capacity(self, required: int) -> None:
required = int(required)
if required <= self._tail_capacity:
return
growth = min(self.group_size, 16)
limit = self.residual_length + self.group_size
capacity = min(limit, max(required, self._tail_capacity + growth))
self._resize_tail_capacity(capacity)
def _resize_tail_capacity(self, capacity: int) -> None:
capacity = int(capacity)
if capacity < self._tail_length:
raise ValueError("tail capacity cannot be smaller than its logical length")
if capacity == self._tail_capacity:
return
batch, heads, channels = self._shape_prefix
grown_keys = [
torch.empty(
(batch, heads, capacity, channels),
device=self._device,
dtype=self._dtype,
)
for _ in range(4)
]
grown_values = [torch.empty_like(tensor) for tensor in grown_keys]
if self._tail_length:
for target, source in zip(grown_keys, self._tail_keys, strict=True):
target[:, :, : self._tail_length, :].copy_(
source[:, :, : self._tail_length, :]
)
for target, source in zip(grown_values, self._tail_values, strict=True):
target[:, :, : self._tail_length, :].copy_(
source[:, :, : self._tail_length, :]
)
grown_active = [
torch.zeros((batch, capacity), device=self._device, dtype=torch.bool)
for _ in range(2)
]
if self._tail_length:
for target, source in zip(grown_active, self._tail_active, strict=True):
target[:, : self._tail_length].copy_(source[:, : self._tail_length])
self._tail_keys = grown_keys
self._tail_values = grown_values
self._tail_active = (grown_active[0], grown_active[1])
self._tail_capacity = capacity
@classmethod
def from_prefill(
cls,
keys: Sequence[torch.Tensor],
values: Sequence[torch.Tensor],
*,
mask_loop3: torch.Tensor,
mask_loop4: torch.Tensor,
group_size: int = 64,
residual_length: int = 64,
absolute_late_overrides: bool = False,
absolute_override_dtype: str = "int4",
reader_backend: str = "triton_row",
) -> "CrossLoopKVLayer":
batch, heads, tokens, channels = _validate_loop_tensors(keys, values)
group_size = int(group_size)
residual_length = int(residual_length)
if group_size <= 0 or residual_length < 0:
raise ValueError("invalid group_size or residual_length")
if mask_loop3.shape != (batch, tokens) or mask_loop4.shape != (batch, tokens):
raise ValueError("prefill masks must have shape [1, tokens]")
mask_loop3 = mask_loop3.to(device=keys[0].device, dtype=torch.bool)
mask_loop4 = mask_loop4.to(device=keys[0].device, dtype=torch.bool)
if not bool(torch.all(~mask_loop4 | mask_loop3).item()):
raise ValueError("Loop-4 overrides must be nested in Loop-3 overrides")
packed_tokens = max(0, ((tokens - residual_length) // group_size) * group_size)
result = cls()
result.group_size = group_size
result.residual_length = residual_length
result.quantized_tokens = packed_tokens
result._shape_prefix = (batch, heads, channels)
result._dtype = keys[0].dtype
result._device = keys[0].device
result.absolute_late_overrides = bool(absolute_late_overrides)
if absolute_override_dtype not in {"int4", "bf16"}:
raise ValueError("absolute_override_dtype must be 'int4' or 'bf16'")
if absolute_override_dtype == "bf16" and not result.absolute_late_overrides:
raise ValueError("bf16 absolute overrides require absolute_late_overrides=True")
result.absolute_override_dtype = absolute_override_dtype
if reader_backend not in {"kivi_outer", "triton_row"}:
raise ValueError("unknown KV reader backend")
if reader_backend == "kivi_outer" and result.absolute_late_overrides:
raise ValueError("kivi_outer does not support absolute late overrides")
result.reader_backend = reader_backend
if packed_tokens:
result._encode_initial_prefix(
[tensor[:, :, :packed_tokens, :] for tensor in keys],
[tensor[:, :, :packed_tokens, :] for tensor in values],
mask_loop3[:, :packed_tokens],
mask_loop4[:, :packed_tokens],
)
else:
empty = torch.empty(0, dtype=torch.int32, device=result._device)
result.override_indices = (empty.clone(), empty.clone())
rank = torch.empty(0, dtype=torch.int32, device=result._device)
result.rank_maps = (rank.clone(), rank.clone())
result._install_tail_storage(
[tensor[:, :, packed_tokens:, :] for tensor in keys],
[tensor[:, :, packed_tokens:, :] for tensor in values],
mask_loop3[:, packed_tokens:].clone(),
mask_loop4[:, packed_tokens:].clone(),
)
return result
@classmethod
def from_prefill_updates(
cls,
*,
loop1_key: torch.Tensor,
loop1_value: torch.Tensor,
loop2_key: torch.Tensor,
loop2_value: torch.Tensor,
loop3_positions: torch.Tensor,
loop3_keys: torch.Tensor,
loop3_values: torch.Tensor,
loop4_positions: torch.Tensor,
loop4_keys: torch.Tensor,
loop4_values: torch.Tensor,
group_size: int = 64,
residual_length: int = 64,
absolute_late_overrides: bool = False,
absolute_override_dtype: str = "int4",
reader_backend: str = "triton_row",
) -> "CrossLoopKVLayer":
"""Build physical storage without ever constructing full Loop-3/4 K/V."""
shape = tuple(int(value) for value in loop1_key.shape)
if len(shape) != 4 or shape[0] != 1:
raise ValueError("dense prefill K/V must have shape [1, heads, tokens, channels]")
dense = (loop1_key, loop1_value, loop2_key, loop2_value)
if any(tensor.shape != loop1_key.shape for tensor in dense):
raise ValueError("Loop-1/2 K/V tensors must share a shape")
if any(tensor.dtype != loop1_key.dtype or tensor.device != loop1_key.device for tensor in dense):
raise ValueError("Loop-1/2 K/V tensors must share dtype and device")
batch, heads, tokens, channels = shape
positions = []
update_pairs = (
(loop3_positions, loop3_keys, loop3_values),
(loop4_positions, loop4_keys, loop4_values),
)
for logical, key, value in update_pairs:
logical = logical.to(device=loop1_key.device, dtype=torch.int32).contiguous()
if logical.ndim != 1 or (logical.numel() > 1 and not bool(torch.all(logical[1:] > logical[:-1]).item())):
raise ValueError("late-loop positions must be strictly sorted")
if logical.numel() and (int(logical.min().item()) < 0 or int(logical.max().item()) >= tokens):
raise IndexError("late-loop update is outside the prompt")
expected = (batch, heads, int(logical.numel()), channels)
if tuple(key.shape) != expected or value.shape != key.shape:
raise ValueError("late-loop compact K/V shape differs from its positions")
positions.append(logical)
positions3, positions4 = positions
if positions4.numel():
ranks4 = torch.searchsorted(positions3, positions4)
valid_rank = ranks4 < positions3.numel()
matched = torch.zeros_like(valid_rank)
matched[valid_rank] = positions3[ranks4[valid_rank]] == positions4[valid_rank]
if not bool(matched.all().item()):
raise ValueError("Loop-4 positions must be nested in Loop-3 positions")
group_size = int(group_size)
residual_length = int(residual_length)
if group_size <= 0 or residual_length < 0:
raise ValueError("invalid group_size or residual_length")
packed_tokens = max(0, ((tokens - residual_length) // group_size) * group_size)
result = cls()
result.group_size = group_size
result.residual_length = residual_length
result.quantized_tokens = packed_tokens
result._shape_prefix = (batch, heads, channels)
result._dtype = loop1_key.dtype
result._device = loop1_key.device
result.absolute_late_overrides = bool(absolute_late_overrides)
if absolute_override_dtype not in {"int4", "bf16"}:
raise ValueError("absolute_override_dtype must be 'int4' or 'bf16'")
if absolute_override_dtype == "bf16" and not result.absolute_late_overrides:
raise ValueError("bf16 absolute overrides require absolute_late_overrides=True")
result.absolute_override_dtype = absolute_override_dtype
if reader_backend not in {"kivi_outer", "triton_row"}:
raise ValueError("unknown KV reader backend")
if reader_backend == "kivi_outer" and result.absolute_late_overrides:
raise ValueError("kivi_outer does not support absolute late overrides")
result.reader_backend = reader_backend
prefix_positions: list[torch.Tensor] = []
prefix_update_ranks: list[torch.Tensor] = []
for logical in (positions3, positions4):
compact_ranks = torch.nonzero(logical < packed_tokens, as_tuple=False).flatten()
prefix_update_ranks.append(compact_ranks)
prefix_positions.append(logical.index_select(0, compact_ranks))
result.override_indices = tuple(prefix_positions) # type: ignore[assignment]
result.rank_maps = tuple(
_rank_map(packed_tokens, logical, result._device) for logical in prefix_positions
) # type: ignore[assignment]
if packed_tokens:
anchor_key = loop1_key[:, :, :packed_tokens, :]
anchor_value = loop1_value[:, :, :packed_tokens, :]
result._packed_keys[0] = _pack_key(anchor_key, group_size, reader_backend)
result._packed_values[0] = _pack_value(anchor_value, group_size, reader_backend)
reconstructed_key = _decode_packed(result._packed_keys[0])
reconstructed_value = _decode_packed(result._packed_values[0])
delta2_key = loop2_key[:, :, :packed_tokens, :] - reconstructed_key
delta2_value = loop2_value[:, :, :packed_tokens, :] - reconstructed_value
result._packed_keys[1] = _pack_key(delta2_key, group_size, reader_backend)
result._packed_values[1] = _pack_value(delta2_value, group_size, reader_backend)
reconstructed_key = reconstructed_key + _decode_packed(result._packed_keys[1])
reconstructed_value = reconstructed_value + _decode_packed(result._packed_values[1])
target_keys = (loop3_keys, loop4_keys)
target_values = (loop3_values, loop4_values)
decoded3_key: torch.Tensor | None = None
decoded3_value: torch.Tensor | None = None
for stream_index in (2, 3):
logical = prefix_positions[stream_index - 2]
compact = prefix_update_ranks[stream_index - 2]
if not logical.numel():
continue
target_key = target_keys[stream_index - 2].index_select(2, compact)
target_value = target_values[stream_index - 2].index_select(2, compact)
if result.absolute_late_overrides:
if result.absolute_override_dtype == "bf16":
result._absolute_keys[stream_index] = target_key.to(
torch.bfloat16
).contiguous()
result._absolute_values[stream_index] = target_value.to(
torch.bfloat16
).contiguous()
else:
result._packed_keys[stream_index] = _pack_key(
target_key, group_size, reader_backend
)
result._packed_values[stream_index] = _pack_value(
target_value, group_size, reader_backend
)
continue
base_key = reconstructed_key.index_select(2, logical.long())
base_value = reconstructed_value.index_select(2, logical.long())
if stream_index == 3:
assert decoded3_key is not None and decoded3_value is not None
ranks_in_loop3 = torch.searchsorted(prefix_positions[0], logical).long()
base_key = base_key + decoded3_key.index_select(2, ranks_in_loop3)
base_value = base_value + decoded3_value.index_select(2, ranks_in_loop3)
result._packed_keys[stream_index] = _pack_key(
target_key - base_key,
group_size,
reader_backend,
)
result._packed_values[stream_index] = _pack_value(
target_value - base_value,
group_size,
reader_backend,
)
if stream_index == 2:
decoded3_key = _decode_packed(result._packed_keys[2])
decoded3_value = _decode_packed(result._packed_values[2])
tail_keys = [
loop1_key[:, :, packed_tokens:, :].clone(),
loop2_key[:, :, packed_tokens:, :].clone(),
]
tail_values = [
loop1_value[:, :, packed_tokens:, :].clone(),
loop2_value[:, :, packed_tokens:, :].clone(),
]
for logical, target_key, target_value in update_pairs:
tail_key = tail_keys[-1].clone()
tail_value = tail_values[-1].clone()
compact = torch.nonzero(logical >= packed_tokens, as_tuple=False).flatten()
if compact.numel():
tail_positions = logical.index_select(0, compact).long() - packed_tokens
tail_key.index_copy_(2, tail_positions, target_key.index_select(2, compact))
tail_value.index_copy_(2, tail_positions, target_value.index_select(2, compact))
tail_keys.append(tail_key)
tail_values.append(tail_value)
tail_masks = []
for logical in (positions3, positions4):
mask = torch.zeros(
(1, tokens - packed_tokens),
dtype=torch.bool,
device=result._device,
)
selected = logical[logical >= packed_tokens].long() - packed_tokens
if selected.numel():
mask[:, selected] = True
tail_masks.append(mask)
result._install_tail_storage(