Pull Request has been successfully merged by CANN-robot.
(Thank you for yhf0922's contribution.)变更摘要
本 PR(类型为 docs 文档更新)通过新增一组正/反示例来补充 L2 Cache 切分优化的说明:新增示例目录 examples/01_simd_cpp_api/03_basic_api/10_add_l2_cache_split/,以 Add 算子为例对比"不切分"(一次处理整个 384MB 数据范围)与"按 L2 batch 切分"(每轮只激活一个 96MB 的 L2 batch,处理完再进入下一批)两种遍历方式。核心逻辑由命名空间 AddL2Cache 中的 KernelAdd 类承载,通过 ProcessWholeData 与 ProcessL2Batch 分别实现两种路径,并由共享的 host 运行时 RunSample/RunKernel 驱动,配合数据生成脚本 gen_data.py 和文件读写工具 data_utils.h 完成样例闭环。
主要改动
- 新增正/反例核函数样例:新增
add_l2cache_split.asc(正向,外层按l2BatchCount循环调用ProcessL2Batch并SyncAllCores)与add_l2cache_nosplit.asc(反向,整个computeRoundCount轮均调用ProcessWholeData处理全量 384MB),并通过RunSample的enableL2Split参数区分两种场景,用于直观对比 L2 Cache 切分的收益。 - 新增共享参数与设备侧处理头文件
l2_cache_kernel.h:定义vectorCoreCount = 20、computeRoundCount = 2、totalByteSize = 384MB、L2_TILE_THRESHOLD = 100MB,据此推导出l2BatchCount = 4与l2BatchSizeBytes = 96MB;KernelAdd以 32 字节DataBlock为单位向 20 个核均分连续、不重叠的 GM 数据范围,并使用MAX_DATA_COPY_LEN = 16384做 UB 分片流水(复用单一事件 ID 串起 DataCopy/Adds/DataCopy 的依赖)。 - 新增共享 host 运行时
l2_cache_runner.h:提供RunKernel(完成 host/device 内存分配、输入读取、核函数启动、输出回写)与RunSample(打印l2_split、active_working_set、l2_batches等关键参数并管理 ACL 生命周期),两个示例共用同一套运行时。 - 新增数据工具与数据生成脚本:
data_utils.h提供ReadFile/WriteFile二进制文件读写工具;scripts/gen_data.py生成固定的 384MiB(TOTAL_DATA_ELEMENTS = 201326592个 half 元素)输入文件input/input.bin,供两个示例使用。 - 新增冒烟测试样例:新增
add_l2cache_split_test.asc,包含aclInit/aclrtSetDevice/aclrtCreateStream等 ACL 初始化与释放流程的冒烟测试入口。


代码审查
Let me start by reviewing each file in the diff. I'll read the files to understand context, then check for issues.
Let me start with the C/C++ files and the Python script.
Key files:
- CMakeLists.txt - build config
- add_l2cache_nosplit.asc
- add_l2cache_split.asc
- add_l2cache_split_test.asc
- data_utils.h
- l2_cache_kernel.h
- l2_cache_runner.h
- scripts/gen_data.py
Let me analyze each carefully.
data_utils.h
ReadFile: usesstd::ifstream, checks size > bufferSize. OK.WriteFile: usesopenwithO_RDWR | O_CREAT | O_TRUNC. Note the mode usesS_IWRITEwhich is a Windows macro; on Linux it'sS_IWUSR | S_IWGRP | S_IWOTH. ActuallyS_IWRITEis defined on Windows only. On Linux,<sys/stat.h>doesn't defineS_IWRITE. This would be a compile error on Linux! Let me check. In<sys/stat.h>on Linux, there'sS_IRUSR,S_IWUSR,S_IXUSR, etc. There's noS_IWRITE. Hmm, actually in some environments,S_IWRITEmay be defined... In MSVC CRT,S_IWRITEis defined as_S_IWRITE. On Linux, glibc doesn't defineS_IWRITE. So this would be a compile error. Wait, but this is a common pattern in CANN samples... Let me check other examples in the repo forS_IWRITE.
Actually, let me grep the repository for S_IWRITE usage.
-
write(fd, buffer, size)— return value checked. But note thatwritemay write fewer bytes than requested (partial write); it returns the number written, checked against size. OK-ish. -
ERROR_LOGusesfprintf(stdout, ...)— includes<cstdio>? In data_utils.h, includes are fcntl.h, sys/stat.h, unistd.h, fstream.fprintfneeds<cstdio>. It may be pulled transitively. Minor.
l2_cache_kernel.h
Constants:
totalByteSize = 384 * 1024 * 1024— 384 * 1024 * 1024 = 402,653,184. As uint32_t, fine (< 2^32).L2_TILE_THRESHOLD = 100 * 1024 * 1024= 104,857,600.l2BatchCount = (totalByteSize + L2_TILE_THRESHOLD - 1) / L2_TILE_THRESHOLD= ceil(402653184/104857600) = ceil(3.84) = 4. 402653184 + 104857599 = 507510783; /104857600 = 4.84 → 4. OK, so l2BatchCount = 4.l2BatchSizeBytes = totalByteSize / l2BatchCount= 402653184 / 4 = 100,663,296 (96MB). But wait, the comment says "four 96MB L2 batches" — 402653184/4 = 100663296 = 96MB. OK.totalElementCount = totalByteSize / sizeof(half)= 402653184 / 2 = 201,326,592 elements. As uint32_t, 201326592 fits fine.l2BatchElementCount = l2BatchSizeBytes / 2= 50,331,648.dataBlockSizeBytes = 32,elementsPerDataBlock = 16.MAX_DATA_COPY_LEN = 16384— this is a byte count or element count? InInit,LocalTensor<half>(TPosition::VECIN, inputUbOffsetBytes, MAX_DATA_COPY_LEN)— the third parameter is the size in elements for LocalTensor? Actually the LocalTensor constructor signature:LocalTensor<T>(TPosition tPosition, uint32_t bufferOffset, uint32_t size)where size is in elements? Hmm. Let me think. In AscendC,LocalTensor<T>(TPosition::VECIN, offset, size)— size is the number of elements of type T. Hmm, actually I recall the LocalTensor constructorLocalTensor(TPosition tPosition, uint32_t bufferOffset, uint32_t size). The size is the number of elements. SoLocalTensor<half>(VECIN, 0, 16384)allocates 16384 half elements = 32KB. ThenoutputUbOffsetBytes = MAX_DATA_COPY_LEN * sizeof(half)= 16384*2 = 32768 bytes offset. That suggests inputLocal_ occupies bytes [0, 32768) — i.e., 16384 half elements. OK consistent: input uses 16384 elements = 32KB, output starts at byte 32768.
Wait — but is the offset in bytes or elements? The name says inputUbOffsetBytes. LocalTensor buffer offset is in bytes typically. OK.
Then in ProcessCoreRange, tileElementNum is capped at MAX_DATA_COPY_LEN = 16384. And DataCopy length: AscendC::DataCopy(inputLocal_, dataGm_[gmElementOffset], tileElementNum) — DataCopy's third parameter is the number of elements? Actually DataCopy(local, global, count) — count is in elements of the local tensor type. Hmm, for DataCopy<T>(LocalTensor<T> dstLocal, GlobalTensor<T> srcGlobal, int32_t count), count is in elements. So 16384 elements = 32KB per copy, within the 32KB UB buffer. And the max DataCopy length limit is... For vector core, DataCopy max length per instruction might be limited, but the API handles splitting. Actually wait, DataCopy has a max length limit of... there's a constraint that count ≤ 32KB? Hmm. Actually the L1/L2 DataCopy max length. For half (FP16), 16384 elements = 32KB. That should be OK.
But MAX_DATA_COPY_LEN is named as if it's a length in bytes? "MAX_DATA_COPY_LEN = 16384". The DataCopy count param is in elements for half → 16384 half = 32KB. Hmm, but DataCopy max count in elements? The limit might be that DataCopy can copy at most... Actually there's a well-known constraint: DataCopy max block length is 32KB per copy for vector. OK.
Also, Adds(outputLocal_, inputLocal_, half(1.0), tileElementNum) — Adds count in elements. Fine.
Wait — but there's a subtlety: the element count per tile is 16384, but the DataCopy from GM requires GM addresses aligned to 32 bytes; tileElementNum = 16384, alignment fine. But the last tile may have tileElementNum not multiple of... e.g., if coreElementNum is not a multiple of 16384. Last tile remainder could be non-32-byte-aligned in element count → DataCopy handles it? The comment says "so every DataCopy length remains aligned" based on 32-byte data blocks distributed per core. Each core gets a multiple of elementsPerDataBlock=16 elements (32 bytes). And MAX_DATA_COPY_LEN = 16384 is a multiple of 16. So tile sizes are multiples of 16 → 32 bytes. But is 32-byte alignment enough for DataCopy? GM requires 32-byte aligned for fp16? DataCopy requires 32-byte alignment (for half, 16 elements = 32 bytes). OK.
Hmm, but wait: the concern is about UB tiling, the last tile's DataCopy length must be at least 32 bytes? The minimum DataCopy length is... some minimum. Not critical for review.
Now the pipelining: uses WaitFlag/SetFlag on EVENT_ID0 with HardEvent::V_MTE2, MTE2_V, MTE3_V, V_MTE3. Let me analyze:
For tile 0:
- no wait for V_MTE2 (ubTileIdx==0).
- DataCopy(inputLocal_, ..., tileElementNum) — MTE2 loads.
- SetFlag<MTE2_V>(EVENT_ID0) — after load completes, signal MTE2→V.
- WaitFlag<MTE2_V>(EVENT_ID0) — wait for load done before compute.
- no wait MTE3_V (ubTileIdx==0).
- Adds(...) — V computes.
- SetFlag<V_MTE3>(EVENT_ID0) — signal V→MTE3 (output ready).
- WaitFlag<V_MTE3>(EVENT_ID0) — wait.
- DataCopy(dataGm_, outputLocal_, tileElementNum) — MTE3 stores.
- if not last: SetFlag<MTE3_V>(EVENT_ID0) — signal store done → V can overwrite output UB.
For tile 1:
- ubTileIdx != 0 → WaitFlag<V_MTE2>(EVENT_ID0) — wait for previous tile's store done (MTE3_V event). Hmm wait, the comment says "wait for the previous tile's V->MTE2 dependency". Actually V_MTE2 event signals that Vector's use of inputLocal_ is done? Let me re-read.
The SetFlag<V_MTE2> is set after Adds (at line 115: if (ubTileIdx != ubTileNum - 1) SetFlag<V_MTE2>(EVENT_ID0);). So V_MTE2 means "vector finished reading inputLocal_, MTE2 can overwrite it with next tile". And at tile i>0, WaitFlag<V_MTE2> waits for that.
But here's a problem: EVENT_ID0 is reused for multiple events (V_MTE2, MTE2_V, MTE3_V, V_MTE3) on the same event id. In AscendC, event ids must be unique per (event, id) pair? Actually each HardEvent type has its own event register space; reusing the same event id for different HardEvent types is allowed as long as the pair (event type, id) is distinct. Hmm, actually in AscendC, event IDs are per-event registers. SetFlag<MTE2_V>(EVENT_ID0) and SetFlag<V_MTE2>(EVENT_ID0) use different event registers (different HardEvent types), so reusing EVENT_ID0 is fine.
But within the same event type, you must not have two outstanding (unconsumed) events with the same id. Let's check V_MTE2: at tile i, SetFlag<V_MTE2> set at end of Adds (if not last). Then at tile i+1, WaitFlag<V_MTE2> consumes it. Then next SetFlag<V_MTE2> at tile i+1 (if not last). So one outstanding at a time. OK.
MTE2_V: tile i: SetFlag<MTE2_V> after DataCopy, WaitFlag<MTE2_V> right after. One outstanding. OK.
V_MTE3: tile i: SetFlag<V_MTE3> after Adds, WaitFlag<V_MTE3> right after. OK.
MTE3_V: tile i: SetFlag<MTE3_V> after DataCopy (store) if not last. tile i+1: WaitFlag<MTE3_V> at start (if ubTileIdx != 0). Hmm wait, at tile i+1, first WaitFlag<V_MTE2> then DataCopy, SetFlag<MTE2_V>, WaitFlag<MTE2_V>, then WaitFlag<MTE3_V>. The MTE3_V event from tile i signals that MTE3 finished reading outputLocal_ (store done), so V can now write outputLocal_. OK.
Now the interesting race: at tile i+1, after WaitFlag<MTE3_V>, the Adds writes outputLocal_. But DataCopy(inputLocal_...) at tile i+1 was issued before... inputLocal_ and outputLocal_ are different buffers. The V_MTE2 wait ensures inputLocal_ can be overwritten. OK.
Hmm, but wait: there's an issue with WaitFlag<V_MTE2> at tile i+1 being before DataCopy — the V_MTE2 event from tile i is set after the Adds of tile i, but the Adds of tile i reads inputLocal_... yes, so V_MTE2 signals "V is done reading input", so MTE2 can overwrite. Good.
Now — a subtle correctness issue: The steady-state pipeline reuses a single event ID for V_MTE2 across tiles. Since it's one outstanding at a time, fine.
Now let me check the potential deadlock / missing event: For the last tile, no SetFlag<V_MTE2>, no SetFlag<MTE3_V>. That's fine since no next tile.
But there's an issue at tile 0: WaitFlag<V_MTE2> skipped at ubTileIdx==0. Good.
Now, SyncAll() between rounds: SyncAllCores() calls AscendC::SyncAll(). In the split kernel, SyncAll is called after each round inside the batch loop. Wait — actually, hmm, AscendC::SyncAll() is a cross-core barrier. Calling it after each round... For the split version, the loop is:
for l2BatchIdx:
for roundIdx:
op.ProcessL2Batch(l2BatchIdx);
op.SyncAllCores();
Hmm, that processes the same batch twice (computeRoundCount=2) then moves to next batch. That matches the description: "Positive example: finish every round of an L2 batch before moving to the next L2 batch."
The negative:
for roundIdx (2):
op.ProcessWholeData();
op.SyncAllCores();
processes the whole 384MB twice.
Now — a big issue: The total data transferred: logicalGmToUbBytesPerKernel = totalByteSize * computeRoundCount = 384MB * 2 = 768MB. This is uint32_t = 805,306,368, fits.
Hmm, wait. Is there an issue with the L2 cache being used? The example is a demo. Not a real issue for review.
Now the important AscendC review points:
-
AscendC::InitSocState()— fine. -
Kernel signature
extern "C" __global__ __vector__ void l2_cache_nosplit(__gm__ uint8_t* data). The project-specific rule says__global__ __vector__is fine (SIMD+SIMT mixed programming). -
SetFlag/WaitFlagpairing: seems consistent. -
Actually, wait — there might be an issue with the flag usage:
WaitFlag<V_MTE2>(EVENT_ID0)— the V_MTE2 event must be SetFlag'd by V... but actually in AscendC, V_MTE2 is a HardEvent that is set by the Vector unit.SetFlag<HardEvent::V_MTE2>sets a flag that MTE2 waits on. AndWaitFlag<HardEvent::V_MTE2>makes Vector wait for an event set by MTE2... Hmm wait, no. Let me recall AscendC flag semantics.
In AscendC:
SetFlag<HardEvent::MTE2_V>(eventId)— set flag to indicate MTE2 completed (data in UB ready), vector can proceed.WaitFlag<HardEvent::MTE2_V>(eventId)— vector waits for the flag.SetFlag<HardEvent::V_MTE2>(eventId)— vector sets flag indicating compute done with source, MTE2 can overwrite.WaitFlag<HardEvent::V_MTE2>(eventId)— MTE2 waits. But can MTE2 wait? In AscendC, WaitFlagHardEvent::V_MTE2 can be called... The vector core can wait on MTE2_V; the naming convention is "from_to" meaning the flag is set by "from" and waited by "to"? Actually the HardEvent enum:MTE2_Vmeans "event from MTE2 to Vector" — set by MTE2, waited by Vector.V_MTE2means "event from Vector to MTE2" — set by Vector, waited by MTE2. But here in the code,WaitFlag<HardEvent::V_MTE2>(EVENT_ID0)is executed by the vector core (in the kernel code). Hmm.
Wait, in AscendC, on the vector core, WaitFlag is a synchronous wait executed by the vector pipeline. The event register is shared between MTE2 and Vector. SetFlag<HardEvent::V_MTE2> executed by vector sets the V_MTE2 flag register; WaitFlag<HardEvent::V_MTE2> executed by MTE2 would wait on it. But the vector core can also issue WaitFlag for a flag set by itself? That would be wrong.
Hmm, actually let me reconsider. In many AscendC samples, the pattern for ping-pong is:
DataCopy(inputLocal, dataGm[offset], len); // MTE2 loads
SetFlag<HardEvent::MTE2_V>(EVENT_ID0); // MTE2 done
WaitFlag<HardEvent::MTE2_V>(EVENT_ID0); // V waits
Adds(outputLocal, inputLocal, ...); // V computes
SetFlag<HardEvent::V_MTE3>(EVENT_ID0); // V done
WaitFlag<HardEvent::V_MTE3>(EVENT_ID0); // MTE3 waits...
DataCopy(dataGm[offset], outputLocal, len); // MTE3 stores
Wait, that's not right either — the vector code executes WaitFlag<V_MTE3> after SetFlag<V_MTE3>? That would be waiting on its own flag which was just set — meaning it waits until the flag value increments... Hmm.
Actually, in AscendC's event model, SetFlag increments an event register value, and WaitFlag waits until the register value is >= expected. The vector unit and MTE units share the event registers. So:
-
SetFlag<HardEvent::MTE2_V>(id)by MTE2: increments register (MTE2_V, id). Vector'sWaitFlag<MTE2_V>(id)waits for that count. This synchronizes MTE2→V. -
SetFlag<HardEvent::V_MTE2>(id)by Vector: increments (V_MTE2, id) register. MTE2'sWaitFlag<V_MTE2>(id)... but in vector code,WaitFlag<V_MTE2>— who executes it? The instructionWaitFlagwith a HardEvent type can be executed by the corresponding unit. In vector kernel code, WaitFlag<V_MTE2> would be a vector-side wait on a flag that was set by... hmm, but the vector set it.
Let me look at actual AscendC examples to understand. The standard double-buffer pattern from Huawei samples:
// copy in
DataCopy(inputLocal, srcGlobal, length);
SetFlag<HardEvent::MTE2_V>(EVENT_ID0);
WaitFlag<HardEvent::MTE2_V>(EVENT_ID0);
// compute
Adds(outputLocal, inputLocal, scalar, length);
SetFlag<HardEvent::V_MTE3>(EVENT_ID0);
WaitFlag<HardEvent::V_MTE3>(EVENT_ID0);
// copy out
DataCopy(dstGlobal, outputLocal, length);
Hmm, that's the simple pattern, but it's wrong for pipelining across iterations because the SetFlag after Add and WaitFlag right after don't synchronize anything meaningful.
Actually, in AscendC, SetFlag<HardEvent::X_Y> sets a flag of type X→Y; the instruction is executed by unit X. WaitFlag<HardEvent::X_Y> waits on flag X→Y; executed by unit Y. In vector kernel code, all these are issued from the same instruction stream but target different units: SetFlag<MTE2_V> targets MTE2 (the "set" side), WaitFlag<MTE2_V> targets Vector. Hmm, but actually both SetFlag and WaitFlag appear in the same code stream.
Let me recall from the AscendC API docs:
template <HardEvent event> __aicore__ inline void SetFlag(uint32_t eventID) — "Set flag" — for event = MTE2_V, it's executed on MTE2 (i.e., waits until MTE2's operations complete then sets the flag). For event = V_MTE2, executed on vector. Actually I believe SetFlag<MTE2_V> inserts a synchronization in MTE2 pipeline so that all previously issued MTE2 ops complete before setting the flag, and WaitFlag<MTE2_V> on the vector waits for the flag.
WaitFlag<HardEvent::MTE2_V>(eventID) — waits on MTE2 side? No — the vector core executes WaitFlag to wait for the flag set by MTE2.
Hmm. The naming: HardEvent::MTE2_V = "MTE2 to Vector". SetFlag<MTE2_V> is called by... Let me think about which unit executes the SetFlag instruction. The instruction SetFlag(event) is a vector instruction? In the instruction set, set_flag and wait_flag are executed by the AI core's scalar/vector pipelines. The HardEvent type specifies which event register pair.
Actually I think the semantics in AscendC:
SetFlag<HardEvent::MTE2_V>(id): issued after DataCopy; it ensures MTE2's outstanding copies complete, then sets the MTE2_V flag so the vector can proceed. It's a barrier for MTE2.WaitFlag<HardEvent::MTE2_V>(id): the vector waits until MTE2_V flag count matches.SetFlag<HardEvent::V_MTE2>(id): after vector compute, ensures vector ops complete, sets V_MTE2 flag for MTE2.WaitFlag<HardEvent::V_MTE2>(id): MTE2 (issued by the code stream but executes on MTE2) waits for vector to finish.
Hmm, this is getting complicated, but the pattern in this code seems self-consistent: for each tile:
- if not first: WaitFlag<V_MTE2> — wait until the previous tile's V compute has finished with inputLocal_ (so it's safe for MTE2 to overwrite inputLocal_).
- DataCopy → load.
- SetFlag<MTE2_V>; WaitFlag<MTE2_V> — load complete before compute.
- if not first: WaitFlag<MTE3_V> — wait until previous store (MTE3) finished reading outputLocal_ (so it's safe for V to overwrite outputLocal_).
- Adds.
- SetFlag<V_MTE2> if not last — V done with input, MTE2 can load next.
- SetFlag<V_MTE3>; WaitFlag<V_MTE3> — output ready before store.
- DataCopy → store.
- SetFlag<MTE3_V> if not last — MTE3 done with output, V can overwrite.
This is a coherent single-buffer software pipeline. The event IDs are reused per event type with one outstanding each. Looks OK.
Wait, but there's one concern: WaitFlag<V_MTE3> after SetFlag<V_MTE3> on the same event id — the WaitFlag<V_MTE3> should be consumed by... Actually, since both SetFlag<V_MTE3> and WaitFlag<V_MTE3> are executed in the same stream, and V_MTE3 means "V→MTE3", the WaitFlag<V_MTE3> would be executed by MTE3? No wait. Hmm.
Hmm, actually in AscendC the convention from real Huawei samples is exactly:
SetFlag<HardEvent::MTE2_V>(EVENT_ID0);
WaitFlag<HardEvent::MTE2_V>(EVENT_ID0);
Wait no. Let me look at actual code. In the Add
| 类型 | 数量 |
|---|---|
| 🔴 阻塞 | 0 |
| 🟡 建议 | 2 |
💬 仅评论


Thanks for your pull-request.
The full list of commands accepted by me can be found at here.
You can get sig-info at here.
You can self-configure the PR merge rules for this repository. For more details, please refer to Here.
For more, you also can visit HICANN.
PR Approval Progress
✅ Congratulations! All modules have met the lgtm and approve requirements.
Module Approval Details
| module | lgtm status | approve status |
|---|---|---|
| docs | ✅ ai_xin, Lycheeeee (2/2) | ✅ ai_xin (1/1) |
| examples | ✅ ai_xin, Lycheeeee (2/2) | ✅ ai_xin (1/1) |
💡 Tip:
- Committer can comment
/approveor/lgtm- Commenting
/approveimplies both code review (lgtm) and intent to merge (approve)
CLA Signature Pass
yhf0922, thanks for your pull request. All authors of the commits have signed the CLA. 👍


/lgtm


描述
补充l2cache 切分优化说明
关联的Issue
测试
文档更新
类型标签