forked from AI-Hypercomputer/maxtext
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathattention_op.py
More file actions
1873 lines (1668 loc) · 78.6 KB
/
Copy pathattention_op.py
File metadata and controls
1873 lines (1668 loc) · 78.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pytype: disable=module-attr
"""Attentions Ops Layers."""
import dataclasses
import functools
from typing import Any, Callable, Optional, Tuple
from functools import partial
import math
import numpy as np
import jax
from jax import lax
from jax.ad_checkpoint import checkpoint_name
from jax.experimental.pallas.ops.gpu import attention as gpu_pallas_attention
from jax.experimental.pallas.ops.gpu import decode_attention as gpu_pallas_decode_attention
from jax.experimental import pallas as pl
from jax.sharding import Mesh, NamedSharding
import jax.numpy as jnp
from jax.experimental.pallas.ops.tpu.splash_attention import splash_attention_kernel
from jax.experimental.pallas.ops.tpu.splash_attention import splash_attention_mask
from tokamax._src.ops.experimental.tpu.splash_attention import splash_attention_kernel as tokamax_splash_kernel
from tokamax._src.ops.experimental.tpu.splash_attention import splash_attention_mask as tokamax_splash_mask
from flax import linen as nn
from flax import nnx
from flax.linen import partitioning
from MaxText import max_utils
from MaxText.sharding import maybe_shard_with_name
from MaxText.common_types import (
DEFAULT_MASK_VALUE,
BATCH,
BATCH_NO_EXP,
HEAD,
KV_LENGTH,
PREFILL_LENGTH,
D_KV,
CACHE_BATCH_PREFILL,
CACHE_SEQUENCE,
AxisNames,
CACHE_BATCH,
CACHE_HEADS,
CACHE_SCALE_BATCH,
CACHE_KV,
CACHE_SCALE_SEQUENCE,
CACHE_SCALE_HEADS,
CACHE_SCALE_KV,
AxisIdxes,
LENGTH,
LENGTH_NO_EXP,
DType,
Config,
Array,
Q_LENGTH,
Q_LENGTH_NO_EXP,
DECODE_LENGTH,
DECODE_BATCH,
MODEL_MODE_AUTOREGRESSIVE,
DECODING_ACTIVE_SEQUENCE_INDICATOR,
MODEL_MODE_TRAIN,
MODEL_MODE_PREFILL,
EP_AS_CONTEXT,
AttentionType,
)
from MaxText.inference import page_manager
from MaxText.inference.kvcache import KVQuant, KVTensor
from MaxText.kernels.ragged_attention import ragged_gqa
from MaxText.kernels.ragged_attention import ragged_mha
from MaxText.layers import nnx_wrappers
from MaxText.layers.initializers import variable_to_logically_partitioned
from MaxText.layers.quantizations import AqtQuantization as Quant
# pylint: disable=line-too-long, g-doc-args, g-doc-return-or-yield, bad-continuation, g-inconsistent-quotes
# pytype: disable=attribute-error
# Used to pass in splash attention block sizes from config.
global_block_q = 0
global_block_kv = 0
global_block_kv_compute = 0
global_block_q_dkv = 0
global_block_kv_dkv = 0
global_block_kv_dkv_compute = 0
global_block_q_dq = 0
global_block_kv_dq = 0
global_use_fused_bwd_kernel = False
global_q_layout = ""
global_k_layout = ""
global_v_layout = ""
dynamic_vector_slice_in_dim = jax.vmap(lax.dynamic_slice_in_dim, in_axes=(None, 0, None, None))
def validate_compute_axis_order(s: AxisIdxes) -> None:
valid_compute_axis_order = ((0, 1, 2, 3), (0, 2, 1, 3))
if s not in valid_compute_axis_order: # currently supported compute_axis_order
raise ValueError("Invalid compute_axis_order was passed. Valid options ", valid_compute_axis_order)
def apply_mask_to_logits(logits: Array, mask: Array):
"""Applies a floating-point mask to a set of logits.
The mask is represented as a tensor with some dtype where 0 represents true and values
below a large negative number (here set to
get_large_negative_number(logits.dtype) / 2) represent false. Applying the mask
leaves the logits alone in the true case and replaces them by
get_large_negative_number(logits.dtype) in the false case. Previously, this was
done by adding the logits to the mask; however, this leads to a bad fusion
decision in the compiler that saves the values in memory rather than
just the predicate. This implementation avoids that problem.
from https://github.com/google/praxis/blob/4712a6b9ee13e224b86e235ff55f7c6bab9fbab3/praxis/py_utils.py#L706
Args:
logits: A JTensor of logit values.
mask: A JTensor of mask values with the encoding described in the
function documentation.
Returns:
Masked logits.
"""
return jnp.where((mask >= DEFAULT_MASK_VALUE * 0.5), logits, DEFAULT_MASK_VALUE)
def validate_flash_attention_with_sinks_on_gpu(sinks: Array | None) -> None:
"""Helper function to check for sinks with flash attention on GPU."""
if sinks is not None:
raise ValueError("The flash attention with sinks is not supported on GPU yet.")
# TODO(agagik): change splash_attention_mask._ComputableMask to be non protected
class ChunkedCausalMask(splash_attention_mask._ComputableMask): # pylint: disable=protected-access
"""Lazy chunked causal mask.
Attention is causal within each chunk (0, K), (K, 2K), (2K, 3K), ... tokens attend to each other but not across chunks.
Llama4 models use interleaved chunk attention along with global attention.
This mask class inherits from splash_attention_mask._ComputableMask and is designed to be used with Splash Attention.
It allows the mask logic to be computed on-the-fly or fused into the attention kernel, avoiding the memory cost of
materializing the full (sequence_length, sequence_length) boolean mask array, which can be prohibitive for long sequences.
Attributes:
chunk_size: The size of each attention chunk.
"""
chunk_size: int
def __init__(
self,
shape: tuple[int, int],
chunk_size: int,
shard_count: int = 1,
):
if chunk_size <= 0:
raise ValueError("chunk_size must be positive")
self.chunk_size = chunk_size
# Define the mask function for chunk attention
def chunked_causal_mask_function(q_ids, kv_ids):
"""Computes the mask logic for the given slice indices."""
if q_ids.size == 0 or kv_ids.size == 0:
return np.empty((q_ids.shape[0], kv_ids.shape[1]), dtype=np.bool_)
# Condition 1: Same chunk
q_chunk = q_ids // self.chunk_size
kv_chunk = kv_ids // self.chunk_size
same_chunk = q_chunk == kv_chunk
# Condition 2: Causal
causal = q_ids >= kv_ids
return same_chunk & causal
# Initialize the parent ComputableMask with this function
super().__init__(
shape=shape,
mask_function=chunked_causal_mask_function,
shard_count=shard_count,
)
# Implement equality and hashing based on relevant attributes
def __eq__(self, other: object):
if not isinstance(other, type(self)):
return NotImplemented
# Compare shape, chunk_size, and the underlying q_sequence array
return (
self.shape == other.shape
and self.chunk_size == other.chunk_size
and np.array_equal(self.q_sequence, other.q_sequence)
)
def __hash__(self):
return hash(
(
type(self),
self.shape,
self.chunk_size,
self.q_sequence.tobytes() if self.q_sequence is not None else None,
)
)
def _generate_chunk_attention_mask(mask_shape: tuple[int, int], chunk_size: int, q_offset: int = 0) -> jax.Array:
"""Generates an explicit boolean mask for chunked causal attention.
This function computes the full boolean mask array where True indicates
attention is allowed based on chunked causal rules (tokens attend only
within the same chunk, and causally within that chunk).
Args:
mask_shape: The desired shape of the mask (q_seq_len, kv_seq_len).
chunk_size: The size of the attention chunks.
Returns:
A boolean mask of shape `mask_shape` where True indicates attention is
allowed according to chunked causal rules, and False otherwise.
Raises:
ValueError: If chunk_window_size is None or not positive.
"""
row_ids = jax.lax.broadcasted_iota(jnp.int32, mask_shape, 0) + q_offset
col_ids = jax.lax.broadcasted_iota(jnp.int32, mask_shape, 1)
if chunk_size <= 0:
raise ValueError("chunk_size must be positive")
# chunk mask calculation
same_chunk = (row_ids // chunk_size) == (col_ids // chunk_size)
chunk_mask = same_chunk & (row_ids >= col_ids)
return chunk_mask
def _make_block_mask_indices(bidirectional_mask):
"""Creates block mask identifying segments based on a bidirectional mask.
Args:
bidirectional_mask: boolean mask, e.g. [011110011010].
Returns:
block mask for segments, e.g. [011110022030].
"""
# Left pad 0.
padded_mask = jnp.pad(bidirectional_mask, [(0, 0), (1, 0)], constant_values=0)
boundary = padded_mask[..., 1:] > padded_mask[..., :-1]
numbered_boundary = jnp.cumsum(boundary, axis=-1)
return bidirectional_mask * numbered_boundary
def _make_bidirectional_block_mask(bidirectional_mask):
"""Creates bidirectional block mask from bidirectional_mask, where True corresponds to image tokens.
bidirectional_mask shape: [B, L]
bidirectional_block_mask shape: [B, L, L]
Examples:
bidirectional_mask = [[0, 1, 1, 1, 0, 0]]
bidirectional_block_mask = [[
[False, False, False, False, False, False],
[False, True, True, True, False, False],
[False, True, True, True, False, False],
[False, True, True, True, False, False],
[False, False, False, False, False, False],
[False, False, False, False, False, False],
]]
"""
q_block_indices = _make_block_mask_indices(bidirectional_mask)
kv_block_indices = q_block_indices
bidirectional_block_mask = (kv_block_indices[:, None, :] == q_block_indices[..., None]) & (
q_block_indices[..., None] > 0
)
return bidirectional_block_mask
def attention_op_as_linen(
*,
config: Config,
mesh: Mesh,
attention_kernel: str,
max_target_length: int,
num_query_heads: int,
num_kv_heads: int,
float32_qk_product: bool = False,
max_prefill_predict_length: int = -1,
float32_logits: bool = False,
flash_axis_names_q: AxisNames = (BATCH, HEAD, LENGTH_NO_EXP, D_KV),
flash_axis_names_q_ep: AxisNames = (BATCH_NO_EXP, HEAD, LENGTH, D_KV),
flash_axis_names_kv: AxisNames = (BATCH, HEAD, KV_LENGTH, D_KV),
flash_axis_names_kv_ep: AxisNames = (BATCH_NO_EXP, HEAD, KV_LENGTH, D_KV),
flash_axis_names_splash_kernel: AxisNames = (HEAD, LENGTH_NO_EXP),
flash_axis_names_splash_kernel_ep: AxisNames = (HEAD, LENGTH),
prefill_cache_logical_axis_names: AxisNames = (CACHE_BATCH_PREFILL, CACHE_SEQUENCE, CACHE_HEADS, CACHE_KV),
cache_logical_axis_names: AxisNames = (CACHE_BATCH, CACHE_SEQUENCE, CACHE_HEADS, CACHE_KV),
cache_scale_logical_axis_names: AxisNames = (
CACHE_SCALE_BATCH,
CACHE_SCALE_SEQUENCE,
CACHE_SCALE_HEADS,
CACHE_SCALE_KV,
),
ragged_qkv_axis_names: AxisNames = (CACHE_BATCH, CACHE_HEADS, CACHE_SEQUENCE, CACHE_KV),
ragged_lengths_names: AxisNames = (CACHE_BATCH,),
compute_axis_order: AxisIdxes = (0, 1, 2, 3),
key_axis_order: AxisIdxes = (2, 0, 1, 3),
reshape_q: bool = False,
dropout_rate: float = 0.0,
dtype: DType = jnp.float32,
quant: Optional[Quant] = None,
kv_quant: Optional[KVQuant] = None,
attention_type: AttentionType = AttentionType.GLOBAL, # Default to global attention
attn_logits_soft_cap: float | None = None,
sliding_window_size: int | None = None,
chunk_attn_window_size: int | None = None,
use_ragged_attention: bool = False,
ragged_block_size: int = 256,
):
"""A factory function to create an AttentionOp as a Linen module.
This function serves as a bridge to use the NNX-based `AttentionOp` within a
Linen model.
"""
return nnx_wrappers.to_linen(
AttentionOp,
config=config,
mesh=mesh,
attention_kernel=attention_kernel,
max_target_length=max_target_length,
num_query_heads=num_query_heads,
num_kv_heads=num_kv_heads,
float32_qk_product=float32_qk_product,
max_prefill_predict_length=max_prefill_predict_length,
float32_logits=float32_logits,
flash_axis_names_q=flash_axis_names_q,
flash_axis_names_q_ep=flash_axis_names_q_ep,
flash_axis_names_kv=flash_axis_names_kv,
flash_axis_names_kv_ep=flash_axis_names_kv_ep,
flash_axis_names_splash_kernel=flash_axis_names_splash_kernel,
flash_axis_names_splash_kernel_ep=flash_axis_names_splash_kernel_ep,
prefill_cache_logical_axis_names=prefill_cache_logical_axis_names,
cache_logical_axis_names=cache_logical_axis_names,
cache_scale_logical_axis_names=cache_scale_logical_axis_names,
ragged_qkv_axis_names=ragged_qkv_axis_names,
ragged_lengths_names=ragged_lengths_names,
compute_axis_order=compute_axis_order,
key_axis_order=key_axis_order,
reshape_q=reshape_q,
dropout_rate=dropout_rate,
dtype=dtype,
quant=quant,
kv_quant=kv_quant,
attention_type=attention_type,
attn_logits_soft_cap=attn_logits_soft_cap,
sliding_window_size=sliding_window_size,
chunk_attn_window_size=chunk_attn_window_size,
use_ragged_attention=use_ragged_attention,
ragged_block_size=ragged_block_size,
metadata_fn=variable_to_logically_partitioned,
)
class AttentionOp(nnx.Module):
"""Attention operation"""
def __init__(
self,
config: Config,
mesh: Mesh,
attention_kernel: str,
max_target_length: int,
num_query_heads: int,
num_kv_heads: int,
float32_qk_product: bool = False,
max_prefill_predict_length: int = -1,
float32_logits: bool = False,
flash_axis_names_q: AxisNames = (BATCH, HEAD, LENGTH_NO_EXP, D_KV),
flash_axis_names_q_ep: AxisNames = (BATCH_NO_EXP, HEAD, LENGTH, D_KV),
flash_axis_names_kv: AxisNames = (BATCH, HEAD, KV_LENGTH, D_KV),
flash_axis_names_kv_ep: AxisNames = (BATCH_NO_EXP, HEAD, KV_LENGTH, D_KV),
flash_axis_names_splash_kernel: AxisNames = (HEAD, LENGTH_NO_EXP),
flash_axis_names_splash_kernel_ep: AxisNames = (HEAD, LENGTH),
prefill_cache_logical_axis_names: AxisNames = (CACHE_BATCH_PREFILL, CACHE_SEQUENCE, CACHE_HEADS, CACHE_KV),
cache_logical_axis_names: AxisNames = (CACHE_BATCH, CACHE_SEQUENCE, CACHE_HEADS, CACHE_KV),
cache_scale_logical_axis_names: AxisNames = (
CACHE_SCALE_BATCH,
CACHE_SCALE_SEQUENCE,
CACHE_SCALE_HEADS,
CACHE_SCALE_KV,
),
ragged_qkv_axis_names: AxisNames = (CACHE_BATCH, CACHE_HEADS, CACHE_SEQUENCE, CACHE_KV),
ragged_lengths_names: AxisNames = (CACHE_BATCH,),
compute_axis_order: AxisIdxes = (0, 1, 2, 3),
key_axis_order: AxisIdxes = (2, 0, 1, 3),
reshape_q: bool = False,
dropout_rate: float = 0.0,
dtype: DType = jnp.float32,
quant: Optional[Quant] = None,
kv_quant: Optional[KVQuant] = None,
attention_type: AttentionType = AttentionType.GLOBAL, # Default to global attention
attn_logits_soft_cap: float | None = None,
sliding_window_size: int | None = None,
chunk_attn_window_size: int | None = None,
use_ragged_attention: bool = False,
ragged_block_size: int = 256,
rngs: nnx.Rngs | None = None,
):
"""Initializes the AttentionOp module.
Args:
config: The configuration for the model.
mesh: The device mesh.
attention_kernel: The attention kernel to use.
max_target_length: The maximum target length.
num_query_heads: The number of query heads.
num_kv_heads: The number of key/value heads.
float32_qk_product: Whether to compute qk_product in float32.
max_prefill_predict_length: The maximum prefill predict length.
float32_logits: Whether to compute logits in float32.
flash_axis_names_kv: The logical axis names for the KV cache in flash attention.
flash_axis_names_q: The logical axis names for the query in flash attention.
flash_axis_names_splash_kernel: The logical axis names for the splash attention kernel.
prefill_cache_logical_axis_names: The logical axis names for the prefill cache.
cache_logical_axis_names: The logical axis names for the cache.
cache_scale_logical_axis_names: The logical axis names for the cache scale.
ragged_qkv_axis_names: The logical axis names for ragged QKV tensors.
ragged_lengths_names: The logical axis names for ragged lengths.
compute_axis_order: The order of axes for computation.
key_axis_order: The order of axes for the key.
... and other configuration parameters.
rngs: The random number generators for initialization, passed by the nnx.to_linen wrapper.
"""
self.config = config
self.mesh = mesh
self.attention_kernel = attention_kernel
self.max_target_length = max_target_length
self.num_query_heads = num_query_heads
self.num_kv_heads = num_kv_heads
self.float32_qk_product = float32_qk_product
self.max_prefill_predict_length = max_prefill_predict_length
self.float32_logits = float32_logits
self.flash_axis_names_q = flash_axis_names_q
self.flash_axis_names_q_ep = flash_axis_names_q_ep
self.flash_axis_names_kv = flash_axis_names_kv
self.flash_axis_names_kv_ep = flash_axis_names_kv_ep
self.flash_axis_names_splash_kernel = flash_axis_names_splash_kernel
self.flash_axis_names_splash_kernel_ep = flash_axis_names_splash_kernel_ep
self.prefill_cache_logical_axis_names = prefill_cache_logical_axis_names
self.cache_logical_axis_names = cache_logical_axis_names
self.cache_scale_logical_axis_names = cache_scale_logical_axis_names
self.ragged_qkv_axis_names = ragged_qkv_axis_names
self.ragged_lengths_names = ragged_lengths_names
self.compute_axis_order = compute_axis_order
self.key_axis_order = key_axis_order
self.reshape_q = reshape_q
self.dropout_rate = dropout_rate
self.dtype = dtype
self.quant = quant
self.kv_quant = kv_quant
self.attention_type = attention_type
self.attn_logits_soft_cap = attn_logits_soft_cap
self.sliding_window_size = sliding_window_size
self.chunk_attn_window_size = chunk_attn_window_size
self.use_ragged_attention = use_ragged_attention
self.ragged_block_size = ragged_block_size
self.rngs = rngs
def maybe_create_nnx(einsum, *args):
if isinstance(einsum, nn.Module):
return nnx_wrappers.ToNNX(einsum, rngs=rngs).lazy_init(*args)
return einsum
# qk_product
if self.kv_quant:
# Dummy inputs for lazy initialization
b = 1
t_prefill = self.max_prefill_predict_length
t_ar = 1 # Autoregressive mode has a query length of 1
n = self.num_query_heads
n_kv = self.num_kv_heads
d = self.config.head_dim
g = n // n_kv
s_prefill = self.max_prefill_predict_length
s_ar = self.max_target_length
# Dummy query/key/value shapes as before...
dummy_query_prefill = jnp.zeros((b, t_prefill, n_kv, g, d), dtype=self.dtype)
dummy_key_prefill = jnp.zeros((b, s_prefill, n_kv, d), dtype=self.dtype)
dummy_query_ar = jnp.zeros((b, t_ar, n_kv, g, d), dtype=self.dtype)
dummy_key_ar = jnp.zeros((b, s_ar, n_kv, d), dtype=self.dtype)
dummy_attn_weights_prefill = jnp.zeros((b, n_kv, g, t_prefill, s_prefill), dtype=jnp.float32)
dummy_value_prefill = jnp.zeros((b, s_prefill, n_kv, d), dtype=self.dtype)
dummy_attn_weights_ar = jnp.zeros((b, n_kv, g, t_ar, s_ar), dtype=jnp.float32)
dummy_value_ar = jnp.zeros((b, s_ar, n_kv, d), dtype=self.dtype)
# Prefill AqtEinsum instances
self.AqtEinsum_0 = maybe_create_nnx(
self.kv_quant.einsum_fn_with_rhs_qtensor(), "btkgd,bskd->bkgts", dummy_query_prefill, dummy_key_prefill
)
self.AqtEinsum_1 = maybe_create_nnx(
self.kv_quant.einsum_fn_with_rhs_qtensor_and_dequant(),
"bkgts,bskd->btkgd",
dummy_attn_weights_prefill,
dummy_value_prefill,
)
# Autoregressive AqtEinsum instances
self.AqtEinsum_2 = maybe_create_nnx(
self.kv_quant.einsum_fn_with_rhs_qtensor(), "btkgd,bskd->bkgts", dummy_query_ar, dummy_key_ar
)
self.AqtEinsum_3 = maybe_create_nnx(
self.kv_quant.einsum_fn_with_rhs_qtensor_and_dequant(),
"bkgts,bskd->btkgd",
dummy_attn_weights_ar,
dummy_value_ar,
)
else:
self.AqtEinsum_0 = jnp.einsum
self.AqtEinsum_1 = jnp.einsum
self.AqtEinsum_2 = jnp.einsum
self.AqtEinsum_3 = jnp.einsum
def check_attention_inputs(self, query: Array, key: Array | KVTensor, value: Array | KVTensor) -> None:
"""Check attention inputs."""
assert key.ndim == value.ndim, f"k (dim {key.ndim}), v (dim {value.ndim}) must have same rank."
assert (
query.shape[:-3] == key.shape[:-3] == value.shape[:-3]
), f"{query.shape[:-3]=}, {key.shape[:-3]=}, {value.shape[:-3]=} batch dims must match."
assert key.shape[-2] == value.shape[-2], "k, v num_kv_heads must match."
assert key.shape[-3] == value.shape[-3], "k, v lengths must match."
assert query.shape[-1] == key.shape[-1], "q, k depths must match."
def generate_attention_mask(
self,
query,
key,
decoder_segment_ids: Array | None,
model_mode: str,
previous_chunk: Any = None,
bidirectional_mask: Any = None,
) -> Array | None:
"""Generates a combined attention mask for Transformer models.
This function constructs an attention mask by potentially combining
several types of masks based on the input parameters and model
configuration. The generated mask dictates which query-key pairs are
allowed to attend to each other.
The masking logic can enforce:
1. **Sequence Separation:** Using `decoder_segment_ids`, attention is
confined within distinct sequences in a batch. This is crucial when
multiple unrelated sequences are packed together.
2. **Causality:** Preventing attention to future positions. This is
standard for autoregressive decoding. For chunked prefill, as
described in the SARATHI paper [2], causality is adjusted based
on `previous_chunk` information.
3. **Specialized Attention Patterns:** Depending on `self.attention_type`,
it can apply:
* Local Sliding Window Attention: Restricts attention to a
fixed-size window around each query position.
* Chunk Attention: Divides sequences into chunks and applies
masking at the chunk level.
4. **Bidirectional Attention for Sub-sequences:** If `bidirectional_mask`
is provided (e.g., for image tokens in a multimodal model),
those parts of the sequence can attend bidirectionally, and this
mask is OR-ed with other generated masks.
The overall approach and specific masking techniques are influenced by
efficient attention mechanisms like those found in the Pallas MHA
Flash Attention reference [1].
Args:
query: The query tensor, typically of shape
`[batch_size, q_sequence_length, num_heads, head_dim]`.
Used primarily for deriving sequence length.
key: The key tensor, typically of shape
`[batch_size, kv_sequence_length, num_heads, head_dim]`.
Used primarily for deriving sequence length.
decoder_segment_ids: Optional `Array` of shape `[batch_size, q_sequence_length]`.
Identifies distinct sequences within the batch. Attention is
restricted to elements within the same segment ID. In autoregressive
mode, specific values (e.g., `common_types.DECODING_ACTIVE_SEQUENCE_INDICATOR`)
can mark the currently active sequence for decoding.
model_mode: A string (e.g., `common_types.MODEL_MODE_AUTOREGRESSIVE`,
`MODEL_MODE_PREFILL`) indicating the operational
mode. This significantly influences mask generation, particularly
how causality and segment separation are handled.
previous_chunk: Optional. Information about previously processed
key/value chunks, often a tensor representing the previous keys/values.
Used to correctly offset causal masks in chunked attention or
streaming scenarios. Its shape might be
`[batch_size, prev_kv_sequence_length, ...]`.
bidirectional_mask: Optional `Array` of shape `[batch_size, kv_sequence_length]`.
If provided, this boolean mask indicates tokens (e.g., image tokens)
that are allowed to attend bidirectionally. The resulting
block-wise bidirectional mask is combined with other masks using a
logical OR.
Returns:
An `Array` representing the attention mask, broadcastable to the shape
`[batch_size, num_heads, q_sequence_length, kv_sequence_length]`.
Positions with `0.0` allow attention, while positions with
`DEFAULT_MASK_VALUE` (a large negative number) prevent it.
Returns `None` if no masking is determined to be necessary based on
the inputs and configuration.
References:
[1] JAX Pallas MHA Flash Attention:
https://github.com/jax-ml/jax/blob/main/jax/experimental/pallas/ops/tpu/flash_attention.py
[2] SARATHI: Efficient LLM Inference by Piggybacking Decodes with
Chunked Prefills - ArXiv:2308.16369 (https://arxiv.org/abs/2308.16369)
"""
mask = None
if model_mode == MODEL_MODE_AUTOREGRESSIVE:
mask = decoder_segment_ids[:, None, None, None, :] == DECODING_ACTIVE_SEQUENCE_INDICATOR
elif decoder_segment_ids is not None:
mask = decoder_segment_ids[:, :, None] == decoder_segment_ids[:, None, :]
mask = mask[:, None, None, :, :]
_, q_seq_len, _, _ = query.shape
_, kv_seq_len, _, _ = key.shape
next_pos = 0
if previous_chunk is not None:
next_pos = previous_chunk.shape[1]
if mask is not None:
mask = mask[:, :, :, next_pos : next_pos + q_seq_len, :]
elif model_mode == MODEL_MODE_AUTOREGRESSIVE and q_seq_len == 1:
# In autoregression, the query position is the last position in the KV sequence.
next_pos = kv_seq_len - 1
causal_mask = None
# We enforce causality except for AUTOREGRESSION
if model_mode != MODEL_MODE_AUTOREGRESSIVE and self.attention_type != AttentionType.FULL:
mask_shape = (q_seq_len, kv_seq_len)
# row_ids indicates the position of query
# col_ids indicates the position of kv
row_ids = jax.lax.broadcasted_iota(jnp.int32, mask_shape, 0)
col_ids = jax.lax.broadcasted_iota(jnp.int32, mask_shape, 1)
# Attention mask for chunked prefill is generated in the same way
# as mentioned in SARATHI - https://arxiv.org/abs/2308.16369
causal_mask = (col_ids <= row_ids + next_pos)[None, None, None, :, :]
output_mask = None
if (mask is not None) and (causal_mask is not None):
output_mask = jnp.logical_and(mask, causal_mask)
elif mask is not None:
output_mask = mask
elif causal_mask is not None:
output_mask = causal_mask
if self.attention_type == AttentionType.LOCAL_SLIDING and output_mask is not None:
if self.sliding_window_size is None:
raise ValueError("Sliding_window_size must be set if Local Sliding attention type")
row_ids_sliding = jax.lax.broadcasted_iota(jnp.int32, (q_seq_len, 1), 0) + next_pos
col_ids_sliding = jax.lax.broadcasted_iota(jnp.int32, (1, kv_seq_len), 1)
sliding_mask = (col_ids_sliding > (row_ids_sliding - self.sliding_window_size)) & (
col_ids_sliding <= row_ids_sliding
)
output_mask = sliding_mask * output_mask
elif self.attention_type == AttentionType.CHUNK and output_mask is not None:
mask_shape = (q_seq_len, kv_seq_len)
chunk_mask = _generate_chunk_attention_mask(
mask_shape=(q_seq_len, kv_seq_len), chunk_size=self.chunk_attn_window_size, q_offset=next_pos
)
output_mask = chunk_mask * output_mask
if bidirectional_mask is not None:
image_mask = _make_bidirectional_block_mask(bidirectional_mask)
output_mask = output_mask | image_mask[:, None, None, ...]
return jnp.where(output_mask, 0.0, DEFAULT_MASK_VALUE) if output_mask is not None else None
def calculate_moba_gate_logic(self, q_item, k_item, q_pos_item):
"""Computes the block-level MoBA gating intermediates for one batch item.
Args:
q_item: Query tensor shaped `[q_len, n_q_heads, head_dim]`.
k_item: Key tensor shaped `[kv_len, n_kv_heads, head_dim]`.
q_pos_item: Absolute query positions shaped `[q_len]`, used to derive the
chunk index for each query.
For example, during prefill after 128 tokens
have been processed `q_pos_item` is `jnp.arange(128, 128 + q_len)`,
while in autoregressive decode with a single query token it is
`jnp.array([kv_len - 1])`.
Returns:
`need_attend`, a boolean mask of shape `[n_kv_heads, g, q_len, num_block]`
indicating which key blocks each query should attend to. The additional
values in the returned tuple are debug intermediates used for logging and
diagnostics when inspecting the gating behaviour.
"""
q_len, n_q_heads, head_dim = q_item.shape
kv_len, n_kv_heads, _ = k_item.shape
g = n_q_heads // n_kv_heads
q_item_f32 = q_item.astype(jnp.float32).reshape(q_len, n_kv_heads, g, head_dim) # grouped-query attention (GQA)
moba_chunk_size = self.config.moba_chunk_size
moba_topk = self.config.moba_topk
num_block = math.ceil(kv_len / moba_chunk_size)
block_ids = jnp.arange(kv_len, dtype=jnp.int32) // moba_chunk_size # chunk index for each key position
# Sum key vectors per chunk so we can later average within each block.
key_gate_weight_sum = jax.ops.segment_sum(
k_item.astype(jnp.float32), block_ids, num_segments=num_block
) # [num_block, n_kv_heads, head_dim]
# Count how many tokens end up in each chunk so we can take the mean.
block_counts = jax.ops.segment_sum(
jnp.ones((kv_len,), dtype=jnp.float32), block_ids, num_segments=num_block
) # [num_block]
# Mean Pooling, Avoid division by zero for empty blocks.
key_gate_weight = key_gate_weight_sum / jnp.maximum(
block_counts[:, None, None], 1
) # [num_block, n_kv_heads, head_dim]
# Take the dot product between each query and every key chunk to get a score.
gate = jnp.einsum("skgd,Nkd->kgsN", q_item_f32, key_gate_weight) # [n_kv_heads, g, q_len, num_block]
gate_before_masking = gate
q_block_idx = q_pos_item // moba_chunk_size # chunk id for each query
block_indices = jnp.arange(num_block) # list every key chunk index
q_block_idx_b = jnp.expand_dims(q_block_idx, axis=-1) # [q_len, 1]
block_indices_b = jnp.expand_dims(block_indices, axis=0) # [1, num_block]
# Block-causal masking: a query can't attend to future key blocks,
# and must attend to its own key block.
mask_future = q_block_idx_b > block_indices_b
gate = jnp.where(mask_future, gate, -float("inf"))
mask_diag = q_block_idx_b == block_indices_b
gate = jnp.where(mask_diag, float("inf"), gate)
gate_after_masking = gate
k_for_topk = min(moba_topk, num_block)
gate_top_k_val, gate_top_k_idx = jax.lax.top_k(gate, k=k_for_topk) # [n_kv_heads, g, q_len, k_for_topk]
gate_top_k_val_min = jnp.min(gate_top_k_val, axis=-1, keepdims=True) # [n_kv_heads, g, q_len, 1]
need_attend_threshold_mask = gate >= gate_top_k_val_min # [n_kv_heads, g, q_len, num_block]
# Tie-breaking: if multiple blocks have the same gate value as the k-th
# block, we only select the ones that appear in the top-k indices.
gate_idx_mask = jnp.sum(
jax.nn.one_hot(gate_top_k_idx, num_block, dtype=jnp.bool_), axis=-2
) # [n_kv_heads, g, q_len, num_block]
need_attend = jnp.logical_and(need_attend_threshold_mask, gate_idx_mask) # [n_kv_heads, g, q_len, num_block]
return (
key_gate_weight,
gate_before_masking,
gate_after_masking,
gate_top_k_val,
gate_top_k_idx,
gate_top_k_val_min,
need_attend_threshold_mask,
gate_idx_mask,
need_attend, # [n_kv_heads, g, q_len, num_block]
)
def generate_moba_mask_single_item(self, q_item, k_item, q_positions):
"""Generates the token-level MoBA additive mask for a single batch item."""
q_len, _, _ = q_item.shape
kv_len, _, _ = k_item.shape
moba_chunk_size = self.config.moba_chunk_size
# Run the gating logic to find which key blocks this query cares about.
*_, need_attend = self.calculate_moba_gate_logic(q_item, k_item, q_positions)
# Expand the block-level `need_attend` mask to a token-level mask.
k_block_indices = jnp.arange(kv_len, dtype=jnp.int32) // moba_chunk_size
token_level_need_attend = need_attend[..., k_block_indices]
# Convert the boolean mask to float mask values.
gate = jnp.where(token_level_need_attend, 0.0, -float("inf"))
# Apply a final per-token causal mask to ensure causality within chunks.
k_indices = jax.lax.broadcasted_iota(jnp.int32, (q_len, kv_len), 1)
q_indices = q_positions[:, None]
causal_mask = q_indices >= k_indices
gate = jnp.where(causal_mask, gate, -float("inf"))
# Return the additive mask for this batch item.
return gate
def _generate_moba_mask(self, query: Array, key: Array, q_positions: Array) -> Array:
"""Builds the token-level MoBA additive mask for the whole batch.
Args:
query: Query tensor shaped `[batch, q_len, n_q_heads, head_dim]`.
key: Key tensor shaped `[batch, kv_len, n_kv_heads, head_dim]`.
q_positions: Absolute query positions shaped `[q_len]`, shared across the
batch, identifying the starting offset of each query token.
For example, in prefill after 128 tokens we pass
`jnp.arange(128, 128 + q_len)`, while in autoregressive decode with a
single new token the vector is `[kv_len - 1]` for each batch element.
Returns:
Additive attention mask with shape
`[batch, n_kv_heads, n_q_heads // n_kv_heads, q_len, kv_len]` containing
`0.` for permitted positions and `-inf` for masked ones.
"""
# vmap over the batch dimension of query and key. q_positions is constant across the batch.
moba_mask = jax.vmap(self.generate_moba_mask_single_item, in_axes=(0, 0, None))(query, key, q_positions)
return moba_mask
def apply_attention(
self,
query: Array,
key: Array | KVTensor,
value: Array | KVTensor,
decoder_segment_ids: Array | None,
lengths: Array | None,
model_mode: str,
use_ragged_attention: bool = False,
previous_chunk: Any = None,
bidirectional_mask: Any = None,
sinks: Array | None = None,
*,
qk_product_einsum: Callable[..., Array],
wv_product_einsum: Callable[..., Array],
):
"""Apply attention"""
self.check_attention_inputs(query, key, value)
length = query.shape[-3]
target_hardware = self.mesh.devices[(0,) * self.mesh.devices.ndim].platform
if use_ragged_attention and model_mode == MODEL_MODE_AUTOREGRESSIVE:
if lengths is None:
lengths = jnp.sum(decoder_segment_ids, axis=-1)
if target_hardware == "tpu":
impl = self.tpu_ragged_attention
elif target_hardware == "gpu":
impl = self.gpu_ragged_attention
else:
raise NotImplementedError(target_hardware)
return impl(query, key, value, lengths, self.ragged_block_size)
# 'vllm_rpa' uses the same dot-attention wrapper but routes to the vLLM
# ragged paged attention kernel in `Attention.__call__`.
elif (
self.attention_kernel == "dot_product"
or (self.attention_kernel == "autoselected" and model_mode == MODEL_MODE_AUTOREGRESSIVE)
or (self.attention_kernel == "autoselected" and length < 128)
or (self.attention_kernel == "paged")
or (self.attention_kernel == "vllm_rpa")
):
return self.apply_attention_dot(
query,
key,
value,
decoder_segment_ids,
model_mode,
previous_chunk,
bidirectional_mask=bidirectional_mask,
sinks=sinks,
qk_product_einsum=qk_product_einsum,
wv_product_einsum=wv_product_einsum,
)
elif self.attention_kernel in ("flash", "autoselected"):
if target_hardware == "tpu":
if isinstance(key, KVTensor):
key = key.dequant()
if isinstance(value, KVTensor):
value = value.dequant()
if model_mode == MODEL_MODE_AUTOREGRESSIVE:
raise ValueError(
"""Decode not supported with flash attention.
Use `dot_product` instead."""
)
return (
self.tpu_flash_attention(query, key, value, decoder_segment_ids, self.attn_logits_soft_cap, sinks),
None,
None,
)
else:
validate_flash_attention_with_sinks_on_gpu(sinks)
if model_mode == MODEL_MODE_AUTOREGRESSIVE:
# fallback to dot_product as pallas gpu flash attention doesn't support decode stage
return self.apply_attention_dot(
query,
key,
value,
decoder_segment_ids,
model_mode,
bidirectional_mask=bidirectional_mask,
qk_product_einsum=qk_product_einsum,
wv_product_einsum=wv_product_einsum,
)
else:
head_axis = -2
num_query_heads = query.shape[head_axis]
num_kv_heads = key.shape[head_axis]
if num_query_heads != num_kv_heads:
# Handle cases where the number of query heads is different from the number of key/value heads.
if num_query_heads % num_kv_heads != 0:
raise ValueError(
f"Number of query heads ({num_query_heads}) must be divisible by number of key/value heads ({num_kv_heads})."
)
# TODO Investigate if the KV copy can be eliminated. It's likely redundant.
q_heads_per_kv_head = num_query_heads // num_kv_heads
key = jnp.repeat(
key, q_heads_per_kv_head, axis=head_axis
) # key shape [batch_size, kv_seq_len, num_kv_heads, head_dim]
value = jnp.repeat(
value, q_heads_per_kv_head, axis=head_axis
) # value shape [batch_size, kv_seq_len, num_kv_heads, head_dim]
out = gpu_pallas_attention.mha(query, key, value, decoder_segment_ids, sm_scale=1.0, causal=True)
return out, None, None
elif self.attention_kernel == "cudnn_flash_te":
validate_flash_attention_with_sinks_on_gpu(sinks)
if isinstance(key, KVTensor):
key = key.dequant()
if isinstance(value, KVTensor):
value = value.dequant()
if model_mode == MODEL_MODE_AUTOREGRESSIVE:
raise ValueError(
"""Decode not supported with flash attention.
Use `dot_product` instead."""
)
return self.cudnn_flash_attention(query, key, value, decoder_segment_ids, model_mode), None, None
elif self.attention_kernel == "cudnn_flash_jax":
validate_flash_attention_with_sinks_on_gpu(sinks)
if isinstance(key, KVTensor):
key = key.dequant()
if isinstance(value, KVTensor):
value = value.dequant()
return *self.cudnn_jax_flash_attention(query, key, value, decoder_segment_ids, model_mode), None
else:
raise ValueError(f"Unexpected attention kernel {self.attention_kernel=}.")
def gpu_ragged_attention(self, q: Array, k: Array | KVTensor, v: Array | KVTensor, lengths: Array, block_size: int):
"""gpu ragged attention"""
batch_size, q_length, q_heads, head_dim = q.shape
# Reshape q to match gqa's expected shape
q_for_gqa = q.squeeze(axis=1)
# Define logical axis names - clearer and avoids repeated calls.
b = nn.logical_to_mesh_axes(self.ragged_lengths_names)
bsnd = nn.logical_to_mesh_axes(self.cache_logical_axis_names)
bnd = nn.logical_to_mesh_axes((CACHE_BATCH, CACHE_HEADS, CACHE_KV))
bn = nn.logical_to_mesh_axes((CACHE_BATCH, CACHE_HEADS))
@functools.partial(
jax.shard_map,
mesh=self.mesh,
in_specs=(bnd, bsnd, bsnd, b, None),
out_specs=(bnd, bn, bn),
check_vma=False,
)
def wrap_ragged_attention(
q: Array, k: Array, v: Array, lengths: Array, block_size: int
) -> Tuple[Array, Array, Array]:
# Use the original gqa function to get the attention output
"""
Wraps the GQA function with appropriate sharding.
Args:
q: Query tensor.
k: Key tensor.
v: Value tensor.
lengths: Sequence lengths.
block_size: Block size for attention.
Returns:
A tuple containing the output, max, and sum tensors.
"""
# Use the original gqa function to get the attention output
local_out, (local_sum, local_max) = gpu_pallas_decode_attention.gqa(
q=q,
k=k,
v=v,
kv_seq_len=lengths,
block_k=block_size,
sm_scale=1.0,
return_residuals=True,
normalize_output=False,
)
return local_out, local_max, local_sum
local_out, local_max, local_sum = wrap_ragged_attention(q_for_gqa, k, v, lengths, block_size)
# Reshape local_out, local_max and local_sum to match Maxtext requirements
local_out = local_out.reshape(batch_size, q_length, q_heads, head_dim)
local_max = local_max.reshape(batch_size, q_length, q_heads, 1)
local_sum = local_sum.reshape(batch_size, q_length, q_heads, 1)