Merged
SIMT新增Cache访问优化样例 #2453
SIMT新增Cache访问优化样例 #2453
Merged
ruoshuisixueAdd on May 22
Total: 8 files changed+606-1
@@ -290,6 +290,7 @@
290 - [内存访问](算子实践参考/SIMT算子性能优化/内存访问/访存合并.md)290 - [内存访问](算子实践参考/SIMT算子性能优化/内存访问/访存合并.md)
291 - [访存合并](算子实践参考/SIMT算子性能优化/内存访问/访存合并.md)291 - [访存合并](算子实践参考/SIMT算子性能优化/内存访问/访存合并.md)
292 - [避免UB的Bank冲突](算子实践参考/SIMT算子性能优化/内存访问/避免UB的Bank冲突.md)292 - [避免UB的Bank冲突](算子实践参考/SIMT算子性能优化/内存访问/避免UB的Bank冲突.md)
293+ - [DCache访问优化](算子实践参考/SIMT算子性能优化/内存访问/DCache访问优化.md)
293 294 
294 - [优秀实践](算子实践参考/优秀实践/优秀实践.md)295 - [优秀实践](算子实践参考/优秀实践/优秀实践.md)
295 - [FlashAttention算子性能调优案例](算子实践参考/优秀实践/FlashAttention算子性能调优案例.md)296 - [FlashAttention算子性能调优案例](算子实践参考/优秀实践/FlashAttention算子性能调优案例.md)
@@ -0,0 +1,79 @@
1+# DCache访问优化
2+ 
3+【优先级】中
4+ 
5+【描述】SIMT编程模式下,经由DCache访问Global Memory数据。当算子中存在多种不同访问模式的数据时,如仅遍历一次的输入数据与需要反复访问的热点数据,若不加区分,所有数据会共同竞争DCache空间,导致热点数据被其他数据挤出DCache,后续再次访问热点数据时需要从GM重新加载,增加访存时间。此时可以通过不同访存函数,为不同类型的数据指定不同的缓存策略,使热点数据优先驻留DCache,减少不必要的GM访问。
6+ 
7+SIMT编程模式下提供以下访存函数:
8+ 
9+- **`asc_ldcg`**:加载数据时从Global Memory加载,适用于仅遍历一次的输入数据,减少其对DCache空间的占用。
10+- **`asc_ldca`**:加载数据时优先从DCache加载,适用于需要频繁访问的热点数据(如查找表),确保热点数据常驻DCache,减少从Global Memory重新加载的次数。
11+- **`asc_stcg`**:存储数据时直接缓存到Global Memory空间,适用于数据写到GM后不会再被使用,不需要使用Cache缓存,避免输出数据占用DCache空间影响热点数据的缓存。
12+ 
13+【样例介绍】以[sin查表算子](https://gitcode.com/cann/asc-devkit/tree/master/examples/03_simt_api/03_best_practices/03_simt_data_cache_hint)为例,使用查表法计算sin值,通过线性插值提高精度。输入数据长度为65536(256KB),sin查找表长度为8192(32KB)。算法实现中,每个线程根据输入值计算查找表索引,根据索引从sin表中读取对应位置及其后续位置的数据,通过线性插值得到结果。其中每个输入数据仅访问一次,属于非热点数据;sin查找表会被反复访问,属于热点数据。
14+ 
15+【反例】所有数据使用默认方式加载,输入、输出和sin表数据共同竞争DCache空间。
16+ 
17+```
18+__global__ void sin_table_lookup_baseline(float* input, float* sin_table, float* output,
19+ uint32_t input_length, uint32_t table_length)
20+{
21+ for (int idx = threadIdx.x; idx < input_length; idx += blockDim.x) {
22+ float x = input[idx];
23+ ...
24+ float low_val = sin_table[n];
25+ float high_val = 0.0f;
26+ if (n + 1 >= table_length) {
27+ high_val = sin_table[0];
28+ } else {
29+ high_val = sin_table[n + 1];
30+ }
31+ output[idx] = sign * (low_val + frac * (high_val - low_val));
32+ }
33+}
34+```
35+ 
36+上述实现中,`input[idx]`、`sin_table[n]`、`sin_table[n+1]`和 `output[idx]`均使用默认方式加载访问Global Memory。输入数据虽然仅访问一次,但其加载时会占用DCache空间;输出数据写入后也可能驻留DCache。当输入和输出数据大量加载时,sin查找表的数据会被挤出DCache,导致后续线程查表时需要重新从Global Memory加载,增加DCache Read GM次数。
37+ 
38+反例算子的性能数据如下:
39+ 
40+| Task Duration(us) | DCache Read GM(次) | DCache Read Vector(次) | DCache Write Vector(次) |
41+|:-----------------:|:-----------------:|:---------------------:|:----------------------:|
42+| 56.82 | 5064 | 2048 | 6144 |
43+ 
44+【正例】使用访存函数区分不同数据的缓存策略。
45+ 
46+```
47+__global__ void sin_table_lookup_optimized(float* input, float* sin_table, float* output,
48+ uint32_t input_length, uint32_t table_length)
49+{
50+ for (int idx = threadIdx.x; idx < input_length; idx += blockDim.x) {
51+ float x = asc_ldcg(&input[idx]);
52+ ...
53+ float low_val = asc_ldca(&sin_table[n]);
54+ float high_val = 0.0f;
55+ if (n + 1 >= table_length) {
56+ high_val = asc_ldca(&sin_table[0]);
57+ } else {
58+ high_val = asc_ldca(&sin_table[n + 1]);
59+ }
60+ float y = sign * (low_val + frac * (high_val - low_val));
61+ asc_stcg(&output[idx], y);
62+ }
63+}
64+```
65+ 
66+上述实现中:
67+- 输入数据使用`asc_ldcg`加载,输入数据直接从Global Memory读取,不需要占用DCache空间,避免输入数据对DCache的占用;
68+- sin查找表使用`asc_ldca`加载,优先为sin表数据分配DCache空间,确保sin表常驻DCache;
69+- 输出数据使用`asc_stcg`写入,直接写入Global Memory,不经过DCache缓存,避免输出数据占用DCache影响热点数据的缓存。
70+ 
71+正例算子的性能数据如下:
72+ 
73+| Task Duration(us) | DCache Read GM(次) | DCache Read Vector(次) | DCache Write Vector(次) |
74+|:-----------------:|:-----------------:|:---------------------:|:----------------------:|
75+| 50.895 | 3531 | 2048 | 6144 |
76+ 
77+从Task Duration看,优化后的执行耗时为50.895us,相比优化前的56.82us,下降约10.4%。从DCache Read GM看,优化后为3531次,相比优化前的5064次,减少约30.2%(减少1533次GM访问)。这说明优化前的主要瓶颈来自所有数据共同竞争DCache空间,导致热点数据(sin查找表)被挤出DCache后需要重新从GM加载;通过访存函数区分缓存策略后,sin查找表优先驻留DCache,减少了从GM重新加载的次数,DCache命中率提升,整体性能得到改善。
78+ 
79+【总结】当SIMT算子中存在多种不同访问模式的数据时,应分析各类数据的访问特征,通过访存函数为不同类型的数据指定合适的缓存策略:对仅遍历一次的数据使用`asc_ldcg`降低其Cache占用优先级;对需要频繁访问的热点数据使用`asc_ldca`确保其常驻DCache;对写入后无需驻留DCache的输出数据使用`asc_stcg`优化写入后的Cache分配。这样可以减少热点数据被挤出DCache的情况,降低GM访问次数,提升算子整体性能。
@@ -0,0 +1,36 @@
1+# ----------------------------------------------------------------------------------------------------------
2+# This program is free software, you can redistribute it and/or modify it.
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This file is a part of the CANN Open Software.
5+# Licensed under 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+cmake_minimum_required(VERSION 3.16)
14+ 
15+set(SCENARIO_NUM 1 CACHE STRING "Case type to run (1-2)")
16+set(CMAKE_ASC_ARCHITECTURES "dav-3510" CACHE STRING "NPU ARCH, e.g. dav-3510")
17+ 
18+find_package(ASC REQUIRED)
19+ 
20+project(kernel_samples LANGUAGES ASC CXX)
21+ 
22+add_executable(data_cache_hint
23+ data_cache_hint.asc
24+)
25+ 
26+target_compile_definitions(data_cache_hint PRIVATE
27+ SCENARIO_NUM=${SCENARIO_NUM}
28+)
29+ 
30+target_link_libraries(data_cache_hint PRIVATE
31+ m
32+)
33+ 
34+target_compile_options(data_cache_hint PRIVATE
35+ $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${CMAKE_ASC_ARCHITECTURES} --enable-simt>
36+)
@@ -0,0 +1,248 @@
1+# DataCacheHint性能调优样例
2+ 
3+## 概述
4+ 
5+本样例以查表法计算sin值为例,介绍Ascend C SIMT编程方式下的数据缓存优化思路。样例包含1个基线版本以及1个优化版本,基线版本中所有数据使用默认方式加载,输入、输出和sin表数据共同竞争DCache空间;优化版本为不同类型的数据指定不同的的缓存策略,确保频繁访问的sin查找表常驻DCache,减少Global Memory访问次数,展示SIMT编程方式下数据缓存优化的调优路径。
6+ 
7+## 支持的产品
8+ 
9+- Ascend 950PR/Ascend 950DT
10+ 
11+## 支持的CANN软件版本
12+ 
13+- \> CANN 9.0.0
14+ 
15+## 目录结构介绍
16+ 
17+```text
18+├── 03_simt_data_cache_hint
19+│ ├── CMakeLists.txt // cmake编译文件
20+│ ├── data_cache_hint.asc // SIMT数据缓存样例实现
21+│ ├── figures // README中的图片资源
22+│ └── README.md
23+```
24+ 
25+## 样例描述
26+ 
27+- 样例功能
28+ 
29+ 使用查表法计算sin值,通过线性插值提高精度。
30+ 
31+- 样例规格:
32+ 
33+ <table>
34+ <tr><td rowspan="1" align="center">样例类型(OpType)</td><td colspan="4" align="center">SinTableLookup</td></tr>
35+ <tr><td rowspan="3" align="center">样例输入</td><td align="center">name</td><td align="center">shape</td><td align="center">data type</td><td align="center">format</td></tr>
36+ <tr><td align="center">input</td><td align="center">[65536]</td><td align="center">float</td><td align="center">ND</td></tr>
37+ <tr><td align="center">sin_table</td><td align="center">[8192]</td><td align="center">float</td><td align="center">ND</td></tr>
38+ <tr><td rowspan="1" align="center">样例输出</td><td align="center">output</td><td align="center">[65536]</td><td align="center">float</td><td align="center">ND</td></tr>
39+ <tr><td rowspan="1" align="center">核函数名</td><td colspan="4" align="center">sin_table_lookup_baseline / sin_table_lookup_optimized</td></tr>
40+ </table>
41+ 
42+## 样例实现
43+ 
44+### 查表法计算说明
45+ 
46+本样例使用查表法计算sin值,核心思路是预先将[0, π]区间的sin值存入查找表,通过线性插值获取任意角度的sin近似值。计算流程如下:
47+ 
48+1. 将输入角度归约到[0, π]区间,处理负数和周期性
49+2. 计算查找表索引:`index_float = x / π * table_length`
50+3. 获取`index_float`的整数部分`n`和小数部分`frac`
51+4. 从查找表读取`table[n]`和`table[n+1]`
52+5. 线性插值得到结果:`y = table[n] + frac * (table[n+1] - table[n])`
53+ 
54+### 样例实现说明
55+ 
56+本样例通过2个独立的kernel实现不同的数据缓存策略,每个kernel对应特定的Case版本。
57+ 
58+| Case | 实现特点 | 使用的核函数 | 优化特性 |
59+|--------|----------------------------------------------------------------------|----------------------------|---------------------|
60+| Case 0 | 所有数据使用默认方式加载,输入、输出和sin表数据共同竞争DCache空间 | sin_table_lookup_baseline | 基线版本,无缓存优化 |
61+| Case 1 | 输入数据`x`直接从GM加载,输入数据`sin_table`为热点数据,优先从DCache加载,减少对GM的加载,输出数据直接写出到GM | sin_table_lookup_optimized | 数据缓存优化,sin表常驻DCache |
62+ 
63+#### 1. 数据加载特点
64+ 
65+在样例中,为了体现性能差异,构造DCache空间大小为32KB的场景。默认的数据加载会优先从DCache读取,若DCache中数据不存在,则从Global Memory(GM)加载并同时缓存到DCache中。本样例中三类数据的访问特征如下:
66+ 
67+| 数据 | 大小 | 访问特征 |
68+|-----------|-------|-------------------|
69+| input | 256KB | 每个元素仅读取一次 |
70+| sin_table | 32KB | 数据被反复访问,属于热点数据 |
71+| output | 256KB | 每个元素仅写入一次,写入后不再读取 |
72+ 
73+默认情况下,加载的数据会在DCache中保存。在计算过程中,部分热点数据会被多个线程中多次使用,但另一部分数据在计算的过程中仅使用一次,这类数据不需要进行缓存,不应让这类数据与热点数据竞争DCache空间
74+ 
75+- **`asc_ldcg`**:加载数据时从Global Memory加载,适用于仅遍历一次的输入数据,减少其对DCache空间的占用
76+- **`asc_ldca`**:加载数据时优先从DCache加载,适用于需要频繁访问的热点数据(如查找表),确保热点数据常驻DCache,减少从Global Memory重新加载的次数
77+- **`asc_stcg`**:存储数据时直接缓存到Global Memory空间,适用于数据写到GM后不会再被使用,不需要使用Cache缓存,避免输出数据占用DCache空间影响热点数据的缓存
78+- input数据通过`asc_ldcg`直接从GM加载,不缓存到DCache
79+- sin_table数据通过`asc_ldca`优先从DCache加载,确保常驻DCache
80+- output数据通过`asc_stcg`直接写入GM,不经过DCache缓存
81+ 
82+由于sin_table大小为32KB,可以缓存到DCache后不会被挤出,热点数据持续驻留DCache,可减少sin_table数据从GM→DCache的反复加载。
83+ 
84+---
85+### 性能指标说明
86+ 
87+| 指标 | 说明 |
88+|---------------------|-----------------------------|
89+| Task Duration(us) | 整个任务执行的总时间,算子执行时间以该参数为准 |
90+| DCache Read GM | DCache从Global Memory读取数据的次数 |
91+| DCache Read Vector | Vector Core从DCache读取数据的次数 |
92+| DCache Write Vector | Vector Core向DCache写入数据的次数 |
93+---
94+ 
95+### Case 0: 基线版本
96+ 
97+**样例目标**:建立查表法计算sin值的耗时基线,观察输入、输出和sin表数据共同竞争DCache空间对性能的影响
98+ 
99+**核心实现**:
100+- 直接读取`input[idx]`和`sin_table[n]` / `sin_table[n+1]`的数据
101+- 使用线性差值进行计算数据结果
102+- 线程直接写回`output[idx]`
103+- 所有数据访问使用默认方式加载,`input`、`sin_table`和`output`数据共同竞争DCache空间
104+ 
105+当访问大量输入和输出数据时,sin查找表的数据会被换出DCache,导致后续查表时需要重新从GM加载,增加访存延迟。
106+ 
107+**关键代码**:
108+```cpp
109+float x = input[idx];
110+float index_float = x * static_cast<float>(table_length) / PI;
111+uint32_t n = static_cast<uint32_t>(floorf(index_float));
112+float frac = index_float - static_cast<float>(n);
113+float low_val = sin_table[n];
114+float high_val = sin_table[n + 1];
115+output[idx] = sign * (low_val + frac * (high_val - low_val));
116+```
117+ 
118+**性能数据**:
119+ 
120+| Task Duration(us) | DCache Read GM | DCache Read Vector | DCache Write Vector |
121+|:-----------------:|:-----------------:|:---------------------:|:----------------------:|
122+| 56.82 | 5064 | 2048 | 6144 |
123+ 
124+**分析**:
125+ 
126+Case 0的Task Duration为56.82us,DCache Read GM为5064次,作为基线版本。
127+ 
128+Case0的场景中,加载input,output时会把数据缓存在DCache上,替换Dcache中某个缓存数据,假设sin2的数据被替换掉了,当后续某个线程计算时需要sin2的数据,就会出现cache miss,需要从GM重新加载。此外,被缓存到DCache上的input和output数据实际上不会再被使用,不需要缓存,不应该占用DCache空间。
129+ 
130+<img src="./figures/DCache访问优化.png" width="80%">
131+ 
132+优化方向:加载input,output的时不需要缓存DCache上,保证table数据常驻DCache,后续在使用sin2数据的时,可以直接从DCache加载,不需要GM重新加载数据。
133+ 
134+---
135+ 
136+### Case 1: 数据缓存优化版本
137+ 
138+**优化目标**:通过访存函数区分不同数据的缓存策略,确保sin查找表常驻DCache,减少GM访问次数,降低端到端耗时
139+ 
140+**核心优化**:
141+- 使用`asc_ldcg`读取数据:每个输入数据仅访问一次,不需要使用DCache
142+- 使用`asc_ldca`读取sin表数据:sin表是热点数据,需要频繁访问,确保数据常驻DCache
143+- 使用`asc_stcg`写出数据:输出数据写到GM后不会再被使用,不需要使用DCache
144+ 
145+**关键代码**:
146+```cpp
147+float x = asc_ldcg(&input[idx]);
148+float index_float = x * static_cast<float>(table_length) / PI;
149+uint32_t n = static_cast<uint32_t>(floorf(index_float));
150+float frac = index_float - static_cast<float>(n);
151+float low_val = asc_ldca(&sin_table[n]);
152+float high_val = asc_ldca(&sin_table[n + 1]);
153+float y = sign * (low_val + frac * (high_val - low_val));
154+asc_stcg(&output[idx], y);
155+```
156+ 
157+**性能数据**:
158+ 
159+| Task Duration(us) | DCache Read GM(次) | DCache Read Vector(次) | DCache Write Vector(次) |
160+|:-----------------:|:-----------------:|:---------------------:|:----------------------:|
161+| 50.895 | 3531 | 2048 | 6144 |
162+ 
163+**分析**:
164+- 相比Case 0基线版本,Task Duration从56.82us降低到50.895us,耗时下降约10.4%
165+- DCache Read GM从5064次降至3531次,减少约30.2%(减少1533次Global Memory访问),这是性能提升的关键因素
166+- DCache Read Vector和DCache Write Vector保持不变,说明优化没有增加额外开销
167+- sin表数据常驻DCache后,避免被输入/输出数据挤出,减少了从Global Memory重新加载sin表的次数
168+---
169+ 
170+## 性能对比总结
171+ 
172+### Ascend 950PR性能数据
173+**综合优化效果**:
174+- 从Case 0基线版本到Case 1优化版本,Task Duration从56.82us降低到50.895us,耗时下降约10.4%
175+- DCache Read GM从5064次降至3531次,减少约30.2%,减少1533次Global Memory访问
176+ 
177+| Case version | Task Duration(us) | Task Duration相对Case 0 | 优化点 |
178+|--------------|-------------------|-----------------------|-----------------------|
179+| Case 0 | 56.82 | **1x** | 基线版本,所有数据共同竞争DCache空间 |
180+| Case 1 | 50.895 | **0.90x耗时** | 数据缓存优化,sin表常驻DCache空间 |
181+ 
182+## 调优建议
183+ 
184+1. **识别热点数据**:在查表类算子中,查找表是频繁访问的热点数据,应优先保证其常驻DCache。
185+2. **区分数据访问模式**:对于仅访问一次的数据(如输入数据),使用`asc_ldcg`避免其对DCache空间的占用;对于需要频繁访问的数据(如查找表),使用`asc_ldca`优先分配Cache空间。
186+3. **避免写出数据占用Cache**:对于写入后不再读取的输出数据,使用`asc_stcg`避免其占用DCache空间。
187+4. **关注DCache Read GM指标**:DCache Read GM次数的减少直接反映了Cache命中率提升和Global Memory访问延迟降低的效果。
188+ 
189+## 编译运行
190+在本样例根目录下执行如下步骤,编译并执行样例。
191+- 配置环境变量
192+ 请根据当前环境上CANN开发套件包的[安装方式](../../../../docs/quick_start.md#prepare&install),选择对应配置环境变量的命令。
193+ - 默认路径,root用户安装CANN软件包
194+ ```bash
195+ source /usr/local/Ascend/cann/set_env.sh
196+ ```
197+ 
198+ - 默认路径,非root用户安装CANN软件包
199+ ```bash
200+ source $HOME/Ascend/cann/set_env.sh
201+ ```
202+ 
203+ - 指定路径install_path,安装CANN软件包
204+ ```bash
205+ source ${install_path}/cann/set_env.sh
206+ ```
207+ 
208+- 样例执行
209+ ```bash
210+ SCENARIO_NUM=1 # 选择执行场景,可选1-2
211+ mkdir -p build && cd build; # 创建并进入build目录
212+ cmake -DCMAKE_ASC_ARCHITECTURES=dav-3510 -DSCENARIO_NUM=$SCENARIO_NUM ..;make -j; # 编译工程
213+ ./data_cache_hint # 执行样例
214+ ```
215+ 
216+- 编译选项说明
217+ 
218+ | 选项 | 可选值 | 说明 |
219+ |---------------------------|------------|---------------------------------------------------|
220+ | `CMAKE_ASC_ARCHITECTURES` | `dav-3510` | NPU 架构:本样例仅支持 dav-3510(Ascend 950PR/Ascend 950DT) |
221+ | `SCENARIO_NUM` | `1`-`2` | 样例类型,默认为1 |
222+ 
223+ 执行结果如下,说明精度对比成功。
224+ 
225+ ```text
226+ [Success] Case accuracy is verification passed.
227+ ```
228+ 
229+## 性能分析
230+使用 `msprof` 工具获取详细性能数据:
231+```bash
232+msprof op ./data_cache_hint # 分析case的性能
233+```
234+ 
235+命令完成后,会在默认目录下生成以"OPPROF_{timestamp}_XXX"命名的文件夹,性能数据文件夹结构示例如下:
236+ 
237+```text
238+├──dump # 原始的性能数据,用户无需关注
239+├──ArithmeticUtilization.csv # cube/vector指令cycle占比
240+├──L2Cache.csv # L2 Cache命中率
241+├──Memory.csv # UB,L1和主存储器读写带宽速率
242+├──MemoryL0.csv # L0A,L0B,和L0C读写带宽速率
243+├──MemoryUB.csv # Vector和Scalar到UB的读写带宽速率
244+├──OpBasicInfo.csv # 算子基础信息
245+├──PipeUtilization.csv # 采集计算单元和搬运单元耗时和占比
246+├──ResourceConflictRatio.csv # UB上的 bank group、bank conflict和资源冲突率在所有指令中的占比
247+└──visualize_data.bin # MindStudio Insight呈现文件
248+```
@@ -0,0 +1,236 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/* !
12+ * \file data_cache_hint.asc
13+ * \brief Demo for data cache hint optimization using asc_ldcg and asc_stcg
14+ */
15+ 
16+#include <cstdint>
17+#include <cstddef>
18+#include <cmath>
19+#include <random>
20+#include <iostream>
21+#include <vector>
22+#include "acl/acl.h"
23+#include "asc_simt.h"
24+ 
25+#ifndef SCENARIO_NUM
26+#define SCENARIO_NUM 1
27+#endif
28+ 
29+#if SCENARIO_NUM < 1 || SCENARIO_NUM > 2
30+#error "SCENARIO_NUM must be one of 1, 2"
31+#endif
32+ 
33+namespace {
34+constexpr float PI = ASCRT_PI_F;
35+constexpr uint32_t INPUT_SIZE = 256 * 1024 / sizeof(float);
36+constexpr uint32_t TABLE_SIZE = 32 * 1024 / sizeof(float);
37+constexpr uint32_t THREAD_COUNT = 1024;
38+constexpr uint32_t UB_SIZE = 216 * 1024;
39+}
40+ 
41+enum KernelKind {
42+ USE_BASELINE = 1,
43+ USE_OPTIMIZED = 2
44+};
45+ 
46+extern __ubuf__ char dynamicBuf[];
47+ 
48+__global__ void sin_table_lookup_baseline(float* input, float* sin_table, float* output, uint32_t input_length,
49+ uint32_t table_length)
50+{
51+ for (int idx = threadIdx.x; idx < input_length; idx += blockDim.x) {
52+ float x = input[idx];
53+ float sign = 1.0f;
54+ if (x < 0.0f) {
55+ sign = -1.0f;
56+ x = -x;
57+ }
58+ float two_pi = 2.0f * PI;
59+ x = fmodf(x, two_pi);
60+ if (x >= PI) {
61+ x = two_pi - x;
62+ sign = -sign;
63+ }
64+ 
65+ float index_float = x * static_cast<float>(table_length) / PI;
66+ uint32_t n = static_cast<uint32_t>(floorf(index_float));
67+ float frac = index_float - static_cast<float>(n);
68+ 
69+ float low_val = sin_table[n];
70+ float high_val = 0.0f;
71+ if (n + 1 >= table_length) {
72+ high_val = sin_table[0];
73+ } else {
74+ high_val = sin_table[n + 1];
75+ }
76+ output[idx] = sign * (low_val + frac * (high_val - low_val));
77+ }
78+}
79+ 
80+__global__ void sin_table_lookup_optimized(float* input, float* sin_table, float* output, uint32_t input_length,
81+ uint32_t table_length)
82+{
83+ for (int idx = threadIdx.x; idx < input_length; idx += blockDim.x) {
84+ float x = asc_ldcg(&input[idx]);
85+ float sign = 1.0f;
86+ if (x < 0.0f) {
87+ sign = -1.0f;
88+ x = -x;
89+ }
90+ float two_pi = 2.0f * PI;
91+ x = fmodf(x, two_pi);
92+ if (x >= PI) {
93+ x = two_pi - x;
94+ sign = -sign;
95+ }
96+ 
97+ float index_float = x * static_cast<float>(table_length) / PI;
98+ uint32_t n = static_cast<uint32_t>(floorf(index_float));
99+ float frac = index_float - static_cast<float>(n);
100+ 
101+ float low_val = asc_ldca(&sin_table[n]);
102+ float high_val = 0.0f;
103+ if (n + 1 >= table_length) {
104+ high_val = asc_ldca(&sin_table[0]);
105+ } else {
106+ high_val = asc_ldca(&sin_table[n + 1]);
107+ }
108+ float y = sign * (low_val + frac * (high_val - low_val));
109+ asc_stcg(&output[idx], y);
110+ }
111+}
112+ 
113+void generate_input_and_golden_data(std::vector<float>& input, std::vector<float>& golden, uint32_t input_length)
114+{
115+ for (int32_t index = 0; index < input_length; index ++) {
116+ input[index] = 2 * PI * index / TABLE_SIZE;
117+ golden[index] = sinf(input[index]);
118+ }
119+}
120+ 
121+void generate_sin_table(std::vector<float>& sin_table, uint32_t table_length)
122+{
123+ for (uint32_t i = 0; i < table_length; i++) {
124+ float angle = static_cast<float>(i) / table_length * PI;
125+ sin_table[i] = sin(angle);
126+ }
127+}
128+ 
129+std::vector<float> launch_kernel(std::vector<float>& input, std::vector<float>& sin_table,
130+ uint32_t input_length, uint32_t table_length, uint32_t kernel_type)
131+{
132+ size_t input_bytes = input_length * sizeof(float);
133+ size_t table_bytes = table_length * sizeof(float);
134+ size_t output_bytes = input_length * sizeof(float);
135+ 
136+ uint32_t num_blocks = 1;
137+ 
138+ int32_t device_id = 0;
139+ aclrtStream stream = nullptr;
140+ void* input_host = reinterpret_cast<void*>(input.data());
141+ void* input_device = nullptr;
142+ void* table_host = reinterpret_cast<void*>(sin_table.data());
143+ void* table_device = nullptr;
144+ void* output_host = nullptr;
145+ void* output_device = nullptr;
146+ 
147+ aclInit(nullptr);
148+ aclrtSetDevice(device_id);
149+ aclrtCreateStream(&stream);
150+ aclrtMallocHost(&output_host, output_bytes);
151+ aclrtMalloc(&input_device, input_bytes, ACL_MEM_MALLOC_HUGE_FIRST);
152+ aclrtMalloc(&table_device, table_bytes, ACL_MEM_MALLOC_HUGE_FIRST);
153+ aclrtMalloc(&output_device, output_bytes, ACL_MEM_MALLOC_HUGE_FIRST);
154+ 
155+ aclrtMemcpy(input_device, input_bytes, input_host, input_bytes, ACL_MEMCPY_HOST_TO_DEVICE);
156+ aclrtMemcpy(table_device, table_bytes, table_host, table_bytes, ACL_MEMCPY_HOST_TO_DEVICE);
157+ 
158+ if (kernel_type == USE_BASELINE) {
159+ sin_table_lookup_baseline<<<num_blocks, THREAD_COUNT, UB_SIZE, stream>>>(
160+ static_cast<float*>(input_device), static_cast<float*>(table_device),
161+ static_cast<float*>(output_device), input_length, table_length);
162+ } else {
163+ sin_table_lookup_optimized<<<num_blocks, THREAD_COUNT, UB_SIZE, stream>>>(
164+ static_cast<float*>(input_device), static_cast<float*>(table_device),
165+ static_cast<float*>(output_device), input_length, table_length);
166+ }
167+ 
168+ aclrtSynchronizeStream(stream);
169+ 
170+ aclrtMemcpy(output_host, output_bytes, output_device, output_bytes, ACL_MEMCPY_DEVICE_TO_HOST);
171+ std::vector<float> output(static_cast<float*>(output_host), static_cast<float*>(output_host) + input_length);
172+ 
173+ aclrtFree(input_device);
174+ aclrtFree(table_device);
175+ aclrtFree(output_device);
176+ aclrtFreeHost(output_host);
177+ 
178+ const char* err = aclGetRecentErrMsg();
179+ if (err != nullptr) {
180+ fprintf(stderr, "%s\n", err);
181+ }
182+ 
183+ aclrtDestroyStream(stream);
184+ aclrtResetDevice(device_id);
185+ aclFinalize();
186+ 
187+ return output;
188+}
189+ 
190+uint32_t verify_result(const std::vector<float> &output, const std::vector<float> &golden, float abs_tolerance = 1e-3f)
191+{
192+ if (output.size() != golden.size()) {
193+ printf("[Failed] Case accuracy is verification failed!\n");
194+ return 1;
195+ }
196+ for (size_t i = 0; i < output.size(); ++i) {
197+ if (std::fabs(output[i] - golden[i]) > abs_tolerance) {
198+ printf("[Failed] Case accuracy is verification failed!\n");
199+ return 1;
200+ }
201+ }
202+ printf("[Success] Case accuracy is verification passed.\n");
203+ return 0;
204+}
205+ 
206+ 
207+const char *get_kernel_name(int kernel_kind)
208+{
209+ switch (kernel_kind) {
210+ case USE_BASELINE:
211+ return "baseline";
212+ case USE_OPTIMIZED:
213+ return "optimized";
214+ default:
215+ return "unknown";
216+ }
217+}
218+ 
219+int32_t main(int32_t argc, char* argv[])
220+{
221+ const uint32_t kernel_kind = static_cast<uint32_t>(SCENARIO_NUM);
222+ printf("Usage: %s (compile-time SCENARIO_NUM=%u)\n", argv[0], kernel_kind);
223+ printf("Running case %u: %s...\n", kernel_kind, get_kernel_name(static_cast<int32_t>(kernel_kind)));
224+ 
225+ std::vector<float> input(INPUT_SIZE);
226+ std::vector<float> sin_table(TABLE_SIZE);
227+ std::vector<float> golden(INPUT_SIZE);
228+ 
229+ generate_input_and_golden_data(input, golden, INPUT_SIZE);
230+ generate_sin_table(sin_table, TABLE_SIZE);
231+ 
232+ printf("=== Running Kernel ===\n");
233+ std::vector<float> output = launch_kernel(input, sin_table, INPUT_SIZE, TABLE_SIZE, SCENARIO_NUM);
234+ 
235+ return verify_result(output, golden);
236+}
@@ -0,0 +1,3 @@
1+version https://git-lfs.github.com/spec/v1
2+oid sha256:50e4b20575124e87d34608c0c0dfc71418cba2271f0311e6a66866e1fd99aa74
3+size 241728
@@ -10,3 +10,4 @@
10| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------- |10| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------- |
11| [01_simt_matrix_transpose](./01_simt_matrix_transpose) | 样例基于Ascend C SIMT编程方式实现MatrixTranspose算子,展示Ascend C SIMT编程方式的性能调优思路。 |11| [01_simt_matrix_transpose](./01_simt_matrix_transpose) | 样例基于Ascend C SIMT编程方式实现MatrixTranspose算子,展示Ascend C SIMT编程方式的性能调优思路。 |
12| [02_short_vector_add](./02_short_vector_add) | 样例基于Ascend C SIMT编程方式实现Add算子,主要演示基于短向量half2性能调优方法。 |12| [02_short_vector_add](./02_short_vector_add) | 样例基于Ascend C SIMT编程方式实现Add算子,主要演示基于短向量half2性能调优方法。 |
13+| [03_simt_data_cache_hint](./03_simt_data_cache_hint) | 样例基于Ascend C SIMT编程方式实现Sin算子,展示SIMT算子的缓存优化能力。 |
@@ -9,4 +9,5 @@ Operator development practices based on Ascend C SIMT, demonstrating the applica
9| Directory Name | Description |9| Directory Name | Description |
10| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------- |10| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------- |
11| [01_simt_matrix_transpose](./01_simt_matrix_transpose) | This example implements the MatrixTranspose operator based on Ascend C SIMT programming, demonstrating performance tuning strategies for Ascend C SIMT programming. |11| [01_simt_matrix_transpose](./01_simt_matrix_transpose) | This example implements the MatrixTranspose operator based on Ascend C SIMT programming, demonstrating performance tuning strategies for Ascend C SIMT programming. |
12-| [02_short_vector_add](./02_short_vector_add) | This example implements the Add operator based on Ascend C SIMT programming, demonstrating performance tuning methods based on the short vector half2. |12+| [02_short_vector_add](./02_short_vector_add) | This example implements the Add operator based on Ascend C SIMT programming, demonstrating performance tuning methods based on the short vector half2. |
13+| [03_simt_data_cache_hint](./03_simt_data_cache_hint) | This example implements the Sin operator based on Ascend C SIMT programming, demonstrating the cache optimization capabilities of SIMT programming. |