Merged
refactor(models): Remove models directory and dependent tests. #5724
chaizhengtongAdd on Aug 27
refactor(models): Remove models directory and dependent tests. #5724
Merged
Merged fromchai-hw/pypto_chaidelete_modelsintocann/pyptomaster
Total: 89 files changed+22-34819
| @@ -33,13 +33,6 @@ PyPTO(发音:pai p-t-o)是一款面向AI加速器的高性能编程框架 | |||
| 33 | 33 | ||
| 34 | PyPTO提供了丰富的示例代码,涵盖从基础操作到复杂模型实现的多个层级。一些最佳实践样例参考: | 34 | PyPTO提供了丰富的示例代码,涵盖从基础操作到复杂模型实现的多个层级。一些最佳实践样例参考: |
| 35 | 35 | ||
| 36 | -### 大模型实现样例 | ||
| 37 | - | ||
| 38 | -- [DeepSeekV3.2 SFA](https://gitcode.com/cann/pypto/blob/master/models/deepseek_v32_exp/deepseekv32_sparse_flash_attention_quant.py) -稀疏Flash Attention量化实现 | ||
| 39 | -- [DeepSeekV3.2 MLA-PROLOG](https://gitcode.com/cann/pypto/blob/master/models/deepseek_v32_exp/deepseekv32_mla_indexer_prolog_quant.py) -MLA Indexer Prolog量化实现 | ||
| 40 | -- [GLM V4.5 Attention](https://gitcode.com/cann/pypto/blob/master/models/glm_v4_5/glm_attention.py) -GLM注意力机制实现 | ||
| 41 | -- [GLM V4.5 ExpertsSelector](https://gitcode.com/cann/pypto/blob/master/models/glm_v4_5/glm_select_experts.py) -GLM专家选择器实现 | ||
| 42 | - | ||
| 43 | ### 学习路径 | 36 | ### 学习路径 |
| 44 | 37 | ||
| 45 | 在 [examples](https://gitcode.com/cann/pypto/blob/master/examples)目录下,我们规划了多个层级的样例: | 38 | 在 [examples](https://gitcode.com/cann/pypto/blob/master/examples)目录下,我们规划了多个层级的样例: |
| @@ -89,8 +82,6 @@ PyPTO提供了丰富的示例代码,涵盖从基础操作到复杂模型实现 | |||
| 89 | │ ├── 02_intermediate/ # 中级示例 | 82 | │ ├── 02_intermediate/ # 中级示例 |
| 90 | │ └── 03_advanced/ # 高级示例 | 83 | │ └── 03_advanced/ # 高级示例 |
| 91 | │ | 84 | │ |
| 92 | -├── models/ # 模型实现示例 | ||
| 93 | -│ | ||
| 94 | ├── python/ # Python源码 | 85 | ├── python/ # Python源码 |
| 95 | │ ├── pypto/ # Python包源码根目录 | 86 | │ ├── pypto/ # Python包源码根目录 |
| 96 | │ ├── src/ # pybind11源码根目录 | 87 | │ ├── src/ # pybind11源码根目录 |
| @@ -33,13 +33,6 @@ This repository has integrated a code repository agent. Click the [ - Sparse Flash Attention quantized implementation | ||
| 39 | -- [DeepSeekV3.2 MLA-PROLOG](https://gitcode.com/cann/pypto/blob/master/models/deepseek_v32_exp/deepseekv32_mla_indexer_prolog_quant.py) - MLA Indexer Prolog quantized implementation | ||
| 40 | -- [GLM V4.5 Attention](https://gitcode.com/cann/pypto/blob/master/models/glm_v4_5/glm_attention.py) - GLM attention mechanism implementation | ||
| 41 | -- [GLM V4.5 ExpertsSelector](https://gitcode.com/cann/pypto/blob/master/models/glm_v4_5/glm_select_experts.py) - GLM expert selector implementation | ||
| 42 | - | ||
| 43 | ### Learning Path | 36 | ### Learning Path |
| 44 | 37 | ||
| 45 | In the [examples](https://gitcode.com/cann/pypto/blob/master/examples) directory, the following multi-level samples are available: | 38 | In the [examples](https://gitcode.com/cann/pypto/blob/master/examples) directory, the following multi-level samples are available: |
| @@ -90,8 +83,6 @@ Key directories are as follows: | |||
| 90 | │ ├── 02_intermediate/ # Intermediate samples | 83 | │ ├── 02_intermediate/ # Intermediate samples |
| 91 | │ └── 03_advanced/ # Advanced samples | 84 | │ └── 03_advanced/ # Advanced samples |
| 92 | │ | 85 | │ |
| 93 | -├── models/ # Model implementation samples | ||
| 94 | -│ | ||
| 95 | ├── python/ # Python source code | 86 | ├── python/ # Python source code |
| 96 | │ ├── pypto/ # Python package source root | 87 | │ ├── pypto/ # Python package source root |
| 97 | │ ├── src/ # pybind11 source root | 88 | │ ├── src/ # pybind11 source root |
| @@ -4,7 +4,7 @@ | |||
| 4 | 4 | ||
| 5 | ffn\_shared\_expert\_quant算子对应GLM4.5网络中MoE共享专家的计算逻辑,包含symmetric\_quantization\_per\_token、matmul、dequant\_dynamic和swiglu,用于进行单个共享专家的量化前向传播计算,通过在不同任务或数据流之间复用同一组权重参数,以学习通用的特征表示,同时减少模型的参数总量。 | 5 | ffn\_shared\_expert\_quant算子对应GLM4.5网络中MoE共享专家的计算逻辑,包含symmetric\_quantization\_per\_token、matmul、dequant\_dynamic和swiglu,用于进行单个共享专家的量化前向传播计算,通过在不同任务或数据流之间复用同一组权重参数,以学习通用的特征表示,同时减少模型的参数总量。 |
| 6 | 6 | ||
| 7 | -下面通过该算子介绍功能调试的大致步骤,完整样例请参考:[glm_ffn_shared_expert_quant](../../../../models/glm_v4_5/glm_ffn_shared_expert_quant.py)。 | 7 | +下面通过该算子介绍功能调试的大致步骤。 |
| 8 | 8 | ||
| 9 | ## 问题定位 | 9 | ## 问题定位 |
| 10 | 10 | ||
| @@ -207,7 +207,7 @@ msprof --instr-profiling=on [--output=<数据存放路径>] python xxx.py | |||
| 207 | 207 | ||
| 208 | ## 开箱性能调优 | 208 | ## 开箱性能调优 |
| 209 | 209 | ||
| 210 | -算子初始性能与loop的写法、TileShape的设置最为密切。本章将介绍如何使用相关接口,在算子初始编写过程中直接得到较好的开箱性能。请参考PyPTO仓库的models文件夹内已开发算子的实现,进行新算子的开发。 | 210 | +算子初始性能与loop的写法、TileShape的设置最为密切。本章将介绍如何使用相关接口,在算子初始编写过程中直接得到较好的开箱性能。 |
| 211 | 211 | ||
| 212 | ### 正确选择loop写法 | 212 | ### 正确选择loop写法 |
| 213 | 213 | ||
| @@ -362,7 +362,7 @@ pypto.set_vec_tile_shapes(64, 512) | |||
| 362 | ) | 362 | ) |
| 363 | ``` | 363 | ``` |
| 364 | 364 | ||
| 365 | -以[glm_attention.py](../../../../models/glm_v4_5/glm_attention.py)算子为例,对比下该值的影响: | 365 | +以glm_attention.py算子为例,对比下该值的影响: |
| 366 | 366 | ||
| 367 | - 当该值过小(如配置为1)时,每个任务都需要同步,调度开销大,性能差。算子kernel耗时为1230us,端到端耗时(调度耗时+执行耗时)为1590us,对应泳道图如下: | 367 | - 当该值过小(如配置为1)时,每个任务都需要同步,调度开销大,性能差。算子kernel耗时为1230us,端到端耗时(调度耗时+执行耗时)为1590us,对应泳道图如下: |
| 368 | 368 | ||
| @@ -430,7 +430,7 @@ PyPTO框架在深度方向上已经实现了自动合图的功能,在极致性 | |||
| 430 | 430 | ||
| 431 | 融合的目标通常来自于Operation间的依赖关系,例如上下游的两个Operation间传输的数据量较大时,应当将其合并以减少搬运耗时;或者多个Operation进行tile切分后变成多个并行的连通分支时,应当将这些Operation进行合并。融合的目标也可以来自于特定类型算子的固有经验,例如IFA算子切batch轴、s2轴和g轴后,V1和V2一般应各作为一个子图任务。 | 431 | 融合的目标通常来自于Operation间的依赖关系,例如上下游的两个Operation间传输的数据量较大时,应当将其合并以减少搬运耗时;或者多个Operation进行tile切分后变成多个并行的连通分支时,应当将这些Operation进行合并。融合的目标也可以来自于特定类型算子的固有经验,例如IFA算子切batch轴、s2轴和g轴后,V1和V2一般应各作为一个子图任务。 |
| 432 | 432 | ||
| 433 | -当前主要考虑在连续的Vector计算过程中使用该能力,暂不支持将Matmul Operation与Vector Operation进行合图。使用时需要结合泳道图信息进行分析和调整。具体使用方式可以参考案例:[glm_attention.py](../../../../models/glm_v4_5/glm_attention.py)。 | 433 | +当前主要考虑在连续的Vector计算过程中使用该能力,暂不支持将Matmul Operation与Vector Operation进行合图。使用时需要结合泳道图信息进行分析和调整。 |
| 434 | 434 | ||
| 435 | #### 广度方向合图 | 435 | #### 广度方向合图 |
| 436 | 436 | ||
| @@ -464,13 +464,13 @@ CubeNBuffer针对的是不能使能L1Reuse的场景,此类场景较少,主 | |||
| 464 | 1. Cube子图间没有重复L1搬运。如BatchMatmul的左右矩阵Shape分别为(128,64,64)和(128,64,64)时,pass切出128个左右矩阵Shape分别为(64,64)和(64,64)的同构Cube子图后,它们之间没有重复L1搬运。还有FA算子的MM2,不同S2 block的MM2子图之间没有重复L1搬运。 | 464 | 1. Cube子图间没有重复L1搬运。如BatchMatmul的左右矩阵Shape分别为(128,64,64)和(128,64,64)时,pass切出128个左右矩阵Shape分别为(64,64)和(64,64)的同构Cube子图后,它们之间没有重复L1搬运。还有FA算子的MM2,不同S2 block的MM2子图之间没有重复L1搬运。 |
| 465 | 2. K轴很长。当没有进行切K时,L1Reuse要求左矩阵的一整行或右矩阵的一整列数据块驻留在L1中。而L1缓存容量有限。因此当K轴较长、且没有切K时,无法使用L1Reuse。 | 465 | 2. K轴很长。当没有进行切K时,L1Reuse要求左矩阵的一整行或右矩阵的一整列数据块驻留在L1中。而L1缓存容量有限。因此当K轴较长、且没有切K时,无法使用L1Reuse。 |
| 466 | 466 | ||
| 467 | -此时可以配置`cube_nbuffer_setting`参数,并结合泳道图实测数据进一步调优。可参考案例[mla_prolog_quant_impl.py](../../../../models/deepseek_v32_exp/mla_prolog_quant_impl.py) | 467 | +此时可以配置`cube_nbuffer_setting`参数,并结合泳道图实测数据进一步调优。 |
| 468 | 468 | ||
| 469 | **Vector广度方向合图** | 469 | **Vector广度方向合图** |
| 470 | 470 | ||
| 471 | Vector运算场景下通过[set_pass_options](../../api/config/pypto-set_pass_options.md)接口的`vec_nbuffer_setting`参数配置广度方向的合图操作。需要注意的是,应先进行前面的优化步骤将上下游子图的切分和合并调到较合适后,再尝试使用vecNBuffer来进行广度合并。当泳道图内有同构子图组具有大量的小子图(耗时在10u以下)时,应该使用该功能进行优化,以减少调度开销和kernel的头开销。 | 471 | Vector运算场景下通过[set_pass_options](../../api/config/pypto-set_pass_options.md)接口的`vec_nbuffer_setting`参数配置广度方向的合图操作。需要注意的是,应先进行前面的优化步骤将上下游子图的切分和合并调到较合适后,再尝试使用vecNBuffer来进行广度合并。当泳道图内有同构子图组具有大量的小子图(耗时在10u以下)时,应该使用该功能进行优化,以减少调度开销和kernel的头开销。 |
| 472 | 472 | ||
| 473 | -`vec_nbuffer_setting`参数的配置方式与`cube_nbuffer_setting`相似,可参考案例[sparse_flash_attention_quant_impl.py](../../../../models/deepseek_v32_exp/sparse_flash_attention_quant_impl.py) | 473 | +`vec_nbuffer_setting`参数的配置方式与`cube_nbuffer_setting`相似。 |
| 474 | 474 | ||
| 475 | ### 调度策略调优 | 475 | ### 调度策略调优 |
| 476 | 476 | ||
| @@ -506,7 +506,7 @@ def matmul_kernel(a, b, out): | |||
| 506 | pypto.assemble(e, [0, 0], out) | 506 | pypto.assemble(e, [0, 0], out) |
| 507 | ``` | 507 | ``` |
| 508 | 508 | ||
| 509 | -- 增加冗余计算来避免冗余依赖和搬运。这些下面是PyPTO仓库的[glm_moe_fusion.py](../../../../models/glm_v4_5/glm_moe_fusion.py)的示例,通过将e_score_bias_2d复制tile_batch份后进行cast操作,使得每一份的cast都和对应batch的其他操作进行了合图。这避免了e_score_bias_2d的cast操作和每个batch的后续计算产生一对多的子图依赖、增加调度开销,还避免了cast结果的搬运。 | 509 | +- 增加冗余计算来避免冗余依赖和搬运。例如,通过将e_score_bias_2d复制tile_batch份后进行cast操作,使得每一份的cast都和对应batch的其他操作进行了合图。这避免了e_score_bias_2d的cast操作和每个batch的后续计算产生一对多的子图依赖、增加调度开销,还避免了cast结果的搬运。 |
| 510 | 510 | ||
| 511 | ```python | 511 | ```python |
| 512 | e_score_bias_2d_tile = pypto.tensor([tile_batch, ne], e_score_bias_2d.dtype, "e_score_bias_2d_tile") | 512 | e_score_bias_2d_tile = pypto.tensor([tile_batch, ne], e_score_bias_2d.dtype, "e_score_bias_2d_tile") |
| @@ -40,12 +40,4 @@ | |||
| 40 | 40 | ||
| 41 | ## 获取完整样例 | 41 | ## 获取完整样例 |
| 42 | 42 | ||
| 43 | -实现的example代码位于:[lightning_indexer_prolog_quant.py](../../../../models/deepseek_v32_exp/deepseekv32_lightning_indexer_prolog_quant.py)。该文件主要展示了QuantIndexerProlog的具体实现。 | 43 | +QuantIndexerProlog算子在典型场景(Batch=4,MTP1,Kv Cache长度64k)下,用户可以根据需要编写相应的测试脚本执行不同的用例。 |
| 44 | - | ||
| 45 | -QuantIndexerProlog算子在典型场景(Batch=4,MTP1,Kv Cache长度64k),可以运行如下实例脚本执行: | ||
| 46 | - | ||
| 47 | -```bash | ||
| 48 | -python3 models/deepseek_v32_exp/deepseekv32_lightning_indexer_prolog_quant.py | ||
| 49 | -``` | ||
| 50 | - | ||
| 51 | -该脚本提供了丰富的测试用例,对于不同场景,用户可以根据需要修改脚本执行不同的用例。 | ||
| @@ -10,14 +10,12 @@ | |||
| 10 | - **01_beginner (初级)**: 基础操作与核心概念,适合刚接触 PyPTO 的开发者。 | 10 | - **01_beginner (初级)**: 基础操作与核心概念,适合刚接触 PyPTO 的开发者。 |
| 11 | - **02_intermediate (中级)**: 神经网络组件、算子组合以及运行时(Runtime)特性。 | 11 | - **02_intermediate (中级)**: 神经网络组件、算子组合以及运行时(Runtime)特性。 |
| 12 | - **03_advanced (高级)**: 复杂架构(如 Attention)、高级模式和系统级优化。 | 12 | - **03_advanced (高级)**: 复杂架构(如 Attention)、高级模式和系统级优化。 |
| 13 | -- **models (模型)**: 真实世界的大模型(LLM)算子实现样例。 | ||
| 14 | 13 | ||
| 15 | ## 快速开始 | 14 | ## 快速开始 |
| 16 | 15 | ||
| 17 | 1. **初次使用?** 请从 [初级样例 (01_beginner)](01_beginner/README.md) 开始。 | 16 | 1. **初次使用?** 请从 [初级样例 (01_beginner)](01_beginner/README.md) 开始。 |
| 18 | 2. **构建神经网络?** 参考 [中级样例 (02_intermediate)](02_intermediate/README.md)。 | 17 | 2. **构建神经网络?** 参考 [中级样例 (02_intermediate)](02_intermediate/README.md)。 |
| 19 | 3. **探索高级模式?** 查阅 [高级样例 (03_advanced)](03_advanced/README.md)。 | 18 | 3. **探索高级模式?** 查阅 [高级样例 (03_advanced)](03_advanced/README.md)。 |
| 20 | -4. **大模型算子实现?** 探索 [模型样例 (models)](../models)。 | ||
| 21 | 19 | ||
| 22 | ### 环境准备 | 20 | ### 环境准备 |
| 23 | 请参考[环境准备](../docs/zh/install/prepare_environment.md),完成基础环境搭建 | 21 | 请参考[环境准备](../docs/zh/install/prepare_environment.md),完成基础环境搭建 |
| @@ -39,7 +37,6 @@ source /usr/local/Ascend/ascend-toolkit/set_env.sh | |||
| 39 | # 设置 NPU 设备 ID(运行 NPU 样例时必需) | 37 | # 设置 NPU 设备 ID(运行 NPU 样例时必需) |
| 40 | export TILE_FWK_DEVICE_ID=0 | 38 | export TILE_FWK_DEVICE_ID=0 |
| 41 | ``` | 39 | ``` |
| 42 | -补充说明:如需运行models相关样例,请在真实设备运行 | ||
| 43 | 40 | ||
| 44 | ## 如何运行样例 | 41 | ## 如何运行样例 |
| 45 | 42 | ||
| @@ -79,8 +76,6 @@ python3 examples/01_beginner/basic/basic_ops.py --run_mode sim | |||
| 79 | 3. **第三阶段:深度实践** | 76 | 3. **第三阶段:深度实践** |
| 80 | - [03_advanced/advanced_nn](03_advanced/advanced_nn/README.md) | 77 | - [03_advanced/advanced_nn](03_advanced/advanced_nn/README.md) |
| 81 | - [03_advanced/patterns](03_advanced/patterns/README.md) | 78 | - [03_advanced/patterns](03_advanced/patterns/README.md) |
| 82 | - - [../models/deepseek_v32_exp](../models/deepseek_v32_exp/README.md) | ||
| 83 | - - [../models/glm_v4_5](../models/glm_v4_5/README.md) | ||
| 84 | 79 | ||
| 85 | --- | 80 | --- |
| 86 | 81 | ||
| @@ -10,14 +10,12 @@ The sample codes are divided into the following levels: | |||
| 10 | - **01_beginner (Beginner)**: Basic operations and core concepts, suitable for developers new to PyPTO. | 10 | - **01_beginner (Beginner)**: Basic operations and core concepts, suitable for developers new to PyPTO. |
| 11 | - **02_intermediate (Intermediate)**: Neural network components, operator combinations, and Runtime features. | 11 | - **02_intermediate (Intermediate)**: Neural network components, operator combinations, and Runtime features. |
| 12 | - **03_advanced (Advanced)**: Complex architectures (such as Attention), advanced patterns, and system-level optimization. | 12 | - **03_advanced (Advanced)**: Complex architectures (such as Attention), advanced patterns, and system-level optimization. |
| 13 | -- **models**: Real-world large language model (LLM) operator implementation samples. | ||
| 14 | 13 | ||
| 15 | ## Quick Start | 14 | ## Quick Start |
| 16 | 15 | ||
| 17 | 1. **First time user?** Start from [Beginner Samples (01_beginner)](01_beginner/README_en.md). | 16 | 1. **First time user?** Start from [Beginner Samples (01_beginner)](01_beginner/README_en.md). |
| 18 | 2. **Building a neural network?** Refer to [Intermediate Samples (02_intermediate)](02_intermediate/README_en.md). | 17 | 2. **Building a neural network?** Refer to [Intermediate Samples (02_intermediate)](02_intermediate/README_en.md). |
| 19 | 3. **Exploring advanced patterns?** Refer to [Advanced Samples (03_advanced)](03_advanced/README_en.md). | 18 | 3. **Exploring advanced patterns?** Refer to [Advanced Samples (03_advanced)](03_advanced/README_en.md). |
| 20 | -4. **LLM operator implementations?** Explore [Model Samples (../models/)](../models). | ||
| 21 | 19 | ||
| 22 | ### Environment Preparation | 20 | ### Environment Preparation |
| 23 | For environment preparation, refer to [Environment Setup](../docs/zh/install/prepare_environment.md) to complete the basic environment setup. | 21 | For environment preparation, refer to [Environment Setup](../docs/zh/install/prepare_environment.md) to complete the basic environment setup. |
| @@ -39,7 +37,6 @@ source /usr/local/Ascend/ascend-toolkit/set_env.sh | |||
| 39 | # Set NPU device ID (required when running NPU samples) | 37 | # Set NPU device ID (required when running NPU samples) |
| 40 | export TILE_FWK_DEVICE_ID=0 | 38 | export TILE_FWK_DEVICE_ID=0 |
| 41 | ``` | 39 | ``` |
| 42 | -Additional note: If you need to run models-related samples, run them on a real device. | ||
| 43 | 40 | ||
| 44 | ## How To Run Samples | 41 | ## How To Run Samples |
| 45 | 42 | ||
| @@ -78,8 +75,6 @@ python3 examples/01_beginner/basic/basic_ops.py --run_mode sim | |||
| 78 | 3. **Phase 3: In-Depth Practice** | 75 | 3. **Phase 3: In-Depth Practice** |
| 79 | - [03_advanced/advanced_nn](03_advanced/advanced_nn/README_en.md) | 76 | - [03_advanced/advanced_nn](03_advanced/advanced_nn/README_en.md) |
| 80 | - [03_advanced/patterns](03_advanced/patterns/README_en.md) | 77 | - [03_advanced/patterns](03_advanced/patterns/README_en.md) |
| 81 | - - [../models/deepseek_v32_exp](../models/deepseek_v32_exp/README_en.md) | ||
| 82 | - - [../models/glm_v4_5](../models/glm_v4_5/README_en.md) | ||
| 83 | 78 | ||
| 84 | --- | 79 | --- |
| 85 | 80 | ||
| @@ -1,102 +0,0 @@ | |||
| 1 | -# sum_lstm Operator | ||
| 2 | -## 功能说明 | ||
| 3 | - | ||
| 4 | -sum_lstm算子是Arctic-Inference框架中基于LSTM的speculator的核心机制。它具有以下特点: | ||
| 5 | - | ||
| 6 | -- **输入融合**: 将主要状态输入与额外输入信号进行加权融合 | ||
| 7 | -- **RMS归一化**: 使用RMSNorm代替LayerNorm,提高计算效率 | ||
| 8 | -- **GELU激活**: 使用近似GELU激活函数 | ||
| 9 | -- **门控机制**: 标准的LSTM门控逻辑,控制信息的遗忘、输入和输出 | ||
| 10 | -- **状态更新**: 通过遗忘门和输入门更新细胞状态 | ||
| 11 | -- **输出生成**: 通过输出门控制最终的隐藏状态输出 | ||
| 12 | - | ||
| 13 | -该算子主要用于序列预测和生成任务中的speculative decoding,加速大语言模型的推理过程。 | ||
| 14 | - | ||
| 15 | -## 数学公式 | ||
| 16 | - | ||
| 17 | -Sum LSTM算子的计算过程如下: | ||
| 18 | - | ||
| 19 | -1. **输入融合**: | ||
| 20 | - ``` | ||
| 21 | - fused = states_4d + alpha * z4_4d | ||
| 22 | - ``` | ||
| 23 | - | ||
| 24 | -2. **门控分割**: | ||
| 25 | - 将fused按最后一维分割为4个部分,每个部分大小为 `D_GATE`: | ||
| 26 | - ``` | ||
| 27 | - pre_f, pre_i, pre_o, pre_c = split(fused, 4, dim=-1) | ||
| 28 | - ``` | ||
| 29 | - | ||
| 30 | -3. **门控激活**: | ||
| 31 | - ``` | ||
| 32 | - f_gate = sigmoid(pre_f) # 遗忘门 | ||
| 33 | - i_gate = sigmoid(pre_i) # 输入门 | ||
| 34 | - o_gate = sigmoid(pre_o) # 输出门 | ||
| 35 | - ``` | ||
| 36 | - | ||
| 37 | -4. **细胞候选处理**: | ||
| 38 | - ``` | ||
| 39 | - c_cand_norm = RMSNorm(pre_c, eps_cell) | ||
| 40 | - c_cand_norm = c_cand_norm * w_cell + b_cell (如果权重存在) | ||
| 41 | - c_act = GELU(c_cand_norm) | ||
| 42 | - ``` | ||
| 43 | - | ||
| 44 | -5. **细胞状态更新**: | ||
| 45 | - ``` | ||
| 46 | - c_new = prev_cell * f_gate + c_act * i_gate | ||
| 47 | - ``` | ||
| 48 | - | ||
| 49 | -6. **隐藏状态处理**: | ||
| 50 | - ``` | ||
| 51 | - h_temp = RMSNorm(c_new, eps_state) | ||
| 52 | - h_temp = h_temp * w_state + b_state (如果权重存在) | ||
| 53 | - h_act = GELU(h_temp) | ||
| 54 | - ``` | ||
| 55 | - | ||
| 56 | -7. **最终输出**: | ||
| 57 | - ``` | ||
| 58 | - h_new = h_act * o_gate | ||
| 59 | - ``` | ||
| 60 | - | ||
| 61 | -其中: | ||
| 62 | -- **RMSNorm(x, eps)**: `x * rsqrt(mean(x^2) + eps)` | ||
| 63 | -- **GELU(x)**: `x * sigmoid(1.702 * x)` (近似实现) | ||
| 64 | - | ||
| 65 | -## 函数原型 | ||
| 66 | - | ||
| 67 | -```python | ||
| 68 | -def sum_lstm_kernel( | ||
| 69 | - states_4d: pypto.Tensor((BATCH_SIZE, D_GATE_4), pypto.DT_FP16), | ||
| 70 | - z4_4d: pypto.Tensor((BATCH_SIZE, D_GATE_4), pypto.DT_FP16), | ||
| 71 | - prev_cell: pypto.Tensor((BATCH_SIZE, D_GATE), pypto.DT_FP16), | ||
| 72 | - w_cell: pypto.Tensor((D_GATE,), pypto.DT_FP16), | ||
| 73 | - b_cell: pypto.Tensor((D_GATE,), pypto.DT_FP16), | ||
| 74 | - w_state: pypto.Tensor((D_GATE,), pypto.DT_FP16), | ||
| 75 | - b_state: pypto.Tensor((D_GATE,), pypto.DT_FP16), | ||
| 76 | - config: LstmConfig, | ||
| 77 | - h_out: pypto.Tensor((BATCH_SIZE, D_GATE), pypto.DT_FP16), | ||
| 78 | - c_out: pypto.Tensor((BATCH_SIZE, D_GATE), pypto.DT_FP16) | ||
| 79 | -) -> None | ||
| 80 | -``` | ||
| 81 | - | ||
| 82 | -## 参数说明 | ||
| 83 | - | ||
| 84 | -- **states_4d**: 张量,形状为 `(BATCH_SIZE, D_GATE_4)`,数据类型为 FP16。表示LSTM的状态输入,包含4个门控信号(遗忘门、输入门、输出门、细胞候选)。 | ||
| 85 | -- **z4_4d**: 张量,形状为 `(BATCH_SIZE, D_GATE_4)`,数据类型为 FP16。表示额外的输入信号,与states_4d融合。 | ||
| 86 | -- **prev_cell**: 张量,形状为 `(BATCH_SIZE, D_GATE)`,数据类型为 FP16。表示前一时刻的细胞状态。 | ||
| 87 | -- **w_cell**: 张量,形状为 `(D_GATE,)`,数据类型为 FP16。细胞路径的权重参数。 | ||
| 88 | -- **b_cell**: 张量,形状为 `(D_GATE,)`,数据类型为 FP16。细胞路径的偏置参数。 | ||
| 89 | -- **w_state**: 张量,形状为 `(D_GATE,)`,数据类型为 FP16。状态路径的权重参数。 | ||
| 90 | -- **b_state**: 张量,形状为 `(D_GATE,)`,数据类型为 FP16。状态路径的偏置参数。 | ||
| 91 | -- **config**: LstmConfig 对象,包含超参数: | ||
| 92 | - - `alpha`: 融合系数,默认 0.1 | ||
| 93 | - - `eps_cell`: 细胞RMSNorm的epsilon,默认 1e-6 | ||
| 94 | - - `eps_state`: 状态RMSNorm的epsilon,默认 1e-6 | ||
| 95 | - | ||
| 96 | -## 返回值说明 | ||
| 97 | - | ||
| 98 | -- **h_out**: 张量,形状为 `(BATCH_SIZE, D_GATE)`,数据类型为 FP16。表示新的隐藏状态输出。 | ||
| 99 | -- **c_out**: 张量,形状为 `(BATCH_SIZE, D_GATE)`,数据类型为 FP16。表示新的细胞状态输出。 | ||
| 100 | - | ||
| 101 | -## 调用示例 | ||
| 102 | -- 算子源码执行参考[test_sum_lstm.py](test_sum_lstm.py) | ||
| @@ -1,102 +0,0 @@ | |||
| 1 | -# sum_lstm Operator | ||
| 2 | -## Function Description | ||
| 3 | - | ||
| 4 | -The sum_lstm operator is the core mechanism of the LSTM-based speculator in the Arctic-Inference framework. It has the following features: | ||
| 5 | - | ||
| 6 | -- **Input Fusion**: Weighted fusion of the main state input with additional input signals. | ||
| 7 | -- **RMS Normalization**: Uses RMSNorm instead of LayerNorm to improve computational efficiency. | ||
| 8 | -- **GELU Activation**: Uses an approximate GELU activation function. | ||
| 9 | -- **Gating Mechanism**: Standard LSTM gating logic controlling forget, input, and output. | ||
| 10 | -- **State Update**: Updates the cell state through the forget gate and input gate. | ||
| 11 | -- **Output Generation**: Controls the final hidden state output through the output gate. | ||
| 12 | - | ||
| 13 | -This operator is mainly used for speculative decoding in sequence prediction and generation tasks, accelerating the inference process of large language models. | ||
| 14 | - | ||
| 15 | -## Mathematical Formulas | ||
| 16 | - | ||
| 17 | -The computation process of the Sum LSTM operator is as follows: | ||
| 18 | - | ||
| 19 | -1. **Input Fusion**: | ||
| 20 | - ``` | ||
| 21 | - fused = states_4d + alpha * z4_4d | ||
| 22 | - ``` | ||
| 23 | - | ||
| 24 | -2. **Gate Split**: | ||
| 25 | - Split fused into 4 parts along the last dimension, each of size `D_GATE`: | ||
| 26 | - ``` | ||
| 27 | - pre_f, pre_i, pre_o, pre_c = split(fused, 4, dim=-1) | ||
| 28 | - ``` | ||
| 29 | - | ||
| 30 | -3. **Gate Activation**: | ||
| 31 | - ``` | ||
| 32 | - f_gate = sigmoid(pre_f) # Forget gate | ||
| 33 | - i_gate = sigmoid(pre_i) # Input gate | ||
| 34 | - o_gate = sigmoid(pre_o) # Output gate | ||
| 35 | - ``` | ||
| 36 | - | ||
| 37 | -4. **Cell Candidate Processing**: | ||
| 38 | - ``` | ||
| 39 | - c_cand_norm = RMSNorm(pre_c, eps_cell) | ||
| 40 | - c_cand_norm = c_cand_norm * w_cell + b_cell (if weights exist) | ||
| 41 | - c_act = GELU(c_cand_norm) | ||
| 42 | - ``` | ||
| 43 | - | ||
| 44 | -5. **Cell State Update**: | ||
| 45 | - ``` | ||
| 46 | - c_new = prev_cell * f_gate + c_act * i_gate | ||
| 47 | - ``` | ||
| 48 | - | ||
| 49 | -6. **Hidden State Processing**: | ||
| 50 | - ``` | ||
| 51 | - h_temp = RMSNorm(c_new, eps_state) | ||
| 52 | - h_temp = h_temp * w_state + b_state (if weights exist) | ||
| 53 | - h_act = GELU(h_temp) | ||
| 54 | - ``` | ||
| 55 | - | ||
| 56 | -7. **Final Output**: | ||
| 57 | - ``` | ||
| 58 | - h_new = h_act * o_gate | ||
| 59 | - ``` | ||
| 60 | - | ||
| 61 | -Where: | ||
| 62 | -- **RMSNorm(x, eps)**: `x * rsqrt(mean(x^2) + eps)` | ||
| 63 | -- **GELU(x)**: `x * sigmoid(1.702 * x)` (approximate implementation) | ||
| 64 | - | ||
| 65 | -## Function Prototype | ||
| 66 | - | ||
| 67 | -```python | ||
| 68 | -def sum_lstm_kernel( | ||
| 69 | - states_4d: pypto.Tensor((BATCH_SIZE, D_GATE_4), pypto.DT_FP16), | ||
| 70 | - z4_4d: pypto.Tensor((BATCH_SIZE, D_GATE_4), pypto.DT_FP16), | ||
| 71 | - prev_cell: pypto.Tensor((BATCH_SIZE, D_GATE), pypto.DT_FP16), | ||
| 72 | - w_cell: pypto.Tensor((D_GATE,), pypto.DT_FP16), | ||
| 73 | - b_cell: pypto.Tensor((D_GATE,), pypto.DT_FP16), | ||
| 74 | - w_state: pypto.Tensor((D_GATE,), pypto.DT_FP16), | ||
| 75 | - b_state: pypto.Tensor((D_GATE,), pypto.DT_FP16), | ||
| 76 | - config: LstmConfig, | ||
| 77 | - h_out: pypto.Tensor((BATCH_SIZE, D_GATE), pypto.DT_FP16), | ||
| 78 | - c_out: pypto.Tensor((BATCH_SIZE, D_GATE), pypto.DT_FP16) | ||
| 79 | -) -> None | ||
| 80 | -``` | ||
| 81 | - | ||
| 82 | -## Parameter Description | ||
| 83 | - | ||
| 84 | -- **states_4d**: Tensor with shape `(BATCH_SIZE, D_GATE_4)` and dtype FP16. Represents the LSTM state input, containing 4 gate signals (forget gate, input gate, output gate, cell candidate). | ||
| 85 | -- **z4_4d**: Tensor with shape `(BATCH_SIZE, D_GATE_4)` and dtype FP16. Represents the additional input signal, fused with states_4d. | ||
| 86 | -- **prev_cell**: Tensor with shape `(BATCH_SIZE, D_GATE)` and dtype FP16. Represents the previous cell state. | ||
| 87 | -- **w_cell**: Tensor with shape `(D_GATE,)` and dtype FP16. Weight parameter for the cell path. | ||
| 88 | -- **b_cell**: Tensor with shape `(D_GATE,)` and dtype FP16. Bias parameter for the cell path. | ||
| 89 | -- **w_state**: Tensor with shape `(D_GATE,)` and dtype FP16. Weight parameter for the state path. | ||
| 90 | -- **b_state**: Tensor with shape `(D_GATE,)` and dtype FP16. Bias parameter for the state path. | ||
| 91 | -- **config**: LstmConfig object containing hyperparameters: | ||
| 92 | - - `alpha`: Fusion coefficient, default 0.1 | ||
| 93 | - - `eps_cell`: Epsilon for cell RMSNorm, default 1e-6 | ||
| 94 | - - `eps_state`: Epsilon for state RMSNorm, default 1e-6 | ||
| 95 | - | ||
| 96 | -## Return Value Description | ||
| 97 | - | ||
| 98 | -- **h_out**: Tensor with shape `(BATCH_SIZE, D_GATE)` and dtype FP16. Represents the new hidden state output. | ||
| 99 | -- **c_out**: Tensor with shape `(BATCH_SIZE, D_GATE)` and dtype FP16. Represents the new cell state output. | ||
| 100 | - | ||
| 101 | -## Call Sample | ||
| 102 | -- For operator source code execution, refer to [test_sum_lstm.py](test_sum_lstm.py). | ||
| @@ -1,228 +0,0 @@ | |||
| 1 | -#!/usr/bin/env python3 | ||
| 2 | -# coding: utf-8 | ||
| 3 | -# Copyright (c) 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 | -arctic lstm Example for PyPTO | ||
| 13 | - | ||
| 14 | -This example demonstrates: | ||
| 15 | -- Special lstm provided by arcitc | ||
| 16 | - | ||
| 17 | - | ||
| 18 | -lstm is the core mechanism in arcitc lstm-based speculators | ||
| 19 | -""" | ||
| 20 | - | ||
| 21 | -from dataclasses import dataclass | ||
| 22 | - | ||
| 23 | -from torch._dynamo import allow_in_graph | ||
| 24 | - | ||
| 25 | -import pypto | ||
| 26 | - | ||
| 27 | -BATCH_SIZE = 32 | ||
| 28 | -D_GATE = 4096 | ||
| 29 | -D_GATE_4 = 16384 | ||
| 30 | - | ||
| 31 | - | ||
| 32 | -@dataclass | ||
| 33 | -class LstmConfig: | ||
| 34 | - """Hyperparameters for LSTM.""" | ||
| 35 | - | ||
| 36 | - alpha: float = 0.1 | ||
| 37 | - eps_cell: float = 1e-6 | ||
| 38 | - eps_state: float = 1e-6 | ||
| 39 | - | ||
| 40 | - | ||
| 41 | -@dataclass | ||
| 42 | -class LstmTileConfig: | ||
| 43 | - """Tiling configuration for NPU optimization.""" | ||
| 44 | - | ||
| 45 | - def __init__(self): | ||
| 46 | - self.tile_bs = 1 # Batch dimension tile size | ||
| 47 | - self.unroll_list = [1, 2, 4] # Loop unrolling strategy | ||
| 48 | - self.h_tile = 4096 # Hidden dimension tile size (aligned to 128 bytes) | ||
| 49 | - | ||
| 50 | - | ||
| 51 | -def rms_norm_pure(x: pypto.Tensor, epsilon: float) -> pypto.Tensor: | ||
| 52 | - """ | ||
| 53 | - Pure RMSNorm without learnable parameters. | ||
| 54 | - Formula: x * rsqrt(mean(x^2) + eps) | ||
| 55 | - """ | ||
| 56 | - input_dtype = x.dtype | ||
| 57 | - x_fp32 = pypto.cast(x, pypto.DT_FP32) | ||
| 58 | - | ||
| 59 | - y = pypto.mul(x_fp32, x_fp32) | ||
| 60 | - y = pypto.mul(y, 1.0 / x.shape[-1]) | ||
| 61 | - y = pypto.sum(y, -1, keepdim=True) | ||
| 62 | - | ||
| 63 | - y = pypto.add(y, epsilon) | ||
| 64 | - y = pypto.sqrt(y) | ||
| 65 | - | ||
| 66 | - output = pypto.div(x_fp32, y) | ||
| 67 | - return pypto.cast(output, input_dtype) | ||
| 68 | - | ||
| 69 | - | ||
| 70 | -def gelu_activation_core(x: pypto.Tensor) -> pypto.Tensor: | ||
| 71 | - """ | ||
| 72 | - GELU activation function: x * 0.5 * (1 + erf(x / sqrt(2))) | ||
| 73 | - | ||
| 74 | - Approximated as: x * 0.5 * (1 + tanh(sqrt(2/π) * (x + 0.044715 * x^3))) | ||
| 75 | - | ||
| 76 | - Parameters | ||
| 77 | - ---------- | ||
| 78 | - x : pypto.Tensor | ||
| 79 | - Input tensor | ||
| 80 | - | ||
| 81 | - Returns | ||
| 82 | - ------- | ||
| 83 | - pypto.Tensor | ||
| 84 | - GELU activated tensor | ||
| 85 | - """ | ||
| 86 | - # Use the sigmoid approximation: x * sigmoid(1.702 * x) | ||
| 87 | - x_scaled = pypto.mul(x, 1.702) | ||
| 88 | - sigmoid = pypto.sigmoid(x_scaled) | ||
| 89 | - return pypto.mul(x, sigmoid) | ||
| 90 | - | ||
| 91 | - | ||
| 92 | -def sum_lstm_compute( | ||
| 93 | - states_4d: pypto.Tensor, | ||
| 94 | - z4_4d: pypto.Tensor, | ||
| 95 | - prev_cell: pypto.Tensor, | ||
| 96 | - w_cell: pypto.Tensor, | ||
| 97 | - b_cell: pypto.Tensor, | ||
| 98 | - w_state: pypto.Tensor, | ||
| 99 | - b_state: pypto.Tensor, | ||
| 100 | - config: LstmConfig, | ||
| 101 | - tile_config: LstmTileConfig, | ||
| 102 | - h_out: pypto.Tensor, | ||
| 103 | - c_out: pypto.Tensor, | ||
| 104 | -): | ||
| 105 | - """Core computation logic for Snowflake Arctic LSTM.""" | ||
| 106 | - # Dimensions | ||
| 107 | - batch_size = states_4d.shape[0] | ||
| 108 | - hidden_dim_4 = states_4d.shape[1] # 4 * H | ||
| 109 | - hidden_dim = prev_cell.shape[1] # H | ||
| 110 | - | ||
| 111 | - # Pre-broadcast 1D weights to [1, H] for correct vector multiplication | ||
| 112 | - if w_cell is not None: | ||
| 113 | - w_cell_b_half = pypto.reshape(w_cell, [1, hidden_dim], inplace=True) | ||
| 114 | - b_cell_b_half = pypto.reshape(b_cell, [1, hidden_dim], inplace=True) | ||
| 115 | - | ||
| 116 | - if w_state is not None: | ||
| 117 | - w_state_b_half = pypto.reshape(w_state, [1, hidden_dim], inplace=True) | ||
| 118 | - b_state_b_half = pypto.reshape(b_state, [1, hidden_dim], inplace=True) | ||
| 119 | - | ||
| 120 | - # Main Loop over Batch Dimension | ||
| 121 | - for bs_offset, unroll_length in pypto.loop_unroll( | ||
| 122 | - 0, batch_size, 1, name="LSTM_BATCH_LOOP", idx_name="bs_offset", unroll_list=tile_config.unroll_list | ||
| 123 | - ): | ||
| 124 | - current_tile_bs = unroll_length | ||
| 125 | - output_offset = [bs_offset, 0] | ||
| 126 | - pypto.set_vec_tile_shapes(current_tile_bs, tile_config.h_tile) | ||
| 127 | - if w_cell is not None: | ||
| 128 | - w_cell_b = pypto.cast(w_cell_b_half, pypto.DT_FP32) | ||
| 129 | - b_cell_b = pypto.cast(b_cell_b_half, pypto.DT_FP32) | ||
| 130 | - if w_state is not None: | ||
| 131 | - b_state_b = pypto.cast(b_state_b_half, pypto.DT_FP32) | ||
| 132 | - w_state_b = pypto.cast(w_state_b_half, pypto.DT_FP32) | ||
| 133 | - # Set vector tile shape for current batch | ||
| 134 | - pypto.set_vec_tile_shapes(1, hidden_dim_4) | ||
| 135 | - | ||
| 136 | - # === Step 1: Input Fusion (states + alpha * z4) === | ||
| 137 | - pypto.set_semantic_label("Input_Fusion") | ||
| 138 | - states_tile_half = pypto.view(states_4d, [current_tile_bs, hidden_dim_4], [bs_offset, 0]) | ||
| 139 | - z4_tile_half = pypto.view(z4_4d, [current_tile_bs, hidden_dim_4], [bs_offset, 0]) | ||
| 140 | - x_dtype = states_4d.dtype | ||
| 141 | - states_tile = pypto.cast(states_tile_half, pypto.DT_FP32) | ||
| 142 | - z4_tile = pypto.cast(z4_tile_half, pypto.DT_FP32) | ||
| 143 | - z4_scaled = pypto.mul(z4_tile, config.alpha) | ||
| 144 | - fused = pypto.add(states_tile, z4_scaled) | ||
| 145 | - | ||
| 146 | - # === Step 2: Logical Split === | ||
| 147 | - # Reshape [BS, 4H] -> [BS, 4, H] logic handled by stride/view | ||
| 148 | - pre_f = pypto.view(fused, [current_tile_bs, hidden_dim], [0, 0]) | ||
| 149 | - pre_i = pypto.view(fused, [current_tile_bs, hidden_dim], [0, hidden_dim * 1]) | ||
| 150 | - pre_o = pypto.view(fused, [current_tile_bs, hidden_dim], [0, hidden_dim * 2]) | ||
| 151 | - pre_c = pypto.view(fused, [current_tile_bs, hidden_dim], [0, hidden_dim * 3]) | ||
| 152 | - | ||
| 153 | - # === Step 3: Gates === | ||
| 154 | - pypto.set_semantic_label("Gate_Sigmoid") | ||
| 155 | - pypto.set_vec_tile_shapes(1, tile_config.h_tile) | ||
| 156 | - f_gate = pypto.sigmoid(pre_f) | ||
| 157 | - i_gate = pypto.sigmoid(pre_i) | ||
| 158 | - o_gate = pypto.sigmoid(pre_o) | ||
| 159 | - | ||
| 160 | - # === Step 4: Pre-Cell Path === | ||
| 161 | - pypto.set_semantic_label("rms_norm_pure") | ||
| 162 | - c_cand_norm = rms_norm_pure(pre_c, config.eps_cell) | ||
| 163 | - | ||
| 164 | - if w_cell is not None: | ||
| 165 | - c_cand_norm = pypto.mul(c_cand_norm, w_cell_b) | ||
| 166 | - if b_cell is not None: | ||
| 167 | - c_cand_norm = pypto.add(c_cand_norm, b_cell_b) | ||
| 168 | - | ||
| 169 | - pypto.set_semantic_label("gelu_activation_core") | ||
| 170 | - c_act = gelu_activation_core(c_cand_norm) | ||
| 171 | - | ||
| 172 | - # === Step 5: Cell Update (c_new = prev * f + act * i) === | ||
| 173 | - pypto.set_semantic_label("Cell_Update") | ||
| 174 | - prev_cell_tile_half = pypto.view(prev_cell, [current_tile_bs, hidden_dim], [bs_offset, 0]) | ||
| 175 | - prev_cell_tile = pypto.cast(prev_cell_tile_half, pypto.DT_FP32) | ||
| 176 | - term1 = pypto.mul(prev_cell_tile, f_gate) | ||
| 177 | - term2 = pypto.mul(c_act, i_gate) | ||
| 178 | - c_new_tile = pypto.add(term1, term2) | ||
| 179 | - c_new_tile_out = pypto.cast(c_new_tile, x_dtype) | ||
| 180 | - pypto.assemble(c_new_tile_out, output_offset, c_out) | ||
| 181 | - | ||
| 182 | - # === Step 6: Post-Cell Path === | ||
| 183 | - pypto.set_semantic_label("Post_Cell_Process") | ||
| 184 | - h_temp = rms_norm_pure(c_new_tile, config.eps_state) | ||
| 185 | - | ||
| 186 | - if w_state is not None: | ||
| 187 | - h_temp = pypto.mul(h_temp, w_state_b) | ||
| 188 | - if b_state is not None: | ||
| 189 | - h_temp = pypto.add(h_temp, b_state_b) | ||
| 190 | - | ||
| 191 | - pypto.set_semantic_label("gelu_activation_core 2") | ||
| 192 | - h_act = gelu_activation_core(h_temp) | ||
| 193 | - | ||
| 194 | - # === Step 7: Final Output (h_new = h_act * o_gate) === | ||
| 195 | - h_new_tile = pypto.mul(h_act, o_gate) | ||
| 196 | - h_new_tile_out = pypto.cast(h_new_tile, x_dtype) | ||
| 197 | - pypto.assemble(h_new_tile_out, output_offset, h_out) | ||
| 198 | - | ||
| 199 | - | ||
| 200 | -@allow_in_graph | ||
| 201 | -def sum_lstm(run_mode: str = "npu"): | ||
| 202 | - if run_mode == "npu": | ||
| 203 | - _mode = pypto.RunMode.NPU | ||
| 204 | - elif run_mode == "sim": | ||
| 205 | - _mode = pypto.RunMode.SIM | ||
| 206 | - else: | ||
| 207 | - raise ValueError(f"Invalid run_mode: {run_mode}. Must be 'npu' or 'sim'") | ||
| 208 | - | ||
| 209 | - @pypto.frontend.jit( | ||
| 210 | - runtime_options={"device_sched_mode": 1}, | ||
| 211 | - ) | ||
| 212 | - def sum_lstm_kernel( | ||
| 213 | - states_4d: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC], pypto.DT_FP16), | ||
| 214 | - z4_4d: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC], pypto.DT_FP16), | ||
| 215 | - prev_cell: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC], pypto.DT_FP16), | ||
| 216 | - w_cell: pypto.Tensor([...], pypto.DT_FP16), | ||
| 217 | - b_cell: pypto.Tensor([...], pypto.DT_FP16), | ||
| 218 | - w_state: pypto.Tensor([...], pypto.DT_FP16), | ||
| 219 | - b_state: pypto.Tensor([...], pypto.DT_FP16), | ||
| 220 | - h_out: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC], pypto.DT_FP16), | ||
| 221 | - c_out: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC], pypto.DT_FP16), | ||
| 222 | - config: LstmConfig, | ||
| 223 | - ): | ||
| 224 | - tile_cfg = LstmTileConfig() | ||
| 225 | - | ||
| 226 | - sum_lstm_compute(states_4d, z4_4d, prev_cell, w_cell, b_cell, w_state, b_state, config, tile_cfg, h_out, c_out) | ||
| 227 | - | ||
| 228 | - return sum_lstm_kernel | ||
| @@ -1,304 +0,0 @@ | |||
| 1 | -#!/usr/bin/env python3 | ||
| 2 | -# coding: utf-8 | ||
| 3 | -# Copyright (c) 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 | -Test file for Arctic Sum LSTM operator. | ||
| 13 | - | ||
| 14 | -This file contains: | ||
| 15 | -- Torch golden reference implementations | ||
| 16 | -- Test data preparation | ||
| 17 | -- Precision and performance tests | ||
| 18 | -""" | ||
| 19 | - | ||
| 20 | -import argparse | ||
| 21 | -import logging | ||
| 22 | -import os | ||
| 23 | -import time | ||
| 24 | -from typing import Any, Dict, Optional, Tuple | ||
| 25 | - | ||
| 26 | -from numpy.testing import assert_allclose | ||
| 27 | -import pytest | ||
| 28 | -from sum_lstm import LstmConfig, sum_lstm | ||
| 29 | -import torch | ||
| 30 | - | ||
| 31 | -BATCH_SIZE = 32 | ||
| 32 | -D_GATE = 4096 | ||
| 33 | -D_GATE_4 = 16384 | ||
| 34 | - | ||
| 35 | - | ||
| 36 | -def rms_norm_golden(x: torch.Tensor, eps: float) -> torch.Tensor: | ||
| 37 | - x = x.to(torch.float32) | ||
| 38 | - mean_square = x.pow(2).mean(-1, keepdim=True) | ||
| 39 | - inv_rms = torch.rsqrt(mean_square + eps) | ||
| 40 | - return x * inv_rms | ||
| 41 | - | ||
| 42 | - | ||
| 43 | -def gelu_approx_sigmoid_golden(x: torch.Tensor) -> torch.Tensor: | ||
| 44 | - """ | ||
| 45 | - GELU approximation using Sigmoid: x * sigmoid(1.702 * x). | ||
| 46 | - Matches the NPU implementation for alignment. | ||
| 47 | - """ | ||
| 48 | - return x * torch.sigmoid(1.702 * x) | ||
| 49 | - | ||
| 50 | - | ||
| 51 | -def sum_lstm_golden( | ||
| 52 | - states_4d: torch.Tensor, | ||
| 53 | - z4_4d: torch.Tensor, | ||
| 54 | - prev_cell: torch.Tensor, | ||
| 55 | - alpha: float, | ||
| 56 | - eps_cell: float, | ||
| 57 | - eps_state: float, | ||
| 58 | - w_cell: Optional[torch.Tensor] = None, | ||
| 59 | - b_cell: Optional[torch.Tensor] = None, | ||
| 60 | - w_state: Optional[torch.Tensor] = None, | ||
| 61 | - b_state: Optional[torch.Tensor] = None, | ||
| 62 | -) -> Tuple[torch.Tensor, torch.Tensor]: | ||
| 63 | - """Golden reference for Arctic LSTM kernel.""" | ||
| 64 | - | ||
| 65 | - # 1. Input Fusion | ||
| 66 | - fused = states_4d + alpha * z4_4d | ||
| 67 | - | ||
| 68 | - # 2. Chunking: [Forget, Input, Output, Cell_Candidate] | ||
| 69 | - chunk_size = fused.shape[-1] // 4 | ||
| 70 | - pre_f, pre_i, pre_o, pre_c = torch.split(fused, chunk_size, dim=-1) | ||
| 71 | - | ||
| 72 | - # 3. Gates | ||
| 73 | - f_gate = torch.sigmoid(pre_f) | ||
| 74 | - i_gate = torch.sigmoid(pre_i) | ||
| 75 | - | ||
| 76 | - # 4. Pre-Cell Path | ||
| 77 | - c_cand_norm = rms_norm_golden(pre_c, eps_cell) | ||
| 78 | - | ||
| 79 | - if w_cell is not None: | ||
| 80 | - c_cand_norm = c_cand_norm * w_cell | ||
| 81 | - if b_cell is not None: | ||
| 82 | - c_cand_norm = c_cand_norm + b_cell | ||
| 83 | - | ||
| 84 | - c_act = gelu_approx_sigmoid_golden(c_cand_norm) | ||
| 85 | - | ||
| 86 | - # 5. Cell Update | ||
| 87 | - c_new = prev_cell * f_gate + c_act * i_gate | ||
| 88 | - | ||
| 89 | - # 6. Post-Cell Path | ||
| 90 | - h_temp = rms_norm_golden(c_new, eps_state) | ||
| 91 | - | ||
| 92 | - if w_state is not None: | ||
| 93 | - h_temp = h_temp * w_state | ||
| 94 | - if b_state is not None: | ||
| 95 | - h_temp = h_temp + b_state | ||
| 96 | - | ||
| 97 | - h_act = gelu_approx_sigmoid_golden(h_temp) | ||
| 98 | - | ||
| 99 | - # 7. Output Gate & Final Output | ||
| 100 | - o_gate = torch.sigmoid(pre_o) | ||
| 101 | - h_new = h_act * o_gate | ||
| 102 | - | ||
| 103 | - return h_new, c_new | ||
| 104 | - | ||
| 105 | - | ||
| 106 | -def prepare_test_data(device) -> Dict[str, Any]: | ||
| 107 | - """Prepare common data for both precision and performance tests.""" | ||
| 108 | - # Data | ||
| 109 | - states_4d = torch.randn(BATCH_SIZE, D_GATE_4, dtype=torch.float16, device=device) | ||
| 110 | - z4_4d = torch.randn(BATCH_SIZE, D_GATE_4, dtype=torch.float16, device=device) | ||
| 111 | - prev_cell = torch.randn(BATCH_SIZE, D_GATE, dtype=torch.float16, device=device) | ||
| 112 | - | ||
| 113 | - # Weights (None for this test case, can be tensors) | ||
| 114 | - w_c = torch.randn(D_GATE, dtype=torch.float16, device=device) | ||
| 115 | - b_c = torch.randn(D_GATE, dtype=torch.float16, device=device) | ||
| 116 | - w_s = torch.randn(D_GATE, dtype=torch.float16, device=device) | ||
| 117 | - b_s = torch.randn(D_GATE, dtype=torch.float16, device=device) | ||
| 118 | - | ||
| 119 | - # Outputs | ||
| 120 | - h_out = torch.zeros(BATCH_SIZE, D_GATE, dtype=torch.float16, device=device) | ||
| 121 | - c_out = torch.zeros(BATCH_SIZE, D_GATE, dtype=torch.float16, device=device) | ||
| 122 | - | ||
| 123 | - config = LstmConfig(alpha=0.1, eps_cell=1e-6, eps_state=1e-6) | ||
| 124 | - | ||
| 125 | - # PyPTO Wrappers | ||
| 126 | - inputs_torch = [states_4d, z4_4d, prev_cell, w_c, b_c, w_s, b_s] | ||
| 127 | - outputs_torch = [h_out, c_out] | ||
| 128 | - | ||
| 129 | - return { | ||
| 130 | - "torch_inputs": inputs_torch, | ||
| 131 | - "torch_outputs": outputs_torch, | ||
| 132 | - "pto_inputs": inputs_torch, | ||
| 133 | - "pto_outputs": outputs_torch, | ||
| 134 | - "config": config, | ||
| 135 | - } | ||
| 136 | - | ||
| 137 | - | ||
| 138 | -def run_precision_test(kernel_func, data: Dict[str, Any]): | ||
| 139 | - """Run correctness verification.""" | ||
| 140 | - logging.info("\n" + "=" * 40) | ||
| 141 | - logging.info("Running [Precision Test]") | ||
| 142 | - logging.info("=" * 40) | ||
| 143 | - | ||
| 144 | - # Unpack data | ||
| 145 | - t_in = data["torch_inputs"] | ||
| 146 | - h_out, c_out = data["torch_outputs"] | ||
| 147 | - pto_inputs = data["pto_inputs"] | ||
| 148 | - pto_outputs = data["pto_outputs"] | ||
| 149 | - cfg = data["config"] | ||
| 150 | - | ||
| 151 | - # 1. Run NPU Kernel | ||
| 152 | - # Reset outputs to 0 to ensure we are reading fresh results | ||
| 153 | - kernel_func(*pto_inputs, *pto_outputs, cfg) | ||
| 154 | - | ||
| 155 | - # 2. Run Golden | ||
| 156 | - golden_h, golden_c = sum_lstm_golden( | ||
| 157 | - t_in[0], | ||
| 158 | - t_in[1], | ||
| 159 | - t_in[2], | ||
| 160 | - alpha=cfg.alpha, | ||
| 161 | - eps_cell=cfg.eps_cell, | ||
| 162 | - eps_state=cfg.eps_state, | ||
| 163 | - w_cell=t_in[3], | ||
| 164 | - b_cell=t_in[4], | ||
| 165 | - w_state=t_in[5], | ||
| 166 | - b_state=t_in[6], | ||
| 167 | - ) | ||
| 168 | - | ||
| 169 | - # 3. Compare | ||
| 170 | - diff_h = (h_out - golden_h).abs().max().item() | ||
| 171 | - diff_c = (c_out - golden_c).abs().max().item() | ||
| 172 | - logging.info(f"Max Diff Hidden: {diff_h:.6f}") | ||
| 173 | - logging.info(f"Max Diff Cell: {diff_c:.6f}") | ||
| 174 | - | ||
| 175 | - try: | ||
| 176 | - assert_allclose(h_out.cpu().numpy(), golden_h.cpu().numpy(), rtol=0.001, atol=5e-3) | ||
| 177 | - assert_allclose(c_out.cpu().numpy(), golden_c.cpu().numpy(), rtol=5e-3, atol=5e-3) | ||
| 178 | - logging.info(">> Precision Test PASSED!") | ||
| 179 | - except AssertionError as e: | ||
| 180 | - logging.error(">> Precision Test FAILED!") | ||
| 181 | - raise e | ||
| 182 | - | ||
| 183 | - | ||
| 184 | -def benchmark_func(func, name: str, n_warmup=1, n_repeat=2) -> float: | ||
| 185 | - """Helper for measuring execution time.""" | ||
| 186 | - logging.info(f"Benchmarking {name} ...") | ||
| 187 | - # Warmup | ||
| 188 | - for _ in range(n_warmup): | ||
| 189 | - func() | ||
| 190 | - torch.npu.synchronize() | ||
| 191 | - | ||
| 192 | - # Timing | ||
| 193 | - t0 = time.time() | ||
| 194 | - for _ in range(n_repeat): | ||
| 195 | - func() | ||
| 196 | - torch.npu.synchronize() | ||
| 197 | - t1 = time.time() | ||
| 198 | - | ||
| 199 | - avg_ms = (t1 - t0) * 1000 / n_repeat | ||
| 200 | - logging.info(f" -> {name}: {avg_ms:.4f} ms") | ||
| 201 | - return avg_ms | ||
| 202 | - | ||
| 203 | - | ||
| 204 | -def run_performance_test(kernel_func, data: Dict[str, Any]): | ||
| 205 | - """Run performance benchmarking.""" | ||
| 206 | - logging.info("\n" + "=" * 40) | ||
| 207 | - logging.info("Running [Performance Test]") | ||
| 208 | - logging.info("=" * 40) | ||
| 209 | - | ||
| 210 | - # Unpack data | ||
| 211 | - t_in = data["torch_inputs"] | ||
| 212 | - pto_inputs = data["pto_inputs"] | ||
| 213 | - pto_outputs = data["pto_outputs"] | ||
| 214 | - cfg = data["config"] | ||
| 215 | - | ||
| 216 | - # Wrap calls | ||
| 217 | - def run_npu(): | ||
| 218 | - kernel_func(*pto_inputs, *pto_outputs, cfg) | ||
| 219 | - | ||
| 220 | - def run_golden(): | ||
| 221 | - sum_lstm_golden( | ||
| 222 | - t_in[0], | ||
| 223 | - t_in[1], | ||
| 224 | - t_in[2], | ||
| 225 | - alpha=cfg.alpha, | ||
| 226 | - eps_cell=cfg.eps_cell, | ||
| 227 | - eps_state=cfg.eps_state, | ||
| 228 | - w_cell=t_in[3], | ||
| 229 | - b_cell=t_in[4], | ||
| 230 | - w_state=t_in[5], | ||
| 231 | - b_state=t_in[6], | ||
| 232 | - ) | ||
| 233 | - | ||
| 234 | - # Benchmark | ||
| 235 | - time_npu = benchmark_func(run_npu, "PyPTO NPU Kernel") | ||
| 236 | - time_gold = benchmark_func(run_golden, "PyTorch Golden") | ||
| 237 | - | ||
| 238 | - if time_npu > 0: | ||
| 239 | - logging.info(f"\n>> Speedup: {time_gold / time_npu:.2f}x") | ||
| 240 | - | ||
| 241 | - | ||
| 242 | -def get_device_id(): | ||
| 243 | - """ | ||
| 244 | - Get and validate TILE_FWK_DEVICE_ID from environment variable. | ||
| 245 | - | ||
| 246 | - Returns: | ||
| 247 | - int: The device ID if valid, None otherwise. | ||
| 248 | - """ | ||
| 249 | - if 'TILE_FWK_DEVICE_ID' not in os.environ: | ||
| 250 | - logging.info("If no NPU environment is available, set --run_mode sim to run in simulation mode;") | ||
| 251 | - logging.info("otherwise, set the environment variable TILE_FWK_DEVICE_ID.") | ||
| 252 | - logging.info("Please set it before running this example:") | ||
| 253 | - logging.info(" export TILE_FWK_DEVICE_ID=0") | ||
| 254 | - return None | ||
| 255 | - | ||
| 256 | - try: | ||
| 257 | - device_id = int(os.environ['TILE_FWK_DEVICE_ID']) | ||
| 258 | - return device_id | ||
| 259 | - except ValueError: | ||
| 260 | - logging.error(f"ERROR: TILE_FWK_DEVICE_ID must be an integer, got: {os.environ['TILE_FWK_DEVICE_ID']}") | ||
| 261 | - return None | ||
| 262 | - | ||
| 263 | - | ||
| 264 | -@pytest.mark.skip("precision test") | ||
| 265 | -def main(): | ||
| 266 | - parser = argparse.ArgumentParser(description="Run Arctic LSTM PyPTO Example") | ||
| 267 | - parser.add_argument('--run_mode', type=str, default="npu", choices=["npu", "sim"]) | ||
| 268 | - parser.add_argument( | ||
| 269 | - '--test_type', | ||
| 270 | - type=str, | ||
| 271 | - default="precision", | ||
| 272 | - choices=["precision", "performance", "all"], | ||
| 273 | - help="Choose test type: check correctness or measure performance.", | ||
| 274 | - ) | ||
| 275 | - args = parser.parse_args() | ||
| 276 | - | ||
| 277 | - # # Enable debug options for development | ||
| 278 | - if args.run_mode == "npu": | ||
| 279 | - device_id = get_device_id() | ||
| 280 | - if device_id is None: | ||
| 281 | - return | ||
| 282 | - device_id = int(os.environ.get('TILE_FWK_DEVICE_ID', 0)) | ||
| 283 | - torch.npu.set_device(device_id) | ||
| 284 | - | ||
| 285 | - # 1. Compile Kernel (JIT) | ||
| 286 | - kernel_func = sum_lstm(args.run_mode) | ||
| 287 | - | ||
| 288 | - # 2. Prepare Data | ||
| 289 | - data = prepare_test_data(device_id) | ||
| 290 | - | ||
| 291 | - # 3. Dispatch Tests | ||
| 292 | - if args.test_type in ["precision", "all"]: | ||
| 293 | - run_precision_test(kernel_func, data) | ||
| 294 | - | ||
| 295 | - if args.test_type in ["performance", "all"]: | ||
| 296 | - # Only meaningful on NPU hardware | ||
| 297 | - if args.run_mode == "npu": | ||
| 298 | - run_performance_test(kernel_func, data) | ||
| 299 | - else: | ||
| 300 | - logging.info("\n[INFO] Skipping performance test in simulation mode.") | ||
| 301 | - | ||
| 302 | - | ||
| 303 | -if __name__ == "__main__": | ||
| 304 | - main() | ||
| @@ -1,396 +0,0 @@ | |||
| 1 | -# deepseek V3.2 样例 (Examples) | ||
| 2 | - | ||
| 3 | -本目录包含了一系列 PyPTO deepseek V3.2 EXP 的开发样例代码,我们对 DeepSeek-V3.2-Exp 进行了拆解,交付了五个算子:mla prolog, lightning indexer prolog, sparese flash attention, mla_indexer_prolog和lightning indexer。 | ||
| 4 | -## 参数说明/约束 | ||
| 5 | -- shape 格式字段含义说明 | ||
| 6 | - | 字段名 | 英文全称/含义 | 取值规则与说明 | | ||
| 7 | - |--------------|--------------------------------|------------------------------------------------------------------------------| | ||
| 8 | - | b | Batch(输入样本批量大小) | 取值范围:decode场景1~128 prefill场景固定为1 | | ||
| 9 | - | s1 | query Seq-Length | 取值范围:decode场景 1~4 prefill场景1~1K | | ||
| 10 | - | s2 | key Seq-Length | 取值范围:1~128K | | ||
| 11 | - | h | Head-Size(隐藏层大小) | 取值固定为:7168 | | ||
| 12 | - | n_q(n1) | query 的 Head-Num(多头数) | 取值范围:128 | | ||
| 13 | - | n_kv(n2) | kv 的 head 数 | 取值范围:1 | | ||
| 14 | - | kv_lora_rank | kv 低秩矩阵维度 | 取值范围:512 | | ||
| 15 | - | rope_dim | qk 位置编码维度 | 取值范围:64 | | ||
| 16 | - | v_head_dim | value 的头维度 | 取值范围:128 | | ||
| 17 | - | q_head_dim | query 的头维度 | 取值范围:192 | | ||
| 18 | - | q_lora_rank |query 低秩矩阵维度 | 取值范围:1536 | | ||
| 19 | - | idx_n_heads | indexer里query的head num | 取值固定为:64 | | ||
| 20 | - | idx_head_dim | indexer里query的头维度 | 取值固定为:128 | | ||
| 21 | - | selected_count | topk选择的个数 | 取值固定为:2048 | | ||
| 22 | - | block_num | PagedAttention 场景下per-tile量的块数 | 取值为计算 `B*Skv/BlockSize` 的结果后向上取整(Skv 表示 kv 的序列长度,允许取 0) | | ||
| 23 | - | block_size | PagedAttention 场景下的块大小 | 取值范围:128 | | ||
| 24 | - | t | BS 合轴后的大小 | 取值范围:b * s1| | ||
| 25 | -# mla_polog_quant | ||
| 26 | - | ||
| 27 | -## 功能说明 | ||
| 28 | - | ||
| 29 | -MLA Prolog 模块将hidden状态 $\bold{X}$ 转换为查询投影 $\bold{q}$、键投影 $\bold{k}$ 和值投影 $\bold{v}$,其结构与 DeepSeek V3 的架构一致。在解码阶段,采用了权重吸收技术。 | ||
| 30 | -## 计算公式 | ||
| 31 | - | ||
| 32 | -**RmsNorm公式** | ||
| 33 | -$$ | ||
| 34 | -\text{RmsNorm}(x) = \gamma \cdot \frac{x_i}{\text{RMS}(x)} | ||
| 35 | -$$ | ||
| 36 | -$$ | ||
| 37 | -\text{RMS}(x) = \sqrt{\frac{1}{N} \sum_{i=1}^{N} x_i^2 + \epsilon} | ||
| 38 | -$$ | ||
| 39 | - | ||
| 40 | - **路径1:标准Query计算** | ||
| 41 | - | ||
| 42 | -包括下采样、RmsNorm和两次上采样: | ||
| 43 | -$$ | ||
| 44 | -c^Q = RmsNorm(x \cdot W^{DQ}) | ||
| 45 | -$$ | ||
| 46 | -$$ | ||
| 47 | -q^C = c^Q \cdot W^{UQ} | ||
| 48 | -$$ | ||
| 49 | -$$ | ||
| 50 | -q^N = q^C \cdot W^{UK} | ||
| 51 | -$$ | ||
| 52 | - | ||
| 53 | -**路径2:位置编码Query计算** | ||
| 54 | - | ||
| 55 | -对Query进行ROPE旋转位置编码: | ||
| 56 | -$$ | ||
| 57 | -q^R = ROPE(c^Q \cdot W^{QR}) | ||
| 58 | -$$ | ||
| 59 | - | ||
| 60 | -**路径3:标准Key计算** | ||
| 61 | - | ||
| 62 | -包括下采样、RmsNorm,将计算结果存入Cache: | ||
| 63 | -$$ | ||
| 64 | -c^{KV} = RmsNorm(x \cdot W^{DKV}) | ||
| 65 | -$$ | ||
| 66 | -$$ | ||
| 67 | -k^C = Cache(c^{KV}) | ||
| 68 | -$$ | ||
| 69 | - | ||
| 70 | -**路径4:位置编码Key计算** | ||
| 71 | - | ||
| 72 | -对Key进行ROPE旋转位置编码,并将结果存入Cache: | ||
| 73 | -$$ | ||
| 74 | -k^R = Cache(ROPE(x \cdot W^{KR})) | ||
| 75 | -$$ | ||
| 76 | - | ||
| 77 | -## 函数原型 | ||
| 78 | -``` | ||
| 79 | -def mla_prolog_quant_compute(token_x, w_dq, w_uq_qr, dequant_scale, w_uk, w_dkv_kr, gamma_cq, gamma_ckv, cos, | ||
| 80 | - sin, cache_index, kv_cache, kr_cache, k_scale_cache, q_norm_out, q_norm_scale_out, query_nope_out, | ||
| 81 | - query_rope_out, kv_cache_out, kr_cache_out, k_scale_cache_out, epsilon_cq, epsilon_ckv, cache_mode, | ||
| 82 | - tile_config, rope_cfg): | ||
| 83 | -``` | ||
| 84 | - | ||
| 85 | -## 参数说明 | ||
| 86 | - | ||
| 87 | -- **token_x**(`Tensor`):公式中用于计算Query和Key的输入tensor,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[t, h]。 | ||
| 88 | -- **w_dq**(`Tensor`):公式中用于计算Query的下采样权重矩阵$W^{DQ}$,不支持非连续的 Tensor。数据格式支持NZ,数据类型支持`bfloat16`,shape为[h, q_lora_rank]。 | ||
| 89 | -- **w_uq_qr**(`Tensor`):公式中用于计算Query的上采样权重矩阵$W^{UQ}$和位置编码权重矩阵$W^{QR}$,不支持非连续的 Tensor,数据格式支持NZ,数据类型支持`int8`,shape为[q_lora_rank, n_q * q_head_dim]。 | ||
| 90 | -- **dequant_scale**(`Tensor`):用于MatmulQcQr矩阵乘后w_uq_qr反量化操作的per-channel参数,不支持非连续的 Tensor。数据格式支持ND,数据类型支持`float`,shape为[n_q*q_head_dim, 1]。 | ||
| 91 | -- **w_uk**(`Tensor`):公式中用于计算Key的上采样权重$W^{UK}$,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[n_q, qk_nope_head_dim, kv_lora_rank]。 | ||
| 92 | -- **w_dkv_kr**(`Tensor`):公式中用于计算Key的下采样权重矩阵$W^{DKV}$和位置编码权重矩阵$W^{KR}$,不支持非连续的 Tensor,数据格式支持NZ,数据类型支持`bfloat16`,shape为[h, kv_lora_rank+rope_dim]。 | ||
| 93 | -- **gamma_cq**(`Tensor`):计算$c^Q$的RmsNorm公式中的$\gamma$参数,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[q_lora_rank]。 | ||
| 94 | -- **gamma_ckv**(`Tensor`):计算$c^{KV}$的RmsNorm公式中的$\gamma$参数,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[kv_lora_rank]。 | ||
| 95 | -- **cos**(`Tensor`):用于计算旋转位置编码的余弦参数矩阵,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[t, rope_dim]。 | ||
| 96 | -- **sin**(`Tensor`):用于计算旋转位置编码的正弦参数矩阵,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[t, rope_dim]。 | ||
| 97 | -- **cache_index**(`Tensor`):用于存储kv_cache和kr_cache的索引,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`int64`,shape为[t]。 | ||
| 98 | -- **kv_cache**(`Tensor`):用于cache索引的aclTensor,计算结果原地更新(对应公式中的$k^C$),不支持非连续的 Tensor。数据格式支持ND,数据类型支持`int8`,cache_mode为"PA_BSND",shape为[block_num, block_size, n_kv, kv_lora_rank]。 | ||
| 99 | -- **kr_cache**(`Tensor`):用于key位置编码的cache,计算结果原地更新(对应公式中的$k^R$),不支持非连续的 Tensor。数据格式支持ND,cache_mode为"PA_BSND",数据类型支持`bfloat16`,cache_mode为"PA_BSND"、shape为[block_num, block_size, n_kv, rope_dim]。 | ||
| 100 | -- **k_scale_cache**(`Tensor`):表示 key 反量化因子的缓存,必选参数,不支持非连续的 Tensor,数据格式支持 ND,cache_mode为"PA_BSND",数据类型支持`float`,shape为[block_num, block_size, n_kv, 4]。 | ||
| 101 | -- **epsilon_cq**(`float`):计算$c^Q$的RmsNorm公式中的$\epsilon$参数。用户未特意指定时,建议传入1e-05,仅支持double类型,默认值为1e-05。 | ||
| 102 | -- **epsilon_ckv**(`float`):计算$c^{KV}$的RmsNorm公式中的$\epsilon$参数。用户未特意指定时,建议传入1e-05,仅支持double类型,默认值为1e-05。 | ||
| 103 | -- **cache_mode**(`str`):表示kv_cache的模式,支持"PA_BSND"。 | ||
| 104 | -- **tile_config**(`class MlaTileConfig`):表示tile切分配置。 | ||
| 105 | -- **rope_cfg**(`class RopeTileShapeConfig`):表示rope tile切分配置。 | ||
| 106 | - | ||
| 107 | -## 返回值说明 | ||
| 108 | -- **q_norm_out**(`Tensor`):Query做RmsNorm_cq后的输出tensor(对应$q^C$),不支持非连续的 Tensor。数据格式支持ND,数据类型支持`int8`,shape为[t, q_lora_rank]。 | ||
| 109 | -- **q_norm_scale_out**(`Tensor`):Query做RmsNorm_cq后的反量化参数,不支持非连续的 Tensor。数据格式支持ND,数据类型支持`float`,shape为[t, 1]。 | ||
| 110 | -- **q_nope_out**(`Tensor`):公式中Query的输出tensor(对应$q^N$),不支持非连续的 Tensor。数据格式支持ND,数据类型支持`bfloat16`,shape为[t, n_q, kv_lora_rank]。 | ||
| 111 | -- **q_rope_out**(`Tensor`):公式中Query位置编码的输出tensor(对应$q^R$),不支持非连续的 Tensor。数据格式支持ND,数据类型支持`bfloat16`,shape为[t, n_q, rope_dim]。 | ||
| 112 | -- **kv_cache_out**(`Tensor`):Key输出到`kv_cache`中的tensor(对应$k^C$),不支持非连续的 Tensor。数据格式支持ND,cache_mode为"PA_BSND",数据类型支持`int8`,shape为[block_num, block_size, n_kv, kv_lora_rank]。 | ||
| 113 | -- **kr_cache_out**(`Tensor`):Key的位置编码输出到`kr_cache`中的tensor(对应$k^R$),不支持非连续的 Tensor。数据格式支持ND,cache_mode为"PA_BSND",数据类型支持`bfloat16`,shape为[block_num, block_size, n_kv, qk_rope_dim]。 | ||
| 114 | -- **k_scale_cache_out**(`Tensor`):Key做反量化后输出的反量化参数,不支持非连续的 Tensor。数据格式支持ND,数据类型支持`float`,cache_mode为"PA_BSND",shape为[block_num, block_size, n_kv, 4]。 | ||
| 115 | - | ||
| 116 | -## 调用示例 | ||
| 117 | - | ||
| 118 | -- 详见 [deepseekv32_mla_prolog_quant.py](deepseekv32_mla_prolog_quant.py) | ||
| 119 | - | ||
| 120 | -# lightning_indexer_prolog | ||
| 121 | -## 功能说明 | ||
| 122 | - | ||
| 123 | -用于 Deepseek IndexerAttention 中,计算 Lightning Indexer 所需要的 query,key 和 weights。 | ||
| 124 | -Indexer Prolog 的量化策略如下:Q_b_proj 使用 W8A8 量化,其他 Linear 均不量化;query 使用 A8 量化,key(cache) 使用 C8 量化;反量化因子以 FP16 存储;weights 以 FP16 存储; | ||
| 125 | - | ||
| 126 | -## 计算公式 | ||
| 127 | - **Query 的计算公式如下:** | ||
| 128 | - | ||
| 129 | - Q 的计算采用了动态的 Per-Token-Head 量化,其中 Hadamard 变换通过矩阵右乘 hadamard_q 实现。而 $\bold{q}, \bold{w}_{qb}$ 均是 Int8 类型。 | ||
| 130 | - | ||
| 131 | -$$ | ||
| 132 | -\bold{q}, \bold{q}_{scale} = \text{DynamicQuant}(\text{Hadamard}(\text{RoPE}(\text{DeQuant}(\bold{q} \cdot \bold{w}_{qb})))) | ||
| 133 | -$$ | ||
| 134 | - | ||
| 135 | -**Key(cache) 的计算公式如下:** | ||
| 136 | - | ||
| 137 | -Cache 的计算同样采用了动态的 Per-Token-Head 量化,其中 Hadamard 变换通过矩阵右乘 hadamard_k 实现。 | ||
| 138 | - | ||
| 139 | -$$ | ||
| 140 | -\bold{k}, \bold{k}_{scale} = \text{DynamicQuant}(\text{Hadamard}(\text{RoPE}(\text{LayerNorm}(\bold{x} \cdot \bold{w}_k)))) | ||
| 141 | -$$ | ||
| 142 | - | ||
| 143 | -**Weights 的计算公式如下:** | ||
| 144 | - | ||
| 145 | -Weights 的计算没有采用量化,同时需要最后转化为 FP16 数据类型,供后续的 Lightning Indexer 计算使用。 | ||
| 146 | - | ||
| 147 | -$$ | ||
| 148 | -\bold{weight} = (\bold{x} \cdot \bold{w}_{proj}) * \text{scale} | ||
| 149 | -$$ | ||
| 150 | - | ||
| 151 | -## 函数原型 | ||
| 152 | - | ||
| 153 | -``` | ||
| 154 | -def lightning_indexer_prolog_quant_compute(x_in, q_norm_in, q_norm_scale_in, w_qb_in, w_qb_scale_in, wk_in, w_proj_in, | ||
| 155 | - ln_gamma_k_in, ln_beta_k_in, cos_idx_rope_in, sin_idx_rope_in, hadamard_q_in, hadamard_k_in, k_int8_in, k_scale_in, | ||
| 156 | - k_cache_index_in, q_int8_out, q_scale_out, k_int8_out,k_scale_out, weights_out, attrs, configs): | ||
| 157 | -``` | ||
| 158 | - | ||
| 159 | -## 参数说明 | ||
| 160 | - | ||
| 161 | - | ||
| 162 | -- **x_in**(`Tensor`):表示 hidden 状态token\_x,必选参数,不支持非连续的Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[t, h]。 | ||
| 163 | -- **q_norm_in**(`Tensor`):表示经过 rmsnorm 后量化的 query,必选参数,不支持非连续的Tensor,数据格式支持ND,数据类型支持`int8`,shape为[t, q_lora_rank]。 | ||
| 164 | -- **q_norm_scale_in**(`Tensor`):表示 query 的反量化因子,必选参数,不支持非连续的Tensor,数据格式支持ND,数据类型支持`float32`,shape为[t, 1]。 | ||
| 165 | -- **wq_b_in**(`Tensor`):表示 query 的权重,必选参数,不支持非连续的Tensor,数据格式支持NZ,数据类型支持`int8`,shape为[q_lora_rank, idx_n_heads*idx_head_dim]。 | ||
| 166 | -- **wq_qb_scale_in**(`Tensor`):表示 query 的权重反量化因子,必选参数,不支持非连续的Tensor,数据格式支持ND,数据类型支持`float32`,shape为[idx_n_heads*idx_head_dim, 1]。 | ||
| 167 | -- **wk_in**(`Tensor`):表示 key 的权重,必选参数,不支持非连续的Tensor,数据格式支持NZ,数据类型支持`bfloat16`,shape为[h, idx_head_dim]。 | ||
| 168 | -- **w_proj_in**(`Tensor`):表示 weights 的权重,必选参数,不支持非连续的Tensor,数据格式支持NZ,数据类型支持`bfloat16`,shape为[h, idx_n_heads]。 | ||
| 169 | -- **ln_gamma_k_in**(`Tensor`):表示 key 的 layernorm 缩放,必选参数,不支持非连续的Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[idx_head_dim]。 | ||
| 170 | -- **ln_beta_k_in**(`Tensor`):表示 key 的 layernorm 偏移,必选参数,不支持非连续的Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[idx_head_dim]。 | ||
| 171 | -- **cos_idx_rope_in**(`Tensor`):表示用于 RoPE 的 cos,不支持非连续的 Tensor,数据格式支持 ND,数据类型支持`bfloat16`,shape为[t, rope_dim]。 | ||
| 172 | -- **sin_idx_rope_in**(`Tensor`):表示用于 RoPE 的 sin,不支持非连续的 Tensor,数据格式支持 ND,数据类型支持`bfloat16`,shape为[t, rope_dim]。 | ||
| 173 | -- **hadamard_q_in**(`Tensor`):表示用于 query Hadamard 变换的权重矩阵,不支持非连续的 Tensor,数据格式支持 ND,数据类型支持`bfloat16`,shape为[idx_head_dim, idx_head_dim]。 | ||
| 174 | -- **hadamard_k_in**(`Tensor`):表示用于 key Hadamard 变换的权重矩阵,不支持非连续的 Tensor,数据格式支持 ND,数据类型支持`bfloat16`,shape为[idx_head_dim, idx_head_dim]。 | ||
| 175 | -- **k_int8_in**(`Tensor`):表示 key 的缓存(k_cache),必选参数,不支持非连续的 Tensor,数据格式支持 ND,cache_mode为"PA_BSND",数据类型支持`int8`,shape为[block_num, block_size, n_kv, idx_head_dim]。 | ||
| 176 | -- **k_scale_in**(`Tensor`):表示 key 反量化因子的缓存,必选参数,不支持非连续的 Tensor,数据格式支持 ND,cache_mode为"PA_BSND",数据类型支持`float16`,shape为[block_num, block_size, n_kv, 1]。 | ||
| 177 | -- **k_cache_index_in**(`Tensor`):表示更新 key 缓存的位置,必选参数,不支持非连续的 Tensor,数据格式支持 ND,数据类型支持`int64`,shape为[t]。 | ||
| 178 | -- **attrs.layernorm_epsilon_k**(`float`):表示 key layernorm 防除 0 系数,必选参数,数据类型支持`float32`。 | ||
| 179 | -- **attrs.layout_query**(`str`):可选参数,用于标识输入`query`的数据排布格式,默认值"TND"。当前仅支持 "TND"。 | ||
| 180 | -- **attrs.layout_key**(`str`):可选参数,用于标识输入`key`的数据排布格式,默认值"PA_BSND"。当前仅支持 "PA_BSND"。 | ||
| 181 | -- **configs**(`class IndexerPrologQuantConfigs`):表示tile切分配置。 | ||
| 182 | - | ||
| 183 | -## 返回值说明 | ||
| 184 | - | ||
| 185 | -- **q_int8_out**(`Tensor`):公式中 query 的输出 tensor,不支持非连续的 Tensor,数据格式支持 ND,数据类型支持`int8`,shape为[t, idx_n_heads, idx_head_dim]。 | ||
| 186 | -- **q_scale_out**(`Tensor`):公式中 query 反量化因子的输出 tensor,不支持非连续的 Tensor,数据格式支持 ND,数据类型支持`float16`,shape为[t, idx_n_heads, 1]。 | ||
| 187 | -- **k_int8_out**(`Tensor`):表示 key 的缓存(k_cache)的输出 tensor,不支持非连续的 Tensor,数据格式支持 ND,cache_mode为"PA_BSND",数据类型支持`int8`,shape为[block_num, block_size, n_kv, idx_head_dim]。 | ||
| 188 | -- **k_scale_out**(`Tensor`):表示 key 反量化因子的缓存的输出 tensor,不支持非连续的 Tensor,cache_mode为"PA_BSND",数据格式支持 ND,数据类型支持`float16`,shape为[block_num, block_size, n_kv, 1]。 | ||
| 189 | -- **weights_out**(`Tensor`):公式中 weights 的输出 tensor,不支持非连续的 Tensor,数据格式支持 ND,数据类型支持`float16`,shape为[t, idx_n_heads]。 | ||
| 190 | - | ||
| 191 | -## 调用示例 | ||
| 192 | -- 算子源码执行参考[deepseekv32_lightning_indexer_prolog_quant.py](deepseekv32_lightning_indexer_prolog_quant.py) | ||
| 193 | - | ||
| 194 | - | ||
| 195 | -# sparse_flash_attention_quant | ||
| 196 | - | ||
| 197 | -## 功能说明 | ||
| 198 | - | ||
| 199 | -对于每个查询 token $\bold{x}_i$,索引模块会为每个键值缓存项(表示键值对或 MLA 潜在表示)计算一个相关性得分 $I_{i,j}$。然后,通过将注意力机制应用于查询 token $\bold{x}_i$ 以及得分最高的前 $k$ 个缓存项,来计算输出 $\bold{o}_i$: | ||
| 200 | - | ||
| 201 | -## 计算公式 | ||
| 202 | - | ||
| 203 | -$$ | ||
| 204 | -\bold{o}_i = \text{Attn}(\bold{x}_i, \{\bold{c}_j | j \in \text{Top-k}(\bold{I}_{i, :})\}) | ||
| 205 | -$$ | ||
| 206 | - | ||
| 207 | -## 函数原型 | ||
| 208 | - | ||
| 209 | -``` | ||
| 210 | -def sparse_flash_attention_quant_compute(query_nope, query_rope, key_nope_2d, key_rope_2d, k_nope_scales, | ||
| 211 | - topk_indices, block_table, kv_act_seqs, attention_out, nq, n_kv, softmax_scale, topk, block_size, | ||
| 212 | - max_blocknum_perbatch, tile_config): | ||
| 213 | -``` | ||
| 214 | - | ||
| 215 | -## 参数说明 | ||
| 216 | - | ||
| 217 | -- **query_nope**(`Tensor`):必选参数,表示MLA结构中的query的rope信息,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[t * n_q, kv_lora_rank]。 | ||
| 218 | -- **query_rope**(`Tensor`):必选参数,表示MLA结构中的query的nope信息,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[t * n_q, rope_dim]。 | ||
| 219 | -- **key_nope_2d**(`Tensor`):必选参数,表示MLA结构中的key的rope信息,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`int8`,shape为[block_num * block_size, kv_lora_rank]。 | ||
| 220 | -- **key_rope_2d**(`Tensor`):必选参数,表示MLA结构中的key的nope信息,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[block_num * block_size, rope_dim]。 | ||
| 221 | -- **k_nope_scales**(`Tensor`):必选参数,表示k_nope的反量化缩放因子,必选参数,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`float`,shape为[block_num * block_size, 4]。 | ||
| 222 | -- **topk_indices**(`Tensor`):必选参数,表示每个token选出的topk索引,必选参数,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`int32`,shape为[t, n_kv * selected_count]。 | ||
| 223 | -- **block_table**(`Tensor`):必选参数,表示PageAttention中KV存储使用的block映射表,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`int32`,shape为[b, s2_max/block_size],其中第二维表示长度不小于所有batch中最大的s2对应的block数量,即s2_max / block_size向上取整。 | ||
| 224 | -- **kv_act_seqs**(`Tensor`):必选参数,数据格式支持ND,表示不同Batch中`key`和`value`的有效token数,数据类型支持`int32`,shape为[b]。 | ||
| 225 | -- **nq**(`int`):必选参数,代表缩放系数,作为query和key矩阵乘后Muls的scalar值,数据类型支持float。 | ||
| 226 | -- **n_kv**(`int`):必选参数,代表缩放系数,作为query和key矩阵乘后Muls的scalar值,数据类型支持float。 | ||
| 227 | -- **softmax_scale**(`float`):必选参数,代表缩放系数,作为query和key矩阵乘后Muls的scalar值,数据类型支持float。 | ||
| 228 | -- **topk**(`int`):必选参数,代表选取的token个数,数据类型支持int。 | ||
| 229 | -- **block_size**(`int`):必选参数,代表sparse阶段的block大小,数据类型支持int。 | ||
| 230 | -- **max_blocknum_perbatch**(`int`):必选参数,每个batch最大的blocksize数量,数据类型支持int。 | ||
| 231 | -- **tile_config**(`class SaTileShapeConfig`):TileShapeConfig配置结构体,表示tile切分配置,配置项数据类型支持int。 | ||
| 232 | - | ||
| 233 | - | ||
| 234 | -## 返回值说明 | ||
| 235 | - | ||
| 236 | -- **attention_out**(`Tensor`):公式中的输出。数据格式支持ND,数据类型支持`bfloat16`,输出shape[b, s1, n_q, kv_lora_rank]。 | ||
| 237 | - | ||
| 238 | -## 调用示例 | ||
| 239 | - | ||
| 240 | -- 详见[deepseekv32_sparse_flash_attention_quant.py](deepseekv32_sparse_flash_attention_quant.py) | ||
| 241 | - | ||
| 242 | - | ||
| 243 | -# sparse_attention_antiquant | ||
| 244 | - | ||
| 245 | -## 功能说明 | ||
| 246 | - | ||
| 247 | -sa_antiquant是在sfa_quant基础上做的 存8算16 优化。在sfa_quant场景中,key_nope_2d,key_rope_2d 和 k_nope_scales 分别是 int8,bf16 和 fp32 类型;在后续 attention 的计算上,会离散地存储这三个 tensor,需要调三次离散访存指令去分别调用进行反量化和 concat;而 sa_antiquant 会将同一个 token 的 nope,rope 和 nope_scale 按尾轴合并在一起,仅需一条离散访存指令,总计可以节省 b * s * topk 次离散访存命令,节省搬运指令,提升搬运效率。 | ||
| 248 | - | ||
| 249 | -## 函数原型 | ||
| 250 | - | ||
| 251 | -``` | ||
| 252 | -def sparse_attention_antiquant_compute(query_nope, query_rope, nope_cache, topk_indices, block_table, | ||
| 253 | - kv_act_seqs, attention_out, nq, n_kv, softmax_scale, topk, block_size, max_blocknum_perbatch, | ||
| 254 | - tile_config): | ||
| 255 | -``` | ||
| 256 | - | ||
| 257 | -## 参数说明 | ||
| 258 | - | ||
| 259 | -- **query_nope**(`Tensor`):必选参数,表示MLA结构中的query的rope信息,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[t * n_q, kv_lora_rank]。 | ||
| 260 | -- **query_rope**(`Tensor`):必选参数,表示MLA结构中的query的nope信息,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[t * n_q, rope_dim]。 | ||
| 261 | -- **nope_cache**(`Tensor`):必选参数,表示MLA结构中的key的反量化缩放因子,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`int8`,shape为[block_num * block_size, kv_lora_rank + rope_dim * 2 + 4 * scale_size],其中scale_size=4。 | ||
| 262 | -- **topk_indices**(`Tensor`):必选参数,表示每个token选出的topk索引,必选参数,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`int32`,shape为[t, n_kv * selected_count]。 | ||
| 263 | -- **block_table**(`Tensor`):必选参数,表示PageAttention中KV存储使用的block映射表,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`int32`,shape为[b, s2_max/block_size],其中第二维表示长度不小于所有batch中最大的s2对应的block数量,即s2_max / block_size向上取整。 | ||
| 264 | -- **kv_act_seqs**(`Tensor`):必选参数,数据格式支持ND,表示不同Batch中`key`和`value`的有效token数,数据类型支持`int32`,shape为[b]。 | ||
| 265 | -- **nq**(`int`):必选参数,代表缩放系数,作为query和key矩阵乘后Muls的scalar值,数据类型支持float。 | ||
| 266 | -- **n_kv**(`int`):必选参数,代表缩放系数,作为query和key矩阵乘后Muls的scalar值,数据类型支持float。 | ||
| 267 | -- **softmax_scale**(`float`):必选参数,代表缩放系数,作为query和key矩阵乘后Muls的scalar值,数据类型支持float。 | ||
| 268 | -- **topk**(`int`):必选参数,代表选取的token个数,数据类型支持int。 | ||
| 269 | -- **block_size**(`int`):必选参数,代表sparse阶段的block大小,数据类型支持int。 | ||
| 270 | -- **max_blocknum_perbatch**(`int`):必选参数,每个batch最大的blocksize数量,数据类型支持int。 | ||
| 271 | -- **tile_config**(`class SaTileShapeConfig`):TileShapeConfig配置结构体,表示tile切分配置,配置项数据类型支持int。 | ||
| 272 | - | ||
| 273 | - | ||
| 274 | -## 返回值说明 | ||
| 275 | - | ||
| 276 | -- **attention_out**(`Tensor`):公式中的输出。数据格式支持ND,数据类型支持`bfloat16`,输出shape[b * s1 * n_q, kv_lora_rank]。 | ||
| 277 | - | ||
| 278 | -## 调用示例 | ||
| 279 | - | ||
| 280 | -- 详见[deepseekv32_sparse_attention_antiquant.py](deepseekv32_sparse_attention_antiquant.py) | ||
| 281 | - | ||
| 282 | - | ||
| 283 | -# mla_indexer_polog_quant | ||
| 284 | - | ||
| 285 | -## 功能说明 | ||
| 286 | - | ||
| 287 | -MLA Indexer Prolog 模块将MLA Prolog和Lightning Indexer Prolog两个算子进行了更大范围的融合,实现了算子间的流水并行,提升了算子的性能。 | ||
| 288 | - | ||
| 289 | -## 函数原型 | ||
| 290 | -``` | ||
| 291 | -def mla_indexer_prolog_quant_compute( | ||
| 292 | - token_x, mla_w_dq, mla_w_uq_qr, mla_dequant_scale, mla_w_uk, mla_w_dkv_kr, mla_gamma_cq, | ||
| 293 | - mla_gamma_ckv, cos, sin, cache_index, mla_kv_cache, mla_kr_cache, | ||
| 294 | - mla_k_scale_cache, ip_w_qb_in, ip_w_qb_scale_in, ip_wk_in, ip_w_proj_in, | ||
| 295 | - ip_ln_gamma_k_in, ip_ln_beta_k_in, ip_hadamard_q_in, ip_hadamard_k_in, | ||
| 296 | - ip_k_cache, ip_k_cache_scale, mla_query_nope_out, mla_query_rope_out, | ||
| 297 | - mla_q_norm_out, mla_q_norm_scale_out, mla_kv_cache_out, mla_kr_cache_out, | ||
| 298 | - mla_k_scale_cache_out, ip_q_int8_out, ip_q_scale_out, ip_k_int8_out, | ||
| 299 | - ip_k_scale_out, ip_weights_out, mla_epsilon_cq, mla_epsilon_ckv, | ||
| 300 | - mla_cache_mode, mla_tile_config, | ||
| 301 | - ip_attrs, ip_configs, rope_cfg | ||
| 302 | -): | ||
| 303 | -``` | ||
| 304 | - | ||
| 305 | -## 参数说明 | ||
| 306 | - | ||
| 307 | -- **token_x**(`Tensor`):公式中用于计算Query和Key的输入tensor,不支持非连续的 Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[t, h]。 | ||
| 308 | -- **mla_w_dq**(`Tensor`):公式中用于计算Query的下采样权重矩阵$W^{DQ}$,不支持非连续的 Tensor。数据格式支持NZ,数据类型支持`bfloat16`,shape为[h, q_lora_rank]。 | ||
| 309 | -- **mla_w_uq_qr**(`Tensor`):公式中用于计算Query的上采样权重矩阵$W^{UQ}$和位置编码权重矩阵$W^{QR}$。不支持非连续,数据格式支持NZ,数据类型支持`int8`,shape为[q_lora_rank, n_q*q_head_dim]。 | ||
| 310 | -- **mla_dequant_scale**(`Tensor`):用于MatmulQcQr矩阵乘后w_uq_qr反量化操作的per-channel参数,不支持非连续的 Tensor。数据格式支持ND,数据类型支持`float`,shape为[n_q*q_head_dim, 1]。 | ||
| 311 | -- **mla_w_uk**(`Tensor`):公式中用于计算Key的上采样权重$W^{UK}$。不支持非连续,数据格式支持ND,数据类型支持`bfloat16`,shape为[n_q, qk_nope_head_dim, kv_lora_rank]。 | ||
| 312 | -- **mla_w_dkv_kr**(`Tensor`):公式中用于计算Key的下采样权重矩阵$W^{DKV}$和位置编码权重矩阵$W^{KR}$。不支持非连续,数据格式支持NZ,数据类型支持`bfloat16`,shape为[h, kv_lora_rank+rope_dim]。 | ||
| 313 | -- **mla_gamma_cq**(`Tensor`):计算$c^Q$的RmsNorm公式中的$\gamma$参数。不支持非连续,数据格式支持ND,数据类型支持`bfloat16`,shape为[q_lora_rank]。 | ||
| 314 | -- **mla_gamma_ckv**(`Tensor`):计算$c^{KV}$的RmsNorm公式中的$\gamma$参数。不支持非连续,数据格式支持ND,数据类型支持`bfloat16`,shape为[kv_lora_rank]。 | ||
| 315 | -- **cos**(`Tensor`):用于计算旋转位置编码的余弦参数矩阵。不支持非连续,数据格式支持ND,数据类型支持`bfloat16`,shape为[t, rope_dim]。 | ||
| 316 | -- **sin**(`Tensor`):用于计算旋转位置编码的正弦参数矩阵。不支持非连续,数据格式支持ND,数据类型支持`bfloat16`,shape为[t, rope_dim]。 | ||
| 317 | -- **cache_index**(`Tensor`):用于存储kv_cache和kr_cache的索引。不支持非连续,数据格式支持ND,数据类型支持`int64`,shape为[T]。 | ||
| 318 | -- **mla_kv_cache**(`Tensor`):用于cache索引的aclTensor,计算结果原地更新(对应公式中的$k^C$),不支持非连续的 Tensor。数据格式支持ND,cache_mode为"PA_BSND",数据类型支持`int8`,cache_mode为"PA_BSND"、shape为[block_num, block_size, n_kv, kv_lora_rank]。 | ||
| 319 | -- **mla_kr_cache**(`Tensor`):用于key位置编码的cache,计算结果原地更新(对应公式中的$k^R$),不支持非连续的 Tensor。数据格式支持ND,cache_mode为"PA_BSND",数据类型支持`bfloat16`,cache_mode为"PA_BSND"、shape为[block_num, block_size, n_kv, rope_dim]。 | ||
| 320 | -- **mla_k_scale_cache**(`Tensor`):表示 key 反量化因子的缓存,必选参数,不支持非连续的 Tensor,数据格式支持 ND,cache_mode为"PA_BSND",数据类型支持`float`,shape为[block_num, block_size, n_kv, 4]。 | ||
| 321 | -- **ip_w_qb_in**(`Tensor`):表示 query 的权重,必选参数,不支持非连续的Tensor,数据格式支持NZ,数据类型支持`int8`,shape为[q_lora_rank, idx_n_heads*idx_head_dim]。 | ||
| 322 | -- **ip_w_qb_scale_in**(`Tensor`):表示 query 的权重反量化因子,必选参数,不支持非连续的Tensor,数据格式支持ND,数据类型支持`float32`,shape为[idx_n_heads*idx_head_dim, 1]。 | ||
| 323 | -- **ip_wk_in**(`Tensor`):表示 key 的权重,必选参数,不支持非连续的Tensor,数据格式支持NZ,数据类型支持`bfloat16`,shape为[h, idx_head_dim]。 | ||
| 324 | -- **ip_w_proj_in**(`Tensor`):表示 weights 的权重,必选参数,不支持非连续的Tensor,数据格式支持NZ,数据类型支持`bfloat16`,shape为[h, idx_n_heads]。 | ||
| 325 | -- **ip_ln_gamma_k_in**(`Tensor`):表示 key 的 layernorm 缩放,必选参数,不支持非连续的Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[idx_head_dim]。 | ||
| 326 | -- **ip_ln_beta_k_in**(`Tensor`):表示 key 的 layernorm 偏移,必选参数,不支持非连续的Tensor,数据格式支持ND,数据类型支持`bfloat16`,shape为[idx_head_dim]。 | ||
| 327 | -- **ip_hadamard_q_in**(`Tensor`):表示用于 query Hadamard 变换的权重矩阵,不支持非连续的 Tensor,数据格式支持 ND,数据类型支持`bfloat16`,shape为[idx_head_dim, idx_head_dim]。 | ||
| 328 | -- **ip_hadamard_k_in**(`Tensor`):表示用于 key Hadamard 变换的权重矩阵,不支持非连续的 Tensor,数据格式支持 ND,数据类型支持`bfloat16`,shape为[idx_head_dim, idx_head_dim]。 | ||
| 329 | -- **ip_k_cache**(`Tensor`):表示 key 的缓存,必选参数,不支持非连续的 Tensor,数据格式支持 ND,数据类型支持`int8`,cache_mode为"PA_BSND",shape为[block_num, block_size, n_kv, idx_head_dim]。 | ||
| 330 | -- **ip_k_cache_scale**(`Tensor`):表示 key 反量化因子的缓存,必选参数,不支持非连续的 Tensor,数据格式支持 ND,cache_mode为"PA_BSND",数据类型支持`float16`,shape为[block_num, block_size, n_kv, 1]。 | ||
| 331 | -- **mla_epsilon_cq**(`float`):计算$c^Q$的RmsNorm公式中的$\epsilon$参数。用户未特意指定时,建议传入1e-05,仅支持double类型,默认值为1e-05。 | ||
| 332 | -- **mla_epsilon_ckv**(`float`):计算$c^{KV}$的RmsNorm公式中的$\epsilon$参数。用户未特意指定时,建议传入1e-05,仅支持double类型,默认值为1e-05。 | ||
| 333 | -- **mla_cache_mode**(`str`):表示kv_cache的模式,支持"PA_BSND" | ||
| 334 | -- **mla_tile_config**(`class MlaTileConfig`):表示mla子图的tile切分配置。 | ||
| 335 | -- **ip_attrs**(`class IndexerPrologQuantAttr`):lightning indexer prolog子图计算所需的属性值,包括layernorm_epsilon_k,layout\_query,layout\_key | ||
| 336 | -- **ip.layernorm_epsilon_k**(`float`):表示 key layernorm 防除 0 系数,必选参数,数据类型支持`float32`。 | ||
| 337 | -- **ip.layout_query**(`str`):可选参数,用于标识输入`query`的数据排布格式,默认值"TND"。当前仅支持 "TND"。 | ||
| 338 | -- **ip.layout_key**(`str`):可选参数,用于标识输入`key`的数据排布格式,默认值"PA_BSND"。当前仅支持 "PA_BSND"。 | ||
| 339 | -- **ip_config**(`class IndexerPrologQuantConfigs`):表示ip子图的tile切分配置及动态分档配置。 | ||
| 340 | -- **rope_cfg**(`class RopeTileShapeConfig`):表示rope子图的tile切分配置及动态分档配置。 | ||
| 341 | - | ||
| 342 | -## 返回值说明 | ||
| 343 | -- **mla_query_nope_out**(`Tensor`):公式中Query的输出tensor(对应$q^N$),不支持非连续的 Tensor。数据格式支持ND,数据类型支持`bfloat16`,shape为[t, n_q, kv_lora_rank]。 | ||
| 344 | -- **mla_query_rope_out**(`Tensor`):公式中Query位置编码的输出tensor(对应$q^R$),不支持非连续的 Tensor。数据格式支持ND,数据类型支持`bfloat16`,shape为[t, n_q, rope_dim]。 | ||
| 345 | -- **mla_q_norm_out**(`Tensor`):对公式中Query位置编码的输出tensor做rmsnorm转换并量化后的输出,不支持非连续的 Tensor。数据格式支持ND,数据类型支持`int8`,shape为[t, q_lora_rank]。 | ||
| 346 | -- **mla_q_norm_scale_out**(`Tensor`):对公式中Query位置编码的输出tensor做rmsnorm转换并量化后的反量化系数输出,不支持非连续的 Tensor。数据格式支持ND,数据类型支持`float32`,shape为[t, 1]。 | ||
| 347 | -- **mla_kv_cache_out**(`Tensor`):Key输出到`kv_cache`中的tensor(对应$k^C$),不支持非连续的 Tensor。数据格式支持ND,cache_mode为"PA_BSND",数据类型支持`int8`,shape为[block_num, block_size, n_kv, kv_lora_rank]。 | ||
| 348 | -- **mla_kr_cache_out**(`Tensor`):Key的位置编码输出到`kr_cache`中的tensor(对应$k^R$),不支持非连续的 Tensor。数据格式支持ND,cache_mode为"PA_BSND",数据类型支持`bfloat16`,shape为[block_num, block_size, n_kv, qk_rope_dim]。 | ||
| 349 | -- **mla_k_scale_cache_out**(`Tensor`):Key做反量化后输出的反量化参数,不支持非连续的 Tensor。数据格式支持ND,cache_mode为"PA_BSND",数据类型支持`float`,shape为[block_num, block_size, n_kv, 4]。 | ||
| 350 | -- **ip_q_int8_out**(`Tensor`):公式中 query 的输出 tensor,数据格式支持 ND,数据类型支持`int8`,shape为[t, idx_n_heads, idx_head_dim]。 | ||
| 351 | -- **ip_q_scale_out**(`Tensor`):公式中 query 反量化因子的输出 tensor,不支持非连续的 Tensor,数据格式支持 ND,数据类型支持`float16`,shape为[t, idx_n_heads, 1]。 | ||
| 352 | -- **ip_k_int8_out**(`Tensor`):表示 key 的缓存(k_cache)的输出 tensor,不支持非连续的 Tensor,数据格式支持 ND,cache_mode为"PA_BSND",数据类型支持`int8`,shape为[block_num, block_size, n_kv, idx_head_dim]。 | ||
| 353 | -- **ip_k_scale_out**(`Tensor`):表示 key 反量化因子的缓存的输出 tensor,不支持非连续的 Tensor,数据格式支持 ND,cache_mode为"PA_BSND",数据类型支持`float16`,shape为[block_num, block_size, n_kv, 1]。 | ||
| 354 | -- **ip_weights_out**(`Tensor`):公式中 weights 的输出 tensor,不支持非连续的 Tensor,数据格式支持 ND,数据类型支持`float16`,shape为[t, idx_n_heads]。 | ||
| 355 | - | ||
| 356 | -## 调用示例 | ||
| 357 | - | ||
| 358 | -- 详见 [deepseekv32_mla_indexer_prolog_quant.py](deepseekv32_mla_indexer_prolog_quant.py) | ||
| 359 | - | ||
| 360 | -# lightning indexer | ||
| 361 | - | ||
| 362 | -## 功能说明 | ||
| 363 | - | ||
| 364 | -LightningIndexer基于一系列操作得到每一个 token 对应的 Top-$k$ 个位置。对于某个 token 对应的 Index Query $Q_{index}\in\R^{g\times d}$,给定上下文 Index Key $K_{index}\in\R^{S_{k}\times d},W\in\R^{g\times 1}$,其中 $g$ 为 GQA 对应的 group size,$d$ 为每一个头的维度,$S_{k}$ 是上下文的长度,LightningIndexer的具体计算公式如下: | ||
| 365 | -$$ | ||
| 366 | -\text{Top-}k\left\{[1]_{1\times g}@\left[(W@[1]_{1\times S_{k}})\odot\text{ReLU}\left(Q_{index}@K_{index}^T\right)\right]\right\} | ||
| 367 | -$$ | ||
| 368 | - | ||
| 369 | -## 函数原型 | ||
| 370 | - | ||
| 371 | -``` | ||
| 372 | -def lightning_indexer_decode_compute( | ||
| 373 | - idx_query, idx_query_scale, idx_key_cache, idx_key_scale, idx_weight, act_seq_key, block_table, topk_res, | ||
| 374 | - unroll_list, configs, selected_count): | ||
| 375 | -``` | ||
| 376 | - | ||
| 377 | -## 参数说明 | ||
| 378 | - | ||
| 379 | -- **idx_query**(`Tensor`):必选参数,不支持非连续,数据格式支持ND,数据类型支持`int8`,shape为[t, n_q, idx_head_dim]。 | ||
| 380 | -- **idx_query_scale**(`Tensor`):必选参数,表示idx_query的缩放系数,数据格式支持ND,数据类型支持`float16`,shape为[t, n_q, idx_head_dim]。 | ||
| 381 | -- **idx_key_cache**(`Tensor`):必选参数,不支持非连续,数据格式支持ND,数据类型支持`int8`,shape为[t, n_kv, idx_head_dim]。 | ||
| 382 | -- **idx_key_scale**(`Tensor`):必选参数,表示idx_key_cache的缩放系数,数据格式支持ND,数据类型支持`float16`,shape为[t, n_kv, idx_head_dim] | ||
| 383 | -- **idx_weight**(`Tensor`):必选参数,不支持非连续,数据格式支持ND,数据类型支持`float16`,支持输入shape[t, n_q]。 | ||
| 384 | -- **act_seq_key**(`Tensor`):必选参数,表示不同Batch中`key`的有效token数,数据类型支持`int32`, shape为[b]。 | ||
| 385 | -- **block_table**(`Tensor`):必选参数,表示PageAttention中KV存储使用的block映射表,数据格式支持ND,数据类型支持`int32`,shape为[b, ceilDiv(max(s2), block_size)], 其中max(s2)为s2中最大值, ceilDiv表示向上取整。 | ||
| 386 | -- **unroll_list**(`List`):非必选参数,表示多档位切分配置。 | ||
| 387 | -- **configs**(`class LightningIndexerConfigs`):非必选参数,LightningIndexerConfigs配置结构体,表示tile切分配置和优化选项。 | ||
| 388 | -- **selected_count**(`int`):必选参数,topk选择数量,默认为2048。 | ||
| 389 | - | ||
| 390 | -## 返回值说明 | ||
| 391 | - | ||
| 392 | -- **topk_res**(`Tensor`):公式中的输出,数据类型支持`int32`。数据格式支持ND,输出shape[t, n_kv, selected_count]。 | ||
| 393 | - | ||
| 394 | -## 调用示例 | ||
| 395 | - | ||
| 396 | -- 详见[deepseekv32_lightning_indexer_quant.py](deepseekv32_lightning_indexer_quant.py) | ||
| @@ -1,393 +0,0 @@ | |||
| 1 | -# DeepSeek V3.2 Examples | ||
| 2 | - | ||
| 3 | -This directory contains a series of PyPTO DeepSeek V3.2 EXP development sample code. We have decomposed DeepSeek-V3.2-Exp and delivered five operators: mla prolog, lightning indexer prolog, sparse flash attention, mla_indexer_prolog, and lightning indexer. | ||
| 4 | - | ||
| 5 | -## Parameter Description/Constraints | ||
| 6 | -- Shape format field meaning description | ||
| 7 | - | Field Name | English Full Name/Meaning | Value Rules and Description | | ||
| 8 | - |---------------|---------------------------------------------|----------------------------------------------------------------------------------------------| | ||
| 9 | - | b | Batch (input sample batch size) | Range: decode scenario 1 to 128, prefill scenario fixed to 1 | | ||
| 10 | - | s1 | Query Seq-Length | Range: decode scenario 1 to 4, prefill scenario 1 to 1K | | ||
| 11 | - | s2 | Key Seq-Length | Range: 1 to 128K | | ||
| 12 | - | h | Head-Size (hidden layer size) | Fixed value: 7168 | | ||
| 13 | - | n_q(n1) | Query Head-Num (multi-head count) | Range: 128 | | ||
| 14 | - | n_kv(n2) | KV Head-Num | Range: 1 | | ||
| 15 | - | kv_lora_rank | KV low-rank matrix dimension | Range: 512 | | ||
| 16 | - | rope_dim | QK position encoding dimension | Range: 64 | | ||
| 17 | - | v_head_dim | Value head dimension | Range: 128 | | ||
| 18 | - | q_head_dim | Query head dimension | Range: 192 | | ||
| 19 | - | q_lora_rank | Query low-rank matrix dimension | Range: 1536 | | ||
| 20 | - | idx_n_heads | Indexer query head num | Fixed value: 64 | | ||
| 21 | - | idx_head_dim | Indexer query head dimension | Fixed value: 128 | | ||
| 22 | - | selected_count| Topk selected count | Fixed value: 2048 | | ||
| 23 | - | block_num | Number of per-tile blocks in PagedAttention scenario | Computed as `ceil(B*Skv/BlockSize)` (Skv represents the KV sequence length, allows 0) | | ||
| 24 | - | block_size | Block size in PagedAttention scenario | Range: 128 | | ||
| 25 | - | t | Size after BS axis merge | Range: b * s1| | ||
| 26 | - | ||
| 27 | -# mla_prolog_quant | ||
| 28 | - | ||
| 29 | -## Function Description | ||
| 30 | - | ||
| 31 | -The MLA Prolog module transforms the hidden state $\bold{X}$ into the query projection $\bold{q}$, key projection $\bold{k}$, and value projection $\bold{v}$, with a structure consistent with DeepSeek V3 architecture. In the decode phase, it uses weight absorption technology. | ||
| 32 | - | ||
| 33 | -## Computation Formulas | ||
| 34 | - | ||
| 35 | -**RmsNorm Formula** | ||
| 36 | -$$ | ||
| 37 | -\text{RmsNorm}(x) = \gamma \cdot \frac{x_i}{\text{RMS}(x)} | ||
| 38 | -$$ | ||
| 39 | -$$ | ||
| 40 | -\text{RMS}(x) = \sqrt{\frac{1}{N} \sum_{i=1}^{N} x_i^2 + \epsilon} | ||
| 41 | -$$ | ||
| 42 | - | ||
| 43 | -**Path 1: Standard Query Computation** | ||
| 44 | - | ||
| 45 | -Includes down-projection, RmsNorm, and two up-projections: | ||
| 46 | -$$ | ||
| 47 | -c^Q = RmsNorm(x \cdot W^{DQ}) | ||
| 48 | -$$ | ||
| 49 | -$$ | ||
| 50 | -q^C = c^Q \cdot W^{UQ} | ||
| 51 | -$$ | ||
| 52 | -$$ | ||
| 53 | -q^N = q^C \cdot W^{UK} | ||
| 54 | -$$ | ||
| 55 | - | ||
| 56 | -**Path 2: Positional Encoding Query Computation** | ||
| 57 | - | ||
| 58 | -Applies ROPE rotary position encoding to the Query: | ||
| 59 | -$$ | ||
| 60 | -q^R = ROPE(c^Q \cdot W^{QR}) | ||
| 61 | -$$ | ||
| 62 | - | ||
| 63 | -**Path 3: Standard Key Computation** | ||
| 64 | - | ||
| 65 | -Includes down-projection and RmsNorm, stores the result in cache: | ||
| 66 | -$$ | ||
| 67 | -c^{KV} = RmsNorm(x \cdot W^{DKV}) | ||
| 68 | -$$ | ||
| 69 | -$$ | ||
| 70 | -k^C = Cache(c^{KV}) | ||
| 71 | -$$ | ||
| 72 | - | ||
| 73 | -**Path 4: Positional Encoding Key Computation** | ||
| 74 | - | ||
| 75 | -Applies ROPE rotary position encoding to the Key and stores the result in cache: | ||
| 76 | -$$ | ||
| 77 | -k^R = Cache(ROPE(x \cdot W^{KR})) | ||
| 78 | -$$ | ||
| 79 | - | ||
| 80 | -## Function Prototype | ||
| 81 | -``` | ||
| 82 | -def mla_prolog_quant_compute(token_x, w_dq, w_uq_qr, dequant_scale, w_uk, w_dkv_kr, gamma_cq, gamma_ckv, cos, | ||
| 83 | - sin, cache_index, kv_cache, kr_cache, k_scale_cache, q_norm_out, q_norm_scale_out, query_nope_out, | ||
| 84 | - query_rope_out, kv_cache_out, kr_cache_out, k_scale_cache_out, epsilon_cq, epsilon_ckv, cache_mode, | ||
| 85 | - tile_config, rope_cfg): | ||
| 86 | -``` | ||
| 87 | - | ||
| 88 | -## Parameter Description | ||
| 89 | - | ||
| 90 | -- **token_x** (`Tensor`): Input tensor used to compute Query and Key. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t, h]. | ||
| 91 | -- **w_dq** (`Tensor`): Down-projection weight matrix $W^{DQ}$ for Query computation. Does not support non-contiguous tensors. Data format supports NZ. Data type supports `bfloat16`. Shape is [h, q_lora_rank]. | ||
| 92 | -- **w_uq_qr** (`Tensor`): Up-projection weight matrix $W^{UQ}$ and positional encoding weight matrix $W^{QR}$ for Query computation. Does not support non-contiguous tensors. Data format supports NZ. Data type supports `int8`. Shape is [q_lora_rank, n_q * q_head_dim]. | ||
| 93 | -- **dequant_scale** (`Tensor`): Per-channel parameter for dequantizing w_uq_qr after MatmulQcQr matrix multiplication. Does not support non-contiguous tensors. Data format supports ND. Data type supports `float`. Shape is [n_q*q_head_dim, 1]. | ||
| 94 | -- **w_uk** (`Tensor`): Up-projection weight $W^{UK}$ for Key computation. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [n_q, qk_nope_head_dim, kv_lora_rank]. | ||
| 95 | -- **w_dkv_kr** (`Tensor`): Down-projection weight matrix $W^{DKV}$ and positional encoding weight matrix $W^{KR}$ for Key computation. Does not support non-contiguous tensors. Data format supports NZ. Data type supports `bfloat16`. Shape is [h, kv_lora_rank+rope_dim]. | ||
| 96 | -- **gamma_cq** (`Tensor`): $\gamma$ parameter in the RmsNorm formula for computing $c^Q$. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [q_lora_rank]. | ||
| 97 | -- **gamma_ckv** (`Tensor`): $\gamma$ parameter in the RmsNorm formula for computing $c^{KV}$. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [kv_lora_rank]. | ||
| 98 | -- **cos** (`Tensor`): Cosine parameter matrix for rotary position encoding. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t, rope_dim]. | ||
| 99 | -- **sin** (`Tensor`): Sine parameter matrix for rotary position encoding. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t, rope_dim]. | ||
| 100 | -- **cache_index** (`Tensor`): Index for storing kv_cache and kr_cache. Does not support non-contiguous tensors. Data format supports ND. Data type supports `int64`. Shape is [t]. | ||
| 101 | -- **kv_cache** (`Tensor`): aclTensor for cache index, updated in place (corresponding to $k^C$ in the formula). Does not support non-contiguous tensors. Data format supports ND. Data type supports `int8`. cache_mode is "PA_BSND". Shape is [block_num, block_size, n_kv, kv_lora_rank]. | ||
| 102 | -- **kr_cache** (`Tensor`): Cache for key positional encoding, updated in place (corresponding to $k^R$ in the formula). Does not support non-contiguous tensors. Data format supports ND. cache_mode is "PA_BSND". Data type supports `bfloat16`. Shape is [block_num, block_size, n_kv, rope_dim]. | ||
| 103 | -- **k_scale_cache** (`Tensor`): Cache for key dequantization factors. Required parameter. Does not support non-contiguous tensors. Data format supports ND. cache_mode is "PA_BSND". Data type supports `float`. Shape is [block_num, block_size, n_kv, 4]. | ||
| 104 | -- **epsilon_cq** (`float`): $\epsilon$ parameter in the RmsNorm formula for computing $c^Q$. If the user does not specify, the recommended value is 1e-05. Supports double type only. Default value is 1e-05. | ||
| 105 | -- **epsilon_ckv** (`float`): $\epsilon$ parameter in the RmsNorm formula for computing $c^{KV}$. If the user does not specify, the recommended value is 1e-05. Supports double type only. Default value is 1e-05. | ||
| 106 | -- **cache_mode** (`str`): KV cache mode. Supports "PA_BSND". | ||
| 107 | -- **tile_config** (`class MlaTileConfig`): Tile split configuration. | ||
| 108 | -- **rope_cfg** (`class RopeTileShapeConfig`): Rope tile split configuration. | ||
| 109 | - | ||
| 110 | -## Return Value Description | ||
| 111 | -- **q_norm_out** (`Tensor`): Output tensor after RmsNorm_cq on Query (corresponding to $q^C$). Does not support non-contiguous tensors. Data format supports ND. Data type supports `int8`. Shape is [t, q_lora_rank]. | ||
| 112 | -- **q_norm_scale_out** (`Tensor`): Dequantization parameter after RmsNorm_cq on Query. Does not support non-contiguous tensors. Data format supports ND. Data type supports `float`. Shape is [t, 1]. | ||
| 113 | -- **q_nope_out** (`Tensor`): Output tensor of Query in the formula (corresponding to $q^N$). Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t, n_q, kv_lora_rank]. | ||
| 114 | -- **q_rope_out** (`Tensor`): Output tensor of Query positional encoding in the formula (corresponding to $q^R$). Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t, n_q, rope_dim]. | ||
| 115 | -- **kv_cache_out** (`Tensor`): Tensor output of Key to `kv_cache` (corresponding to $k^C$). Does not support non-contiguous tensors. Data format supports ND. cache_mode is "PA_BSND". Data type supports `int8`. Shape is [block_num, block_size, n_kv, kv_lora_rank]. | ||
| 116 | -- **kr_cache_out** (`Tensor`): Tensor output of Key positional encoding to `kr_cache` (corresponding to $k^R$). Does not support non-contiguous tensors. Data format supports ND. cache_mode is "PA_BSND". Data type supports `bfloat16`. Shape is [block_num, block_size, n_kv, qk_rope_dim]. | ||
| 117 | -- **k_scale_cache_out** (`Tensor`): Dequantization parameter output after Key dequantization. Does not support non-contiguous tensors. Data format supports ND. Data type supports `float`. cache_mode is "PA_BSND". Shape is [block_num, block_size, n_kv, 4]. | ||
| 118 | - | ||
| 119 | -## Call Sample | ||
| 120 | - | ||
| 121 | -- For details, refer to [deepseekv32_mla_prolog_quant.py](deepseekv32_mla_prolog_quant.py). | ||
| 122 | - | ||
| 123 | -# lightning_indexer_prolog | ||
| 124 | -## Function Description | ||
| 125 | - | ||
| 126 | -Used in Deepseek IndexerAttention to compute the query, key, and weights required for Lightning Indexer. | ||
| 127 | -The quantization strategy for Indexer Prolog is as follows: Q_b_proj uses W8A8 quantization, and all other Linear layers do not use quantization. Query uses A8 quantization. Key (cache) uses C8 quantization. Dequantization factors are stored as FP16. Weights are stored as FP16. | ||
| 128 | - | ||
| 129 | -## Computation Formulas | ||
| 130 | -**Query Computation Formula:** | ||
| 131 | - | ||
| 132 | -The Q computation uses dynamic Per-Token-Head quantization, where the Hadamard transform is implemented by right-multiplying the matrix by hadamard_q. Both $\bold{q}$ and $\bold{w}_{qb}$ are of type Int8. | ||
| 133 | - | ||
| 134 | -$$ | ||
| 135 | -\bold{q}, \bold{q}_{scale} = \text{DynamicQuant}(\text{Hadamard}(\text{RoPE}(\text{DeQuant}(\bold{q} \cdot \bold{w}_{qb})))) | ||
| 136 | -$$ | ||
| 137 | - | ||
| 138 | -**Key(cache) Computation Formula:** | ||
| 139 | - | ||
| 140 | -The Cache computation also uses dynamic Per-Token-Head quantization, where the Hadamard transform is implemented by right-multiplying the matrix by hadamard_k. | ||
| 141 | - | ||
| 142 | -$$ | ||
| 143 | -\bold{k}, \bold{k}_{scale} = \text{DynamicQuant}(\text{Hadamard}(\text{RoPE}(\text{LayerNorm}(\bold{x} \cdot \bold{w}_k)))) | ||
| 144 | -$$ | ||
| 145 | - | ||
| 146 | -**Weights Computation Formula:** | ||
| 147 | - | ||
| 148 | -The Weights computation does not use quantization and must be converted to the FP16 data type for subsequent Lightning Indexer computation. | ||
| 149 | - | ||
| 150 | -$$ | ||
| 151 | -\bold{weight} = (\bold{x} \cdot \bold{w}_{proj}) * \text{scale} | ||
| 152 | -$$ | ||
| 153 | - | ||
| 154 | -## Function Prototype | ||
| 155 | - | ||
| 156 | -``` | ||
| 157 | -def lightning_indexer_prolog_quant_compute(x_in, q_norm_in, q_norm_scale_in, w_qb_in, w_qb_scale_in, wk_in, w_proj_in, | ||
| 158 | - ln_gamma_k_in, ln_beta_k_in, cos_idx_rope_in, sin_idx_rope_in, hadamard_q_in, hadamard_k_in, k_int8_in, k_scale_in, | ||
| 159 | - k_cache_index_in, q_int8_out, q_scale_out, k_int8_out, k_scale_out, weights_out, attrs, configs): | ||
| 160 | -``` | ||
| 161 | - | ||
| 162 | -## Parameter Description | ||
| 163 | - | ||
| 164 | -- **x_in** (`Tensor`): Hidden state token. Required parameter. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t, h]. | ||
| 165 | -- **q_norm_in** (`Tensor`): Quantized query after rmsnorm. Required parameter. Does not support non-contiguous tensors. Data format supports ND. Data type supports `int8`. Shape is [t, q_lora_rank]. | ||
| 166 | -- **q_norm_scale_in** (`Tensor`): Dequantization factor for query. Required parameter. Does not support non-contiguous tensors. Data format supports ND. Data type supports `float32`. Shape is [t, 1]. | ||
| 167 | -- **wq_b_in** (`Tensor`): Query weight. Required parameter. Does not support non-contiguous tensors. Data format supports NZ. Data type supports `int8`. Shape is [q_lora_rank, idx_n_heads*idx_head_dim]. | ||
| 168 | -- **wq_qb_scale_in** (`Tensor`): Weight dequantization factor for query. Required parameter. Does not support non-contiguous tensors. Data format supports ND. Data type supports `float32`. Shape is [idx_n_heads*idx_head_dim, 1]. | ||
| 169 | -- **wk_in** (`Tensor`): Key weight. Required parameter. Does not support non-contiguous tensors. Data format supports NZ. Data type supports `bfloat16`. Shape is [h, idx_head_dim]. | ||
| 170 | -- **w_proj_in** (`Tensor`): Weights weight. Required parameter. Does not support non-contiguous tensors. Data format supports NZ. Data type supports `bfloat16`. Shape is [h, idx_n_heads]. | ||
| 171 | -- **ln_gamma_k_in** (`Tensor`): Key layernorm scale. Required parameter. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [idx_head_dim]. | ||
| 172 | -- **ln_beta_k_in** (`Tensor`): Key layernorm shift. Required parameter. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [idx_head_dim]. | ||
| 173 | -- **cos_idx_rope_in** (`Tensor`): Cosine for RoPE. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t, rope_dim]. | ||
| 174 | -- **sin_idx_rope_in** (`Tensor`): Sine for RoPE. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t, rope_dim]. | ||
| 175 | -- **hadamard_q_in** (`Tensor`): Weight matrix for query Hadamard transform. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [idx_head_dim, idx_head_dim]. | ||
| 176 | -- **hadamard_k_in** (`Tensor`): Weight matrix for key Hadamard transform. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [idx_head_dim, idx_head_dim]. | ||
| 177 | -- **k_int8_in** (`Tensor`): Key cache (k_cache). Required parameter. Does not support non-contiguous tensors. Data format supports ND. cache_mode is "PA_BSND". Data type supports `int8`. Shape is [block_num, block_size, n_kv, idx_head_dim]. | ||
| 178 | -- **k_scale_in** (`Tensor`): Key dequantization factor cache. Required parameter. Does not support non-contiguous tensors. Data format supports ND. cache_mode is "PA_BSND". Data type supports `float16`. Shape is [block_num, block_size, n_kv, 1]. | ||
| 179 | -- **k_cache_index_in** (`Tensor`): Position for updating the key cache. Required parameter. Does not support non-contiguous tensors. Data format supports ND. Data type supports `int64`. Shape is [t]. | ||
| 180 | -- **attrs.layernorm_epsilon_k** (`float`): Key layernorm epsilon to prevent division by zero. Required parameter. Data type supports `float32`. | ||
| 181 | -- **attrs.layout_query** (`str`): Optional parameter identifying the data layout format of the input `query`. Default value is "TND". Currently supports only "TND". | ||
| 182 | -- **attrs.layout_key** (`str`): Optional parameter identifying the data layout format of the input `key`. Default value is "PA_BSND". Currently supports only "PA_BSND". | ||
| 183 | -- **configs** (`class IndexerPrologQuantConfigs`): Tile split configuration. | ||
| 184 | - | ||
| 185 | -## Return Value Description | ||
| 186 | - | ||
| 187 | -- **q_int8_out** (`Tensor`): Output tensor of query in the formula. Does not support non-contiguous tensors. Data format supports ND. Data type supports `int8`. Shape is [t, idx_n_heads, idx_head_dim]. | ||
| 188 | -- **q_scale_out** (`Tensor`): Output tensor of query dequantization factor in the formula. Does not support non-contiguous tensors. Data format supports ND. Data type supports `float16`. Shape is [t, idx_n_heads, 1]. | ||
| 189 | -- **k_int8_out** (`Tensor`): Output tensor of key cache (k_cache). Does not support non-contiguous tensors. Data format supports ND. cache_mode is "PA_BSND". Data type supports `int8`. Shape is [block_num, block_size, n_kv, idx_head_dim]. | ||
| 190 | -- **k_scale_out** (`Tensor`): Output tensor of key dequantization factor cache. Does not support non-contiguous tensors. cache_mode is "PA_BSND". Data format supports ND. Data type supports `float16`. Shape is [block_num, block_size, n_kv, 1]. | ||
| 191 | -- **weights_out** (`Tensor`): Output tensor of weights in the formula. Does not support non-contiguous tensors. Data format supports ND. Data type supports `float16`. Shape is [t, idx_n_heads]. | ||
| 192 | - | ||
| 193 | -## Call Sample | ||
| 194 | -- For operator source code execution, refer to [deepseekv32_lightning_indexer_prolog_quant.py](deepseekv32_lightning_indexer_prolog_quant.py). | ||
| 195 | - | ||
| 196 | -# sparse_flash_attention_quant | ||
| 197 | - | ||
| 198 | -## Function Description | ||
| 199 | - | ||
| 200 | -For each query token $\bold{x}_i$, the indexing module computes a relevance score $I_{i,j}$ for each key-value cache item (representing a key-value pair or MLA latent representation). It then computes the output $\bold{o}_i$ by applying the attention mechanism to the query token $\bold{x}_i$ and the top $k$ cache items with the highest scores: | ||
| 201 | - | ||
| 202 | -## Computation Formula | ||
| 203 | - | ||
| 204 | -$$ | ||
| 205 | -\bold{o}_i = \text{Attn}(\bold{x}_i, \{\bold{c}_j | j \in \text{Top-k}(\bold{I}_{i, :})\}) | ||
| 206 | -$$ | ||
| 207 | - | ||
| 208 | -## Function Prototype | ||
| 209 | - | ||
| 210 | -``` | ||
| 211 | -def sparse_flash_attention_quant_compute(query_nope, query_rope, key_nope_2d, key_rope_2d, k_nope_scales, | ||
| 212 | - topk_indices, block_table, kv_act_seqs, attention_out, nq, n_kv, softmax_scale, topk, block_size, | ||
| 213 | - max_blocknum_perbatch, tile_config): | ||
| 214 | -``` | ||
| 215 | - | ||
| 216 | -## Parameter Description | ||
| 217 | - | ||
| 218 | -- **query_nope** (`Tensor`): Required parameter. RoPE information of query in MLA structure. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t * n_q, kv_lora_rank]. | ||
| 219 | -- **query_rope** (`Tensor`): Required parameter. Nope information of query in MLA structure. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t * n_q, rope_dim]. | ||
| 220 | -- **key_nope_2d** (`Tensor`): Required parameter. RoPE information of key in MLA structure. Does not support non-contiguous tensors. Data format supports ND. Data type supports `int8`. Shape is [block_num * block_size, kv_lora_rank]. | ||
| 221 | -- **key_rope_2d** (`Tensor`): Required parameter. Nope information of key in MLA structure. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [block_num * block_size, rope_dim]. | ||
| 222 | -- **k_nope_scales** (`Tensor`): Required parameter. Dequantization scaling factor for k_nope. Does not support non-contiguous tensors. Data format supports ND. Data type supports `float`. Shape is [block_num * block_size, 4]. | ||
| 223 | -- **topk_indices** (`Tensor`): Required parameter. Topk index selected for each token. Does not support non-contiguous tensors. Data format supports ND. Data type supports `int32`. Shape is [t, n_kv * selected_count]. | ||
| 224 | -- **block_table** (`Tensor`): Required parameter. Block mapping table used for KV storage in PageAttention. Does not support non-contiguous tensors. Data format supports ND. Data type supports `int32`. Shape is [b, s2_max/block_size], where the second dimension indicates a length not less than the number of blocks corresponding to the largest s2 among all batches (that is, ceiling of s2_max / block_size). | ||
| 225 | -- **kv_act_seqs** (`Tensor`): Required parameter. Data format supports ND. Indicates the number of valid tokens for `key` and `value` in different batches. Data type supports `int32`. Shape is [b]. | ||
| 226 | -- **nq** (`int`): Required parameter. Scaling coefficient used as the scalar value for Muls after query and key matrix multiplication. Data type supports float. | ||
| 227 | -- **n_kv** (`int`): Required parameter. Scaling coefficient used as the scalar value for Muls after query and key matrix multiplication. Data type supports float. | ||
| 228 | -- **softmax_scale** (`float`): Required parameter. Scaling coefficient used as the scalar value for Muls after query and key matrix multiplication. Data type supports float. | ||
| 229 | -- **topk** (`int`): Required parameter. Number of selected tokens. Data type supports int. | ||
| 230 | -- **block_size** (`int`): Required parameter. Block size for the sparse phase. Data type supports int. | ||
| 231 | -- **max_blocknum_perbatch** (`int`): Required parameter. Maximum number of blocks per batch. Data type supports int. | ||
| 232 | -- **tile_config** (`class SaTileShapeConfig`): TileShapeConfig configuration structure. Represents tile split configuration. Configuration item data type supports int. | ||
| 233 | - | ||
| 234 | -## Return Value Description | ||
| 235 | - | ||
| 236 | -- **attention_out** (`Tensor`): Output in the formula. Data format supports ND. Data type supports `bfloat16`. Output shape is [b, s1, n_q, kv_lora_rank]. | ||
| 237 | - | ||
| 238 | -## Call Sample | ||
| 239 | - | ||
| 240 | -- For details, refer to [deepseekv32_sparse_flash_attention_quant.py](deepseekv32_sparse_flash_attention_quant.py). | ||
| 241 | - | ||
| 242 | -# sparse_attention_antiquant | ||
| 243 | - | ||
| 244 | -## Function Description | ||
| 245 | - | ||
| 246 | -sa_antiquant is an optimization based on sfa_quant that stores in 8-bit and computes in 16-bit. In the sfa_quant scenario, key_nope_2d, key_rope_2d, and k_nope_scales are of types int8, bf16, and fp32 respectively. During subsequent attention computation, these three tensors are stored discretely, requiring three discrete memory access instructions to separately dequantize and concatenate. In contrast, sa_antiquant merges the nope, rope, and nope_scale of the same token along the trailing axis, requiring only one discrete memory access instruction. This saves b * s * topk discrete memory access instructions in total, reducing load instructions and improving load efficiency. | ||
| 247 | - | ||
| 248 | -## Function Prototype | ||
| 249 | - | ||
| 250 | -``` | ||
| 251 | -def sparse_attention_antiquant_compute(query_nope, query_rope, nope_cache, topk_indices, block_table, | ||
| 252 | - kv_act_seqs, attention_out, nq, n_kv, softmax_scale, topk, block_size, max_blocknum_perbatch, | ||
| 253 | - tile_config): | ||
| 254 | -``` | ||
| 255 | - | ||
| 256 | -## Parameter Description | ||
| 257 | - | ||
| 258 | -- **query_nope** (`Tensor`): Required parameter. RoPE information of query in MLA structure. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t * n_q, kv_lora_rank]. | ||
| 259 | -- **query_rope** (`Tensor`): Required parameter. Nope information of query in MLA structure. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t * n_q, rope_dim]. | ||
| 260 | -- **nope_cache** (`Tensor`): Required parameter. Dequantization scaling factor for key in MLA structure. Does not support non-contiguous tensors. Data format supports ND. Data type supports `int8`. Shape is [block_num * block_size, kv_lora_rank + rope_dim * 2 + 4 * scale_size], where scale_size = 4. | ||
| 261 | -- **topk_indices** (`Tensor`): Required parameter. Topk index selected for each token. Does not support non-contiguous tensors. Data format supports ND. Data type supports `int32`. Shape is [t, n_kv * selected_count]. | ||
| 262 | -- **block_table** (`Tensor`): Required parameter. Block mapping table used for KV storage in PageAttention. Does not support non-contiguous tensors. Data format supports ND. Data type supports `int32`. Shape is [b, s2_max/block_size], where the second dimension indicates a length not less than the number of blocks corresponding to the largest s2 among all batches (that is, ceiling of s2_max / block_size). | ||
| 263 | -- **kv_act_seqs** (`Tensor`): Required parameter. Data format supports ND. Indicates the number of valid tokens for `key` and `value` in different batches. Data type supports `int32`. Shape is [b]. | ||
| 264 | -- **nq** (`int`): Required parameter. Scaling coefficient used as the scalar value for Muls after query and key matrix multiplication. Data type supports float. | ||
| 265 | -- **n_kv** (`int`): Required parameter. Scaling coefficient used as the scalar value for Muls after query and key matrix multiplication. Data type supports float. | ||
| 266 | -- **softmax_scale** (`float`): Required parameter. Scaling coefficient used as the scalar value for Muls after query and key matrix multiplication. Data type supports float. | ||
| 267 | -- **topk** (`int`): Required parameter. Number of selected tokens. Data type supports int. | ||
| 268 | -- **block_size** (`int`): Required parameter. Block size for the sparse phase. Data type supports int. | ||
| 269 | -- **max_blocknum_perbatch** (`int`): Required parameter. Maximum number of blocks per batch. Data type supports int. | ||
| 270 | -- **tile_config** (`class SaTileShapeConfig`): TileShapeConfig configuration structure. Represents tile split configuration. Configuration item data type supports int. | ||
| 271 | - | ||
| 272 | -## Return Value Description | ||
| 273 | - | ||
| 274 | -- **attention_out** (`Tensor`): Output in the formula. Data format supports ND. Data type supports `bfloat16`. Output shape is [b * s1 * n_q, kv_lora_rank]. | ||
| 275 | - | ||
| 276 | -## Call Sample | ||
| 277 | - | ||
| 278 | -- For details, refer to [deepseekv32_sparse_attention_antiquant.py](deepseekv32_sparse_attention_antiquant.py). | ||
| 279 | - | ||
| 280 | -# mla_indexer_prolog_quant | ||
| 281 | - | ||
| 282 | -## Function Description | ||
| 283 | - | ||
| 284 | -The MLA Indexer Prolog module fuses the MLA Prolog and Lightning Indexer Prolog operators at a larger scope, implementing pipeline parallelism between operators and improving operator performance. | ||
| 285 | - | ||
| 286 | -## Function Prototype | ||
| 287 | -``` | ||
| 288 | -def mla_indexer_prolog_quant_compute( | ||
| 289 | - token_x, mla_w_dq, mla_w_uq_qr, mla_dequant_scale, mla_w_uk, mla_w_dkv_kr, mla_gamma_cq, | ||
| 290 | - mla_gamma_ckv, cos, sin, cache_index, mla_kv_cache, mla_kr_cache, | ||
| 291 | - mla_k_scale_cache, ip_w_qb_in, ip_w_qb_scale_in, ip_wk_in, ip_w_proj_in, | ||
| 292 | - ip_ln_gamma_k_in, ip_ln_beta_k_in, ip_hadamard_q_in, ip_hadamard_k_in, | ||
| 293 | - ip_k_cache, ip_k_cache_scale, mla_query_nope_out, mla_query_rope_out, | ||
| 294 | - mla_q_norm_out, mla_q_norm_scale_out, mla_kv_cache_out, mla_kr_cache_out, | ||
| 295 | - mla_k_scale_cache_out, ip_q_int8_out, ip_q_scale_out, ip_k_int8_out, | ||
| 296 | - ip_k_scale_out, ip_weights_out, mla_epsilon_cq, mla_epsilon_ckv, | ||
| 297 | - mla_cache_mode, mla_tile_config, | ||
| 298 | - ip_attrs, ip_configs, rope_cfg | ||
| 299 | -): | ||
| 300 | -``` | ||
| 301 | - | ||
| 302 | -## Parameter Description | ||
| 303 | - | ||
| 304 | -- **token_x** (`Tensor`): Input tensor used to compute Query and Key. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t, h]. | ||
| 305 | -- **mla_w_dq** (`Tensor`): Down-projection weight matrix $W^{DQ}$ for Query computation. Does not support non-contiguous tensors. Data format supports NZ. Data type supports `bfloat16`. Shape is [h, q_lora_rank]. | ||
| 306 | -- **mla_w_uq_qr** (`Tensor`): Up-projection weight matrix $W^{UQ}$ and positional encoding weight matrix $W^{QR}$ for Query computation. Does not support non-contiguous tensors. Data format supports NZ. Data type supports `int8`. Shape is [q_lora_rank, n_q*q_head_dim]. | ||
| 307 | -- **mla_dequant_scale** (`Tensor`): Per-channel parameter for dequantizing w_uq_qr after MatmulQcQr matrix multiplication. Does not support non-contiguous tensors. Data format supports ND. Data type supports `float`. Shape is [n_q*q_head_dim, 1]. | ||
| 308 | -- **mla_w_uk** (`Tensor`): Up-projection weight $W^{UK}$ for Key computation. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [n_q, qk_nope_head_dim, kv_lora_rank]. | ||
| 309 | -- **mla_w_dkv_kr** (`Tensor`): Down-projection weight matrix $W^{DKV}$ and positional encoding weight matrix $W^{KR}$ for Key computation. Does not support non-contiguous tensors. Data format supports NZ. Data type supports `bfloat16`. Shape is [h, kv_lora_rank+rope_dim]. | ||
| 310 | -- **mla_gamma_cq** (`Tensor`): $\gamma$ parameter in the RmsNorm formula for computing $c^Q$. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [q_lora_rank]. | ||
| 311 | -- **mla_gamma_ckv** (`Tensor`): $\gamma$ parameter in the RmsNorm formula for computing $c^{KV}$. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [kv_lora_rank]. | ||
| 312 | -- **cos** (`Tensor`): Cosine parameter matrix for rotary position encoding. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t, rope_dim]. | ||
| 313 | -- **sin** (`Tensor`): Sine parameter matrix for rotary position encoding. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t, rope_dim]. | ||
| 314 | -- **cache_index** (`Tensor`): Index for storing kv_cache and kr_cache. Does not support non-contiguous tensors. Data format supports ND. Data type supports `int64`. Shape is [T]. | ||
| 315 | -- **mla_kv_cache** (`Tensor`): aclTensor for cache index, updated in place (corresponding to $k^C$ in the formula). Does not support non-contiguous tensors. Data format supports ND. cache_mode is "PA_BSND". Data type supports `int8`. Shape is [block_num, block_size, n_kv, kv_lora_rank]. | ||
| 316 | -- **mla_kr_cache** (`Tensor`): Cache for key positional encoding, updated in place (corresponding to $k^R$ in the formula). Does not support non-contiguous tensors. Data format supports ND. cache_mode is "PA_BSND". Data type supports `bfloat16`. Shape is [block_num, block_size, n_kv, rope_dim]. | ||
| 317 | -- **mla_k_scale_cache** (`Tensor`): Cache for key dequantization factors. Required parameter. Does not support non-contiguous tensors. Data format supports ND. cache_mode is "PA_BSND". Data type supports `float`. Shape is [block_num, block_size, n_kv, 4]. | ||
| 318 | -- **ip_w_qb_in** (`Tensor`): Query weight. Required parameter. Does not support non-contiguous tensors. Data format supports NZ. Data type supports `int8`. Shape is [q_lora_rank, idx_n_heads*idx_head_dim]. | ||
| 319 | -- **ip_w_qb_scale_in** (`Tensor`): Weight dequantization factor for query. Required parameter. Does not support non-contiguous tensors. Data format supports ND. Data type supports `float32`. Shape is [idx_n_heads*idx_head_dim, 1]. | ||
| 320 | -- **ip_wk_in** (`Tensor`): Key weight. Required parameter. Does not support non-contiguous tensors. Data format supports NZ. Data type supports `bfloat16`. Shape is [h, idx_head_dim]. | ||
| 321 | -- **ip_w_proj_in** (`Tensor`): Weights weight. Required parameter. Does not support non-contiguous tensors. Data format supports NZ. Data type supports `bfloat16`. Shape is [h, idx_n_heads]. | ||
| 322 | -- **ip_ln_gamma_k_in** (`Tensor`): Key layernorm scale. Required parameter. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [idx_head_dim]. | ||
| 323 | -- **ip_ln_beta_k_in** (`Tensor`): Key layernorm shift. Required parameter. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [idx_head_dim]. | ||
| 324 | -- **ip_hadamard_q_in** (`Tensor`): Weight matrix for query Hadamard transform. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [idx_head_dim, idx_head_dim]. | ||
| 325 | -- **ip_hadamard_k_in** (`Tensor`): Weight matrix for key Hadamard transform. Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [idx_head_dim, idx_head_dim]. | ||
| 326 | -- **ip_k_cache** (`Tensor`): Key cache. Required parameter. Does not support non-contiguous tensors. Data format supports ND. Data type supports `int8`. cache_mode is "PA_BSND". Shape is [block_num, block_size, n_kv, idx_head_dim]. | ||
| 327 | -- **ip_k_cache_scale** (`Tensor`): Key dequantization factor cache. Required parameter. Does not support non-contiguous tensors. Data format supports ND. cache_mode is "PA_BSND". Data type supports `float16`. Shape is [block_num, block_size, n_kv, 1]. | ||
| 328 | -- **mla_epsilon_cq** (`float`): $\epsilon$ parameter in the RmsNorm formula for computing $c^Q$. If the user does not specify, the recommended value is 1e-05. Supports double type only. Default value is 1e-05. | ||
| 329 | -- **mla_epsilon_ckv** (`float`): $\epsilon$ parameter in the RmsNorm formula for computing $c^{KV}$. If the user does not specify, the recommended value is 1e-05. Supports double type only. Default value is 1e-05. | ||
| 330 | -- **mla_cache_mode** (`str`): KV cache mode. Supports "PA_BSND". | ||
| 331 | -- **mla_tile_config** (`class MlaTileConfig`): Tile split configuration for the mla subgraph. | ||
| 332 | -- **ip_attrs** (`class IndexerPrologQuantAttr`): Attribute values required for lightning indexer prolog subgraph computation, including layernorm_epsilon_k, layout\_query, layout\_key. | ||
| 333 | -- **ip.layernorm_epsilon_k** (`float`): Key layernorm epsilon to prevent division by zero. Required parameter. Data type supports `float32`. | ||
| 334 | -- **ip.layout_query** (`str`): Optional parameter identifying the data layout format of the input `query`. Default value is "TND". Currently supports only "TND". | ||
| 335 | -- **ip.layout_key** (`str`): Optional parameter identifying the data layout format of the input `key`. Default value is "PA_BSND". Currently supports only "PA_BSND". | ||
| 336 | -- **ip_config** (`class IndexerPrologQuantConfigs`): Tile split configuration and dynamic binning configuration for the ip subgraph. | ||
| 337 | -- **rope_cfg** (`class RopeTileShapeConfig`): Tile split configuration and dynamic binning configuration for the rope subgraph. | ||
| 338 | - | ||
| 339 | -## Return Value Description | ||
| 340 | -- **mla_query_nope_out** (`Tensor`): Output tensor of Query in the formula (corresponding to $q^N$). Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t, n_q, kv_lora_rank]. | ||
| 341 | -- **mla_query_rope_out** (`Tensor`): Output tensor of Query positional encoding in the formula (corresponding to $q^R$). Does not support non-contiguous tensors. Data format supports ND. Data type supports `bfloat16`. Shape is [t, n_q, rope_dim]. | ||
| 342 | -- **mla_q_norm_out** (`Tensor`): Output after rmsnorm transformation and quantization of the Query positional encoding output tensor in the formula. Does not support non-contiguous tensors. Data format supports ND. Data type supports `int8`. Shape is [t, q_lora_rank]. | ||
| 343 | -- **mla_q_norm_scale_out** (`Tensor`): Dequantization coefficient output after rmsnorm transformation and quantization of the Query positional encoding output tensor in the formula. Does not support non-contiguous tensors. Data format supports ND. Data type supports `float32`. Shape is [t, 1]. | ||
| 344 | -- **mla_kv_cache_out** (`Tensor`): Tensor output of Key to `kv_cache` (corresponding to $k^C$). Does not support non-contiguous tensors. Data format supports ND. cache_mode is "PA_BSND". Data type supports `int8`. Shape is [block_num, block_size, n_kv, kv_lora_rank]. | ||
| 345 | -- **mla_kr_cache_out** (`Tensor`): Tensor output of Key positional encoding to `kr_cache` (corresponding to $k^R$). Does not support non-contiguous tensors. Data format supports ND. cache_mode is "PA_BSND". Data type supports `bfloat16`. Shape is [block_num, block_size, n_kv, qk_rope_dim]. | ||
| 346 | -- **mla_k_scale_cache_out** (`Tensor`): Dequantization parameter output after Key dequantization. Does not support non-contiguous tensors. Data format supports ND. cache_mode is "PA_BSND". Data type supports `float`. Shape is [block_num, block_size, n_kv, 4]. | ||
| 347 | -- **ip_q_int8_out** (`Tensor`): Output tensor of query in the formula. Data format supports ND. Data type supports `int8`. Shape is [t, idx_n_heads, idx_head_dim]. | ||
| 348 | -- **ip_q_scale_out** (`Tensor`): Output tensor of query dequantization factor in the formula. Does not support non-contiguous tensors. Data format supports ND. Data type supports `float16`. Shape is [t, idx_n_heads, 1]. | ||
| 349 | -- **ip_k_int8_out** (`Tensor`): Output tensor of key cache (k_cache). Does not support non-contiguous tensors. Data format supports ND. cache_mode is "PA_BSND". Data type supports `int8`. Shape is [block_num, block_size, n_kv, idx_head_dim]. | ||
| 350 | -- **ip_k_scale_out** (`Tensor`): Output tensor of key dequantization factor cache. Does not support non-contiguous tensors. Data format supports ND. cache_mode is "PA_BSND". Data type supports `float16`. Shape is [block_num, block_size, n_kv, 1]. | ||
| 351 | -- **ip_weights_out** (`Tensor`): Output tensor of weights in the formula. Does not support non-contiguous tensors. Data format supports ND. Data type supports `float16`. Shape is [t, idx_n_heads]. | ||
| 352 | - | ||
| 353 | -## Call Sample | ||
| 354 | - | ||
| 355 | -- For details, refer to [deepseekv32_mla_indexer_prolog_quant.py](deepseekv32_mla_indexer_prolog_quant.py). | ||
| 356 | - | ||
| 357 | -# lightning_indexer | ||
| 358 | - | ||
| 359 | -## Function Description | ||
| 360 | - | ||
| 361 | -Lightning Indexer obtains the top-$k$ positions for each token through a series of operations. For an Index Query $Q_{index}\in\R^{g\times d}$ corresponding to a token, given the context Index Key $K_{index}\in\R^{S_{k}\times d}, W\in\R^{g\times 1}$, where $g$ is the group size for GQA, $d$ is the dimension of each head, and $S_{k}$ is the context length, the specific computation formula of Lightning Indexer is as follows: | ||
| 362 | -$$ | ||
| 363 | -\text{Top-}k\left\{[1]_{1\times g}@\left[(W@[1]_{1\times S_{k}})\odot\text{ReLU}\left(Q_{index}@K_{index}^T\right)\right]\right\} | ||
| 364 | -$$ | ||
| 365 | - | ||
| 366 | -## Function Prototype | ||
| 367 | - | ||
| 368 | -``` | ||
| 369 | -def lightning_indexer_decode_compute( | ||
| 370 | - idx_query, idx_query_scale, idx_key_cache, idx_key_scale, idx_weight, act_seq_key, block_table, topk_res, | ||
| 371 | - unroll_list, configs, selected_count): | ||
| 372 | -``` | ||
| 373 | - | ||
| 374 | -## Parameter Description | ||
| 375 | - | ||
| 376 | -- **idx_query** (`Tensor`): Required parameter. Does not support non-contiguous tensors. Data format supports ND. Data type supports `int8`. Shape is [t, n_q, idx_head_dim]. | ||
| 377 | -- **idx_query_scale** (`Tensor`): Required parameter. Scaling factor for idx_query. Data format supports ND. Data type supports `float16`. Shape is [t, n_q, idx_head_dim]. | ||
| 378 | -- **idx_key_cache** (`Tensor`): Required parameter. Does not support non-contiguous tensors. Data format supports ND. Data type supports `int8`. Shape is [t, n_kv, idx_head_dim]. | ||
| 379 | -- **idx_key_scale** (`Tensor`): Required parameter. Scaling factor for idx_key_cache. Data format supports ND. Data type supports `float16`. Shape is [t, n_kv, idx_head_dim]. | ||
| 380 | -- **idx_weight** (`Tensor`): Required parameter. Does not support non-contiguous tensors. Data format supports ND. Data type supports `float16`. Supports input shape [t, n_q]. | ||
| 381 | -- **act_seq_key** (`Tensor`): Required parameter. Indicates the number of valid `key` tokens in different batches. Data type supports `int32`. Shape is [b]. | ||
| 382 | -- **block_table** (`Tensor`): Required parameter. Block mapping table used for KV storage in PageAttention. Data format supports ND. Data type supports `int32`. Shape is [b, ceilDiv(max(s2), block_size)], where max(s2) is the maximum value in s2 and ceilDiv indicates ceiling division. | ||
| 383 | -- **unroll_list** (`List`): Optional parameter. Multi-gear split configuration. | ||
| 384 | -- **configs** (`class LightningIndexerConfigs`): Optional parameter. LightningIndexerConfigs configuration structure. Represents tile split configuration and optimization options. | ||
| 385 | -- **selected_count** (`int`): Required parameter. Topk selection count. Default is 2048. | ||
| 386 | - | ||
| 387 | -## Return Value Description | ||
| 388 | - | ||
| 389 | -- **topk_res** (`Tensor`): Output in the formula. Data type supports `int32`. Data format supports ND. Output shape is [t, n_kv, selected_count]. | ||
| 390 | - | ||
| 391 | -## Call Sample | ||
| 392 | - | ||
| 393 | -- For details, refer to [deepseekv32_lightning_indexer_quant.py](deepseekv32_lightning_indexer_quant.py). | ||
| @@ -1,479 +0,0 @@ | |||
| 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 | - | ||
| 13 | -import logging | ||
| 14 | -import math | ||
| 15 | -import os | ||
| 16 | - | ||
| 17 | -from lightning_indexer_prolog_quant_impl import ( | ||
| 18 | - IndexerPrologQuantAttr, | ||
| 19 | - IndexerPrologQuantConfigs, | ||
| 20 | - IndexerPrologQuantInput, | ||
| 21 | - IndexerPrologQuantOutput, | ||
| 22 | - lightning_indexer_prolog_quant, | ||
| 23 | -) | ||
| 24 | -import pytest | ||
| 25 | -import torch | ||
| 26 | -import torch_npu | ||
| 27 | -from utils.compare import compare | ||
| 28 | - | ||
| 29 | -import pypto | ||
| 30 | - | ||
| 31 | - | ||
| 32 | -def gen_dims(params): | ||
| 33 | - dims = {} | ||
| 34 | - dims["s2"] = params["s2"] | ||
| 35 | - dims["b"] = params["b"] | ||
| 36 | - dims["t"] = params["b"] * params["s1"] | ||
| 37 | - dims["h"] = 7168 | ||
| 38 | - dims["q_lora_rank"] = 1536 | ||
| 39 | - dims["idx_head_dim"] = 128 | ||
| 40 | - dims["idx_n_heads"] = 64 | ||
| 41 | - dims["rope_head_dim"] = 64 | ||
| 42 | - dims["block_size"] = 128 | ||
| 43 | - dims["block_num"] = dims["b"] * dims["s2"] // dims["block_size"] | ||
| 44 | - dims["n_kv"] = 1 | ||
| 45 | - return dims | ||
| 46 | - | ||
| 47 | - | ||
| 48 | -def gen_block_table(act_seq, block_size, s1): | ||
| 49 | - b = act_seq.shape[0] | ||
| 50 | - block_num = 0 | ||
| 51 | - block_num_each = [] | ||
| 52 | - max_kv = max(act_seq) | ||
| 53 | - for cur_s in act_seq: | ||
| 54 | - cur_block_num = math.ceil(cur_s / block_size) | ||
| 55 | - block_num_each.append(cur_block_num) | ||
| 56 | - block_num += cur_block_num | ||
| 57 | - block_table_shape = [b, math.ceil(max_kv / block_size)] | ||
| 58 | - block_idx_list = torch.arange(0, block_num, 1) | ||
| 59 | - block_idx_list = block_idx_list[torch.randperm(block_idx_list.size(0))].to(torch.int32) | ||
| 60 | - | ||
| 61 | - block_idx = 0 | ||
| 62 | - block_table_bidx = 0 | ||
| 63 | - block_table = -torch.ones(block_table_shape, dtype=torch.int32) | ||
| 64 | - | ||
| 65 | - for cur_block in block_num_each: | ||
| 66 | - for j in range(cur_block): | ||
| 67 | - block_table[block_table_bidx, j] = block_idx_list[block_idx] | ||
| 68 | - block_idx += 1 | ||
| 69 | - block_table_bidx += 1 | ||
| 70 | - | ||
| 71 | - cache_index = -torch.ones((b, s1), dtype=torch.int64) | ||
| 72 | - for i in range(b): | ||
| 73 | - cur_act = act_seq[i] | ||
| 74 | - for j in range(s1): | ||
| 75 | - pos = cur_act - s1 + j | ||
| 76 | - block_idx_in_seq = pos // block_size | ||
| 77 | - global_block_id = block_table[i, block_idx_in_seq] | ||
| 78 | - | ||
| 79 | - offset_in_block = pos % block_size | ||
| 80 | - global_index = global_block_id * block_size + offset_in_block | ||
| 81 | - cache_index[i, j] = global_index | ||
| 82 | - | ||
| 83 | - return block_num, block_table, cache_index | ||
| 84 | - | ||
| 85 | - | ||
| 86 | -def gen_cache_tensor(k_cache_bsnd, block_table, block_num, block_size): | ||
| 87 | - dtype = k_cache_bsnd.dtype | ||
| 88 | - b, s2, n_kv, d = k_cache_bsnd.shape | ||
| 89 | - k_cache = torch.zeros((block_num, block_size, n_kv, d), dtype=dtype) | ||
| 90 | - s2_new = ((s2 + block_size - 1) // block_size) * block_size # ceil to block_size | ||
| 91 | - k_cache_raw = torch.zeros((b, s2_new, n_kv, d), dtype=dtype) | ||
| 92 | - k_cache_raw[:, :s2, :, :] = k_cache_bsnd | ||
| 93 | - | ||
| 94 | - for b_idx in range(b): | ||
| 95 | - for block_idx, cache_block_idx in enumerate(block_table[b_idx]): | ||
| 96 | - block_offset = block_idx * block_size | ||
| 97 | - if cache_block_idx == -1: | ||
| 98 | - continue | ||
| 99 | - else: | ||
| 100 | - k_cache[cache_block_idx, :, :, :] = k_cache_raw[b_idx, block_offset:(block_offset + block_size), :, :] | ||
| 101 | - | ||
| 102 | - return k_cache | ||
| 103 | - | ||
| 104 | - | ||
| 105 | -def gen_inputs(dims, dtype=torch.bfloat16, qunat_dtype=torch.int8): | ||
| 106 | - b, t, n, d = dims["b"], dims["t"], dims["idx_n_heads"], dims["idx_head_dim"] | ||
| 107 | - s = t // b | ||
| 108 | - h = dims["h"] | ||
| 109 | - q_lora_rank = dims["q_lora_rank"] | ||
| 110 | - block_size = dims["block_size"] | ||
| 111 | - n_kv = dims["n_kv"] | ||
| 112 | - s2 = dims["s2"] | ||
| 113 | - rope_head_dim = dims["rope_head_dim"] | ||
| 114 | - | ||
| 115 | - x = torch.empty((b, s, h), dtype=dtype).uniform_(-1, 1) | ||
| 116 | - q_norm = torch.randint(low=-128, high=128, size=(b, s, q_lora_rank), dtype=qunat_dtype) | ||
| 117 | - q_norm_scale = torch.empty((b, s, 1), dtype=torch.float32).uniform_(-1, 1) | ||
| 118 | - w_idx_qb = torch.randint(low=-128, high=128, size=(q_lora_rank, n * d), dtype=qunat_dtype) | ||
| 119 | - w_idx_qb_scale = torch.empty((n * d, 1), dtype=torch.float32).uniform_(-1, 1) | ||
| 120 | - w_idx_k = torch.empty((h, d), dtype=dtype).uniform_(-1, 1) | ||
| 121 | - w_idx_proj = torch.empty((h, n), dtype=dtype).uniform_(-1, 1) | ||
| 122 | - ln_gamma = torch.ones((d,), dtype=dtype) | ||
| 123 | - ln_beta = torch.zeros((d,), dtype=dtype) | ||
| 124 | - | ||
| 125 | - random_angles = torch.rand(b, s, rope_head_dim, dtype=torch.float32) * 2 * torch.pi | ||
| 126 | - cos = torch.cos(random_angles).to(dtype) | ||
| 127 | - sin = torch.sin(random_angles).to(dtype) | ||
| 128 | - | ||
| 129 | - hadamard_q = torch.empty((d, d), dtype=dtype).uniform_(-1, 1) # (128, 128) | ||
| 130 | - hadamard_k = torch.empty((d, d), dtype=dtype).uniform_(-1, 1) | ||
| 131 | - | ||
| 132 | - act_seq = torch.tensor([s2] * b) # (b,) | ||
| 133 | - k_cache_bsnd = torch.randint(low=-128, high=128, size=(b, s2, n_kv, d), dtype=qunat_dtype) | ||
| 134 | - k_scale_cache_bsnd = torch.empty((b, s2, n_kv, 1), dtype=torch.float16).uniform_(-1, 1) | ||
| 135 | - block_num, block_table, k_cache_index = gen_block_table(act_seq, block_size, s) | ||
| 136 | - k_cache = gen_cache_tensor(k_cache_bsnd, block_table, block_num, block_size) | ||
| 137 | - k_scale_cache = gen_cache_tensor(k_scale_cache_bsnd, block_table, block_num, block_size) | ||
| 138 | - | ||
| 139 | - return { | ||
| 140 | - "token_x": x, # input0, bf16 | ||
| 141 | - "q_norm": q_norm, # input1, int8 | ||
| 142 | - "q_norm_scale": q_norm_scale, # input2, fp32 | ||
| 143 | - "w_idx_qb": w_idx_qb, # input3, int8 | ||
| 144 | - "w_idx_qb_scale": w_idx_qb_scale, # input4, fp32 | ||
| 145 | - "w_idx_k": w_idx_k, # input5, bf16 | ||
| 146 | - "w_idx_proj": w_idx_proj, # input6, bf16 | ||
| 147 | - "layer_norm_gamma": ln_gamma, # input7, bf16 | ||
| 148 | - "layer_norm_beta": ln_beta, # input8, bf16 | ||
| 149 | - "cos_idx_rope": cos, # input9, bf16 | ||
| 150 | - "sin_idx_rope": sin, # input10, bf16 | ||
| 151 | - "hadamard_q": hadamard_q, # input11, bf16 | ||
| 152 | - "hadamard_k": hadamard_k, # input12, bf16 | ||
| 153 | - "idx_k_cache": k_cache, # input13, int8 # (block_num, block_size, n_kv, d) | ||
| 154 | - "idx_k_scale_cache": k_scale_cache, # input14, fp16 # (block_num, block_size, n_kv, 1) | ||
| 155 | - "idx_k_cache_index": k_cache_index, # input15, int64 (b, s)/(t,) | ||
| 156 | - "idx_block_table": block_table, # input16, int32 (b, ceil(s2, block_size)) | ||
| 157 | - "act_seq": act_seq, # input17, int32 | ||
| 158 | - } | ||
| 159 | - | ||
| 160 | - | ||
| 161 | -def scatter_update_pa_bsnd(cache, k_bsnd, cache_index, axis): | ||
| 162 | - block_number, block_size, n_kv, d = cache.shape | ||
| 163 | - res = cache.reshape(block_number * block_size * n_kv, d) | ||
| 164 | - b, s1 = cache_index.shape | ||
| 165 | - | ||
| 166 | - if axis == -2: | ||
| 167 | - for b_i in range(b): | ||
| 168 | - for s1_i in range(s1): | ||
| 169 | - index_value = cache_index[b_i][s1_i] | ||
| 170 | - res[index_value, :] = k_bsnd[b_i, s1_i, :, :] | ||
| 171 | - | ||
| 172 | - return res.reshape(block_number, block_size, n_kv, d) | ||
| 173 | - | ||
| 174 | - | ||
| 175 | -def layer_norm(x: torch.Tensor, gamma: torch.Tensor, beta: torch.Tensor, eps=1e-6) -> torch.Tensor: | ||
| 176 | - x_dtype = x.dtype | ||
| 177 | - if x_dtype != torch.float32: | ||
| 178 | - x = x.to(torch.float32) | ||
| 179 | - mean = x.mean(dim=-1, keepdim=True) | ||
| 180 | - var = ((x - mean) ** 2).mean(dim=-1, keepdim=True) | ||
| 181 | - x = (x - mean) / torch.sqrt(var + eps) | ||
| 182 | - return (x * gamma.to(torch.float32) + beta.to(torch.float32)).to(x_dtype) | ||
| 183 | - | ||
| 184 | - | ||
| 185 | -def quant_int8(x: torch.Tensor): | ||
| 186 | - # pertoken | ||
| 187 | - x_dtype = x.dtype # bf16, (b, s, n, d) | ||
| 188 | - x_fp32 = x.to(torch.float32) | ||
| 189 | - max_value = torch.amax(torch.abs(x_fp32), dim=-1, keepdim=True) | ||
| 190 | - scale_quant = 127.0 / max_value | ||
| 191 | - y_fp32 = x_fp32 * scale_quant | ||
| 192 | - y_fp32 = y_fp32.view(x.shape) | ||
| 193 | - y_int32 = torch.round(y_fp32).to(torch.int32) # rint mode | ||
| 194 | - y_int8 = torch.trunc(y_int32.to(x_dtype)).to(torch.int8) | ||
| 195 | - scale_dequant = 1.0 / scale_quant | ||
| 196 | - # (b, s, n, d) int8, (b, s, n, 1) fp32 | ||
| 197 | - return y_int8, scale_dequant | ||
| 198 | - | ||
| 199 | - | ||
| 200 | -def rotate_half(x): | ||
| 201 | - """Rotates half the hidden dims of the input.""" | ||
| 202 | - x1, x2 = x.chunk(2, dim=-1) | ||
| 203 | - return torch.cat((-x2, x1), dim=-1) | ||
| 204 | - | ||
| 205 | - | ||
| 206 | -def single_rope(x, cos_in, sin_in): | ||
| 207 | - logging.info("Entering into single_rope") | ||
| 208 | - # x: (b, s, n, d), cos_in: (b, s, d), sin_in: (b, s, d) | ||
| 209 | - x_dtype = x.dtype | ||
| 210 | - b, s, n, d = x.shape | ||
| 211 | - x_cast = x.to(torch.float32) | ||
| 212 | - cos_cast = cos_in.to(torch.float32) | ||
| 213 | - sin_cast = sin_in.to(torch.float32) | ||
| 214 | - cos_re = cos_cast.unsqueeze(2) # (b, s, 1, d) | ||
| 215 | - sin_re = sin_cast.unsqueeze(2) # (b, s, 1, d) | ||
| 216 | - res = x_cast * cos_re + rotate_half(x_cast) * sin_re # (b, s, n, d) | ||
| 217 | - return res.to(x_dtype) | ||
| 218 | - | ||
| 219 | - | ||
| 220 | -def indexer_prolog(inputs: dict, dims: dict): | ||
| 221 | - # input | ||
| 222 | - b, t, n, d = dims["b"], dims["t"], dims["idx_n_heads"], dims["idx_head_dim"] | ||
| 223 | - s = t // b | ||
| 224 | - | ||
| 225 | - rope_head_dim = dims["rope_head_dim"] | ||
| 226 | - x = inputs["token_x"] # (b, s, h) | ||
| 227 | - q_norm = inputs["q_norm"] # (b, s, q_lora_rank), int8 | ||
| 228 | - q_norm_scale = inputs["q_norm_scale"] # (b, s, 1), fp32 | ||
| 229 | - w_idx_qb = inputs["w_idx_qb"] # (q_lora_rank, n * d), int8 | ||
| 230 | - w_idx_qb_scale = inputs["w_idx_qb_scale"] # (n * d, 1), fp32 | ||
| 231 | - w_idx_k = inputs["w_idx_k"] # (h, d) | ||
| 232 | - w_idx_proj = inputs["w_idx_proj"] # (h, n) | ||
| 233 | - layer_norm_gamma = inputs["layer_norm_gamma"] # (d,) | ||
| 234 | - layer_norm_beta = inputs["layer_norm_beta"] # (d,) | ||
| 235 | - cos = inputs["cos_idx_rope"] # (b, s, rope_head_dim) | ||
| 236 | - sin = inputs["sin_idx_rope"] # (b, s, rope_head_dim) | ||
| 237 | - hadamard_q = inputs["hadamard_q"] # (d, d) | ||
| 238 | - hadamard_k = inputs["hadamard_k"] # (d, d) | ||
| 239 | - idx_k_cache = inputs["idx_k_cache"] # input13, int8 | ||
| 240 | - idx_k_scale_cache = inputs["idx_k_scale_cache"] # input14, fp16 | ||
| 241 | - cache_index = inputs["idx_k_cache_index"] # (b, s), int32 | ||
| 242 | - x_dtype = x.dtype | ||
| 243 | - | ||
| 244 | - # calculate | ||
| 245 | - q = torch.matmul(q_norm.to(torch.int32), w_idx_qb.to(torch.int32)) # (b, s, n * d) | ||
| 246 | - q_fp32 = q.to(torch.float32) | ||
| 247 | - q_fp32 = q_fp32 * q_norm_scale | ||
| 248 | - q_fp32 = q_fp32 * w_idx_qb_scale.reshape(1, n * d) | ||
| 249 | - q_bf16 = q_fp32.reshape(b, s, n, d).to(torch.bfloat16) | ||
| 250 | - q_rope, q_nope = torch.split(q_bf16, [rope_head_dim, d - rope_head_dim], dim=-1) | ||
| 251 | - q_rope = single_rope(q_rope, cos, sin) | ||
| 252 | - q = torch.cat([q_rope, q_nope], dim=-1) | ||
| 253 | - # hadamard | ||
| 254 | - # matmul use float32 for arm, arm平台matmul在bfloat16数据类型下表现跟x86不一致,通过升精度保证正确性 | ||
| 255 | - q = torch.matmul(q.to(torch.float32), hadamard_q.to(torch.float32)).to(x_dtype) # (b, s, n, d) | ||
| 256 | - q_int8, q_scale = quant_int8(q) # (b, s, n, d) int8, (b, s, n, 1) fp32 | ||
| 257 | - q_scale = q_scale.to(torch.float16) | ||
| 258 | - | ||
| 259 | - k = torch.matmul(x.to(torch.float32), w_idx_k.to(torch.float32)) # (b, s, d) | ||
| 260 | - k = layer_norm(k, layer_norm_gamma, layer_norm_beta).to(x_dtype) | ||
| 261 | - k_rope, k_nope = torch.split(k, [rope_head_dim, d - rope_head_dim], dim=-1) | ||
| 262 | - k_rope = single_rope(k_rope.unsqueeze(2), cos, sin).squeeze(2) | ||
| 263 | - k = torch.cat([k_rope, k_nope], dim=-1) | ||
| 264 | - # hadamard | ||
| 265 | - # matmul use float32 for arm, arm平台matmul在bfloat16数据类型下表现跟x86不一致,通过升精度保证正确性 | ||
| 266 | - k = torch.matmul(k.to(torch.float32), hadamard_k.to(torch.float32)).to(x_dtype) # (b, s, d) | ||
| 267 | - k_int8, k_scale = quant_int8(k) # (b, s, d) int8, (b, s, 1) fp32 | ||
| 268 | - k_scale = k_scale.to(torch.float16) | ||
| 269 | - # cache update | ||
| 270 | - k_cache = idx_k_cache.clone() # (block_num, block_size, n_kv, d) | ||
| 271 | - k_scale_cache = idx_k_scale_cache.clone() # (block_num, block_size, n_kv, 1) | ||
| 272 | - scatter_update_pa_bsnd(k_cache, k_int8.reshape(b, s, 1, d), cache_index, -2) | ||
| 273 | - scatter_update_pa_bsnd(k_scale_cache, k_scale.reshape(b, s, 1, 1), cache_index, -2) | ||
| 274 | - | ||
| 275 | - # matmul use float32 for arm, arm平台matmul在bfloat16数据类型下表现跟x86不一致,通过升精度保证正确性 | ||
| 276 | - weights = torch.matmul(x.to(torch.float32), w_idx_proj.to(torch.float32)).to(x_dtype).to(torch.float32) # (b, s, n) | ||
| 277 | - weights = weights * (n**-0.5) * (d**-0.5) | ||
| 278 | - weights = weights.to(torch.float16) | ||
| 279 | - | ||
| 280 | - # output dtype: int8, fp16, int8, fp16, fp16 | ||
| 281 | - outputs = { | ||
| 282 | - "query": q_int8, | ||
| 283 | - "query_scale": q_scale, | ||
| 284 | - "idx_k_cache_out": k_cache, | ||
| 285 | - "idx_k_scale_cache_out": k_scale_cache, | ||
| 286 | - "weights": weights, | ||
| 287 | - } | ||
| 288 | - return outputs | ||
| 289 | - | ||
| 290 | - | ||
| 291 | -def gen_data(case_name): | ||
| 292 | - if case_name.startswith("QuantLightningIndexerPrologSTest.b4_s1_2_s2_64k"): | ||
| 293 | - params = {"b": 4, "s1": 2, "s2": 1024 * 64} | ||
| 294 | - elif case_name.startswith("QuantLightningIndexerPrologSTest.b8_s1_2_s2_64k"): | ||
| 295 | - params = {"b": 8, "s1": 2, "s2": 1024 * 64} | ||
| 296 | - elif case_name.startswith("QuantLightningIndexerPrologSTest.b1_s1_4k_s2_64k"): | ||
| 297 | - params = {"b": 1, "s1": 1024 * 4, "s2": 1024 * 64} | ||
| 298 | - elif case_name.startswith("QuantLightningIndexerPrologSTest.b2_s1_4k_s2_64k"): | ||
| 299 | - params = {"b": 2, "s1": 1024 * 4, "s2": 1024 * 64} | ||
| 300 | - elif case_name.startswith("QuantLightningIndexerPrologSTest.b128_s1_4_s2_8k"): | ||
| 301 | - params = {"b": 128, "s1": 4, "s2": 1024 * 8} | ||
| 302 | - else: | ||
| 303 | - raise Exception(f"Can't get func to gen golden, Case({case_name})") | ||
| 304 | - | ||
| 305 | - seed = 7 | ||
| 306 | - # PyTorch 随机数生成器 | ||
| 307 | - torch.manual_seed(seed) | ||
| 308 | - dims = gen_dims(params) | ||
| 309 | - inputs = gen_inputs(dims, torch.bfloat16) | ||
| 310 | - outputs = indexer_prolog(inputs, dims) | ||
| 311 | - return dims, inputs, outputs | ||
| 312 | - | ||
| 313 | - | ||
| 314 | -def gen_zero_tensor(t): | ||
| 315 | - return torch.zeros_like(t).npu() | ||
| 316 | - | ||
| 317 | - | ||
| 318 | -def do_test_lighting_indexer_prolog_quant(case_name, configs): | ||
| 319 | - device_id = int(os.environ.get('TILE_FWK_DEVICE_ID', 0)) | ||
| 320 | - torch.npu.set_device(device_id) | ||
| 321 | - | ||
| 322 | - print(f"=== run test case: {case_name} ===") | ||
| 323 | - | ||
| 324 | - dims, inputs_data, golden_data = gen_data(case_name) | ||
| 325 | - | ||
| 326 | - t = dims["t"] | ||
| 327 | - h = dims["h"] | ||
| 328 | - q_lora_rank = dims["q_lora_rank"] | ||
| 329 | - idx_head_dim = dims["idx_head_dim"] | ||
| 330 | - head_num = dims["idx_n_heads"] | ||
| 331 | - rope_head_dim = dims["rope_head_dim"] | ||
| 332 | - | ||
| 333 | - torch_npu.npu.config.allow_internal_format = True | ||
| 334 | - | ||
| 335 | - inputs = IndexerPrologQuantInput( | ||
| 336 | - x=inputs_data["token_x"].npu().reshape(t, h), | ||
| 337 | - q_norm=inputs_data["q_norm"].npu().reshape(t, q_lora_rank), | ||
| 338 | - q_norm_scale=inputs_data["q_norm_scale"].npu().reshape(t, 1), | ||
| 339 | - w_qb=torch_npu.npu_format_cast(inputs_data["w_idx_qb"].npu().contiguous(), torch_npu.Format.FRACTAL_NZ), | ||
| 340 | - w_qb_scale=inputs_data["w_idx_qb_scale"].npu(), | ||
| 341 | - wk=torch_npu.npu_format_cast(inputs_data["w_idx_k"].npu().contiguous(), torch_npu.Format.FRACTAL_NZ), | ||
| 342 | - w_proj=torch_npu.npu_format_cast(inputs_data["w_idx_proj"].npu().contiguous(), torch_npu.Format.FRACTAL_NZ), | ||
| 343 | - ln_gamma_k=inputs_data["layer_norm_gamma"].npu(), | ||
| 344 | - ln_beta_k=inputs_data["layer_norm_beta"].npu(), | ||
| 345 | - cos_idx_rope=inputs_data["cos_idx_rope"].npu().reshape(t, rope_head_dim), | ||
| 346 | - sin_idx_rope=inputs_data["sin_idx_rope"].npu().reshape(t, rope_head_dim), | ||
| 347 | - hadamard_q=inputs_data["hadamard_q"].npu(), | ||
| 348 | - hadamard_k=inputs_data["hadamard_k"].npu(), | ||
| 349 | - k_cache=inputs_data["idx_k_cache"].npu(), | ||
| 350 | - k_cache_scale=inputs_data["idx_k_scale_cache"].npu(), | ||
| 351 | - k_cache_index=inputs_data["idx_k_cache_index"].npu().reshape(t), | ||
| 352 | - ) | ||
| 353 | - | ||
| 354 | - q_int8_golden = golden_data["query"].reshape(t, head_num, idx_head_dim) | ||
| 355 | - q_scale_golden = golden_data["query_scale"].reshape(t, head_num, 1) | ||
| 356 | - k_cache_golden = golden_data["idx_k_cache_out"] | ||
| 357 | - k_cache_scale_golden = golden_data["idx_k_scale_cache_out"] | ||
| 358 | - weights_golden = golden_data["weights"].reshape(t, head_num) | ||
| 359 | - | ||
| 360 | - outputs = IndexerPrologQuantOutput( | ||
| 361 | - q_int8=gen_zero_tensor(q_int8_golden), | ||
| 362 | - q_scale=gen_zero_tensor(q_scale_golden), | ||
| 363 | - k_int8=inputs.k_cache, | ||
| 364 | - k_scale=inputs.k_cache_scale, | ||
| 365 | - weights=gen_zero_tensor(weights_golden), | ||
| 366 | - ) | ||
| 367 | - | ||
| 368 | - # ---- Attrs ---- | ||
| 369 | - attrs = IndexerPrologQuantAttr( | ||
| 370 | - eps=1e-6, | ||
| 371 | - layerout_query="TND", | ||
| 372 | - layerout_key="PA_BSND", | ||
| 373 | - ) | ||
| 374 | - | ||
| 375 | - tensors = [tensor for _, tensor in vars(inputs).items()] + [tensor for _, tensor in vars(outputs).items()] | ||
| 376 | - lightning_indexer_prolog_quant(*tensors, configs, attrs) | ||
| 377 | - | ||
| 378 | - compare(outputs.q_int8.cpu(), q_int8_golden, "q_int8", 1, 0, 0) | ||
| 379 | - compare(outputs.q_scale.cpu(), q_scale_golden, "q_scale", 0.000025, 0, 0.005) | ||
| 380 | - compare(outputs.k_int8.cpu(), k_cache_golden, "k_int8", 1, 0, 0) | ||
| 381 | - compare(outputs.k_scale.cpu(), k_cache_scale_golden, "k_scale", 0.000025, 0, 0) | ||
| 382 | - compare(outputs.weights.cpu(), weights_golden, "weights", 0.000025, 0.0, 0) | ||
| 383 | - | ||
| 384 | - print(f"=== {case_name}: PASS ===") | ||
| 385 | - | ||
| 386 | - | ||
| 387 | -@pytest.mark.soc("950", "910") | ||
| 388 | -@pypto.options(pass_options={"enable_slice": False}) | ||
| 389 | -def test_b4_s1_2_s2_64k(): | ||
| 390 | - configs = IndexerPrologQuantConfigs( | ||
| 391 | - q_linear=[16, 16, 512, 512, 128, 128], | ||
| 392 | - q_hd=[32, 32, 128, 128, 128, 128], | ||
| 393 | - k_linear=[16, 16, 512, 512, 64, 64], | ||
| 394 | - w_linear=[16, 16, 1024, 1024, 32, 32], | ||
| 395 | - unroll_list=[32, 16, 8, 4, 2, 1], | ||
| 396 | - cube_l1_reuse_setting={1: 4}, | ||
| 397 | - block_size=128, | ||
| 398 | - t_sub_tile=1, | ||
| 399 | - chunk_size=2, | ||
| 400 | - vec_nbuffer_setting={-1: 1}, | ||
| 401 | - ) | ||
| 402 | - do_test_lighting_indexer_prolog_quant("QuantLightningIndexerPrologSTest.b4_s1_2_s2_64k", configs) | ||
| 403 | - | ||
| 404 | - | ||
| 405 | -@pytest.mark.skip(reason="large test case") | ||
| 406 | -@pypto.options(pass_options={"enable_slice": True}) | ||
| 407 | -def test_b8_s1_2_s2_64k(): | ||
| 408 | - configs = IndexerPrologQuantConfigs( | ||
| 409 | - q_linear=[16, 16, 512, 512, 128, 128], | ||
| 410 | - q_hd=[32, 32, 128, 128, 128, 128], | ||
| 411 | - k_linear=[16, 16, 512, 512, 64, 64], | ||
| 412 | - w_linear=[16, 16, 1024, 1024, 32, 32], | ||
| 413 | - unroll_list=[32, 16, 8, 4, 2, 1], | ||
| 414 | - cube_l1_reuse_setting={1: 4}, | ||
| 415 | - block_size=128, | ||
| 416 | - t_sub_tile=1, | ||
| 417 | - chunk_size=2, | ||
| 418 | - vec_nbuffer_setting={-1: 1}, | ||
| 419 | - ) | ||
| 420 | - do_test_lighting_indexer_prolog_quant("QuantLightningIndexerPrologSTest.b8_s1_2_s2_64k", configs) | ||
| 421 | - | ||
| 422 | - | ||
| 423 | -@pytest.mark.skip(reason="large test case") | ||
| 424 | -@pypto.options(pass_options={"enable_slice": True}) | ||
| 425 | -def test_b1_s1_4k_s2_64k(): | ||
| 426 | - configs = IndexerPrologQuantConfigs( | ||
| 427 | - q_linear=[16, 16, 512, 512, 128, 128], | ||
| 428 | - q_hd=[32, 32, 128, 128, 128, 128], | ||
| 429 | - k_linear=[16, 16, 512, 512, 64, 64], | ||
| 430 | - w_linear=[16, 16, 1024, 1024, 32, 32], | ||
| 431 | - unroll_list=[32, 16, 8, 4, 2, 1], | ||
| 432 | - cube_l1_reuse_setting={1: 4}, | ||
| 433 | - block_size=128, | ||
| 434 | - t_sub_tile=1, | ||
| 435 | - chunk_size=2, | ||
| 436 | - vec_nbuffer_setting={-1: 1}, | ||
| 437 | - ) | ||
| 438 | - do_test_lighting_indexer_prolog_quant("QuantLightningIndexerPrologSTest.b1_s1_4k_s2_64k", configs) | ||
| 439 | - | ||
| 440 | - | ||
| 441 | -@pytest.mark.skip(reason="large test case") | ||
| 442 | -@pypto.options(pass_options={"enable_slice": True}) | ||
| 443 | -def test_b2_s1_4k_s2_64k(): | ||
| 444 | - configs = IndexerPrologQuantConfigs( | ||
| 445 | - q_linear=[16, 16, 512, 512, 128, 128], | ||
| 446 | - q_hd=[32, 32, 128, 128, 128, 128], | ||
| 447 | - k_linear=[16, 16, 512, 512, 64, 64], | ||
| 448 | - w_linear=[16, 16, 1024, 1024, 32, 32], | ||
| 449 | - unroll_list=[32, 16, 8, 4, 2, 1], | ||
| 450 | - cube_l1_reuse_setting={1: 4}, | ||
| 451 | - block_size=128, | ||
| 452 | - t_sub_tile=1, | ||
| 453 | - chunk_size=2, | ||
| 454 | - vec_nbuffer_setting={-1: 1}, | ||
| 455 | - ) | ||
| 456 | - do_test_lighting_indexer_prolog_quant("QuantLightningIndexerPrologSTest.b2_s1_4k_s2_64k", configs) | ||
| 457 | - | ||
| 458 | - | ||
| 459 | -@pytest.mark.skip(reason="large test case") | ||
| 460 | -@pypto.options(pass_options={"enable_slice": True}) | ||
| 461 | -def test_b128_s1_4_s2_8k(): | ||
| 462 | - configs = IndexerPrologQuantConfigs( | ||
| 463 | - q_linear=[128, 128, 256, 256, 256, 256], | ||
| 464 | - q_hd=[128, 128, 64, 64, 128, 128], | ||
| 465 | - k_linear=[64, 64, 256, 256, 128, 128], | ||
| 466 | - w_linear=[32, 32, 512, 512, 64, 64], | ||
| 467 | - unroll_list=[128, 64, 32, 16, 8, 4, 2, 1], | ||
| 468 | - cube_l1_reuse_setting={1: 4, 3: 4}, | ||
| 469 | - block_size=128, | ||
| 470 | - t_sub_tile=2, | ||
| 471 | - chunk_size=1, | ||
| 472 | - vec_nbuffer_setting={-1: 1}, | ||
| 473 | - ) | ||
| 474 | - do_test_lighting_indexer_prolog_quant("QuantLightningIndexerPrologSTest.b128_s1_4_s2_8k", configs) | ||
| 475 | - | ||
| 476 | - | ||
| 477 | -if __name__ == "__main__": | ||
| 478 | - logging.basicConfig(format='%(asctime)s - %(filename)s:%(lineno)d - %(levelname)s: %(message)s', level=logging.INFO) | ||
| 479 | - test_b4_s1_2_s2_64k() | ||
| @@ -1,415 +0,0 @@ | |||
| 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 | - | ||
| 13 | -from dataclasses import dataclass | ||
| 14 | -import logging | ||
| 15 | -import math | ||
| 16 | -import os | ||
| 17 | - | ||
| 18 | -import numpy as np | ||
| 19 | -import pytest | ||
| 20 | -import torch | ||
| 21 | -import torch_npu | ||
| 22 | - | ||
| 23 | -import pypto | ||
| 24 | - | ||
| 25 | - | ||
| 26 | -@dataclass | ||
| 27 | -class LightningIndexerConfigs: | ||
| 28 | - # graph optimization params | ||
| 29 | - # used for copy in merge graph | ||
| 30 | - mg_copy_in_upper_bound = 2 * 1024 * 1024 | ||
| 31 | - # l1 reuse merge params | ||
| 32 | - cube_l1_reuse_setting = {0: 16} | ||
| 33 | - # vector graph fuse optimization | ||
| 34 | - vec_merge_mode = 2 | ||
| 35 | - vec_nbuffer_setting = {-1: 16} | ||
| 36 | - # tile params | ||
| 37 | - s1_tile = 2 | ||
| 38 | - topk_tile = 8192 | ||
| 39 | - # set the tileshape size in cube computation | ||
| 40 | - c1_tile = [64, 64, 128, 128, 128, 128] # (m, M), (k, K), (n, N) | ||
| 41 | - c2_tile = [128, 128, 64, 64, 128, 128] # (m, M), (k, K), (n, N) | ||
| 42 | - # matmul relu fuse params | ||
| 43 | - extend_param = {'scale': 1 / 2048.0, 'relu_type': pypto.ReLuType.RELU} | ||
| 44 | - | ||
| 45 | - | ||
| 46 | -def gen_cache_tensor(k_tensor, block_table, block_num, block_size, b): | ||
| 47 | - logging.info("Entering into gen_cache_tensor!") | ||
| 48 | - # 获取输入张量的数据类型 | ||
| 49 | - dtype = k_tensor.dtype | ||
| 50 | - b, s, n, d = k_tensor.shape | ||
| 51 | - | ||
| 52 | - # 初始化KV缓存张量 | ||
| 53 | - k_cache = torch.zeros([block_num, block_size, n * d], dtype=dtype) | ||
| 54 | - k_tensor_bsh_raw = k_tensor.reshape(b, s, n * d) | ||
| 55 | - | ||
| 56 | - # 创建填充后的张量,长度扩展到块对齐 | ||
| 57 | - k_tensor_bsh = torch.zeros((b, block_table.shape[1] * block_size, n * d), dtype=dtype) | ||
| 58 | - | ||
| 59 | - # 将原始数据填充到新张量的前部 | ||
| 60 | - k_tensor_bsh[:, :k_tensor_bsh_raw.shape[1], :] = k_tensor_bsh_raw[:, :, :] | ||
| 61 | - | ||
| 62 | - # 遍历每个样本和块进行缓存填充 | ||
| 63 | - for b_idx in range(b): # 遍历batch维度 | ||
| 64 | - for block_idx, cache_block_idx in enumerate(block_table[b_idx]): # 遍历块映射表 | ||
| 65 | - block_offset = block_idx * block_size # 计算当前块在序列中的起始位置 | ||
| 66 | - # 如果cache_block_idx有效(非-1),则执行数据拷贝 | ||
| 67 | - if cache_block_idx != -1: | ||
| 68 | - # 将数据从k_tensor_bsh复制到k_cache的指定块位置 | ||
| 69 | - # 注意:block_offset到block_offset+block_size的切片对应当前块的数据 | ||
| 70 | - k_cache[cache_block_idx, :, :] = k_tensor_bsh[b_idx, block_offset:(block_offset + block_size), :] | ||
| 71 | - | ||
| 72 | - k_cache = k_cache.reshape(block_num, block_size, n, d) | ||
| 73 | - return k_cache | ||
| 74 | - | ||
| 75 | - | ||
| 76 | -def gen_block_table(b, block_size, max_kv, act_kv): | ||
| 77 | - logging.info("Entering into gen_block_table!") | ||
| 78 | - | ||
| 79 | - # 初始化总块数和每个样本的块数列表 | ||
| 80 | - block_num = 0 | ||
| 81 | - block_num_each = [] | ||
| 82 | - | ||
| 83 | - # 计算每个样本需要的块数(向上取整)并累加总块数 | ||
| 84 | - for cur_s in act_kv: | ||
| 85 | - cur_block_num = math.ceil(cur_s / block_size) # 当前样本需要的块数 | ||
| 86 | - block_num_each.append(cur_block_num) | ||
| 87 | - block_num += cur_block_num | ||
| 88 | - | ||
| 89 | - shape_bt = [b, math.ceil(max_kv / block_size)] | ||
| 90 | - | ||
| 91 | - # 生成物理块索引列表,并随机排列以优化缓存效率 | ||
| 92 | - block_idx_list = np.arange(0, block_num, 1) | ||
| 93 | - block_idx_list = np.random.permutation(block_idx_list).astype(np.int32) | ||
| 94 | - | ||
| 95 | - # 初始化块表,无效块标记为-1 | ||
| 96 | - block_table = [-1] * shape_bt[1] | ||
| 97 | - block_table = np.tile(block_table, (shape_bt[0], 1)).astype(np.int32) | ||
| 98 | - | ||
| 99 | - block_table_bidx = 0 | ||
| 100 | - block_idx = 0 | ||
| 101 | - | ||
| 102 | - # 填充块表:将物理块索引分配给每个样本的有效块位置 | ||
| 103 | - for cur_block in block_num_each: | ||
| 104 | - for j in range(cur_block): | ||
| 105 | - block_table[block_table_bidx][j] = block_idx_list[block_idx] | ||
| 106 | - block_idx += 1 | ||
| 107 | - block_table_bidx += 1 | ||
| 108 | - | ||
| 109 | - return block_num, block_table | ||
| 110 | - | ||
| 111 | - | ||
| 112 | -def gen_data_for_compute(params, is_quant: bool): | ||
| 113 | - b = params.get("b") | ||
| 114 | - s1 = params.get("s1") | ||
| 115 | - n1 = params.get("n1") | ||
| 116 | - n2 = params.get("n2") | ||
| 117 | - d = params.get("d") | ||
| 118 | - dtype = params.get("dtype") | ||
| 119 | - s2 = params.get("s2") | ||
| 120 | - act_seq_len = params.get("act_seq") | ||
| 121 | - block_size = params.get("block_size") | ||
| 122 | - block_num = params.get("block_num") | ||
| 123 | - selected_count = params.get("selected_count") | ||
| 124 | - | ||
| 125 | - # 生成query张量 [b, s1, n1, d] | ||
| 126 | - query = torch.randn([b, s1, n1, d]).to(torch.int8) | ||
| 127 | - # 生成权重张量 [b, s1, n1] | ||
| 128 | - weights = torch.randn([b, s1, n1], dtype=dtype).to(torch.float16) | ||
| 129 | - | ||
| 130 | - # 生成key张量 [b, s2, n2, d] | ||
| 131 | - k_bsnd = torch.randn([b, s2, n2, d]).to(torch.int8) | ||
| 132 | - | ||
| 133 | - # 生成块表 | ||
| 134 | - _, block_table_list = gen_block_table(b, block_size, s2, act_seq_len) | ||
| 135 | - block_table = torch.tensor(block_table_list, dtype=torch.int32) | ||
| 136 | - act_seq = torch.tensor(act_seq_len, dtype=torch.int32) | ||
| 137 | - | ||
| 138 | - # 初始化输出张量 | ||
| 139 | - topk_res = torch.ones([b, s1, n2, selected_count], dtype=torch.int32) | ||
| 140 | - | ||
| 141 | - # 生成KV缓存张量 | ||
| 142 | - key = gen_cache_tensor(k_bsnd, block_table_list, block_num, block_size, b) | ||
| 143 | - | ||
| 144 | - input_data_map = {} | ||
| 145 | - | ||
| 146 | - # 量化处理逻辑 | ||
| 147 | - if is_quant: | ||
| 148 | - # 计算query的缩放因子(最大值/127,最小1e-3) | ||
| 149 | - q_scale = ( | ||
| 150 | - (query.abs().max(dim=-1, keepdim=True).values / 127).to(dtype=torch.float16).maximum(torch.tensor(1e-3)) | ||
| 151 | - ) | ||
| 152 | - # 计算key的缩放因子 | ||
| 153 | - k_scale = (key.abs().max(dim=-1, keepdim=True).values / 127).to(dtype=torch.float16).maximum(torch.tensor(1e-3)) | ||
| 154 | - | ||
| 155 | - # 量化:归一化后四舍五入并裁剪到int8范围 | ||
| 156 | - query = torch.round(query / q_scale).clip(-127, 127).to(dtype=torch.int8) | ||
| 157 | - key = torch.round(key / k_scale).clip(-127, 127).to(dtype=torch.int8) | ||
| 158 | - | ||
| 159 | - # 存储量化数据和缩放因子 | ||
| 160 | - input_data_map["query"] = query | ||
| 161 | - input_data_map["key"] = key | ||
| 162 | - input_data_map["q_scale"] = q_scale | ||
| 163 | - input_data_map["k_scale"] = k_scale | ||
| 164 | - else: | ||
| 165 | - # 非量化模式直接存储原始数据 | ||
| 166 | - input_data_map["query"] = query | ||
| 167 | - input_data_map["key"] = key | ||
| 168 | - | ||
| 169 | - input_data_map["weights"] = weights | ||
| 170 | - input_data_map["act_seq"] = act_seq | ||
| 171 | - input_data_map["block_table"] = block_table | ||
| 172 | - input_data_map["selected_count"] = selected_count | ||
| 173 | - input_data_map["topk_res"] = topk_res | ||
| 174 | - | ||
| 175 | - return input_data_map | ||
| 176 | - | ||
| 177 | - | ||
| 178 | -def lightning_indexer_compute(input_data_map, params): | ||
| 179 | - # 提取参数 | ||
| 180 | - block_size = params.get("block_size") | ||
| 181 | - selected_count = params.get("selected_count") | ||
| 182 | - b = params.get("b") | ||
| 183 | - s1 = params.get("s1") | ||
| 184 | - n1 = params.get("n1") | ||
| 185 | - d = params.get("d") | ||
| 186 | - block_num = params.get("block_num") | ||
| 187 | - max_block_num = params.get("max_block_num") | ||
| 188 | - | ||
| 189 | - query = input_data_map.get("query") | ||
| 190 | - key = input_data_map.get("key") | ||
| 191 | - q_scale = input_data_map.get("q_scale") | ||
| 192 | - k_scale = input_data_map.get("k_scale") | ||
| 193 | - weights = input_data_map.get("weights") | ||
| 194 | - act_seq = input_data_map.get("act_seq") | ||
| 195 | - block_table = input_data_map.get("block_table") | ||
| 196 | - | ||
| 197 | - topk_res = torch.zeros([b * s1, 1, selected_count], dtype=torch.int32) | ||
| 198 | - first_mm = torch.zeros(b * s1 * n1, max_block_num * block_size, dtype=torch.float16) | ||
| 199 | - mm_out = torch.zeros([b * s1 * 1, max_block_num * block_size], dtype=torch.float32) | ||
| 200 | - avoid_fp32_to_fp16_overflow_scale = 1.0 / 2048 | ||
| 201 | - | ||
| 202 | - # 重塑张量形状 | ||
| 203 | - query = query.reshape(b * s1 * n1, d) | ||
| 204 | - q_scale = q_scale.reshape(b * s1, 1, n1) | ||
| 205 | - key = key.reshape(block_num * block_size, d) | ||
| 206 | - k_scale = k_scale.reshape(block_num, block_size) | ||
| 207 | - weights = weights.reshape(b * s1, 1, n1) | ||
| 208 | - | ||
| 209 | - for b_idx in range(b): | ||
| 210 | - cur_seq = act_seq[b_idx] | ||
| 211 | - cur_block = (cur_seq + block_size - 1) // block_size | ||
| 212 | - # cur_qs的形状为(s1, 1, n1) | ||
| 213 | - cur_qs = q_scale[b_idx * s1:(b_idx + 1) * s1, :, :] | ||
| 214 | - # cur_w的形状为(s1, 1, n1) | ||
| 215 | - cur_w = weights[b_idx * s1:(b_idx + 1) * s1, :, :] | ||
| 216 | - w_scale = cur_qs * cur_w # (s1, 1, n1), fp16 | ||
| 217 | - | ||
| 218 | - for block_idx in range(cur_block): | ||
| 219 | - # cur_q的形状为(s1 * n1, d) | ||
| 220 | - cur_q = query[b_idx * s1 * n1:(b_idx + 1) * s1 * n1, :] | ||
| 221 | - cur_block_idx = block_table[b_idx][block_idx] | ||
| 222 | - tail_seq = min(block_size, cur_seq - block_size * block_idx) | ||
| 223 | - # cur_k形状为(tail_seq, d) | ||
| 224 | - cur_k = key[cur_block_idx * block_size:(cur_block_idx * block_size + tail_seq), :] | ||
| 225 | - # 使用随路量化计算,qk_dot形状为(s1 * n1, tail_seq) | ||
| 226 | - qk_dot = torch.matmul(cur_q.to(torch.int32), cur_k.transpose(1, 0).to(torch.int32)).to(torch.float32).relu() | ||
| 227 | - qk_dot = qk_dot * avoid_fp32_to_fp16_overflow_scale | ||
| 228 | - qk_dot = qk_dot.to(torch.float16) | ||
| 229 | - first_mm[ | ||
| 230 | - b_idx * s1 * n1:(b_idx + 1) * s1 * n1, block_idx * block_size:(block_idx * block_size + tail_seq) | ||
| 231 | - ] = qk_dot | ||
| 232 | - qk_dot = qk_dot.reshape(s1, n1, tail_seq) | ||
| 233 | - | ||
| 234 | - # cur_ks形状为(1, tail_seq) | ||
| 235 | - cur_ks = k_scale[cur_block_idx:(cur_block_idx + 1), :tail_seq] | ||
| 236 | - cur_ks = cur_ks.to(torch.float32) | ||
| 237 | - # w_qk形状为(s1, 1, tail_seq) | ||
| 238 | - w_qk = torch.bmm(w_scale.to(torch.float32), qk_dot.to(torch.float32)) | ||
| 239 | - w_qk = w_qk.reshape(s1, tail_seq) | ||
| 240 | - # k_res形状为(s1, tail_seq), fp32 | ||
| 241 | - k_res = w_qk * cur_ks | ||
| 242 | - mm_out[b_idx * s1:(b_idx + 1) * s1, block_idx * block_size:(block_idx * block_size + tail_seq)] = k_res | ||
| 243 | - # Top-k选择,对每个批次 b_idx 和每个序列 s_idx 进行处理 | ||
| 244 | - for b_idx in range(b): | ||
| 245 | - cur_seq = act_seq[b_idx] | ||
| 246 | - for s_idx in range(s1): | ||
| 247 | - # 计算当前序列的有效长度 eff_seq | ||
| 248 | - eff_seq = cur_seq - (s1 - s_idx - 1) | ||
| 249 | - # 从mm_out中提取当前序列的点积结果topk_in | ||
| 250 | - topk_in = mm_out[(b_idx * s1 + s_idx):(b_idx * s1 + s_idx + 1), :eff_seq] # (1, act_seq) | ||
| 251 | - # 如果有效长度小于 selected_count,则进行Top-k选择,并填充结果 | ||
| 252 | - if eff_seq < selected_count: | ||
| 253 | - cur_res, cur_idx = torch.topk(topk_in, k=eff_seq, dim=-1) # (1, eff_seq) | ||
| 254 | - pad_res = torch.full((1, selected_count - eff_seq), float("-inf"), dtype=torch.float32) | ||
| 255 | - pad_idx = torch.full((1, selected_count - eff_seq), -1, dtype=torch.int32) | ||
| 256 | - cur_res = torch.cat([cur_res, pad_res], dim=1) | ||
| 257 | - cur_idx = torch.cat([cur_idx, pad_idx], dim=1) | ||
| 258 | - topk_res[(b_idx * s1 + s_idx):(b_idx * s1 + s_idx + 1), :, :] = cur_idx.reshape(1, 1, selected_count) | ||
| 259 | - else: | ||
| 260 | - cur_res, cur_idx = torch.topk(topk_in, k=selected_count, dim=-1) # (1, selected_count) | ||
| 261 | - topk_res[(b_idx * s1 + s_idx):(b_idx * s1 + s_idx + 1), :, :] = cur_idx.reshape(1, 1, selected_count) | ||
| 262 | - | ||
| 263 | - return topk_res | ||
| 264 | - | ||
| 265 | - | ||
| 266 | -def topk_idx_compare(t: torch.Tensor, t_ref: torch.Tensor, name, atol, error_count_threshold): | ||
| 267 | - part_result_dict = {} | ||
| 268 | - err_msg = None | ||
| 269 | - | ||
| 270 | - # 按元素遍历比较 | ||
| 271 | - for idx, (act, exp) in enumerate(zip(t.flatten().tolist(), t_ref.flatten().tolist())): | ||
| 272 | - # 按误差阈值分组(每组包含error_count_threshold个元素) | ||
| 273 | - part_index = idx // error_count_threshold | ||
| 274 | - # 记录不匹配的索引 | ||
| 275 | - if exp != act: | ||
| 276 | - if part_index not in part_result_dict: | ||
| 277 | - part_result_dict[part_index] = { | ||
| 278 | - "exp": [], # 预期索引列表 | ||
| 279 | - "act": [], # 实际索引列表 | ||
| 280 | - } | ||
| 281 | - part_result_dict[part_index]["exp"].append(exp) | ||
| 282 | - part_result_dict[part_index]["act"].append(act) | ||
| 283 | - | ||
| 284 | - # 初始化精度状态 | ||
| 285 | - precision = "PASS" | ||
| 286 | - | ||
| 287 | - # 遍历所有分组进行比较 | ||
| 288 | - for idx_index in part_result_dict.keys(): | ||
| 289 | - exp_list = part_result_dict[idx_index]["exp"] | ||
| 290 | - act_list = part_result_dict[idx_index]["act"] | ||
| 291 | - | ||
| 292 | - # 排序后比较 | ||
| 293 | - exp_list.sort() | ||
| 294 | - act_list.sort() | ||
| 295 | - | ||
| 296 | - # 统计错误数量 | ||
| 297 | - error_count = 0 | ||
| 298 | - for topk_id in exp_list: | ||
| 299 | - if topk_id not in act_list: | ||
| 300 | - error_count += 1 | ||
| 301 | - | ||
| 302 | - if error_count > int(error_count_threshold * atol): | ||
| 303 | - precision = "FAIL" | ||
| 304 | - err_msg = f"compare fail: {name}, error_count: {error_count}, \ | ||
| 305 | - error_count_threshold: {int(error_count_threshold * atol)}" | ||
| 306 | - break | ||
| 307 | - assert precision == "PASS", err_msg | ||
| 308 | - | ||
| 309 | - | ||
| 310 | -def lightning_indexer(case_name: str) -> bool: | ||
| 311 | - from lightning_indexer_quant_impl import lightning_indexer_decode | ||
| 312 | - | ||
| 313 | - # 设置设备ID | ||
| 314 | - device_id = int(os.environ.get('TILE_FWK_DEVICE_ID', 0)) | ||
| 315 | - torch.npu.set_device(device_id) | ||
| 316 | - | ||
| 317 | - # 基础参数配置 | ||
| 318 | - n1, d = 64, 128 # query头数和维度 | ||
| 319 | - n2 = 1 # key头数 | ||
| 320 | - block_size = 128 # 块大小 | ||
| 321 | - dtype = torch.float16 # 数据类型 | ||
| 322 | - | ||
| 323 | - # 根据测试用例名称配置参数 | ||
| 324 | - if case_name == "LightningIndexerSTest.lightning_indexer_quant_4_b_2_s1_64k_s2": | ||
| 325 | - b, s1 = 4, 2 # batch size和query序列长度 | ||
| 326 | - act_seq = [64 * 1024, 971, 32 * 1024 + 101, 16 * 1024 - 1] # 每个样本的实际序列长度 | ||
| 327 | - elif case_name == "LightningIndexerSTest.lightning_indexer_quant_8_b_2_s1_64k_s2": | ||
| 328 | - b, s1 = 8, 2 | ||
| 329 | - act_seq = [32767, 32656, 384, 2000, 64 * 1024, 971, 32 * 1024 + 101, 129090] | ||
| 330 | - elif case_name == "LightningIndexerSTest.lightning_indexer_quant_4_b_2_s1_64k_s2_perf": | ||
| 331 | - b, s1 = 4, 2 # batch size和query序列长度 | ||
| 332 | - act_seq = [64 * 1024] * b # 每个样本的实际序列长度 | ||
| 333 | - else: | ||
| 334 | - logging.error("Fail to gen golden for Case(%s)", case_name) | ||
| 335 | - return False | ||
| 336 | - # 计算关键参数 | ||
| 337 | - s2 = max(act_seq) # 最大序列长度 | ||
| 338 | - block_num = sum([(s + block_size - 1) // block_size for s in act_seq]) # 总块数 | ||
| 339 | - max_block_num = (s2 + block_size - 1) // block_size # 最大块数 | ||
| 340 | - selected_count = 2048 # TopK选择数量 | ||
| 341 | - | ||
| 342 | - # 构建参数字典 | ||
| 343 | - params = { | ||
| 344 | - "b": b, | ||
| 345 | - "s1": s1, | ||
| 346 | - "n1": n1, | ||
| 347 | - "n2": n2, | ||
| 348 | - "d": d, | ||
| 349 | - "dtype": dtype, | ||
| 350 | - "s2": s2, | ||
| 351 | - "act_seq": act_seq, | ||
| 352 | - "block_size": block_size, | ||
| 353 | - "block_num": block_num, | ||
| 354 | - "max_block_num": max_block_num, | ||
| 355 | - "selected_count": selected_count, | ||
| 356 | - } | ||
| 357 | - | ||
| 358 | - input_data_map = gen_data_for_compute(params, is_quant=True) | ||
| 359 | - | ||
| 360 | - idx_query_npu = input_data_map["query"].reshape(b * s1, n1, d).npu() | ||
| 361 | - idx_query_scale_npu = input_data_map["q_scale"].reshape(b * s1, n1).npu() | ||
| 362 | - idx_key_cache_npu = input_data_map["key"].npu() | ||
| 363 | - idx_key_scale_npu = input_data_map["k_scale"].reshape(block_num, block_size, 1).npu() | ||
| 364 | - idx_weight_npu = input_data_map["weights"].reshape(b * s1, n1).npu() | ||
| 365 | - act_seq_key_npu = input_data_map["act_seq"].npu() | ||
| 366 | - block_table_npu = input_data_map["block_table"].npu() | ||
| 367 | - | ||
| 368 | - topk_res_out = torch.zeros([b * s1, 1, selected_count], dtype=torch.int32) | ||
| 369 | - topk_res_npu = topk_res_out.npu() | ||
| 370 | - | ||
| 371 | - unroll_list = [128, 64, 32, 16, 8, 4, 1] | ||
| 372 | - configs = LightningIndexerConfigs() | ||
| 373 | - | ||
| 374 | - lightning_indexer_decode( | ||
| 375 | - idx_query_npu, | ||
| 376 | - idx_query_scale_npu, | ||
| 377 | - idx_key_cache_npu, | ||
| 378 | - idx_key_scale_npu, | ||
| 379 | - idx_weight_npu, | ||
| 380 | - act_seq_key_npu, | ||
| 381 | - block_table_npu, | ||
| 382 | - topk_res_npu, | ||
| 383 | - unroll_list, | ||
| 384 | - configs, | ||
| 385 | - selected_count, | ||
| 386 | - ) | ||
| 387 | - | ||
| 388 | - torch_npu.npu.synchronize() | ||
| 389 | - | ||
| 390 | - topk_res_golden = lightning_indexer_compute(input_data_map, params) | ||
| 391 | - topk_idx_compare(topk_res_npu.cpu(), topk_res_golden.cpu(), "topk_res", 5e-4, selected_count) | ||
| 392 | - | ||
| 393 | - return True | ||
| 394 | - | ||
| 395 | - | ||
| 396 | -@pypto.options(pass_options={"enable_slice": True}) | ||
| 397 | -def test_lightning_indexer_topk_quant_4_b_2_s1_64k_s2(): | ||
| 398 | - lightning_indexer("LightningIndexerSTest.lightning_indexer_quant_4_b_2_s1_64k_s2") | ||
| 399 | - | ||
| 400 | - | ||
| 401 | -@pypto.options(pass_options={"enable_slice": True}) | ||
| 402 | -def test_lightning_indexer_topk_quant_8_b_2_s1_64k_s2(): | ||
| 403 | - lightning_indexer("LightningIndexerSTest.lightning_indexer_quant_8_b_2_s1_64k_s2") | ||
| 404 | - | ||
| 405 | - | ||
| 406 | -@pytest.mark.skip(reason="large shape") | ||
| 407 | -@pypto.options(pass_options={"enable_slice": True}) | ||
| 408 | -def test_lightning_indexer_topk_quant_4_b_2_s1_64k_s2_perf(): | ||
| 409 | - lightning_indexer("LightningIndexerSTest.lightning_indexer_quant_4_b_2_s1_64k_s2_perf") | ||
| 410 | - | ||
| 411 | - | ||
| 412 | -if __name__ == "__main__": | ||
| 413 | - test_lightning_indexer_topk_quant_4_b_2_s1_64k_s2() | ||
| 414 | - test_lightning_indexer_topk_quant_8_b_2_s1_64k_s2() | ||
| 415 | - test_lightning_indexer_topk_quant_4_b_2_s1_64k_s2_perf() | ||