Repository navigation
Expand file tree
/
Copy pathstatic_attention.py
More file actions
1663 lines (1463 loc) · 60.2 KB
/
Copy pathstatic_attention.py
File metadata and controls
1663 lines (1463 loc) · 60.2 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
import copy
import logging
from abc import ABC, abstractmethod
from collections import defaultdict, deque
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from executorch.examples.models.llama.attention import (
Attention,
AttentionMHA,
ForwardOptions,
register_attention,
)
from executorch.examples.models.llama.lora import lora_call, LoRALinear
from executorch.examples.models.llama.model_args import ModelArgs
from executorch.examples.models.llama.norm import ScalelessRMSNorm
from executorch.examples.models.llama.rope import Rope
logger = logging.getLogger(__name__)
_CacheMap = Dict[str, torch.Tensor]
# Key and value caches are kept separate so the key caches can be kept transposed.
_InputCacheState = Tuple[_CacheMap, _CacheMap]
_OutputCacheState = Tuple[_CacheMap, _CacheMap]
def none_throws(x: Optional[Any]) -> Any:
assert x is not None
return x
class StaticKVCache(nn.Module, ABC):
def __init__(self, layer_id: int, head_id: int):
super().__init__()
self.layer_id = layer_id
self.head_id = head_id
@abstractmethod
def update(
self,
new_data: torch.Tensor,
in_cache_state: Optional[_InputCacheState],
out_cache_state: Optional[_OutputCacheState],
) -> Tuple[torch.Tensor, Optional[_OutputCacheState]]:
"""
Given input cache state and new keys/values, returns the combined keys/values
and the updated the output cache state.
"""
pass
def cache_key(self) -> str:
return self.calculate_cache_key(self.layer_id, self.head_id)
@staticmethod
def calculate_cache_key(layer_id: int, head_id: int) -> str:
return f"l{layer_id},h{head_id}"
@staticmethod
def apply_update(
cache, update, pos, style, transpose=False, update_pos=0, update_len=None
):
"""
After inference, update the cache state for next iteration. The runtime needs to
implement the same operation.
`pos` is the absolute position of the first token in the update. Caches smaller
than the sequence (sliding-window layers) wrap it into a ring index.
"""
seq_dim = -1 if transpose else -2
cache_len = cache.size(seq_dim)
if cache_len == 0:
return
if update_len is None:
update_len = update.size(seq_dim)
# Only the newest cache_len tokens fit. Drop from the front of the real-token
# window instead of narrowing the update tensor, which may be padded past
# update_len and would otherwise push padding into the cache.
dropped = max(0, update_len - cache_len)
update_pos += dropped
update_len -= dropped
pos = (pos + dropped) % cache_len
if style == "shift_pointer":
updated = torch.roll(cache, -update_len, seq_dim)
if transpose:
updated[..., -update_len:] = update[
..., update_pos : update_pos + update_len
]
else:
updated[..., -update_len:, :] = update[
..., update_pos : update_pos + update_len, :
]
if style == "smart_mask":
# Ring buffer: fill to the end of the cache, then wrap to the front.
contiguous_len = min(update_len, cache_len - pos)
wrap = update_len - contiguous_len
wrap_pos = update_pos + contiguous_len
updated = torch.clone(cache)
if transpose:
updated[..., pos : pos + contiguous_len] = update[
..., update_pos : update_pos + contiguous_len
]
if wrap > 0:
updated[..., :wrap] = update[..., wrap_pos : wrap_pos + wrap]
else:
updated[..., pos : pos + contiguous_len, :] = update[
..., update_pos : update_pos + contiguous_len, :
]
if wrap > 0:
updated[..., :wrap, :] = update[..., wrap_pos : wrap_pos + wrap, :]
return updated
class StaticKCache(StaticKVCache):
def __init__(self, layer_id: int, head_id: int, transpose=False):
"""
If transpose is True, key cache is kept in (batch, dim, seq_len), otherwise in
(batch, seq_len, dim).
"""
super().__init__(layer_id, head_id)
self.transpose = transpose
def update(
self,
new_data: torch.Tensor,
in_cache_state: Optional[_InputCacheState],
out_cache_state: Optional[_OutputCacheState],
) -> Tuple[torch.Tensor, Optional[_OutputCacheState]]:
seq_dim = -2
if self.transpose:
seq_dim = -1
new_data = new_data.transpose(-1, -2)
if in_cache_state is None:
return new_data, None
cache = in_cache_state[0].get(self.cache_key())
if cache is None:
return new_data, None
if out_cache_state is None:
out_cache_state = ({}, {})
all_data = torch.cat([cache, new_data], dim=seq_dim)
out_k_cache, out_v_cache = out_cache_state
out_k_cache[self.cache_key()] = new_data
return all_data, (out_k_cache, out_v_cache)
class StaticVCache(StaticKVCache):
def update(
self,
new_data: torch.Tensor,
in_cache_state: Optional[_InputCacheState],
out_cache_state: Optional[_OutputCacheState],
) -> Tuple[torch.Tensor, Optional[_OutputCacheState]]:
if in_cache_state is None:
return new_data, None
cache = in_cache_state[1].get(self.cache_key())
if cache is None:
return new_data, None
if out_cache_state is None:
out_cache_state = ({}, {})
all_data = torch.cat([cache, new_data], dim=-2)
out_k_cache, out_v_cache = out_cache_state
out_v_cache[self.cache_key()] = new_data
return all_data, (out_k_cache, out_v_cache)
class StaticAttentionMask:
def __init__(
self, input_len, cache_len, style, mask_val=float("-inf"), dtype=torch.float32
):
self.input_len = input_len
self.cache_len = cache_len
assert style in ("shift_pointer", "smart_mask")
self.style = style
self.mask_val = mask_val
self.unmasked_len = 0
self.tensor = torch.zeros(1, input_len, input_len + cache_len, dtype=dtype)
self.reset()
def reset(self):
self.unmasked_len = 0
self.tensor[:, :, : self.cache_len] = self.mask_val
def set_input_mask(self, input_mask):
self.tensor[:, :, self.cache_len :] = input_mask
def unmask(self, new_unmasked_len):
# Clamp to what is left of the cache region, mirroring the runtime
# (static_attention_io_manager.h). Without this the smart_mask branch walks
# past cache_len and zeroes part of the in-chunk causal mask.
new_unmasked_len = min(new_unmasked_len, self.cache_len - self.unmasked_len)
if new_unmasked_len <= 0:
return
if self.style == "shift_pointer":
self.tensor[
:,
:,
self.cache_len
- self.unmasked_len
- new_unmasked_len : self.cache_len
- self.unmasked_len,
] = 0
if self.style == "smart_mask":
self.tensor[
:,
:,
self.unmasked_len : self.unmasked_len + new_unmasked_len,
] = 0
self.unmasked_len += new_unmasked_len
def _is_kv_shared_layer(
layer_idx: int, n_layers: int, num_kv_shared_layers: int
) -> bool:
"""Check if this layer uses shared K/V from a donor layer (YOCO)."""
if num_kv_shared_layers <= 0:
return False
first_shared = n_layers - num_kv_shared_layers
if first_shared <= 0:
return False
return layer_idx >= first_shared
class StaticAttentionIOManager:
class NGramCache:
def __init__(self, max_size):
self.cache = deque()
self.max_size = max_size
def add(self, x):
if x in self.cache:
return
if len(self.cache) == self.max_size:
self.cache.popleft()
self.cache.append(x)
def __iter__(self):
return iter(self.cache)
def __str__(self):
return str(self.cache)
def __init__(
self,
config_or_model: Union[ModelArgs, nn.Module],
input_len: int,
cache_lens: Union[int, List[int]],
batch_size: int = 1,
dtype: torch.dtype = torch.float32,
style: str = "shift_pointer",
mask_val: float = float("-inf"),
):
if isinstance(cache_lens, int):
cache_lens_dict = defaultdict(lambda x=cache_lens: x)
cache_lens = [cache_lens]
else:
cache_lens_dict = dict(enumerate(cache_lens))
self._masks = {
cl: StaticAttentionMask(
input_len, cl, style=style, mask_val=mask_val, dtype=dtype
)
for cl in set(cache_lens)
}
# Global (full-attention) layers use the largest cache; local
# (sliding-window) layers use a strictly smaller cache. In a global-only
# model every layer shares the same cache, so this stays equal to it.
self._global_cache_len = max(
(mask.cache_len for mask in self._masks.values()), default=0
)
if isinstance(config_or_model, ModelArgs):
self._from_config(config_or_model, cache_lens_dict, batch_size, dtype)
else:
self._from_model(config_or_model, cache_lens_dict, batch_size, dtype)
self.input_len = input_len
self.style = style
self.mask_val = mask_val
self.pos = 0
self.cache_full = False
def _from_config(
self,
config: ModelArgs,
cache_lens: Dict[int, int],
batch_size: int,
dtype: torch.dtype,
):
rope = Rope(config)
freqs = rope.get_freqs(None, config.max_context_len)
self.freqs_cos = freqs[0].to(dtype)
self.freqs_sin = freqs[1].to(dtype)
split_mha = config.attention_type in ("static", "static_shas")
num_kv_shared = getattr(config, "num_kv_shared_layers", 0)
if split_mha:
self.k_caches = {
StaticKVCache.calculate_cache_key(layer_id, head_id): torch.zeros(
batch_size,
cache_lens[layer_id],
none_throws(config.head_dim),
dtype=dtype,
)
for layer_id in range(config.n_layers)
for head_id in range(none_throws(config.n_kv_heads))
if cache_lens[layer_id] > 0
and not _is_kv_shared_layer(layer_id, config.n_layers, num_kv_shared)
}
self.v_caches = {
StaticKVCache.calculate_cache_key(layer_id, head_id): torch.zeros(
batch_size,
cache_lens[layer_id],
none_throws(config.head_dim),
dtype=dtype,
)
for layer_id in range(config.n_layers)
for head_id in range(none_throws(config.n_kv_heads))
if cache_lens[layer_id] > 0
and not _is_kv_shared_layer(layer_id, config.n_layers, num_kv_shared)
}
else:
self.k_caches = {
StaticKVCache.calculate_cache_key(layer_id, 0): torch.zeros(
batch_size,
none_throws(config.n_kv_heads),
cache_lens[layer_id],
none_throws(config.head_dim),
dtype=dtype,
)
for layer_id in range(config.n_layers)
if cache_lens[layer_id] > 0
and not _is_kv_shared_layer(layer_id, config.n_layers, num_kv_shared)
}
self.v_caches = {
StaticKVCache.calculate_cache_key(layer_id, 0): torch.zeros(
batch_size,
none_throws(config.n_kv_heads),
cache_lens[layer_id],
none_throws(config.head_dim),
dtype=dtype,
)
for layer_id in range(config.n_layers)
if cache_lens[layer_id] > 0
and not _is_kv_shared_layer(layer_id, config.n_layers, num_kv_shared)
}
self.generate_full_logits = config.generate_full_logits
def _from_model(
self,
config: nn.Module,
cache_lens: Dict[int, int],
batch_size: int,
dtype: torch.dtype,
):
static_attentions = []
for module in config.modules():
if isinstance(module, StaticAttention):
static_attentions.append(module)
if not static_attentions:
raise ValueError("No StaticAttention modules found in the provided module")
config = copy.copy(static_attentions[0].rope.config)
config.use_hf_rope = static_attentions[0].rope.use_hf_rope
rope = Rope(config)
freqs = rope.get_freqs(None, config.max_context_len)
self.freqs_cos = freqs[0].to(dtype)
self.freqs_sin = freqs[1].to(dtype)
self.k_caches = {}
self.v_caches = {}
for attn in static_attentions:
if attn.is_kv_shared_layer:
continue
if attn.split_mha:
for head_id in range(attn.n_heads):
cache_key = StaticKVCache.calculate_cache_key(
attn.layer_id, head_id
)
for cache in (self.k_caches, self.v_caches):
assert (
cache_key not in cache
), "Found StaticAttention modules with duplicated layer_id"
cache[cache_key] = torch.zeros(
batch_size,
cache_lens[attn.layer_id],
attn.head_dim,
dtype=dtype,
)
else:
cache_key = StaticKVCache.calculate_cache_key(attn.layer_id, 0)
for cache in (self.k_caches, self.v_caches):
assert (
cache_key not in cache
), "Found StaticAttention modules with duplicated layer_id"
cache[cache_key] = torch.zeros(
batch_size,
attn.n_kv_heads,
cache_lens[attn.layer_id],
attn.head_dim,
dtype=dtype,
)
self.generate_full_logits = True
@property
def masks(self):
return {cache_len: mask.tensor for cache_len, mask in self._masks.items()}
def reset(self):
self.pos = 0
self.cache_full = False
for mask in self._masks.values():
mask.reset()
def _is_windowed_mask(self, mask: StaticAttentionMask) -> bool:
"""
A mask belongs to a local (sliding-window) layer iff its cache is strictly
smaller than the global cache. A pure sliding-window model is
indistinguishable from a global one by cache_len alone and counts as global.
"""
return 0 < mask.cache_len < self._global_cache_len
def _mask_cache_outside_window(self):
"""
Rewrite the cache region of every windowed mask so each query row only sees
its own window. `unmask` fills the cache region identically for all rows,
which lets query row k attend to cache_len + k + 1 keys instead of cache_len.
Express both layouts through the age of the token held in a slot -- how many
tokens are newer than it. With W = cache_len and v = min(pos, W) valid entries,
slot c is visible to query row k iff age(c) < min(v, W - 1 - k): the first term
is validity, the second is the window. Once k >= W - 1 the whole window lives
inside the chunk and nothing in the cache is visible.
Only the age mapping differs by layout. shift_pointer keeps valid entries right
aligned oldest to newest, so age is W - 1 - c. smart_mask is a ring indexed by
absolute position, so the same pattern is rotated by pos.
Composes with the in-chunk causal/window mask set by the caller, and holds for
both prefill chunks and decode steps.
"""
for mask in self._masks.values():
if not self._is_windowed_mask(mask):
continue
w = mask.cache_len
rows = torch.arange(self.input_len).unsqueeze(1)
cols = torch.arange(w).unsqueeze(0)
if mask.style == "smart_mask":
age = (self.pos - 1 - cols) % w
else:
age = w - 1 - cols
limit = torch.clamp(w - 1 - rows, max=min(self.pos, w))
cache_mask = torch.full(
(self.input_len, w), mask.mask_val, dtype=mask.tensor.dtype
)
cache_mask[age < limit] = 0
mask.tensor[:, :, :w] = cache_mask
def prefill(
self,
model: Callable[..., Any],
tokens: Union[List[int], torch.Tensor],
) -> torch.Tensor:
if self.cache_full:
raise RuntimeError("KV cache is full.")
for mask in self._masks.values():
input_mask = torch.triu(
torch.full((1, self.input_len, self.input_len), self.mask_val),
diagonal=1,
)
# Local (sliding-window) layers use a per-layer cache_len smaller than
# the prompt. When the whole prompt is prefilled in a single chunk, the
# cache-eviction window is never exercised, so also mask keys older than
# the window here to reproduce the local attention instead of full causal.
# Only genuine local layers (cache smaller than the global cache) are
# windowed; a global layer is left full-causal even when its (nominal)
# cache is smaller than the prompt. No-op for chunked prefill
# (input_len <= cache_len).
if self._is_windowed_mask(mask) and mask.cache_len < self.input_len:
input_mask = input_mask + torch.tril(
torch.full((1, self.input_len, self.input_len), self.mask_val),
diagonal=-mask.cache_len,
)
mask.set_input_mask(input_mask)
if isinstance(tokens, list):
tokens = torch.tensor([tokens], dtype=torch.int32)
logits = None
all_logits = None
for i in range(0, tokens.size(1), self.input_len):
self._mask_cache_outside_window()
logits = self._run_once(model, tokens[:, i : i + self.input_len])[0]
if self.generate_full_logits:
if all_logits is None:
all_logits = logits
else:
all_logits = torch.cat([all_logits, logits], dim=1)
if self.generate_full_logits:
return all_logits[:, : tokens.size(1), :]
return logits
def decode(
self,
model: Callable[..., Any],
init_token: int,
n: int,
stop_tokens: Optional[List[int]] = None,
):
if self.cache_full:
raise RuntimeError("KV cache is full.")
for mask in self._masks.values():
mask.set_input_mask(
torch.triu(
torch.full((1, self.input_len, self.input_len), self.mask_val),
diagonal=1,
)
)
stop_tokens = stop_tokens or []
new_tokens = [init_token]
for _ in range(n):
self._mask_cache_outside_window()
y = self._run_once(model, new_tokens[-1:])[0]
if self.generate_full_logits:
new_tokens.append(y[:, :1, ...].argmax().item())
else:
new_tokens.append(y.argmax().item())
if new_tokens[-1] in stop_tokens:
break
return new_tokens
def lookahead_decode( # noqa: C901
self,
model: Callable[..., Any],
init_token: int,
n: int,
ngram_size: int,
window_size: int,
n_verifications: int,
stop_tokens: Optional[List[int]] = None,
ngram_caches: Optional[Dict[int, "StaticAttentionIOManager.NGramCache"]] = None,
):
if self.cache_full:
raise RuntimeError("KV cache is full.")
if (ngram_size - 1) * (window_size + n_verifications) > self.input_len:
raise RuntimeError(
"Lookahead decoding setting not compatible with input length."
f" input_len = {self.input_len},"
f" ngram_size = {ngram_size},"
f" window_size = {window_size},"
f" n_verifications = {n_verifications}"
)
stop_tokens = stop_tokens or []
if ngram_caches is None:
ngram_caches = defaultdict(
lambda: StaticAttentionIOManager.NGramCache(n_verifications)
)
for mask in self._masks.values():
mask.set_input_mask(
self._get_lookahead_decoding_mask(
ngram_size, window_size, n_verifications
)
)
pos_offsets = self._get_lookahead_position_offsets(
ngram_size, window_size, n_verifications
)
verification_offset = max(window_size * (ngram_size - 1), 1)
new_tokens = [init_token]
x = [init_token] * self.input_len
inference_cnt = 0
while len(new_tokens) < n + 1:
# Update verification branch with cached n-grams.
cache = ngram_caches[x[0]]
for i, ngram in enumerate(cache):
for j, token in enumerate(ngram):
x[verification_offset + i * (ngram_size - 1) + j] = token
y, attn_updates = self._run_once(
model,
x,
non_padded_len=1,
freqs_cos_override=self.freqs_cos[pos_offsets + self.pos],
freqs_sin_override=self.freqs_sin[pos_offsets + self.pos],
)
inference_cnt += 1
# Only supports greedy decoding for now.
y = y[0].argmax(dim=-1).tolist()
new_tokens.append(y[0])
logger.debug(f"{self.pos}: x = {x[0]}, y = {y[0]}")
if new_tokens[-1] in stop_tokens:
break
# Collect new n-grams.
for i in range(window_size):
key = x[i]
suffix = []
for j in range(1, ngram_size - 1):
suffix.append(x[i + j * window_size])
suffix.append(y[i + window_size * (ngram_size - 2)])
ngram_caches[key].add(suffix)
# Verification.
longest_match = []
matched_branch = None
for i in range(n_verifications):
match = [y[0]]
j = 0
# for j in range(ngram_size - 1):
while (
j < ngram_size - 1
and x[verification_offset + (ngram_size - 1) * i + j] == match[-1]
):
match.append(y[verification_offset + (ngram_size - 1) * i + j])
j += 1
if len(match) - 1 > len(longest_match):
longest_match = match[1:]
matched_branch = i
if matched_branch is not None:
logger.debug(
f"Matched {len(longest_match)} additional tokens from n-grams: {longest_match}"
)
for stop in stop_tokens:
if stop in longest_match:
longest_match = longest_match[: longest_match.index(stop) + 1]
new_tokens.extend(longest_match)
# Update KV caches and attention mask for the additional matched tokens.
branch_offset = verification_offset + (ngram_size - 1) * matched_branch
self._update_states(
attn_updates,
update_pos=branch_offset,
update_len=len(longest_match),
)
# Update lookahead branch.
for i in range(ngram_size - 2):
for j in range(window_size):
x[window_size * i + j] = x[window_size * (i + 1) + j]
for j in range(window_size):
x[window_size * (ngram_size - 2) + j] = y[
window_size * (ngram_size - 2) + j
]
x[0] = new_tokens[-1]
if new_tokens[-1] in stop_tokens:
break
logger.info(
f"Generated {len(new_tokens) - 1} tokens with {inference_cnt} inference(s)."
)
return new_tokens
def _run_once(
self,
model: Callable[..., Any],
tokens: Union[List[int], torch.Tensor],
non_padded_len: Optional[int] = None,
freqs_cos_override: Optional[torch.Tensor] = None,
freqs_sin_override: Optional[torch.Tensor] = None,
):
if isinstance(tokens, list):
tokens = torch.tensor([tokens], dtype=torch.int32)
n_tokens = tokens.size(1)
if n_tokens < self.input_len:
tokens = F.pad(tokens, (0, self.input_len - n_tokens))
if freqs_cos_override is None:
freqs_cos_override = self.freqs_cos[self.pos : self.pos + self.input_len]
if freqs_sin_override is None:
freqs_sin_override = self.freqs_sin[self.pos : self.pos + self.input_len]
if not self.generate_full_logits:
extra_attn_options = {
"last_valid_token_pos": torch.tensor([n_tokens - 1], dtype=torch.long)
}
else:
extra_attn_options = {}
y, attn_updates = model(
tokens,
{
"masks": self.masks,
"freqs_cos_override": freqs_cos_override,
"freqs_sin_override": freqs_sin_override,
"in_cache_state": (self.k_caches, self.v_caches),
**extra_attn_options,
},
)
non_padded_len = non_padded_len or n_tokens
self._update_states(attn_updates, 0, non_padded_len)
return y, attn_updates
def _update_states(self, attn_updates, update_pos, update_len):
if attn_updates["out_cache_state"] is None:
return
for mask in self._masks.values():
mask.unmask(update_len)
k_cache_updates, v_cache_updates = attn_updates["out_cache_state"]
for cache_id, update in k_cache_updates.items():
self.k_caches[cache_id] = StaticKVCache.apply_update(
self.k_caches[cache_id],
update,
self.pos,
style=self.style,
update_pos=update_pos,
update_len=update_len,
).detach()
for cache_id, update in v_cache_updates.items():
self.v_caches[cache_id] = StaticKVCache.apply_update(
self.v_caches[cache_id],
update,
self.pos,
style=self.style,
update_pos=update_pos,
update_len=update_len,
).detach()
self.pos += update_len
def _get_lookahead_decoding_mask(
self, ngram_size: int, window_size: int, n_verifications: int
) -> torch.Tensor:
mask = torch.full((self.input_len, self.input_len), self.mask_val)
mask[0][0] = 0.0
lookahead_submask = torch.triu(
torch.full((window_size, window_size), self.mask_val),
diagonal=1,
)
for i in range(ngram_size - 1):
offset = window_size * i
mask[offset : offset + window_size, :window_size] = lookahead_submask
for j in range(1, i + 1):
mask[
offset : offset + window_size,
window_size * j : window_size * (j + 1),
].fill_diagonal_(0.0)
verification_offset = max(window_size * (ngram_size - 1), 1)
verification_submask = torch.triu(
torch.full((ngram_size - 1, ngram_size - 1), self.mask_val),
diagonal=1,
)
for i in range(n_verifications):
mask[
verification_offset
+ i * (ngram_size - 1) : verification_offset
+ (i + 1) * (ngram_size - 1),
verification_offset
+ i * (ngram_size - 1) : verification_offset
+ (i + 1) * (ngram_size - 1),
] = verification_submask
mask[verification_offset:, :1] = 0.0
return mask
def _get_lookahead_position_offsets(
self, ngram_size: int, window_size: int, n_verifications: int
) -> torch.Tensor:
# Input position offsets, used for indexing RoPE frequencies.
pos_offsets = torch.zeros(self.input_len, dtype=torch.int32)
idx = 0
# Lookahead branches: [i + 0, i + 1, ..., i + window_size - 1] for time i.
if window_size > 0:
for i in range(ngram_size - 1):
for j in range(window_size):
pos_offsets[idx] = i + j
idx += 1
else:
pos_offsets[0] = 0
idx += 1
# Verification branches: [1, 2, ..., ngram_size - 1].
for _ in range(n_verifications):
for j in range(1, ngram_size):
pos_offsets[idx] = j
idx += 1
return pos_offsets
class _Rope(nn.Module):
def __init__(self, config: ModelArgs):
super().__init__()
self.config = config
self.use_hf_rope = config.use_hf_rope
def forward(
self, x: torch.Tensor, freqs_cos: torch.Tensor, freqs_sin: torch.Tensor
) -> torch.Tensor:
if self.use_hf_rope:
if len(freqs_cos.shape) == 2:
freqs_cos = freqs_cos.unsqueeze(0)
if len(freqs_sin.shape) == 2:
freqs_sin = freqs_sin.unsqueeze(0)
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
x_rotated = torch.cat((-x2, x1), dim=-1)
return x * freqs_cos + x_rotated * freqs_sin
else:
x_r, x_i = x[..., ::2], x[..., 1::2]
x_out_r = x_r * freqs_cos - x_i * freqs_sin
x_out_i = x_r * freqs_sin + x_i * freqs_cos
x_out = torch.stack([x_out_r, x_out_i], dim=-1).flatten(-2)
return x_out
@register_attention("static")
class StaticAttention(Attention):
"""
An attention implementation meant for NPUs that require static shapes and are not
flexible with tensor operations needed to perform KV cache updates. MHA/GQA is
implemented as multiple SHAs, and the KV caches keep valid data at the end so the
model only needs to perform a concat to combine past and new data.
"""
def __init__(
self,
config: ModelArgs,
layer_id: int,
rope: Rope,
split_mha: bool = True,
is_kv_shared_layer: bool = False,
**kwargs: Any,
):
super().__init__()
self.n_heads = config.n_heads
self.n_kv_heads = (
self.n_heads if config.n_kv_heads is None else config.n_kv_heads
)
self.n_rep = self.n_heads // self.n_kv_heads
assert self.n_heads % self.n_kv_heads == 0
self.n_heads_per_kv_group = self.n_heads // self.n_kv_heads
self.dim = config.dim
self.head_dim = config.head_dim
self.inv_scale = 1.0 / (float(self.head_dim) ** 0.5)
self.attention_qkv_bias = config.attention_qkv_bias
self.use_qk_norm = config.use_qk_norm
self.qk_norm_before_rope = config.qk_norm_before_rope
self.scale_query_by = getattr(config, "scale_query_by", 1.0)
self.split_mha = split_mha
self.is_kv_shared_layer = is_kv_shared_layer
self.num_kv_shared_layers = config.num_kv_shared_layers
self.use_conv2d = False
self.enable_qnn_masked_softmax = kwargs.get("enable_qnn_masked_softmax", False)
# This fixes numerics on iOS26 on Core ML
# Possibly disable in future, depending on bug fixes in Core ML runtime
self.decompose_sdpa_in_mha: bool = kwargs.get("decompose_sdpa_in_mha", False)
if self.split_mha:
self.wqs = nn.ModuleList(
[
nn.Linear(self.dim, self.head_dim, bias=self.attention_qkv_bias)
for _ in range(self.n_heads)
]
)
if is_kv_shared_layer:
self.wks = nn.ModuleList()
self.wvs = nn.ModuleList()
self.k_caches = nn.ModuleList()
self.v_caches = nn.ModuleList()
else:
self.wks = nn.ModuleList(
[
nn.Linear(self.dim, self.head_dim, bias=self.attention_qkv_bias)
for _ in range(self.n_kv_heads)
]
)
self.wvs = nn.ModuleList(
[
nn.Linear(self.dim, self.head_dim, bias=self.attention_qkv_bias)
for _ in range(self.n_kv_heads)
]
)
self.k_caches = nn.ModuleList(
[StaticKCache(layer_id, i) for i in range(self.n_kv_heads)]
)
self.v_caches = nn.ModuleList(
[StaticVCache(layer_id, i) for i in range(self.n_kv_heads)]
)
else:
has_lora = config.target_modules is not None
_PROJ_TARGET = {
"wqs": ("q_proj", self.dim, self.head_dim * self.n_heads),
"wks": ("k_proj", self.dim, self.head_dim * self.n_kv_heads),
"wvs": ("v_proj", self.dim, self.head_dim * self.n_kv_heads),
}
for attr, (target, in_dim, out_dim) in _PROJ_TARGET.items():
if is_kv_shared_layer and attr in ("wks", "wvs"):
setattr(self, attr, nn.ModuleList())
continue
if has_lora and target in config.target_modules:
proj = LoRALinear(
in_dim=in_dim,
out_dim=out_dim,
rank=config.r,
alpha=config.lora_alpha,
use_bias=self.attention_qkv_bias,
)
else:
proj = nn.Linear(in_dim, out_dim, bias=self.attention_qkv_bias)
setattr(self, attr, nn.ModuleList([proj]))
if is_kv_shared_layer:
self.k_caches = nn.ModuleList()
self.v_caches = nn.ModuleList()
else:
self.k_caches = nn.ModuleList([StaticKCache(layer_id, 0)])
self.v_caches = nn.ModuleList([StaticVCache(layer_id, 0)])
self._init_wo(config)
self.rope = _Rope(rope.params)
self.layer_id = layer_id
self._init_qk_norms(config, is_kv_shared_layer)
def _init_wo(self, config: ModelArgs) -> None:
wo_use_lora = (
not self.split_mha
and config.target_modules is not None
and (
"output_proj" in config.target_modules
or "o_proj" in config.target_modules
)
)
if wo_use_lora:
self.wo = LoRALinear(
in_dim=self.n_heads * self.head_dim,
out_dim=self.dim,
rank=config.r,
alpha=config.lora_alpha,
use_bias=False,
)
else:
self.wo = nn.Linear(self.n_heads * self.head_dim, self.dim, bias=False)
def _init_qk_norms(self, config: ModelArgs, is_kv_shared_layer: bool) -> None:
if self.use_qk_norm:
if getattr(config, "qk_norm_affine", True):
self.q_norm = torch.nn.RMSNorm(self.head_dim, config.norm_eps)
if is_kv_shared_layer:
self.k_norm = nn.Identity()
else:
self.k_norm = torch.nn.RMSNorm(self.head_dim, config.norm_eps)
else:
self.q_norm = ScalelessRMSNorm(self.head_dim, eps=config.norm_eps)
if is_kv_shared_layer:
self.k_norm = nn.Identity()
else:
self.k_norm = ScalelessRMSNorm(self.head_dim, eps=config.norm_eps)
else:
self.q_norm = torch.nn.Identity()
self.k_norm = torch.nn.Identity()
@classmethod
def from_attention_mha(
cls,
other: AttentionMHA,
split_mha: bool = True,
rms_norm_class=torch.nn.RMSNorm,
**kwargs: Any,
) -> "StaticAttention":
is_kv_shared = getattr(other, "is_kv_shared_layer", False)
lora_projs = [other.wq, other.wo]
if other.wk is not None:
lora_projs.append(other.wk)
if other.wv is not None:
lora_projs.append(other.wv)
has_lora = any(isinstance(proj, LoRALinear) for proj in lora_projs)
if has_lora and split_mha:
raise ValueError(
"split_mha=True is not supported when the source AttentionMHA "
"contains LoRALinear modules. Use split_mha=False instead."
)