Merged
补充l2cache 切分优化说明 #5418
yhf0922Add on Aug 27
补充l2cache 切分优化说明 #5418
Merged
Merged fromyhf0922/asc-devkitls_cache_newintocann/asc-devkitmaster
Total: 17 files changed+1279-125
| @@ -0,0 +1,3 @@ | |||
| 1 | +version https://git-lfs.github.com/spec/v1 | ||
| 2 | +oid sha256:9c4bb2aa2d7b5543d4b2c2a1fde0efebb47a45d95a7c9daae45ac3a2f9d6d69f | ||
| 3 | +size 10276 | ||
| @@ -0,0 +1,3 @@ | |||
| 1 | +version https://git-lfs.github.com/spec/v1 | ||
| 2 | +oid sha256:25a563eaa8d2b112a11bc715849f1f166a96375544e41d227d0250155f26d565 | ||
| 3 | +size 30624 | ||
| @@ -0,0 +1,3 @@ | |||
| 1 | +version https://git-lfs.github.com/spec/v1 | ||
| 2 | +oid sha256:d53647ddc547271c9056ae9e5bc7fe77702eb713750cf282093de09c040ca5a2 | ||
| 3 | +size 22627 | ||
| @@ -0,0 +1,3 @@ | |||
| 1 | +version https://git-lfs.github.com/spec/v1 | ||
| 2 | +oid sha256:0714cb7bb8b976e8bbbe3244387cd3f1f0d2f29ee8311d567ccc81a4c8f957a5 | ||
| 3 | +size 6870 | ||
| @@ -4,143 +4,202 @@ | |||
| 4 | 4 | ||
| 5 | 【描述】假设,AI处理器的L2 Cache大小为192MB,L2 Cache读写混合带宽约为7TB/s,而GM的带宽约为1.6TB/s,两者之间存在较大差距。搬入或搬出相同数据量的情况下,访问L2 Cache读写数据比GM更快。若数据无法命中L2 Cache,即需要访问的数据不在L2 Cache内,导致需要去GM上读写,带宽利用效率较低,最终算子搬入或搬出数据变为算子整个运行过程的性能瓶颈。切分策略建议:当输入和输出数据的数据量超过L2 Cache大小时,Tiling中开启L2 Cache切分策略。 | 5 | 【描述】假设,AI处理器的L2 Cache大小为192MB,L2 Cache读写混合带宽约为7TB/s,而GM的带宽约为1.6TB/s,两者之间存在较大差距。搬入或搬出相同数据量的情况下,访问L2 Cache读写数据比GM更快。若数据无法命中L2 Cache,即需要访问的数据不在L2 Cache内,导致需要去GM上读写,带宽利用效率较低,最终算子搬入或搬出数据变为算子整个运行过程的性能瓶颈。切分策略建议:当输入和输出数据的数据量超过L2 Cache大小时,Tiling中开启L2 Cache切分策略。 |
| 6 | 6 | ||
| 7 | -【反例】 | 7 | +优化的核心思路是:**通过开启L2 Cache切分策略,将单轮处理的数据规模控制在L2 Cache范围内,提升数据在L2 Cache中的复用率,从而减少重复的数据搬入或搬出**。本文及配套样例将L2 Cache可容纳的有效数据量阈值设为100MB,该取值仅用于样例展示。 |
| 8 | 8 | ||
| 9 | -假设输入数据大小为InputTotalSize,L2 Cache大小为L2CacheSize,InputTotalSize = L2CacheSize \* 2,总核数为20个核,数据未切分,整体一次完成计算。假设20个核一次可以处理共L2CacheSize的数据,则每个核至少两次读取输入数据。 | 9 | +## 场景设定 |
| 10 | + | ||
| 11 | +- 使用20个Vector Core并行计算,每个元素执行两轮“加1”运算,最终结果为`data + 2`。 | ||
| 12 | +- 反例不做L2 Cache切分,每轮把384MB数据作为一个整体进行搬入、计算、搬出。 | ||
| 13 | +- 正例将384MB数据切分成B0至B3四个L2 Batch,每批包含96MB的数据量,每一批进行两轮加1计算。 | ||
| 14 | +- 完整实现方法请参考[add_l2_cache_split样例](../../../../../../examples/01_simd_cpp_api/03_basic_api/10_add_l2_cache_split)。 | ||
| 15 | + | ||
| 16 | +两个场景的数据处理方式如下图所示。 | ||
| 17 | + | ||
| 18 | +**图 1** 未开启L2 Cache切分<a name="fig_l2_cache_no_split"></a> | ||
| 10 | 19 | ||
| 11 | -**图1** 未开启L2 Cache切分<a name="fig126831114552"></a> | ||
| 12 |  | 20 |  |
| 13 | 21 | ||
| 14 | -``` | 22 | +**图 2** 开启L2 Cache切分<a name="fig_l2_cache_split"></a> |
| 15 | -constexpr int32_t TOTAL_LENGTH = InputTotalSize / sizeof(half); | ||
| 16 | -constexpr int32_t USE_CORE_NUM = 20; | ||
| 17 | -constexpr int32_t TILE_NUM = 2; | ||
| 18 | -constexpr int32_t BLOCK_LENGTH = TOTAL_LENGTH / USE_CORE_NUM; | ||
| 19 | -constexpr int32_t TILE_LENGTH = BLOCK_LENGTH / TILE_NUM; | ||
| 20 | 23 | ||
| 21 | -class KernelSample { | ||
| 22 | -public: | ||
| 23 | - __aicore__ inline KernelSample() {} | ||
| 24 | - __aicore__ inline void Init(__gm__ uint8_t* x) | ||
| 25 | - { | ||
| 26 | - xGm.SetGlobalBuffer((__gm__ half*)x + BLOCK_LENGTH * GetBlockIdx(), BLOCK_LENGTH); | ||
| 27 | - yGm.SetGlobalBuffer((__gm__ half*)y + BLOCK_LENGTH * GetBlockIdx(), BLOCK_LENGTH); | ||
| 28 | - pipe.InitBuffer(inQueueX, 1, BLOCK_LENGTH * sizeof(half)); | ||
| 29 | - pipe.InitBuffer(inQueueY, 1, BLOCK_LENGTH * sizeof(half)); | ||
| 30 | - } | ||
| 31 | - __aicore__ inline void Process() | ||
| 32 | - { | ||
| 33 | - // 示例演示对输入数据加2的运算 | ||
| 34 | - constexpr int32_t loopCount = 2; | ||
| 35 | - for (int32_t i = 0; i < loopCount; i++) { | ||
| 36 | - // 外层的每次循环对输入数据进行加1的运算 | ||
| 37 | - for (int32_t j = 0; j < TILE_NUM; j++) { | ||
| 38 | - // 内层循环分别处理每个核第0块和第1块数据 | ||
| 39 | - CopyIn(j); | ||
| 40 | - Compute(); | ||
| 41 | - CopyOut(j); | ||
| 42 | - } | ||
| 43 | - } | ||
| 44 | - } | ||
| 45 | -private: | ||
| 46 | - __aicore__ inline void CopyIn(int32_t process) | ||
| 47 | - { | ||
| 48 | - LocalTensor<half> xLocal = inQueueX.AllocTensor<half>(); | ||
| 49 | - // 对于每个核,除了首次读取外,读取第0块数据时,L2 Cache内缓存的是第1块数据; | ||
| 50 | - // 对于每个核,读取第1块数据时,L2 Cache内缓存的是第0块数据; | ||
| 51 | - // 每个核需要4次读取GM上的数据 | ||
| 52 | - DataCopy(xLocal, xGm[process * TILE_LENGTH], TILE_LENGTH ); | ||
| 53 | - inQueueX.EnQue(xLocal); | ||
| 54 | - } | ||
| 55 | - __aicore__ inline void Compute() | ||
| 56 | - { | ||
| 57 | - LocalTensor<half> yLocal = inQueueY.AllocTensor<half>(); | ||
| 58 | - LocalTensor<half> xLocal = inQueueX.DeQue<half>(); | ||
| 59 | - Adds(yLocal, xLocal, 1, TILE_LENGTH); | ||
| 60 | - inQueueY.EnQue<half>(yLocal); | ||
| 61 | - inQueueX.FreeTensor(xLocal); | ||
| 62 | - } | ||
| 63 | - __aicore__ inline void CopyOut(int32_t process) | ||
| 64 | - { | ||
| 65 | - LocalTensor<half> yLocal = inQueueY.DeQue<half>(); | ||
| 66 | - DataCopy(yGm[process * TILE_LENGTH], yLocal, TILE_LENGTH); | ||
| 67 | - inQueueY.FreeTensor(yLocal); | ||
| 68 | - } | ||
| 69 | -} | ||
| 70 | -... | ||
| 71 | -``` | ||
| 72 | - | ||
| 73 | -【正例】 | ||
| 74 | - | ||
| 75 | -假设输入数据大小为InputTotalSize,L2 Cache大小为L2CacheSize,InputTotalSize = L2CacheSize \* 2,能使用的总核数为20个核,输入数据均等切分成2份数据,则整体分两次进行计算,每次的计算量为L2CacheSize,第一次20个核先计算前L2CacheSize个数据,第二次20个核计算后L2CacheSize个数据。每次计算前读取的数据能够命中L2 Cache,提升算子性能。 | ||
| 76 | - | ||
| 77 | -**图2** 开启L2 Cache切分<a name="fig1623673819553"></a> | ||
| 78 |  | 24 |  |
| 79 | 25 | ||
| 80 | -``` | 26 | +## 反例:不做L2 Cache切分 |
| 81 | -constexpr int32_t TOTAL_LENGTH = InputTotalSize / sizeof(half); | ||
| 82 | -constexpr int32_t TILE_NUM = 2; | ||
| 83 | -constexpr int32_t USE_CORE_NUM = 20; | ||
| 84 | -constexpr int32_t TILE_LENGTH = TOTAL_LENGTH / TILE_NUM; | ||
| 85 | -constexpr int32_t BLOCK_LENGTH = TILE_LENGTH / USE_CORE_NUM; | ||
| 86 | 27 | ||
| 87 | -class KernelSample { | 28 | +反例中不做数据切分,直接处理384MB数据整体。L2 Cache对用户不可见,用户可感知数据从GM搬运到UB的过程为:384MB总数据由20个核均分,平均每个核搬运约19.2MB。 |
| 88 | -public: | 29 | + |
| 89 | - __aicore__ inline KernelSample() {} | 30 | +**【用户视角】** |
| 90 | - __aicore__ inline void Init(__gm__ uint8_t* x, __gm__ uint8_t* y, int32_t index) | 31 | + |
| 91 | - { | 32 | +只感知GM到UB搬运过程,384MB总数据由20个核均分搬运,每个核搬运19.2MB。 |
| 92 | - xGm.SetGlobalBuffer((__gm__ half*)x + BLOCK_LENGTH * GetBlockIdx() + index * TILE_LENGTH, BLOCK_LENGTH); | 33 | + |
| 93 | - yGm.SetGlobalBuffer((__gm__ half*)y + BLOCK_LENGTH * GetBlockIdx() + index * TILE_LENGTH, BLOCK_LENGTH); | 34 | +**【实际数据路径】** |
| 94 | - pipe.InitBuffer(inQueueX, 1, BLOCK_LENGTH * sizeof(half)); | 35 | + |
| 95 | - pipe.InitBuffer(inQueueY, 1, BLOCK_LENGTH * sizeof(half)); | 36 | +输入数据会先从GM填充到L2 Cache,再到UB。 |
| 96 | - } | 37 | + |
| 97 | - __aicore__ inline void Process() | 38 | +**图 3** GM搬运到UB路径<a name="fig_l2_cache_gm_to_ub"></a> |
| 98 | - { | 39 | + |
| 99 | - // 示例演示对输入数据加2的运算 | 40 | + |
| 100 | - constexpr int32_t loopCount = 2; | 41 | + |
| 101 | - for (int32_t i = 0; i < loopCount; i++) { | 42 | +**【搬运填充过程】** |
| 102 | - // 每次循环对输入数据进行加1的运算 | 43 | + |
| 103 | - CopyIn(); | 44 | +假设20个核处理的数据按核序逐段搬入L2 Cache,L2 Cache有效数据阈值为100MB,则L2 Cache内约可容纳5个核的数据量。 |
| 104 | - Compute(); | 45 | + |
| 105 | - CopyOut(); | 46 | +**图 4** 数据搬运填充L2 Cache过程<a name="fig_l2_cache_fill_process"></a> |
| 106 | - } | 47 | + |
| 107 | - } | 48 | + |
| 108 | -private: | 49 | + |
| 109 | - __aicore__ inline void CopyIn() | 50 | +后续新数据填充L2 Cache时,可能替换核0~核4早期Cache Line。 |
| 110 | - { | 51 | + |
| 111 | - LocalTensor<half> xLocal = inQueueX.AllocTensor<half>(); | 52 | +**【不切分反例的执行时序】** |
| 112 | - // 对于每个核,除了首次读取外,第二次读取可以命中L2 Cache; | 53 | + |
| 113 | - // 每个核2次读取GM上的数据,2次访问L2 Cache读数据 | 54 | +**图 5** 未开启L2 Cache切分反例<a name="fig_l2_cache_no_split_example"></a> |
| 114 | - DataCopy(xLocal, xGm, BLOCK_LENGTH ); | 55 | + |
| 115 | - inQueueX.EnQue(xLocal); | 56 | + |
| 116 | - } | 57 | + |
| 117 | - __aicore__ inline void Compute() | 58 | +在第1轮(R0)处理384MB后半段数据时,后续搬入的新数据可能会替换先前搬入的数据。由于R0是首轮访问,仅比较一轮搬运计算不能稳定体现L2 Cache命中收益;第2轮(R1)再次访问384MB数据时,先前的数据可能已经不在L2 Cache中,因此更可能从GM重新搬运。 |
| 118 | - { | 59 | + |
| 119 | - LocalTensor<half> yLocal = inQueueY.AllocTensor<half>(); | 60 | +## 正例:按L2 Cache切分 |
| 120 | - LocalTensor<half> xLocal = inQueueX.DeQue<half>(); | 61 | + |
| 121 | - Adds(yLocal, xLocal, 1, BLOCK_LENGTH); | 62 | +在正例中,根据阈值100MB, 对384MB数据进行切分,分成4个Batch,每份96MB。每轮20核共处理96MB数据,每轮数据复用,这样每次计算前读取的数据能够命中L2 Cache,提升算子性能。 |
| 122 | - inQueueY.EnQue<half>(yLocal); | 63 | +正例的循环层级为`L2 Batch -> Round`。同一批连续完成全部轮次后,再切换到下一批: |
| 123 | - inQueueX.FreeTensor(xLocal); | 64 | + |
| 124 | - } | 65 | +```text |
| 125 | - __aicore__ inline void CopyOut() | 66 | +L2 Batch数 = ceil(总数据量 / L2 Cache有效数据阈值) |
| 126 | - { | 67 | + = ceil(384MB / 100MB) |
| 127 | - LocalTensor<half> yLocal = inQueueY.DeQue<half>(); | 68 | + = 4 |
| 128 | - DataCopy(yGm, yLocal, BLOCK_LENGTH); | 69 | +单个L2 Batch大小 = 384MB / 4 = 96MB |
| 129 | - inQueueY.FreeTensor(yLocal); | 70 | +``` |
| 71 | + | ||
| 72 | +```cpp | ||
| 73 | +for (uint32_t l2BatchIdx = 0; l2BatchIdx < L2_BATCH_NUM; ++l2BatchIdx) { | ||
| 74 | + for (uint32_t roundIdx = 0; roundIdx < COMPUTE_ROUND_NUM; ++roundIdx) { | ||
| 75 | + ProcessL2Batch(l2BatchIdx); | ||
| 76 | + AscendC::SyncAll(); | ||
| 130 | } | 77 | } |
| 131 | } | 78 | } |
| 132 | -... | 79 | +``` |
| 133 | 80 | ||
| 134 | -extern "C" __global__ __aicore__ void simple_kernel(__gm__ uint8_t* srcGm, __gm__ uint8_t* dstGm) | 81 | +**【L2 Cache切分正例的执行时序】** |
| 82 | + | ||
| 83 | +**图 6** 开启切分正例<a name="fig_l2_cache_split_example"></a> | ||
| 84 | + | ||
| 85 | + | ||
| 86 | + | ||
| 87 | +同一Batch的两轮访问之间,没有插入其他超过100MB有效阈值的大数据,因此第2轮更有机会命中第1轮留在L2 Cache中的数据。<br> | ||
| 88 | +B0的数据量为96MB,不超过100MB阈值;B0在两次访问之间也没有其他大数据插入更新L2 Cache,因此R1更有机会从L2 Cache读取R0的结果。B0处理完毕后再依次处理B1至B3,原理相同。 | ||
| 89 | + | ||
| 90 | +**【性能观察重点】** | ||
| 91 | + | ||
| 92 | +只执行一轮计算:R0是首轮访问,反例和正例都需要从GM首次搬入数据,Cache Miss差异通常不明显。<br> | ||
| 93 | +正反例通过对L2 Cache中数据复用程度体现性能优化:R1再次访问同一批地址时,目标数据是否仍在L2 Cache中,才是减少Cache Miss的关键。<br> | ||
| 94 | + | ||
| 95 | +反例的循环层级为`Round -> Whole Data`。外层每轮都处理完整384MB范围: | ||
| 96 | + | ||
| 97 | +```cpp | ||
| 98 | +for (uint32_t roundIdx = 0; roundIdx < COMPUTE_ROUND_NUM; ++roundIdx) { | ||
| 99 | + ProcessWholeData(); | ||
| 100 | + AscendC::SyncAll(); | ||
| 101 | +} | ||
| 102 | +``` | ||
| 103 | + | ||
| 104 | +**表 1** 样例数据量 | ||
| 105 | + | ||
| 106 | +| 数据量 | 计算方法 | 结果 | | ||
| 107 | +| ------ | ------ | -----: | | ||
| 108 | +| 总数据量 | 样例固定值 | 384MB | | ||
| 109 | +| 总元素数 | `384MB / sizeof(half)` | 201326592 | | ||
| 110 | +| L2 Cache有效数据阈值 | 样例固定值 | 100MB | | ||
| 111 | +| 反例单阶段全核数据 | 不做L2 Cache切分 | 384MB | | ||
| 112 | +| 正例L2 Batch数 | `ceil(384MB / 100MB)` | 4 | | ||
| 113 | +| 正例单个L2 Batch数据量 | `384MB / 4` | 96MB | | ||
| 114 | +| 正例单个L2 Batch元素数 | `96MB / sizeof(half)` | 50331648 | | ||
| 115 | + | ||
| 116 | +## 为什么不切分会降低复用概率 | ||
| 117 | + | ||
| 118 | +以本文100MB阈值为例,核0至核4合计处理约96MB,已经接近L2 Cache有效容量;当核5及后续核继续搬入新数据时,总数据量超过100MB阈值,核0等较早进入L2 Cache的数据就可能被替换。也就是说,替换风险在第1轮处理过程中已经产生,不是等到第2轮才产生。如果算子在同一轮后续步骤就复用早期地址,这种替换会在单轮内直接表现为Cache Miss。<br> | ||
| 119 | +文档中设计两轮计算,是为了显式体现数据复用:第2轮再次访问第1轮刚处理过的同一批地址。不切分时,第2轮重新访问`data[0]`所在地址范围,先前数据可能已经在第1轮后续扫描中被替换,因此更可能发生Cache Miss并从GM重新取数。<br> | ||
| 120 | +L2 Cache切分正例将单个循环需要处理的数据量限制在96MB。单个Batch内,20个核合计覆盖的数据量不超过100MB阈值,每个核只处理约4.8MB。先在`data[B0]`上完成第1轮和第2轮计算,再依次处理B1至B3。同一批两轮访问之间没有插入其他大数据更新L2 Cache,因此第2轮更有机会直接命中第1轮刚写回的L2 Cache数据。<br> | ||
| 121 | + | ||
| 122 | +## 公共处理逻辑 | ||
| 123 | + | ||
| 124 | +两种实现都使用同一份`data` Buffer,并将结果写回搬入时的同一GM地址。差异在于传给公共处理函数的连续数据范围不同:反例传入完整384MB范围,正例传入单个96MB L2 Batch范围。以下代码仅展示实际样例采用的32字节DataBlock分核公式和正反例传入范围差异,不展开单核内部搬运和计算细节。 | ||
| 125 | + | ||
| 126 | +```cpp | ||
| 127 | +__aicore__ inline void ProcessWholeData() | ||
| 135 | { | 128 | { |
| 136 | - AscendC::KernelSample op; | 129 | + ProcessDataRange(0, TOTAL_DATA_ELEMENTS); |
| 137 | - // 输入数据均等切分成2份数据进行计算 | ||
| 138 | - for (int32_t i = 0; i < TILE_NUM; i++) { | ||
| 139 | - op.Init(srcGm, dstGm, i); | ||
| 140 | - op.Process(); | ||
| 141 | - } | ||
| 142 | } | 130 | } |
| 143 | -... | 131 | + |
| 132 | +__aicore__ inline void ProcessL2Batch(uint32_t l2BatchIdx) | ||
| 133 | +{ | ||
| 134 | + ProcessDataRange(l2BatchIdx * L2_BATCH_ELEMENTS, L2_BATCH_ELEMENTS); | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +__aicore__ inline void ProcessDataRange(int64_t rangeOffsetInData, uint32_t rangeElementNum) | ||
| 138 | +{ | ||
| 139 | + const uint32_t coreIdx = AscendC::GetBlockIdx(); | ||
| 140 | + const uint32_t rangeDataBlockNum = rangeElementNum / ELEMENTS_PER_DATA_BLOCK; | ||
| 141 | + const uint32_t baseDataBlocksPerCore = rangeDataBlockNum / VECTOR_CORE_NUM; | ||
| 142 | + const uint32_t coresWithExtraDataBlock = rangeDataBlockNum % VECTOR_CORE_NUM; | ||
| 143 | + const uint32_t extraDataBlockNumBeforeCore = | ||
| 144 | + coreIdx < coresWithExtraDataBlock ? coreIdx : coresWithExtraDataBlock; | ||
| 145 | + const uint32_t coreDataBlockNum = | ||
| 146 | + baseDataBlocksPerCore + (coreIdx < coresWithExtraDataBlock ? 1U : 0U); | ||
| 147 | + const uint32_t coreDataBlockOffset = | ||
| 148 | + coreIdx * baseDataBlocksPerCore + extraDataBlockNumBeforeCore; | ||
| 149 | + const uint32_t coreElementNum = coreDataBlockNum * ELEMENTS_PER_DATA_BLOCK; | ||
| 150 | + const int64_t coreOffsetInData = | ||
| 151 | + rangeOffsetInData + static_cast<int64_t>(coreDataBlockOffset) * ELEMENTS_PER_DATA_BLOCK; | ||
| 152 | + ProcessCoreRange(coreOffsetInData, coreElementNum); | ||
| 153 | +} | ||
| 154 | + | ||
| 155 | +// 单核内部搬运和计算流程以配套样例完整实现为准。 | ||
| 144 | ``` | 156 | ``` |
| 145 | 157 | ||
| 146 | -更多完整样例请参考[L2 Cache切分的算子样例](../../../../../../examples/01_simd_cpp_api/04_advanced_api/00_matmul/matmul_l2cache)。 | 158 | +对于不切分反例的384MB整体范围,前12个核各处理629146个DataBlock,其余8个核各处理629145个DataBlock,单核数据量约19.2MB,20个核合计覆盖完整`data[0, 384MB)`范围且互不重叠。对于正例的单个96MB L2 Batch,前8个核各处理157287个DataBlock,其余12个核各处理157286个DataBlock,单核数据量约4.8MB,20个核合计覆盖完整L2 Batch且互不重叠。每个DataBlock包含16个`half`元素,因此所有`DataCopy`搬运的数据长度均满足32字节对齐要求。完整核内流水同步实现以配套样例为准;阶段之间的核间同步由配套样例的`KernelAdd::SyncAllCores`函数直接调用API`AscendC::SyncAll()`接口完成,不是额外封装的自定义同步函数。 |
| 159 | + | ||
| 160 | +## 正反例对比总结 | ||
| 161 | + | ||
| 162 | +**表 2** 正反例对比 | ||
| 163 | + | ||
| 164 | +| 维度 | 反例 | 正例 | | ||
| 165 | +| ------ | ------ | ------ | | ||
| 166 | +| L2 Cache切分 | 不切分 | 切分为4个96MB L2 Batch | | ||
| 167 | +| 循环层级 | `Round -> Whole Data` | `L2 Batch -> Round` | | ||
| 168 | +| 单阶段全核数据量 | 384MB | 96MB | | ||
| 169 | +| 单核平均处理量 | 约19.2MB | 约4.8MB | | ||
| 170 | +| 执行时间线 | `R0/data[0,384MB) -> R1/data[0,384MB)` | `B0/R0 -> B0/R1 -> ... -> B3/R0 -> B3/R1` | | ||
| 171 | +| 同一批两次访问之间 | 一轮内20核已合计扫描完整384MB范围 | 不插入其他超过阈值的大数据范围 | | ||
| 172 | +| L2 Cache数据替换风险 | 较高 | 较低 | | ||
| 173 | +| 第2轮L2 Cache命中率 | 预期较低,以实测为准 | 预期较高,以实测为准 | | ||
| 174 | + | ||
| 175 | +## 适用场景 | ||
| 176 | + | ||
| 177 | +- 算子总数据量超过可用的L2 Cache有效阈值,且同一批数据需要被多次读取。 | ||
| 178 | +- 只读取一次的数据不存在跨Round复用,调整L2 Cache切分顺序通常收益有限。 | ||
不存在跨Round复用, 调整L2 Cache切分顺序通常收益有限。 为什么还适用L2 Cache切分呢 ![]() ![]() | |||
| 179 | + | ||
| 180 | +## 测试用例设计 | ||
| 181 | + | ||
| 182 | +测试正反例使用相同的384MB的GM数据Buffer、核数、Round数和计算逻辑。唯一核心差异是反例不做L2 Cache切分,正例中输入数据按100MB有效数据阈值切分为4个96MB L2 Batch。 | ||
| 183 | + | ||
| 184 | +### 正反例用例 | ||
| 185 | + | ||
| 186 | +**表 3** 正反例用例 | ||
执行时间线 、数据量、L2 Cache切分 列项 建议删除,重复出现多次 ![]() ![]() | |||
| 187 | + | ||
| 188 | +| 用例 | 循环层级 | 数据元素数 | 核数 | Round数 | 验证目的 | | ||
| 189 | +| ------ | ------ | ------ | -------: | ------ | -----: | | ||
| 190 | +| 反例no-split | `Round -> Whole Data` | 201326592 | 20 | 2 | 验证20核合计384MB数据量超过L2 Cache有效阈值时的替换风险 | | ||
| 191 | +| 正例L2-split | `L2 Batch -> Round` | 201326592 | 20 | 2 | 验证单个96MB Batch连续复用带来的L2 Cache局部性改善 | | ||
| 192 | + | ||
| 193 | +正例每个L2 Batch包含50331648个`half`元素,占96MB。以32字节DataBlock为最小单位分配给20个Vector Core,前8个核各处理2516592个元素,其余12个核各处理2516576个元素。反例每轮直接处理完整384MB范围,20个核共同覆盖`data[0,384MB)`。所有`DataCopy`长度均保持32字节对齐。 | ||
| 194 | + | ||
| 195 | +### 验证检查点 | ||
| 196 | + | ||
| 197 | +**表 4** 验证检查点 | ||
| 198 | + | ||
| 199 | +| 检查项 | 验证方法 | 预期结果 | | ||
| 200 | +| ------ | ------ | ------ | | ||
AB公平性是什么意思 ![]() ![]() | |||
| 201 | +| L2 Cache命中率 | 独立进程采集L2 Cache读命中指标 | 正例中位数通常高于反例,具体字段按架构和工具版本解释 | | ||
| 202 | +| 搬运效率 | 对比MTE2耗时和有效带宽 | 正例MTE2耗时中位数通常降低,有效带宽通常提升 | | ||
| 203 | +| 端到端耗时 | 正反例各采集多组独立Profile并比较`Task Duration(us)`中位数 | 搬运受限场景下,正例耗时通常低于反例 | | ||
| 204 | + | ||
| 205 | +> **说明**:`aiv_gm_to_ub_bw(GB/s)`表示有效带宽,不表示GM读取量。优化后有效带宽可能升高,不能以“带宽更低”作为预期。性能采集应交替安排正反例的先后顺序,并使用多组结果的中位数降低系统波动影响。 | ||
| @@ -0,0 +1,53 @@ | |||
| 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 | +cmake_minimum_required(VERSION 3.16) | ||
| 13 | + | ||
| 14 | +set(CMAKE_ASC_RUN_MODE "npu" CACHE STRING "Run mode: npu, cpu, sim") | ||
| 15 | +set(CMAKE_ASC_ARCHITECTURES "dav-2201" CACHE STRING "NPU architecture: dav-2201, dav-3510") | ||
| 16 | +set(SCENARIO_NUM "1" CACHE STRING "Scenario number: 1=no split, 2=L2 Cache split") | ||
| 17 | + | ||
| 18 | +find_package(ASC REQUIRED) | ||
| 19 | + | ||
| 20 | +project(kernel_samples LANGUAGES ASC CXX) | ||
| 21 | + | ||
| 22 | +if(NOT CMAKE_ASC_ARCHITECTURES STREQUAL "dav-2201" AND | ||
| 23 | + NOT CMAKE_ASC_ARCHITECTURES STREQUAL "dav-3510") | ||
| 24 | + message(FATAL_ERROR "Unsupported CMAKE_ASC_ARCHITECTURES=${CMAKE_ASC_ARCHITECTURES}") | ||
| 25 | +endif() | ||
| 26 | + | ||
| 27 | +if(SCENARIO_NUM STREQUAL "1") | ||
| 28 | + set(SAMPLE_SOURCE add_l2cache_nosplit.asc) | ||
| 29 | +elseif(SCENARIO_NUM STREQUAL "2") | ||
| 30 | + set(SAMPLE_SOURCE add_l2cache_split.asc) | ||
| 31 | +else() | ||
| 32 | + message(FATAL_ERROR "Unsupported SCENARIO_NUM=${SCENARIO_NUM}. Use 1 for no split or 2 for L2 Cache split.") | ||
| 33 | +endif() | ||
| 34 | + | ||
| 35 | +add_executable(demo | ||
| 36 | + ${SAMPLE_SOURCE} | ||
| 37 | +) | ||
| 38 | + | ||
| 39 | +target_compile_options(demo PRIVATE | ||
| 40 | + $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${CMAKE_ASC_ARCHITECTURES}> | ||
| 41 | +) | ||
| 42 | + | ||
| 43 | +target_compile_definitions(demo PRIVATE | ||
| 44 | + SCENARIO_NUM=${SCENARIO_NUM} | ||
| 45 | +) | ||
| 46 | + | ||
| 47 | +target_link_libraries(demo PRIVATE | ||
| 48 | + tiling_api | ||
| 49 | + register | ||
| 50 | + platform | ||
| 51 | + m | ||
| 52 | + dl | ||
| 53 | +) | ||
| @@ -0,0 +1,186 @@ | |||
| 1 | +# L2 Cache切分样例 | ||
| 2 | + | ||
| 3 | +## 概述 | ||
整体模板风格应该参考其他样例文档 ![]() ![]() | |||
| 4 | + | ||
| 5 | +本样例通过一个原地加法固定负载,展示L2 Cache切分对跨轮数据复用的影响。 | ||
| 6 | + | ||
| 7 | +样例使用一份384MB的GM数据,连续执行两轮`data = data + 1`计算。两种实现的逻辑GM->UB搬运量、UB->GM搬运量和Adds计算量相同,区别在于数据访问顺序: | ||
| 8 | + | ||
| 9 | +- 反例`no-split`:每轮直接处理完整384MB数据。 | ||
| 10 | +- 正例`l2-split`:将384MB数据切成4个96MB的L2 Batch,同一Batch连续完成两轮计算后再处理下一Batch。 | ||
| 11 | + | ||
| 12 | +## 本样例支持的产品及CANN软件版本 | ||
| 13 | + | ||
| 14 | +| 产品 | CANN软件版本 | | ||
| 15 | +|------|-------------| | ||
| 16 | +| Ascend 950PR/Ascend 950DT | >= CANN 9.1.0 | | ||
| 17 | +| Atlas A3 训练系列产品/Atlas A3 推理系列产品 | >= CANN 9.0.0 | | ||
| 18 | +| Atlas A2 训练系列产品/Atlas A2 推理系列产品 | >= CANN 9.0.0 | | ||
| 19 | + | ||
| 20 | +## 目录结构介绍 | ||
| 21 | + | ||
| 22 | +```text | ||
| 23 | +├── 10_add_l2_cache_split | ||
| 24 | +│ ├── scripts | ||
| 25 | +│ │ ├── gen_data.py // 输入数据和真值数据生成脚本 | ||
| 26 | +│ │ └── verify_result.py // 验证输出数据和真值数据是否一致的验证脚本 | ||
| 27 | +│ ├── add_l2cache_nosplit.asc // 反例Kernel入口和Host main | ||
| 28 | +│ ├── add_l2cache_split.asc // 正例Kernel入口和Host main | ||
| 29 | +│ ├── CMakeLists.txt // 编译工程文件 | ||
| 30 | +│ ├── data_utils.h // 数据读入写出函数 | ||
| 31 | +│ ├── l2_cache_kernel.h // 固定负载参数和公共Device处理逻辑 | ||
| 32 | +│ ├── l2_cache_runner.h // 公共Host运行逻辑 | ||
| 33 | +│ ├── README.md // 中文样例说明文档 | ||
| 34 | +│ └── README_en.md // 英文样例说明文档 | ||
| 35 | +``` | ||
| 36 | + | ||
| 37 | +## 样例描述 | ||
| 38 | + | ||
| 39 | +- 样例功能: | ||
| 40 | + | ||
| 41 | + 本样例对输入`data`执行两轮原地加法计算,每轮对每个`half`元素加1,最终结果为`data + 2`。样例通过`SCENARIO_NUM`区分不切分和L2 Cache切分两个编译场景,用于对比相同计算量下不同访问顺序的性能差异。 | ||
| 42 | + | ||
| 43 | +- 样例规格: | ||
| 44 | + | ||
| 45 | + <table> | ||
| 46 | + <tr><th align="center">样例类型(OpType)</th><th colspan="4" align="center">AddL2CacheSplit</th></tr> | ||
| 47 | + <tr><td rowspan="2" 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> | ||
| 48 | + <tr><td align="center">data</td><td align="center">[201326592]</td><td align="center">half</td><td align="center">ND</td></tr> | ||
| 49 | + <tr><td rowspan="1" align="center">样例输出</td><td align="center">data</td><td align="center">[201326592]</td><td align="center">half</td><td align="center">ND</td></tr> | ||
| 50 | + <tr><td rowspan="2" align="center">核函数名</td><td colspan="4" align="center">l2_cache_nosplit</td></tr> | ||
| 51 | + <tr><td colspan="4" align="center">l2_cache_split</td></tr> | ||
| 52 | + </table> | ||
| 53 | + | ||
| 54 | +- 样例参数: | ||
| 55 | + | ||
| 56 | + | 参数 | 取值 | 说明 | | ||
| 57 | + |------|-----:|------| | ||
| 58 | + | `totalByteSize` | 384MB | 输入数据总大小 | | ||
| 59 | + | `L2_TILE_THRESHOLD` | 100MB | 单批数据的L2 Cache有效容量阈值 | | ||
| 60 | + | `l2BatchCount` | 4 | 正例L2 Batch数量 | | ||
| 61 | + | `l2BatchSizeBytes` | 96MB | 正例单个L2 Batch大小 | | ||
| 62 | + | `vectorCoreCount` | 20 | Vector Core数量 | | ||
| 63 | + | `computeRoundCount` | 2 | 计算轮数 | | ||
| 64 | + | ||
| 65 | +- 样例场景: | ||
| 66 | + | ||
| 67 | + | `SCENARIO_NUM` | 场景 | 源文件 | Kernel入口 | 输出文件 | | ||
| 68 | + |------|------|------|------|------| | ||
| 69 | + | `1` | 不做L2 Cache切分 | `add_l2cache_nosplit.asc` | `l2_cache_nosplit` | `output/output.bin` | | ||
| 70 | + | `2` | 开启L2 Cache切分 | `add_l2cache_split.asc` | `l2_cache_split` | `output/output.bin` | | ||
| 71 | + | ||
| 72 | +- 样例实现: | ||
| 73 | + | ||
| 74 | + - Kernel实现 | ||
| 75 | + | ||
| 76 | + 公共Device逻辑按32字节数据块切分数据范围,并分配给20个Vector Core。每个核内部按UB Tile循环执行`DataCopy`、`Adds`和写回。 | ||
换行未生效 ![]() ![]() | |||
| 77 | + | ||
| 78 | + 反例每轮处理完整`data[0, 384MB)`范围: | ||
| 79 | + | ||
| 80 | + ```text | ||
| 81 | + Round 0: data[0, 384MB) | ||
| 82 | + Round 1: data[0, 384MB) | ||
| 83 | + ``` | ||
| 84 | + | ||
| 85 | + 正例按L2 Batch处理,每个Batch连续完成两轮计算: | ||
| 86 | + | ||
| 87 | + ```text | ||
| 88 | + B0: Round 0 -> Round 1 | ||
| 89 | + B1: Round 0 -> Round 1 | ||
| 90 | + B2: Round 0 -> Round 1 | ||
| 91 | + B3: Round 0 -> Round 1 | ||
| 92 | + ``` | ||
| 93 | + | ||
| 94 | + 384MB超过样例设置的100MB有效容量阈值,不切分时Round 0早期访问的数据可能在后续扫描中被替换出L2 Cache。正例单个Batch为96MB,同一批数据连续复用时更容易命中L2 Cache。 | ||
| 95 | + | ||
| 96 | + - 同步实现 | ||
| 97 | + | ||
| 98 | + 反例每处理完一轮完整数据后调用`AscendC::SyncAll()`。正例每个L2 Batch与Round组合结束后调用`AscendC::SyncAll()`,确保所有核完成当前阶段的UB->GM搬运后,再进入下一阶段。 | ||
换行未生效 ![]() ![]() | |||
| 99 | + | ||
| 100 | + - 调用实现 | ||
| 101 | + | ||
| 102 | + 使用内核调用符`<<<>>>`调用核函数。编译时通过`SCENARIO_NUM`选择源文件,生成的可执行程序统一为`demo`。 | ||
换行未生效 ![]() ![]() | |||
| 103 | + | ||
| 104 | +## 编译运行 | ||
| 105 | + | ||
| 106 | +在本样例根目录下执行如下步骤,编译并执行样例。 | ||
| 107 | + | ||
| 108 | +- 配置环境变量 | ||
| 109 | + 请根据当前环境上CANN开发套件包的[安装方式](../../../../docs/zh/quick_start.md#prepare&install),配置环境变量。 | ||
| 110 | + | ||
| 111 | + ```bash | ||
| 112 | + source ${install_path}/cann/set_env.sh | ||
| 113 | + ``` | ||
| 114 | + | ||
| 115 | + > **说明:** `${install_path}` 为CANN包安装目录,未指定安装目录时默认安装至`/usr/local/Ascend`下。 | ||
| 116 | + | ||
| 117 | +- 样例执行 | ||
| 118 | + | ||
| 119 | + 在本样例目录下执行如下命令。 | ||
| 120 | + | ||
| 121 | + ```bash | ||
| 122 | + SCENARIO_NUM=1 | ||
| 123 | + mkdir -p build && cd build; # 创建并进入build目录 | ||
| 124 | + cmake -DSCENARIO_NUM=$SCENARIO_NUM -DCMAKE_ASC_ARCHITECTURES=dav-2201 ..;make -j; # 编译工程,默认NPU模式 | ||
| 125 | + python3 ../scripts/gen_data.py -scenarioNum=$SCENARIO_NUM # 生成测试输入数据和真值数据 | ||
| 126 | + ./demo # 执行样例 | ||
| 127 | + python3 ../scripts/verify_result.py output/output.bin ./output/golden.bin -scenarioNum=$SCENARIO_NUM # 验证输出结果 | ||
| 128 | + ``` | ||
| 129 | + | ||
| 130 | + 本样例主要面向NPU模式运行和性能采集。需要排查编译或功能问题时,可添加`-DCMAKE_ASC_RUN_MODE=cpu`或`-DCMAKE_ASC_RUN_MODE=sim`参数进行对应模式的工程配置和运行验证。 | ||
| 131 | + | ||
| 132 | + 示例如下: | ||
| 133 | + | ||
| 134 | + ```bash | ||
| 135 | + cmake -DSCENARIO_NUM=$SCENARIO_NUM -DCMAKE_ASC_RUN_MODE=cpu -DCMAKE_ASC_ARCHITECTURES=dav-2201 ..;make -j; # CPU调试模式配置 | ||
| 136 | + cmake -DSCENARIO_NUM=$SCENARIO_NUM -DCMAKE_ASC_RUN_MODE=sim -DCMAKE_ASC_ARCHITECTURES=dav-2201 ..;make -j; # NPU仿真模式配置 | ||
| 137 | + ``` | ||
| 138 | + | ||
| 139 | + > **注意:** 切换编译模式、架构或场景前需清理CMake缓存,可在`build`目录下执行`rm CMakeCache.txt`后重新执行CMake配置。 | ||
| 140 | + | ||
| 141 | +- 编译选项说明 | ||
| 142 | + | ||
| 143 | + | 选项 | 可选值 | 说明 | | ||
| 144 | + |------|--------|------| | ||
| 145 | + | `CMAKE_ASC_RUN_MODE` | `npu`(默认)、`cpu`、`sim` | 工程配置模式:NPU运行、CPU调试、NPU仿真。其中`sim`模式支持完整执行验证,但384MB负载仿真耗时较长,仿真耗时不作为L2 Cache性能收益评估依据 | | ||
| 146 | + | `CMAKE_ASC_ARCHITECTURES` | `dav-2201`(默认)、`dav-3510` | NPU架构:dav-2201对应Atlas A2 训练系列产品/Atlas A2 推理系列产品和Atlas A3 训练系列产品/Atlas A3 推理系列产品,dav-3510对应Ascend 950PR/Ascend 950DT | | ||
| 147 | + | `SCENARIO_NUM` | `1`、`2` | 场景编号:1=不做L2 Cache切分,2=开启L2 Cache切分 | | ||
| 148 | + | ||
| 149 | +- 执行结果 | ||
| 150 | + | ||
| 151 | + 执行结果如下,说明精度对比成功。 | ||
| 152 | + | ||
| 153 | + ```bash | ||
| 154 | + test pass! | ||
| 155 | + ``` | ||
| 156 | + | ||
| 157 | + 程序运行阶段校验失败时会打印`test failed!`,并输出首个错误元素的索引、输入值、实际输出值和期望输出值。`verify_result.py`验证失败时会打印首个错误元素的索引、实际输出值和期望输出值。 | ||
| 158 | + | ||
| 159 | + 运行后输出文件如下: | ||
| 160 | + | ||
| 161 | + ```text | ||
| 162 | + output/output.bin | ||
| 163 | + output/golden.bin | ||
| 164 | + ``` | ||
| 165 | + | ||
| 166 | +## 性能采集与分析 | ||
| 167 | + | ||
| 168 | +本样例用于观察L2 Cache切分对数据搬入路径的影响。建议分别启动独立进程采集正反例,避免同一进程中前一个Kernel残留的Cache状态影响后一个Kernel。 | ||
| 169 | + | ||
| 170 | +```bash | ||
| 171 | +msopprof ./demo | ||
| 172 | +``` | ||
| 173 | + | ||
| 174 | +分析时,先确认`Memory.csv`中的`GM_to_UB_datas(KB)`总量接近,保证正反例逻辑搬运量公平;再结合`L2Cache.csv`中的L2 Cache读命中率、`PipeUtilization.csv`中的MTE2耗时和`OpBasicInfo.csv`中的`Task Duration(us)`进行判断。 | ||
| 175 | + | ||
| 176 | +常用指标如下: | ||
| 177 | + | ||
| 178 | +| 字段名 | 含义 | 来源文件 | | ||
| 179 | +|------|------|---------| | ||
| 180 | +| `Task Duration(us)` | Kernel任务整体耗时 | `OpBasicInfo.csv` | | ||
| 181 | +| `aiv_mte2_time(us)` | MTE2搬入耗时 | `PipeUtilization.csv` | | ||
| 182 | +| `GM_to_UB_datas(KB)` | 逻辑GM->UB搬运量 | `Memory.csv` | | ||
| 183 | +| `read_main_memory_datas(KB)` | 主存储器读取计数,统计口径与架构和工具版本相关 | `Memory.csv` | | ||
| 184 | +| `aiv_read_hit_rate(%)` | L2 Cache读命中率 | `L2Cache.csv` | | ||
| 185 | + | ||
| 186 | +`aiv_gm_to_ub_bw(GB/s)`是有效带宽,不是GM读取量。优化后带宽可能升高,不能将“带宽降低”作为优化预期。分析性能收益时,应以逻辑搬运量公平性为前提,结合L2 Cache读命中率、MTE2耗时和整体任务耗时综合判断。 | ||
| @@ -0,0 +1,189 @@ | |||
| 1 | +# L2 Cache Splitting Sample | ||
| 2 | + | ||
| 3 | +## Overview | ||
| 4 | + | ||
| 5 | +This sample uses a fixed in-place addition workload to show how L2 Cache splitting affects data reuse across compute rounds. | ||
| 6 | + | ||
| 7 | +The sample uses one 384MB GM data buffer and runs two rounds of `data = data + 1`. The two scenarios issue the same logical GM-to-UB copies, UB-to-GM copies, and Adds operations. The difference is the access order: | ||
| 8 | + | ||
| 9 | +- Scenario 1 `no-split`: each round processes the whole 384MB range. | ||
| 10 | +- Scenario 2 `l2-split`: the 384MB range is split into four 96MB L2 batches, and each batch finishes both rounds before the next batch starts. | ||
| 11 | + | ||
| 12 | +## Supported Products And CANN Versions | ||
| 13 | + | ||
| 14 | +| Product | CANN version | | ||
| 15 | +|------|-------------| | ||
| 16 | +| Ascend 950PR/Ascend 950DT | >= CANN 9.1.0 | | ||
| 17 | +| Atlas A3 training series products/Atlas A3 inference series products | >= CANN 9.0.0 | | ||
| 18 | +| Atlas A2 training series products/Atlas A2 inference series products | >= CANN 9.0.0 | | ||
| 19 | + | ||
| 20 | +## Directory Structure | ||
| 21 | + | ||
| 22 | +```text | ||
| 23 | +├── 10_add_l2_cache_split | ||
| 24 | +│ ├── scripts | ||
| 25 | +│ │ ├── gen_data.py // Input and golden data generation script | ||
| 26 | +│ │ └── verify_result.py // Result verification script | ||
| 27 | +│ ├── add_l2cache_nosplit.asc // Scenario 1 kernel entry and host main | ||
| 28 | +│ ├── add_l2cache_split.asc // Scenario 2 kernel entry and host main | ||
| 29 | +│ ├── CMakeLists.txt // Build project file | ||
| 30 | +│ ├── data_utils.h // Data read/write utilities | ||
| 31 | +│ ├── l2_cache_kernel.h // Fixed workload parameters and shared device logic | ||
| 32 | +│ ├── l2_cache_runner.h // Shared host runtime | ||
| 33 | +│ ├── README.md // Chinese sample documentation | ||
| 34 | +│ └── README_en.md // English sample documentation | ||
| 35 | +``` | ||
| 36 | + | ||
| 37 | +## Sample Description | ||
| 38 | + | ||
| 39 | +- Sample function: | ||
| 40 | + The sample runs two in-place addition rounds on input `data`. Each round adds 1 to every `half` element, so the final result is `input + 2`. `SCENARIO_NUM` selects the no-split or L2 Cache split scenario at build time. | ||
| 41 | + | ||
| 42 | +- Sample specification: | ||
| 43 | + | ||
| 44 | + <table> | ||
| 45 | + <tr><th align="center">OpType</th><th colspan="4" align="center">AddL2CacheSplit</th></tr> | ||
| 46 | + <tr><td rowspan="2" align="center">Input</td><td align="center">name</td><td align="center">shape</td><td align="center">data type</td><td align="center">format</td></tr> | ||
| 47 | + <tr><td align="center">data</td><td align="center">[201326592]</td><td align="center">half</td><td align="center">ND</td></tr> | ||
| 48 | + <tr><td rowspan="1" align="center">Output</td><td align="center">data</td><td align="center">[201326592]</td><td align="center">half</td><td align="center">ND</td></tr> | ||
| 49 | + <tr><td rowspan="2" align="center">Kernel name</td><td colspan="4" align="center">l2_cache_nosplit</td></tr> | ||
| 50 | + <tr><td colspan="4" align="center">l2_cache_split</td></tr> | ||
| 51 | + </table> | ||
| 52 | + | ||
| 53 | +- Sample parameters: | ||
| 54 | + | ||
| 55 | + | Parameter | Value | Description | | ||
| 56 | + |------|-----:|------| | ||
| 57 | + | `totalByteSize` | 384MB | Total input data size | | ||
| 58 | + | `L2_TILE_THRESHOLD` | 100MB | Effective L2 Cache capacity threshold for one batch | | ||
| 59 | + | `l2BatchCount` | 4 | Number of L2 batches in scenario 2 | | ||
| 60 | + | `l2BatchSizeBytes` | 96MB | Size of one L2 batch in scenario 2 | | ||
| 61 | + | `vectorCoreCount` | 20 | Number of Vector Cores | | ||
| 62 | + | `computeRoundCount` | 2 | Number of compute rounds | | ||
| 63 | + | ||
| 64 | +- Sample scenarios: | ||
| 65 | + | ||
| 66 | + | `SCENARIO_NUM` | Scenario | Source file | Kernel entry | Output file | | ||
| 67 | + |------|------|------|------|------| | ||
| 68 | + | `1` | No L2 Cache split | `add_l2cache_nosplit.asc` | `l2_cache_nosplit` | `output/output.bin` | | ||
| 69 | + | `2` | L2 Cache split enabled | `add_l2cache_split.asc` | `l2_cache_split` | `output/output.bin` | | ||
| 70 | + | ||
| 71 | +- Sample implementation: | ||
| 72 | + | ||
| 73 | + - Kernel implementation | ||
| 74 | + The shared device logic splits the data range by 32-byte data blocks and assigns them to 20 Vector Cores. Inside each core, the workload is processed by UB tiles with `DataCopy`, `Adds`, and writes data back to GM. | ||
| 75 | + | ||
| 76 | + Scenario 1 processes the whole `data[0, 384MB)` range in each round: | ||
| 77 | + | ||
| 78 | + ```text | ||
| 79 | + Round 0: data[0, 384MB) | ||
| 80 | + Round 1: data[0, 384MB) | ||
| 81 | + ``` | ||
| 82 | + | ||
| 83 | + Scenario 2 processes one L2 batch at a time and finishes both rounds of the same batch before moving on: | ||
| 84 | + | ||
| 85 | + ```text | ||
| 86 | + B0: Round 0 -> Round 1 | ||
| 87 | + B1: Round 0 -> Round 1 | ||
| 88 | + B2: Round 0 -> Round 1 | ||
| 89 | + B3: Round 0 -> Round 1 | ||
| 90 | + ``` | ||
| 91 | + | ||
| 92 | + The whole 384MB range exceeds the sample's 100MB effective capacity threshold, so early data from Round 0 in scenario 1 can be evicted by later data in the same scan. In scenario 2, each batch is 96MB, so repeated accesses within the same batch are more likely to hit L2 Cache. | ||
| 93 | + | ||
| 94 | + - Synchronization | ||
| 95 | + Scenario 1 calls `AscendC::SyncAll()` after each full-data round. Scenario 2 calls `AscendC::SyncAll()` after each L2-batch/round stage, ensuring all cores finish current UB-to-GM stores before the next stage starts. | ||
| 96 | + | ||
| 97 | + - Invocation | ||
| 98 | + The host code launches kernels with `<<<>>>`. The build selects the source file by `SCENARIO_NUM`, and the generated executable is always `demo`. | ||
| 99 | + | ||
| 100 | +## Build And Run | ||
| 101 | + | ||
| 102 | +Run the following steps from the sample root directory. | ||
| 103 | + | ||
| 104 | +- Configure environment variables | ||
| 105 | + Configure environment variables according to the [CANN installation guide](../../../../docs/zh/quick_start.md#prepare&install). | ||
| 106 | + | ||
| 107 | + ```bash | ||
| 108 | + source ${install_path}/cann/set_env.sh | ||
| 109 | + ``` | ||
| 110 | + | ||
| 111 | + > **Note:** `${install_path}` is the CANN installation directory. If no installation directory is specified, the default path is `/usr/local/Ascend`. | ||
| 112 | + | ||
| 113 | +- Run the sample | ||
| 114 | + | ||
| 115 | + ```bash | ||
| 116 | + SCENARIO_NUM=2 | ||
| 117 | + mkdir -p build && cd build; # Create and enter the build directory | ||
| 118 | + cmake -DSCENARIO_NUM=$SCENARIO_NUM -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # Build the project, NPU mode by default | ||
| 119 | + python3 ../scripts/gen_data.py -scenarioNum=$SCENARIO_NUM # Generate test input and golden data | ||
| 120 | + ./demo # Run the sample | ||
| 121 | + python3 ../scripts/verify_result.py output/output.bin ./output/golden.bin -scenarioNum=$SCENARIO_NUM # Verify the output result | ||
| 122 | + ``` | ||
| 123 | + | ||
| 124 | + To use CPU debug or NPU simulation mode, add `-DCMAKE_ASC_RUN_MODE=cpu` or `-DCMAKE_ASC_RUN_MODE=sim`. | ||
| 125 | + | ||
| 126 | + Examples: | ||
| 127 | + | ||
| 128 | + ```bash | ||
| 129 | + cmake -DSCENARIO_NUM=$SCENARIO_NUM -DCMAKE_ASC_RUN_MODE=cpu -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # CPU debug mode | ||
| 130 | + cmake -DSCENARIO_NUM=$SCENARIO_NUM -DCMAKE_ASC_RUN_MODE=sim -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # NPU simulation mode | ||
| 131 | + ``` | ||
| 132 | + | ||
| 133 | + > **Note:** Clear the CMake cache before switching run mode, architecture, or scenario. For example, run `rm CMakeCache.txt` in the `build` directory and configure again. | ||
| 134 | + | ||
| 135 | +- Build options | ||
| 136 | + | ||
| 137 | + | Option | Value | Description | | ||
| 138 | + |------|--------|------| | ||
| 139 | + | `CMAKE_ASC_RUN_MODE` | `npu` (default), `cpu`, `sim` | Project mode: NPU run, CPU debug, or NPU simulation. The `sim` mode supports full execution verification, but the 384MB workload takes a long time to simulate and simulation time is not used to evaluate L2 Cache performance benefits. | | ||
| 140 | + | `CMAKE_ASC_ARCHITECTURES` | `dav-2201` (default), `dav-3510` | NPU architecture. `dav-2201` maps to Atlas A2 training series products/Atlas A2 inference series products and Atlas A3 training series products/Atlas A3 inference series products, and `dav-3510` maps to Ascend 950PR/Ascend 950DT. | | ||
| 141 | + | `SCENARIO_NUM` | `1`, `2` | Scenario number: 1=no L2 Cache split, 2=L2 Cache split enabled. | | ||
| 142 | + | ||
| 143 | +- Execution result | ||
| 144 | + | ||
| 145 | + Each scenario verifies its output after execution. The following output indicates that the result is correct: | ||
| 146 | + | ||
| 147 | + ```bash | ||
| 148 | + test pass! | ||
| 149 | + ``` | ||
| 150 | + | ||
| 151 | + If runtime verification fails, `test failed!` is printed together with the first mismatched element index, input value, actual output value, and expected output value. If `verify_result.py` fails, it prints the first mismatched element index, actual output value, and expected output value. | ||
| 152 | + | ||
| 153 | + Output files: | ||
| 154 | + | ||
| 155 | + ```text | ||
| 156 | + output/output.bin | ||
| 157 | + output/golden.bin | ||
| 158 | + ``` | ||
| 159 | + | ||
| 160 | +## Profile Collection And Analysis | ||
| 161 | + | ||
| 162 | +This sample is used to observe how L2 Cache splitting affects the data load path. Launch the two scenarios as separate processes so the first kernel's cache state does not affect the second. | ||
| 163 | + | ||
| 164 | +```bash | ||
| 165 | +SCENARIO_NUM=1 | ||
| 166 | +mkdir -p build && cd build | ||
| 167 | +cmake -DSCENARIO_NUM=$SCENARIO_NUM -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j | ||
| 168 | +python3 ../scripts/gen_data.py -scenarioNum=$SCENARIO_NUM | ||
| 169 | +msopprof --output=./prof_384m_inplace_no_split_1 ./demo | ||
| 170 | + | ||
| 171 | +SCENARIO_NUM=2 | ||
| 172 | +cmake -DSCENARIO_NUM=$SCENARIO_NUM -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j | ||
| 173 | +python3 ../scripts/gen_data.py -scenarioNum=$SCENARIO_NUM | ||
| 174 | +msopprof --output=./prof_384m_inplace_l2_split_1 ./demo | ||
| 175 | +``` | ||
| 176 | + | ||
| 177 | +When analyzing results, first confirm that `GM_to_UB_datas(KB)` in `Memory.csv` is close between the two scenarios. Then compare the L2 Cache read hit rate in `L2Cache.csv`, MTE2 time in `PipeUtilization.csv`, and `Task Duration(us)` in `OpBasicInfo.csv`. | ||
| 178 | + | ||
| 179 | +Common metrics: | ||
| 180 | + | ||
| 181 | +| Field | Meaning | Source | | ||
| 182 | +|------|------|---------| | ||
| 183 | +| `Task Duration(us)` | Kernel task duration | `OpBasicInfo.csv` | | ||
| 184 | +| `aiv_mte2_time(us)` | MTE2 load time | `PipeUtilization.csv` | | ||
| 185 | +| `GM_to_UB_datas(KB)` | Logical GM-to-UB traffic | `Memory.csv` | | ||
| 186 | +| `read_main_memory_datas(KB)` | Main-memory read counter. Semantics can vary by architecture and profiler version. | `Memory.csv` | | ||
| 187 | +| `aiv_read_hit_rate(%)` | L2 Cache read hit rate | `L2Cache.csv` | | ||
| 188 | + | ||
| 189 | +`aiv_gm_to_ub_bw(GB/s)` is effective bandwidth, not GM traffic. Performance benefits should be attributed by checking logical traffic fairness, L2 Cache read hit rate, MTE2 time, and total task duration together. | ||
| @@ -0,0 +1,47 @@ | |||
| 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 add_l2cache_nosplit.asc | ||
| 13 | + * \brief Negative example: process the whole 384MB range without L2 Cache splitting. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "l2_cache_kernel.h" | ||
| 17 | +#include "l2_cache_runner.h" | ||
| 18 | + | ||
| 19 | +#ifdef ASCENDC_CPU_DEBUG | ||
| 20 | +#include "cpu_debug_launch.h" | ||
| 21 | +#endif | ||
| 22 | + | ||
| 23 | +extern "C" __global__ __vector__ void l2_cache_nosplit(__gm__ uint8_t* data) | ||
| 24 | +{ | ||
| 25 | + AscendC::InitSocState(); | ||
| 26 | + AddL2Cache::KernelAdd op; | ||
| 27 | + op.Init(data); | ||
| 28 | + for (uint32_t roundIdx = 0; roundIdx < AddL2Cache::computeRoundCount; ++roundIdx) { | ||
| 29 | + op.ProcessWholeData(); | ||
| 30 | + op.SyncAllCores(); | ||
| 31 | + } | ||
| 32 | + AscendC::PipeBarrier<PIPE_ALL>(); | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +namespace { | ||
| 36 | + | ||
| 37 | +void LaunchKernel(aclrtStream stream, uint8_t* data) | ||
| 38 | +{ | ||
| 39 | + l2_cache_nosplit<<<AddL2Cache::vectorCoreCount, 0, stream>>>(data); | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +} // namespace | ||
| 43 | + | ||
| 44 | +int32_t main(int32_t argc, char* argv[]) | ||
| 45 | +{ | ||
| 46 | + return AddL2Cache::RunSample(argc, argv, "no_split", "./output/output.bin", LaunchKernel, false); | ||
| 47 | +} | ||
| @@ -0,0 +1,49 @@ | |||
| 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 add_l2cache_split.asc | ||
| 13 | + * \brief Positive example: finish every round of an L2 batch before moving to the next L2 batch. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "l2_cache_kernel.h" | ||
| 17 | +#include "l2_cache_runner.h" | ||
| 18 | + | ||
| 19 | +#ifdef ASCENDC_CPU_DEBUG | ||
| 20 | +#include "cpu_debug_launch.h" | ||
| 21 | +#endif | ||
| 22 | + | ||
| 23 | +extern "C" __global__ __vector__ void l2_cache_split(__gm__ uint8_t* data) | ||
| 24 | +{ | ||
| 25 | + AscendC::InitSocState(); | ||
| 26 | + AddL2Cache::KernelAdd op; | ||
| 27 | + op.Init(data); | ||
| 28 | + for (uint32_t l2BatchIdx = 0; l2BatchIdx < AddL2Cache::l2BatchCount; ++l2BatchIdx) { | ||
| 29 | + for (uint32_t roundIdx = 0; roundIdx < AddL2Cache::computeRoundCount; ++roundIdx) { | ||
| 30 | + op.ProcessL2Batch(l2BatchIdx); | ||
| 31 | + op.SyncAllCores(); | ||
| 32 | + } | ||
| 33 | + } | ||
| 34 | + AscendC::PipeBarrier<PIPE_ALL>(); | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +namespace { | ||
| 38 | + | ||
| 39 | +void LaunchKernel(aclrtStream stream, uint8_t* data) | ||
| 40 | +{ | ||
| 41 | + l2_cache_split<<<AddL2Cache::vectorCoreCount, 0, stream>>>(data); | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +} // namespace | ||
| 45 | + | ||
| 46 | +int32_t main(int32_t argc, char* argv[]) | ||
| 47 | +{ | ||
| 48 | + return AddL2Cache::RunSample(argc, argv, "l2_split", "./output/output.bin", LaunchKernel, true); | ||
| 49 | +} | ||
| @@ -0,0 +1,86 @@ | |||
| 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_utils.h | ||
| 13 | + * \brief Utility functions for reading and writing binary files | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#ifndef DATA_UTILS_H | ||
| 17 | +#define DATA_UTILS_H | ||
| 18 | +#include <fcntl.h> | ||
| 19 | +#include <sys/stat.h> | ||
| 20 | +#include <unistd.h> | ||
| 21 | +#include <fstream> | ||
| 22 | + | ||
| 23 | +#define ERROR_LOG(fmt, args...) fprintf(stdout, "[ERROR] " fmt "\n", ##args) | ||
| 24 | + | ||
| 25 | +bool ReadFile(const std::string& filePath, size_t& fileSize, void* buffer, size_t bufferSize) | ||
| 26 | +{ | ||
| 27 | + struct stat sBuf; | ||
| 28 | + int fileStatus = stat(filePath.data(), &sBuf); | ||
| 29 | + if (fileStatus == -1) { | ||
| 30 | + ERROR_LOG("failed to get file"); | ||
| 31 | + return false; | ||
| 32 | + } | ||
| 33 | + if (S_ISREG(sBuf.st_mode) == 0) { | ||
| 34 | + ERROR_LOG("%s is not a file, please enter a file", filePath.c_str()); | ||
| 35 | + return false; | ||
| 36 | + } | ||
| 37 | + | ||
| 38 | + std::ifstream file; | ||
| 39 | + file.open(filePath, std::ios::binary); | ||
| 40 | + if (!file.is_open()) { | ||
| 41 | + ERROR_LOG("Open file failed. path = %s", filePath.c_str()); | ||
| 42 | + return false; | ||
| 43 | + } | ||
| 44 | + | ||
| 45 | + std::filebuf* buf = file.rdbuf(); | ||
| 46 | + size_t size = buf->pubseekoff(0, std::ios::end, std::ios::in); | ||
| 47 | + if (size == 0) { | ||
| 48 | + ERROR_LOG("file size is 0"); | ||
| 49 | + file.close(); | ||
| 50 | + return false; | ||
| 51 | + } | ||
| 52 | + if (size > bufferSize) { | ||
| 53 | + ERROR_LOG("file size is larger than buffer size"); | ||
| 54 | + file.close(); | ||
| 55 | + return false; | ||
| 56 | + } | ||
| 57 | + buf->pubseekpos(0, std::ios::in); | ||
| 58 | + buf->sgetn(static_cast<char*>(buffer), size); | ||
| 59 | + fileSize = size; | ||
| 60 | + file.close(); | ||
| 61 | + return true; | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +bool WriteFile(const std::string& filePath, const void* buffer, size_t size) | ||
| 65 | +{ | ||
| 66 | + if (buffer == nullptr) { | ||
| 67 | + ERROR_LOG("Write file failed. buffer is nullptr"); | ||
| 68 | + return false; | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + int fd = open(filePath.c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWRITE); | ||
| 72 | + if (fd < 0) { | ||
| 73 | + ERROR_LOG("Open file failed. path = %s", filePath.c_str()); | ||
| 74 | + return false; | ||
| 75 | + } | ||
| 76 | + | ||
| 77 | + size_t writeSize = write(fd, buffer, size); | ||
| 78 | + (void)close(fd); | ||
| 79 | + if (writeSize != size) { | ||
| 80 | + ERROR_LOG("Write file Failed."); | ||
| 81 | + return false; | ||
| 82 | + } | ||
| 83 | + | ||
| 84 | + return true; | ||
| 85 | +} | ||
| 86 | +#endif // DATA_UTILS_H | ||
| @@ -0,0 +1,136 @@ | |||
| 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 l2_cache_kernel.h | ||
| 13 | + * \brief Workload parameters and device processing shared by both traversal orders. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#ifndef ADD_L2_CACHE_SPLIT_L2_CACHE_KERNEL_H | ||
| 17 | +#define ADD_L2_CACHE_SPLIT_L2_CACHE_KERNEL_H | ||
| 18 | + | ||
| 19 | +#include "kernel_operator.h" | ||
| 20 | +#include "tiling/platform/platform_ascendc.h" | ||
| 21 | + | ||
| 22 | +namespace AddL2Cache { | ||
| 23 | + | ||
| 24 | +constexpr uint32_t vectorCoreCount = 20; | ||
| 25 | +constexpr uint32_t computeRoundCount = 2; | ||
| 26 | + | ||
| 27 | +// The negative example scans the whole 384MB range. The positive example derives four 96MB L2 batches | ||
| 28 | +// from the 100MB effective working-set threshold, so repeated reads stay closer to the first access. | ||
| 29 | +constexpr uint32_t totalByteSize = 384 * 1024 * 1024; | ||
| 30 | +constexpr uint32_t L2_TILE_THRESHOLD = 100 * 1024 * 1024; | ||
| 31 | +constexpr uint32_t l2BatchCount = (totalByteSize + L2_TILE_THRESHOLD - 1) / L2_TILE_THRESHOLD; | ||
| 32 | +constexpr uint32_t l2BatchSizeBytes = totalByteSize / l2BatchCount; | ||
| 33 | +constexpr uint32_t totalElementCount = totalByteSize / sizeof(half); | ||
| 34 | +constexpr uint32_t l2BatchElementCount = l2BatchSizeBytes / sizeof(half); | ||
| 35 | + | ||
| 36 | +// Use 32-byte DataBlocks as the core distribution unit so every DataCopy length remains aligned. | ||
| 37 | +constexpr uint32_t dataBlockSizeBytes = 32; | ||
| 38 | +constexpr uint32_t elementsPerDataBlock = dataBlockSizeBytes / sizeof(half); | ||
| 39 | + | ||
| 40 | +constexpr uint32_t MAX_DATA_COPY_LEN = 16384; | ||
| 41 | +constexpr uint32_t logicalGmToUbBytesPerKernel = totalByteSize * computeRoundCount; | ||
| 42 | +constexpr uint32_t logicalUbToGmBytesPerKernel = logicalGmToUbBytesPerKernel; | ||
| 43 | + | ||
| 44 | +class KernelAdd { | ||
| 45 | +public: | ||
| 46 | + __aicore__ inline void Init(__gm__ uint8_t* data) | ||
| 47 | + { | ||
| 48 | + dataGm_.SetGlobalBuffer(reinterpret_cast<__gm__ half*>(data), totalElementCount); | ||
| 49 | + inputLocal_ = AscendC::LocalTensor<half>(AscendC::TPosition::VECIN, inputUbOffsetBytes, MAX_DATA_COPY_LEN); | ||
| 50 | + outputLocal_ = AscendC::LocalTensor<half>(AscendC::TPosition::VECOUT, outputUbOffsetBytes, MAX_DATA_COPY_LEN); | ||
| 51 | + } | ||
| 52 | + | ||
| 53 | + __aicore__ inline void ProcessL2Batch(uint32_t l2BatchIdx) | ||
| 54 | + { | ||
| 55 | + // Positive path: only one 96MB L2 batch is active before the next round reuses it. | ||
| 56 | + ProcessDataRange(static_cast<int64_t>(l2BatchIdx) * l2BatchElementCount, l2BatchElementCount); | ||
| 57 | + } | ||
| 58 | + | ||
| 59 | + __aicore__ inline void ProcessWholeData() | ||
| 60 | + { | ||
| 61 | + // Negative path: one round treats the full 384MB range as a single L2 working set. | ||
| 62 | + ProcessDataRange(0, totalElementCount); | ||
| 63 | + } | ||
| 64 | + | ||
| 65 | + __aicore__ inline void SyncAllCores() { AscendC::SyncAll(); } | ||
| 66 | + | ||
| 67 | +private: | ||
| 68 | + static constexpr uint32_t inputUbOffsetBytes = 0; | ||
| 69 | + static constexpr uint32_t outputUbOffsetBytes = MAX_DATA_COPY_LEN * sizeof(half); | ||
| 70 | + | ||
| 71 | + __aicore__ inline void ProcessDataRange(int64_t rangeOffsetInData, uint32_t rangeElementNum) | ||
| 72 | + { | ||
| 73 | + const uint32_t coreIdx = AscendC::GetBlockIdx(); | ||
| 74 | + const uint32_t rangeDataBlockNum = rangeElementNum / elementsPerDataBlock; | ||
| 75 | + // Distribute aligned DataBlocks evenly. The first cores take one extra block when the division has | ||
| 76 | + // a remainder, which keeps each core's GM range contiguous and non-overlapping. | ||
| 77 | + const uint32_t baseDataBlocksPerCore = rangeDataBlockNum / vectorCoreCount; | ||
| 78 | + const uint32_t coresWithExtraDataBlock = rangeDataBlockNum % vectorCoreCount; | ||
| 79 | + const uint32_t extraDataBlockNumBeforeCore = | ||
| 80 | + coreIdx < coresWithExtraDataBlock ? coreIdx : coresWithExtraDataBlock; | ||
| 81 | + const uint32_t coreDataBlockNum = baseDataBlocksPerCore + (coreIdx < coresWithExtraDataBlock ? 1U : 0U); | ||
| 82 | + const uint32_t coreDataBlockOffset = coreIdx * baseDataBlocksPerCore + extraDataBlockNumBeforeCore; | ||
| 83 | + const uint32_t coreElementNum = coreDataBlockNum * elementsPerDataBlock; | ||
| 84 | + const int64_t coreOffsetInData = | ||
| 85 | + rangeOffsetInData + static_cast<int64_t>(coreDataBlockOffset) * elementsPerDataBlock; | ||
| 86 | + ProcessCoreRange(coreOffsetInData, coreElementNum); | ||
| 87 | + } | ||
| 88 | + | ||
| 89 | + __aicore__ inline void ProcessCoreRange(int64_t coreOffsetInData, uint32_t coreElementNum) | ||
| 90 | + { | ||
| 91 | + // UB tiling only fits each core's local buffer. It is not the L2 Cache split granularity. | ||
| 92 | + const uint32_t ubTileNum = AscendC::Ceil(coreElementNum, MAX_DATA_COPY_LEN); | ||
| 93 | + for (uint32_t ubTileIdx = 0; ubTileIdx < ubTileNum; ++ubTileIdx) { | ||
| 94 | + const uint32_t processedElementNum = ubTileIdx * MAX_DATA_COPY_LEN; | ||
| 95 | + const uint32_t remainingElementNum = coreElementNum - processedElementNum; | ||
| 96 | + const uint32_t tileElementNum = | ||
| 97 | + remainingElementNum > MAX_DATA_COPY_LEN ? MAX_DATA_COPY_LEN : remainingElementNum; | ||
| 98 | + const int64_t gmElementOffset = coreOffsetInData + processedElementNum; | ||
| 99 | + | ||
| 100 | + // Reuse one event id for the steady-state single-buffer pipeline: wait for the previous tile's | ||
| 101 | + // V->MTE2 dependency, load the current tile, then release Vector compute. | ||
| 102 | + if (ubTileIdx != 0) { | ||
| 103 | + AscendC::WaitFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID0); | ||
| 104 | + } | ||
| 105 | + AscendC::DataCopy(inputLocal_, dataGm_[gmElementOffset], tileElementNum); | ||
| 106 | + AscendC::SetFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0); | ||
| 107 | + AscendC::WaitFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0); | ||
| 108 | + | ||
| 109 | + // Do not overwrite the output UB region until the previous store has consumed it. | ||
| 110 | + if (ubTileIdx != 0) { | ||
| 111 | + AscendC::WaitFlag<AscendC::HardEvent::MTE3_V>(EVENT_ID0); | ||
| 112 | + } | ||
| 113 | + AscendC::Adds(outputLocal_, inputLocal_, half(1.0), tileElementNum); | ||
| 114 | + if (ubTileIdx != ubTileNum - 1) { | ||
| 115 | + AscendC::SetFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID0); | ||
| 116 | + } | ||
| 117 | + | ||
| 118 | + AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0); | ||
| 119 | + AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0); | ||
| 120 | + AscendC::DataCopy(dataGm_[gmElementOffset], outputLocal_, tileElementNum); | ||
| 121 | + // The last tile has no following load or compute stage, so it leaves no outstanding event. | ||
| 122 | + if (ubTileIdx != ubTileNum - 1) { | ||
| 123 | + AscendC::SetFlag<AscendC::HardEvent::MTE3_V>(EVENT_ID0); | ||
| 124 | + } | ||
| 125 | + } | ||
| 126 | + } | ||
| 127 | + | ||
| 128 | +private: | ||
| 129 | + AscendC::GlobalTensor<half> dataGm_; | ||
| 130 | + AscendC::LocalTensor<half> inputLocal_; | ||
| 131 | + AscendC::LocalTensor<half> outputLocal_; | ||
| 132 | +}; | ||
| 133 | + | ||
| 134 | +} // namespace AddL2Cache | ||
| 135 | + | ||
| 136 | +#endif | ||
| @@ -0,0 +1,187 @@ | |||
| 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 l2_cache_runner.h | ||
| 13 | + * \brief Host runtime shared by the negative and positive examples. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#ifndef ADD_L2_CACHE_SPLIT_L2_CACHE_RUNNER_H | ||
| 17 | +#define ADD_L2_CACHE_SPLIT_L2_CACHE_RUNNER_H | ||
| 18 | + | ||
| 19 | +#include "acl/acl.h" | ||
| 20 | +#include "data_utils.h" | ||
| 21 | +#include "l2_cache_kernel.h" | ||
| 22 | +#include <cerrno> | ||
| 23 | +#include <cstdio> | ||
| 24 | +#include <cstdint> | ||
| 25 | +#include <cstring> | ||
| 26 | +#include <sys/stat.h> | ||
| 27 | + | ||
| 28 | +namespace AddL2Cache { | ||
| 29 | + | ||
| 30 | +using KernelLauncher = void (*)(aclrtStream, uint8_t*); | ||
| 31 | + | ||
| 32 | +inline bool CheckAcl(const char* action, aclError ret) | ||
| 33 | +{ | ||
| 34 | + if (ret == ACL_SUCCESS) { | ||
| 35 | + return true; | ||
| 36 | + } | ||
| 37 | + std::fprintf(stderr, "[ERROR] %s failed, aclError=%d\n", action, static_cast<int32_t>(ret)); | ||
| 38 | + return false; | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +inline uint16_t GetHalfBits(const aclFloat16& value) | ||
| 42 | +{ | ||
| 43 | + uint16_t bits = 0; | ||
| 44 | + static_assert(sizeof(bits) == sizeof(value), "aclFloat16 must use 16 bits"); | ||
| 45 | + std::memcpy(&bits, &value, sizeof(bits)); | ||
| 46 | + return bits; | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +inline bool VerifyOutput(const uint8_t* inputHost, const uint8_t* outputHost, size_t dataSizeBytes) | ||
| 50 | +{ | ||
| 51 | + const aclFloat16* input = reinterpret_cast<const aclFloat16*>(inputHost); | ||
| 52 | + const aclFloat16* output = reinterpret_cast<const aclFloat16*>(outputHost); | ||
| 53 | + const size_t elementCount = dataSizeBytes / sizeof(aclFloat16); | ||
| 54 | + | ||
| 55 | + for (size_t idx = 0; idx < elementCount; ++idx) { | ||
| 56 | + const float inputValue = aclFloat16ToFloat(input[idx]); | ||
| 57 | + const aclFloat16 expected = aclFloatToFloat16(inputValue + static_cast<float>(computeRoundCount)); | ||
| 58 | + if (std::memcmp(&output[idx], &expected, sizeof(aclFloat16)) == 0) { | ||
| 59 | + continue; | ||
| 60 | + } | ||
| 61 | + | ||
| 62 | + std::fprintf( | ||
| 63 | + stderr, "[ERROR] result mismatch at index %zu: input=%f, output=%f(0x%04x), expected=%f(0x%04x)\n", idx, | ||
| 64 | + inputValue, aclFloat16ToFloat(output[idx]), GetHalfBits(output[idx]), aclFloat16ToFloat(expected), | ||
| 65 | + GetHalfBits(expected)); | ||
| 66 | + return false; | ||
| 67 | + } | ||
| 68 | + return true; | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +inline bool RunKernel(const char* caseName, const char* outputPath, KernelLauncher launchKernel, aclrtStream stream) | ||
| 72 | +{ | ||
| 73 | + constexpr size_t dataSizeBytes = static_cast<size_t>(totalElementCount) * sizeof(aclFloat16); | ||
| 74 | + | ||
| 75 | + uint8_t* inputHost = nullptr; | ||
| 76 | + uint8_t* outputHost = nullptr; | ||
| 77 | + uint8_t* dataDevice = nullptr; | ||
| 78 | + | ||
| 79 | + bool success = | ||
| 80 | + CheckAcl("aclrtMallocHost(inputHost)", aclrtMallocHost(reinterpret_cast<void**>(&inputHost), dataSizeBytes)); | ||
| 81 | + success = | ||
| 82 | + success && | ||
| 83 | + CheckAcl("aclrtMallocHost(outputHost)", aclrtMallocHost(reinterpret_cast<void**>(&outputHost), dataSizeBytes)); | ||
| 84 | + success = | ||
| 85 | + success && CheckAcl( | ||
| 86 | + "aclrtMalloc(dataDevice)", | ||
| 87 | + aclrtMalloc(reinterpret_cast<void**>(&dataDevice), dataSizeBytes, ACL_MEM_MALLOC_HUGE_FIRST)); | ||
| 88 | + | ||
| 89 | + size_t fileSize = 0; | ||
| 90 | + if (success) { | ||
| 91 | + success = ReadFile("./input/input.bin", fileSize, inputHost, dataSizeBytes) && fileSize == dataSizeBytes; | ||
| 92 | + if (!success) { | ||
| 93 | + std::fprintf(stderr, "[ERROR] invalid input file (expected %zu bytes, got %zu)\n", dataSizeBytes, fileSize); | ||
| 94 | + } | ||
| 95 | + } | ||
| 96 | + if (success && mkdir("./output", 0755) != 0 && errno != EEXIST) { | ||
| 97 | + std::fprintf(stderr, "[ERROR] failed to create output directory: %s\n", std::strerror(errno)); | ||
| 98 | + success = false; | ||
| 99 | + } | ||
| 100 | + if (success) { | ||
| 101 | + success = CheckAcl( | ||
| 102 | + "aclrtMemcpy(HOST_TO_DEVICE)", | ||
| 103 | + aclrtMemcpy(dataDevice, dataSizeBytes, inputHost, dataSizeBytes, ACL_MEMCPY_HOST_TO_DEVICE)); | ||
| 104 | + } | ||
| 105 | + if (success) { | ||
| 106 | + launchKernel(stream, dataDevice); | ||
| 107 | + success = CheckAcl("aclrtSynchronizeStream", aclrtSynchronizeStream(stream)); | ||
| 108 | + } | ||
| 109 | + if (success) { | ||
| 110 | + success = CheckAcl( | ||
| 111 | + "aclrtMemcpy(DEVICE_TO_HOST)", | ||
| 112 | + aclrtMemcpy(outputHost, dataSizeBytes, dataDevice, dataSizeBytes, ACL_MEMCPY_DEVICE_TO_HOST)); | ||
| 113 | + } | ||
| 114 | + if (success) { | ||
| 115 | + success = VerifyOutput(inputHost, outputHost, dataSizeBytes); | ||
| 116 | + } | ||
| 117 | + if (success) { | ||
| 118 | + success = WriteFile(outputPath, outputHost, dataSizeBytes); | ||
| 119 | + } | ||
| 120 | + if (success) { | ||
| 121 | + std::printf("%s output: %s\n", caseName, outputPath); | ||
| 122 | + } | ||
| 123 | + | ||
| 124 | + if (dataDevice != nullptr) { | ||
| 125 | + (void)aclrtFree(dataDevice); | ||
| 126 | + } | ||
| 127 | + if (outputHost != nullptr) { | ||
| 128 | + (void)aclrtFreeHost(outputHost); | ||
| 129 | + } | ||
| 130 | + if (inputHost != nullptr) { | ||
| 131 | + (void)aclrtFreeHost(inputHost); | ||
| 132 | + } | ||
| 133 | + return success; | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +inline int32_t RunSample( | ||
| 137 | + int32_t argc, char* argv[], const char* caseName, const char* outputPath, KernelLauncher launchKernel, | ||
| 138 | + bool enableL2Split) | ||
| 139 | +{ | ||
| 140 | + constexpr uint32_t bytesPerMiB = 1024 * 1024; | ||
| 141 | + if (argc != 1) { | ||
| 142 | + std::fprintf(stderr, "Usage: %s\n", argv[0]); | ||
| 143 | + return 1; | ||
| 144 | + } | ||
| 145 | + const uint32_t activeWorkingSetBytes = enableL2Split ? l2BatchSizeBytes : totalByteSize; | ||
| 146 | + const uint32_t activeBatchCount = enableL2Split ? l2BatchCount : 1U; | ||
| 147 | + std::printf( | ||
| 148 | + "case=%s, total_data_elements=%u, total_data=%u MB, " | ||
| 149 | + "l2_split=%s, l2_working_set_threshold=%u MB, active_working_set=%u MB, " | ||
| 150 | + "logical_gm_to_ub=%u MB, vector_cores=%u, l2_batches=%u, compute_rounds=%u\n", | ||
| 151 | + caseName, totalElementCount, totalByteSize / bytesPerMiB, enableL2Split ? "enabled" : "disabled", | ||
| 152 | + L2_TILE_THRESHOLD / bytesPerMiB, activeWorkingSetBytes / bytesPerMiB, logicalGmToUbBytesPerKernel / bytesPerMiB, | ||
| 153 | + vectorCoreCount, activeBatchCount, computeRoundCount); | ||
| 154 | + std::fflush(stdout); | ||
| 155 | + | ||
| 156 | + bool aclInitialized = CheckAcl("aclInit", aclInit(nullptr)); | ||
| 157 | + bool success = aclInitialized; | ||
| 158 | + constexpr int32_t deviceId = 0; | ||
| 159 | + bool deviceSet = false; | ||
| 160 | + if (success) { | ||
| 161 | + deviceSet = CheckAcl("aclrtSetDevice", aclrtSetDevice(deviceId)); | ||
| 162 | + success = deviceSet; | ||
| 163 | + } | ||
| 164 | + aclrtStream stream = nullptr; | ||
| 165 | + if (success) { | ||
| 166 | + success = CheckAcl("aclrtCreateStream", aclrtCreateStream(&stream)); | ||
| 167 | + } | ||
| 168 | + | ||
| 169 | + if (success) { | ||
| 170 | + success = RunKernel(caseName, outputPath, launchKernel, stream); | ||
| 171 | + } | ||
| 172 | + if (stream != nullptr) { | ||
| 173 | + success = CheckAcl("aclrtDestroyStream", aclrtDestroyStream(stream)) && success; | ||
| 174 | + } | ||
| 175 | + if (deviceSet) { | ||
| 176 | + success = CheckAcl("aclrtResetDevice", aclrtResetDevice(deviceId)) && success; | ||
| 177 | + } | ||
| 178 | + if (aclInitialized) { | ||
| 179 | + success = CheckAcl("aclFinalize", aclFinalize()) && success; | ||
| 180 | + } | ||
| 181 | + std::printf("test %s!\n", success ? "pass" : "failed"); | ||
| 182 | + return success ? 0 : 1; | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +} // namespace AddL2Cache | ||
| 186 | + | ||
| 187 | +#endif | ||
| @@ -0,0 +1,60 @@ | |||
| 1 | +#!/usr/bin/python3 | ||
| 2 | +# coding=utf-8 | ||
| 3 | + | ||
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 10 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 11 | + | ||
| 12 | +"""Generate fixed input and golden data for the L2 Cache split sample.""" | ||
| 13 | + | ||
| 14 | +import argparse | ||
| 15 | +import struct | ||
| 16 | +from pathlib import Path | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +TOTAL_DATA_ELEMENTS = 201326592 | ||
| 20 | +CHUNK_ELEMENTS = 65536 | ||
| 21 | +COMPUTE_ROUND_COUNT = 2 | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +def parse_args(): | ||
| 25 | + parser = argparse.ArgumentParser() | ||
| 26 | + parser.add_argument("-scenarioNum", type=int, choices=[1, 2], default=1) | ||
| 27 | + return parser.parse_args() | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +def main(): | ||
| 31 | + args = parse_args() | ||
| 32 | + input_dir = Path("input") | ||
| 33 | + output_dir = Path("output") | ||
| 34 | + input_dir.mkdir(exist_ok=True) | ||
| 35 | + output_dir.mkdir(exist_ok=True) | ||
| 36 | + | ||
| 37 | + input_path = input_dir / "input.bin" | ||
| 38 | + golden_path = output_dir / "golden.bin" | ||
| 39 | + with input_path.open("wb") as input_file, golden_path.open("wb") as golden_file: | ||
| 40 | + offset = 0 | ||
| 41 | + while offset < TOTAL_DATA_ELEMENTS: | ||
| 42 | + count = min(CHUNK_ELEMENTS, TOTAL_DATA_ELEMENTS - offset) | ||
| 43 | + input_values = [ | ||
| 44 | + float(((offset + index) % 32) - 16) for index in range(count) | ||
| 45 | + ] | ||
| 46 | + golden_values = [value + COMPUTE_ROUND_COUNT for value in input_values] | ||
| 47 | + input_file.write(struct.pack(f"<{count}e", *input_values)) | ||
| 48 | + golden_file.write(struct.pack(f"<{count}e", *golden_values)) | ||
| 49 | + offset += count | ||
| 50 | + | ||
| 51 | + bytes_per_half = 2 | ||
| 52 | + total_data_mib = TOTAL_DATA_ELEMENTS * bytes_per_half / 1024 / 1024 | ||
| 53 | + print( | ||
| 54 | + f"scenarioNum={args.scenarioNum}, total_data_elements={TOTAL_DATA_ELEMENTS}, " | ||
| 55 | + f"total_data={total_data_mib:.0f} MB" | ||
| 56 | + ) | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +if __name__ == "__main__": | ||
| 60 | + main() | ||
| @@ -0,0 +1,88 @@ | |||
| 1 | +#!/usr/bin/python3 | ||
| 2 | +# coding=utf-8 | ||
| 3 | + | ||
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 10 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 11 | + | ||
| 12 | +"""Verify output data for the L2 Cache split sample.""" | ||
| 13 | + | ||
| 14 | +import argparse | ||
| 15 | +import struct | ||
| 16 | +import sys | ||
| 17 | +from pathlib import Path | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +BYTES_PER_HALF = 2 | ||
| 21 | +CHUNK_BYTES = 1024 * 1024 | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +def parse_args(): | ||
| 25 | + parser = argparse.ArgumentParser() | ||
| 26 | + parser.add_argument("output") | ||
| 27 | + parser.add_argument("golden") | ||
| 28 | + parser.add_argument("-scenarioNum", type=int, choices=[1, 2], default=1) | ||
| 29 | + return parser.parse_args() | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +def half_to_float(data): | ||
| 33 | + return struct.unpack("<e", data)[0] | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +def verify_result(output_path, golden_path): | ||
| 37 | + output_file_path = Path(output_path) | ||
| 38 | + golden_file_path = Path(golden_path) | ||
| 39 | + output_size = output_file_path.stat().st_size | ||
| 40 | + golden_size = golden_file_path.stat().st_size | ||
| 41 | + if output_size != golden_size: | ||
| 42 | + print( | ||
| 43 | + f"[ERROR] file size mismatch: output={output_size} bytes, " | ||
| 44 | + f"golden={golden_size} bytes" | ||
| 45 | + ) | ||
| 46 | + return False | ||
| 47 | + if output_size % BYTES_PER_HALF != 0: | ||
| 48 | + print(f"[ERROR] invalid output file size: {output_size} bytes") | ||
| 49 | + return False | ||
| 50 | + | ||
| 51 | + with output_file_path.open("rb") as output_file, golden_file_path.open( | ||
| 52 | + "rb" | ||
| 53 | + ) as golden_file: | ||
| 54 | + base_index = 0 | ||
| 55 | + while True: | ||
| 56 | + output_data = output_file.read(CHUNK_BYTES) | ||
| 57 | + golden_data = golden_file.read(CHUNK_BYTES) | ||
| 58 | + if not output_data and not golden_data: | ||
| 59 | + return True | ||
| 60 | + if output_data == golden_data: | ||
| 61 | + base_index += len(output_data) // BYTES_PER_HALF | ||
| 62 | + continue | ||
| 63 | + | ||
| 64 | + for offset in range(0, len(output_data), BYTES_PER_HALF): | ||
| 65 | + output_half = output_data[offset : offset + BYTES_PER_HALF] | ||
| 66 | + golden_half = golden_data[offset : offset + BYTES_PER_HALF] | ||
| 67 | + if output_half == golden_half: | ||
| 68 | + continue | ||
| 69 | + index = base_index + offset // BYTES_PER_HALF | ||
| 70 | + print( | ||
| 71 | + f"[ERROR] result mismatch at index {index}: " | ||
| 72 | + f"actual={half_to_float(output_half)}, " | ||
| 73 | + f"expected={half_to_float(golden_half)}" | ||
| 74 | + ) | ||
| 75 | + return False | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +def main(): | ||
| 79 | + args = parse_args() | ||
| 80 | + if not verify_result(args.output, args.golden): | ||
| 81 | + print("test failed!") | ||
| 82 | + return 1 | ||
| 83 | + print("test pass!") | ||
| 84 | + return 0 | ||
| 85 | + | ||
| 86 | + | ||
| 87 | +if __name__ == "__main__": | ||
| 88 | + sys.exit(main()) | ||
| @@ -17,3 +17,4 @@ | |||
| 17 | | [06_atomic](./06_atomic) | 本路径下包含了与原子操作相关的多个API的样例。每个样例均基于Ascend C的<<<>>>直调方法,支持main函数和kernel函数在同一个cpp文件中实现。 | | 17 | | [06_atomic](./06_atomic) | 本路径下包含了与原子操作相关的多个API的样例。每个样例均基于Ascend C的<<<>>>直调方法,支持main函数和kernel函数在同一个cpp文件中实现。 | |
| 18 | | [07_tpipe_tque](./07_tpipe_tque) | 本路径下包含了与tpipe和tque相关的多个API的样例。每个样例均基于Ascend C的<<<>>>直调方法,支持main函数和kernel函数在同一个cpp文件中实现。 | | 18 | | [07_tpipe_tque](./07_tpipe_tque) | 本路径下包含了与tpipe和tque相关的多个API的样例。每个样例均基于Ascend C的<<<>>>直调方法,支持main函数和kernel函数在同一个cpp文件中实现。 | |
| 19 | | [09_utils](./09_utils) | 本路径下包含了与工具相关API的样例。每个样例均基于Ascend C的<<<>>>直调方法,支持main函数和kernel函数在同一个cpp文件中实现。 | | 19 | | [09_utils](./09_utils) | 本路径下包含了与工具相关API的样例。每个样例均基于Ascend C的<<<>>>直调方法,支持main函数和kernel函数在同一个cpp文件中实现。 | |
| 20 | +| [10_add_l2_cache_split](./10_add_l2_cache_split) | 本样例通过384MB原地Add固定负载,对比不切分和按96MB L2 Batch切分两种访问顺序,展示跨轮复用数据场景下提升L2 Cache命中率的方法。| | ||
| @@ -17,3 +17,4 @@ This sample introduces the usage of Ascend C Basic API, including data movement, | |||
| 17 | | [06_atomic](./06_atomic) | This directory contains samples for multiple APIs related to atomic operations. Each sample is based on the Ascend C `<<<>>>` direct invocation method, supporting the implementation of both the main function and kernel function in the same cpp file. | | 17 | | [06_atomic](./06_atomic) | This directory contains samples for multiple APIs related to atomic operations. Each sample is based on the Ascend C `<<<>>>` direct invocation method, supporting the implementation of both the main function and kernel function in the same cpp file. | |
| 18 | | [07_tpipe_tque](./07_tpipe_tque) | This directory contains samples for multiple APIs related to TPipe/TQue resource management. Each sample is based on the Ascend C `<<<>>>` direct invocation method, supporting the implementation of both the main function and kernel function in the same cpp file. | | 18 | | [07_tpipe_tque](./07_tpipe_tque) | This directory contains samples for multiple APIs related to TPipe/TQue resource management. Each sample is based on the Ascend C `<<<>>>` direct invocation method, supporting the implementation of both the main function and kernel function in the same cpp file. | |
| 19 | | [09_utils](./09_utils) | This directory contains API samples related to utilities. Each sample is based on the Ascend C `<<<>>>` direct invocation method, supporting the implementation of both the main function and kernel function in the same cpp file. | | 19 | | [09_utils](./09_utils) | This directory contains API samples related to utilities. Each sample is based on the Ascend C `<<<>>>` direct invocation method, supporting the implementation of both the main function and kernel function in the same cpp file. | |
| 20 | +| [10_add_l2_cache_split](./10_add_l2_cache_split) | This sample compares no-split and 96MB L2-batch traversal orders for a fixed 384MB in-place Add workload, demonstrating how to improve the L2 Cache hit rate for repeated data access.| | ||


前面说明的是input ,这里是data,建议统一为相同的变量名