Merged
feat(deepseek_v4): Add new fused LIFA operator for DeepSeek-v4 #744
yasakova_anastasiaAdd on Sep 25
feat(deepseek_v4): Add new fused LIFA operator for DeepSeek-v4 #744
Merged
Merged fromlifilim/pypto-gymfused_LIFAintocann/pypto-gymmaster
Total: 5 files changed+1452-103
| @@ -542,4 +542,123 @@ torch.ops.pypto.hc_pre( | |||
| 542 | ``` | 542 | ``` |
| 543 | python3 tests/ops/deepseek_v4/test_hc_pre.py | 543 | python3 tests/ops/deepseek_v4/test_hc_pre.py |
| 544 | 544 | ||
| 545 | -``` | 545 | +``` |
| 546 | + | ||
| 547 | + | ||
| 548 | +# QuantLightningIndexerFlashAttention | ||
| 549 | + | ||
| 550 | +## Product Support | ||
| 551 | + | ||
| 552 | +- Ascend 950PR:支持 | ||
| 553 | +- Atlas A3 训练系列产品/Atlas A3 推理系列产品:支持 | ||
| 554 | +- Atlas A2 训练系列产品/Atlas A2 推理系列产品:支持 | ||
| 555 | + | ||
| 556 | + | ||
| 557 | +## Function Description | ||
| 558 | + | ||
| 559 | +- **API Function**: The QuantLightningIndexerFlashAttention operator fuses three sequential stages of the DeepSeek V4 Lightning Attention path into a single PyPTO operator, significantly improving inference performance during the decode phase by eliminating intermediate data round-trips and redundant inputs. | ||
| 560 | + | ||
| 561 | +- **Fused Stages**: | ||
| 562 | + | ||
| 563 | + - **Prolog Stage** (from QuantLightningIndexerProlog): Performs linear transformation, inverse rotary position embedding, Hadamard transform, and quantization on the quantized low-rank query `qr`, generating `q` (`int8`), `q_scale` (`fp16`), and `weights` (`fp16`) required by the indexer. | ||
| 564 | + - **Indexer Stage** (from DeepSeek V3.2 LightningIndexer): Computes weighted dot products using the outputs from the Prolog stage and the paged `int8` key cache, then performs TopK selection to output sparse token indices `topk_res` (`int32`). | ||
| 565 | + - **SCFA Stage** (from SparseCompressedFlashAttention): Gathers relevant tokens from the compressed KV cache according to the TopK indices and performs sparse-compressed attention computation, outputting `attention_out` (`bf16`). | ||
| 566 | + | ||
| 567 | +- **Fusion Benefits**: | ||
| 568 | + Compared to separately calling Lightning Indexer Prolog, Lightning Indexer, and Sparse Compressed Flash Attention, the fused operator provides the following advantages: | ||
| 569 | + - `q`, `q_scale`, and `weights` remain as in-kernel scratch memory and are not returned to the eager context, reducing memory access overhead. | ||
| 570 | + - `topk_res` serves as a bridge tensor between the Prolog and SCFA stages, being written and read within the kernel, avoiding data round-trips and boundary reshape operations. | ||
| 571 | + - `act_seq_key` and `block_table` are shared between the Indexer and SCFA stages and only need to be passed once, reducing the number of input parameters and dispatch overhead. | ||
| 572 | + | ||
| 573 | + | ||
| 574 | +## Function Prototype | ||
| 575 | + | ||
| 576 | +``` | ||
| 577 | +torch.ops.pypto.quant_lightning_indexer_flash_attention( | ||
| 578 | + # Prolog stage inputs | ||
| 579 | + qr, | ||
| 580 | + idx_wq_b, | ||
| 581 | + x, | ||
| 582 | + weights_proj, | ||
| 583 | + cos, | ||
| 584 | + sin, | ||
| 585 | + hadamard, | ||
| 586 | + qr_scale, | ||
| 587 | + idx_wq_b_scale, | ||
| 588 | + # Indexer stage inputs | ||
| 589 | + idx_key_cache, | ||
| 590 | + idx_key_scale, | ||
| 591 | + act_seq_key, | ||
| 592 | + block_table, | ||
| 593 | + # SCFA stage inputs | ||
| 594 | + query, | ||
| 595 | + q_act_seqs, | ||
| 596 | + ori_kv, | ||
| 597 | + cmp_kv, | ||
| 598 | + ori_block_table, | ||
| 599 | + atten_sink, | ||
| 600 | + # Parameters | ||
| 601 | + selected_count, | ||
| 602 | + n_q, | ||
| 603 | + softmax_scale, | ||
| 604 | + win_size, | ||
| 605 | + cmp_ratio | ||
| 606 | +) -> (Tensor) | ||
| 607 | +``` | ||
| 608 | +## Parameter Description | ||
| 609 | + | ||
| 610 | +### Prolog Stage Parameters (from QuantLightningIndexerProlog) | ||
| 611 | + | ||
| 612 | +- **`qr`** (`Tensor`): Required parameter. Left input for q matrix computation. Non-contiguous data is not supported. Data format supports ND. Data type supports `int8`. When `layout_query` is TND, shape is `[t, q_lora_rank]`. | ||
| 613 | +- **`idx_wq_b`** (`Tensor`): Required parameter. Right input for q matrix computation. Non-contiguous data is not supported. Data format supports ND. Data type supports `int8`. When `layout_query` is TND, shape is `[q_lora_rank, idx_nq * head_dim]`. | ||
| 614 | +- **`x`** (`Tensor`): Required parameter. Left input for weights matrix computation. Non-contiguous data is not supported. Data format supports ND. Data type supports `bfloat16`. When `layout_query` is TND, shape is `[t, h]`. | ||
| 615 | +- **`weights_proj`** (`Tensor`): Required parameter. Right input for weights matrix computation. Non-contiguous data is not supported. Data format supports ND. Data type supports `bfloat16`. When `layout_query` is TND, shape is `[h, idx_nq]`. | ||
| 616 | +- **`cos`** (`Tensor`): Required parameter. Used for positional encoding computation of q. Non-contiguous data is not supported. Data format supports ND. Data type supports `float32`. When `layout_query` is TND, shape is `[t, rope_dim]`. | ||
| 617 | +- **`sin`** (`Tensor`): Required parameter. Used for positional encoding computation of q. Non-contiguous data is not supported. Data format supports ND. Data type supports `float32`. When `layout_query` is TND, shape is `[t, rope_dim]`. | ||
| 618 | +- **`hadamard`** (`Tensor`): Required parameter. Right input for Hadamard matrix computation of q. Non-contiguous data is not supported. Data format supports ND. Data type supports `bfloat16`. When `layout_query` is TND, shape is `[head_dim, head_dim]`. | ||
| 619 | +- **`qr_scale`** (`Tensor`): Required parameter. Dequantization scale input after qr matrix computation. Non-contiguous data is not supported. Data format supports ND. Data type supports `float32`. When `layout_query` is TND, shape is `[t, 1]`. | ||
| 620 | +- **`idx_wq_b_scale`** (`Tensor`): Required parameter. Multiplication input after qr matrix computation. Non-contiguous data is not supported. Data format supports ND. Data type supports `float32`. When `layout_query` is TND, shape is `[idx_nq * head_dim, 1]`. | ||
| 621 | + | ||
| 622 | +### Indexer Stage Parameters (from DeepSeek V3.2 LightningIndexer) | ||
| 623 | + | ||
| 624 | +- **`idx_key_cache`** (`Tensor`): Required parameter. Paged `int8` key cache in PageAttention format. Non-contiguous data is not supported. Data format supports ND. Data type supports `int8`. Shape is `[block_num, block_size, 1, head_dim]`, where `block_size` is `128`. | ||
| 625 | +- **`idx_key_scale`** (`Tensor`): Required parameter. Quantization scale factor for key cache. Non-contiguous data is not supported. Data format supports ND. Data type supports `float16`. Shape is `[block_num, block_size, 1, 1]`, one scale value per token. | ||
| 626 | +- **`act_seq_key`** (`Tensor`): Required parameter. Actual key sequence length for each batch. Data format supports ND. Data type supports `int32`. Shape is `[b]`. This parameter is shared between the Indexer and SCFA stages (equivalent to SCFA's `seqused_kv`) and only needs to be passed once. | ||
| 627 | +- **`block_table`** (`Tensor`): Required parameter. PageAttention block mapping table for c4a cache storage. Data format supports ND. Data type supports `int32`. Shape is `[b, max_blocks]`. This parameter is shared between the Indexer and SCFA stages (equivalent to SCFA's `cmp_block_table`) and only needs to be passed once. | ||
| 628 | + | ||
| 629 | +### SCFA Stage Parameters (from SparseCompressedFlashAttention) | ||
| 630 | + | ||
| 631 | +- **`query`** (`Tensor`): Required parameter. Corresponds to $Q$ in the formula. Non-contiguous data is not supported. Data format supports ND. Data type supports `bfloat16`. Shape is `[t * n_q, d]`, where `n_q` only supports `64`. | ||
| 632 | +- **`q_act_seqs`** (`Tensor`): Required parameter. Effective when `layout_query` is TND. Represents the prefix sum of valid token counts for query across different batches. Dimension is `[B+1]`. Data type supports `int32`. | ||
| 633 | +- **`ori_kv`** (`Tensor`): Required parameter. Original (window) KV cache, corresponds to part of $\tilde{K}$ and $\tilde{V}$ in the formula. Non-contiguous data is not supported. Data format supports ND. Data type supports `bfloat16`. Shape is `[block_num1 * ori_block_size, KV_N * D]`, where `ori_block_size` is `128` and `KV_N` only supports `1`. | ||
| 634 | +- **`cmp_kv`** (`Tensor`): Required parameter. Compressed KV cache, corresponds to part of $\tilde{K}$ and $\tilde{V}$ in the formula. Non-contiguous data is not supported. Data format supports ND. Data type supports `bfloat16`. Shape is `[block_num2 * cmp_block_size, KV_N * D]`, where `cmp_block_size` is `128`. | ||
| 635 | +- **`ori_block_table`** (`Tensor`): Required parameter. Block mapping table for `ori_kv` storage in PageAttention. Data format supports ND. Data type supports `int32`. Shape is `[b, max_blocks]`. | ||
| 636 | +- **`atten_sink`** (`Tensor`): Required parameter. Attention sink tensor. Data format supports ND. Data type supports `float32`. Shape is `[n_q]`. | ||
| 637 | + | ||
| 638 | +### Common Parameters | ||
| 639 | + | ||
| 640 | +- **`selected_count`** (`int`): Required parameter. Number of TopK sparse selections. Data type supports `int`. Valid range is `(0, 128 * 1024]`. Typical value is `2048`. | ||
| 641 | +- **`n_q`** (`int`): Required parameter. Number of query heads. Data type supports `int`. Only supports `64`. | ||
| 642 | +- **`softmax_scale`** (`float`): Required parameter. Attention softmax scaling factor. Data type supports `float`. | ||
| 643 | +- **`win_size`** (`int`): Required parameter. Sliding window size. Data type supports `int`. Only supports `128`. | ||
| 644 | +- **`cmp_ratio`** (`int`): Required parameter. Compression ratio for `ori_kv`. Data type supports `int`. Only supports `4`. | ||
| 645 | + | ||
| 646 | +## Return Value Description | ||
| 647 | + | ||
| 648 | +- **`attention_out`** (`Tensor`): Sparse-compressed flash attention output. Data format supports ND. Data type supports `bfloat16`. Shape is `[t * n_q, d]`. | ||
| 649 | + | ||
| 650 | + | ||
| 651 | +## Constraints | ||
| 652 | + | ||
| 653 | +- This interface only supports the decode phase in inference scenarios. | ||
| 654 | +- This interface supports aclgraph mode. | ||
| 655 | +- `idx_nq`, `head_dim`, and `block_size` only support default values (`64`, `128`, and `128` respectively). | ||
| 656 | +- `q_lora_rank`, `h`, and `rope_dim` only support default values (`1024`, `4096`, and `64` respectively). | ||
| 657 | +- All input and output data layouts only support TND format. | ||
| 658 | +- All input and output data types only support the listed types; additional types are not supported. | ||
| 659 | + | ||
| 660 | +## Usage | ||
| 661 | + | ||
| 662 | +``` | ||
| 663 | +python3 tests/ops/deepseek_v4/test_quant_lightning_indexer_flash_attention.py | ||
| 664 | +``` | ||
| @@ -17,7 +17,10 @@ Main Functions: | |||
| 17 | - interleaved_rope_3d: attention common RoPE computation | 17 | - interleaved_rope_3d: attention common RoPE computation |
| 18 | - rotate_half: rotate main function of rope | 18 | - rotate_half: rotate main function of rope |
| 19 | """ | 19 | """ |
| 20 | +from collections import namedtuple | ||
| 20 | from typing import Tuple | 21 | from typing import Tuple |
| 22 | +import math | ||
| 23 | + | ||
| 21 | import pypto | 24 | import pypto |
| 22 | from pypto import pypto_impl | 25 | from pypto import pypto_impl |
| 23 | from pypto.operation import op_wrapper | 26 | from pypto.operation import op_wrapper |
| @@ -236,3 +239,103 @@ def quant_tensor(x: pypto.Tensor): | |||
| 236 | temp1 = pypto.full(scale_quant.shape, s8_one_value, pypto.DT_FP32) | 239 | temp1 = pypto.full(scale_quant.shape, s8_one_value, pypto.DT_FP32) |
| 237 | scale_dequant = temp1 / scale_quant | 240 | scale_dequant = temp1 / scale_quant |
| 238 | return out_int8, scale_dequant | 241 | return out_int8, scale_dequant |
| 242 | + | ||
| 243 | + | ||
| 244 | +PrologCtx = namedtuple("PrologCtx", [ | ||
| 245 | + "qr", "idx_wq_b", "x", "weights_proj", "cos", "sin", "hadamard", "qr_scale", | ||
| 246 | + "idx_wq_b_scale", "q", "weights", "q_scale", "unroll_list", | ||
| 247 | +]) | ||
| 248 | + | ||
| 249 | +PrologTileCtx = namedtuple("PrologTileCtx", [ | ||
| 250 | + "qr", "idx_wq_b", "qr_scale", "cos", "sin", "x", "weights_proj", | ||
| 251 | + "hadamard_q", "w_qb_scale", "q", "weights", "q_scale", "x_dtype", | ||
| 252 | + "q_lora_rank", "h", "idx_nq", "head_dim", "rope_dim", | ||
| 253 | +]) | ||
| 254 | + | ||
| 255 | + | ||
| 256 | +def _prolog_query_tile(ctx: PrologTileCtx, t_idx, t_tile): | ||
| 257 | + """Per-tile prolog: query linear, dequant and inverse RoPE.""" | ||
| 258 | + qr_in = pypto.view(ctx.qr, [t_tile, ctx.q_lora_rank], [t_idx, 0]) | ||
| 259 | + qs_in = pypto.view(ctx.qr_scale, [t_tile, 1], [t_idx, 0]) | ||
| 260 | + pypto.set_semantic_label("Query-Linear") | ||
| 261 | + # (t_tile, q_lora_rank) @ (q_lora_rank, idx_nq * head_dim) --> (t_tile, idx_nq * head_dim) | ||
| 262 | + pypto.set_cube_tile_shapes([128, 128], [256, 1024], [256, 256]) | ||
| 263 | + q_s32 = pypto.matmul(qr_in, ctx.idx_wq_b, pypto.DT_INT32) | ||
| 264 | + | ||
| 265 | + pypto.set_semantic_label("Query-Dequant") | ||
| 266 | + pypto.set_vec_tile_shapes(1, ctx.idx_nq * ctx.head_dim) | ||
| 267 | + q_f32 = pypto.cast(q_s32, pypto.DT_FP32) | ||
| 268 | + q_f32 = q_f32 * qs_in | ||
| 269 | + q_f32 = q_f32 * ctx.w_qb_scale | ||
| 270 | + q_cast = pypto.cast(q_f32, ctx.x_dtype) | ||
| 271 | + q_re = pypto.reshape(q_cast, [t_tile, ctx.idx_nq, ctx.head_dim]) | ||
| 272 | + | ||
| 273 | + q_nope = pypto.view(q_re, [t_tile, ctx.idx_nq, ctx.head_dim - ctx.rope_dim], [0, 0, 0]) | ||
| 274 | + q_rope = pypto.view(q_re, [t_tile, ctx.idx_nq, ctx.rope_dim], | ||
| 275 | + [0, 0, ctx.head_dim - ctx.rope_dim]) | ||
| 276 | + rope_cos = pypto.view(ctx.cos, [t_tile, ctx.rope_dim], [t_idx, 0]) | ||
| 277 | + rope_sin = pypto.view(ctx.sin, [t_tile, ctx.rope_dim], [t_idx, 0]) | ||
| 278 | + q_roped = inverse_rope_3d(q_rope, rope_cos, rope_sin) | ||
| 279 | + | ||
| 280 | + pypto.set_vec_tile_shapes(1, ctx.idx_nq, ctx.head_dim) | ||
| 281 | + q_assemble = pypto.tensor([t_tile, ctx.idx_nq, ctx.head_dim], ctx.x_dtype, "q_assemble") | ||
| 282 | + pypto.assemble(pypto.clone(q_nope), [0, 0, 0], q_assemble) | ||
| 283 | + pypto.assemble(q_roped, [0, 0, ctx.head_dim - ctx.rope_dim], q_assemble) | ||
| 284 | + return q_assemble | ||
| 285 | + | ||
| 286 | + | ||
| 287 | +def _prolog_hadamard_weight_tile(ctx: PrologTileCtx, q_assemble, t_idx, t_tile): | ||
| 288 | + """Per-tile prolog: Hadamard transform, quantization and weights projection.""" | ||
| 289 | + pypto.set_semantic_label("Hadamard-Compute") | ||
| 290 | + # (t_tile, idx_nq, head_dim) @ (1, head_dim, head_dim) -> (t_tile, idx_nq, head_dim) | ||
| 291 | + pypto.set_cube_tile_shapes([ctx.idx_nq, ctx.idx_nq], [ctx.head_dim, ctx.head_dim], | ||
| 292 | + [ctx.head_dim, ctx.head_dim]) | ||
| 293 | + q_hadamard = pypto.matmul(q_assemble, ctx.hadamard_q, ctx.x_dtype) | ||
| 294 | + pypto.set_vec_tile_shapes(1, ctx.idx_nq, ctx.head_dim) | ||
| 295 | + q_res, q_scale_res = quant_tensor(q_hadamard) | ||
| 296 | + q_scale_out = pypto.reshape(q_scale_res, [t_tile, ctx.idx_nq]) | ||
| 297 | + pypto.set_vec_tile_shapes(t_tile, ctx.idx_nq) | ||
| 298 | + q_scale_cast = pypto.cast(q_scale_out, pypto.DT_FP16) | ||
| 299 | + pypto.assemble(q_res, [t_idx, 0, 0], ctx.q) | ||
| 300 | + pypto.assemble(q_scale_cast, [t_idx, 0], ctx.q_scale) | ||
| 301 | + | ||
| 302 | + pypto.set_semantic_label("Weight-Compute") | ||
| 303 | + x_in = pypto.view(ctx.x, [t_tile, ctx.h], [t_idx, 0]) | ||
| 304 | + # (t_tile, h) @ (h, idx_nq) --> (t_tile, idx_nq) | ||
| 305 | + pypto.set_cube_tile_shapes([32, 64], [ctx.h // 4, ctx.h], | ||
| 306 | + [ctx.idx_nq // 4, ctx.idx_nq // 4]) | ||
| 307 | + pypto.set_vec_tile_shapes(t_tile, ctx.idx_nq) | ||
| 308 | + weights_fp32 = pypto.cast(pypto.matmul(x_in, ctx.weights_proj, ctx.x_dtype), pypto.DT_FP32) | ||
| 309 | + weights_mul = pypto.mul(weights_fp32, 1.0 / (math.sqrt(ctx.idx_nq) * math.sqrt(ctx.head_dim))) | ||
| 310 | + weights_fp16 = pypto.cast(weights_mul, pypto.DT_FP16) | ||
| 311 | + pypto.assemble(weights_fp16, [t_idx, 0], ctx.weights) | ||
| 312 | + | ||
| 313 | + | ||
| 314 | +def quant_lightning_indexer_prolog_compute(ctx: PrologCtx): | ||
| 315 | + """Shared Lightning-Indexer prolog computation. | ||
| 316 | + | ||
| 317 | + Computes the quantized indexer query (int8 + scale) and indexer weights | ||
| 318 | + from the dequantized latent query ``qr``. Used by both the standalone | ||
| 319 | + prolog kernel and the fused Lightning-Indexer + SCFA kernel. | ||
| 320 | + """ | ||
| 321 | + ctx.idx_wq_b.set_cache_policy(pypto.CachePolicy.NONE_CACHEABLE, True) | ||
| 322 | + ctx.weights_proj.set_cache_policy(pypto.CachePolicy.NONE_CACHEABLE, True) | ||
| 323 | + ctx.hadamard.set_cache_policy(pypto.CachePolicy.NONE_CACHEABLE, True) | ||
| 324 | + idx_nq = ctx.weights_proj.shape[1] | ||
| 325 | + head_dim = ctx.hadamard.shape[0] | ||
| 326 | + tile_ctx = PrologTileCtx( | ||
| 327 | + qr=ctx.qr, idx_wq_b=ctx.idx_wq_b, qr_scale=ctx.qr_scale, | ||
| 328 | + cos=ctx.cos, sin=ctx.sin, x=ctx.x, weights_proj=ctx.weights_proj, | ||
| 329 | + hadamard_q=pypto.reshape(ctx.hadamard, [1, head_dim, head_dim], inplace=True), | ||
| 330 | + w_qb_scale=pypto.reshape(ctx.idx_wq_b_scale, [1, idx_nq * head_dim], inplace=True), | ||
| 331 | + q=ctx.q, weights=ctx.weights, q_scale=ctx.q_scale, x_dtype=ctx.x.dtype, | ||
| 332 | + q_lora_rank=ctx.qr.shape[1], h=ctx.x.shape[1], idx_nq=idx_nq, | ||
| 333 | + head_dim=head_dim, rope_dim=ctx.cos.shape[1], | ||
| 334 | + ) | ||
| 335 | + for t_idx, unroll_length in pypto.loop_unroll( | ||
| 336 | + 0, ctx.qr.shape[0], 1, name="IndexerPrologLoop", idx_name="t_idx", | ||
| 337 | + unroll_list=ctx.unroll_list, | ||
| 338 | + ): | ||
| 339 | + pypto.experimental.set_operation_options(combine_axis=True) | ||
| 340 | + q_assemble = _prolog_query_tile(tile_ctx, t_idx, unroll_length) | ||
| 341 | + _prolog_hadamard_weight_tile(tile_ctx, q_assemble, t_idx, unroll_length) | ||
| @@ -23,7 +23,6 @@ Example: | |||
| 23 | See test_lightning_indexer_prolog_quant.py for usage examples. | 23 | See test_lightning_indexer_prolog_quant.py for usage examples. |
| 24 | """ | 24 | """ |
| 25 | 25 | ||
| 26 | -import math | ||
| 27 | from dataclasses import dataclass | 26 | from dataclasses import dataclass |
| 28 | import torch | 27 | import torch |
| 29 | from torch._subclasses.fake_tensor import FakeTensor | 28 | from torch._subclasses.fake_tensor import FakeTensor |
| @@ -31,7 +30,7 @@ from torch._dynamo import allow_in_graph | |||
| 31 | import pypto | 30 | import pypto |
| 32 | 31 | ||
| 33 | 32 | ||
| 34 | -from deepseek_v4.common import inverse_rope_3d, quant_tensor | 33 | +from deepseek_v4.common import PrologCtx, quant_lightning_indexer_prolog_compute |
| 35 | 34 | ||
| 36 | 35 | ||
| 37 | @dataclass | 36 | @dataclass |
| @@ -204,105 +203,10 @@ def quant_lightning_indexer_prolog_kernel( | |||
| 204 | It configures pass options for memory optimization and calls the core | 203 | It configures pass options for memory optimization and calls the core |
| 205 | computation function. | 204 | computation function. |
| 206 | """ | 205 | """ |
| 207 | - | 206 | + quant_lightning_indexer_prolog_compute(PrologCtx( |
| 208 | - idx_wq_b.set_cache_policy(pypto.CachePolicy.NONE_CACHEABLE, True) | 207 | + qr, idx_wq_b, x, weights_proj, cos, sin, hadamard, qr_scale, idx_wq_b_scale, |
| 209 | - weights_proj.set_cache_policy(pypto.CachePolicy.NONE_CACHEABLE, True) | 208 | + q, weights, q_scale, tile_config.unroll_list, |
| 210 | - hadamard.set_cache_policy(pypto.CachePolicy.NONE_CACHEABLE, True) | 209 | + )) |
| 211 | - x_dtype = x.dtype | ||
| 212 | - # dynamic axis | ||
| 213 | - t = qr.shape[0] | ||
| 214 | - # static axes | ||
| 215 | - q_lora_rank = qr.shape[1] | ||
| 216 | - h = x.shape[1] | ||
| 217 | - idx_nq = weights_proj.shape[1] | ||
| 218 | - head_dim = hadamard.shape[0] | ||
| 219 | - rope_dim = cos.shape[1] | ||
| 220 | - | ||
| 221 | - # Reshape inplace will not generate data move | ||
| 222 | - w_qb_scale = pypto.reshape(idx_wq_b_scale, [1, idx_nq * head_dim], inplace=True) | ||
| 223 | - hadamard_q = pypto.reshape(hadamard, [1, head_dim, head_dim], inplace=True) | ||
| 224 | - | ||
| 225 | - unroll_list = tile_config.unroll_list | ||
| 226 | - for t_idx, unrollLength in pypto.loop_unroll( | ||
| 227 | - 0, | ||
| 228 | - t, | ||
| 229 | - 1, | ||
| 230 | - name="IndexerPrologLoop", | ||
| 231 | - idx_name="t_idx", | ||
| 232 | - unroll_list=unroll_list, | ||
| 233 | - ): | ||
| 234 | - # use for perf optimization | ||
| 235 | - pypto.experimental.set_operation_options(combine_axis=True) | ||
| 236 | - t_tile = unrollLength | ||
| 237 | - qr_in = pypto.view(qr, [t_tile, q_lora_rank], [t_idx, 0]) | ||
| 238 | - qs_in = pypto.view(qr_scale, [t_tile, 1], [t_idx, 0]) | ||
| 239 | - pypto.set_semantic_label("Query-Linear") | ||
| 240 | - # (t_tile, q_lora_rank) @ (q_lora_rank, idx_nq * head_dim) --> (t_tile, idx_nq * head_dim) | ||
| 241 | - pypto.set_cube_tile_shapes( | ||
| 242 | - [128, 128], [256, 1024], [256, 256] | ||
| 243 | - ) | ||
| 244 | - q_s32 = pypto.matmul(qr_in, idx_wq_b, pypto.DT_INT32) | ||
| 245 | - | ||
| 246 | - pypto.set_semantic_label("Query-Dequant") | ||
| 247 | - pypto.set_vec_tile_shapes(1, idx_nq * head_dim) | ||
| 248 | - q_f32 = pypto.cast(q_s32, pypto.DT_FP32) | ||
| 249 | - # (t_tile, idx_nq * head_dim), fp32, last dim brc | ||
| 250 | - q_f32 = q_f32 * qs_in | ||
| 251 | - # (t_tile, idx_nq * head_dim), fp32, first dim brc | ||
| 252 | - q_f32 = q_f32 * w_qb_scale | ||
| 253 | - q_cast = pypto.cast(q_f32, x_dtype) | ||
| 254 | - q_re = pypto.reshape(q_cast, [t_tile, idx_nq, head_dim]) | ||
| 255 | - | ||
| 256 | - # UB view | ||
| 257 | - q_nope = pypto.view(q_re, [t_tile, idx_nq, head_dim - rope_dim], [0, 0, 0]) | ||
| 258 | - q_rope = pypto.view( | ||
| 259 | - q_re, [t_tile, idx_nq, rope_dim], [0, 0, head_dim - rope_dim] | ||
| 260 | - ) | ||
| 261 | - | ||
| 262 | - rope_cos = pypto.view(cos, [t_tile, rope_dim], [t_idx, 0]) | ||
| 263 | - rope_sin = pypto.view(sin, [t_tile, rope_dim], [t_idx, 0]) | ||
| 264 | - | ||
| 265 | - q_roped = inverse_rope_3d(q_rope, rope_cos, rope_sin) | ||
| 266 | - | ||
| 267 | - pypto.set_vec_tile_shapes(1, idx_nq, head_dim) | ||
| 268 | - q_assemble = pypto.tensor([t_tile, idx_nq, head_dim], x_dtype, "q_assemble") | ||
| 269 | - pypto.assemble(pypto.clone(q_nope), [0, 0, 0], q_assemble) | ||
| 270 | - pypto.assemble(q_roped, [0, 0, head_dim - rope_dim], q_assemble) | ||
| 271 | - | ||
| 272 | - pypto.set_semantic_label("Hadamard-Compute") | ||
| 273 | - # (t_tile, idx_nq, head_dim) @ (1, head_dim, head_dim) -> (t_tile, idx_nq, head_dim) | ||
| 274 | - pypto.set_cube_tile_shapes( | ||
| 275 | - [idx_nq, idx_nq], [head_dim, head_dim], [head_dim, head_dim] | ||
| 276 | - ) | ||
| 277 | - q_hadamard = pypto.matmul( | ||
| 278 | - q_assemble, hadamard_q, x_dtype | ||
| 279 | - ) # (t_tile, idx_nq, head_dim) | ||
| 280 | - pypto.set_vec_tile_shapes(1, idx_nq, head_dim) | ||
| 281 | - q_res, q_scale_res = quant_tensor(q_hadamard) | ||
| 282 | - q_scale_out = pypto.reshape(q_scale_res, [t_tile, idx_nq]) | ||
| 283 | - pypto.set_vec_tile_shapes(t_tile, idx_nq) | ||
| 284 | - q_scale_cast = pypto.cast(q_scale_out, pypto.DT_FP16) | ||
| 285 | - | ||
| 286 | - pypto.assemble(q_res, [t_idx, 0, 0], q) | ||
| 287 | - pypto.assemble(q_scale_cast, [t_idx, 0], q_scale) | ||
| 288 | - | ||
| 289 | - pypto.set_semantic_label("Weight-Compute") | ||
| 290 | - x_in = pypto.view(x, [t_tile, h], [t_idx, 0]) | ||
| 291 | - # (t_tile, h) @ (h, idx_nq) --> (t_tile, idx_nq) | ||
| 292 | - pypto.set_cube_tile_shapes( | ||
| 293 | - [32, 64], | ||
| 294 | - [h // 4, h], | ||
| 295 | - [idx_nq // 4, idx_nq // 4], | ||
| 296 | - ) | ||
| 297 | - pypto.set_vec_tile_shapes(t_tile, idx_nq) | ||
| 298 | - weights_fp32 = pypto.cast( | ||
| 299 | - pypto.matmul(x_in, weights_proj, x_dtype), pypto.DT_FP32 | ||
| 300 | - ) | ||
| 301 | - weights_mul = pypto.mul( | ||
| 302 | - weights_fp32, 1.0 / (math.sqrt(idx_nq) * math.sqrt(head_dim)) | ||
| 303 | - ) | ||
| 304 | - weights_fp16 = pypto.cast(weights_mul, pypto.DT_FP16) | ||
| 305 | - pypto.assemble(weights_fp16, [t_idx, 0], weights) | ||
| 306 | 210 | ||
| 307 | 211 | ||
| 308 | pyptolib = torch.library.Library("pypto", "FRAGMENT") | 212 | pyptolib = torch.library.Library("pypto", "FRAGMENT") |
| @@ -350,4 +254,4 @@ except Exception as e: | |||
| 350 | if "could not parse dispatch key: NPU" in str(e): | 254 | if "could not parse dispatch key: NPU" in str(e): |
| 351 | logging.warning("Skip: torchair not installed, skip NPU registration for operator 'IP'") | 255 | logging.warning("Skip: torchair not installed, skip NPU registration for operator 'IP'") |
| 352 | else: | 256 | else: |
| 353 | - logging.warning(f"Skip: Unexpected error: {e}") | 257 | + logging.warning(f"Skip: Unexpected error: {e}") |
| @@ -0,0 +1,477 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | +""" """ | ||
| 12 | +from collections import namedtuple | ||
| 13 | +import logging | ||
| 14 | +import math | ||
| 15 | +import os | ||
| 16 | +import sys | ||
| 17 | + | ||
| 18 | +import pypto | ||
| 19 | +import pytest | ||
| 20 | +import torch | ||
| 21 | +import torch_npu | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +_p = os.path.dirname(__file__) | ||
| 25 | +while not os.path.isdir(os.path.join(_p, 'src')): | ||
| 26 | + _p = os.path.dirname(_p) | ||
| 27 | +sys.path.insert(0, _p) | ||
| 28 | +sys.path.insert(0, os.path.join(_p, 'ops', 'pypto_tensor')) | ||
| 29 | + | ||
| 30 | +from common_utils import gen_uniform_data | ||
| 31 | +from deepseek_v4.quant_lightning_indexer_flash_attention_impl import ( | ||
| 32 | + FusedLifaInputs, | ||
| 33 | + quant_lightning_indexer_flash_attention_graph, | ||
| 34 | +) | ||
| 35 | +from common_utils import compare | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +def rotate_half(x): | ||
| 39 | + """Rotates half the hidden dims of the input.""" | ||
| 40 | + x1 = x[..., : x.shape[-1] // 2] | ||
| 41 | + x2 = x[..., x.shape[-1] // 2:] | ||
| 42 | + return torch.cat((-x2, x1), dim=-1) | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +def apply_rotary_pos_emb(q, cos, sin): | ||
| 46 | + """ | ||
| 47 | + q: (t, n_q, rope_dim), bf16 | ||
| 48 | + cos: (t, rope_dim), bf16 | ||
| 49 | + sin: (t, rope_dim), bf16 | ||
| 50 | + """ | ||
| 51 | + input_dtype = q.dtype | ||
| 52 | + q_new = q.to(torch.float32) | ||
| 53 | + cos = cos.to(torch.float32) | ||
| 54 | + sin = sin.to(torch.float32) | ||
| 55 | + | ||
| 56 | + cos = torch.unsqueeze(cos, dim=1) # [t, 1, rope_dim] | ||
| 57 | + sin = torch.unsqueeze(sin, dim=1) # [t, 1, rope_dim] | ||
| 58 | + | ||
| 59 | + t, n, d = q_new.shape | ||
| 60 | + q_re = q_new.reshape(t, n, d // 2, 2) | ||
| 61 | + q_rotary = rotate_half(q_re).reshape(t, n, d) | ||
| 62 | + | ||
| 63 | + q_embed = (q_new * cos) + (q_rotary * -sin) | ||
| 64 | + | ||
| 65 | + if input_dtype != torch.float32: | ||
| 66 | + q_embed = q_embed.to(input_dtype) | ||
| 67 | + | ||
| 68 | + return q_embed | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def quant_golden(x: torch.Tensor): | ||
| 72 | + x_dtype = x.dtype | ||
| 73 | + x_fp32 = x.to(torch.float32) | ||
| 74 | + max_value = torch.amax(torch.abs(x_fp32), dim=-1, keepdim=True) | ||
| 75 | + scale_quant = 127.0 / max_value | ||
| 76 | + y_fp32 = x_fp32 * scale_quant | ||
| 77 | + y_fp32 = y_fp32.view(x.shape) | ||
| 78 | + y_int32 = torch.round(y_fp32).to(torch.int32) # rint mode | ||
| 79 | + y_int8 = torch.trunc(y_int32.to(x_dtype)).to(torch.int8) | ||
| 80 | + scale_dequant = 1.0 / scale_quant # fp32 | ||
| 81 | + return y_int8, scale_dequant | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def compute_quant_lightning_indexer_prolog(inputs, params): | ||
| 85 | + qr = inputs[0] | ||
| 86 | + idx_wq_b = inputs[1] | ||
| 87 | + x = inputs[2] | ||
| 88 | + weights_proj = inputs[3] | ||
| 89 | + cos = inputs[4] | ||
| 90 | + sin = inputs[5] | ||
| 91 | + hadamard = inputs[6] | ||
| 92 | + qr_scale = inputs[7] | ||
| 93 | + idx_wq_b_scale = inputs[8] | ||
| 94 | + | ||
| 95 | + t = params.get("t") | ||
| 96 | + idx_nq = params.get("idx_nq") | ||
| 97 | + head_dim = params.get("head_dim") | ||
| 98 | + rope_dim = params.get("rope_dim") | ||
| 99 | + calc_dtype = torch.bfloat16 | ||
| 100 | + | ||
| 101 | + q_fp32 = torch.matmul(qr.to(torch.int32), idx_wq_b.to(torch.int32)).to(torch.float32) # (t, idx_nq * head_dim) | ||
| 102 | + q_fp32 = q_fp32 * qr_scale | ||
| 103 | + q_fp32 = q_fp32 * idx_wq_b_scale.reshape(1, idx_nq * head_dim) | ||
| 104 | + q_re = q_fp32.to(calc_dtype).reshape(t, idx_nq, head_dim) | ||
| 105 | + q_nope, q_rope = torch.split(q_re, [head_dim - rope_dim, rope_dim], dim=-1) | ||
| 106 | + q_roped = apply_rotary_pos_emb(q_rope, cos, sin) | ||
| 107 | + q = torch.cat([q_nope, q_roped], dim=-1) | ||
| 108 | + | ||
| 109 | + # matmul use float32 for arm: bfloat16 differs from x86, upcast for correctness | ||
| 110 | + # (t, idx_nq, head_dim) @ (1, head_dim, head_dim) -> (t, idx_nq, head_dim) | ||
| 111 | + q_hadamard = torch.matmul(q.to(torch.float32), hadamard.reshape(1, head_dim, head_dim).to(torch.float32)).to( | ||
| 112 | + calc_dtype | ||
| 113 | + ) | ||
| 114 | + # dtype fp16, q_res (t, idx_nq, head_dim), q_scale (t, idx_nq, 1) | ||
| 115 | + q_int8, q_scale = quant_golden(q_hadamard) | ||
| 116 | + q_scale = q_scale.to(torch.float16).reshape(t, idx_nq) | ||
| 117 | + | ||
| 118 | + # matmul use float32 for arm: bfloat16 differs from x86, upcast for correctness | ||
| 119 | + weights = torch.matmul(x.to(torch.float32), weights_proj.to(torch.float32)).to(calc_dtype).to(torch.float32) | ||
| 120 | + weights = weights * (idx_nq**-0.5) * (head_dim**-0.5) | ||
| 121 | + weights = weights.to(torch.float16) | ||
| 122 | + | ||
| 123 | + return q_int8, weights, q_scale | ||
| 124 | + | ||
| 125 | + | ||
| 126 | +def compute_quant_indexer_topk(inputs, params): | ||
| 127 | + """Return Top-K indices, shape (t, selected_count), int32.""" | ||
| 128 | + q_int8, q_scale, weights, idx_key_cache, idx_key_scale, act_seq_key, block_table = inputs | ||
| 129 | + t = params.get("t") | ||
| 130 | + head_dim = params.get("head_dim") | ||
| 131 | + selected_count = params.get("selected_count") | ||
| 132 | + block_size = params.get("block_size") | ||
| 133 | + b = act_seq_key.shape[0] | ||
| 134 | + s1 = t // b | ||
| 135 | + key_2d = idx_key_cache.reshape(idx_key_cache.shape[0] * block_size, head_dim) | ||
| 136 | + k_scale_2d = idx_key_scale.reshape(idx_key_cache.shape[0], block_size) | ||
| 137 | + topk_res = torch.full((t, selected_count), -1, dtype=torch.int32) | ||
| 138 | + for b_idx in range(b): | ||
| 139 | + cur_seq = act_seq_key[b_idx].item() | ||
| 140 | + for s1_idx in range(s1): | ||
| 141 | + eff_seq = cur_seq - (s1 - s1_idx - 1) | ||
| 142 | + if eff_seq <= 0: | ||
| 143 | + continue | ||
| 144 | + t_idx = b_idx * s1 + s1_idx | ||
| 145 | + scores = torch.zeros(cur_seq, dtype=torch.float32) | ||
| 146 | + w_scale = (q_scale[t_idx, :].to(torch.float16) * weights[t_idx, :].to(torch.float16)).to(torch.float32) | ||
| 147 | + for block_idx in range((eff_seq + block_size - 1) // block_size): | ||
| 148 | + remain = min(block_size, eff_seq - block_idx * block_size) | ||
| 149 | + cbi = block_table[b_idx, block_idx].item() | ||
| 150 | + acc = torch.matmul(q_int8[t_idx, :, :].to(torch.int32), | ||
| 151 | + key_2d[cbi * block_size:cbi * block_size + remain, :].to(torch.int32).t()) | ||
| 152 | + qk = torch.relu(acc.to(torch.float32) / 2048.0).to(torch.float16) | ||
| 153 | + w_qk = torch.matmul(w_scale.unsqueeze(0).to(torch.float32), qk.to(torch.float32)).squeeze(0) | ||
| 154 | + k_s = k_scale_2d[cbi, :remain].to(torch.float32) | ||
| 155 | + scores[block_idx * block_size:block_idx * block_size + remain] = w_qk * k_s | ||
| 156 | + k_num = min(selected_count, eff_seq) | ||
| 157 | + _, cur_index = torch.topk(scores[:eff_seq], k=k_num, largest=True) | ||
| 158 | + topk_res[t_idx, :k_num] = cur_index.to(torch.int32) | ||
| 159 | + return topk_res | ||
| 160 | + | ||
| 161 | + | ||
| 162 | +def _compute_attention_s2_tile(input_data, params, s2_tile, ctx): | ||
| 163 | + """Per (b, s1, s2-tile) golden attention: gather sparse-compress KV via the | ||
| 164 | + topk indices, build ``kj`` (window + gathered), then run QK / softmax+sink / | ||
| 165 | + PV. Returns the partial attention output for this s2-tile.""" | ||
| 166 | + (q, compress_kv, origin_kv, topk_indices, block_table, _, _, | ||
| 167 | + origin_block_table, _, atten_sink) = input_data | ||
| 168 | + block_size, scalar, topk, d_v, win_size = params | ||
| 169 | + b_idx, t_idx, cur_seq, s2_idx, start_block, end_block, start_offset, origin_cur_win_size = ctx | ||
| 170 | + _, n1, d = q.shape | ||
| 171 | + input_dtype = q.dtype | ||
| 172 | + kv_dtype = compress_kv.dtype | ||
| 173 | + atten_sink_2d = atten_sink.unsqueeze(-1) | ||
| 174 | + s2_tile_cur = min(s2_tile, cur_seq - s2_idx * s2_tile) | ||
| 175 | + s2_start = s2_tile * s2_idx | ||
| 176 | + topk_indices_tmp = topk_indices[t_idx, s2_start:s2_start + s2_tile_cur] | ||
| 177 | + slc_compress_kv = torch.zeros([s2_tile_cur, d_v], dtype=kv_dtype) | ||
| 178 | + for cur_s2_idx in range(s2_tile_cur): | ||
| 179 | + topk_index = topk_indices_tmp[cur_s2_idx] | ||
| 180 | + slc_block_idx = block_table[b_idx, topk_index // block_size] | ||
| 181 | + slc_compress_kv[cur_s2_idx, :] = compress_kv[slc_block_idx * block_size + topk_index % block_size, :] | ||
| 182 | + kv_list = [] | ||
| 183 | + for block_idx in range(start_block, end_block + 1): | ||
| 184 | + pid = origin_block_table[b_idx, block_idx] | ||
| 185 | + kv_list.append(origin_kv[pid * block_size: (pid + 1) * block_size, :]) | ||
| 186 | + win_kv_cache = torch.cat(kv_list, axis=0)[start_offset: start_offset + origin_cur_win_size, :] | ||
| 187 | + kj = torch.zeros([origin_cur_win_size + s2_tile_cur, d], dtype=kv_dtype) | ||
| 188 | + kj[:origin_cur_win_size, :] = win_kv_cache | ||
| 189 | + kj[origin_cur_win_size:, :] = slc_compress_kv | ||
| 190 | + qi = q[t_idx, :, :].reshape(n1, d) | ||
| 191 | + sij = torch.matmul(qi.to(torch.float32), kj.t().to(torch.float32)) | ||
| 192 | + sij_scale = sij * scalar | ||
| 193 | + tilda_mij = sij_scale.amax(dim=-1, keepdims=True) | ||
| 194 | + tilda_pij = torch.exp(sij_scale - tilda_mij) | ||
| 195 | + tilda_lij = tilda_pij.sum(dim=-1, keepdims=True) + torch.exp(atten_sink_2d - tilda_mij) | ||
| 196 | + tmp_softmax = (tilda_pij / tilda_lij).to(input_dtype) | ||
| 197 | + return torch.matmul(tmp_softmax.to(torch.float32), kj.to(torch.float32)) | ||
| 198 | + | ||
| 199 | + | ||
| 200 | +def compute_attention_no_flash(input_data, params, s2_tile): | ||
| 201 | + (q, compress_kv, origin_kv, topk_indices, block_table, actual_seq_q, actual_seq, | ||
| 202 | + origin_block_table, origin_actual_seq, atten_sink) = input_data | ||
| 203 | + block_size, scalar, topk, d_v, win_size = params | ||
| 204 | + | ||
| 205 | + t, n1, d = q.shape | ||
| 206 | + t = actual_seq_q[-1] | ||
| 207 | + b = len(actual_seq) | ||
| 208 | + | ||
| 209 | + if topk_indices.ndim > 2: | ||
| 210 | + topk_indices = topk_indices.reshape(t, topk) | ||
| 211 | + | ||
| 212 | + atten_out_shape = [t, n1, d_v] | ||
| 213 | + input_dtype = q.dtype | ||
| 214 | + kv_dtype = compress_kv.dtype | ||
| 215 | + | ||
| 216 | + attention_output = torch.zeros(atten_out_shape, dtype=input_dtype) | ||
| 217 | + atten_sink_2d = atten_sink.unsqueeze(-1) | ||
| 218 | + | ||
| 219 | + for b_idx in range(b): | ||
| 220 | + cur_k_seq = actual_seq[b_idx] | ||
| 221 | + origin_cur_k_seq = origin_actual_seq[b_idx] | ||
| 222 | + s1 = actual_seq_q[b_idx + 1] - actual_seq_q[b_idx] | ||
| 223 | + | ||
| 224 | + for s1_idx in range(s1): | ||
| 225 | + t_idx = actual_seq_q[b_idx] + s1_idx | ||
| 226 | + cur_len = max(origin_cur_k_seq - s1 + 1 + s1_idx, 0) | ||
| 227 | + origin_cur_win_size = min(cur_len, win_size) | ||
| 228 | + valid_start_pos = cur_len - origin_cur_win_size | ||
| 229 | + valid_end_pos = cur_len - 1 | ||
| 230 | + start_block = valid_start_pos // block_size | ||
| 231 | + start_offset = valid_start_pos % block_size | ||
| 232 | + end_block = valid_end_pos // block_size | ||
| 233 | + | ||
| 234 | + cur_seq = min(max(cur_k_seq - s1 + 1 + s1_idx, 0), topk) | ||
| 235 | + | ||
| 236 | + bn_per_batch = math.ceil(cur_seq / s2_tile) | ||
| 237 | + for s2_idx in range(bn_per_batch): | ||
| 238 | + ctx = (b_idx, t_idx, cur_seq, s2_idx, start_block, end_block, | ||
| 239 | + start_offset, origin_cur_win_size) | ||
| 240 | + atten_out_part = _compute_attention_s2_tile(input_data, params, s2_tile, ctx) | ||
| 241 | + attention_output[t_idx, :, :] = atten_out_part.to(input_dtype) | ||
| 242 | + | ||
| 243 | + return attention_output | ||
| 244 | + | ||
| 245 | + | ||
| 246 | +def gen_block_table(act_seq, block_size): | ||
| 247 | + block_num = 0 | ||
| 248 | + block_num_each = [] | ||
| 249 | + b = act_seq.shape[0] | ||
| 250 | + max_kv = max(act_seq) | ||
| 251 | + for cur_s in act_seq: | ||
| 252 | + cur_block_num = math.ceil(cur_s / block_size) | ||
| 253 | + block_num_each.append(cur_block_num) | ||
| 254 | + block_num += cur_block_num | ||
| 255 | + block_table_shape = [b, math.ceil(max_kv / block_size)] | ||
| 256 | + block_idx_list = torch.arange(0, block_num, 1) | ||
| 257 | + block_idx_list = block_idx_list[torch.randperm(block_idx_list.size(0))].to(torch.int32) | ||
| 258 | + | ||
| 259 | + block_table = -torch.ones(block_table_shape, dtype=torch.int32) | ||
| 260 | + | ||
| 261 | + block_table_bidx = 0 | ||
| 262 | + block_idx = 0 | ||
| 263 | + for cur_block in block_num_each: | ||
| 264 | + for j in range(cur_block): | ||
| 265 | + block_table[block_table_bidx, j] = block_idx_list[block_idx] | ||
| 266 | + block_idx += 1 | ||
| 267 | + block_table_bidx += 1 | ||
| 268 | + | ||
| 269 | + return block_num, block_table | ||
| 270 | + | ||
| 271 | + | ||
| 272 | +PrologGolden = namedtuple( | ||
| 273 | + "PrologGolden", | ||
| 274 | + ["qr", "idx_wq_b", "x", "weights_proj", "cos", "sin", "hadamard", "qr_scale", | ||
| 275 | + "idx_wq_b_scale", "q_int8", "weights", "q_scale"], | ||
| 276 | +) | ||
| 277 | +IndexerGolden = namedtuple( | ||
| 278 | + "IndexerGolden", | ||
| 279 | + ["act_seq_key", "block_table", "idx_key_cache", "idx_key_scale", "block_num", | ||
| 280 | + "topk_indices"], | ||
| 281 | +) | ||
| 282 | +AttentionGolden = namedtuple( | ||
| 283 | + "AttentionGolden", | ||
| 284 | + ["query", "cmp_kv", "ori_kv", "ori_block_table", "atten_sink", "q_act_seqs", | ||
| 285 | + "softmax_scale", "golden"], | ||
| 286 | +) | ||
| 287 | + | ||
| 288 | + | ||
| 289 | +# Full golden: stage1 -> stage2 -> stage3 | ||
| 290 | +def _gen_prolog_golden(params): | ||
| 291 | + """Stage 1 golden: generate prolog inputs and compute q_int8/weights/q_scale.""" | ||
| 292 | + t = params["t"] | ||
| 293 | + idx_nq = params["idx_nq"] | ||
| 294 | + head_dim = params["head_dim"] | ||
| 295 | + rope_dim = params["rope_dim"] | ||
| 296 | + q_lora_rank = params["q_lora_rank"] | ||
| 297 | + h = params["h"] | ||
| 298 | + qr_ori = gen_uniform_data([t, q_lora_rank], -127, 127, torch.int8) | ||
| 299 | + idx_wq_b_ori = gen_uniform_data([q_lora_rank, idx_nq * head_dim], -127, 127, torch.int8) | ||
| 300 | + x = gen_uniform_data([t, h], -1, 1, torch.bfloat16) | ||
| 301 | + weights_proj = gen_uniform_data([h, idx_nq], -0.1, 0.1, torch.bfloat16) | ||
| 302 | + cos = gen_uniform_data([t, rope_dim], -1, 1, torch.float32) | ||
| 303 | + sin = gen_uniform_data([t, rope_dim], -1, 1, torch.float32) | ||
| 304 | + hadamard = gen_uniform_data([head_dim, head_dim], -1, 1, torch.bfloat16) | ||
| 305 | + qr, qr_scale = quant_golden(qr_ori) | ||
| 306 | + idx_wq_b, idx_wq_b_scale = quant_golden(idx_wq_b_ori.t()) | ||
| 307 | + idx_wq_b = idx_wq_b.t() | ||
| 308 | + prolog_inputs = [qr, idx_wq_b, x, weights_proj, cos, sin, hadamard, qr_scale, idx_wq_b_scale] | ||
| 309 | + q_int8, weights, q_scale = compute_quant_lightning_indexer_prolog(prolog_inputs, params) | ||
| 310 | + return PrologGolden(qr, idx_wq_b, x, weights_proj, cos, sin, hadamard, qr_scale, | ||
| 311 | + idx_wq_b_scale, q_int8, weights, q_scale) | ||
| 312 | + | ||
| 313 | + | ||
| 314 | +def _gen_indexer_golden(params, q_int8, q_scale, weights): | ||
| 315 | + """Stage 2 golden: generate indexer inputs and compute topk_indices.""" | ||
| 316 | + b = params["b"] | ||
| 317 | + cur_seq = params["cur_seq"] | ||
| 318 | + block_size = params["block_size"] | ||
| 319 | + head_dim = params["head_dim"] | ||
| 320 | + act_seq_key = torch.tensor([cur_seq] * b, dtype=torch.int32) | ||
| 321 | + block_num, block_table = gen_block_table(act_seq_key, block_size) | ||
| 322 | + idx_key_cache = gen_uniform_data([block_num, block_size, 1, head_dim], -127, 127, torch.int8) | ||
| 323 | + idx_key_scale = gen_uniform_data([block_num, block_size, 1, 1], 0.1, 1.0, torch.float16) | ||
| 324 | + topk_inputs = (q_int8, q_scale, weights, idx_key_cache, idx_key_scale, | ||
| 325 | + act_seq_key, block_table) | ||
| 326 | + topk_indices = compute_quant_indexer_topk(topk_inputs, params) | ||
| 327 | + return IndexerGolden(act_seq_key, block_table, idx_key_cache, idx_key_scale, | ||
| 328 | + block_num, topk_indices) | ||
| 329 | + | ||
| 330 | + | ||
| 331 | +def _gen_attention_golden(params, stage2): | ||
| 332 | + """Stage 3 golden: generate attention inputs, run no-flash golden attention.""" | ||
| 333 | + act_seq_key, block_table, _, _, block_num, topk_indices = stage2 | ||
| 334 | + t = params["t"] | ||
| 335 | + n_q = params["n_q"] | ||
| 336 | + d = params["d"] | ||
| 337 | + block_size = params["block_size"] | ||
| 338 | + win_size = params["win_size"] | ||
| 339 | + cmp_ratio = params["cmp_ratio"] | ||
| 340 | + cur_seq = params["cur_seq"] | ||
| 341 | + b = params["b"] | ||
| 342 | + s1 = params["s1"] | ||
| 343 | + selected_count = params["selected_count"] | ||
| 344 | + query_3d = gen_uniform_data([t, n_q, d], -1, 1, torch.bfloat16) | ||
| 345 | + query = query_3d.reshape(t * n_q, d) | ||
| 346 | + cmp_kv = gen_uniform_data([block_num * block_size, d], -1, 1, torch.bfloat16) | ||
| 347 | + ori_kv = gen_uniform_data([block_num * block_size, d], -1, 1, torch.bfloat16) | ||
| 348 | + _, ori_block_table = gen_block_table(act_seq_key, block_size) | ||
| 349 | + atten_sink = gen_uniform_data([n_q], -1, 1, torch.float32) | ||
| 350 | + q_act_seqs = torch.tensor([i * s1 for i in range(b + 1)], dtype=torch.int32) | ||
| 351 | + softmax_scale = d ** -0.5 | ||
| 352 | + scfa_params = [block_size, softmax_scale, selected_count, d, win_size] | ||
| 353 | + origin_actual_seq = [cur_seq] * b | ||
| 354 | + actual_seq = [cur_seq // cmp_ratio] * b | ||
| 355 | + input_data = [query_3d, cmp_kv, ori_kv, topk_indices, block_table, q_act_seqs, | ||
| 356 | + actual_seq, ori_block_table, origin_actual_seq, atten_sink] | ||
| 357 | + s2_tile = 512 | ||
| 358 | + assert selected_count <= s2_tile, ( | ||
| 359 | + f"selected_count ({selected_count}) must be <= s2_tile ({s2_tile}); " | ||
| 360 | + f"the golden attention assigns only the last s2-tile's result") | ||
| 361 | + atten_out = compute_attention_no_flash(input_data, scfa_params, s2_tile) | ||
| 362 | + golden = atten_out.reshape(t * n_q, d) | ||
| 363 | + return AttentionGolden(query, cmp_kv, ori_kv, ori_block_table, atten_sink, | ||
| 364 | + q_act_seqs, softmax_scale, golden) | ||
| 365 | + | ||
| 366 | + | ||
| 367 | +def gen_fused_golden(params): | ||
| 368 | + torch.manual_seed(42) | ||
| 369 | + stage1 = _gen_prolog_golden(params) | ||
| 370 | + (qr, idx_wq_b, x, weights_proj, cos, sin, hadamard, qr_scale, idx_wq_b_scale, | ||
| 371 | + q_int8, weights, q_scale) = stage1 | ||
| 372 | + stage2 = _gen_indexer_golden(params, q_int8, q_scale, weights) | ||
| 373 | + attn = _gen_attention_golden(params, stage2) | ||
| 374 | + op_inputs = dict( | ||
| 375 | + qr=qr, idx_wq_b=idx_wq_b, x=x, weights_proj=weights_proj, cos=cos, sin=sin, | ||
| 376 | + hadamard=hadamard, qr_scale=qr_scale, idx_wq_b_scale=idx_wq_b_scale, | ||
| 377 | + idx_key_cache=stage2.idx_key_cache, idx_key_scale=stage2.idx_key_scale, | ||
| 378 | + act_seq_key=stage2.act_seq_key, block_table=stage2.block_table, | ||
| 379 | + query=attn.query, q_act_seqs=attn.q_act_seqs, ori_kv=attn.ori_kv, | ||
| 380 | + cmp_kv=attn.cmp_kv, ori_block_table=attn.ori_block_table, | ||
| 381 | + atten_sink=attn.atten_sink, | ||
| 382 | + selected_count=params["selected_count"], n_q=params["n_q"], | ||
| 383 | + softmax_scale=attn.softmax_scale, win_size=params["win_size"], cmp_ratio=params["cmp_ratio"], | ||
| 384 | + ) | ||
| 385 | + return op_inputs, attn.golden | ||
| 386 | + | ||
| 387 | + | ||
| 388 | +def do_test_fused(case_name, is_acl_graph=False): | ||
| 389 | + case_config = get_case_config(case_name) | ||
| 390 | + if not case_config: | ||
| 391 | + logging.error("Can't get config for Case(%s)", case_name) | ||
| 392 | + return False | ||
| 393 | + params = case_config | ||
| 394 | + logging.info(f"================ case_config: {case_config}") | ||
| 395 | + | ||
| 396 | + device_id = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 397 | + torch.npu.set_device(device_id) | ||
| 398 | + torch_npu.npu.config.allow_internal_format = True | ||
| 399 | + | ||
| 400 | + op_inputs, golden = gen_fused_golden(params) | ||
| 401 | + kwargs = dict(op_inputs) | ||
| 402 | + kwargs["idx_wq_b"] = torch_npu.npu_format_cast(op_inputs["idx_wq_b"].npu(), torch_npu.Format.FRACTAL_NZ) | ||
| 403 | + kwargs["weights_proj"] = torch_npu.npu_format_cast(op_inputs["weights_proj"].npu(), torch_npu.Format.FRACTAL_NZ) | ||
| 404 | + for k, v in list(kwargs.items()): | ||
| 405 | + if k not in ("selected_count", "n_q", "softmax_scale", "win_size", "cmp_ratio"): | ||
| 406 | + kwargs[k] = v.npu() | ||
| 407 | + inputs = FusedLifaInputs(**kwargs) | ||
| 408 | + | ||
| 409 | + if is_acl_graph: | ||
| 410 | + import torchair as tng | ||
| 411 | + from torchair.configs.compiler_config import CompilerConfig | ||
| 412 | + compiler_config = CompilerConfig() | ||
| 413 | + compiler_config.mode = "reduce-overhead" | ||
| 414 | + model = torch.compile( | ||
| 415 | + type("M", (torch.nn.Module,), | ||
| 416 | + {"forward": lambda self, inputs: quant_lightning_indexer_flash_attention_graph(inputs)})(), | ||
| 417 | + dynamic=False, fullgraph=True, | ||
| 418 | + backend=tng.get_npu_backend(compiler_config=compiler_config)) | ||
| 419 | + attention_out = model(inputs) | ||
| 420 | + else: | ||
| 421 | + attention_out = quant_lightning_indexer_flash_attention_graph(inputs) | ||
| 422 | + | ||
| 423 | + torch_npu.npu.synchronize() | ||
| 424 | + compare(attention_out.cpu(), golden.to(torch.bfloat16), "attention_out", | ||
| 425 | + atol=params.get("atol", 0.0001), rtol=params.get("rtol", 0.0078125), | ||
| 426 | + max_error_ratio=0.005) | ||
| 427 | + return True | ||
| 428 | + | ||
| 429 | + | ||
| 430 | +def get_case_config(case_name: str): | ||
| 431 | + base = dict( | ||
| 432 | + idx_nq=64, head_dim=128, rope_dim=64, q_lora_rank=1024, h=4096, | ||
| 433 | + block_size=128, win_size=128, cmp_ratio=4, n_q=64, d=512, | ||
| 434 | + ) | ||
| 435 | + configs = { | ||
| 436 | + "fused_b64_s2_seq8k_topk512_d": dict(base, b=64, s1=2, t=128, cur_seq=8192, | ||
| 437 | + selected_count=512, atol=0.005, rtol=0.0078125), | ||
| 438 | + "fused_b1_s1_seq130_topk64_d": dict(base, b=1, s1=1, t=1, cur_seq=130, | ||
| 439 | + selected_count=64, atol=0.0001, rtol=0.0078125), | ||
| 440 | + "fused_b1_s1_seq130_topk256_d": dict(base, b=1, s1=1, t=1, cur_seq=130, | ||
| 441 | + selected_count=256, atol=0.0001, rtol=0.0078125), | ||
| 442 | + } | ||
| 443 | + return configs.get(case_name) | ||
| 444 | + | ||
| 445 | + | ||
| 446 | +@pytest.mark.skip(reason="large test case") | ||
| 447 | +@pytest.mark.soc("950", "910") | ||
| 448 | +def test_fused_b64_s2_seq8k_topk512_acl_graph(): | ||
| 449 | + """fused decode acl_graph case.""" | ||
| 450 | + do_test_fused("fused_b64_s2_seq8k_topk512_d", is_acl_graph=True) | ||
| 451 | + | ||
| 452 | + | ||
| 453 | +@pytest.mark.skip(reason="large test case") | ||
| 454 | +@pytest.mark.soc("950", "910") | ||
| 455 | +def test_fused_b64_s2_seq8k_topk512_d(): | ||
| 456 | + """fused decode case.""" | ||
| 457 | + do_test_fused("fused_b64_s2_seq8k_topk512_d") | ||
| 458 | + | ||
| 459 | + | ||
| 460 | +@pytest.mark.soc("950", "910") | ||
| 461 | +def test_fused_b1_s1_seq130_topk64_d(): | ||
| 462 | + """fused pure decode case.""" | ||
| 463 | + do_test_fused("fused_b1_s1_seq130_topk64_d") | ||
| 464 | + | ||
| 465 | + | ||
| 466 | +@pytest.mark.soc("950", "910") | ||
| 467 | +def test_fused_b1_s1_seq130_topk256_d(): | ||
| 468 | + """fused decode case, TOPK_LT_SC branch.""" | ||
| 469 | + do_test_fused("fused_b1_s1_seq130_topk256_d") | ||
| 470 | + | ||
| 471 | + | ||
| 472 | +if __name__ == "__main__": | ||
| 473 | + logging.basicConfig( | ||
| 474 | + format="%(asctime)s - %(filename)s:%(lineno)d - %(levelname)s: %(message)s", | ||
| 475 | + level=logging.INFO, | ||
| 476 | + ) | ||
| 477 | + test_fused_b1_s1_seq130_topk64_d() | ||