tpu-inference 0.0.1rc1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of tpu-inference might be problematic. Click here for more details.

Files changed (174) hide show
  1. tests/__init__.py +0 -0
  2. tests/core/__init__.py +0 -0
  3. tests/core/test_core_tpu.py +513 -0
  4. tests/core/test_disagg_executor.py +60 -0
  5. tests/core/test_disagg_utils.py +53 -0
  6. tests/core/test_dp_scheduler.py +899 -0
  7. tests/core/test_init.py +49 -0
  8. tests/kernels/__init__.py +0 -0
  9. tests/kernels/fused_moe_v1_test.py +374 -0
  10. tests/kernels/mla_v1_test.py +396 -0
  11. tests/kernels/quantized_matmul_kernel_test.py +191 -0
  12. tests/kernels/ragged_kv_cache_update_v2_test.py +234 -0
  13. tests/kernels/ragged_paged_attention_kernel_v2_test.py +400 -0
  14. tests/kernels/ragged_paged_attention_kernel_v3_hd64_test.py +549 -0
  15. tests/kernels/ragged_paged_attention_kernel_v3_test.py +504 -0
  16. tests/lora/__init__.py +0 -0
  17. tests/lora/conftest.py +32 -0
  18. tests/lora/test_bgmv.py +43 -0
  19. tests/lora/test_layers.py +648 -0
  20. tests/lora/test_lora.py +133 -0
  21. tests/lora/utils.py +88 -0
  22. tests/test_base.py +201 -0
  23. tests/test_envs.py +203 -0
  24. tests/test_quantization.py +836 -0
  25. tests/test_tpu_info.py +120 -0
  26. tests/test_utils.py +235 -0
  27. tpu_inference/__init__.py +53 -0
  28. tpu_inference/core/__init__.py +0 -0
  29. tpu_inference/core/core_tpu.py +786 -0
  30. tpu_inference/core/disagg_executor.py +118 -0
  31. tpu_inference/core/disagg_utils.py +49 -0
  32. tpu_inference/core/sched/__init__.py +0 -0
  33. tpu_inference/core/sched/dp_scheduler.py +523 -0
  34. tpu_inference/distributed/__init__.py +0 -0
  35. tpu_inference/distributed/jax_parallel_state.py +67 -0
  36. tpu_inference/distributed/tpu_connector.py +727 -0
  37. tpu_inference/distributed/utils.py +60 -0
  38. tpu_inference/env_override.py +9 -0
  39. tpu_inference/envs.py +160 -0
  40. tpu_inference/executors/__init__.py +0 -0
  41. tpu_inference/executors/ray_distributed_executor.py +382 -0
  42. tpu_inference/experimental/__init__.py +0 -0
  43. tpu_inference/experimental/llama3_jax_stashed.py +258 -0
  44. tpu_inference/kernels/__init__.py +0 -0
  45. tpu_inference/kernels/collectives/__init__.py +0 -0
  46. tpu_inference/kernels/collectives/all_gather_matmul.py +735 -0
  47. tpu_inference/kernels/collectives/all_gather_matmul_tuned_block_sizes.py +60 -0
  48. tpu_inference/kernels/collectives/util.py +47 -0
  49. tpu_inference/kernels/flash_attention/__init__.py +0 -0
  50. tpu_inference/kernels/flash_attention/kernel.py +772 -0
  51. tpu_inference/kernels/fused_moe/__init__.py +0 -0
  52. tpu_inference/kernels/fused_moe/v1/__init__.py +0 -0
  53. tpu_inference/kernels/fused_moe/v1/kernel.py +1566 -0
  54. tpu_inference/kernels/mla/__init__.py +0 -0
  55. tpu_inference/kernels/mla/v1/__init__.py +0 -0
  56. tpu_inference/kernels/mla/v1/kernel.py +1349 -0
  57. tpu_inference/kernels/quantized_matmul/__init__.py +0 -0
  58. tpu_inference/kernels/quantized_matmul/kernel.py +395 -0
  59. tpu_inference/kernels/quantized_matmul/tuned_block_sizes.py +609 -0
  60. tpu_inference/kernels/quantized_matmul/util.py +58 -0
  61. tpu_inference/kernels/ragged_paged_attention/__init__.py +0 -0
  62. tpu_inference/kernels/ragged_paged_attention/v2/__init__.py +0 -0
  63. tpu_inference/kernels/ragged_paged_attention/v2/kernel.py +875 -0
  64. tpu_inference/kernels/ragged_paged_attention/v2/ragged_kv_cache_update.py +287 -0
  65. tpu_inference/kernels/ragged_paged_attention/v2/tuned_block_sizes.py +1482 -0
  66. tpu_inference/kernels/ragged_paged_attention/v3/__init__.py +0 -0
  67. tpu_inference/kernels/ragged_paged_attention/v3/kernel.py +1501 -0
  68. tpu_inference/kernels/ragged_paged_attention/v3/kernel_hd64.py +1603 -0
  69. tpu_inference/kernels/ragged_paged_attention/v3/tuned_block_sizes.py +4147 -0
  70. tpu_inference/kernels/ragged_paged_attention/v3/tuned_block_sizes_hd64.py +367 -0
  71. tpu_inference/kernels/ragged_paged_attention/v3/util.py +51 -0
  72. tpu_inference/layers/__init__.py +0 -0
  73. tpu_inference/layers/common/__init__.py +0 -0
  74. tpu_inference/layers/common/attention_interface.py +396 -0
  75. tpu_inference/layers/common/attention_metadata.py +34 -0
  76. tpu_inference/layers/common/binary_search.py +295 -0
  77. tpu_inference/layers/common/quant_methods.py +8 -0
  78. tpu_inference/layers/common/sharding.py +582 -0
  79. tpu_inference/layers/jax/__init__.py +0 -0
  80. tpu_inference/layers/jax/attention/__init__.py +0 -0
  81. tpu_inference/layers/jax/attention/attention.py +255 -0
  82. tpu_inference/layers/jax/attention/deepseek_v3_attention.py +354 -0
  83. tpu_inference/layers/jax/attention/gpt_oss_attention.py +262 -0
  84. tpu_inference/layers/jax/attention/llama4_attention.py +153 -0
  85. tpu_inference/layers/jax/base.py +151 -0
  86. tpu_inference/layers/jax/constants.py +88 -0
  87. tpu_inference/layers/jax/layers.py +301 -0
  88. tpu_inference/layers/jax/misc.py +16 -0
  89. tpu_inference/layers/jax/moe/__init__.py +0 -0
  90. tpu_inference/layers/jax/moe/deepseek_v3_moe.py +608 -0
  91. tpu_inference/layers/jax/moe/gpt_oss_moe.py +185 -0
  92. tpu_inference/layers/jax/moe/moe.py +209 -0
  93. tpu_inference/layers/jax/rope.py +280 -0
  94. tpu_inference/layers/jax/rope_interface.py +214 -0
  95. tpu_inference/layers/jax/sample/__init__.py +0 -0
  96. tpu_inference/layers/jax/sample/rejection_sampler.py +515 -0
  97. tpu_inference/layers/jax/sample/sampling.py +96 -0
  98. tpu_inference/layers/jax/sample/sampling_metadata.py +76 -0
  99. tpu_inference/layers/jax/transformer_block.py +107 -0
  100. tpu_inference/layers/vllm/__init__.py +0 -0
  101. tpu_inference/layers/vllm/attention.py +221 -0
  102. tpu_inference/layers/vllm/fused_moe.py +469 -0
  103. tpu_inference/layers/vllm/linear_common.py +186 -0
  104. tpu_inference/layers/vllm/quantization/__init__.py +39 -0
  105. tpu_inference/layers/vllm/quantization/awq.py +207 -0
  106. tpu_inference/layers/vllm/quantization/common.py +110 -0
  107. tpu_inference/layers/vllm/quantization/compressed_tensors/__init__.py +0 -0
  108. tpu_inference/layers/vllm/quantization/compressed_tensors/compressed_tensors.py +120 -0
  109. tpu_inference/layers/vllm/quantization/compressed_tensors/compressed_tensors_moe.py +203 -0
  110. tpu_inference/layers/vllm/quantization/compressed_tensors/schemes/__init__.py +0 -0
  111. tpu_inference/layers/vllm/quantization/compressed_tensors/schemes/compressed_tensors_w8a8_fp8.py +208 -0
  112. tpu_inference/layers/vllm/quantization/compressed_tensors/schemes/compressed_tensors_w8a8_int8.py +136 -0
  113. tpu_inference/layers/vllm/quantization/mxfp4.py +331 -0
  114. tpu_inference/layers/vllm/quantization/unquantized.py +368 -0
  115. tpu_inference/layers/vllm/sharding.py +230 -0
  116. tpu_inference/logger.py +10 -0
  117. tpu_inference/lora/__init__.py +0 -0
  118. tpu_inference/lora/torch_lora_ops.py +103 -0
  119. tpu_inference/lora/torch_punica_tpu.py +310 -0
  120. tpu_inference/models/__init__.py +0 -0
  121. tpu_inference/models/common/__init__.py +0 -0
  122. tpu_inference/models/common/model_loader.py +478 -0
  123. tpu_inference/models/jax/__init__.py +0 -0
  124. tpu_inference/models/jax/deepseek_v3.py +868 -0
  125. tpu_inference/models/jax/gpt_oss.py +492 -0
  126. tpu_inference/models/jax/jax_intermediate_tensor.py +79 -0
  127. tpu_inference/models/jax/llama3.py +376 -0
  128. tpu_inference/models/jax/llama4.py +629 -0
  129. tpu_inference/models/jax/llama_eagle3.py +336 -0
  130. tpu_inference/models/jax/llama_guard_4.py +361 -0
  131. tpu_inference/models/jax/qwen2.py +376 -0
  132. tpu_inference/models/jax/qwen2_5_vl.py +1218 -0
  133. tpu_inference/models/jax/qwen3.py +303 -0
  134. tpu_inference/models/jax/utils/__init__.py +0 -0
  135. tpu_inference/models/jax/utils/file_utils.py +96 -0
  136. tpu_inference/models/jax/utils/multi_modal_utils.py +163 -0
  137. tpu_inference/models/jax/utils/quantization/__init__.py +0 -0
  138. tpu_inference/models/jax/utils/quantization/configs/fp8_all_modules_w_only.yaml +5 -0
  139. tpu_inference/models/jax/utils/quantization/configs/fp8_default.yaml +6 -0
  140. tpu_inference/models/jax/utils/quantization/configs/int8_all_modules_w_only.yaml +5 -0
  141. tpu_inference/models/jax/utils/quantization/configs/int8_default.yaml +6 -0
  142. tpu_inference/models/jax/utils/quantization/mxfp4_utils.py +105 -0
  143. tpu_inference/models/jax/utils/quantization/quantization_utils.py +650 -0
  144. tpu_inference/models/jax/utils/weight_utils.py +584 -0
  145. tpu_inference/models/vllm/__init__.py +0 -0
  146. tpu_inference/models/vllm/vllm_model_wrapper.py +293 -0
  147. tpu_inference/models/vllm/vllm_model_wrapper_context.py +45 -0
  148. tpu_inference/platforms/__init__.py +2 -0
  149. tpu_inference/platforms/tpu_platform.py +275 -0
  150. tpu_inference/runner/__init__.py +0 -0
  151. tpu_inference/runner/block_table.py +122 -0
  152. tpu_inference/runner/compilation_manager.py +865 -0
  153. tpu_inference/runner/input_batch.py +435 -0
  154. tpu_inference/runner/kv_cache.py +132 -0
  155. tpu_inference/runner/kv_cache_manager.py +478 -0
  156. tpu_inference/runner/lora_utils.py +92 -0
  157. tpu_inference/runner/multimodal_manager.py +217 -0
  158. tpu_inference/runner/persistent_batch_manager.py +282 -0
  159. tpu_inference/runner/speculative_decoding_manager.py +248 -0
  160. tpu_inference/runner/structured_decoding_manager.py +87 -0
  161. tpu_inference/runner/tpu_runner.py +1744 -0
  162. tpu_inference/runner/utils.py +426 -0
  163. tpu_inference/spec_decode/__init__.py +0 -0
  164. tpu_inference/spec_decode/jax/__init__.py +0 -0
  165. tpu_inference/spec_decode/jax/eagle3.py +417 -0
  166. tpu_inference/tpu_info.py +78 -0
  167. tpu_inference/utils.py +340 -0
  168. tpu_inference/worker/__init__.py +0 -0
  169. tpu_inference/worker/tpu_worker.py +458 -0
  170. tpu_inference-0.0.1rc1.dist-info/METADATA +108 -0
  171. tpu_inference-0.0.1rc1.dist-info/RECORD +174 -0
  172. tpu_inference-0.0.1rc1.dist-info/WHEEL +5 -0
  173. tpu_inference-0.0.1rc1.dist-info/licenses/LICENSE +201 -0
  174. tpu_inference-0.0.1rc1.dist-info/top_level.txt +2 -0
