Merged
fix(machine): Add aicore-resolve macro #5549
huangluAdd on Aug 19
fix(machine): Add aicore-resolve macro #5549
Merged
huangluAdd on Aug 19
Total: 38 files changed+1564-119
@@ -342,9 +342,21 @@ INLINE uint32_t WaitWaveSignal(__gm__ KernelArgs* args)
342 342 
343#include "tilefwk/aicore_entry_devtask.h"343#include "tilefwk/aicore_entry_devtask.h"
344 344 
345+#if IS_AICORE
346+#if ENABLE_AICORE_RESOLVE
347+#include "tilefwk/aicore_entry_drco.h"
348+#endif
349+#endif
350+ 
345INLINE void KernelEntry(int64_t ffts_addr, int64_t inputs, int64_t outputs, int64_t workspace, int64_t tilingdata,351INLINE void KernelEntry(int64_t ffts_addr, int64_t inputs, int64_t outputs, int64_t workspace, int64_t tilingdata,
346 int64_t cfgdata)352 int64_t cfgdata)
347{353{
354+#if IS_AICORE
355+#if ENABLE_AICORE_RESOLVE
356+ KernelEntryDrco(ffts_addr, inputs, outputs, workspace, tilingdata, cfgdata);
357+ return;
358+#endif
359+#endif
348 uint64_t start = get_sys_cnt();360 uint64_t start = get_sys_cnt();
349 UNUSED(ffts_addr);361 UNUSED(ffts_addr);
350 UNUSED(inputs);362 UNUSED(inputs);
@@ -0,0 +1,478 @@
1+/**
2+ * Copyright (c) 2025-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 aicore_entry_drco.h
13+ * \brief DRCO (Dependency Resolving by aiCOre) scheduling flow for aicore_entry.h.
14+ */
15+ 
16+#ifndef AICORE_ENTRY_DRCO_H
17+#define AICORE_ENTRY_DRCO_H
18+ 
19+// device switch head file begin
20+namespace npu::tile_fwk {
21+ 
22+#if defined(__AIV__)
23+constexpr CoreType drcoCoreType = CoreType::AIV;
24+#elif defined(__AIC__)
25+constexpr CoreType drcoCoreType = CoreType::AIC;
26+#else
27+constexpr CoreType drcoCoreType = CoreType::MIX;
28+#endif
29+ 
30+} // namespace npu::tile_fwk
31+// device switch head file end
32+ 
33+#define DRCO_DCCI_SINGLE_CACHE_LINE(ptr) dcci((__gm__ uint8_t*)ptr, SINGLE_CACHE_LINE, CACHELINE_OUT)
34+#define DRCO_DCCI_ENTIRE_DATA_CACHE() dcci((__gm__ void*)0, ENTIRE_DATA_CACHE, CACHELINE_OUT)
35+ 
36+#define DRCO_BUSY_BACKOFF_CYC 1000
37+ 
38+INLINE void DrcoBusyBackOff()
39+{
40+ uint64_t t0 = get_sys_cnt();
41+ while (get_sys_cnt() - t0 < DRCO_BUSY_BACKOFF_CYC) {
42+ }
43+}
44+ 
45+using DrcoDeviceTask = npu::tile_fwk::DrcoDeviceTask;
46+using DrcoDeviceTaskReadyQueue = npu::tile_fwk::DrcoDeviceTaskReadyQueue;
47+using DrcoGlobalReadyQueue = npu::tile_fwk::DrcoGlobalReadyQueue;
48+using DrcoGlobalReadyQueuePtr = npu::tile_fwk::DrcoGlobalReadyQueuePtr;
49+using DrcoLocalReadyQueue = npu::tile_fwk::DrcoLocalReadyQueue;
50+ 
51+INLINE __gm__ DrcoDeviceTask* GetCurrentDeviceTask(__gm__ DrcoDeviceTaskReadyQueue* queue)
52+{
53+ DRCO_DCCI_SINGLE_CACHE_LINE(queue);
54+ if (queue->head >= queue->size) {
55+ return nullptr;
56+ }
57+ __gm__ DrcoDeviceTask* elem = &queue->dynFuncDataListList[queue->head];
58+ DRCO_DCCI_SINGLE_CACHE_LINE(elem);
59+ if (elem->dynFuncDataList == nullptr) {
60+ return nullptr;
61+ }
62+ return elem;
63+}
64+ 
65+INLINE uint32_t DrcoAtomicAddToSigned(__gm__ int32_t* ptr, int32_t value)
66+{
67+ return static_cast<uint32_t>(atomicAdd(ptr, value));
68+}
69+ 
70+INLINE uint32_t DrcoAtomicAddTo(__gm__ uint32_t* ptr, uint32_t value)
71+{
72+ return static_cast<uint32_t>(atomicAdd(ptr, value));
73+}
74+ 
75+INLINE uint32_t DrcoAtomicCasTo(__gm__ uint32_t* ptr, uint32_t compare, uint32_t value)
76+{
77+ return static_cast<uint32_t>(atomicCAS(ptr, compare, value));
78+}
79+ 
80+INLINE uint32_t DrcoAtomicExchTo(__gm__ uint32_t* ptr, uint32_t value)
81+{
82+ return static_cast<uint32_t>(atomicExch(ptr, value));
83+}
84+ 
85+INLINE void DrcoLocalReadyQueuePushTask(__gm__ DrcoLocalReadyQueue* queue, uint32_t readyTask)
86+{
87+ uint32_t tail = DrcoAtomicAddTo(&queue->tail, 1);
88+ DrcoAtomicExchTo(&queue->taskList[tail], DRCO_ENCODE_TASK(readyTask));
89+}
90+ 
91+INLINE uint32_t DrcoLocalReadyQueueGetFirstTask(__gm__ DrcoLocalReadyQueue* queue)
92+{
93+ DRCO_DCCI_SINGLE_CACHE_LINE(queue);
94+ uint32_t head = queue->head;
95+ uint32_t tail = queue->tail;
96+ if (head >= tail) {
97+ return static_cast<uint32_t>(AICORE_TASK_NO_INCOME);
98+ }
99+ uint32_t headPrev = DrcoAtomicCasTo(&queue->head, head, head + 1);
100+ if (headPrev != head) {
101+ return static_cast<uint32_t>(AICORE_TASK_FETCH_CONFLICT);
102+ }
103+ uint32_t taskId = DrcoAtomicAddTo(&queue->taskList[headPrev], 0);
104+ while (taskId == 0) {
105+ taskId = DrcoAtomicAddTo(&queue->taskList[headPrev], 0);
106+ }
107+ return DRCO_DECODE_TASK(taskId);
108+}
109+ 
110+INLINE uint32_t DrcoPerCorePendingQueueGetFirstTask(__gm__ npu::tile_fwk::PerCorePendingQueue* queue)
111+{
112+ DRCO_DCCI_SINGLE_CACHE_LINE(&queue->size);
113+ uint32_t head = queue->head;
114+ if (head >= queue->size) {
115+ return static_cast<uint32_t>(AICORE_TASK_NO_INCOME);
116+ }
117+ DRCO_DCCI_SINGLE_CACHE_LINE(&queue->taskList[head]);
118+ uint32_t taskId = queue->taskList[head];
119+ queue->head = head + 1;
120+ return taskId;
121+}
122+ 
123+INLINE int DrcoGlobalReadyQueueTryPushLastTask(__gm__ DrcoGlobalReadyQueue* queue, uint32_t readyTask)
124+{
125+ __gm__ uint32_t* tailPtr = &queue->tail;
126+ uint32_t tail = DrcoAtomicAddTo(tailPtr, 0);
127+ uint32_t tailPrev = DrcoAtomicCasTo(&queue->tail, tail, tail + 1);
128+ if (tailPrev == tail) {
129+ DrcoAtomicExchTo(&queue->taskList[tailPrev], DRCO_ENCODE_TASK(readyTask));
130+ return 0;
131+ }
132+ return 1;
133+}
134+ 
135+INLINE void DrcoGlobalReadyQueuePushLastTask(__gm__ DrcoGlobalReadyQueue* queue, uint32_t readyTask)
136+{
137+ int result = DrcoGlobalReadyQueueTryPushLastTask(queue, readyTask);
138+ while (result == 1) {
139+ result = DrcoGlobalReadyQueueTryPushLastTask(queue, readyTask);
140+ }
141+}
142+ 
143+INLINE uint32_t DrcoGlobalReadyQueueTryGetFirstTask(__gm__ DrcoGlobalReadyQueue* queue)
144+{
145+ DRCO_DCCI_SINGLE_CACHE_LINE(queue);
146+ volatile __gm__ uint32_t* headAddr = &queue->head;
147+ volatile __gm__ uint32_t* tailAddr = &queue->tail;
148+ uint32_t head = *headAddr;
149+ uint32_t tail = *tailAddr;
150+ if (head < tail) {
151+ uint32_t headPrev = DrcoAtomicCasTo(&queue->head, head, head + 1);
152+ if (headPrev == head) {
153+ uint32_t taskId = DrcoAtomicAddTo(&queue->taskList[headPrev], 0);
154+ while (taskId == 0) {
155+ taskId = DrcoAtomicAddTo(&queue->taskList[headPrev], 0);
156+ }
157+ return DRCO_DECODE_TASK(taskId);
158+ }
159+ return static_cast<uint32_t>(AICORE_TASK_FETCH_CONFLICT);
160+ } else if (head < queue->size) {
161+ return static_cast<uint32_t>(AICORE_TASK_NO_INCOME);
162+ }
163+ return static_cast<uint32_t>(AICORE_TASK_ALL_FINISH);
164+}
165+ 
166+INLINE uint32_t DrcoGlobalReadyQueueGetFirstTask(__gm__ DrcoGlobalReadyQueue* queue)
167+{
168+ uint32_t taskId = static_cast<uint32_t>(AICORE_TASK_FETCH_CONFLICT);
169+ while (taskId == static_cast<uint32_t>(AICORE_TASK_FETCH_CONFLICT)) {
170+ taskId = DrcoGlobalReadyQueueTryGetFirstTask(queue);
171+ if (taskId == static_cast<uint32_t>(AICORE_TASK_ALL_FINISH)) {
172+ break;
173+ }
174+ }
175+ return taskId;
176+}
177+ 
178+INLINE __gm__ DrcoGlobalReadyQueue* GetDrcoGlobalReadyQueue(__gm__ npu::tile_fwk::DrcoRootFuncList* rootFuncList,
179+ uint32_t readyQueueCoreType)
180+{
181+ if (readyQueueCoreType == static_cast<uint32_t>(npu::tile_fwk::CoreType::AIV)) {
182+ return rootFuncList->globalReadyQueueList[npu::tile_fwk::DRCO_QUEUE_AIV].ptr;
183+ } else if (readyQueueCoreType == static_cast<uint32_t>(npu::tile_fwk::CoreType::AIC)) {
184+ return rootFuncList->globalReadyQueueList[npu::tile_fwk::DRCO_QUEUE_AIC].ptr;
185+ }
186+ return nullptr;
187+}
188+ 
189+INLINE __gm__ DrcoLocalReadyQueue* GetDrcoLocalReadyQueue(__gm__ npu::tile_fwk::DrcoRootFuncList* rootFuncList,
190+ uint32_t readyQueueCoreType)
191+{
192+ if (readyQueueCoreType < npu::tile_fwk::NUM_CORE_TYPES) {
193+ return rootFuncList->localReadyQueueArray[readyQueueCoreType][0];
194+ }
195+ return nullptr;
196+}
197+ 
198+struct DrcoDynFuncDataListPush {
199+ INLINE static void Push(__gm__ npu::tile_fwk::DrcoRootFuncList* rootFuncList, uint32_t succTaskId,
200+ uint32_t succCoreType)
201+ {
202+ __gm__ DrcoLocalReadyQueue* localQueue = GetDrcoLocalReadyQueue(rootFuncList, succCoreType);
203+ if (localQueue != nullptr) {
204+ DRCO_DCCI_SINGLE_CACHE_LINE(localQueue);
205+ if (localQueue->tail < localQueue->size) {
206+ DrcoLocalReadyQueuePushTask(localQueue, succTaskId);
207+ return;
208+ }
209+ }
210+ __gm__ DrcoGlobalReadyQueue* globalQueue = GetDrcoGlobalReadyQueue(rootFuncList, succCoreType);
211+ if (globalQueue != nullptr) {
212+ DrcoGlobalReadyQueuePushLastTask(globalQueue, succTaskId);
213+ }
214+ }
215+};
216+ 
217+template <typename GlobalReadyQueueHandler>
218+INLINE void ExecDrcoResolve(ExecuteContext* ctx, __gm__ npu::tile_fwk::DrcoRootFuncList* rootFuncList, uint32_t taskId)
219+{
220+ constexpr uint32_t HUB_STACK_SIZE = 64;
221+ uint32_t hubStack[HUB_STACK_SIZE];
222+ int32_t hubStackTop = -1;
223+ hubStack[++hubStackTop] = taskId;
224+ 
225+ while (hubStackTop >= 0) {
226+ uint32_t curTaskId = hubStack[hubStackTop--];
227+ uint32_t funcIdx = npu::tile_fwk::FuncID(curTaskId);
228+ auto funcData = &ctx->cachedDevTasks[ctx->curLeafTaskParallelIdx].funcDataList[funcIdx];
229+ 
230+ __gm__ npu::tile_fwk::DrcoRootFuncData* rootFuncData = &funcData->drcoRootFuncData;
231+ __gm__ npu::tile_fwk::DevAscendFunctionOperationSuccInfo* succInfoList = rootFuncData->succInfoList;
232+ __gm__ int32_t* succStaticList = rootFuncData->succStaticList;
233+ __gm__ npu::tile_fwk::DevAscendFunctionDuppedStitchNode** succStitchList = rootFuncData->succStitchList;
234+ __gm__ int32_t* predCount = rootFuncData->predCount;
235+ 
236+ uint32_t operationIndex = npu::tile_fwk::TaskID(curTaskId);
237+ volatile __gm__ npu::tile_fwk::DevAscendFunctionOperationSuccInfo* succInfo = &succInfoList[operationIndex];
238+ uint16_t staticIndex = succInfo->staticIndex;
239+ uint16_t staticSize = succInfo->staticSize;
240+ uint32_t stitchIndex = succInfo->stitchIndex;
241+ 
242+ for (uint16_t i = staticIndex; i < staticIndex + staticSize; i++) {
243+ uint32_t succOpIdx = succStaticList[i];
244+ int32_t old = DrcoAtomicAddToSigned(&predCount[succOpIdx], -1);
245+ if (old == 1) {
246+ uint32_t succTaskId = npu::tile_fwk::MakeTaskID(funcIdx, succOpIdx);
247+ int cceBinaryIndex = funcData->cceBinaryIndexList[succOpIdx];
248+ uint32_t
249+ succCoreType = ctx->cachedDevTasks[ctx->curLeafTaskParallelIdx].cceBinary[cceBinaryIndex].coreType;
250+ if (succCoreType == static_cast<uint32_t>(npu::tile_fwk::CoreType::HUB)) {
251+ if (hubStackTop + 1 < HUB_STACK_SIZE) {
252+ hubStack[++hubStackTop] = succTaskId;
253+ }
254+ } else if (succCoreType != static_cast<uint32_t>(npu::tile_fwk::CoreType::HUB_MIX)) {
255+ GlobalReadyQueueHandler::Push(rootFuncList, succTaskId, succCoreType);
256+ }
257+ }
258+ }
259+ 
260+ if (stitchIndex != 0) {
261+ for (__gm__ npu::tile_fwk::DevAscendFunctionDuppedStitchNode* node = succStitchList[stitchIndex];
262+ node != nullptr; node = node->nodeNext) {
263+ for (uint32_t i = 0; i < node->nodeSize; i++) {
264+ uint32_t succTaskId = node->nodeTaskList[i];
265+ uint32_t succFuncId = npu::tile_fwk::FuncID(succTaskId);
266+ uint32_t succOpIdx = npu::tile_fwk::TaskID(succTaskId);
267+ __gm__ npu::tile_fwk::DrcoRootFuncData*
268+ succRootFuncData = &ctx->cachedDevTasks[ctx->curLeafTaskParallelIdx]
269+ .funcDataList[succFuncId]
270+ .drcoRootFuncData;
271+ int32_t old = DrcoAtomicAddToSigned(&succRootFuncData->predCount[succOpIdx], -1);
272+ if (old == 1) {
273+ int cceBinaryIndex = ctx->cachedDevTasks[ctx->curLeafTaskParallelIdx]
274+ .funcDataList[succFuncId]
275+ .cceBinaryIndexList[succOpIdx];
276+ uint32_t succCoreType = ctx->cachedDevTasks[ctx->curLeafTaskParallelIdx]
277+ .cceBinary[cceBinaryIndex]
278+ .coreType;
279+ if (succCoreType == static_cast<uint32_t>(npu::tile_fwk::CoreType::HUB)) {
280+ if (hubStackTop + 1 < HUB_STACK_SIZE) {
281+ hubStack[++hubStackTop] = succTaskId;
282+ }
283+ } else if (succCoreType != static_cast<uint32_t>(npu::tile_fwk::CoreType::HUB_MIX)) {
284+ GlobalReadyQueueHandler::Push(rootFuncList, succTaskId, succCoreType);
285+ }
286+ }
287+ }
288+ }
289+ }
290+ }
291+}
292+ 
293+INLINE uint32_t DrcoDynFuncDataListGetFirstTask(__gm__ npu::tile_fwk::DrcoRootFuncList* rootFuncList)
294+{
295+ uint64_t t0 = get_sys_cnt();
296+ while (true) {
297+ if (get_sys_cnt() - t0 > AICORE_LEAF_TASK_RUN_TIMEOUT) {
298+ Trap();
299+ }
300+ __gm__ DrcoLocalReadyQueue* localQueue = GetDrcoLocalReadyQueue(
301+ rootFuncList, static_cast<uint32_t>(npu::tile_fwk::drcoCoreType));
302+ if (localQueue != nullptr) {
303+ DRCO_DCCI_SINGLE_CACHE_LINE(localQueue);
304+ uint32_t taskId = static_cast<uint32_t>(AICORE_TASK_FETCH_CONFLICT);
305+ while (taskId == static_cast<uint32_t>(AICORE_TASK_FETCH_CONFLICT)) {
306+ taskId = DrcoLocalReadyQueueGetFirstTask(localQueue);
307+ }
308+ if (taskId != static_cast<uint32_t>(AICORE_TASK_NO_INCOME)) {
309+ return taskId;
310+ }
311+ }
312+ 
313+ __gm__ DrcoGlobalReadyQueue* globalReadyQueue = GetDrcoGlobalReadyQueue(
314+ rootFuncList, static_cast<uint32_t>(npu::tile_fwk::drcoCoreType));
315+ if (globalReadyQueue != nullptr) {
316+ DRCO_DCCI_SINGLE_CACHE_LINE(globalReadyQueue);
317+ uint32_t taskId = DrcoGlobalReadyQueueGetFirstTask(globalReadyQueue);
318+ if (taskId != static_cast<uint32_t>(AICORE_TASK_NO_INCOME) &&
319+ taskId != static_cast<uint32_t>(AICORE_TASK_ALL_FINISH)) {
320+ return taskId;
321+ }
322+ }
323+ 
324+ DRCO_DCCI_SINGLE_CACHE_LINE(rootFuncList->executedTaskCount);
325+ if (*rootFuncList->executedTaskCount >= rootFuncList->totalTaskCount) {
326+ return static_cast<uint32_t>(AICORE_TASK_ALL_FINISH);
327+ }
328+ }
329+}
330+ 
331+INLINE void KernelEntryDrco(int64_t ffts_addr, int64_t inputs, int64_t outputs, int64_t workspace, int64_t tilingdata,
332+ int64_t cfgdata)
333+{
334+ uint64_t start = get_sys_cnt();
335+ UNUSED(ffts_addr);
336+ UNUSED(inputs);
337+ UNUSED(outputs);
338+ UNUSED(workspace);
339+ UNUSED(tilingdata);
340+#if defined(__AIV__) && defined(__MIX__)
341+ int32_t blockIdx = get_block_idx() * get_subblockdim() + get_subblockid() + get_block_num();
342+#else
343+ int32_t blockIdx = get_block_idx();
344+#endif
345+ auto devArgs = (DeviceArgs*)cfgdata;
346+ __gm__ KernelArgs* args = (__gm__ KernelArgs*)(devArgs->sharedBuffer + blockIdx * SHARED_BUFFER_SIZE);
347+ __gm__ Metrics* metric = (__gm__ Metrics*)(args->shakeBuffer[SHAK_BUF_DFX_DATA_INDEX]);
348+ ExecuteContext ctx = {};
349+ ctx.args = args;
350+ ctx.blockIdx = blockIdx;
351+ __gm__ DevDfxArgs* devDfxAddr = (__gm__ DevDfxArgs*)devArgs->devDfxArgAddr;
352+ ctx.aicoreDevTaskMetric.devTaskMetricEnable = devDfxAddr->isOpenPerfTrace != 0;
353+ uint8_t aicoreLogLevel = static_cast<uint8_t>(AicoreLogLevel::NONE);
354+#if ENABLE_AICORE_PRINT
355+ if (devDfxAddr->logLevel >= 0) {
356+ aicoreLogLevel = static_cast<uint8_t>(devDfxAddr->logLevel);
357+ }
358+#endif
359+ if (ctx.aicoreDevTaskMetric.devTaskMetricEnable && metric->turnNum < MAX_ROUND_NUM) {
360+ uint64_t round = metric->turnNum;
361+ ctx.aicoreDevTaskMetric.devTaskMetric = &(metric->aicoreDevTaskInfo[round]);
362+ PerfTraceRecord(INVALID_DEV_TASK_ID, ctx.aicoreDevTaskMetric.devTaskMetric, PERF_TRACE_CORE_BEGIN, start);
363+ }
364+ 
365+ SetStatus(args, STAGE_HANDSHAKE_START);
366+ HandshakeClient(args->shakeBuffer);
367+ SetStatus(args, STAGE_HANDSHAKE_END);
368+ set_mask_norm();
369+ uint8_t lastMixResourceType = static_cast<uint8_t>(MixResourceType::MIX_UNKNOWN);
370+ 
371+ PerfTraceRecord(INVALID_DEV_TASK_ID, ctx.aicoreDevTaskMetric.devTaskMetric, PERF_TRACE_CORE_INIT);
372+ 
373+ InitCtx(&ctx, metric, nullptr, aicoreLogLevel);
374+ 
375+ __gm__ npu::tile_fwk::RuntimeDataRingBufferHeadData*
376+ runtimeDataRingBufferHeadData = (__gm__ npu::tile_fwk::RuntimeDataRingBufferHeadData*)
377+ devArgs->runtimeDataRingBufferAddr;
378+ DRCO_DCCI_SINGLE_CACHE_LINE(runtimeDataRingBufferHeadData);
379+ __gm__ npu::tile_fwk::DevStartArgsBase* base = npu::tile_fwk::RuntimeDataRingBufferHeadData::GetRuntimeDataCurrent(
380+ runtimeDataRingBufferHeadData);
381+ DRCO_DCCI_SINGLE_CACHE_LINE(base);
382+ DRCO_DCCI_SINGLE_CACHE_LINE(&base->drcoDeviceTaskReadyQueue);
383+ __gm__ DrcoDeviceTaskReadyQueue* deviceTaskReadyQueue = base->drcoDeviceTaskReadyQueue;
384+ 
385+ AICORE_TIMEOUT_CHECK_BEGIN(t0, loop_count);
386+ while (true) {
387+ AICORE_TIMEOUT_CHECK_RETURN_VOID(t0, loop_count, AICORE_LEAF_TASK_RUN_TIMEOUT, STAGE_RUN_LEAFTASK_TIMEOUT);
388+ if (deviceTaskReadyQueue == nullptr) {
389+ DRCO_DCCI_SINGLE_CACHE_LINE(runtimeDataRingBufferHeadData);
390+ base = npu::tile_fwk::RuntimeDataRingBufferHeadData::GetRuntimeDataCurrent(runtimeDataRingBufferHeadData);
391+ DRCO_DCCI_SINGLE_CACHE_LINE(base);
392+ DRCO_DCCI_SINGLE_CACHE_LINE(&base->drcoDeviceTaskReadyQueue);
393+ deviceTaskReadyQueue = base->drcoDeviceTaskReadyQueue;
394+ if (deviceTaskReadyQueue == nullptr) {
395+ DrcoBusyBackOff();
396+ continue;
397+ }
398+ }
399+ 
400+ __gm__ DrcoDeviceTask* deviceTask = GetCurrentDeviceTask(deviceTaskReadyQueue);
401+ if (deviceTask == nullptr) {
402+ DRCO_DCCI_SINGLE_CACHE_LINE(deviceTaskReadyQueue);
403+ if (deviceTaskReadyQueue->head < deviceTaskReadyQueue->size) {
404+ __gm__ DrcoDeviceTask* elem = &deviceTaskReadyQueue->dynFuncDataListList[deviceTaskReadyQueue->head];
405+ DRCO_DCCI_SINGLE_CACHE_LINE(elem);
406+ if (elem->dynFuncDataList == nullptr) {
407+ break;
408+ }
409+ }
410+ DrcoBusyBackOff();
411+ continue;
412+ }
413+ 
414+ __gm__ DynFuncHeader* deviceTaskDynFuncDataList = deviceTask->dynFuncDataList;
415+ __gm__ npu::tile_fwk::DrcoRootFuncList* rootFuncList = deviceTask->drcoRootFuncList;
416+ 
417+ UpdateCacheDevTask(&ctx, ctx.curLeafTaskParallelIdx, (int64_t)deviceTaskDynFuncDataList);
418+ 
419+ __gm__ npu::tile_fwk::PerCorePendingQueue* myPerCoreQueue = rootFuncList->perCorePendingQueueArray[blockIdx];
420+ DRCO_DCCI_SINGLE_CACHE_LINE(myPerCoreQueue);
421+ DRCO_DCCI_SINGLE_CACHE_LINE(&myPerCoreQueue->size);
422+ ctx.profLevel = 0;
423+ 
424+ if (rootFuncList->totalTaskCount == 0) {
425+ uint32_t oldHead = deviceTaskReadyQueue->head;
426+ DrcoAtomicCasTo(&deviceTaskReadyQueue->head, oldHead, oldHead + 1);
427+ continue;
428+ }
429+ 
430+ while (myPerCoreQueue->size > myPerCoreQueue->head) {
431+ uint32_t taskId = DrcoPerCorePendingQueueGetFirstTask(myPerCoreQueue);
432+ if (taskId == static_cast<uint32_t>(AICORE_TASK_NO_INCOME)) {
433+ break;
434+ }
435+ ExecCoreFunctionKernel(&ctx, taskId, lastMixResourceType);
436+#ifdef __HAS_SUB_FUNC__
437+ ExecDrcoResolve<DrcoDynFuncDataListPush>(&ctx, rootFuncList, taskId);
438+#endif
439+ uint32_t oldCount = DrcoAtomicAddTo(rootFuncList->executedTaskCount, 1);
440+ if (oldCount == (rootFuncList->totalTaskCount - 1)) {
441+ uint32_t oldHead = deviceTaskReadyQueue->head;
442+ DrcoAtomicCasTo(&deviceTaskReadyQueue->head, oldHead, oldHead + 1);
443+ }
444+ }
445+ 
446+ uint32_t taskId = DrcoDynFuncDataListGetFirstTask(rootFuncList);
447+ while (taskId != static_cast<uint32_t>(AICORE_TASK_ALL_FINISH)) {
448+ if ((taskId & AICORE_FIN_MASK) == 0) {
449+ ExecCoreFunctionKernel(&ctx, taskId, lastMixResourceType);
450+#ifdef __HAS_SUB_FUNC__
451+ ExecDrcoResolve<DrcoDynFuncDataListPush>(&ctx, rootFuncList, taskId);
452+#endif
453+ uint32_t oldCount = DrcoAtomicAddTo(rootFuncList->executedTaskCount, 1);
454+ if (oldCount == (rootFuncList->totalTaskCount - 1)) {
455+ uint32_t oldHead = deviceTaskReadyQueue->head;
456+ DrcoAtomicCasTo(&deviceTaskReadyQueue->head, oldHead, oldHead + 1);
457+ }
458+ }
459+ taskId = DrcoDynFuncDataListGetFirstTask(rootFuncList);
460+ }
461+ 
462+ DRCO_DCCI_SINGLE_CACHE_LINE(rootFuncList->executedTaskCount);
463+ while (*rootFuncList->executedTaskCount < rootFuncList->totalTaskCount) {
464+ DRCO_DCCI_SINGLE_CACHE_LINE(rootFuncList->executedTaskCount);
465+ }
466+ }
467+ if (blockIdx == 0) {
468+ DRCO_DCCI_SINGLE_CACHE_LINE(runtimeDataRingBufferHeadData);
469+ uint64_t finished = runtimeDataRingBufferHeadData->indexFinished.value + 1;
470+ runtimeDataRingBufferHeadData->indexFinished.value = finished;
471+ DRCO_DCCI_SINGLE_CACHE_LINE(runtimeDataRingBufferHeadData);
472+ }
473+ 
474+ FlushMetricStatistic(args);
475+ return;
476+}
477+ 
478+#endif
@@ -27,6 +27,9 @@ const uint64_t AICORE_TASK_INIT = 0xFFFFFFFF;
27const uint64_t AICORE_TASK_STOP = 0xF0000001;27const uint64_t AICORE_TASK_STOP = 0xF0000001;
28const uint64_t AICORE_FUNC_STOP = 0xF0000002;28const uint64_t AICORE_FUNC_STOP = 0xF0000002;
29const uint64_t AICORE_TASK_ABNORMAL_STOP = 0xF0000004;29const uint64_t AICORE_TASK_ABNORMAL_STOP = 0xF0000004;
30+const uint64_t AICORE_TASK_FETCH_CONFLICT = 0xF0000008;
31+const uint64_t AICORE_TASK_NO_INCOME = 0xF0000009;
32+const uint64_t AICORE_TASK_ALL_FINISH = 0xF000000a;
30const uint64_t AICORE_FIN_MASK = 0x80000000;33const uint64_t AICORE_FIN_MASK = 0x80000000;
31const uint64_t AICORE_TASK_MAX = 0x70000000;34const uint64_t AICORE_TASK_MAX = 0x70000000;
32 35 
@@ -130,6 +133,7 @@ struct DeviceRuntimeOffset {
130 uint64_t startArgsOffset{0};133 uint64_t startArgsOffset{0};
131 uint64_t taskCtrlPoolOffset{0};134 uint64_t taskCtrlPoolOffset{0};
132 uint64_t taskQueueOffset{0};135 uint64_t taskQueueOffset{0};
136+ uint64_t deviceTaskReadyQueueOffset{0};
133 uint64_t generalOffset{0};137 uint64_t generalOffset{0};
134 uint64_t stitchPoolOffset{0};138 uint64_t stitchPoolOffset{0};
135 uint64_t size{0};139 uint64_t size{0};
@@ -172,6 +176,7 @@ struct DeviceArgs {
172 bool enableVFFusion = false;176 bool enableVFFusion = false;
173 bool enableEslModel = false;177 bool enableEslModel = false;
174 bool hasAicpuTask = false;178 bool hasAicpuTask = false;
179+ bool enableAicoreResolve = false; // runtime switch, driven by env ENABLE_AICORE_RESOLVE=true
175 ArchInfo archInfo{ArchInfo::DAV_2201};180 ArchInfo archInfo{ArchInfo::DAV_2201};
176 ToSubMachineConfig toSubMachineConfig;181 ToSubMachineConfig toSubMachineConfig;
177};182};
@@ -27,6 +27,8 @@ namespace npu::tile_fwk {
27 27 
28constexpr uint32_t HCCL_GROUP_NUM = 2;28constexpr uint32_t HCCL_GROUP_NUM = 2;
29 29 
30+enum class CoreType { AIV = 0, AIC = 1, MIX = 2, AICPU = 3, HUB = 4, GMATOMIC = 5, HUB_MIX = 6, INVALID = 20 };
31+ 
30struct CoreFuncParam {32struct CoreFuncParam {
31 __gm__ DynFuncData* funcData;33 __gm__ DynFuncData* funcData;
32 __gm__ uint64_t* opAttrs;34 __gm__ uint64_t* opAttrs;
@@ -47,4 +47,8 @@
47#define UNUSED(n) (void)(n)47#define UNUSED(n) (void)(n)
48#endif48#endif
49 49 
50+#ifndef ENABLE_AICORE_RESOLVE
51+#define ENABLE_AICORE_RESOLVE 0
52+#endif
53+ 
50#endif54#endif
@@ -24,6 +24,14 @@
24namespace npu::tile_fwk {24namespace npu::tile_fwk {
25 25 
26struct DevStartArgsBase;26struct DevStartArgsBase;
27+ 
28+struct DrcoRootFuncData {
29+ __gm__ int32_t* predCount;
30+ __gm__ int32_t* succStaticList;
31+ __gm__ DevAscendFunctionDuppedStitchNode** succStitchList;
32+ __gm__ DevAscendFunctionOperationSuccInfo* succInfoList;
33+};
34+ 
27struct DynFuncData {35struct DynFuncData {
28 uint64_t exprNum; // static36 uint64_t exprNum; // static
29 __gm__ uint64_t* opAttrs; // static37 __gm__ uint64_t* opAttrs; // static
@@ -39,6 +47,7 @@ struct DynFuncData {
39 uint64_t stackWorkSpaceSize;47 uint64_t stackWorkSpaceSize;
40 __gm__ DevStartArgsBase* startArgs; // should be removed as it is global data48 __gm__ DevStartArgsBase* startArgs; // should be removed as it is global data
41 __gm__ int* cceBinaryIndexList;49 __gm__ int* cceBinaryIndexList;
50+ DrcoRootFuncData drcoRootFuncData;
42};51};
43 52 
44struct DynFuncBin {53struct DynFuncBin {
@@ -65,13 +74,6 @@ struct DynFuncHeader {
65 INLINE DynFuncData& At(int index) { return (reinterpret_cast<DynFuncData*>(this + 1))[index]; }74 INLINE DynFuncData& At(int index) { return (reinterpret_cast<DynFuncData*>(this + 1))[index]; }
66};75};
67 76 
68-struct DrcoRootFuncData {
69- __gm__ int32_t* predCount;
70- __gm__ int32_t* succStaticList;
71- __gm__ DevAscendFunctionDuppedStitchNode** succStitchList;
72- __gm__ DevAscendFunctionOperationSuccInfo* succInfoList;
73-};
74- 
75constexpr uint32_t DRCO_QUEUE_AIV = 0;77constexpr uint32_t DRCO_QUEUE_AIV = 0;
76constexpr uint32_t DRCO_QUEUE_AIC = 1;78constexpr uint32_t DRCO_QUEUE_AIC = 1;
77constexpr uint32_t DRCO_QUEUE_M1V = 2;79constexpr uint32_t DRCO_QUEUE_M1V = 2;
@@ -103,9 +105,10 @@ struct DrcoDeviceTaskReadyQueue {
103 head = 0;105 head = 0;
104 size = 0;106 size = 0;
105 }107 }
106- void Append(DynFuncHeader* dynFuncDataList)108+ void Append(DynFuncHeader* dynFuncDataList, DrcoRootFuncList* rootFuncList)
107 {109 {
108 dynFuncDataListList[size].dynFuncDataList = dynFuncDataList;110 dynFuncDataListList[size].dynFuncDataList = dynFuncDataList;
111+ dynFuncDataListList[size].drcoRootFuncList = rootFuncList;
109 size++;112 size++;
110 }113 }
111#endif114#endif
@@ -42,8 +42,12 @@ __always_inline uint64_t GetCycles()
42#endif42#endif
43}43}
44 44 
45-__always_inline void WaitAicoreStart([[maybe_unused]] npu::tile_fwk::DevStartArgsBase* startArgs)45+__always_inline void WaitAicoreStart(npu::tile_fwk::DevStartArgsBase* startArgs)
46{46{
47+#if ENABLE_AICORE_RESOLVE
48+ (void)startArgs;
49+ return; // aicore resolve: 依赖由AICore在设备端自己解析,无需等待AICPU的syncFlag
50+#endif
47#if defined(__aarch64__) && defined(__DEVICE__)51#if defined(__aarch64__) && defined(__DEVICE__)
48 uint64_t start = GetCycles();52 uint64_t start = GetCycles();
49 while (__atomic_load_n(&startArgs->syncFlag, __ATOMIC_ACQUIRE) != 1) {53 while (__atomic_load_n(&startArgs->syncFlag, __ATOMIC_ACQUIRE) != 1) {
@@ -51,6 +55,8 @@ __always_inline void WaitAicoreStart([[maybe_unused]] npu::tile_fwk::DevStartArg
51 break;55 break;
52 }56 }
53 }57 }
58+#else
59+ (void)startArgs;
54#endif60#endif
55}61}
56 62 
@@ -33,6 +33,13 @@ namespace npu::tile_fwk {
33 33 
34// VIRTUAL_PURE & VIRTUAL_MIX are special core type ,just used by machine34// VIRTUAL_PURE & VIRTUAL_MIX are special core type ,just used by machine
35enum class MachineType { AIV = 0, AIC = 1, MIX = 2, AICPU = 3, HUB = 4, VIRTUAL_PURE = 5, VIRTUAL_MIX = 6 };35enum class MachineType { AIV = 0, AIC = 1, MIX = 2, AICPU = 3, HUB = 4, VIRTUAL_PURE = 5, VIRTUAL_MIX = 6 };
36+ 
37+constexpr uint64_t HUB_MIX_DUMMY_HASH = 0xFFFFFFFFFFFFFFFEULL;
38+ 
39+inline bool IsHubType(int coreType)
40+{
41+ return coreType == static_cast<int>(CoreType::HUB) || coreType == static_cast<int>(CoreType::HUB_MIX);
42+}
36#pragma pack(1)43#pragma pack(1)
37struct CoreFunctionTopo {44struct CoreFunctionTopo {
38 uint64_t coreType; // aic=0 aiv=1 aicpu=245 uint64_t coreType; // aic=0 aiv=1 aicpu=2
@@ -30,6 +30,7 @@
30#include "tilefwk/error.h"30#include "tilefwk/error.h"
31#include "tilefwk/symbolic_scalar.h"31#include "tilefwk/symbolic_scalar.h"
32#include "core/bimap.h"32#include "core/bimap.h"
33+#include "tilefwk/core_func_data.h"
33 34 
34namespace npu::tile_fwk {35namespace npu::tile_fwk {
35 36 
@@ -193,15 +194,6 @@ enum PipeType {
193 PIPE_FIX = 10, // {L0C} ->{L1,UB,L1UB}194 PIPE_FIX = 10, // {L0C} ->{L1,UB,L1UB}
194};195};
195 196 
196-enum class CoreType { AIV = 0, AIC = 1, MIX = 2, AICPU = 3, HUB = 4, GMATOMIC = 5, HUB_MIX = 6, INVALID = 20 };
197- 
198-constexpr uint64_t HUB_MIX_DUMMY_HASH = 0xFFFFFFFFFFFFFFFEULL;
199- 
200-inline bool IsHubType(int coreType)
201-{
202- return coreType == static_cast<int>(CoreType::HUB) || coreType == static_cast<int>(CoreType::HUB_MIX);
203-}
204- 
205template <typename T>197template <typename T>
206inline std::string IntVecToStr(const std::vector<T>& shape)198inline std::string IntVecToStr(const std::vector<T>& shape)
207{199{
@@ -479,6 +471,17 @@ inline bool IsPtoDataDumpEnabled()
479 return result;471 return result;
480}472}
481 473 
474+// 判断环境变量 ENABLE_AICORE_RESOLVE 是否为 true
475+inline bool IsAicoreResolveEnabled()
476+{
477+ static const bool result = []() {
478+ std::string value = GetEnvVar("ENABLE_AICORE_RESOLVE", true, true);
479+ return (value == "true");
480+ }();
481+ 
482+ return result;
483+}
484+ 
482// 向上取整除法485// 向上取整除法
483inline int CeilDiv(int a, int b)486inline int CeilDiv(int a, int b)
484{487{
@@ -22,6 +22,7 @@
22#include <vector>22#include <vector>
23#include "codegen/utils/parallel_execute.h"23#include "codegen/utils/parallel_execute.h"
24#include "utils/file_utils.h"24#include "utils/file_utils.h"
25+#include "interface/utils/common.h"
25#include "interface/utils/op_info_manager.h"26#include "interface/utils/op_info_manager.h"
26#include "machine/compile/gen_aicore_code.h"27#include "machine/compile/gen_aicore_code.h"
27#include "machine/host/main_block.h"28#include "machine/host/main_block.h"
@@ -53,6 +54,8 @@ static int CompileCoreMachine(const std::string& objFile, bool isCube, uint64_t
53 config::GetRuntimeOption<int64_t>(CFG_VALID_SHAPE_OPTIMIZE) == 1)) ?54 config::GetRuntimeOption<int64_t>(CFG_VALID_SHAPE_OPTIMIZE) == 1)) ?
54 "-D__ENABLE_MAIN_BLOCK" :55 "-D__ENABLE_MAIN_BLOCK" :
55 "";56 "";
57+ const std::string enableAicoreResolve = IsAicoreResolveEnabled() ? "-DENABLE_AICORE_RESOLVE=1" :
58+ "-DENABLE_AICORE_RESOLVE=0";
56 std::string ccecCmd;59 std::string ccecCmd;
57 ccecCmd.resize(CMD_SIZE_2K);60 ccecCmd.resize(CMD_SIZE_2K);
58 std::string includePath = GetPyptoLibPath() + "/../include/tile_fwk";61 std::string includePath = GetPyptoLibPath() + "/../include/tile_fwk";
@@ -72,6 +75,7 @@ static int CompileCoreMachine(const std::string& objFile, bool isCube, uint64_t
72 "-D__HEAD_FILE__=%s "75 "-D__HEAD_FILE__=%s "
73 "%s "76 "%s "
74 "%s "77 "%s "
78+ "%s "
75 "-I%s/tileop/arch32 "79 "-I%s/tileop/arch32 "
76 "-I%s/ "80 "-I%s/ "
77 "-I%s/include/tileop/arch32 "81 "-I%s/include/tileop/arch32 "
@@ -79,8 +83,9 @@ static int CompileCoreMachine(const std::string& objFile, bool isCube, uint64_t
79 "-o %s %s %s %s",83 "-o %s %s %s %s",
80 BISHENG_PROGRAM_CMD, cc_opt.c_str(), std::to_string(tilingKey).c_str(), opType.c_str(),84 BISHENG_PROGRAM_CMD, cc_opt.c_str(), std::to_string(tilingKey).c_str(), opType.c_str(),
81 funcRawName.c_str(), headFile.c_str(), hasSubFunc.c_str(), coreType.c_str(),85 funcRawName.c_str(), headFile.c_str(), hasSubFunc.c_str(), coreType.c_str(),
82- includePath.c_str(), includePath.c_str(), GetPyptoLibPath().c_str(), GetPyptoLibPath().c_str(),86+ enableAicoreResolve.c_str(), includePath.c_str(), includePath.c_str(),
83- objFile.c_str(), aicoreSrcFile.c_str(), davArch.c_str(), enableMainBlock.c_str());87+ GetPyptoLibPath().c_str(), GetPyptoLibPath().c_str(), objFile.c_str(), aicoreSrcFile.c_str(),
88+ davArch.c_str(), enableMainBlock.c_str());
84 if (ret < 0) {89 if (ret < 0) {
85 MACHINE_LOGE(HostBackEndErr::COMPILE_AICORE_FAILED, "Compile aicore construct cmd failed.");90 MACHINE_LOGE(HostBackEndErr::COMPILE_AICORE_FAILED, "Compile aicore construct cmd failed.");
86 return ret;91 return ret;
@@ -115,6 +115,11 @@ bool TieFwkAicpuPreCompile(std::string& preCompileO, std::string& controlAicpuPa
115 std::string compileCmd = DeviceMahineCompiler + " -Wall -O2 -fPIC -c -std=gnu++17 -fno-common " +115 std::string compileCmd = DeviceMahineCompiler + " -Wall -O2 -fPIC -c -std=gnu++17 -fno-common " +
116 controlAicpuPath + file + " -I" + includePath + " -I" + includePath + "/include/" +116 controlAicpuPath + file + " -I" + includePath + " -I" + includePath + "/include/" +
117 " -I" + GetPyptoLibPath() + "/include/" + " -o " + objFile;117 " -I" + GetPyptoLibPath() + "/include/" + " -o " + objFile;
118+ if (npu::tile_fwk::IsAicoreResolveEnabled()) {
119+ compileCmd += " -DENABLE_AICORE_RESOLVE=1";
120+ } else {
121+ compileCmd += " -DENABLE_AICORE_RESOLVE=0";
122+ }
118 MACHINE_LOGD("PreCompileCmd is %s, file is %s.\n", compileCmd.c_str(), file.c_str());123 MACHINE_LOGD("PreCompileCmd is %s, file is %s.\n", compileCmd.c_str(), file.c_str());
119 int ret = Checkinject(compileCmd.c_str(), compileCmd.size());124 int ret = Checkinject(compileCmd.c_str(), compileCmd.size());
120 if (ret != 0) {125 if (ret != 0) {
@@ -128,8 +128,8 @@ void DeviceExecuteContext::GELaunchRunCached(DevStartArgs* startArgs, PushTaskEn
128 DynDeviceTask* dynTask = reinterpret_cast<DynDeviceTask*>(128 DynDeviceTask* dynTask = reinterpret_cast<DynDeviceTask*>(
129 devProg->ctrlFlowCacheAnchor->deviceTaskCacheList[index].dynTaskBase);129 devProg->ctrlFlowCacheAnchor->deviceTaskCacheList[index].dynTaskBase);
130 devProg->ctrlFlowCacheAnchor->PredCountDataRestore(dynTask);130 devProg->ctrlFlowCacheAnchor->PredCountDataRestore(dynTask);
131- devProg->ctrlFlowCacheAnchor->ReadyQueueDataRestore(dynTask);131+ devProg->ctrlFlowCacheAnchor->ReadyQueueDataRestore(dynTask, devProg->devArgs.nrValidAic);
132- devProg->ctrlFlowCacheAnchor->DieReadyQueueDataRestore(dynTask);132+ devProg->ctrlFlowCacheAnchor->DieReadyQueueDataRestore(dynTask, devProg->devArgs.nrValidAic);
133 devProg->ctrlFlowCacheAnchor->MixTaskDataRestore(dynTask);133 devProg->ctrlFlowCacheAnchor->MixTaskDataRestore(dynTask);
134 taskContext.UpdateReadyTaskNum(dynTask->readyQueueBackup->readyTaskNum);134 taskContext.UpdateReadyTaskNum(dynTask->readyQueueBackup->readyTaskNum);
135 135 
@@ -53,6 +53,7 @@ inline void FillOneDynFuncData(DynFuncData* dyndata, DevAscendFunctionDupped& du
53 dyndata->opAttrSize = src->GetOpAttrSize();53 dyndata->opAttrSize = src->GetOpAttrSize();
54 dyndata->rawTensorAddrSize = src->GetIncastSize() + src->GetOutcastSize();54 dyndata->rawTensorAddrSize = src->GetIncastSize() + src->GetOutcastSize();
55 dyndata->rawTensorDescSize = src->GetRawTensorDescSize();55 dyndata->rawTensorDescSize = src->GetRawTensorDescSize();
56+ dyndata->drcoRootFuncData = {};
56 57 
57 CheckAddrAligned(reinterpret_cast<uint64_t>(dyndata->opAttrs), OP_ATTRS_PRE_NUM,58 CheckAddrAligned(reinterpret_cast<uint64_t>(dyndata->opAttrs), OP_ATTRS_PRE_NUM,
58 "#ctrl.task.pre.dynfunc.process: opAttrs address is not aligned.");59 "#ctrl.task.pre.dynfunc.process: opAttrs address is not aligned.");
@@ -78,6 +79,7 @@ void DeviceTaskContext::InitAllocator(DevAscendProgram* devProg, DeviceWorkspace
78 devProg_ = devProg;79 devProg_ = devProg;
79 workspace_ = &workspace;80 workspace_ = &workspace;
80 startArgs_ = startArgs;81 startArgs_ = startArgs;
82+ enableAicoreResolve_ = devProg->devArgs.enableAicoreResolve;
81}83}
82 84 
83DynDeviceTask* DeviceTaskContext::BuildDeviceTaskData(DeviceStitchContext& stitchContext, uint32_t taskId,85DynDeviceTask* DeviceTaskContext::BuildDeviceTaskData(DeviceStitchContext& stitchContext, uint32_t taskId,
@@ -158,6 +160,10 @@ int DeviceTaskContext::InitReadyQueues(DynDeviceTask* dyntask, DevAscendProgram*
158 queue[i] = q;160 queue[i] = q;
159 dyntask->readyQueue[i] = q;161 dyntask->readyQueue[i] = q;
160 }162 }
163+ 
164+ if (enableAicoreResolve_) {
165+ InitDrcoRootFuncList(dyntask);
166+ }
161 return DEVICE_MACHINE_OK;167 return DEVICE_MACHINE_OK;
162}168}
163 169 
@@ -321,6 +327,13 @@ int DeviceTaskContext::BuildDynFuncData(DynDeviceTask* dyntask, uint32_t taskId,
321 DEV_IF_NONDEVICE { mem_dump::DumpRootMemory(taskId, static_cast<uint32_t>(funcIdx), stitchedList[funcIdx]); }327 DEV_IF_NONDEVICE { mem_dump::DumpRootMemory(taskId, static_cast<uint32_t>(funcIdx), stitchedList[funcIdx]); }
322 dyndata++;328 dyndata++;
323 }329 }
330+ if (enableAicoreResolve_) {
331+ auto* drcoDyndata = &funcHeader->At(0);
332+ for (size_t funcIdx = 0; funcIdx < stitchedSize; ++funcIdx) {
333+ BuildDrcoRootFuncData(drcoDyndata, stitchedList[funcIdx]);
334+ drcoDyndata++;
335+ }
336+ }
324 dynFuncDataSize += headerSize * sizeof(int64_t);337 dynFuncDataSize += headerSize * sizeof(int64_t);
gaoxingwang

if (devProg_->devArgs.enableAicoreResolve) { BuildDrcoRootFuncData(dyndata, stitchedList[funcIdx]); }

    独立个循环 用devProg_->devArgs.enableAicoreResolve 隔离吧 ,避免非aicore解依赖场景频繁判断
likedislike
325 return DEVICE_MACHINE_OK;338 return DEVICE_MACHINE_OK;
326}339}
@@ -553,6 +566,11 @@ int DeviceTaskContext::BuildDeviceTaskDataAndReadyQueue(DynDeviceTask* dyntask,
553 PerfEnd(PERF_EVT_CORE_FUNCDATA);566 PerfEnd(PERF_EVT_CORE_FUNCDATA);
554 DEV_DEBUG("Finish build a new device task");567 DEV_DEBUG("Finish build a new device task");
555 568 
569+ if (enableAicoreResolve_) {
570+ DispatchReadyQueueToCores(dyntask, devProg);
571+ DispatchDieReadyQueueToCores(dyntask, devProg);
572+ }
573+ 
556#ifndef __DEVICE__574#ifndef __DEVICE__
gaoxingwang

函数调用前外边加个开关隔离吧

likedislike
557 DEV_IF_NONDEVICE575 DEV_IF_NONDEVICE
558 {576 {
@@ -47,6 +47,7 @@ private:
47 DevAscendProgram* devProg_{nullptr};47 DevAscendProgram* devProg_{nullptr};
48 DeviceWorkspaceAllocator* workspace_{nullptr};48 DeviceWorkspaceAllocator* workspace_{nullptr};
49 npu::tile_fwk::DevStartArgsBase* startArgs_{nullptr};49 npu::tile_fwk::DevStartArgsBase* startArgs_{nullptr};
50+ bool enableAicoreResolve_{false};
50 51 
51private:52private:
52 int BuildReadyQueue(DynDeviceTask* dyntask, DevAscendProgram* devProg);53 int BuildReadyQueue(DynDeviceTask* dyntask, DevAscendProgram* devProg);
@@ -57,13 +58,17 @@ private:
57 void InitReadyCoreFunctionQueue(ReadyCoreFunctionQueue* q, uint32_t capacity);58 void InitReadyCoreFunctionQueue(ReadyCoreFunctionQueue* q, uint32_t capacity);
58 int InitReadyQueues(DynDeviceTask* dyntask, DevAscendProgram* devProg,59 int InitReadyQueues(DynDeviceTask* dyntask, DevAscendProgram* devProg,
59 ReadyCoreFunctionQueue* queue[READY_QUEUE_SIZE]);60 ReadyCoreFunctionQueue* queue[READY_QUEUE_SIZE]);
61+ void InitDrcoRootFuncList(DynDeviceTask* dyntask);
60 int ProcessZeroPredTask(DynDeviceTask* dyntask, WrapInfoQueue* wrapQueue, bool isNeedWrap);62 int ProcessZeroPredTask(DynDeviceTask* dyntask, WrapInfoQueue* wrapQueue, bool isNeedWrap);
61 void InitDieReadyQueues(DynDeviceTask* dyntask, DevAscendProgram* devProg);63 void InitDieReadyQueues(DynDeviceTask* dyntask, DevAscendProgram* devProg);
64+ void DispatchReadyQueueToCores(DynDeviceTask* dyntask, DevAscendProgram* devProg);
65+ void DispatchDieReadyQueueToCores(DynDeviceTask* dyntask, DevAscendProgram* devProg);
62 void UpdateDeviceTaskQueueInfo(DynDeviceTask* dyntask, ReadyCoreFunctionQueue* aicpuQueue,66 void UpdateDeviceTaskQueueInfo(DynDeviceTask* dyntask, ReadyCoreFunctionQueue* aicpuQueue,
63 ReadyCoreFunctionQueue* aivQueue, ReadyCoreFunctionQueue* aicQueue,67 ReadyCoreFunctionQueue* aivQueue, ReadyCoreFunctionQueue* aicQueue,
64 WrapInfoQueue* wrapQueue);68 WrapInfoQueue* wrapQueue);
65 int BuildDynFuncData(DynDeviceTask* dyntask, uint32_t taskId, DevAscendFunctionDupped* stitchedList,69 int BuildDynFuncData(DynDeviceTask* dyntask, uint32_t taskId, DevAscendFunctionDupped* stitchedList,
66 uint64_t stitchedSize);70 uint64_t stitchedSize);
71+ void BuildDrcoRootFuncData(DynFuncData* dyndata, DevAscendFunctionDupped& stitchedFunc);
67 72 
68 // mix subgraph schedule73 // mix subgraph schedule
69 WrapInfoQueue* AllocWrapQueue(DynDeviceTask* dyntask);74 WrapInfoQueue* AllocWrapQueue(DynDeviceTask* dyntask);
@@ -0,0 +1,141 @@
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 device_task_context_drco.cpp
13+ * \brief AICore dependency resolve (DRCO) helpers of DeviceTaskContext, gated by enableAicoreResolve.
14+ */
15+ 
16+#include "machine/device/dynamic/context/device_task_context.h"
17+ 
18+namespace npu::tile_fwk::dynamic {
19+ 
20+void DeviceTaskContext::InitDrcoRootFuncList(DynDeviceTask* dyntask)
21+{
22+ auto* rootFuncList = reinterpret_cast<npu::tile_fwk::DrcoRootFuncList*>(
23+ ControlFlowAllocateSlab(
24+ devProg_, sizeof(npu::tile_fwk::DrcoRootFuncList),
25+ workspace_->SlabAlloc(sizeof(npu::tile_fwk::DrcoRootFuncList), WsAicpuSlabMemType::DYN_FUNC_DATA))
26+ .ptr);
27+ dyntask->drcoRootFuncList = rootFuncList;
28+ uint32_t queueCapacity = dyntask->devTask.coreFunctionCnt;
29+ uint32_t globalReadyQueueSize = sizeof(npu::tile_fwk::DrcoGlobalReadyQueue) +
30+ queueCapacity * sizeof(npu::tile_fwk::LeafTaskId);
31+ for (size_t i = 0; i < npu::tile_fwk::DRCO_QUEUE_MAX; i++) {
32+ auto* q = workspace_->AllocateDrcoGlobalReadyQueue(globalReadyQueueSize);
33+ new (q) npu::tile_fwk::DrcoGlobalReadyQueue();
34+ rootFuncList->globalReadyQueueList[i].ptr = q;
35+ }
36+ uint32_t perCoreSize = sizeof(npu::tile_fwk::PerCorePendingQueue) +
37+ queueCapacity * sizeof(npu::tile_fwk::LeafTaskId);
38+ for (uint32_t i = 0; i < npu::tile_fwk::MAX_AICORE_NUM_FOR_QUEUE; i++) {
39+ auto* perCoreQueue = workspace_->AllocatePerCorePendingQueue(perCoreSize);
40+ new (perCoreQueue) npu::tile_fwk::PerCorePendingQueue();
41+ rootFuncList->perCorePendingQueueArray[i] = perCoreQueue;
42+ }
43+ uint32_t localSize = sizeof(npu::tile_fwk::DrcoLocalReadyQueue);
44+ localSize += queueCapacity * sizeof(npu::tile_fwk::LeafTaskId);
45+ for (uint32_t ct = 0; ct < npu::tile_fwk::NUM_CORE_TYPES; ct++) {
46+ for (uint32_t i = 0; i < npu::tile_fwk::NUM_LOCAL_GROUPS; i++) {
47+ auto* localQueue = workspace_->AllocateDrcoLocalReadyQueue(localSize);
48+ new (localQueue) npu::tile_fwk::DrcoLocalReadyQueue(queueCapacity);
49+ rootFuncList->localReadyQueueArray[ct][i] = localQueue;
50+ }
51+ }
52+ rootFuncList->totalTaskCount = dyntask->devTask.coreFunctionCnt;
53+ WsAllocation execCountAlloc = ControlFlowAllocateSlab(
54+ devProg_, sizeof(uint32_t), workspace_->SlabAlloc(sizeof(uint32_t), WsAicpuSlabMemType::PRED_COUNT));
55+ uint32_t* execCount = execCountAlloc.As<uint32_t>();
56+ *execCount = 0;
57+ rootFuncList->executedTaskCount = execCount;
58+}
59+ 
60+void DeviceTaskContext::DispatchReadyQueueToCores(DynDeviceTask* dyntask, DevAscendProgram* devProg)
61+{
62+ ReadyCoreFunctionQueue* aivQueue = dyntask->readyQueue[DynDeviceTask::GetReadyQueueIndexByCoreType(CoreType::AIV)];
63+ ReadyCoreFunctionQueue* aicQueue = dyntask->readyQueue[DynDeviceTask::GetReadyQueueIndexByCoreType(CoreType::AIC)];
64+ 
65+ uint32_t nrValidAic = devProg->devArgs.nrValidAic;
66+ uint32_t nrAivCores = 2 * nrValidAic;
67+ 
68+ // perCorePendingQueue: distribute aic tasks to aicore cores (0..nrValidAic-1)
69+ uint32_t aicIdx = 0;
70+ for (const auto* it = aicQueue->begin(); it != aicQueue->end(); ++it) {
71+ uint32_t coreIdx = aicIdx % nrValidAic;
72+ dyntask->drcoRootFuncList->perCorePendingQueueArray[coreIdx]->UnsafeEnqueue(*it);
73+ aicIdx++;
74+ }
75+ 
76+ // perCorePendingQueue: distribute aiv tasks to aiv cores (nrValidAic..3*nrValidAic-1)
77+ uint32_t aivIdx = 0;
78+ for (const auto* it = aivQueue->begin(); it != aivQueue->end(); ++it) {
79+ uint32_t coreIdx = nrValidAic + (aivIdx % nrAivCores);
80+ dyntask->drcoRootFuncList->perCorePendingQueueArray[coreIdx]->UnsafeEnqueue(*it);
81+ aivIdx++;
82+ }
83+}
84+ 
85+void DeviceTaskContext::DispatchDieReadyQueueToCores(DynDeviceTask* dyntask, DevAscendProgram* devProg)
86+{
87+ if (!IsMultiDie(devProg)) {
88+ return;
89+ }
90+ uint32_t nrValidAic = devProg->devArgs.nrValidAic;
91+ uint32_t nrAivCores = 2 * nrValidAic;
92+ uint32_t halfAic = nrValidAic / 2;
93+ uint32_t halfAiv = nrAivCores / 2;
94+ // perCorePendingQueue: distribute die tasks, die0 to first-half cores, die1 to second-half cores
95+ for (uint32_t dieId = 0; dieId < DIE_NUM; ++dieId) {
96+ uint32_t aicCoreBase = dieId * halfAic;
97+ uint32_t aicCoreCnt = (dieId == 0) ? halfAic : (nrValidAic - halfAic);
98+ ReadyCoreFunctionQueue* dieAicQue = reinterpret_cast<ReadyCoreFunctionQueue*>(
99+ dyntask->devTask.dieReadyFunctionQue.readyDieAicCoreFunctionQue[dieId]);
100+ uint32_t dieAicIdx = 0;
101+ for (const auto* it = dieAicQue->begin(); it != dieAicQue->end(); ++it) {
102+ uint32_t coreIdx = aicCoreBase + (dieAicIdx % aicCoreCnt);
103+ dyntask->drcoRootFuncList->perCorePendingQueueArray[coreIdx]->UnsafeEnqueue(*it);
104+ dieAicIdx++;
105+ }
106+ 
107+ uint32_t aivCoreBase = nrValidAic + dieId * halfAiv;
108+ uint32_t aivCoreCnt = (dieId == 0) ? halfAiv : (nrAivCores - halfAiv);
109+ ReadyCoreFunctionQueue* dieAivQue = reinterpret_cast<ReadyCoreFunctionQueue*>(
110+ dyntask->devTask.dieReadyFunctionQue.readyDieAivCoreFunctionQue[dieId]);
111+ uint32_t dieAivIdx = 0;
112+ for (const auto* it = dieAivQue->begin(); it != dieAivQue->end(); ++it) {
113+ uint32_t coreIdx = aivCoreBase + (dieAivIdx % aivCoreCnt);
114+ dyntask->drcoRootFuncList->perCorePendingQueueArray[coreIdx]->UnsafeEnqueue(*it);
115+ dieAivIdx++;
116+ }
117+ }
118+}
119+ 
120+void DeviceTaskContext::BuildDrcoRootFuncData(DynFuncData* dyndata, DevAscendFunctionDupped& stitchedFunc)
121+{
122+ DevAscendFunction* source = stitchedFunc.GetSource();
123+ uint32_t opSize = stitchedFunc.GetOperationSize();
124+ // AICore drco uses int32_t predCount because aicore atomicAdd only supports 32bit/64bit operands,
125+ // while the aicpu-side dupped data predCount stays uint16_t (sizeof(predcount_t)).
126+ uint32_t drcoPredCountSize = opSize * sizeof(int32_t);
127+ WsAllocation predAlloc = ControlFlowAllocateSlab(
128+ devProg_, drcoPredCountSize, workspace_->SlabAlloc(drcoPredCountSize, WsAicpuSlabMemType::PRED_COUNT));
129+ int32_t* aicorePredCount = predAlloc.As<int32_t>();
130+ for (uint32_t i = 0; i < opSize; ++i) {
131+ aicorePredCount[i] = static_cast<int32_t>(stitchedFunc.GetOperationCurrPredCount(i));
132+ }
133+ auto* rootFuncData = &dyndata->drcoRootFuncData;
134+ rootFuncData->predCount = aicorePredCount;
135+ rootFuncData->succStaticList = reinterpret_cast<int32_t*>(&source->GetOperationSucc(0));
136+ rootFuncData->succStitchList = &stitchedFunc.DupDataForDynFuncData()->GetStitch(0).Head();
137+ rootFuncData->succInfoList = &source->GetOperationSuccInfo(0);
138+ dyndata->cceBinaryIndexList = source->GetCalleeIndexAddr();
139+}
140+ 
141+} // namespace npu::tile_fwk::dynamic
@@ -105,6 +105,9 @@ public:
105 }105 }
106 bool appendLastTaskCtrl = false;106 bool appendLastTaskCtrl = false;
107 DeviceTaskCtrl* newTaskCtrl = InitTaskCtrl(idx, &dynTask->devTask, ctx);107 DeviceTaskCtrl* newTaskCtrl = InitTaskCtrl(idx, &dynTask->devTask, ctx);
108+ if (AicoreResolveEnabled()) {
109+ dynTask->taskStageAllocMem.ctrlNotFreeFlag = &newTaskCtrl->notFree;
110+ }
108 if (lastTaskCtrl_ && lastTaskCtrl_->SupportParallel()) {111 if (lastTaskCtrl_ && lastTaskCtrl_->SupportParallel()) {
109 if (SameParallelIterTaskCtrl(lastTaskCtrl_, newTaskCtrl)) {112 if (SameParallelIterTaskCtrl(lastTaskCtrl_, newTaskCtrl)) {
110 lastTaskCtrl_->existNextSameIterTask = true;113 lastTaskCtrl_->existNextSameIterTask = true;
@@ -121,8 +124,12 @@ public:
121 }124 }
122 125 
123 if (!appendLastTaskCtrl && !ctx->devProg->ctrlFlowCacheAnchor->IsRecording()) {126 if (!appendLastTaskCtrl && !ctx->devProg->ctrlFlowCacheAnchor->IsRecording()) {
124- for (uint32_t i = 0; i < GetScheAicpuNum(); ++i) {127+ if (AicoreResolveEnabled()) {
125- GetTaskQueue(i).Enqueue(newTaskCtrl);128+ GetDeviceTaskReadyQueue().Append(dynTask->dynFuncDataList, dynTask->drcoRootFuncList);
129+ } else {
130+ for (uint32_t i = 0; i < GetScheAicpuNum(); ++i) {
131+ GetTaskQueue(i).Enqueue(newTaskCtrl);
132+ }
126 }133 }
127 }134 }
128 135 
@@ -131,8 +138,12 @@ public:
131 138 
132 void StopAicoreManager()139 void StopAicoreManager()
133 {140 {
134- for (uint32_t i = 0; i < GetScheAicpuNum(); ++i) {141+ if (AicoreResolveEnabled()) {
135- GetTaskQueue(i).Enqueue(nullptr);142+ GetDeviceTaskReadyQueue().Append(nullptr, nullptr);
143+ } else {
144+ for (uint32_t i = 0; i < GetScheAicpuNum(); ++i) {
145+ GetTaskQueue(i).Enqueue(nullptr);
146+ }
136 }147 }
137 }148 }
138 149 
@@ -144,8 +155,12 @@ public:
144 155 
145 void InitTaskPipeWithSched(DevAscendProgram* devProg)156 void InitTaskPipeWithSched(DevAscendProgram* devProg)
146 {157 {
147- for (uint32_t i = 0; i < devProg->devArgs.scheCpuNum; ++i) {158+ if (AicoreResolveEnabled()) {
148- GetTaskQueue(i).ResetEmpty();159+ GetDeviceTaskReadyQueue().Reset();
160+ } else {
161+ for (uint32_t i = 0; i < devProg->devArgs.scheCpuNum; ++i) {
162+ GetTaskQueue(i).ResetEmpty();
163+ }
149 }164 }
150 }165 }
151 166 
@@ -453,6 +468,15 @@ private:
453private:468private:
454 DeviceTaskCtrl& GetTaskCtrlInPool(int index) { return devStartArgs_->deviceRuntimeDataDesc.taskCtrlPool[index]; }469 DeviceTaskCtrl& GetTaskCtrlInPool(int index) { return devStartArgs_->deviceRuntimeDataDesc.taskCtrlPool[index]; }
455 DeviceTaskCtrlQueue& GetTaskQueue(int index) { return devStartArgs_->deviceRuntimeDataDesc.taskQueueList[index]; }470 DeviceTaskCtrlQueue& GetTaskQueue(int index) { return devStartArgs_->deviceRuntimeDataDesc.taskQueueList[index]; }
471+ npu::tile_fwk::DrcoDeviceTaskReadyQueue& GetDeviceTaskReadyQueue()
472+ {
473+ return *devStartArgs_->drcoDeviceTaskReadyQueue;
474+ }
475+ bool AicoreResolveEnabled() const
476+ {
477+ return devStartArgs_ != nullptr && devStartArgs_->devProg != nullptr &&
478+ devStartArgs_->devProg->devArgs.enableAicoreResolve;
479+ }
456 uint32_t GetScheAicpuNum()480 uint32_t GetScheAicpuNum()
457 {481 {
458 uint64_t arbitratedScehNum = devStartArgs_->devCtrlState.arbitratedScehNum.load();482 uint64_t arbitratedScehNum = devStartArgs_->devCtrlState.arbitratedScehNum.load();
@@ -335,6 +335,7 @@ struct DynMachineManager {
335 DEV_VERBOSE_DEBUG("#trace.round.start: round=%lu", kargs->parameter.globalRound);335 DEV_VERBOSE_DEBUG("#trace.round.start: round=%lu", kargs->parameter.globalRound);
336 ctrlStartRound_.fetch_add(1, std::memory_order_acq_rel);336 ctrlStartRound_.fetch_add(1, std::memory_order_acq_rel);
337 initCtrl_.store(true);337 initCtrl_.store(true);
338+ ReCalcDevArgsAicoreNum(kargs, PtrToPtr<int64_t, DevAscendProgram>(kargs->cfgdata));
338 int ret = RunCtrlInitNoLock(kargs, entry);339 int ret = RunCtrlInitNoLock(kargs, entry);
339 if (ret != 0) {340 if (ret != 0) {
340 initCtrl_.store(false);341 initCtrl_.store(false);
@@ -834,6 +834,14 @@ static void RunCompileControlFlowStage(Function* function, const std::shared_ptr
834#else834#else
835 std::string cflags = "-mgeneral-regs-only";835 std::string cflags = "-mgeneral-regs-only";
836#endif836#endif
837+ if (IsAicoreResolveEnabled()) {
838+ cflags += " -DENABLE_AICORE_RESOLVE=1";
839+ } else {
840+ cflags += " -DENABLE_AICORE_RESOLVE=0";
841+ }
842+ // keep -D__DEVICE__ for the arm64 dev control flow compile, which is otherwise only added when extraCflag is empty
843+ std::string devCflags = "-D__DEVICE__ -DENABLE_AICORE_RESOLVE=";
844+ devCflags += IsAicoreResolveEnabled() ? "1" : "0";
837 845 
838 const std::string funcHash = function->GetFunctionHash().Data();846 const std::string funcHash = function->GetFunctionHash().Data();
839 const std::string arm64TargetToolPath = Arm64TargetTool("g++");847 const std::string arm64TargetToolPath = Arm64TargetTool("g++");
@@ -858,7 +866,7 @@ static void RunCompileControlFlowStage(Function* function, const std::shared_ptr
858 arm64TargetToolPath.c_str());866 arm64TargetToolPath.c_str());
859 attr->devControlFlowBinary = CompileAndLoadSection(867 attr->devControlFlowBinary = CompileAndLoadSection(
860 controlFlowSource, controlFlowDevFilePath, aicpuDirPath, exprSrcFiles, arm64TargetToolPath, BISHENG_LD_CMD,868 controlFlowSource, controlFlowDevFilePath, aicpuDirPath, exprSrcFiles, arm64TargetToolPath, BISHENG_LD_CMD,
861- Arm64TargetTool("objcopy"), ".pypto", IsNeedDumpAicpuKernel(controlFlowDevFilePath));869+ Arm64TargetTool("objcopy"), ".pypto", IsNeedDumpAicpuKernel(controlFlowDevFilePath), devCflags);
862 } else {870 } else {
863 // brk #0871 // brk #0
864 MACHINE_LOGW("Arm64 target tool is not found.");872 MACHINE_LOGW("Arm64 target tool is not found.");
@@ -60,6 +60,9 @@ int BundleLaunchAicpu(RtAicpuArgsEx& rtArgs, DevAscendProgram* devProg)
60 if (ret != RT_SUCCESS) {60 if (ret != RT_SUCCESS) {
61 return ret;61 return ret;
62 }62 }
63+ if (devProg->devArgs.enableAicoreResolve) {
64+ return ret;
65+ }
63 args->kArgs.parameter.runMode = RUN_SPLITTED_STREAM_SCHE;66 args->kArgs.parameter.runMode = RUN_SPLITTED_STREAM_SCHE;
64 startTime = MspfSysCycleTime();67 startTime = MspfSysCycleTime();
65 const int scheCpuNum = static_cast<int>(devProg->devArgs.scheCpuNum);68 const int scheCpuNum = static_cast<int>(devProg->devArgs.scheCpuNum);
@@ -94,7 +94,7 @@ int DeviceLauncher::RunWithProfile(RtStream aicoreStream, RtStream aicpuStream,
94int DeviceLauncher::DynamicLaunchSynchronize(RtStream schedStream, RtStream ctrlStream, RtStream aicoreStream)94int DeviceLauncher::DynamicLaunchSynchronize(RtStream schedStream, RtStream ctrlStream, RtStream aicoreStream)
95{95{
96 int rcAicore = RuntimeStreamSynchronize(aicoreStream);96 int rcAicore = RuntimeStreamSynchronize(aicoreStream);
97- int rcAicpu = RuntimeStreamSynchronize(schedStream);97+ int rcAicpu = IsAicoreResolveEnabled() ? 0 : RuntimeStreamSynchronize(schedStream);
98 int rcCtrl = 0;98 int rcCtrl = 0;
99 if (ctrlStream != nullptr) {99 if (ctrlStream != nullptr) {
100 rcCtrl = RuntimeStreamSynchronize(ctrlStream);100 rcCtrl = RuntimeStreamSynchronize(ctrlStream);
@@ -376,6 +376,9 @@ void DeviceLauncher::SetDevPerfAddr([[maybe_unused]] const bool debugEnable, [[m
376 376 
377int DeviceLauncher::LaunchSyncTask(AclRtStream aicoreStream, bool isCaptureMode, int launchEarlyMode)377int DeviceLauncher::LaunchSyncTask(AclRtStream aicoreStream, bool isCaptureMode, int launchEarlyMode)
378{378{
379+ if (IsAicoreResolveEnabled()) {
380+ return 0;
381+ }
379 if (launchEarlyMode == 1) { // 1 : early launch in all modes382 if (launchEarlyMode == 1) { // 1 : early launch in all modes
380 return 0;383 return 0;
381 }384 }
@@ -439,6 +442,9 @@ int DeviceLauncher::LaunchAicpuKernel(AicpuLaunchDesc& launchDesc, [[maybe_unuse
439 if (ret != RT_SUCCESS) {442 if (ret != RT_SUCCESS) {
440 return ret;443 return ret;
441 }444 }
445+ if (IsAicoreResolveEnabled()) {
446+ return ret;
447+ }
442 args->kArgs.parameter.runMode = RUN_SPLITTED_STREAM_SCHE;448 args->kArgs.parameter.runMode = RUN_SPLITTED_STREAM_SCHE;
443 startTime = MspfSysCycleTime();449 startTime = MspfSysCycleTime();
444 const int scheCpuNum = static_cast<int>(DeviceLauncher::GetDevProg(function)->devArgs.scheCpuNum);450 const int scheCpuNum = static_cast<int>(DeviceLauncher::GetDevProg(function)->devArgs.scheCpuNum);
@@ -461,8 +467,13 @@ int DeviceLauncher::LaunchAicoreKernel(AclRtStream aicoreStream, void* kernel, R
461 auto ret = RuntimeKernelLaunchWithHandleV2(kernel, tilingKey, blockDim, &rtArgs, nullptr, aicoreStream, &rtTaskCfg);467 auto ret = RuntimeKernelLaunchWithHandleV2(kernel, tilingKey, blockDim, &rtArgs, nullptr, aicoreStream, &rtTaskCfg);
462 HostProf::GetInstance().ReportHostProfInfo(aicoreStream, startTime, blockDim, MSPF_GE_TASK_TYPE_MIX_AIC, true);468 HostProf::GetInstance().ReportHostProfInfo(aicoreStream, startTime, blockDim, MSPF_GE_TASK_TYPE_MIX_AIC, true);
463 if (debugEnable || !IsCaptureMode() || IsPtoDataDumpEnabled()) {469 if (debugEnable || !IsCaptureMode() || IsPtoDataDumpEnabled()) {
464- auto scheStream = GetStreamContext().GetScheStream();470+ int rc = 0;
465- int rc = DeviceSynchronize(scheStream, aicoreStream);471+ if (IsAicoreResolveEnabled()) {
472+ rc = RuntimeStreamSynchronize(aicoreStream);
473+ } else {
474+ auto scheStream = GetStreamContext().GetScheStream();
475+ rc = DeviceSynchronize(scheStream, aicoreStream);
476+ }
466 if (rc != 0) {477 if (rc != 0) {
467 MACHINE_LOGE(HostLauncherErr::SYNC_FAILED, "stream sync failed");478 MACHINE_LOGE(HostLauncherErr::SYNC_FAILED, "stream sync failed");
468 return rc;479 return rc;
@@ -218,6 +218,7 @@ public:
218 if (IsPtoDataDumpEnabled()) { // dump tensor218 if (IsPtoDataDumpEnabled()) { // dump tensor
219 devProg->devArgs.hostPid = GetProcessId();219 devProg->devArgs.hostPid = GetProcessId();
220 }220 }
221+ devProg->devArgs.enableAicoreResolve = IsAicoreResolveEnabled();
221 if (isDevice) {222 if (isDevice) {
222 devProg->devArgs.validGetPgMask = RuntimeAgent::GetAgent().GetValidGetPgMask();223 devProg->devArgs.validGetPgMask = RuntimeAgent::GetAgent().GetValidGetPgMask();
223 }224 }
@@ -86,3 +86,22 @@ static inline void CallSubFuncTask(uint64_t, npu::tile_fwk::CoreFuncParam*, int6
86{86{
87 std::this_thread::sleep_for(std::chrono::microseconds(5)); // fixed 5us modeling87 std::this_thread::sleep_for(std::chrono::microseconds(5)); // fixed 5us modeling
88}88}
89+ 
90+template <typename T, typename V>
91+static inline T atomicAdd(__gm__ T* address, V value)
92+{
93+ return __atomic_fetch_add(address, static_cast<T>(value), __ATOMIC_RELAXED);
94+}
95+ 
96+template <typename T>
97+static inline T atomicCAS(__gm__ T* address, T compare, T value)
98+{
99+ __atomic_compare_exchange_n(address, &compare, value, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED);
100+ return compare;
101+}
102+ 
103+template <typename T>
104+static inline T atomicExch(__gm__ T* address, T value)
105+{
106+ return __atomic_exchange_n(address, value, __ATOMIC_RELAXED);
107+}
@@ -33,6 +33,10 @@ enum class WsAicpuSlabMemType : uint8_t {
33 READY_QUE,33 READY_QUE,
34 DIE_READY_QUE,34 DIE_READY_QUE,
35 WRAP_QUEUE,35 WRAP_QUEUE,
36+ PER_CORE_PENDING_QUE,
37+ LOCAL_READY_QUE,
38+ GLOBAL_READY_QUE,
39+ PRED_COUNT,
36 DUPPED_STITCH, // stitch pool memory40 DUPPED_STITCH, // stitch pool memory
37 SLAB_MEM_TYPE_BUTT41 SLAB_MEM_TYPE_BUTT
38};42};
@@ -517,12 +521,14 @@ private:
517 521 
518struct WsSlabStageAllocMem {522struct WsSlabStageAllocMem {
519 std::atomic_bool canFree{false};523 std::atomic_bool canFree{false};
524+ std::atomic_bool* ctrlNotFreeFlag{nullptr};
520 StageAllocInfo generalMetadataStageMem;525 StageAllocInfo generalMetadataStageMem;
521 StageAllocInfo stitchStageMem;526 StageAllocInfo stitchStageMem;
522 527 
523 WsSlabStageAllocMem() = default;528 WsSlabStageAllocMem() = default;
524 WsSlabStageAllocMem(const WsSlabStageAllocMem& other)529 WsSlabStageAllocMem(const WsSlabStageAllocMem& other)
525 : canFree(other.canFree.load(std::memory_order_relaxed)),530 : canFree(other.canFree.load(std::memory_order_relaxed)),
531+ ctrlNotFreeFlag(other.ctrlNotFreeFlag),
526 generalMetadataStageMem(other.generalMetadataStageMem),532 generalMetadataStageMem(other.generalMetadataStageMem),
527 stitchStageMem(other.stitchStageMem)533 stitchStageMem(other.stitchStageMem)
528 {}534 {}
@@ -531,6 +537,7 @@ struct WsSlabStageAllocMem {
531 {537 {
532 if (this != &other) {538 if (this != &other) {
533 canFree.store(other.canFree.load(std::memory_order_relaxed), std::memory_order_relaxed);539 canFree.store(other.canFree.load(std::memory_order_relaxed), std::memory_order_relaxed);
540+ ctrlNotFreeFlag = other.ctrlNotFreeFlag;
534 generalMetadataStageMem = other.generalMetadataStageMem;541 generalMetadataStageMem = other.generalMetadataStageMem;
535 stitchStageMem = other.stitchStageMem;542 stitchStageMem = other.stitchStageMem;
536 }543 }
@@ -600,6 +600,7 @@ void DevAscendFunction::InitOperationBufferLayouts(
600 opAttrOffsetList_.HostInitDataSizeOffset(initOffset, callList.size());600 opAttrOffsetList_.HostInitDataSizeOffset(initOffset, callList.size());
601 opCalleeList_.HostInitDataSizeOffset(initOffset, callList.size());601 opCalleeList_.HostInitDataSizeOffset(initOffset, callList.size());
602 operationSuccList_.HostInitDataSizeOffset(initOffset, sucSize);602 operationSuccList_.HostInitDataSizeOffset(initOffset, sucSize);
603+ operationSuccInfoList_.HostInitDataSizeOffset(initOffset, callList.size());
603 operationCopyOutResolveSuccIndexList_.HostInitDataSizeOffset(initOffset, copyOutResolveSuccIdxSize);604 operationCopyOutResolveSuccIndexList_.HostInitDataSizeOffset(initOffset, copyOutResolveSuccIdxSize);
604}605}
605 606 
@@ -645,7 +646,7 @@ void DevAscendFunction::PopulateOperationEncodedContent(
645 PopulateOneEncodedOpOperandsAndAttrs(index, operanSize, staticAttributeSize, expressionTable, callList, tlist,646 PopulateOneEncodedOpOperandsAndAttrs(index, operanSize, staticAttributeSize, expressionTable, callList, tlist,
646 rawList, calleeHashIndexDict, stitchIndexList);647 rawList, calleeHashIndexDict, stitchIndexList);
647 PopulateOneEncodedOpGraphEdges(index, sucSize, copyOutResolveSuccIdxSize, callList, callOpSuccDict,648 PopulateOneEncodedOpGraphEdges(index, sucSize, copyOutResolveSuccIdxSize, callList, callOpSuccDict,
648- copyOutResolveSuccIndexListDict, dupData);649+ copyOutResolveSuccIndexListDict, stitchIndexList, dupData);
649 }650 }
650}651}
651 652 
@@ -724,12 +725,18 @@ void DevAscendFunction::PopulateOneEncodedOpGraphEdges(
724 size_t index, int& sucSize, int& copyOutResolveSuccIdxSize, const OrderedSet<Operation*>& callList,725 size_t index, int& sucSize, int& copyOutResolveSuccIdxSize, const OrderedSet<Operation*>& callList,
725 const std::unordered_map<Operation*, OrderedSet<Operation*>>& callOpSuccDict,726 const std::unordered_map<Operation*, OrderedSet<Operation*>>& callOpSuccDict,
726 const std::unordered_map<Operation*, std::vector<int>>& copyOutResolveSuccIndexListDict,727 const std::unordered_map<Operation*, std::vector<int>>& copyOutResolveSuccIndexListDict,
727- DevAscendFunctionDuppedData* dupData)728+ const std::vector<int32_t>& stitchIndexList, DevAscendFunctionDuppedData* dupData)
728{729{
729 Operation* op = callList[index];730 Operation* op = callList[index];
730 DevAscendOperation& staticField = At(operationList_, index);731 DevAscendOperation& staticField = At(operationList_, index);
731 732 
732 int opSuccSize = callOpSuccDict.find(op)->second.size();733 int opSuccSize = callOpSuccDict.find(op)->second.size();
734+ 
735+ npu::tile_fwk::DevAscendFunctionOperationSuccInfo& succInfo = At(operationSuccInfoList_, index);
736+ succInfo.staticIndex = static_cast<uint16_t>(sucSize);
737+ succInfo.staticSize = static_cast<uint16_t>(opSuccSize);
738+ succInfo.stitchIndex = stitchIndexList[index];
739+ 
733 staticField.depGraphSuccList.AssignRangeOffsetSize(operationSuccList_, sucSize, opSuccSize);740 staticField.depGraphSuccList.AssignRangeOffsetSize(operationSuccList_, sucSize, opSuccSize);
734 for (int k = 0; k < opSuccSize; k++) {741 for (int k = 0; k < opSuccSize; k++) {
735 int succ = callList.GetIndex(callOpSuccDict.find(op)->second[k]);742 int succ = callList.GetIndex(callOpSuccDict.find(op)->second[k]);
@@ -761,13 +768,13 @@ void DevAscendFunction::VerifyOperationEncodedContent(const OrderedSet<Operation
761 At(operationList_, idx).depGraphPredCount == callOpPredDict.find(op)->second)768 At(operationList_, idx).depGraphPredCount == callOpPredDict.find(op)->second)
762 << "depGraphPredCount mismatch: expected " << callOpPredDict.find(op)->second << ", got "769 << "depGraphPredCount mismatch: expected " << callOpPredDict.find(op)->second << ", got "
763 << At(operationList_, idx).depGraphPredCount;770 << At(operationList_, idx).depGraphPredCount;
764- if (dupData->GetOperationCurrPredCount(idx) != callOpPredDict.find(op)->second) {771+ if (static_cast<uint32_t>(dupData->GetOperationCurrPredCount(idx)) != callOpPredDict.find(op)->second) {
765 MACHINE_LOGE(ProgEncodeErr::CALL_OP_COUNT_EXCEEDS_UINT16_MAX,772 MACHINE_LOGE(ProgEncodeErr::CALL_OP_COUNT_EXCEEDS_UINT16_MAX,
766 "OperationCurrPredCount: %d Callopsize is %u exceeds the maximum allowed value of 65535.",773 "OperationCurrPredCount: %d Callopsize is %u exceeds the maximum allowed value of 65535.",
767 dupData->GetOperationCurrPredCount(idx), dupData->GetOperationSize());774 dupData->GetOperationCurrPredCount(idx), dupData->GetOperationSize());
768 }775 }
769 ASSERT(DevCommonErr::PARAM_CHECK_FAILED,776 ASSERT(DevCommonErr::PARAM_CHECK_FAILED,
770- dupData->GetOperationCurrPredCount(idx) == callOpPredDict.find(op)->second)777+ static_cast<uint32_t>(dupData->GetOperationCurrPredCount(idx)) == callOpPredDict.find(op)->second)
771 << "GetOperationCurrPredCount mismatch: expected " << dupData->GetOperationCurrPredCount(idx) << ", got "778 << "GetOperationCurrPredCount mismatch: expected " << dupData->GetOperationCurrPredCount(idx) << ", got "
772 << callOpPredDict.find(op)->second << ", Callopsize is " << dupData->GetOperationSize()779 << callOpPredDict.find(op)->second << ", Callopsize is " << dupData->GetOperationSize()
773 << " exceeds the maximum allowed value of 65535.";780 << " exceeds the maximum allowed value of 65535.";
@@ -96,6 +96,7 @@ private:
96 DevLocalVector<int> opAttrOffsetList_;96 DevLocalVector<int> opAttrOffsetList_;
97 DevLocalVector<int> opCalleeList_;97 DevLocalVector<int> opCalleeList_;
98 DevLocalVector<int> operationSuccList_;98 DevLocalVector<int> operationSuccList_;
99+ DevLocalVector<npu::tile_fwk::DevAscendFunctionOperationSuccInfo> operationSuccInfoList_;
99 DevLocalVector<int> operationCopyOutResolveSuccIndexList_;100 DevLocalVector<int> operationCopyOutResolveSuccIndexList_;
100 101 
101 DevLocalVector<DevAscendFunctionIncast> incastList;102 DevLocalVector<DevAscendFunctionIncast> incastList;
@@ -419,6 +420,18 @@ public:
419 420 
420 inline void FillOpAttrs(DevCceBinary* cceInfo) { (void)cceInfo; }421 inline void FillOpAttrs(DevCceBinary* cceInfo) { (void)cceInfo; }
421 422 
423+ inline int GetOperationSucc(size_t idx) const { return At(operationSuccList_, idx); }
424+ inline int& GetOperationSucc(size_t idx) { return At(operationSuccList_, idx); }
425+ 
426+ inline npu::tile_fwk::DevAscendFunctionOperationSuccInfo GetOperationSuccInfo(size_t operationIndex) const
427+ {
428+ return At(operationSuccInfoList_, operationIndex);
429+ }
430+ inline npu::tile_fwk::DevAscendFunctionOperationSuccInfo& GetOperationSuccInfo(size_t operationIndex)
431+ {
432+ return At(operationSuccInfoList_, operationIndex);
433+ }
434+ 
422 inline const uint32_t& GetOperationDepGraphPredCount(int operationIndex) const435 inline const uint32_t& GetOperationDepGraphPredCount(int operationIndex) const
423 {436 {
424 return At(operationList_, operationIndex).depGraphPredCount;437 return At(operationList_, operationIndex).depGraphPredCount;
@@ -584,7 +597,7 @@ private:
584 size_t index, int& sucSize, int& copyOutResolveSuccIdxSize, const OrderedSet<Operation*>& callList,597 size_t index, int& sucSize, int& copyOutResolveSuccIdxSize, const OrderedSet<Operation*>& callList,
585 const std::unordered_map<Operation*, OrderedSet<Operation*>>& callOpSuccDict,598 const std::unordered_map<Operation*, OrderedSet<Operation*>>& callOpSuccDict,
586 const std::unordered_map<Operation*, std::vector<int>>& copyOutResolveSuccIndexListDict,599 const std::unordered_map<Operation*, std::vector<int>>& copyOutResolveSuccIndexListDict,
587- DevAscendFunctionDuppedData* dupData);600+ const std::vector<int32_t>& stitchIndexList, DevAscendFunctionDuppedData* dupData);
588 void VerifyOperationEncodedContent(const OrderedSet<Operation*>& callList,601 void VerifyOperationEncodedContent(const OrderedSet<Operation*>& callList,
589 const std::unordered_map<Operation*, uint64_t>& callOpPredDict,602 const std::unordered_map<Operation*, uint64_t>& callOpPredDict,
590 DevAscendFunctionDuppedData* dupData);603 DevAscendFunctionDuppedData* dupData);
@@ -21,42 +21,13 @@
21#include "tilefwk/aicpu_common.h"21#include "tilefwk/aicpu_common.h"
22#include "machine/utils/dynamic/dev_callop_attribute.h"22#include "machine/utils/dynamic/dev_callop_attribute.h"
23namespace npu::tile_fwk::dynamic {23namespace npu::tile_fwk::dynamic {
24+using npu::tile_fwk::DevAscendFunctionDuppedStitchNode;
24using npu::tile_fwk::DUPPED_STITCH_SIZE;25using npu::tile_fwk::DUPPED_STITCH_SIZE;
26+using DevAscendFunctionDuppedStitch = npu::tile_fwk::DevAscendFunctionDuppedStitchNode;
27+static_assert(sizeof(DevAscendFunctionDuppedStitch) == npu::tile_fwk::DUPPED_STITCH_NODE_U32_SIZE * sizeof(uint32_t),
28+ "Invalid size");
25// Max cell-match table entry count (desc stride[0]); checked at encode and in host GetWorkspaceSize.29// Max cell-match table entry count (desc stride[0]); checked at encode and in host GetWorkspaceSize.
26constexpr int64_t MAX_CELLMATCHSSTRIDE = 20000000;30constexpr int64_t MAX_CELLMATCHSSTRIDE = 20000000;
27-struct DevAscendFunctionDuppedStitch {
28- void InitWithNext(DevAscendFunctionDuppedStitch* next)
29- {
30- next_ = next;
31- size_ = 0;
32- }
33- 
34- void PushBack(uint32_t taskId)
35- {
36- DEV_ASSERT_MSG(ProgEncodeErr::STITCH_LIST_TOO_LARGE, size_ < DUPPED_STITCH_SIZE,
37- "Exceed maximum stitch size %u.", DUPPED_STITCH_SIZE);
38- taskList_[size_++] = taskId;
39- }
40- 
41- uint32_t Size() const { return size_; }
42- DevAscendFunctionDuppedStitch* const& Next() const { return next_; }
43- DevAscendFunctionDuppedStitch*& Next() { return next_; }
44- 
45- // 函数在核心流程,已在Size()内循环,校验会影响性能
46- uint32_t At(uint32_t idx) const { return taskList_[idx]; }
47- 
48- void ForEach(const std::function<void(uint32_t id)>& callback) const
49- {
50- for (uint32_t i = 0; i < size_; i++) {
51- callback(taskList_[i]);
52- }
53- }
54- 
55-private:
56- DevAscendFunctionDuppedStitch* next_;
57- uint32_t size_;
58- uint32_t taskList_[DUPPED_STITCH_SIZE];
59-};
60 31 
61struct DevAscendFunctionDuppedStitchList {32struct DevAscendFunctionDuppedStitchList {
62 DevAscendFunctionDuppedStitchList() = default;33 DevAscendFunctionDuppedStitchList() = default;
@@ -83,7 +54,7 @@ struct DevAscendFunctionDuppedStitchList {
83 newNode->InitWithNext(head_);54 newNode->InitWithNext(head_);
84 head_ = newNode;55 head_ = newNode;
85 }56 }
86- head_->PushBack(taskId);57+ head_->SafePushBack(taskId);
87 }58 }
88 59 
89 template <typename T = uint32_t>60 template <typename T = uint32_t>
@@ -93,9 +93,19 @@ void DevControlFlowCache::PredCountDataRestore(DynDeviceTaskBase* base)
93 DynFuncDataCache* dynDataCache = &dynFuncDataCacheList->At(dupIndex);93 DynFuncDataCache* dynDataCache = &dynFuncDataCacheList->At(dupIndex);
94 DynFuncDataBackup* dynDataBackup = &dynFuncDataBackupList->At(dupIndex);94 DynFuncDataBackup* dynDataBackup = &dynFuncDataBackupList->At(dupIndex);
95 DevAscendFunctionDuppedData* duppedData = dynDataCache->duppedData;95 DevAscendFunctionDuppedData* duppedData = dynDataCache->duppedData;
96- size_t backupSize = sizeof(predcount_t) * duppedData->GetOperationSize();96+ uint32_t opSize = duppedData->GetOperationSize();
97+ size_t backupSize = sizeof(predcount_t) * opSize;
97 DevMemcpyS(&duppedData->GetOperationCurrPredCount(0), backupSize, dynDataBackup->predCountBackup, backupSize);98 DevMemcpyS(&duppedData->GetOperationCurrPredCount(0), backupSize, dynDataBackup->predCountBackup, backupSize);
98 99 
100+ DynFuncData* dynData = &dynFuncDataList->At(dupIndex);
101+ if (dynData->drcoRootFuncData.predCount != nullptr) {
102+ // drco predCount is int32_t on aicore side, while cache backup is uint16_t(predcount_t)
103+ int32_t* drcoPredCount = dynData->drcoRootFuncData.predCount;
104+ for (uint32_t i = 0; i < opSize; ++i) {
105+ drcoPredCount[i] = static_cast<int32_t>(dynDataBackup->predCountBackup[i]);
106+ }
107+ }
108+ 
99 BitmapDataRestore(dynDataCache, dynDataBackup);109 BitmapDataRestore(dynDataCache, dynDataBackup);
100 }110 }
101}111}
@@ -121,16 +131,75 @@ void DevControlFlowCache::ReadyQueueDataBackup(DynDeviceTaskBase* base)
121 readyTaskNum += base->readyQueue[i]->UnsafeSize();131 readyTaskNum += base->readyQueue[i]->UnsafeSize();
122 }132 }
123 readyQueueBackup->readyTaskNum = readyTaskNum;133 readyQueueBackup->readyTaskNum = readyTaskNum;
134+ 
135+ if (base->drcoRootFuncList != nullptr) {
136+ for (size_t i = 0; i < npu::tile_fwk::MAX_AICORE_NUM_FOR_QUEUE; i++) {
137+ auto* src = base->drcoRootFuncList->perCorePendingQueueArray[i];
138+ if (src == nullptr) {
139+ continue;
140+ }
141+ size_t backupSize = sizeof(npu::tile_fwk::PerCorePendingQueue) +
142+ sizeof(npu::tile_fwk::LeafTaskId) * src->size;
143+ auto* dst = reinterpret_cast<npu::tile_fwk::PerCorePendingQueue*>(AllocateCache(backupSize));
144+ if (dst == nullptr) {
145+ continue;
146+ }
147+ memcpy_s(dst, backupSize, src, backupSize);
148+ readyQueueBackup->perCorePendingQueueList[i] = dst;
149+ }
150+ }
151+ 
124 base->readyQueueBackup = readyQueueBackup;152 base->readyQueueBackup = readyQueueBackup;
125}153}
126 154 
127-void DevControlFlowCache::ReadyQueueDataRestore(DynDeviceTaskBase* base)155+void DevControlFlowCache::ReadyQueueDataRestore(DynDeviceTaskBase* base, uint32_t nrValidAic)
128{156{
129 ReadyQueueCache* readyQueueBackup = base->readyQueueBackup;157 ReadyQueueCache* readyQueueBackup = base->readyQueueBackup;
130 base->devTask.coreFunctionCnt = readyQueueBackup->coreFunctionCnt;158 base->devTask.coreFunctionCnt = readyQueueBackup->coreFunctionCnt;
131 for (size_t i = 0; i < READY_QUEUE_SIZE; i++) {159 for (size_t i = 0; i < READY_QUEUE_SIZE; i++) {
132 *base->readyQueue[i] = readyQueueBackup->queueList[i];160 *base->readyQueue[i] = readyQueueBackup->queueList[i];
133 }161 }
162+ 
163+ // for aicore-resolve
164+ if (base->drcoRootFuncList != nullptr) {
165+ for (size_t i = 0; i < npu::tile_fwk::MAX_AICORE_NUM_FOR_QUEUE; i++) {
166+ auto* dst = base->drcoRootFuncList->perCorePendingQueueArray[i];
167+ if (dst == nullptr) {
168+ continue;
169+ }
170+ dst->head = 0;
171+ dst->tail = 0;
172+ dst->size = 0;
173+ }
174+ 
175+ uint32_t nrAivCores = nrValidAic * 2;
176+ ReadyCoreFunctionQueue* aivQueue = base->readyQueue[0];
177+ ReadyCoreFunctionQueue* aicQueue = base->readyQueue[1];
178+ uint32_t aicIdx = 0;
179+ for (const auto* it = aicQueue->begin(); it != aicQueue->end(); ++it) {
180+ uint32_t coreIdx = aicIdx % nrValidAic;
181+ base->drcoRootFuncList->perCorePendingQueueArray[coreIdx]->UnsafeEnqueue(*it);
182+ aicIdx++;
183+ }
184+ uint32_t aivIdx = 0;
185+ for (const auto* it = aivQueue->begin(); it != aivQueue->end(); ++it) {
186+ uint32_t coreIdx = nrValidAic + (aivIdx % nrAivCores);
187+ base->drcoRootFuncList->perCorePendingQueueArray[coreIdx]->UnsafeEnqueue(*it);
188+ aivIdx++;
189+ }
190+ __sync_synchronize();
191+ for (uint32_t ct = 0; ct < npu::tile_fwk::NUM_CORE_TYPES; ct++) {
192+ for (uint32_t i = 0; i < npu::tile_fwk::NUM_LOCAL_GROUPS; i++) {
193+ auto* dst = base->drcoRootFuncList->localReadyQueueArray[ct][i];
194+ if (dst == nullptr) {
195+ continue;
196+ }
197+ dst->head = 0;
198+ dst->tail = 0;
199+ }
200+ }
201+ *base->drcoRootFuncList->executedTaskCount = 0;
202+ }
134}203}
135 204 
136void DevControlFlowCache::DieReadyQueueDataBackup(DynDeviceTaskBase* base)205void DevControlFlowCache::DieReadyQueueDataBackup(DynDeviceTaskBase* base)
@@ -165,7 +234,7 @@ void DevControlFlowCache::DieReadyQueueDataBackup(DynDeviceTaskBase* base)
165 base->dieReadyQueueBackup = dieReadyQueueBackup;234 base->dieReadyQueueBackup = dieReadyQueueBackup;
166}235}
167 236 
168-void DevControlFlowCache::DieReadyQueueDataRestore(DynDeviceTaskBase* base)237+void DevControlFlowCache::DieReadyQueueDataRestore(DynDeviceTaskBase* base, uint32_t nrValidAic)
169{238{
170 DieReadyQueueCache* dieReadyQueueBackup = base->dieReadyQueueBackup;239 DieReadyQueueCache* dieReadyQueueBackup = base->dieReadyQueueBackup;
171 if (dieReadyQueueBackup == nullptr) {240 if (dieReadyQueueBackup == nullptr) {
@@ -181,6 +250,42 @@ void DevControlFlowCache::DieReadyQueueDataRestore(DynDeviceTaskBase* base)
181 }250 }
182 *dieReadyQueue = dieReadyQueueBackup->queueList[i];251 *dieReadyQueue = dieReadyQueueBackup->queueList[i];
183 }252 }
253+ 
254+ if (base->drcoRootFuncList == nullptr) {
255+ return;
256+ }
257+ // for aicore-resolve
258+ uint32_t nrAivCores = 2 * nrValidAic;
259+ uint32_t halfAic = nrValidAic / 2;
260+ uint32_t halfAiv = nrAivCores / 2;
261+ // perCorePendingQueue: distribute die tasks, die0 to first-half cores, die1 to second-half cores
262+ for (uint32_t dieId = 0; dieId < DIE_NUM; ++dieId) {
263+ uint32_t aicCoreBase = dieId * halfAic;
264+ uint32_t aicCoreCnt = (dieId == 0) ? halfAic : (nrValidAic - halfAic);
265+ ReadyCoreFunctionQueue* dieAicQue = reinterpret_cast<ReadyCoreFunctionQueue*>(
266+ base->devTask.dieReadyFunctionQue.readyDieAicCoreFunctionQue[dieId]);
267+ if (dieAicQue != nullptr) {
268+ uint32_t dieAicIdx = 0;
269+ for (const auto* it = dieAicQue->begin(); it != dieAicQue->end(); ++it) {
270+ uint32_t coreIdx = aicCoreBase + (dieAicIdx % aicCoreCnt);
271+ base->drcoRootFuncList->perCorePendingQueueArray[coreIdx]->UnsafeEnqueue(*it);
272+ dieAicIdx++;
273+ }
274+ }
275+ 
276+ uint32_t aivCoreBase = nrValidAic + dieId * halfAiv;
277+ uint32_t aivCoreCnt = (dieId == 0) ? halfAiv : (nrAivCores - halfAiv);
278+ ReadyCoreFunctionQueue* dieAivQue = reinterpret_cast<ReadyCoreFunctionQueue*>(
279+ base->devTask.dieReadyFunctionQue.readyDieAivCoreFunctionQue[dieId]);
280+ if (dieAivQue != nullptr) {
281+ uint32_t dieAivIdx = 0;
282+ for (const auto* it = dieAivQue->begin(); it != dieAivQue->end(); ++it) {
283+ uint32_t coreIdx = aivCoreBase + (dieAivIdx % aivCoreCnt);
284+ base->drcoRootFuncList->perCorePendingQueueArray[coreIdx]->UnsafeEnqueue(*it);
285+ dieAivIdx++;
286+ }
287+ }
288+ }
184}289}
185 290 
186void DevControlFlowCache::MixTaskDataBackup(DynDeviceTaskBase* base)291void DevControlFlowCache::MixTaskDataBackup(DynDeviceTaskBase* base)
@@ -738,12 +843,20 @@ void DevControlFlowCache::RelocDuppedDataAndDynFuncData(RelocRange& relocProgram
738 843 
739 relocProgram.Reloc(dynDataCache->devFunc);844 relocProgram.Reloc(dynDataCache->devFunc);
740 relocProgram.Reloc(dynDataCache->calleeList);845 relocProgram.Reloc(dynDataCache->calleeList);
846+ relocProgram.RelocNullable(dynData->cceBinaryIndexList);
741 847 
742 relocCtrlCache.Reloc(dynDataCache->predCount);848 relocCtrlCache.Reloc(dynDataCache->predCount);
743 relocCtrlCache.RelocNullable(dynDataBackup->predCountBackup);849 relocCtrlCache.RelocNullable(dynDataBackup->predCountBackup);
744 relocCtrlCache.RelocNullable(dynDataBackup->rawTensorAddrBackup);850 relocCtrlCache.RelocNullable(dynDataBackup->rawTensorAddrBackup);
745 relocCtrlCache.RelocNullable(dynDataBackup->deadEndHubBitmapBackup);851 relocCtrlCache.RelocNullable(dynDataBackup->deadEndHubBitmapBackup);
746 relocCtrlCache.RelocNullable(dynDataBackup->tailTaskBitmapBackup);852 relocCtrlCache.RelocNullable(dynDataBackup->tailTaskBitmapBackup);
853+ 
854+ if (dynData->drcoRootFuncData.predCount != nullptr) {
855+ relocCtrlCache.Reloc(dynData->drcoRootFuncData.predCount);
856+ relocProgram.Reloc(dynData->drcoRootFuncData.succStaticList);
857+ relocCtrlCache.Reloc(dynData->drcoRootFuncData.succStitchList);
858+ relocProgram.Reloc(dynData->drcoRootFuncData.succInfoList);
859+ }
747}860}
748 861 
749/* Host-to-cache: devStartArgs should be nullptr. Cache-to-Device: devStartArgs should be filled */862/* Host-to-cache: devStartArgs should be nullptr. Cache-to-Device: devStartArgs should be filled */
@@ -774,9 +887,23 @@ void DevControlFlowCache::TaskAddrRelocProgramAndCtrlCache(uint64_t srcProgram,
774 readyQueueBackup->queueList[i].Reloc(relocCtrlCache);887 readyQueueBackup->queueList[i].Reloc(relocCtrlCache);
775 }888 }
776 889 
890+ for (size_t i = 0; i < npu::tile_fwk::DRCO_QUEUE_MAX; i++) {
891+ if (readyQueueBackup->globalReadyQueueList[i].ptr != nullptr) {
892+ RelocControlFlowCachePointer(readyQueueBackup->globalReadyQueueList[i].ptr, relocCtrlCache);
893+ }
894+ }
895+ for (size_t i = 0; i < npu::tile_fwk::MAX_AICORE_NUM_FOR_QUEUE; i++) {
896+ if (readyQueueBackup->perCorePendingQueueList[i] != nullptr) {
897+ RelocControlFlowCachePointer(readyQueueBackup->perCorePendingQueueList[i], relocCtrlCache);
898+ }
899+ }
900+ 
777 DynFuncHeader*& dynFuncDataListRef = dynTaskBase->dynFuncDataList;901 DynFuncHeader*& dynFuncDataListRef = dynTaskBase->dynFuncDataList;
778 DynFuncHeader* dynFuncDataList = RelocControlFlowCachePointer(dynFuncDataListRef, relocCtrlCache);902 DynFuncHeader* dynFuncDataList = RelocControlFlowCachePointer(dynFuncDataListRef, relocCtrlCache);
779 relocProgram.Reloc(dynFuncDataList->cceBinary);903 relocProgram.Reloc(dynFuncDataList->cceBinary);
904+ 
905+ RelocDrcoRootFuncList(relocCtrlCache, dynTaskBase);
906+ 
780 DynFuncDataCache* dynFuncDataCacheList = dynTaskBase->dynFuncDataCacheList;907 DynFuncDataCache* dynFuncDataCacheList = dynTaskBase->dynFuncDataCacheList;
781 DynFuncDataBackup* dynFuncDataBackupList = dynTaskBase->dynFuncDataBackupList;908 DynFuncDataBackup* dynFuncDataBackupList = dynTaskBase->dynFuncDataBackupList;
782 MixTaskDataReloc(relocCtrlCache, relocProgram, dynTaskBase, dynFuncDataList);909 MixTaskDataReloc(relocCtrlCache, relocProgram, dynTaskBase, dynFuncDataList);
@@ -806,6 +933,31 @@ void DevControlFlowCache::TaskAddrRelocProgramAndCtrlCache(uint64_t srcProgram,
806 }933 }
807}934}
808 935 
936+void DevControlFlowCache::RelocDrcoRootFuncList(RelocRange& relocCtrlCache, DynDeviceTaskBase* dynTaskBase)
937+{
938+ npu::tile_fwk::DrcoRootFuncList*& drcoRootFuncListRef = dynTaskBase->drcoRootFuncList;
939+ npu::tile_fwk::DrcoRootFuncList* drcoRootFuncList = nullptr;
940+ if (drcoRootFuncListRef != nullptr) {
941+ drcoRootFuncList = RelocControlFlowCachePointer(drcoRootFuncListRef, relocCtrlCache);
942+ }
943+ if (drcoRootFuncList != nullptr) {
944+ for (size_t i = 0; i < npu::tile_fwk::DRCO_QUEUE_MAX; i++) {
945+ if (drcoRootFuncList->globalReadyQueueList[i].ptr != nullptr) {
946+ RelocControlFlowCachePointer(drcoRootFuncList->globalReadyQueueList[i].ptr, relocCtrlCache);
947+ }
948+ }
949+ for (size_t i = 0; i < npu::tile_fwk::MAX_AICORE_NUM_FOR_QUEUE; i++) {
950+ relocCtrlCache.Reloc(drcoRootFuncList->perCorePendingQueueArray[i]);
951+ }
952+ for (uint32_t ct = 0; ct < npu::tile_fwk::NUM_CORE_TYPES; ct++) {
953+ for (uint32_t i = 0; i < npu::tile_fwk::NUM_LOCAL_GROUPS; i++) {
954+ relocCtrlCache.Reloc(drcoRootFuncList->localReadyQueueArray[ct][i]);
955+ }
956+ }
957+ relocCtrlCache.Reloc(drcoRootFuncList->executedTaskCount);
958+ }
959+}
960+ 
809void DevControlFlowCache::RelocMetaCache(uint64_t srcCache, uint64_t dstCache)961void DevControlFlowCache::RelocMetaCache(uint64_t srcCache, uint64_t dstCache)
810{962{
811 intptr_t shift = static_cast<int64_t>(dstCache) - static_cast<int64_t>(srcCache);963 intptr_t shift = static_cast<int64_t>(dstCache) - static_cast<int64_t>(srcCache);
@@ -41,6 +41,9 @@ struct ReadyQueueCache {
41 uint32_t coreFunctionCnt;41 uint32_t coreFunctionCnt;
42 ReadyCoreFunctionQueueUnsafe queueList[READY_QUEUE_SIZE];42 ReadyCoreFunctionQueueUnsafe queueList[READY_QUEUE_SIZE];
43 uint32_t readyTaskNum;43 uint32_t readyTaskNum;
44+ 
45+ npu::tile_fwk::DrcoGlobalReadyQueuePtr globalReadyQueueList[npu::tile_fwk::DRCO_QUEUE_MAX];
46+ npu::tile_fwk::PerCorePendingQueue* perCorePendingQueueList[npu::tile_fwk::MAX_AICORE_NUM_FOR_QUEUE]{};
44};47};
45 48 
46struct DieReadyQueueCache {49struct DieReadyQueueCache {
@@ -100,6 +103,7 @@ struct ParallelInfo {
100struct DynDeviceTaskBase {103struct DynDeviceTaskBase {
101 DeviceTask devTask;104 DeviceTask devTask;
102 DynFuncHeader* dynFuncDataList{nullptr};105 DynFuncHeader* dynFuncDataList{nullptr};
106+ npu::tile_fwk::DrcoRootFuncList* drcoRootFuncList{nullptr};
103 107 
104 ReadyCoreFunctionQueue* readyQueue[READY_QUEUE_SIZE];108 ReadyCoreFunctionQueue* readyQueue[READY_QUEUE_SIZE];
105 DynFuncDataCache dynFuncDataCacheList[MAX_STITCH_FUNC_NUM];109 DynFuncDataCache dynFuncDataCacheList[MAX_STITCH_FUNC_NUM];
@@ -401,11 +405,11 @@ struct DevControlFlowCache {
401 405 
402 void ReadyQueueDataBackup(DynDeviceTaskBase* base);406 void ReadyQueueDataBackup(DynDeviceTaskBase* base);
403 407 
404- void ReadyQueueDataRestore(DynDeviceTaskBase* base);408+ void ReadyQueueDataRestore(DynDeviceTaskBase* base, uint32_t nrValidAic);
405 409 
406 void DieReadyQueueDataBackup(DynDeviceTaskBase* base);410 void DieReadyQueueDataBackup(DynDeviceTaskBase* base);
407 411 
408- void DieReadyQueueDataRestore(DynDeviceTaskBase* base);412+ void DieReadyQueueDataRestore(DynDeviceTaskBase* base, uint32_t nrValidAic);
409 413 
410 void MixTaskDataBackup(DynDeviceTaskBase* base);414 void MixTaskDataBackup(DynDeviceTaskBase* base);
411 415 
@@ -459,6 +463,7 @@ struct DevControlFlowCache {
459 DynFuncHeader* dynFuncDataList);463 DynFuncHeader* dynFuncDataList);
460 464 
461 void DieReadyQueueReloc(RelocRange& relocCtrlCache, DynDeviceTaskBase* dynTaskBase);465 void DieReadyQueueReloc(RelocRange& relocCtrlCache, DynDeviceTaskBase* dynTaskBase);
466+ void RelocDrcoRootFuncList(RelocRange& relocCtrlCache, DynDeviceTaskBase* dynTaskBase);
462 void RelocDuppedDataAndDynFuncData(RelocRange& relocProgram, RelocRange& relocCtrlCache,467 void RelocDuppedDataAndDynFuncData(RelocRange& relocProgram, RelocRange& relocCtrlCache,
463 DevAscendFunctionDuppedData* duppedData, DynFuncData* dynData,468 DevAscendFunctionDuppedData* duppedData, DynFuncData* dynData,
464 DynFuncDataCache* dynDataCache, DynFuncDataBackup* dynDataBackup);469 DynFuncDataCache* dynDataCache, DynFuncDataBackup* dynDataBackup);
@@ -212,7 +212,13 @@ uint64_t CalcStitchWorkspace(DevAscendProgram& devProg)
212{212{
213 DeviceWorkspaceAllocator workspace(&devProg);213 DeviceWorkspaceAllocator workspace(&devProg);
214 uint32_t slabCapacity[CALC_STITCH_NUM] = {0};214 uint32_t slabCapacity[CALC_STITCH_NUM] = {0};
215- uint32_t objUsedNum[CALC_STITCH_NUM] = {READY_QUEUE_SIZE, DIE_READY_QUEUE_SIZE * DIE_NUM, 1};215+ uint32_t objUsedNum[CALC_STITCH_NUM] = {READY_QUEUE_SIZE,
216+ DIE_READY_QUEUE_SIZE * DIE_NUM,
217+ 1,
218+ MAX_AICORE_NUM_FOR_QUEUE,
219+ NUM_CORE_TYPES * NUM_LOCAL_GROUPS,
220+ DRCO_QUEUE_MAX,
221+ 1};
216 uint32_t slabSize = workspace.CalcStitchSlabMemObjmaxSize(slabCapacity);222 uint32_t slabSize = workspace.CalcStitchSlabMemObjmaxSize(slabCapacity);
217 uint64_t stitchPoolSize = slabSize << 4;223 uint64_t stitchPoolSize = slabSize << 4;
218 224 
@@ -71,6 +71,12 @@ struct DevStartArgs : DevStartArgsBase {
71 base + devProg->GetDeviceRuntimeOffset().taskCtrlPoolOffset);71 base + devProg->GetDeviceRuntimeOffset().taskCtrlPoolOffset);
72 deviceRuntimeDataDesc.taskQueueList = reinterpret_cast<DeviceTaskCtrlQueue*>(72 deviceRuntimeDataDesc.taskQueueList = reinterpret_cast<DeviceTaskCtrlQueue*>(
73 base + devProg->GetDeviceRuntimeOffset().taskQueueOffset);73 base + devProg->GetDeviceRuntimeOffset().taskQueueOffset);
74+ if (devProg->devArgs.enableAicoreResolve) {
75+ drcoDeviceTaskReadyQueue = reinterpret_cast<npu::tile_fwk::DrcoDeviceTaskReadyQueue*>(
76+ base + devProg->GetDeviceRuntimeOffset().deviceTaskReadyQueueOffset);
77+ } else {
78+ drcoDeviceTaskReadyQueue = nullptr;
79+ }
74 deviceRuntimeDataDesc.generalAddr = base + devProg->GetDeviceRuntimeOffset().generalOffset;80 deviceRuntimeDataDesc.generalAddr = base + devProg->GetDeviceRuntimeOffset().generalOffset;
75 deviceRuntimeDataDesc.dynamicCellMatchAddr = devProg->devArgs.dynamicCellMatchAddr;81 deviceRuntimeDataDesc.dynamicCellMatchAddr = devProg->devArgs.dynamicCellMatchAddr;
76 deviceRuntimeDataDesc.stitchPoolAddr = base + devProg->GetDeviceRuntimeOffset().stitchPoolOffset;82 deviceRuntimeDataDesc.stitchPoolAddr = base + devProg->GetDeviceRuntimeOffset().stitchPoolOffset;
@@ -155,26 +161,26 @@ static inline void RuntimeYield(uint64_t microseconds = 0)
155}161}
156 162 
157#define DEFAULT_RUNTIME_DATA_RING_BUFFER_COUNT 4163#define DEFAULT_RUNTIME_DATA_RING_BUFFER_COUNT 4
158-struct RuntimeDataRingBufferHead {164+struct RuntimeDataRingBufferHead : RuntimeDataRingBufferHeadData {
159public:165public:
160- void Initialize(uint64_t runtimeDataSize, uint64_t runtimeDataCount, ArchInfo arch = ArchInfo::DAV_2201)166+ void Initialize(uint64_t runtimeDataSizeArg, uint64_t runtimeDataCountArg, ArchInfo arch = ArchInfo::DAV_2201)
161 {167 {
162- runtimeDataSize_ = GetAlignedSize(runtimeDataSize);168+ runtimeDataSize = GetAlignedSize(runtimeDataSizeArg);
163- runtimeDataCount_ = runtimeDataCount;169+ runtimeDataCount = runtimeDataCountArg;
164- archInfo_ = arch;170+ archInfo = arch;
165 171 
166 /* finish starts from round 0 */172 /* finish starts from round 0 */
167- indexFinished_ = 0;173+ indexFinished = 0;
168- indexPending_ = 0;174+ indexPending = 0;
169 }175 }
170 176 
171- bool Full() const { return indexFinished_ + runtimeDataCount_ <= indexPending_; }177+ bool Full() const { return indexFinished + runtimeDataCount <= indexPending; }
172 178 
173- bool Empty() const { return indexFinished_ == indexPending_; }179+ bool Empty() const { return indexFinished == indexPending; }
174 180 
175 void AllocateWait()181 void AllocateWait()
176 {182 {
177- TIMEOUT_CHECK_INIT_WARN_ONLY(archInfo_);183+ TIMEOUT_CHECK_INIT_WARN_ONLY(archInfo);
178 184 
179 while (Full()) {185 while (Full()) {
180 RuntimeYield();186 RuntimeYield();
@@ -188,35 +194,35 @@ public:
188 AllocateWait();194 AllocateWait();
189 195 
190 /* allocate next element from the ring buffer */196 /* allocate next element from the ring buffer */
191- uint64_t index = ++indexPending_;197+ uint64_t index = ++indexPending;
192 return GetRuntimeData(index);198 return GetRuntimeData(index);
193 }199 }
194 200 
195 uint8_t* AllocatePrepare()201 uint8_t* AllocatePrepare()
196 {202 {
197 AllocateWait();203 AllocateWait();
198- return GetRuntimeData(indexPending_ + 1);204+ return GetRuntimeData(indexPending + 1);
199 }205 }
200 206 
201- void AllocateSubmit() { ++indexPending_; }207+ void AllocateSubmit() { ++indexPending; }
202 208 
203 void Deallocate(uint8_t* ptr)209 void Deallocate(uint8_t* ptr)
204 {210 {
205- uint8_t* nextFree = GetRuntimeData(indexFinished_ + 1);211+ uint8_t* nextFree = GetRuntimeData(indexFinished + 1);
206 ASSERT(DevCommonErr::PARAM_CHECK_FAILED, nextFree == ptr);212 ASSERT(DevCommonErr::PARAM_CHECK_FAILED, nextFree == ptr);
207 /* deallocate from the ring buffer */213 /* deallocate from the ring buffer */
208- indexFinished_ += 1;214+ indexFinished += 1;
209 }215 }
210 216 
211- uint64_t GetRuntimeDataSize() { return runtimeDataSize_; }217+ uint64_t GetRuntimeDataSize() { return runtimeDataSize; }
212- uint64_t GetRuntimeDataCount() { return runtimeDataCount_; }218+ uint64_t GetRuntimeDataCount() { return runtimeDataCount; }
213- uint64_t GetIndexFinished() { return indexFinished_; }219+ uint64_t GetIndexFinished() { return indexFinished; }
214- uint64_t GetIndexPending() { return indexPending_; }220+ uint64_t GetIndexPending() { return indexPending; }
215- uint64_t GetIndexCurrent() { return indexFinished_ + 1; }221+ uint64_t GetIndexCurrent() { return indexFinished + 1; }
216 222 
217 uint64_t GetIndexPendingIndex() { return GetIndexPending() % GetRuntimeDataCount(); }223 uint64_t GetIndexPendingIndex() { return GetIndexPending() % GetRuntimeDataCount(); }
218 224 
219- uint8_t* GetRuntimeData(uint64_t index) { return &data_[runtimeDataSize_ * (index % runtimeDataCount_)]; }225+ uint8_t* GetRuntimeData(uint64_t index) { return &data_[runtimeDataSize * (index % runtimeDataCount)]; }
220 uint8_t* GetRuntimeData() { return &data_[0]; }226 uint8_t* GetRuntimeData() { return &data_[0]; }
221 uint8_t* GetRuntimeDataCurrent() { return GetRuntimeData(GetIndexCurrent()); }227 uint8_t* GetRuntimeDataCurrent() { return GetRuntimeData(GetIndexCurrent()); }
222 uint8_t* GetRuntimeDataPending() { return GetRuntimeData(GetIndexPending()); }228 uint8_t* GetRuntimeDataPending() { return GetRuntimeData(GetIndexPending()); }
@@ -230,14 +236,7 @@ public:
230 return sizeof(RuntimeDataRingBufferHead) + GetAlignedSize(runtimeDataSize) * runtimeDataCount;236 return sizeof(RuntimeDataRingBufferHead) + GetAlignedSize(runtimeDataSize) * runtimeDataCount;
231 }237 }
232 238 
233-private:239+public:
234- uint64_t runtimeDataSize_;
235- uint64_t runtimeDataCount_;
236- ArchInfo archInfo_{ArchInfo::DAV_2201};
237- 
238- /* ringbuffer's end and begin */
239- std::atomic<uint64_t> indexFinished_;
240- std::atomic<uint64_t> indexPending_;
241 unsigned char data_[0];240 unsigned char data_[0];
242};241};
243 242 
@@ -396,6 +396,27 @@ DynFuncHeader* DeviceWorkspaceAllocator::AllocateDynFuncData(uint64_t size)
396 return header;396 return header;
397}397}
398 398 
399+npu::tile_fwk::DrcoGlobalReadyQueue* DeviceWorkspaceAllocator::AllocateDrcoGlobalReadyQueue(uint64_t size)
400+{
401+ WsAllocation allocation = ControlFlowAllocateSlab(devProg_, size,
402+ SlabAlloc(size, WsAicpuSlabMemType::GLOBAL_READY_QUE));
403+ return allocation.As<npu::tile_fwk::DrcoGlobalReadyQueue>();
404+}
405+ 
406+npu::tile_fwk::PerCorePendingQueue* DeviceWorkspaceAllocator::AllocatePerCorePendingQueue(uint64_t size)
407+{
408+ WsAllocation allocation = ControlFlowAllocateSlab(devProg_, size,
409+ SlabAlloc(size, WsAicpuSlabMemType::PER_CORE_PENDING_QUE));
410+ return allocation.As<npu::tile_fwk::PerCorePendingQueue>();
411+}
412+ 
413+npu::tile_fwk::DrcoLocalReadyQueue* DeviceWorkspaceAllocator::AllocateDrcoLocalReadyQueue(uint64_t size)
414+{
415+ WsAllocation allocation = ControlFlowAllocateSlab(devProg_, size,
416+ SlabAlloc(size, WsAicpuSlabMemType::LOCAL_READY_QUE));
417+ return allocation.As<npu::tile_fwk::DrcoLocalReadyQueue>();
418+}
419+ 
399void DeviceWorkspaceAllocator::ResetAicpuMemCounter()420void DeviceWorkspaceAllocator::ResetAicpuMemCounter()
400{421{
401#if DEBUG_MEM_DUMP_LEVEL >= DEBUG_MEM_DUMP_FULL422#if DEBUG_MEM_DUMP_LEVEL >= DEBUG_MEM_DUMP_FULL
@@ -814,7 +835,7 @@ uint32_t DeviceWorkspaceAllocator::ShmemWaitUntilCacheSlabMemObjSize()
814 return 0;835 return 0;
815}836}
816 837 
817-uint32_t DeviceWorkspaceAllocator::DuppedStitchSlabMemObjSize() { return sizeof(struct DevAscendFunctionDuppedStitch); }838+uint32_t DeviceWorkspaceAllocator::DuppedStitchSlabMemObjSize() { return sizeof(DevAscendFunctionDuppedStitch); }
818 839 
819uint32_t DeviceWorkspaceAllocator::ReadyQueSlabMemObjSize()840uint32_t DeviceWorkspaceAllocator::ReadyQueSlabMemObjSize()
820{841{
@@ -839,6 +860,27 @@ uint32_t DeviceWorkspaceAllocator::WrapQueSlabMemObjSize()
839 }860 }
840}861}
841 862 
863+uint32_t DeviceWorkspaceAllocator::PerCorePendingQueSlabMemObjSize()
864+{
865+ return sizeof(npu::tile_fwk::PerCorePendingQueue) + devProg_->stitchFunctionsize * sizeof(uint32_t);
866+}
867+ 
868+uint32_t DeviceWorkspaceAllocator::LocalReadyQueSlabMemObjSize()
869+{
870+ return sizeof(npu::tile_fwk::DrcoLocalReadyQueue) + devProg_->stitchFunctionsize * sizeof(uint32_t);
871+}
872+ 
873+uint32_t DeviceWorkspaceAllocator::GlobalReadyQueSlabMemObjSize()
874+{
875+ return sizeof(npu::tile_fwk::DrcoGlobalReadyQueue) + devProg_->stitchFunctionsize * sizeof(uint32_t);
876+}
877+ 
878+uint32_t DeviceWorkspaceAllocator::PredCountSlabMemObjSize()
879+{
880+ // predCount and executedTaskCount
881+ return sizeof(int32_t) + devProg_->stitchFunctionsize * sizeof(int32_t);
882+}
883+ 
842/* 根据当前算子的业务模型分析计算出slab 管理内存页大小, 基于当前可评估的所有内存类型的最大值评估 */884/* 根据当前算子的业务模型分析计算出slab 管理内存页大小, 基于当前可评估的所有内存类型的最大值评估 */
843uint32_t DeviceWorkspaceAllocator::CalcAicpuMetaSlabAlloctorSlabMemObjmaxSize()885uint32_t DeviceWorkspaceAllocator::CalcAicpuMetaSlabAlloctorSlabMemObjmaxSize()
844{886{
@@ -917,7 +959,23 @@ bool DeviceWorkspaceAllocator::DeviceTaskMemTryRecycle()
917 return true;959 return true;
918 }960 }
919 961 
962+ if (!deviceTask->taskStageAllocMem.canFree.load(std::memory_order_relaxed)) {
963+ auto* dynFuncHeader = deviceTask->dynFuncDataList;
964+ if (dynFuncHeader != nullptr) {
965+ auto* rootFuncList = deviceTask->drcoRootFuncList;
966+ if (rootFuncList != nullptr && (rootFuncList->totalTaskCount == 0 ||
967+ (rootFuncList->executedTaskCount != nullptr &&
968+ __atomic_load_n(rootFuncList->executedTaskCount, __ATOMIC_ACQUIRE) >=
969+ rootFuncList->totalTaskCount))) {
970+ deviceTask->taskStageAllocMem.canFree.store(true, std::memory_order_release);
971+ }
972+ }
973+ }
974+ 
920 if (deviceTask->taskStageAllocMem.canFree.load(std::memory_order_relaxed)) {975 if (deviceTask->taskStageAllocMem.canFree.load(std::memory_order_relaxed)) {
976+ if (deviceTask->taskStageAllocMem.ctrlNotFreeFlag != nullptr) {
977+ deviceTask->taskStageAllocMem.ctrlNotFreeFlag->store(false, std::memory_order_release);
978+ }
921 // recycle slab alloc memory979 // recycle slab alloc memory
922 metadataAllocators_.generalSlab.FreeStageAllocMem(deviceTask->taskStageAllocMem.generalMetadataStageMem);980 metadataAllocators_.generalSlab.FreeStageAllocMem(deviceTask->taskStageAllocMem.generalMetadataStageMem);
923 metadataAllocators_.stitchSlab.FreeStageAllocMem(deviceTask->taskStageAllocMem.stitchStageMem);981 metadataAllocators_.stitchSlab.FreeStageAllocMem(deviceTask->taskStageAllocMem.stitchStageMem);
@@ -332,6 +332,12 @@ public:
332 332 
333 DynFuncHeader* AllocateDynFuncData(uint64_t size);333 DynFuncHeader* AllocateDynFuncData(uint64_t size);
334 334 
335+ npu::tile_fwk::DrcoGlobalReadyQueue* AllocateDrcoGlobalReadyQueue(uint64_t size);
336+ 
337+ npu::tile_fwk::PerCorePendingQueue* AllocatePerCorePendingQueue(uint64_t size);
338+ 
339+ npu::tile_fwk::DrcoLocalReadyQueue* AllocateDrcoLocalReadyQueue(uint64_t size);
340+ 
335 void ResetAicpuMemCounter();341 void ResetAicpuMemCounter();
336 342 
337 void RewindMemoryDumper();343 void RewindMemoryDumper();
@@ -402,6 +408,14 @@ private:
402 408 
403 uint32_t WrapQueSlabMemObjSize();409 uint32_t WrapQueSlabMemObjSize();
404 410 
411+ uint32_t PerCorePendingQueSlabMemObjSize();
412+ 
413+ uint32_t LocalReadyQueSlabMemObjSize();
414+ 
415+ uint32_t GlobalReadyQueSlabMemObjSize();
416+ 
417+ uint32_t PredCountSlabMemObjSize();
418+ 
405 uint32_t (DeviceWorkspaceAllocator::*slabMemObjSizeFunc[ToUnderlying(WsAicpuSlabMemType::SLAB_MEM_TYPE_BUTT)])() = {419 uint32_t (DeviceWorkspaceAllocator::*slabMemObjSizeFunc[ToUnderlying(WsAicpuSlabMemType::SLAB_MEM_TYPE_BUTT)])() = {
406 &DeviceWorkspaceAllocator::DevFunctionDuppedSlabMemObjSize,420 &DeviceWorkspaceAllocator::DevFunctionDuppedSlabMemObjSize,
407 &DeviceWorkspaceAllocator::DynFuncDataSlabMemObjSize,421 &DeviceWorkspaceAllocator::DynFuncDataSlabMemObjSize,
@@ -412,6 +426,10 @@ private:
412 &DeviceWorkspaceAllocator::ReadyQueSlabMemObjSize,426 &DeviceWorkspaceAllocator::ReadyQueSlabMemObjSize,
413 &DeviceWorkspaceAllocator::DieReadyQueSlabMemObjSize,427 &DeviceWorkspaceAllocator::DieReadyQueSlabMemObjSize,
414 &DeviceWorkspaceAllocator::WrapQueSlabMemObjSize,428 &DeviceWorkspaceAllocator::WrapQueSlabMemObjSize,
429+ &DeviceWorkspaceAllocator::PerCorePendingQueSlabMemObjSize,
430+ &DeviceWorkspaceAllocator::LocalReadyQueSlabMemObjSize,
431+ &DeviceWorkspaceAllocator::GlobalReadyQueSlabMemObjSize,
432+ &DeviceWorkspaceAllocator::PredCountSlabMemObjSize,
415 &DeviceWorkspaceAllocator::DuppedStitchSlabMemObjSize,433 &DeviceWorkspaceAllocator::DuppedStitchSlabMemObjSize,
416 };434 };
417 435 
@@ -41,6 +41,16 @@ struct DynDeviceTask : DynDeviceTaskBase {
41 return static_cast<uint32_t>(coreType);41 return static_cast<uint32_t>(coreType);
42 }42 }
43 43 
44+ static uint32_t GetGlobalTaskReadyQueueIndexByCoreType(CoreType coreType)
45+ {
46+ if (coreType == CoreType::AIC) {
47+ return DRCO_QUEUE_AIC;
48+ } else if (coreType == CoreType::AIV) {
49+ return DRCO_QUEUE_AIV;
50+ }
51+ return static_cast<uint32_t>(-1);
52+ }
53+ 
44 DynDeviceTask(DeviceWorkspaceAllocator& allocator)54 DynDeviceTask(DeviceWorkspaceAllocator& allocator)
45 {55 {
46 InitDevTaskShell(devTask);56 InitDevTaskShell(devTask);
@@ -254,16 +264,25 @@ const uint64_t DEVICE_TASK_QUEUE_SIZE = sizeof(DeviceTaskCtrlQueue);
254 264 
255const uint64_t DEVICE_SHM_SIZE = DEV_ARGS_SIZE + DEVICE_TASK_CTRL_POOL_SIZE;265const uint64_t DEVICE_SHM_SIZE = DEV_ARGS_SIZE + DEVICE_TASK_CTRL_POOL_SIZE;
256 266 
267+static inline uint64_t FillDeviceRuntimeSize(uint64_t& offset, uint64_t size)
268+{
269+ uint64_t result = offset;
270+ offset += size;
271+ return result;
272+}
273+ 
257static inline void FillDeviceRuntimeOffset(DevAscendProgram* devProg, uint64_t count)274static inline void FillDeviceRuntimeOffset(DevAscendProgram* devProg, uint64_t count)
258{275{
259 DeviceRuntimeOffset& offset = devProg->deviceRuntimeOffset;276 DeviceRuntimeOffset& offset = devProg->deviceRuntimeOffset;
260 277 
261- offset.startArgsOffset = 0;278+ uint64_t off = 0;
262- offset.taskCtrlPoolOffset = offset.startArgsOffset + DEV_ARGS_SIZE;279+ offset.startArgsOffset = FillDeviceRuntimeSize(off, DEV_ARGS_SIZE);
263- offset.taskQueueOffset = offset.taskCtrlPoolOffset + DEVICE_TASK_CTRL_POOL_SIZE;280+ offset.taskCtrlPoolOffset = FillDeviceRuntimeSize(off, DEVICE_TASK_CTRL_POOL_SIZE);
264- offset.generalOffset = offset.taskQueueOffset + DEVICE_TASK_QUEUE_SIZE * devProg->devArgs.scheCpuNum;281+ offset.taskQueueOffset = FillDeviceRuntimeSize(off, DEVICE_TASK_QUEUE_SIZE * devProg->devArgs.scheCpuNum);
265- offset.stitchPoolOffset = offset.generalOffset + devProg->memBudget.metadata.general;282+ offset.deviceTaskReadyQueueOffset = FillDeviceRuntimeSize(off, sizeof(npu::tile_fwk::DrcoDeviceTaskReadyQueue));
266- offset.size = offset.stitchPoolOffset + devProg->memBudget.metadata.stitchPool;283+ offset.generalOffset = FillDeviceRuntimeSize(off, devProg->memBudget.metadata.general);
284+ offset.stitchPoolOffset = FillDeviceRuntimeSize(off, devProg->memBudget.metadata.stitchPool);
285+ offset.size = off;
267 offset.count = count;286 offset.count = count;
268}287}
269 288 
@@ -248,6 +248,25 @@ static inline void CallSubFuncTask(uint64_t funcIdx, npu::tile_fwk::CoreFuncPara
248 funcIdx, param, gmStackAddr, hcclContext, taskStat);248 funcIdx, param, gmStackAddr, hcclContext, taskStat);
249}249}
250 250 
251+template <typename T, typename V>
252+static inline T atomicAdd(__gm__ T* address, V value)
253+{
254+ return __atomic_fetch_add(address, static_cast<T>(value), __ATOMIC_RELAXED);
255+}
256+ 
257+template <typename T>
258+static inline T atomicCAS(__gm__ T* address, T compare, T value)
259+{
260+ __atomic_compare_exchange_n(address, &compare, value, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED);
261+ return compare;
262+}
263+ 
264+template <typename T>
265+static inline T atomicExch(__gm__ T* address, T value)
266+{
267+ return __atomic_exchange_n(address, value, __ATOMIC_RELAXED);
268+}
269+ 
251#define __HAS_SUB_FUNC__270#define __HAS_SUB_FUNC__
252// don't need head file in emulation.271// don't need head file in emulation.
253#define __HEAD_FILE__ stdint.h272#define __HEAD_FILE__ stdint.h
@@ -0,0 +1,274 @@
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 test_dev_encode_program_ctrlflow_cache.cpp
13+ * \brief Unit tests for the aicore-resolve (drco) branches in DevControlFlowCache.
14+ */
15+#include <gtest/gtest.h>
16+#include <array>
17+#include <cstring>
18+#include <memory>
19+#include <vector>
20+ 
21+#define private public
22+#define protected public
23+#include "machine/device/dynamic/context/device_task_context.h"
24+#include "machine/utils/dynamic/dev_workspace.h"
25+#include "machine/utils/dynamic/device_task.h"
26+#include "machine/utils/dynamic/dev_encode_program_ctrlflow_cache.h"
27+#include "machine/utils/dynamic/dev_encode_function_dupped_data.h"
28+#include "machine/utils/queues.h"
29+#include "interface/machine/device/tilefwk/aikernel_device_task.h"
30+#include "interface/configs/config_manager.h"
31+#include "tilefwk/tilefwk.h"
32+ 
33+using namespace npu::tile_fwk;
34+using namespace npu::tile_fwk::dynamic;
35+ 
36+namespace {
37+ 
38+constexpr size_t kCtrlCacheSize = 512 * 1024;
39+ 
40+// A host-side DrcoRootFuncList that mimics what InitDrcoRootFuncList builds:
41+// all per-core/local queues are backed by real memory, except the last entry of
42+// each array which stays null to exercise the null-continue branches.
43+struct DrcoQueueFixture {
44+ DrcoRootFuncList root{};
45+ std::vector<uint8_t> perCoreStorage;
46+ std::vector<uint8_t> localStorage;
47+ uint32_t execCount = 0;
48+ 
49+ void Build(uint32_t coreFunctionCnt = 8)
50+ {
51+ const size_t perCoreBytes = sizeof(PerCorePendingQueue) + 16 * sizeof(LeafTaskId);
52+ const size_t localBytes = sizeof(DrcoLocalReadyQueue);
53+ perCoreStorage.assign(MAX_AICORE_NUM_FOR_QUEUE * perCoreBytes, 0);
54+ localStorage.assign(NUM_CORE_TYPES * NUM_LOCAL_GROUPS * localBytes, 0);
55+ for (uint32_t i = 0; i < MAX_AICORE_NUM_FOR_QUEUE; ++i) {
56+ if (i == MAX_AICORE_NUM_FOR_QUEUE - 1) {
57+ root.perCorePendingQueueArray[i] = nullptr;
58+ continue;
59+ }
60+ root.perCorePendingQueueArray[i] = reinterpret_cast<PerCorePendingQueue*>(perCoreStorage.data() +
61+ i * perCoreBytes);
62+ }
63+ for (uint32_t ct = 0; ct < NUM_CORE_TYPES; ++ct) {
64+ for (uint32_t i = 0; i < NUM_LOCAL_GROUPS; ++i) {
65+ if (ct == NUM_CORE_TYPES - 1 && i == NUM_LOCAL_GROUPS - 1) {
66+ root.localReadyQueueArray[ct][i] = nullptr;
67+ continue;
68+ }
69+ root.localReadyQueueArray[ct][i] = reinterpret_cast<DrcoLocalReadyQueue*>(
70+ localStorage.data() + (ct * NUM_LOCAL_GROUPS + i) * localBytes);
71+ }
72+ }
73+ root.totalTaskCount = coreFunctionCnt;
74+ root.executedTaskCount = &execCount;
75+ }
76+};
77+ 
78+// Sets up the three ready queues (AIV/AIC/AICPU) on a DynDeviceTask.
79+void SetupReadyQueues(DynDeviceTask* dyntask, std::array<std::array<uint32_t, 16>, READY_QUEUE_SIZE>& elemBuf,
80+ std::array<std::unique_ptr<ReadyCoreFunctionQueue>, READY_QUEUE_SIZE>& queue)
81+{
82+ for (size_t i = 0; i < READY_QUEUE_SIZE; ++i) {
83+ queue[i] = std::make_unique<ReadyCoreFunctionQueue>(16, elemBuf[i].data());
84+ dyntask->readyQueue[i] = queue[i].get();
85+ }
86+}
87+ 
88+// Builds a DynFuncHeader with funcNum entries followed by the DynFuncData array.
89+void SetupDynFuncHeader(DynDeviceTask* dyntask,
90+ std::array<uint8_t, sizeof(DynFuncHeader) + 8 * sizeof(DynFuncData)>& hdrBuf,
91+ uint32_t funcNum = 1)
92+{
93+ auto* header = reinterpret_cast<DynFuncHeader*>(hdrBuf.data());
94+ header->seqNo = 0;
95+ header->funcNum = funcNum;
96+ header->funcSize = static_cast<uint32_t>(sizeof(DynFuncHeader) + funcNum * sizeof(DynFuncData));
97+ dyntask->dynFuncDataList = header;
98+}
99+ 
100+// Builds a minimal DevAscendFunctionDuppedData with one leaf op and no stitches.
101+DevAscendFunctionDuppedData* SetupDuppedData(std::array<uint8_t, 1024>& dupBuf, uint32_t opCount = 1)
102+{
103+ auto* duppedData = reinterpret_cast<DevAscendFunctionDuppedData*>(dupBuf.data());
104+ duppedData->source_ = nullptr;
105+ duppedData->operationList_.size = opCount;
106+ duppedData->operationList_.predCountBase = static_cast<uint32_t>(sizeof(DevAscendFunctionDuppedData));
107+ duppedData->operationList_.stitchCount = 0;
108+ return duppedData;
109+}
110+ 
111+void SetupCtrlCache(DevControlFlowCache& ctrl, std::vector<uint8_t>& cacheBuf, size_t cacheSize = kCtrlCacheSize)
112+{
113+ cacheBuf.assign(cacheSize, 0);
114+ ctrl.cacheData = DevRelocVector<uint8_t>(static_cast<int>(cacheSize), cacheBuf.data());
115+ ctrl.cacheDataOffset = 0;
116+}
117+ 
118+} // namespace
119+ 
120+TEST(CtrlFlowCacheDrcoUt, PredCountDataRestore_CoversDrcoPredCount)
121+{
122+ DeviceWorkspaceAllocator workspace;
123+ auto dyntask = std::make_unique<DynDeviceTask>(workspace);
124+ 
125+ std::array<uint8_t, sizeof(DynFuncHeader) + 8 * sizeof(DynFuncData)> hdrBuf{};
126+ SetupDynFuncHeader(dyntask.get(), hdrBuf, 1);
127+ 
128+ std::array<uint8_t, 1024> dupBuf{};
129+ DynFuncDataCache& cache = dyntask->dynFuncDataCacheList[0];
130+ cache.duppedData = SetupDuppedData(dupBuf, 1);
131+ cache.predCount = nullptr;
132+ cache.calleeList = nullptr;
133+ cache.devFunc = nullptr;
134+ 
135+ dyntask->dynFuncDataBackupList[0] = DynFuncDataBackup{};
136+ std::array<uint8_t, 64> predCountBackup{};
137+ dyntask->dynFuncDataBackupList[0].predCountBackup = reinterpret_cast<predcount_t*>(predCountBackup.data());
138+ 
139+ std::array<uint8_t, 64> predCountDest{};
140+ dyntask->dynFuncDataList->At(0).drcoRootFuncData.predCount = reinterpret_cast<int32_t*>(predCountDest.data());
141+ 
142+ std::vector<uint8_t> cacheBuf;
143+ DevControlFlowCache ctrl;
144+ SetupCtrlCache(ctrl, cacheBuf);
145+ 
146+ ctrl.PredCountDataRestore(dyntask.get());
147+ SUCCEED();
148+}
149+ 
150+TEST(CtrlFlowCacheDrcoUt, ReadyQueueDataBackupRestore_WithDrco)
151+{
152+ DeviceWorkspaceAllocator workspace;
153+ auto dyntask = std::make_unique<DynDeviceTask>(workspace);
154+ dyntask->devTask.coreFunctionCnt = 8;
155+ 
156+ DrcoQueueFixture drco;
157+ drco.Build();
158+ // mark one per-core queue non-empty so the backup memcpy path uses real size
159+ drco.root.perCorePendingQueueArray[3]->size = 1;
160+ drco.root.perCorePendingQueueArray[3]->taskList[0] = MakeTaskID(2, 0);
161+ dyntask->drcoRootFuncList = &drco.root;
162+ 
163+ std::array<std::array<uint32_t, 16>, READY_QUEUE_SIZE> elemBuf{};
164+ std::array<std::unique_ptr<ReadyCoreFunctionQueue>, READY_QUEUE_SIZE> queue{};
165+ SetupReadyQueues(dyntask.get(), elemBuf, queue);
166+ 
167+ const int aivIdx = DynDeviceTask::GetReadyQueueIndexByCoreType(CoreType::AIV);
168+ const int aicIdx = DynDeviceTask::GetReadyQueueIndexByCoreType(CoreType::AIC);
169+ queue[aivIdx]->UnsafeEnqueue(MakeTaskID(0, 1));
170+ queue[aivIdx]->UnsafeEnqueue(MakeTaskID(0, 2));
171+ queue[aicIdx]->UnsafeEnqueue(MakeTaskID(1, 1));
172+ 
173+ std::vector<uint8_t> cacheBuf;
174+ DevControlFlowCache ctrl;
175+ SetupCtrlCache(ctrl, cacheBuf);
176+ 
177+ ctrl.ReadyQueueDataBackup(dyntask.get());
178+ ASSERT_NE(dyntask->readyQueueBackup, nullptr);
179+ 
180+ ctrl.ReadyQueueDataRestore(dyntask.get(), 4);
181+ SUCCEED();
182+ 
183+ EXPECT_EQ(dyntask->devTask.coreFunctionCnt, 8U);
184+ EXPECT_EQ(drco.root.perCorePendingQueueArray[0]->size, 1U);
185+ uint32_t aivRouted = 0;
186+ for (uint32_t i = 4; i < 4 + 8; ++i) {
187+ aivRouted += drco.root.perCorePendingQueueArray[i]->size;
188+ }
189+ EXPECT_EQ(aivRouted, 2U);
190+ EXPECT_EQ(*drco.root.executedTaskCount, 0U);
191+}
192+ 
193+TEST(CtrlFlowCacheDrcoUt, DieReadyQueueDataBackupRestore_WithDrco)
194+{
195+ DeviceWorkspaceAllocator workspace;
196+ auto dyntask = std::make_unique<DynDeviceTask>(workspace);
197+ dyntask->devTask.coreFunctionCnt = 8;
198+ 
199+ DrcoQueueFixture drco;
200+ drco.Build();
201+ dyntask->drcoRootFuncList = &drco.root;
202+ 
203+ std::array<std::array<uint32_t, 16>, DIE_NUM> bufAiv{};
204+ std::array<std::array<uint32_t, 16>, DIE_NUM> bufAic{};
205+ std::array<std::unique_ptr<ReadyCoreFunctionQueue>, DIE_NUM> qAiv;
206+ std::array<std::unique_ptr<ReadyCoreFunctionQueue>, DIE_NUM> qAic;
207+ for (uint32_t i = 0; i < DIE_NUM; ++i) {
208+ qAiv[i] = std::make_unique<ReadyCoreFunctionQueue>(16, bufAiv[i].data());
209+ qAic[i] = std::make_unique<ReadyCoreFunctionQueue>(16, bufAic[i].data());
210+ dyntask->devTask.dieReadyFunctionQue.readyDieAivCoreFunctionQue[i] = reinterpret_cast<uint64_t>(qAiv[i].get());
211+ dyntask->devTask.dieReadyFunctionQue.readyDieAicCoreFunctionQue[i] = reinterpret_cast<uint64_t>(qAic[i].get());
212+ qAiv[i]->UnsafeEnqueue(MakeTaskID(i, 1));
213+ qAic[i]->UnsafeEnqueue(MakeTaskID(i, 2));
214+ }
215+ 
216+ std::vector<uint8_t> cacheBuf;
217+ DevControlFlowCache ctrl;
218+ SetupCtrlCache(ctrl, cacheBuf);
219+ 
220+ ctrl.DieReadyQueueDataBackup(dyntask.get());
221+ ASSERT_NE(dyntask->dieReadyQueueBackup, nullptr);
222+ 
223+ ctrl.DieReadyQueueDataRestore(dyntask.get(), 4);
224+ SUCCEED();
225+ 
226+ EXPECT_EQ(drco.root.perCorePendingQueueArray[0]->size, 1U);
227+ EXPECT_EQ(drco.root.perCorePendingQueueArray[2]->size, 1U);
228+ EXPECT_EQ(drco.root.perCorePendingQueueArray[4]->size, 1U);
229+ EXPECT_EQ(drco.root.perCorePendingQueueArray[8]->size, 1U);
230+}
231+ 
232+TEST(CtrlFlowCacheDrcoUt, TaskAddrRelocProgramAndCtrlCache_WithDrco)
233+{
234+ DeviceWorkspaceAllocator workspace;
235+ auto dyntask = std::make_unique<DynDeviceTask>(workspace);
236+ dyntask->devTask.coreFunctionCnt = 8;
237+ 
238+ DrcoQueueFixture drco;
239+ drco.Build();
240+ drco.root.globalReadyQueueList[DRCO_QUEUE_AIV].ptr = reinterpret_cast<DrcoGlobalReadyQueue*>(0x8);
241+ dyntask->drcoRootFuncList = &drco.root;
242+ 
243+ std::array<std::array<uint32_t, 16>, READY_QUEUE_SIZE> elemBuf{};
244+ std::array<std::unique_ptr<ReadyCoreFunctionQueue>, READY_QUEUE_SIZE> queue{};
245+ SetupReadyQueues(dyntask.get(), elemBuf, queue);
246+ 
247+ std::array<uint8_t, sizeof(DynFuncHeader) + 8 * sizeof(DynFuncData)> hdrBuf{};
248+ SetupDynFuncHeader(dyntask.get(), hdrBuf, 1);
249+ 
250+ std::array<uint8_t, 1024> dupBuf{};
251+ DynFuncDataCache& cache = dyntask->dynFuncDataCacheList[0];
252+ cache.duppedData = SetupDuppedData(dupBuf, 1);
253+ cache.predCount = nullptr;
254+ cache.calleeList = nullptr;
255+ cache.devFunc = nullptr;
256+ dyntask->dynFuncDataBackupList[0] = DynFuncDataBackup{};
257+ 
258+ std::vector<uint8_t> cacheBuf;
259+ DevControlFlowCache ctrl;
260+ SetupCtrlCache(ctrl, cacheBuf);
261+ 
262+ ctrl.ReadyQueueDataBackup(dyntask.get());
263+ ASSERT_NE(dyntask->readyQueueBackup, nullptr);
264+ // Force the non-null reloc branch for the global ready queue backup.
265+ dyntask->readyQueueBackup->globalReadyQueueList[0].ptr = reinterpret_cast<DrcoGlobalReadyQueue*>(0x10);
266+ 
267+ DeviceTaskCache entry;
268+ entry.dynTaskBase = dyntask.get();
269+ ctrl.deviceTaskCacheList = DevRelocVector<DeviceTaskCache>(1, &entry);
270+ ctrl.deviceTaskCount = 1;
271+ 
272+ ctrl.TaskAddrRelocProgramAndCtrlCache(0, 0, 0, 0);
273+ SUCCEED();
274+}
@@ -40,6 +40,7 @@
40#include "tilefwk/data_type.h"40#include "tilefwk/data_type.h"
41#include "tilefwk/platform.h"41#include "tilefwk/platform.h"
42#include "tilefwk/tilefwk.h"42#include "tilefwk/tilefwk.h"
43+#include "interface/machine/device/tilefwk/aikernel_device_task.h"
43 44 
44using namespace npu::tile_fwk;45using namespace npu::tile_fwk;
45using namespace npu::tile_fwk::dynamic;46using namespace npu::tile_fwk::dynamic;
@@ -947,3 +948,138 @@ TEST_F(TestDeviceTaskContext, DeviceTaskCtrl_NextSameIterTaskCtrl)
947 ctrl.nextSameIterTaskCtrl.store(reinterpret_cast<uint64_t>(&other), std::memory_order_release);948 ctrl.nextSameIterTaskCtrl.store(reinterpret_cast<uint64_t>(&other), std::memory_order_release);
948 EXPECT_EQ(ctrl.NextSameIterTaskCtrl(), &other);949 EXPECT_EQ(ctrl.NextSameIterTaskCtrl(), &other);
949}950}
951+ 
952+TEST_F(TestDeviceTaskContext, InitReadyQueues_EnableAicoreResolve_CreatesDrcoRootFuncList)
953+{
954+ DeviceTaskContext taskContext;
955+ DevStartArgsBase startArgs;
956+ constexpr size_t kControlFlowCacheSize = 16 * 1024 * 1024;
957+ auto controlFlowCacheBuf = std::make_unique<uint8_t[]>(kControlFlowCacheSize);
958+ 
959+ DevAscendProgram devProg;
960+ CreateMockDevAscendProgram(&devProg, ArchInfo::DAV_3510);
961+ devProg.stitchFunctionsize = 100;
962+ devProg.devArgs.enableAicoreResolve = true;
963+ devProg.controlFlowCache.cacheData = DevRelocVector<uint8_t>(kControlFlowCacheSize, controlFlowCacheBuf.get());
964+ devProg.controlFlowCache.isRecording = true;
965+ 
966+ DeviceWorkspaceAllocator workspace(&devProg);
967+ taskContext.InitAllocator(&devProg, workspace, &startArgs);
968+ 
969+ auto dyntask = std::make_unique<DynDeviceTask>(workspace);
970+ CreateMockDynDeviceTask(dyntask.get(), 16);
971+ 
972+ ReadyCoreFunctionQueue* queues[READY_QUEUE_SIZE] = {};
973+ EXPECT_EQ(taskContext.InitReadyQueues(dyntask.get(), &devProg, queues), DEVICE_MACHINE_OK);
974+ 
975+ ASSERT_NE(dyntask->drcoRootFuncList, nullptr);
976+ EXPECT_EQ(dyntask->drcoRootFuncList->totalTaskCount, 16U);
977+ ASSERT_NE(dyntask->drcoRootFuncList->executedTaskCount, nullptr);
978+ EXPECT_EQ(*dyntask->drcoRootFuncList->executedTaskCount, 0U);
979+ for (size_t i = 0; i < npu::tile_fwk::DRCO_QUEUE_MAX; ++i) {
980+ EXPECT_NE(dyntask->drcoRootFuncList->globalReadyQueueList[i].ptr, nullptr);
981+ }
982+ for (uint32_t i = 0; i < npu::tile_fwk::MAX_AICORE_NUM_FOR_QUEUE; ++i) {
983+ EXPECT_NE(dyntask->drcoRootFuncList->perCorePendingQueueArray[i], nullptr);
984+ }
985+ for (uint32_t ct = 0; ct < npu::tile_fwk::NUM_CORE_TYPES; ++ct) {
986+ for (uint32_t i = 0; i < npu::tile_fwk::NUM_LOCAL_GROUPS; ++i) {
987+ EXPECT_NE(dyntask->drcoRootFuncList->localReadyQueueArray[ct][i], nullptr);
988+ }
989+ }
990+ for (size_t i = 0; i < READY_QUEUE_SIZE; ++i) {
991+ EXPECT_NE(dyntask->readyQueue[i], nullptr);
992+ }
993+}
994+ 
995+TEST_F(TestDeviceTaskContext, DispatchReadyQueueToCores_DistributesTasks)
996+{
997+ DeviceTaskContext taskContext;
998+ DevStartArgsBase startArgs;
999+ constexpr size_t kControlFlowCacheSize = 16 * 1024 * 1024;
1000+ auto controlFlowCacheBuf = std::make_unique<uint8_t[]>(kControlFlowCacheSize);
1001+ 
1002+ DevAscendProgram devProg;
1003+ CreateMockDevAscendProgram(&devProg, ArchInfo::DAV_3510);
1004+ devProg.stitchFunctionsize = 100;
1005+ devProg.devArgs.enableAicoreResolve = true;
1006+ devProg.devArgs.nrValidAic = 4;
1007+ devProg.controlFlowCache.cacheData = DevRelocVector<uint8_t>(kControlFlowCacheSize, controlFlowCacheBuf.get());
1008+ devProg.controlFlowCache.isRecording = true;
1009+ 
1010+ DeviceWorkspaceAllocator workspace(&devProg);
1011+ taskContext.InitAllocator(&devProg, workspace, &startArgs);
1012+ 
1013+ auto dyntask = std::make_unique<DynDeviceTask>(workspace);
1014+ CreateMockDynDeviceTask(dyntask.get(), 16);
1015+ 
1016+ ReadyCoreFunctionQueue* queues[READY_QUEUE_SIZE] = {};
1017+ ASSERT_EQ(taskContext.InitReadyQueues(dyntask.get(), &devProg, queues), DEVICE_MACHINE_OK);
1018+ 
1019+ const int aivIdx = DynDeviceTask::GetReadyQueueIndexByCoreType(CoreType::AIV);
1020+ const int aicIdx = DynDeviceTask::GetReadyQueueIndexByCoreType(CoreType::AIC);
1021+ dyntask->readyQueue[aivIdx]->UnsafeEnqueue(MakeTaskID(0, 0));
1022+ dyntask->readyQueue[aivIdx]->UnsafeEnqueue(MakeTaskID(1, 1));
1023+ dyntask->readyQueue[aicIdx]->UnsafeEnqueue(MakeTaskID(2, 2));
1024+ 
1025+ taskContext.DispatchReadyQueueToCores(dyntask.get(), &devProg);
1026+ 
1027+ auto* root = dyntask->drcoRootFuncList;
1028+ ASSERT_NE(root, nullptr);
1029+ bool aicRouted = false;
1030+ bool aivRouted = false;
1031+ for (uint32_t i = 0; i < devProg.devArgs.nrValidAic; ++i) {
1032+ if (root->perCorePendingQueueArray[i]->size > 0) {
1033+ aicRouted = true;
1034+ }
1035+ }
1036+ for (uint32_t i = devProg.devArgs.nrValidAic; i < devProg.devArgs.nrValidAic * 3; ++i) {
1037+ if (root->perCorePendingQueueArray[i]->size > 0) {
1038+ aivRouted = true;
1039+ }
1040+ }
1041+ EXPECT_TRUE(aicRouted);
1042+ EXPECT_TRUE(aivRouted);
1043+}
1044+ 
1045+TEST_F(TestDeviceTaskContext, DispatchDieReadyQueueToCores_DistributesDieTasks)
1046+{
1047+ DeviceTaskContext taskContext;
1048+ DevStartArgsBase startArgs;
1049+ constexpr size_t kControlFlowCacheSize = 16 * 1024 * 1024;
1050+ auto controlFlowCacheBuf = std::make_unique<uint8_t[]>(kControlFlowCacheSize);
1051+ 
1052+ DevAscendProgram devProg;
1053+ CreateMockDevAscendProgram(&devProg, ArchInfo::DAV_3510);
1054+ devProg.stitchFunctionsize = 100;
1055+ devProg.devArgs.enableAicoreResolve = true;
1056+ devProg.devArgs.nrValidAic = 4;
1057+ devProg.controlFlowCache.cacheData = DevRelocVector<uint8_t>(kControlFlowCacheSize, controlFlowCacheBuf.get());
1058+ devProg.controlFlowCache.isRecording = true;
1059+ 
1060+ DeviceWorkspaceAllocator workspace(&devProg);
1061+ taskContext.InitAllocator(&devProg, workspace, &startArgs);
1062+ 
1063+ auto dyntask = std::make_unique<DynDeviceTask>(workspace);
1064+ CreateMockDynDeviceTask(dyntask.get(), 16);
1065+ 
1066+ ReadyCoreFunctionQueue* queues[READY_QUEUE_SIZE] = {};
1067+ ASSERT_EQ(taskContext.InitReadyQueues(dyntask.get(), &devProg, queues), DEVICE_MACHINE_OK);
1068+ 
1069+ taskContext.InitDieReadyQueues(dyntask.get(), &devProg);
1070+ auto dieAivQueue = reinterpret_cast<ReadyCoreFunctionQueue*>(
1071+ dyntask->devTask.dieReadyFunctionQue.readyDieAivCoreFunctionQue[0]);
1072+ auto dieAicQueue = reinterpret_cast<ReadyCoreFunctionQueue*>(
1073+ dyntask->devTask.dieReadyFunctionQue.readyDieAicCoreFunctionQue[0]);
1074+ ASSERT_NE(dieAivQueue, nullptr);
1075+ ASSERT_NE(dieAicQueue, nullptr);
1076+ dieAivQueue->UnsafeEnqueue(MakeTaskID(0, 0));
1077+ dieAicQueue->UnsafeEnqueue(MakeTaskID(1, 1));
1078+ 
1079+ taskContext.DispatchDieReadyQueueToCores(dyntask.get(), &devProg);
1080+ 
1081+ auto* root = dyntask->drcoRootFuncList;
1082+ ASSERT_NE(root, nullptr);
1083+ EXPECT_GT(root->perCorePendingQueueArray[0]->size, 0U);
1084+ EXPECT_GT(root->perCorePendingQueueArray[4]->size, 0U);
1085+}
@@ -26,10 +26,10 @@ TEST_F(DevEncodeFunctionStitchTest, Stitch_PushBack_IncreasesSize)
26{26{
27 DevAscendFunctionDuppedStitch stitch;27 DevAscendFunctionDuppedStitch stitch;
28 stitch.InitWithNext(nullptr);28 stitch.InitWithNext(nullptr);
29- stitch.PushBack(100);29+ stitch.SafePushBack(100);
30 EXPECT_EQ(stitch.Size(), 1u);30 EXPECT_EQ(stitch.Size(), 1u);
31 EXPECT_EQ(stitch.At(0), 100u);31 EXPECT_EQ(stitch.At(0), 100u);
32- stitch.PushBack(200);32+ stitch.SafePushBack(200);
33 EXPECT_EQ(stitch.Size(), 2u);33 EXPECT_EQ(stitch.Size(), 2u);
34 EXPECT_EQ(stitch.At(1), 200u);34 EXPECT_EQ(stitch.At(1), 200u);
35}35}
@@ -38,9 +38,9 @@ TEST_F(DevEncodeFunctionStitchTest, Stitch_ForEach_VisitsAll)
38{38{
39 DevAscendFunctionDuppedStitch stitch;39 DevAscendFunctionDuppedStitch stitch;
40 stitch.InitWithNext(nullptr);40 stitch.InitWithNext(nullptr);
41- stitch.PushBack(10);41+ stitch.SafePushBack(10);
42- stitch.PushBack(20);42+ stitch.SafePushBack(20);
43- stitch.PushBack(30);43+ stitch.SafePushBack(30);
44 std::vector<uint32_t> visited;44 std::vector<uint32_t> visited;
45 stitch.ForEach([&](uint32_t id) { visited.push_back(id); });45 stitch.ForEach([&](uint32_t id) { visited.push_back(id); });
46 EXPECT_EQ(visited.size(), 3u);46 EXPECT_EQ(visited.size(), 3u);
@@ -146,7 +146,7 @@ TEST_F(DevWorkspaceTest, DynDevTaskSlabMemObjSize_ReturnsSizeof)
146TEST_F(DevWorkspaceTest, DuppedStitchSlabMemObjSize_ReturnsSizeof)146TEST_F(DevWorkspaceTest, DuppedStitchSlabMemObjSize_ReturnsSizeof)
147{147{
148 DeviceWorkspaceAllocator allocator;148 DeviceWorkspaceAllocator allocator;
149- EXPECT_EQ(allocator.DuppedStitchSlabMemObjSize(), sizeof(struct DevAscendFunctionDuppedStitch));149+ EXPECT_EQ(allocator.DuppedStitchSlabMemObjSize(), sizeof(DevAscendFunctionDuppedStitch));
150}150}
151 151 
152TEST_F(DevWorkspaceTest, ShmemWaitUntilCacheSlabMemObjSize_NoAicpuTask)152TEST_F(DevWorkspaceTest, ShmemWaitUntilCacheSlabMemObjSize_NoAicpuTask)