@@ -0,0 +1,1603 @@
1
+ """
2
+ A variant of TPU-Friendly Ragged Paged Attention kernel optimized for
3
+ head_dim = 64.
4
+ """
5
+
6
+ import functools
7
+
8
+ import jax
9
+ import jax.numpy as jnp
10
+ from jax import lax
11
+ from jax.experimental import pallas as pl
12
+ from jax.experimental.pallas import tpu as pltpu
13
+
14
+ from tpu_inference.kernels.ragged_paged_attention.v3.tuned_block_sizes_hd64 import \
15
+ get_tuned_block_sizes
16
+ from tpu_inference.kernels.ragged_paged_attention.v3.util import (
17
+ align_to, cdiv, get_dtype_packing)
18
+
19
+ DEFAULT_MASK_VALUE = -0.7 * float(jnp.finfo(jnp.dtype("float32")).max)
20
+
21
+ DEFAULT_VMEM_LIMIT_BYTES = 100 * 1024 * 1024
22
+
23
+
24
+ # TODO(chengjiyao): refactor this hd64 variant and the original kernel to make
25
+ # sure most of the code is shared.
26
+ def ref_ragged_paged_attention_hd64(
27
+ queries: jax.
28
+ Array, # [max_num_tokens, actual_num_q_heads, actual_head_dim]
29
+ keys: jax.Array, # [max_num_tokens, actual_num_kv_heads, actual_head_dim]
30
+ values: jax.
31
+ Array, # [max_num_tokens, actual_num_kv_heads, actual_head_dim]
32
+ kv_cache: jax.
33
+ Array, # [total_num_pages, page_size, num_kv_heads, kv_packing, actual_head_dim_x2]
34
+ kv_lens: jax.Array, # i32[max_num_seqs]
35
+ page_indices: jax.Array, # i32[max_num_seqs * pages_per_seq]
36
+ cu_q_lens: jax.Array, # i32[max_num_seqs + 1]
37
+ distribution: jax.Array, # i32[3]
38
+ attention_sink: jax.Array | None = None, # f32[actual_num_q_heads]
39
+ *,
40
+ sm_scale: float = 1.0,
41
+ sliding_window: int | None = None,
42
+ soft_cap: float | None = None,
43
+ mask_value: float | None = DEFAULT_MASK_VALUE,
44
+ q_scale: float | None = None,
45
+ k_scale: float | None = None,
46
+ v_scale: float | None = None,
47
+ ):
48
+ if mask_value is None:
49
+ mask_value = DEFAULT_MASK_VALUE
50
+ dynamic_validate_inputs(
51
+ queries,
52
+ keys,
53
+ values,
54
+ kv_cache,
55
+ kv_lens,
56
+ page_indices,
57
+ cu_q_lens,
58
+ distribution,
59
+ attention_sink,
60
+ sm_scale=sm_scale,
61
+ sliding_window=sliding_window,
62
+ soft_cap=soft_cap,
63
+ mask_value=mask_value,
64
+ q_scale=q_scale,
65
+ k_scale=k_scale,
66
+ v_scale=v_scale,
67
+ )
68
+ actual_head_dim = queries.shape[2]
69
+ actual_num_q_heads = queries.shape[1]
70
+ actual_num_kv_heads = keys.shape[1]
71
+ assert actual_head_dim == 64
72
+ (
73
+ _,
74
+ page_size,
75
+ _,
76
+ kv_packing,
77
+ actual_head_dim_x2,
78
+ ) = kv_cache.shape
79
+
80
+ assert actual_num_q_heads % actual_num_kv_heads == 0
81
+ assert actual_head_dim_x2 == 128
82
+ assert get_dtype_packing(kv_cache.dtype) == kv_packing
83
+ actual_num_q_heads_per_kv_head = actual_num_q_heads // actual_num_kv_heads
84
+ padded_actual_num_kv_heads = align_to(actual_num_kv_heads, kv_packing)
85
+ max_num_seqs = kv_lens.shape[0]
86
+ num_page_indices = page_indices.shape[0]
87
+ assert num_page_indices % max_num_seqs == 0
88
+ pages_per_seq = num_page_indices // max_num_seqs
89
+
90
+ # prepare kv and queries
91
+ merged_kv = merge_kv(keys, values)
92
+ queries = jnp.pad(queries, ((0, 0), (0, 0), (0, 64)), constant_values=0.0)
93
+ outputs = []
94
+
95
+ for i in range(distribution[-1]):
96
+ q_start = cu_q_lens[i]
97
+ q_end = cu_q_lens[i + 1]
98
+ q_len = q_end - q_start
99
+
100
+ kv_len = kv_lens[i]
101
+ indices_start = i * pages_per_seq
102
+ indices_end = indices_start + cdiv(kv_len, page_size)
103
+ indices = page_indices[indices_start:indices_end]
104
+ q = queries[q_start:q_end, :, :]
105
+
106
+ # Update the kv cache.
107
+ assert kv_len - q_len >= 0
108
+ gathered_kv = kv_cache[indices]
109
+ gathered_shape = gathered_kv.shape
110
+ gathered_kv = gathered_kv.reshape(-1, *gathered_shape[-3:])
111
+ gathered_kv = gathered_kv.at[kv_len - q_len:kv_len].set(
112
+ merged_kv[q_start:q_end])
113
+ kv_cache = kv_cache.at[indices].set(
114
+ gathered_kv.reshape(gathered_shape))
115
+
116
+ kv = gathered_kv.reshape(
117
+ -1, padded_actual_num_kv_heads,
118
+ actual_head_dim_x2)[:, :actual_num_kv_heads, :]
119
+ kv = kv[:kv_len, :, :]
120
+ kv = jnp.repeat(kv, actual_num_q_heads_per_kv_head, axis=1)
121
+ if q_scale is not None:
122
+ q = q / q_scale
123
+ if jnp.issubdtype(kv.dtype, jnp.floating):
124
+ dtype_info = jnp.finfo(kv.dtype)
125
+ minval = float(dtype_info.min)
126
+ maxval = float(dtype_info.max)
127
+ q = jnp.clip(q, min=minval, max=maxval)
128
+ q = q.astype(kv.dtype)
129
+ attn = jnp.einsum("qhd,khd->hqk",
130
+ q,
131
+ kv,
132
+ preferred_element_type=jnp.float32)
133
+ attn *= sm_scale
134
+ if k_scale is not None:
135
+ attn *= k_scale
136
+ if q_scale is not None:
137
+ attn *= q_scale
138
+
139
+ q_span = (kv_len - q_len) + jax.lax.broadcasted_iota(
140
+ jnp.int32, attn.shape, 1)
141
+ kv_span = jax.lax.broadcasted_iota(jnp.int32, attn.shape, 2)
142
+ mask = q_span < kv_span
143
+ if sliding_window is not None:
144
+ mask = jnp.logical_or(mask, q_span - sliding_window >= kv_span)
145
+ if soft_cap is not None:
146
+ attn = soft_cap * jnp.tanh(attn / soft_cap)
147
+ attn = jnp.where(mask, mask_value, attn)
148
+
149
+ if attention_sink is not None:
150
+ reshaped_attention_sink = attention_sink.reshape(
151
+ actual_num_q_heads, 1, 1)
152
+ reshaped_attention_sink = jnp.repeat(reshaped_attention_sink,
153
+ q_len,
154
+ axis=1)
155
+ attn = jnp.concat([reshaped_attention_sink, attn], axis=2)
156
+ attn = jax.nn.softmax(attn, axis=-1).astype(kv.dtype)
157
+ attn = attn[..., 1:]
158
+ else:
159
+ attn = jax.nn.softmax(attn, axis=-1).astype(kv.dtype)
160
+
161
+ out = jnp.einsum("hqk,khd->qhd", attn, kv).astype(queries.dtype)
162
+ if v_scale is not None:
163
+ out *= v_scale
164
+
165
+ outputs.append(out)
166
+
167
+ result = jnp.concatenate(outputs, axis=0)
168
+ result = result[:, :, actual_head_dim:]
169
+ return result, kv_cache
170
+
171
+
172
+ def get_smem_estimate_bytes(max_num_seqs, pages_per_seq):
173
+ total_bits = (
174
+ # kv_lens_ref: i32[max_num_seqs]
175
+ align_to(max_num_seqs, 128) * 32 +
176
+ # page_indices_ref: i32[max_num_seqs * pages_per_seq]
177
+ align_to(max_num_seqs * pages_per_seq, 128) * 32 +
178
+ # cu_q_lens_ref: i32[max_num_seqs + 1]
179
+ align_to(max_num_seqs + 1, 128) * 32 +
180
+ # distribution_ref: i32[3]
181
+ 128 * 32 +
182
+ # sem_ids_ref: i32[3]
183
+ 128 * 32 +
184
+ # bo_ids_ref: i32[4]
185
+ 128 * 32 +
186
+ # bkv_update_ids_ref: i32[6]
187
+ 128 * 32)
188
+ return cdiv(total_bits, 8)
189
+
190
+
191
+ def get_vmem_estimate_bytes(
192
+ actual_num_kv_heads,
193
+ actual_num_q_heads_per_kv_head,
194
+ actual_head_dim,
195
+ bq_sz,
196
+ bkv_sz,
197
+ q_dtype,
198
+ kv_dtype,
199
+ ):
200
+ assert actual_head_dim == 64
201
+ q_packing = get_dtype_packing(q_dtype)
202
+ kv_packing = get_dtype_packing(kv_dtype)
203
+ num_q_heads_per_kv_head = align_to(actual_num_q_heads_per_kv_head,
204
+ q_packing)
205
+ num_kv_heads = align_to(actual_num_kv_heads, kv_packing)
206
+ head_dim = actual_head_dim * 2
207
+
208
+ total_bits = (
209
+ # bkv_x2_ref
210
+ (2 * bkv_sz * num_kv_heads * head_dim) * (32 // kv_packing) +
211
+ # bq_x2_ref + bo_x2_ref
212
+ 2 * (2 * actual_num_kv_heads * bq_sz * num_q_heads_per_kv_head *
213
+ head_dim) * (32 // q_packing) +
214
+ # l_ref + m_ref
215
+ 2 *
216
+ (actual_num_kv_heads * bq_sz * num_q_heads_per_kv_head * 128) * 32 +
217
+ # acc_ref
218
+ (actual_num_kv_heads * bq_sz * num_q_heads_per_kv_head * head_dim) *
219
+ 32)
220
+ return cdiv(total_bits, 8)
221
+
222
+
223
+ def get_kv_cache_shape(
224
+ total_num_pages,
225
+ page_size,
226
+ actual_num_kv_heads,
227
+ actual_head_dim,
228
+ kv_dtype,
229
+ ):
230
+ assert actual_head_dim == 64
231
+ kv_packing = get_dtype_packing(kv_dtype)
232
+ return (
233
+ total_num_pages,
234
+ page_size,
235
+ align_to(actual_num_kv_heads, kv_packing) // kv_packing,
236
+ kv_packing,
237
+ 128,
238
+ )
239
+
240
+
241
+ def _ragged_paged_attention_kernel(
242
+ # Prefetch
243
+ kv_lens_ref, # [max_num_seqs]
244
+ page_indices_ref, # [max_num_seqs * pages_per_seq]
245
+ cu_q_lens_ref, # [max_num_seqs + 1]
246
+ # TODO(jevinjiang): merge these into one so we can save SMEM.
247
+ distribution_ref, # [3] (decode_end, prefill_end, mixed_end)
248
+ sem_ids_ref, # [3] (bq_sem_idx, bkv_sem_idx, bo_sem_idx)
249
+ bo_ids_ref, # [4] (bo_sem_0_seq_idx, bo_sem_1_seq_idx, bo_sem_0_bo_idx, bo_sem_1_bo_idx)
250
+ bkv_update_ids_ref, # [6] (bkv_sem_0_seq_idx, bkv_sem_1_seq_idx, bkv_sem_0_offset, bkv_sem_1_offset, bkv_sem_0_sz, bkv_sem_1_sz)
251
+ # Input
252
+ q_hbm_ref, # [actual_num_kv_heads, max_num_tokens, num_q_heads_per_kv_head // q_packing, q_packing, head_dim]
253
+ kv_hbm_ref, # [max_num_tokens, num_kv_heads // kv_packing, kv_packing, actual_head_dim_x2]
254
+ kv_cache_hbm_ref, # [total_num_pages, page_size, num_kv_heads // kv_packing, kv_packing, actual_head_dim_x2]
255
+ attention_sink_ref, # [actual_num_kv_heads, num_q_heads_per_kv_head, 128]
256
+ # Output
257
+ o_hbm_ref, # [actual_num_kv_heads, max_num_tokens, num_q_heads_per_kv_head // q_packing, q_packing, actual_head_dim_x2]
258
+ updated_kv_cache_hbm_ref, # [total_num_pages, page_size, num_kv_heads // kv_packing, kv_packing, actual_head_dim_x2]
259
+ # Scratch
260
+ bkv_x2_ref, # [2, bkv_sz, num_kv_heads // kv_packing, kv_packing, actual_head_dim_x2]
261
+ bq_x2_ref, # [2, actual_num_kv_heads, bq_sz, num_q_heads_per_kv_head // q_packing, q_packing, actual_head_dim_x2]
262
+ bo_x2_ref, # [2, actual_num_kv_heads, bq_sz, num_q_heads_per_kv_head // q_packing, q_packing, actual_head_dim_x2]
263
+ sems, # [4, 2]
264
+ l_ref, # [actual_num_kv_heads, bq_sz * num_q_heads_per_kv_head, 128],
265
+ m_ref, # [actual_num_kv_heads, bq_sz * num_q_heads_per_kv_head, 128],
266
+ acc_ref, # [actual_num_kv_heads, bq_sz * num_q_heads_per_kv_head, actual_head_dim_x2],
267
+ *,
268
+ sm_scale: float,
269
+ sliding_window: int | None = None,
270
+ strict_sliding_window: bool = True,
271
+ soft_cap: float | None = None,
272
+ mask_value: float = DEFAULT_MASK_VALUE,
273
+ q_scale: float | None = None,
274
+ k_scale: float | None = None,
275
+ v_scale: float | None = None,
276
+ chunk_prefill_size: int | None = None,
277
+ bkv_p,
278
+ bq_sz,
279
+ debug_mode: bool = False,
280
+ ):
281
+ assert q_hbm_ref.shape == o_hbm_ref.shape
282
+ assert q_hbm_ref.shape[-1] == kv_cache_hbm_ref.shape[-1]
283
+ (
284
+ actual_num_kv_heads,
285
+ max_num_tokens,
286
+ num_q_heads_per_kv_head_per_packing,
287
+ q_packing,
288
+ actual_head_dim_x2,
289
+ ) = q_hbm_ref.shape
290
+ (
291
+ total_num_pages,
292
+ page_size,
293
+ num_kv_heads_per_kv_packing,
294
+ kv_packing,
295
+ _,
296
+ ) = kv_cache_hbm_ref.shape
297
+ max_num_seqs = kv_lens_ref.shape[0]
298
+ num_page_indices = page_indices_ref.shape[0]
299
+ assert num_page_indices % max_num_seqs == 0
300
+ pages_per_seq = num_page_indices // max_num_seqs
301
+ num_kv_heads = num_kv_heads_per_kv_packing * kv_packing
302
+ num_q_heads_per_kv_head = num_q_heads_per_kv_head_per_packing * q_packing
303
+ q_dtype = q_hbm_ref.dtype
304
+ kv_dtype = kv_cache_hbm_ref.dtype
305
+ assert o_hbm_ref.dtype == q_dtype
306
+ assert get_dtype_packing(q_dtype) == q_packing
307
+ assert get_dtype_packing(kv_dtype) == kv_packing
308
+ assert actual_head_dim_x2 == 128
309
+ bkv_sz = bkv_p * page_size
310
+ seq_idx = pl.program_id(0)
311
+ num_seqs = pl.num_programs(0)
312
+ decode_end = distribution_ref[0]
313
+ prefill_end = distribution_ref[1]
314
+ mixed_end = distribution_ref[2]
315
+
316
+ q_start = cu_q_lens_ref[seq_idx]
317
+ q_end = cu_q_lens_ref[seq_idx + 1]
318
+ q_len = q_end - q_start
319
+ kv_len = kv_lens_ref[seq_idx]
320
+
321
+ if sliding_window is None:
322
+ bkv_idx_start = next_seq_bkv_idx_start = 0
323
+ else:
324
+ bkv_idx_start = jnp.maximum(kv_len - q_len - sliding_window,
325
+ 0) // bkv_sz
326
+
327
+ def get_next_bkv_idx_start():
328
+ next_kv_len = kv_lens_ref[seq_idx + 1]
329
+ next_q_len = cu_q_lens_ref[seq_idx + 2] - q_end
330
+ return jnp.maximum(next_kv_len - next_q_len - sliding_window,
331
+ 0) // bkv_sz
332
+
333
+ next_seq_bkv_idx_start = lax.cond(seq_idx + 1 < num_seqs,
334
+ get_next_bkv_idx_start, lambda: 0)
335
+
336
+ def debug_print(msg, *args):
337
+ if debug_mode:
338
+ pl.debug_print(msg, *args)
339
+
340
+ debug_print("[RPA debug] ======= In loop seq_idx={}", seq_idx)
341
+ debug_print("[RPA debug] num_seqs={}", num_seqs)
342
+ debug_print("[RPA debug] decode_end={}", decode_end)
343
+ debug_print("[RPA debug] prefill_end={}", prefill_end)
344
+ debug_print("[RPA debug] mixed_end={}", mixed_end)
345
+ debug_print("[RPA debug] bkv_p={}", bkv_p)
346
+ debug_print("[RPA debug] page_size={}", page_size)
347
+ debug_print("[RPA debug] pages_per_seq={}", pages_per_seq)
348
+ debug_print("[RPA debug] bkv_sz={}", bkv_sz)
349
+ debug_print("[RPA debug] bq_sz={}", bq_sz)
350
+ debug_print("[RPA debug] q_start={}", q_start)
351
+ debug_print("[RPA debug] q_end={}", q_end)
352
+ debug_print("[RPA debug] q_len={}", q_len)
353
+ debug_print("[RPA debug] kv_len={}", kv_len)
354
+
355
+ def flash_attention_step1_qk_softmax(
356
+ q, # [actual_bq_sz * num_q_heads_per_kv_head, actual_head_dim_x2]
357
+ kv, # [bkv_sz, actual_head_dim_x2]
358
+ *,
359
+ bq_idx,
360
+ bkv_idx,
361
+ kv_head_idx,
362
+ ):
363
+ assert len(q.shape) == 2
364
+ assert q.shape[0] % num_q_heads_per_kv_head == 0
365
+ assert q.shape[1] == actual_head_dim_x2
366
+ assert kv.shape == (bkv_sz, actual_head_dim_x2)
367
+ head_l_ref = l_ref.at[kv_head_idx, :q.shape[0]]
368
+ head_m_ref = m_ref.at[kv_head_idx, :q.shape[0]]
369
+
370
+ def load_with_init(ref, init_val):
371
+ return jnp.where(bkv_idx == bkv_idx_start,
372
+ jnp.full_like(ref, init_val), ref[...])
373
+
374
+ # Follow FlashAttention-2 forward pass.
375
+ if q_scale is not None:
376
+ q = q / q_scale
377
+ if jnp.issubdtype(kv.dtype, jnp.floating):
378
+ dtype_info = jnp.finfo(kv.dtype)
379
+ minval = float(dtype_info.min)
380
+ maxval = float(dtype_info.max)
381
+ q = jnp.clip(q, min=minval, max=maxval)
382
+ q = q.astype(kv.dtype)
383
+
384
+ s = jnp.einsum("nd,md->nm", q, kv, preferred_element_type=jnp.float32)
385
+ s *= sm_scale
386
+ if k_scale is not None:
387
+ s *= k_scale
388
+ if q_scale is not None:
389
+ s *= q_scale
390
+ if soft_cap is not None:
391
+ s = soft_cap * jnp.tanh(s / soft_cap)
392
+
393
+ q_span = (kv_len - q_len + bq_idx * bq_sz +
394
+ lax.broadcasted_iota(jnp.int32, s.shape, 0) //
395
+ num_q_heads_per_kv_head)
396
+ k_span = bkv_idx * bkv_sz + lax.broadcasted_iota(jnp.int32, s.shape, 1)
397
+ mask = k_span <= q_span
398
+
399
+ if sliding_window is not None and strict_sliding_window:
400
+ mask = jnp.logical_and(mask, q_span - sliding_window < k_span)
401
+
402
+ s = jnp.where(mask, s, mask_value)
403
+ s_rowmax = jnp.max(s, axis=1, keepdims=True)
404
+
405
+ if attention_sink_ref is not None:
406
+ sinks = attention_sink_ref[kv_head_idx]
407
+ actual_bq_sz = q.shape[0] // num_q_heads_per_kv_head
408
+ m_prev_init = jnp.concat([sinks] * actual_bq_sz, axis=0)
409
+ m_prev = jnp.where(bkv_idx == bkv_idx_start, m_prev_init,
410
+ head_m_ref[...])
411
+ else:
412
+ m_prev = load_with_init(head_m_ref, -jnp.inf)
413
+
414
+ m_curr = jnp.maximum(m_prev, s_rowmax)
415
+ head_m_ref[...] = m_curr
416
+ p = jnp.exp(s - broadcast_minor(m_curr, s.shape))
417
+
418
+ p_rowsum = jnp.sum(p, axis=1, keepdims=True)
419
+ exp_m_diff = jnp.exp(m_prev - m_curr)
420
+ l_prev = load_with_init(head_l_ref, 1.0)
421
+ l_curr = exp_m_diff * l_prev + p_rowsum
422
+ head_l_ref[...] = l_curr
423
+
424
+ return p, exp_m_diff
425
+
426
+ def flash_attention_step2_pv(
427
+ q_shape_0,
428
+ kv, # [bkv_sz, actual_head_dim_x2]
429
+ p, # from step1
430
+ exp_m_diff, # from step1
431
+ *,
432
+ bkv_idx,
433
+ kv_head_idx,
434
+ ):
435
+ head_acc_ref = acc_ref.at[kv_head_idx, :q_shape_0]
436
+
437
+ def load_with_init(ref, init_val):
438
+ return jnp.where(bkv_idx == bkv_idx_start,
439
+ jnp.full_like(ref, init_val), ref[...])
440
+
441
+ pv = jnp.einsum("nm,md->nd", p, kv, preferred_element_type=jnp.float32)
442
+ if v_scale is not None:
443
+ pv *= v_scale
444
+
445
+ o_prev = load_with_init(head_acc_ref, 0.0)
446
+ o_curr = broadcast_minor(exp_m_diff, o_prev.shape) * o_prev + pv
447
+ head_acc_ref[...] = o_curr
448
+
449
+ def _async_copy(src, dst, sem, wait):
450
+ if debug_mode:
451
+ # Skip DMA if debug mode is enabled.
452
+ return
453
+ cp = pltpu.make_async_copy(src, dst, sem)
454
+ if wait:
455
+ cp.wait()
456
+ else:
457
+ cp.start()
458
+
459
+ def _fetch_bkv(seq_idx,
460
+ bkv_idx,
461
+ bkv_sem_idx,
462
+ *,
463
+ is_full_fetch=False,
464
+ wait=False):
465
+ sem = sems.at[0, bkv_sem_idx]
466
+ vmem_ref = bkv_x2_ref.at[bkv_sem_idx]
467
+
468
+ cache_hbm_shape = kv_cache_hbm_ref.shape
469
+ cache_hbm_ref = kv_cache_hbm_ref.reshape(
470
+ cache_hbm_shape[0] * cache_hbm_shape[1], *cache_hbm_shape[2:])
471
+ kv_len = kv_lens_ref[seq_idx]
472
+ kv_len_start = bkv_idx * bkv_sz
473
+ kv_p_start = bkv_idx * bkv_p
474
+ q_start = cu_q_lens_ref[seq_idx]
475
+ q_end = cu_q_lens_ref[seq_idx + 1]
476
+ q_len = q_end - q_start
477
+
478
+ kv_left = kv_len - kv_len_start
479
+ kv_left_frm_cache = jnp.maximum(kv_left - q_len, 0)
480
+ kv_left_frm_new = kv_left - kv_left_frm_cache
481
+ bkv_p_frm_cache = jnp.minimum(cdiv(kv_left_frm_cache, page_size),
482
+ bkv_p)
483
+ bkv_sz_frm_new = jnp.minimum(
484
+ jnp.maximum(bkv_sz - kv_left_frm_cache, 0), kv_left_frm_new)
485
+ page_indices_offset = seq_idx * pages_per_seq + kv_p_start
486
+
487
+ # Make sure the current bkv buffer is safe to overwrite.
488
+ wait_update_kv_cache(bkv_sem_idx)
489
+
490
+ debug_print(
491
+ "[RPA debug]"
492
+ f" -----------{'wait' if wait else 'start'}_fetch_bkv-----------")
493
+ debug_print("[RPA debug] seq_idx={}", seq_idx)
494
+ debug_print("[RPA debug] bkv_idx={}", bkv_idx)
495
+ debug_print("[RPA debug] bkv_sem_idx={}", bkv_sem_idx)
496
+ debug_print("[RPA debug] kv_len_start={}", kv_len_start)
497
+ debug_print("[RPA debug] kv_p_start={}", kv_p_start)
498
+ debug_print("[RPA debug] kv_left={}", kv_left)
499
+ debug_print("[RPA debug] kv_left_frm_cache={}", kv_left_frm_cache)
500
+ debug_print("[RPA debug] kv_left_frm_new={}", kv_left_frm_new)
501
+ debug_print("[RPA debug] bkv_p_frm_cache={}", bkv_p_frm_cache)
502
+ debug_print("[RPA debug] bkv_sz_frm_new={}", bkv_sz_frm_new)
503
+ debug_print("[RPA debug] page_indices_offset={}", page_indices_offset)
504
+
505
+ if not wait:
506
+ # Fetch effective kv from kv cache.
507
+ def loop_body(i, offset):
508
+ sz = jnp.minimum(page_size, kv_left_frm_cache - i * page_size)
509
+ _async_copy(
510
+ cache_hbm_ref.at[pl.ds(
511
+ page_indices_ref[page_indices_offset + i] * page_size,
512
+ sz)],
513
+ vmem_ref.at[pl.ds(i * page_size, sz)],
514
+ sem,
515
+ wait=False,
516
+ )
517
+ debug_print("[RPA debug] loop_body i={}, sz={}", i, sz)
518
+ return offset + sz
519
+
520
+ offset = lax.fori_loop(
521
+ 0,
522
+ bkv_p_frm_cache,
523
+ loop_body,
524
+ 0, # offset
525
+ unroll=False,
526
+ )
527
+
528
+ # Fetch kv directly from new kv.
529
+ @pl.when(bkv_sz_frm_new > 0)
530
+ def _fetch_bkv_from_new_kv():
531
+ new_kv_len_start = q_end - kv_left_frm_new
532
+ debug_print("[RPA debug] new_kv_len_start={}",
533
+ new_kv_len_start)
534
+ debug_print("[RPA debug] offset_in_bkv={}", offset)
535
+ _async_copy(
536
+ kv_hbm_ref.at[pl.ds(new_kv_len_start, bkv_sz_frm_new)],
537
+ vmem_ref.at[pl.ds(offset, bkv_sz_frm_new)],
538
+ sem,
539
+ wait,
540
+ )
541
+
542
+ # NOTE(chengjiyao): This condition is true for the first two bkv fetches.
543
+ # We need to ensure the bkv_x2_ref VMEM buffer is fully initialized to
544
+ # avoid potential NaN values in regions not overwritten by actual data.
545
+ # This is done by padding the remaining parts of the buffer with data
546
+ # from the KV cache. This special handling is only strictly necessary
547
+ # until both buffers in the double buffer (bkv_x2_ref) have been written
548
+ # to at least once.
549
+ @pl.when(is_full_fetch)
550
+ def _make_sure_bkv_vmem_is_not_nan():
551
+ effective_sz = offset + bkv_sz_frm_new
552
+ remaining_sz = bkv_sz - effective_sz
553
+ _async_copy(
554
+ cache_hbm_ref.at[pl.ds(0, remaining_sz)],
555
+ vmem_ref.at[pl.ds(effective_sz, remaining_sz)],
556
+ sem,
557
+ wait,
558
+ )
559
+
560
+ return kv_len_start + offset, bkv_sz_frm_new
561
+ else:
562
+ offset = jnp.minimum(kv_left_frm_cache, page_size * bkv_p)
563
+ sz = lax.select(is_full_fetch, bkv_sz, offset + bkv_sz_frm_new)
564
+ dst = vmem_ref.at[pl.ds(0, sz)]
565
+ _async_copy(
566
+ src=dst,
567
+ dst=dst,
568
+ sem=sem,
569
+ wait=True,
570
+ )
571
+ return kv_len_start + offset, bkv_sz_frm_new
572
+
573
+ def _update_kv_cache(seq_idx,
574
+ bkv_sem_idx,
575
+ offset,
576
+ update_sz,
577
+ *,
578
+ wait=False):
579
+ sem = sems.at[3, bkv_sem_idx]
580
+ vmem_ref = bkv_x2_ref.at[bkv_sem_idx]
581
+ bkv_id = offset // bkv_sz
582
+ kv_p_start = offset // page_size
583
+ kv_p_end = cdiv(offset + update_sz, page_size)
584
+ ignore = offset % page_size
585
+ p_ignore = kv_p_start - bkv_id * bkv_p
586
+ page_indices_offset = seq_idx * pages_per_seq + kv_p_start
587
+
588
+ cache_hbm_shape = updated_kv_cache_hbm_ref.shape
589
+ cache_hbm_ref = updated_kv_cache_hbm_ref.reshape(
590
+ cache_hbm_shape[0] * cache_hbm_shape[1], *cache_hbm_shape[2:])
591
+
592
+ debug_print(
593
+ "[RPA debug]"
594
+ f" -----------{'wait' if wait else 'start'}_update_kv_cache-----------"
595
+ )
596
+ debug_print("[RPA debug] seq_idx={}", seq_idx)
597
+ debug_print("[RPA debug] bkv_sem_idx={}", bkv_sem_idx)
598
+ debug_print("[RPA debug] offset={}", offset)
599
+ debug_print("[RPA debug] update_sz={}", update_sz)
600
+ debug_print("[RPA debug] bkv_id={}", bkv_id)
601
+ debug_print("[RPA debug] kv_p_start={}", kv_p_start)
602
+ debug_print("[RPA debug] kv_p_end={}", kv_p_end)
603
+ debug_print("[RPA debug] ignore={}", ignore)
604
+ debug_print("[RPA debug] p_ignore={}", p_ignore)
605
+ debug_print("[RPA debug] page_indices_offset={}", page_indices_offset)
606
+
607
+ if not wait:
608
+
609
+ def loop_body(i, states):
610
+ update_sz, ignore = states
611
+ sz = jnp.minimum(page_size - ignore, update_sz)
612
+
613
+ _async_copy(
614
+ vmem_ref.at[pl.ds((p_ignore + i) * page_size + ignore,
615
+ sz)],
616
+ cache_hbm_ref.at[pl.ds(
617
+ page_indices_ref[page_indices_offset + i] * page_size +
618
+ ignore,
619
+ sz,
620
+ )],
621
+ sem,
622
+ wait=False,
623
+ )
624
+ debug_print("[RPA debug] loop_body i={}, sz={}", i, sz)
625
+ return update_sz - sz, 0
626
+
627
+ lax.fori_loop(
628
+ 0,
629
+ kv_p_end - kv_p_start,
630
+ loop_body,
631
+ (update_sz, ignore), # total transfer size
632
+ unroll=False,
633
+ )
634
+ else:
635
+ dst = cache_hbm_ref.at[pl.ds(0, update_sz)]
636
+ _async_copy(
637
+ src=dst,
638
+ dst=dst,
639
+ sem=sem,
640
+ wait=True,
641
+ )
642
+
643
+ def _fetch_bq(seq_idx, bq_idx, bq_sem_idx, *, wait=False):
644
+ sem = sems.at[1, bq_sem_idx]
645
+ vmem_ref = bq_x2_ref.at[bq_sem_idx]
646
+ q_len_start = cu_q_lens_ref[seq_idx] + bq_idx * bq_sz
647
+ q_end = cu_q_lens_ref[seq_idx + 1]
648
+ sz = jnp.minimum(bq_sz, q_end - q_len_start)
649
+
650
+ debug_print(
651
+ "[RPA debug]"
652
+ f" -----------{'wait' if wait else 'start'}_fetch_bq-----------")
653
+ debug_print("[RPA debug] seq_idx={}", seq_idx)
654
+ debug_print("[RPA debug] bq_idx={}", bq_idx)
655
+ debug_print("[RPA debug] bq_sem_idx={}", bq_sem_idx)
656
+ debug_print("[RPA debug] q_len_start={}", q_len_start)
657
+ debug_print("[RPA debug] q_end={}", q_end)
658
+ debug_print("[RPA debug] sz={}", sz)
659
+
660
+ _async_copy(
661
+ q_hbm_ref.at[:, pl.ds(q_len_start, sz)],
662
+ vmem_ref.at[:, pl.ds(0, sz)],
663
+ sem,
664
+ wait,
665
+ )
666
+
667
+ def _send_bo(seq_idx, bo_idx, bo_sem_idx, *, wait=False):
668
+ sem = sems.at[2, bo_sem_idx]
669
+ vmem_ref = bo_x2_ref.at[bo_sem_idx]
670
+ q_len_start = cu_q_lens_ref[seq_idx] + bo_idx * bq_sz
671
+ q_end = cu_q_lens_ref[seq_idx + 1]
672
+ sz = jnp.minimum(bq_sz, q_end - q_len_start)
673
+
674
+ debug_print(
675
+ "[RPA debug]"
676
+ f" -----------{'wait' if wait else 'start'}_send_bo-----------")
677
+ debug_print("[RPA debug] seq_idx={}", seq_idx)
678
+ debug_print("[RPA debug] bo_idx={}", bo_idx)
679
+ debug_print("[RPA debug] bo_sem_idx={}", bo_sem_idx)
680
+ debug_print("[RPA debug] q_len_start={}", q_len_start)
681
+ debug_print("[RPA debug] q_end={}", q_end)
682
+ debug_print("[RPA debug] sz={}", sz)
683
+
684
+ _async_copy(
685
+ vmem_ref.at[:, pl.ds(0, sz)],
686
+ o_hbm_ref.at[:, pl.ds(q_len_start, sz)],
687
+ sem,
688
+ wait,
689
+ )
690
+
691
+ def start_fetch_bkv(seq_idx, bkv_idx, bkv_sem_idx, *, is_full_fetch=False):
692
+ return _fetch_bkv(seq_idx,
693
+ bkv_idx,
694
+ bkv_sem_idx,
695
+ is_full_fetch=is_full_fetch)
696
+
697
+ def wait_fetch_bkv(seq_idx, bkv_idx, bkv_sem_idx, *, is_full_fetch=False):
698
+ return _fetch_bkv(seq_idx,
699
+ bkv_idx,
700
+ bkv_sem_idx,
701
+ is_full_fetch=is_full_fetch,
702
+ wait=True)
703
+
704
+ def start_fetch_bq(seq_idx, bq_idx, bq_sem_idx):
705
+ return _fetch_bq(seq_idx, bq_idx, bq_sem_idx)
706
+
707
+ def wait_fetch_bq(seq_idx, bq_idx, bq_sem_idx):
708
+ return _fetch_bq(seq_idx, bq_idx, bq_sem_idx, wait=True)
709
+
710
+ def start_send_bo(seq_idx, bo_idx, bo_sem_idx):
711
+ bo_ids_ref[bo_sem_idx] = seq_idx
712
+ bo_ids_ref[bo_sem_idx + 2] = bo_idx
713
+ _send_bo(seq_idx, bo_idx, bo_sem_idx)
714
+
715
+ def wait_send_bo(bo_sem_idx):
716
+ old_seq_idx = bo_ids_ref[bo_sem_idx]
717
+ old_bo_idx = bo_ids_ref[bo_sem_idx + 2]
718
+
719
+ @pl.when(jnp.logical_and(0 <= old_seq_idx, old_seq_idx <= seq_idx))
720
+ def _():
721
+ _send_bo(old_seq_idx, old_bo_idx, bo_sem_idx, wait=True)
722
+
723
+ def start_update_kv_cache(seq_idx, bkv_sem_idx, offset, update_sz):
724
+ bkv_update_ids_ref[bkv_sem_idx] = seq_idx
725
+ bkv_update_ids_ref[bkv_sem_idx + 2] = offset
726
+ bkv_update_ids_ref[bkv_sem_idx + 4] = update_sz
727
+ _update_kv_cache(seq_idx, bkv_sem_idx, offset, update_sz)
728
+
729
+ def wait_update_kv_cache(bkv_sem_idx):
730
+ update_sz = bkv_update_ids_ref[bkv_sem_idx + 4]
731
+
732
+ @pl.when(update_sz > 0)
733
+ def _():
734
+ seq_idx = bkv_update_ids_ref[bkv_sem_idx]
735
+ offset = bkv_update_ids_ref[bkv_sem_idx + 2]
736
+ bkv_update_ids_ref[bkv_sem_idx + 4] = 0
737
+ _update_kv_cache(seq_idx,
738
+ bkv_sem_idx,
739
+ offset,
740
+ update_sz,
741
+ wait=True)
742
+
743
+ def load_bq(bq_sem_idx, kv_head_idx, *, actual_bq_sz=bq_sz):
744
+ q_ref = (bq_x2_ref.bitcast(
745
+ jnp.uint32).at[bq_sem_idx, kv_head_idx].reshape(
746
+ bq_sz * num_q_heads_per_kv_head_per_packing,
747
+ actual_head_dim_x2))
748
+ return pltpu.bitcast(
749
+ q_ref[:actual_bq_sz * num_q_heads_per_kv_head_per_packing],
750
+ q_dtype)
751
+
752
+ def strided_load(ref, start, step):
753
+ assert get_dtype_packing(ref.dtype) == 1
754
+ assert len(ref.shape) == 2
755
+ _, l = ref.shape # noqa
756
+ assert l == 128
757
+ vec = ref[start::step]
758
+ return vec
759
+
760
+ def strided_load_bkv(bkv_sem_idx, start, step):
761
+ assert start % kv_packing == 0
762
+ assert step % kv_packing == 0
763
+ start //= kv_packing
764
+ step //= kv_packing
765
+ kv_ref = (bkv_x2_ref.bitcast(jnp.uint32).at[bkv_sem_idx].reshape(
766
+ bkv_sz * step, actual_head_dim_x2))
767
+
768
+ kv = strided_load(kv_ref, start, step)
769
+ bitwidth = 32 // kv_packing
770
+ repack_ty = jnp.dtype(f"uint{bitwidth}")
771
+ lst = []
772
+ for i in range(0, kv_packing):
773
+ cur_kv = pltpu.bitcast((kv >> (i * bitwidth)).astype(repack_ty),
774
+ kv_dtype)
775
+ lst.append(cur_kv)
776
+ return lst
777
+
778
+ def broadcast_minor(src, shape):
779
+ if src.shape == shape:
780
+ return src
781
+ assert src.shape[:-1] == shape[:-1]
782
+ assert src.shape[-1] % 128 == 0
783
+ target_minor = align_to(shape[-1], src.shape[-1])
784
+ # no-op concatenation.
785
+ return jnp.concatenate(
786
+ [src for _ in range(target_minor // src.shape[-1])],
787
+ axis=-1)[..., :shape[-1]]
788
+
789
+ def process(static_q_len=None):
790
+ num_bkv = cdiv(kv_len, bkv_sz)
791
+ if static_q_len is None:
792
+ actual_bq_sz = bq_sz
793
+ num_bq = cdiv(q_len, actual_bq_sz)
794
+ else:
795
+ actual_bq_sz = min(bq_sz, static_q_len)
796
+ num_bq = cdiv(static_q_len, actual_bq_sz)
797
+
798
+ def get_next_bq_ids(seq_idx, bq_idx, bq_sem_idx):
799
+ next_bq_idx = bq_idx + 1
800
+ is_last_bq = next_bq_idx == num_bq
801
+ next_bq_idx = lax.select(is_last_bq, 0, next_bq_idx)
802
+ next_seq_idx = lax.select(is_last_bq, seq_idx + 1, seq_idx)
803
+ next_bq_sem_idx = lax.select(bq_sem_idx == 0, 1, 0)
804
+ return next_seq_idx, next_bq_idx, next_bq_sem_idx
805
+
806
+ def get_next_bkv_ids(seq_idx, bq_idx, bkv_idx, bkv_sem_idx):
807
+ next_bkv_idx = bkv_idx + 1
808
+ is_last_bkv = next_bkv_idx == num_bkv
809
+ next_bq_idx = lax.select(is_last_bkv, bq_idx + 1, bq_idx)
810
+ is_last_bq = next_bq_idx == num_bq
811
+ next_bq_idx = lax.select(is_last_bq, 0, next_bq_idx)
812
+ next_seq_idx = lax.select(is_last_bq, seq_idx + 1, seq_idx)
813
+ next_bkv_sem_idx = lax.select(bkv_sem_idx == 0, 1, 0)
814
+
815
+ if sliding_window is None:
816
+ next_bkv_start_idx = 0
817
+ else:
818
+ next_bkv_start_idx = lax.select(
819
+ is_last_bq,
820
+ next_seq_bkv_idx_start,
821
+ bkv_idx_start,
822
+ )
823
+ next_bkv_idx = lax.select(is_last_bkv, next_bkv_start_idx,
824
+ next_bkv_idx)
825
+
826
+ return next_seq_idx, next_bq_idx, next_bkv_idx, next_bkv_sem_idx
827
+
828
+ def compute_with_bq(bq_idx, _):
829
+ bq_sem_idx = sem_ids_ref[0]
830
+ next_seq_idx, next_bq_idx, next_bq_sem_idx = get_next_bq_ids(
831
+ seq_idx, bq_idx, bq_sem_idx)
832
+
833
+ # Prefetch next bq
834
+ @pl.when(next_seq_idx < num_seqs)
835
+ def prefetch_next_bq():
836
+ sem_ids_ref[0] = next_bq_sem_idx
837
+ start_fetch_bq(next_seq_idx, next_bq_idx, next_bq_sem_idx)
838
+
839
+ def compute_with_bkv(bkv_idx, _):
840
+ # Create bitmask for KV.
841
+ assert bkv_sz % kv_packing == 0
842
+
843
+ # Get next bkv ids.
844
+ bkv_sem_idx = sem_ids_ref[1]
845
+ next_seq_idx, next_bq_idx_for_kv, next_bkv_idx, next_bkv_sem_idx = (
846
+ get_next_bkv_ids(seq_idx, bq_idx, bkv_idx, bkv_sem_idx))
847
+
848
+ # Prefetch next bkv
849
+ @pl.when(next_seq_idx < num_seqs)
850
+ def prefetch_next_bkv():
851
+ sem_ids_ref[1] = next_bkv_sem_idx
852
+ start_fetch_bkv(
853
+ next_seq_idx,
854
+ next_bkv_idx,
855
+ next_bkv_sem_idx,
856
+ is_full_fetch=next_seq_idx + next_bq_idx_for_kv +
857
+ next_bkv_idx < 2,
858
+ )
859
+
860
+ # Wait for cur bq if not ready yet
861
+ @pl.when(bkv_idx == bkv_idx_start)
862
+ def wait_cur_bq():
863
+ wait_fetch_bq(seq_idx, bq_idx, bq_sem_idx)
864
+
865
+ # Wait for cur bkv
866
+ offset, update_sz = wait_fetch_bkv(
867
+ seq_idx,
868
+ bkv_idx,
869
+ bkv_sem_idx,
870
+ is_full_fetch=seq_idx + bq_idx + bkv_idx < 2,
871
+ )
872
+
873
+ # Start updating bkv to kv cache if applicable.
874
+ # Only needed in first bq loop.
875
+ @pl.when(jnp.logical_and(update_sz > 0, bq_idx == 0))
876
+ def update_cur_bkv_to_cache():
877
+ start_update_kv_cache(seq_idx, bkv_sem_idx, offset,
878
+ update_sz)
879
+
880
+ debug_print(
881
+ "[RPA debug] -----------flash attention-----------")
882
+ debug_print("[RPA debug] seq_idx={}", seq_idx)
883
+ debug_print("[RPA debug] bq_idx={}", bq_idx)
884
+ debug_print("[RPA debug] bkv_idx={}", bkv_idx)
885
+ if debug_mode:
886
+ # Skip flash attention if debug mode is enabled.
887
+ return
888
+
889
+ # Flash attention with cur bkv and bq
890
+ prev_bq_shape_0 = None
891
+ prev_kv_head_bkv = None
892
+ prev_kv_head_idx = None
893
+ prev_kv_head_p = None
894
+ prev_kv_head_exp_m_diff = None
895
+ for kv_head_start in range(0, actual_num_kv_heads, kv_packing):
896
+ bkv_lst = strided_load_bkv(
897
+ bkv_sem_idx,
898
+ kv_head_start,
899
+ num_kv_heads,
900
+ )
901
+ assert len(bkv_lst) == kv_packing
902
+ for i in range(kv_packing):
903
+ cur_kv_head_idx = kv_head_start + i
904
+ if cur_kv_head_idx >= actual_num_kv_heads:
905
+ break
906
+ cur_kv_head_bq = load_bq(bq_sem_idx,
907
+ cur_kv_head_idx,
908
+ actual_bq_sz=actual_bq_sz)
909
+ cur_kv_head__bkv = bkv_lst[i]
910
+ # FlashAttention is divided into `flash_attention_step1_qk_softmax`
911
+ # and `flash_attention_step2_pv` to pipeline the computation.
912
+ # `step2_pv` for the previous KV head, which depends on the softmax
913
+ # output, is overlapped with `step1_qk_softmax` for the current KV
914
+ # head, reducing overall wait times.
915
+ cur_kv_head_p, cur_kv_head_exp_m_diff = (
916
+ flash_attention_step1_qk_softmax(
917
+ cur_kv_head_bq,
918
+ cur_kv_head__bkv,
919
+ bq_idx=bq_idx,
920
+ bkv_idx=bkv_idx,
921
+ kv_head_idx=cur_kv_head_idx,
922
+ ))
923
+ if prev_bq_shape_0 is not None:
924
+ flash_attention_step2_pv(
925
+ prev_bq_shape_0,
926
+ prev_kv_head_bkv,
927
+ prev_kv_head_p,
928
+ prev_kv_head_exp_m_diff,
929
+ bkv_idx=bkv_idx,
930
+ kv_head_idx=prev_kv_head_idx,
931
+ )
932
+ prev_bq_shape_0 = cur_kv_head_bq.shape[0]
933
+ prev_kv_head_bkv = cur_kv_head__bkv
934
+ prev_kv_head_p = cur_kv_head_p
935
+ prev_kv_head_exp_m_diff = cur_kv_head_exp_m_diff
936
+ prev_kv_head_idx = cur_kv_head_idx
937
+
938
+ # Execute pv of last attention head.
939
+ assert prev_bq_shape_0 is not None
940
+ flash_attention_step2_pv(
941
+ prev_bq_shape_0,
942
+ prev_kv_head_bkv,
943
+ prev_kv_head_p,
944
+ prev_kv_head_exp_m_diff,
945
+ bkv_idx=bkv_idx,
946
+ kv_head_idx=prev_kv_head_idx,
947
+ )
948
+
949
+ lax.fori_loop(bkv_idx_start,
950
+ num_bkv,
951
+ compute_with_bkv,
952
+ None,
953
+ unroll=False)
954
+
955
+ # Load acc and calculate final output.
956
+ acc = acc_ref[...]
957
+ l = broadcast_minor(l_ref[...], acc.shape) # noqa
958
+ out = (lax.div(acc, l) if q_dtype == jnp.float32 else
959
+ (acc * pl.reciprocal(l, approx=True)).astype(q_dtype))
960
+
961
+ # Wait for previous bo to be fully sent before storing new bo.
962
+ bo_sem_idx = sem_ids_ref[2]
963
+ sem_ids_ref[2] = lax.select(bo_sem_idx == 0, 1, 0)
964
+ wait_send_bo(bo_sem_idx)
965
+
966
+ # Store output from acc to bo.
967
+ bo_x2_ref.at[bo_sem_idx].bitcast(jnp.int32).reshape(
968
+ actual_num_kv_heads,
969
+ bq_sz * num_q_heads_per_kv_head_per_packing,
970
+ actual_head_dim_x2,
971
+ )[...] = pltpu.bitcast(out, jnp.int32)
972
+
973
+ # Send cur bo
974
+ start_send_bo(seq_idx, bq_idx, bo_sem_idx)
975
+
976
+ lax.fori_loop(0, num_bq, compute_with_bq, None, unroll=False)
977
+
978
+ ### ------- Kernel start ------- ###
979
+
980
+ @pl.when(seq_idx == 0)
981
+ def prologue():
982
+ start_fetch_bq(0, 0, 0)
983
+ start_fetch_bkv(0, bkv_idx_start, 0, is_full_fetch=True)
984
+
985
+ @pl.when(seq_idx < decode_end)
986
+ def process_decode():
987
+ process(static_q_len=1)
988
+
989
+ @pl.when(jnp.logical_and(decode_end <= seq_idx, seq_idx < prefill_end))
990
+ def process_prefill():
991
+ process(static_q_len=chunk_prefill_size)
992
+
993
+ @pl.when(jnp.logical_and(prefill_end <= seq_idx, seq_idx < mixed_end))
994
+ def process_mixed():
995
+ process()
996
+
997
+ @pl.when(seq_idx == num_seqs - 1)
998
+ def epilogue():
999
+ for i in range(2):
1000
+ wait_send_bo(i)
1001
+ wait_update_kv_cache(i)
1002
+
1003
+ ### ------- Kernel end ------- ###
1004
+
1005
+
1006
+ def merge_kv(
1007
+ k: jax.
1008
+ Array, # [max_num_tokens, actual_num_kv_heads, actual_head_dim],
1009
+ v: jax.
1010
+ Array, # [max_num_tokens, actual_num_kv_heads, actual_head_dim],
1011
+ ):
1012
+ assert k.shape == v.shape
1013
+ assert k.dtype == v.dtype
1014
+ max_num_tokens, actual_num_kv_heads, actual_head_dim = k.shape
1015
+ kv_packing = get_dtype_packing(k.dtype)
1016
+ num_kv_heads = align_to(actual_num_kv_heads, kv_packing)
1017
+ kv = jnp.pad(
1018
+ jnp.concat([k, v], axis=-1),
1019
+ (
1020
+ (0, 0),
1021
+ (0, num_kv_heads - actual_num_kv_heads),
1022
+ (0, 0),
1023
+ ),
1024
+ constant_values=0,
1025
+ ).reshape(
1026
+ max_num_tokens,
1027
+ num_kv_heads // kv_packing,
1028
+ kv_packing,
1029
+ actual_head_dim * 2,
1030
+ )
1031
+ return kv
1032
+
1033
+
1034
+ def prepare_inputs(
1035
+ q: jax.Array, # [max_num_tokens, actual_num_q_heads, actual_head_dim],
1036
+ k: jax.
1037
+ Array, # [max_num_tokens, actual_num_kv_heads, actual_head_dim],
1038
+ v: jax.
1039
+ Array, # [max_num_tokens, actual_num_kv_heads, actual_head_dim],
1040
+ attention_sink: jax.Array | None = None, # f32[actual_num_q_heads],
1041
+ ):
1042
+ max_num_tokens, actual_num_q_heads, actual_head_dim = q.shape
1043
+ actual_num_kv_heads = k.shape[1]
1044
+ assert actual_num_q_heads % actual_num_kv_heads == 0
1045
+ actual_num_q_heads_per_kv_head = actual_num_q_heads // actual_num_kv_heads
1046
+ q_packing = get_dtype_packing(q.dtype)
1047
+ num_q_heads_per_kv_head = align_to(actual_num_q_heads_per_kv_head,
1048
+ q_packing)
1049
+ head_dim = align_to(actual_head_dim, 128)
1050
+ q = (
1051
+ jnp.pad(
1052
+ q.reshape(
1053
+ max_num_tokens,
1054
+ actual_num_kv_heads,
1055
+ actual_num_q_heads_per_kv_head,
1056
+ actual_head_dim,
1057
+ ),
1058
+ (
1059
+ (0, 0),
1060
+ (0, 0),
1061
+ (0, num_q_heads_per_kv_head - actual_num_q_heads_per_kv_head),
1062
+ (0, head_dim - actual_head_dim),
1063
+ ),
1064
+ constant_values=0,
1065
+ ).reshape(
1066
+ max_num_tokens,
1067
+ actual_num_kv_heads,
1068
+ num_q_heads_per_kv_head // q_packing,
1069
+ q_packing,
1070
+ head_dim,
1071
+ )
1072
+ # TODO(jevinjiang): Explore fusing swapping non-tiling axis to DMA.
1073
+ .swapaxes(0, 1))
1074
+ # TODO(kyuyeunk, chengjiyao): Add kv quantization here.
1075
+ kv = merge_kv(k, v)
1076
+
1077
+ if attention_sink is not None:
1078
+ attention_sink = attention_sink.reshape(
1079
+ (-1, num_q_heads_per_kv_head, 1))
1080
+ attention_sink = jnp.repeat(attention_sink, 128, -1)
1081
+
1082
+ return q, kv, attention_sink
1083
+
1084
+
1085
+ def prepare_outputs(
1086
+ out, # [actual_num_kv_heads, max_num_tokens, num_q_heads_per_kv_head // q_packing, q_packing, actual_head_dim_x2]
1087
+ actual_num_q_heads_per_kv_head: int,
1088
+ actual_head_dim: int,
1089
+ ):
1090
+ (
1091
+ actual_num_kv_heads,
1092
+ max_num_tokens,
1093
+ num_q_heads_per_kv_head_per_q_packing,
1094
+ q_packing,
1095
+ actual_head_dim_x2,
1096
+ ) = out.shape
1097
+ actual_num_q_heads = actual_num_q_heads_per_kv_head * actual_num_kv_heads
1098
+ return (out.swapaxes(0, 1).reshape(
1099
+ max_num_tokens,
1100
+ actual_num_kv_heads,
1101
+ num_q_heads_per_kv_head_per_q_packing * q_packing,
1102
+ actual_head_dim_x2,
1103
+ )[:, :, :actual_num_q_heads_per_kv_head,
1104
+ actual_head_dim:].reshape(max_num_tokens, actual_num_q_heads,
1105
+ actual_head_dim))
1106
+
1107
+
1108
+ # Expect to run this validation during runtime.
1109
+ def dynamic_validate_inputs(
1110
+ queries: jax.
1111
+ Array, # [max_num_tokens, actual_num_q_heads, actual_head_dim]
1112
+ keys: jax.Array, # [max_num_tokens, actual_num_kv_heads, actual_head_dim]
1113
+ values: jax.
1114
+ Array, # [max_num_tokens, actual_num_kv_heads, actual_head_dim]
1115
+ kv_cache: jax.
1116
+ Array, # [total_num_pages, page_size, num_kv_heads // kv_packing, kv_packing, head_dim]
1117
+ kv_lens: jax.Array, # i32[max_num_seqs]
1118
+ page_indices: jax.Array, # i32[max_num_seqs * pages_per_seq]
1119
+ cu_q_lens: jax.Array, # i32[max_num_seqs + 1]
1120
+ distribution: jax.Array, # i32[3]
1121
+ attention_sink: jax.Array | None = None, # f32[actual_num_q_heads]
1122
+ *,
1123
+ sm_scale: float = 1.0,
1124
+ sliding_window: int | None = None,
1125
+ soft_cap: float | None = None,
1126
+ mask_value: float | None = DEFAULT_MASK_VALUE,
1127
+ q_scale: float | None = None,
1128
+ k_scale: float | None = None,
1129
+ v_scale: float | None = None,
1130
+ # Kernel optimization params.
1131
+ chunk_prefill_size: int | None = None,
1132
+ # Kernel tuning params.
1133
+ num_kv_pages_per_block: int | None = None,
1134
+ num_queries_per_block: int | None = None,
1135
+ vmem_limit_bytes: int | None = None,
1136
+ # Debug params.
1137
+ debug_mode: bool = False,
1138
+ ):
1139
+ q, k, v = queries, keys, values
1140
+ static_validate_inputs(
1141
+ q,
1142
+ k,
1143
+ v,
1144
+ kv_cache,
1145
+ kv_lens,
1146
+ page_indices,
1147
+ cu_q_lens,
1148
+ distribution,
1149
+ attention_sink,
1150
+ sm_scale=sm_scale,
1151
+ sliding_window=sliding_window,
1152
+ soft_cap=soft_cap,
1153
+ mask_value=mask_value,
1154
+ q_scale=q_scale,
1155
+ k_scale=k_scale,
1156
+ v_scale=v_scale,
1157
+ chunk_prefill_size=chunk_prefill_size,
1158
+ num_kv_pages_per_block=num_kv_pages_per_block,
1159
+ num_queries_per_block=num_queries_per_block,
1160
+ vmem_limit_bytes=vmem_limit_bytes,
1161
+ debug_mode=debug_mode,
1162
+ )
1163
+ max_num_tokens = q.shape[0]
1164
+ total_num_pages = kv_cache.shape[0]
1165
+ page_size = kv_cache.shape[1]
1166
+ max_num_seqs = kv_lens.shape[0]
1167
+ num_page_indices = page_indices.shape[0]
1168
+ assert num_page_indices % max_num_seqs == 0
1169
+ pages_per_seq = num_page_indices // max_num_seqs
1170
+
1171
+ i, j, k = distribution
1172
+ if not (i <= j <= k):
1173
+ raise ValueError(f"Invalid distribution: {distribution=}")
1174
+
1175
+ if k > max_num_seqs:
1176
+ raise ValueError(f"num_seqs={k} must be <= {max_num_seqs=}")
1177
+
1178
+ if cu_q_lens[k] > max_num_tokens:
1179
+ raise ValueError(
1180
+ f"Total q tokens {cu_q_lens[k]} must be <= {max_num_tokens=}.")
1181
+ for i in range(k):
1182
+ q_len = cu_q_lens[i + 1] - cu_q_lens[i]
1183
+ kv_len = kv_lens[i]
1184
+ if not (0 < q_len <= kv_len):
1185
+ raise ValueError(
1186
+ f"Require 0 < {q_len=} <= {kv_len=} at sequence {i}.")
1187
+ page_cnt = cdiv(kv_len, page_size)
1188
+ if page_cnt > pages_per_seq:
1189
+ raise ValueError(
1190
+ f"Require {page_cnt=} <= {pages_per_seq=} at sequence {i} where"
1191
+ f" {kv_len=} and {page_size=}.")
1192
+ for p in range(page_cnt):
1193
+ page_idx = page_indices[i * pages_per_seq + p]
1194
+ if not (0 <= page_idx < total_num_pages):
1195
+ raise ValueError(
1196
+ f"Require 0 <= {page_idx=} < {total_num_pages=} at sequence"
1197
+ f" {i} where {kv_len=} and {page_size=}.")
1198
+
1199
+
1200
+ # Expect to run this validation during compile time.
1201
+ def static_validate_inputs(
1202
+ queries: jax.
1203
+ Array, # [max_num_tokens, actual_num_q_heads, actual_head_dim]
1204
+ keys: jax.Array, # [max_num_tokens, actual_num_kv_heads, actual_head_dim]
1205
+ values: jax.
1206
+ Array, # [max_num_tokens, actual_num_kv_heads, actual_head_dim]
1207
+ kv_cache: jax.
1208
+ Array, # [total_num_pages, page_size, num_kv_heads // kv_packing, kv_packing, actual_head_dim_x2]
1209
+ kv_lens: jax.Array, # i32[max_num_seqs]
1210
+ page_indices: jax.Array, # i32[max_num_seqs * pages_per_seq]
1211
+ cu_q_lens: jax.Array, # i32[max_num_seqs + 1]
1212
+ distribution: jax.Array, # i32[3]
1213
+ attention_sink: jax.Array | None = None, # f32[actual_num_q_heads]
1214
+ *,
1215
+ sm_scale: float = 1.0,
1216
+ sliding_window: int | None = None,
1217
+ soft_cap: float | None = None,
1218
+ mask_value: float | None = DEFAULT_MASK_VALUE,
1219
+ q_scale: float | None = None,
1220
+ k_scale: float | None = None,
1221
+ v_scale: float | None = None,
1222
+ # Kernel optimization params.
1223
+ chunk_prefill_size: int | None = None,
1224
+ # Kernel tuning params.
1225
+ num_kv_pages_per_block: int | None = None,
1226
+ num_queries_per_block: int | None = None,
1227
+ vmem_limit_bytes: int | None = None,
1228
+ # Debug params.
1229
+ debug_mode: bool = False,
1230
+ ):
1231
+ """Validate inputs to the RPA kernel statically."""
1232
+ q, k, v = queries, keys, values
1233
+ if not (len(q.shape) == len(k.shape) == len(v.shape) == 3):
1234
+ raise ValueError(
1235
+ f"Expected 3D array for {q.shape=}, {k.shape=}, {v.shape=}")
1236
+ if k.shape != v.shape:
1237
+ raise ValueError(f"Expected {k.shape=} to be equal to {v.shape=}")
1238
+ if not (q.shape[0] == k.shape[0] == v.shape[0]):
1239
+ raise ValueError(
1240
+ f"Expected {q.shape[0]=} to be equal to {k.shape[0]=} and {v.shape[0]=}"
1241
+ )
1242
+ if not (q.shape[2] == k.shape[2] == v.shape[2]):
1243
+ raise ValueError(
1244
+ f"Expected {q.shape[2]=} to be equal to {k.shape[2]=} and {v.shape[2]=}"
1245
+ )
1246
+ if attention_sink is not None:
1247
+ if attention_sink.shape[0] != q.shape[1]:
1248
+ raise ValueError(
1249
+ f"Expected {attention_sink.shape[0]=} to be equal to"
1250
+ f" {q.shape[1]=} (num_q_heads).")
1251
+ if attention_sink.dtype != jnp.float32:
1252
+ raise ValueError(
1253
+ f"Expected {attention_sink.dtype=} to be equal to {jnp.float32=}."
1254
+ )
1255
+
1256
+ actual_head_dim = q.shape[2]
1257
+ if actual_head_dim != 64:
1258
+ raise ValueError(f"Expected {actual_head_dim=} to be 64.")
1259
+ actual_num_q_heads = q.shape[1]
1260
+ actual_num_kv_heads = k.shape[1]
1261
+
1262
+ if actual_num_q_heads % actual_num_kv_heads != 0:
1263
+ raise ValueError(f"Expected {actual_num_q_heads=} to be divisible by"
1264
+ f" {actual_num_kv_heads=}.")
1265
+
1266
+ (
1267
+ _,
1268
+ page_size,
1269
+ num_kv_heads_per_kv_packing,
1270
+ kv_packing,
1271
+ actual_head_dim_x2,
1272
+ ) = kv_cache.shape
1273
+
1274
+ if actual_head_dim_x2 != 128:
1275
+ raise ValueError(f"Expected {actual_head_dim_x2=} is equal to 128")
1276
+ # Note: we expect the kv quantization happens outside of the RPA kernel.
1277
+ if not (kv_cache.dtype == k.dtype == v.dtype):
1278
+ raise ValueError(
1279
+ f"Expected {kv_cache.dtype=} to be equal to {k.dtype=} and {v.dtype=}."
1280
+ )
1281
+ # Integer kv quantization is currently not supported.
1282
+ if not jnp.issubdtype(kv_cache.dtype, jnp.floating):
1283
+ raise ValueError(f"Expected {kv_cache.dtype=} to be a floating point.")
1284
+ if kv_packing != get_dtype_packing(kv_cache.dtype):
1285
+ raise ValueError(
1286
+ f"{kv_packing=} does not match with {kv_cache.dtype=}")
1287
+
1288
+ num_kv_heads = num_kv_heads_per_kv_packing * kv_packing
1289
+ if align_to(actual_num_kv_heads, kv_packing) != num_kv_heads:
1290
+ raise ValueError(
1291
+ f"Invalid {num_kv_heads=}, {actual_num_kv_heads=}, {kv_packing=}")
1292
+
1293
+ if not (jnp.int32 == kv_lens.dtype == page_indices.dtype == cu_q_lens.dtype
1294
+ == distribution.dtype):
1295
+ raise ValueError(
1296
+ f"Expected int32 dtype for {kv_lens.dtype=}, {page_indices.dtype=},"
1297
+ f" {cu_q_lens.dtype=}, {distribution.dtype=}")
1298
+
1299
+ if not (len(kv_lens.shape) == len(page_indices.shape) == len(
1300
+ cu_q_lens.shape) == 1):
1301
+ raise ValueError(
1302
+ f"Expected 1D array for {kv_lens.shape=}, {page_indices.shape=},"
1303
+ f" {cu_q_lens.shape=}")
1304
+
1305
+ max_num_seqs = kv_lens.shape[0]
1306
+ num_page_indices = page_indices.shape[0]
1307
+ if num_page_indices % max_num_seqs != 0:
1308
+ raise ValueError(
1309
+ f"Expected {num_page_indices=} to be divisible by {max_num_seqs=}."
1310
+ )
1311
+ if cu_q_lens.shape != (max_num_seqs + 1, ):
1312
+ raise ValueError(
1313
+ f"Expected {cu_q_lens.shape=} to be ({max_num_seqs + 1},).")
1314
+ if distribution.shape != (3, ):
1315
+ raise ValueError(f"Expected {distribution.shape=} to be (3,).")
1316
+
1317
+ if page_size % kv_packing != 0:
1318
+ raise ValueError(f"{page_size=} must be divisible by {kv_packing=}.")
1319
+ if sliding_window is not None and sliding_window <= 0:
1320
+ raise ValueError(f"{sliding_window=} must be positive.")
1321
+ if soft_cap is not None and soft_cap == 0.0:
1322
+ raise ValueError(f"{soft_cap=} must not be 0.0.")
1323
+ if chunk_prefill_size is not None and chunk_prefill_size <= 0:
1324
+ raise ValueError(f"{chunk_prefill_size=} must be positive.")
1325
+ if num_kv_pages_per_block is not None:
1326
+ if num_kv_pages_per_block <= 0:
1327
+ raise ValueError(f"{num_kv_pages_per_block=} must be positive.")
1328
+ if num_queries_per_block is not None:
1329
+ if num_queries_per_block <= 0:
1330
+ raise ValueError(f"{num_queries_per_block=} must be positive.")
1331
+ if vmem_limit_bytes is not None and vmem_limit_bytes <= 0:
1332
+ raise ValueError(f"{vmem_limit_bytes=} must be positive.")
1333
+
1334
+ # No constraints for the following inputs.
1335
+ del sm_scale
1336
+ del mask_value
1337
+ del q_scale
1338
+ del k_scale
1339
+ del v_scale
1340
+ del debug_mode
1341
+
1342
+
1343
+ @functools.partial(
1344
+ jax.jit,
1345
+ static_argnames=(
1346
+ "sm_scale",
1347
+ "sliding_window",
1348
+ "strict_sliding_window",
1349
+ "soft_cap",
1350
+ "mask_value",
1351
+ "q_scale",
1352
+ "k_scale",
1353
+ "v_scale",
1354
+ "chunk_prefill_size",
1355
+ "num_kv_pages_per_block",
1356
+ "num_queries_per_block",
1357
+ "vmem_limit_bytes",
1358
+ "debug_mode",
1359
+ ),
1360
+ donate_argnames=("kv_cache", ),
1361
+ )
1362
+ def ragged_paged_attention_hd64(
1363
+ queries: jax.
1364
+ Array, # [max_num_tokens, actual_num_q_heads, actual_head_dim]
1365
+ keys: jax.Array, # [max_num_tokens, actual_num_kv_heads, actual_head_dim]
1366
+ values: jax.
1367
+ Array, # [max_num_tokens, actual_num_kv_heads, actual_head_dim]
1368
+ kv_cache: jax.
1369
+ Array, # [total_num_pages, page_size, num_kv_heads // kv_packing, kv_packing, actual_head_dim_x2]
1370
+ kv_lens: jax.Array, # i32[max_num_seqs]
1371
+ page_indices: jax.Array, # i32[max_num_seqs * pages_per_seq]
1372
+ cu_q_lens: jax.Array, # i32[max_num_seqs + 1]
1373
+ distribution: jax.Array, # i32[3]
1374
+ attention_sink: jax.Array | None = None, # f32[actual_num_q_heads]
1375
+ *,
1376
+ sm_scale: float = 1.0,
1377
+ sliding_window: int | None = None,
1378
+ strict_sliding_window: bool = True,
1379
+ soft_cap: float | None = None,
1380
+ mask_value: float | None = DEFAULT_MASK_VALUE,
1381
+ q_scale: float | None = None,
1382
+ k_scale: float | None = None,
1383
+ v_scale: float | None = None,
1384
+ # Kernel optimization params.
1385
+ chunk_prefill_size: int | None = None,
1386
+ # Kernel tuning params.
1387
+ num_kv_pages_per_block: int | None = None,
1388
+ num_queries_per_block: int | None = None,
1389
+ vmem_limit_bytes: int | None = None,
1390
+ # Debug params.
1391
+ debug_mode: bool = False,
1392
+ ):
1393
+ """A variant of ragged paged attention for head_dim=64.
1394
+
1395
+ Args:
1396
+ queries: concatenated all sequences' queries.
1397
+ keys: concatenated all sequences' keys (quantized).
1398
+ values: concatenated all sequences' values (quantized).
1399
+ kv_cache: paged KV cache with TPU-friendly shape.
1400
+ kv_lens: padded kv lengths. Only the first num_seqs values are valid.
1401
+ page_indices: flattened page indices look-up table by (seq_id, page_id).
1402
+ cu_q_lens: the cumulative sum of the effective query lengths. Similar to
1403
+ kv_lens, only the first num_seqs+1 values are valid.
1404
+ distribution: (i, j, k) represents that sequences[0:i] are decode-only,
1405
+ sequences[i:j] are chunked-prefill-only, and sequences[j:k] are mixed. The
1406
+ k is also the total number of sequences.
1407
+ attention_sink: optional attention sink for each q head.
1408
+ sm_scale: the softmax scale which will be applied to the Q@K^T.
1409
+ sliding_window: the sliding window size for the attention.
1410
+ strict_sliding_window: compute tokens that are strictly within the window.
1411
+ soft_cap: the logit soft cap for the attention.
1412
+ mask_value: mask value for causal mask.
1413
+ q_scale: the scale for the query.
1414
+ k_scale: the scale for the key cache.
1415
+ v_scale: the scale for the value cache.
1416
+ chunk_prefill_size: the chunk prefill size for the attention.
1417
+ num_kv_pages_per_block: number of kv pages to be processed in one flash
1418
+ attention block in the pallas kernel.
1419
+ num_queries_per_block: number of kv pages to be processed in one flash
1420
+ attention block in the pallas kernel.
1421
+ vmem_limit_bytes: the vmem limit for the pallas kernel.
1422
+ debug_mode: if true, RPA does not issue any DMAs or run flash attention but
1423
+ print debug info. Need to compile with `--xla_tpu_enable_log_recorder`.
1424
+
1425
+ Returns:
1426
+ The output of the attention.
1427
+ """
1428
+ q, k, v = queries, keys, values
1429
+ static_validate_inputs(
1430
+ q,
1431
+ k,
1432
+ v,
1433
+ kv_cache,
1434
+ kv_lens,
1435
+ page_indices,
1436
+ cu_q_lens,
1437
+ distribution,
1438
+ attention_sink,
1439
+ sm_scale=sm_scale,
1440
+ sliding_window=sliding_window,
1441
+ soft_cap=soft_cap,
1442
+ mask_value=mask_value,
1443
+ q_scale=q_scale,
1444
+ k_scale=k_scale,
1445
+ v_scale=v_scale,
1446
+ chunk_prefill_size=chunk_prefill_size,
1447
+ num_kv_pages_per_block=num_kv_pages_per_block,
1448
+ num_queries_per_block=num_queries_per_block,
1449
+ vmem_limit_bytes=vmem_limit_bytes,
1450
+ )
1451
+
1452
+ actual_num_q_heads = q.shape[1]
1453
+ actual_head_dim = q.shape[2]
1454
+ actual_num_kv_heads = k.shape[1]
1455
+
1456
+ actual_num_q_heads_per_kv_head = actual_num_q_heads // actual_num_kv_heads
1457
+ q, kv, attention_sink = prepare_inputs(q, k, v, attention_sink)
1458
+ (
1459
+ _,
1460
+ max_num_tokens,
1461
+ num_q_heads_per_kv_head_per_q_packing,
1462
+ q_packing,
1463
+ head_dim,
1464
+ ) = q.shape
1465
+ page_size = kv_cache.shape[1]
1466
+ max_num_seqs = kv_lens.shape[0]
1467
+ num_page_indices = page_indices.shape[0]
1468
+ assert num_page_indices % max_num_seqs == 0
1469
+ pages_per_seq = num_page_indices // max_num_seqs
1470
+ num_q_heads_per_kv_head = num_q_heads_per_kv_head_per_q_packing * q_packing
1471
+
1472
+ bkv_p = num_kv_pages_per_block
1473
+ bq_sz = num_queries_per_block
1474
+ if bq_sz is None or bkv_p is None:
1475
+ bkv_p, bq_sz = get_tuned_block_sizes(
1476
+ q.dtype,
1477
+ kv_cache.dtype,
1478
+ actual_num_q_heads,
1479
+ actual_num_kv_heads,
1480
+ actual_head_dim,
1481
+ page_size,
1482
+ max_num_tokens,
1483
+ pages_per_seq,
1484
+ )
1485
+ bkv_sz = bkv_p * page_size
1486
+ if vmem_limit_bytes is None:
1487
+ # TODO (jevinjiang/jacobplatin): change this to use
1488
+ # `get_vmem_estimate_bytes` when VREG spilling is fixed.
1489
+ vmem_limit_bytes = DEFAULT_VMEM_LIMIT_BYTES
1490
+ grid = (distribution[2], )
1491
+
1492
+ in_specs = [
1493
+ pl.BlockSpec(memory_space=pltpu.HBM),
1494
+ pl.BlockSpec(memory_space=pltpu.HBM),
1495
+ pl.BlockSpec(memory_space=pltpu.HBM),
1496
+ None if attention_sink is None else pl.BlockSpec(
1497
+ memory_space=pltpu.VMEM),
1498
+ ]
1499
+
1500
+ out_specs = [
1501
+ pl.BlockSpec(memory_space=pltpu.HBM),
1502
+ pl.BlockSpec(memory_space=pltpu.HBM),
1503
+ ]
1504
+
1505
+ bkv_double_buf = pltpu.VMEM(
1506
+ (2, bkv_sz, *kv_cache.shape[2:]),
1507
+ kv_cache.dtype,
1508
+ )
1509
+
1510
+ bq_double_buf = pltpu.VMEM(
1511
+ (2, actual_num_kv_heads, bq_sz, *q.shape[2:]),
1512
+ q.dtype,
1513
+ )
1514
+
1515
+ bo_double_buf = bq_double_buf
1516
+
1517
+ l_scratch = pltpu.VMEM(
1518
+ (actual_num_kv_heads, bq_sz * num_q_heads_per_kv_head, 128),
1519
+ jnp.float32,
1520
+ )
1521
+ m_scratch = l_scratch
1522
+
1523
+ acc_scratch = pltpu.VMEM(
1524
+ (actual_num_kv_heads, bq_sz * num_q_heads_per_kv_head, head_dim),
1525
+ jnp.float32,
1526
+ )
1527
+
1528
+ scratch_shapes = [
1529
+ bkv_double_buf, # Double buffering for kv block.
1530
+ bq_double_buf, # Double buffering for q block.
1531
+ bo_double_buf, # Double buffering for output block.
1532
+ # Semaphores for double buffering of bkv, bq, bo and bkv_update.
1533
+ pltpu.SemaphoreType.DMA((4, 2)),
1534
+ # Intermediate buffers per kv head for flash attention.
1535
+ l_scratch,
1536
+ m_scratch,
1537
+ acc_scratch,
1538
+ ]
1539
+
1540
+ scalar_prefetches = (
1541
+ kv_lens,
1542
+ # TODO(jevinjiang): can we use ragged page_indices to save some smem?
1543
+ page_indices,
1544
+ cu_q_lens,
1545
+ distribution,
1546
+ # (bq_sem_idx, bkv_sem_idx, bo_sem_idx)
1547
+ jnp.zeros((3, ), jnp.int32),
1548
+ # (bo_sem_0_seq_idx, bo_sem_1_seq_idx, bo_sem_0_bo_idx, bo_sem_1_bo_idx)
1549
+ jnp.full((4, ), -1, jnp.int32),
1550
+ # (bkv_sem_0_seq_idx, bkv_sem_1_seq_idx, bkv_sem_0_offset, bkv_sem_1_offset, bkv_sem_0_sz, bkv_sem_1_sz)
1551
+ jnp.full((6, ), -1, jnp.int32),
1552
+ )
1553
+
1554
+ scope_name = f"RPA-HD_64-bq_{bq_sz}-bkvp_{bkv_p}-p_{page_size}"
1555
+ kernel = jax.named_scope(scope_name)(
1556
+ pl.pallas_call(
1557
+ functools.partial(
1558
+ _ragged_paged_attention_kernel,
1559
+ sm_scale=sm_scale,
1560
+ sliding_window=sliding_window,
1561
+ strict_sliding_window=strict_sliding_window,
1562
+ soft_cap=soft_cap,
1563
+ mask_value=mask_value,
1564
+ q_scale=q_scale,
1565
+ k_scale=k_scale,
1566
+ v_scale=v_scale,
1567
+ chunk_prefill_size=chunk_prefill_size,
1568
+ bq_sz=bq_sz,
1569
+ bkv_p=bkv_p,
1570
+ debug_mode=debug_mode,
1571
+ ),
1572
+ grid_spec=pltpu.PrefetchScalarGridSpec(
1573
+ num_scalar_prefetch=len(scalar_prefetches),
1574
+ in_specs=in_specs,
1575
+ out_specs=out_specs,
1576
+ grid=grid,
1577
+ scratch_shapes=scratch_shapes,
1578
+ ),
1579
+ compiler_params=pltpu.CompilerParams(
1580
+ # TODO(jevinjiang): since each sequence depends on the previous
1581
+ # one, we need some extra work to support Megacore mode.
1582
+ dimension_semantics=("arbitrary", ),
1583
+ vmem_limit_bytes=vmem_limit_bytes,
1584
+ ),
1585
+ out_shape=[
1586
+ jax.ShapeDtypeStruct(shape=q.shape, dtype=q.dtype),
1587
+ jax.ShapeDtypeStruct(shape=kv_cache.shape,
1588
+ dtype=kv_cache.dtype),
1589
+ ],
1590
+ input_output_aliases={
1591
+ 7: 0,
1592
+ 9: 1
1593
+ },
1594
+ name=scope_name,
1595
+ ))
1596
+
1597
+ output, updated_kv_cache = kernel(*scalar_prefetches, q, kv, kv_cache,
1598
+ attention_sink)
1599
+ return (
1600
+ prepare_outputs(output, actual_num_q_heads_per_kv_head,
1601
+ actual_head_dim),
1602
+ updated_kv_cache,
1603
+ )