Merged
feat(machine): Cut ctrlflow cache IO Reloc overhead via host arena #7025
LordOfMysteriesAdd on Oct 20
feat(machine): Cut ctrlflow cache IO Reloc overhead via host arena #7025
Merged
LordOfMysteriesAdd on Oct 20
Total: 33 files changed+807-484
@@ -59,7 +59,10 @@ struct RtDevBinary {
59};59};
60 60 
61struct RtHostInputInfo {61struct RtHostInputInfo {
62+ // device 上待刷新的位置, launch时。rt
63+ // 会申请Device内存并将该device内存地址刷新到hostArgs中,该参数描述就是这个待刷新的位置的偏移
62 uint32_t addrOffset;64 uint32_t addrOffset;
65+ // 数据偏移区,指向的数据去需要拷贝到device侧, 该参数用于指定数据区基于hostArgs的地址偏移(主要描述input 信息)
63 uint32_t dataOffset;66 uint32_t dataOffset;
64};67};
65 68 
@@ -112,7 +112,7 @@ extern "C" [aicore] void {KernelName}(CoreFuncParam* param, int64_t GMStackBase,
112 std::string entry = R"!!!(112 std::string entry = R"!!!(
113extern "C" __global__ [aicore] void PvModelKernelEntry(__gm__ npu::tile_fwk::DynFuncHeader *funcHeader, __gm__ uint64_t *opAttrs) {113extern "C" __global__ [aicore] void PvModelKernelEntry(__gm__ npu::tile_fwk::DynFuncHeader *funcHeader, __gm__ uint64_t *opAttrs) {
114 __gm__ npu::tile_fwk::DynFuncData *funcData = (__gm__ npu::tile_fwk::DynFuncData*)(funcHeader + 1);114 __gm__ npu::tile_fwk::DynFuncData *funcData = (__gm__ npu::tile_fwk::DynFuncData*)(funcHeader + 1);
115- CoreFuncParam param = {funcData, funcHeader, opAttrs, funcData->exprTbl};115+ CoreFuncParam param = {funcData, funcHeader, opAttrs, funcData->exprTbl, 0, nullptr, funcData->rawTensorAddr};
116 {KernelName}(&param, funcHeader->stackWorkSpaceAddr, (__gm__ int64_t *)funcHeader->startArgs->commContexts, (__gm__ FedProfLeafTaskProf*)NULL);116 {KernelName}(&param, funcHeader->stackWorkSpaceAddr, (__gm__ int64_t *)funcHeader->startArgs->commContexts, (__gm__ FedProfLeafTaskProf*)NULL);
117}117}
118 118 
@@ -259,10 +259,16 @@ INLINE void ExecDynCoreFunctionKernel(ExecuteContext* ctx, uint32_t taskId, uint
259 dcci((__gm__ uint8_t*)funcData + 128, SINGLE_CACHE_LINE, CACHELINE_OUT);259 dcci((__gm__ uint8_t*)funcData + 128, SINGLE_CACHE_LINE, CACHELINE_OUT);
260#endif260#endif
261 auto opAttrs = &funcData->opAttrs[funcData->opAtrrOffsets[npu::tile_fwk::TaskID(taskId)]];261 auto opAttrs = &funcData->opAttrs[funcData->opAtrrOffsets[npu::tile_fwk::TaskID(taskId)]];
262+ // Valid offset selects the host-args arena. Stitch and no-arena launches keep Invalid.
263+ __gm__ uint64_t* rawTensorAddr = funcData->rawTensorAddr;
264+ if (funcData->ioAddressArenaOffset != npu::tile_fwk::kIoAddressArenaOffsetInvalid) {
265+ rawTensorAddr = ctx->ioAddressArena + funcData->ioAddressArenaOffset;
266+ }
262#if ENABLE_AICORE_PRINT267#if ENABLE_AICORE_PRINT
263- CoreFuncParam param = {funcData, cachedTask.header, opAttrs, funcData->exprTbl, taskId, ctx->logger.Context()};268+ CoreFuncParam param = {funcData, cachedTask.header, opAttrs, funcData->exprTbl,
269+ taskId, ctx->logger.Context(), rawTensorAddr};
264#else270#else
265- CoreFuncParam param = {funcData, cachedTask.header, opAttrs, funcData->exprTbl, taskId, nullptr};271+ CoreFuncParam param = {funcData, cachedTask.header, opAttrs, funcData->exprTbl, taskId, nullptr, rawTensorAddr};
266#endif272#endif
267 273 
268#ifdef __ENABLE_MAIN_BLOCK274#ifdef __ENABLE_MAIN_BLOCK
@@ -319,17 +325,6 @@ INLINE void InitCtx(ExecuteContext* ctx, __gm__ FedProfPerCoreProf* metric,
319 return;325 return;
320}326}
321 327 
322-INLINE void ExecCoreFunctionKernel(ExecuteContext* ctx, uint32_t curTaskIdx, uint8_t& lastMixResourceType)
323-{
324- UNUSED(ctx);
325- UNUSED(curTaskIdx);
326- UNUSED(lastMixResourceType);
327-#ifdef __HAS_SUB_FUNC__
328- ExecDynCoreFunctionKernel(ctx, curTaskIdx, lastMixResourceType);
329- return;
330-#endif
331-}
332- 
333INLINE uint32_t WaitWaveSignal(__gm__ KernelArgs* args)328INLINE uint32_t WaitWaveSignal(__gm__ KernelArgs* args)
334{329{
335 AICORE_TIMEOUT_CHECK_BEGIN(t0, loop_count);330 AICORE_TIMEOUT_CHECK_BEGIN(t0, loop_count);
@@ -363,7 +358,6 @@ INLINE void KernelEntry(int64_t ffts_addr, int64_t inputs, int64_t outputs, int6
363#endif358#endif
364 uint64_t start = get_sys_cnt();359 uint64_t start = get_sys_cnt();
365 UNUSED(ffts_addr);360 UNUSED(ffts_addr);
366- UNUSED(inputs);
367 UNUSED(outputs);361 UNUSED(outputs);
368 UNUSED(workspace);362 UNUSED(workspace);
369 UNUSED(tilingdata);363 UNUSED(tilingdata);
@@ -381,6 +375,8 @@ INLINE void KernelEntry(int64_t ffts_addr, int64_t inputs, int64_t outputs, int6
381 ctx.args = args;375 ctx.args = args;
382 ctx.blockIdx = blockIdx;376 ctx.blockIdx = blockIdx;
383 ctx.perCoreProf = perCoreProf;377 ctx.perCoreProf = perCoreProf;
378+ // Host Materialize piggybacks the absolute IO table on AICore launch args (`inputs`).
379+ ctx.ioAddressArena = (inputs != 0) ? reinterpret_cast<__gm__ uint64_t*>(inputs) : nullptr;
384 __gm__ DevDfxArgs* devDfxAddr = (__gm__ DevDfxArgs*)devArgs->devDfxArgAddr;380 __gm__ DevDfxArgs* devDfxAddr = (__gm__ DevDfxArgs*)devArgs->devDfxArgAddr;
385 ctx.devTaskProfStatus.profEnabled = devDfxAddr->isOpenPerfTrace != 0;381 ctx.devTaskProfStatus.profEnabled = devDfxAddr->isOpenPerfTrace != 0;
386 uint8_t aicoreLogLevel = static_cast<uint8_t>(AicoreLogLevel::NONE);382 uint8_t aicoreLogLevel = static_cast<uint8_t>(AicoreLogLevel::NONE);
@@ -403,7 +399,9 @@ INLINE void KernelEntry(int64_t ffts_addr, int64_t inputs, int64_t outputs, int6
403 uint32_t curTaskIdx;399 uint32_t curTaskIdx;
404 uint32_t lastTaskIdx = AICORE_TASK_INIT;400 uint32_t lastTaskIdx = AICORE_TASK_INIT;
405 uint32_t lastRegHighVal = 0;401 uint32_t lastRegHighVal = 0;
402+#ifdef __HAS_SUB_FUNC__
406 uint8_t lastMixResourceType = static_cast<uint8_t>(MixResourceType::MIX_UNKNOWN);403 uint8_t lastMixResourceType = static_cast<uint8_t>(MixResourceType::MIX_UNKNOWN);
404+#endif
407 405 
408 FedProfDevTaskProfRecord(INVALID_DEV_TASK_ID, ctx.devTaskProfStatus.devTaskProf, PERF_TRACE_CORE_INIT);406 FedProfDevTaskProfRecord(INVALID_DEV_TASK_ID, ctx.devTaskProfStatus.devTaskProf, PERF_TRACE_CORE_INIT);
409 407 
@@ -458,7 +456,9 @@ INLINE void KernelEntry(int64_t ffts_addr, int64_t inputs, int64_t outputs, int6
458 456 
459 SendRegAck(curTaskIdx);457 SendRegAck(curTaskIdx);
460 PmuTestBegin(ctx.profLevel);458 PmuTestBegin(ctx.profLevel);
461- ExecCoreFunctionKernel(&ctx, curTaskIdx, lastMixResourceType);459+#ifdef __HAS_SUB_FUNC__
460+ ExecDynCoreFunctionKernel(&ctx, curTaskIdx, lastMixResourceType);
461+#endif
462 PmuTestEnd(ctx.profLevel);462 PmuTestEnd(ctx.profLevel);
463 SendRegFinish(curTaskIdx);463 SendRegFinish(curTaskIdx);
464 lastTaskIdx = curTaskIdx;464 lastTaskIdx = curTaskIdx;
@@ -44,6 +44,8 @@ struct ExecuteContext {
44 int32_t blockIdx;44 int32_t blockIdx;
45 __gm__ FedProfPerCoreProf* perCoreProf{nullptr};45 __gm__ FedProfPerCoreProf* perCoreProf{nullptr};
46 volatile __gm__ ParallelDevTask* parallelDevTask{nullptr};46 volatile __gm__ ParallelDevTask* parallelDevTask{nullptr};
47+ /* Absolute IO address table from AICore launch host-args (KernelEntry inputs). */
48+ __gm__ uint64_t* ioAddressArena{nullptr};
47 uint32_t curLeafTaskParallelIdx{0};49 uint32_t curLeafTaskParallelIdx{0};
48 uint32_t seqNo{0};50 uint32_t seqNo{0};
49 uint32_t profLevel{0};51 uint32_t profLevel{0};
@@ -244,7 +244,9 @@ struct DrcoEntryState {
244 __gm__ npu::tile_fwk::RuntimeDataRingBufferHeadData* runtimeDataRingBufferHeadData;244 __gm__ npu::tile_fwk::RuntimeDataRingBufferHeadData* runtimeDataRingBufferHeadData;
245 __gm__ npu::tile_fwk::DevStartArgsBase* base;245 __gm__ npu::tile_fwk::DevStartArgsBase* base;
246 __gm__ DrcoDeviceTaskReadyQueue* deviceTaskReadyQueue;246 __gm__ DrcoDeviceTaskReadyQueue* deviceTaskReadyQueue;
247+#ifdef __HAS_SUB_FUNC__
247 uint8_t lastMixResourceType;248 uint8_t lastMixResourceType;
249+#endif
248 250 
249 uint32_t selfReadyQueueSize;251 uint32_t selfReadyQueueSize;
250 uint32_t selfReadyQueue[SELF_QUEUE_SIZE];252 uint32_t selfReadyQueue[SELF_QUEUE_SIZE];
@@ -1921,7 +1923,9 @@ INLINE void InitDrcoEntry(DrcoEntryState* state, int64_t cfgdata)
1921 }1923 }
1922 1924 
1923 set_mask_norm();1925 set_mask_norm();
1926+#ifdef __HAS_SUB_FUNC__
1924 state->lastMixResourceType = static_cast<uint8_t>(MixResourceType::MIX_UNKNOWN);1927 state->lastMixResourceType = static_cast<uint8_t>(MixResourceType::MIX_UNKNOWN);
1928+#endif
1925 1929 
1926 FedProfDevTaskProfRecord(INVALID_DEV_TASK_ID, state->ctx.devTaskProfStatus.devTaskProf, PERF_TRACE_CORE_INIT);1930 FedProfDevTaskProfRecord(INVALID_DEV_TASK_ID, state->ctx.devTaskProfStatus.devTaskProf, PERF_TRACE_CORE_INIT);
1927 1931 
@@ -1996,7 +2000,9 @@ INLINE void ExecLeafFunction(DrcoEntryState* state, uint32_t taskId)
1996{2000{
1997 TraceEvent(state, taskId, EVENT_LEAF_START());2001 TraceEvent(state, taskId, EVENT_LEAF_START());
1998 2002 
1999- ExecCoreFunctionKernel(&state->ctx, taskId, state->lastMixResourceType);2003+#ifdef __HAS_SUB_FUNC__
2004+ ExecDynCoreFunctionKernel(&state->ctx, taskId, state->lastMixResourceType);
2005+#endif
2000 2006 
2001 TraceEvent(state, taskId, EVENT_LEAF_END());2007 TraceEvent(state, taskId, EVENT_LEAF_END());
2002}2008}
@@ -2196,13 +2202,13 @@ INLINE void KernelEntryDrco(int64_t ffts_addr, int64_t inputs, int64_t outputs,
2196 int64_t cfgdata)2202 int64_t cfgdata)
2197{2203{
2198 UNUSED(ffts_addr);2204 UNUSED(ffts_addr);
2199- UNUSED(inputs);
2200 UNUSED(outputs);2205 UNUSED(outputs);
2201 UNUSED(workspace);2206 UNUSED(workspace);
2202 UNUSED(tilingdata);2207 UNUSED(tilingdata);
2203 2208 
2204 DrcoEntryState state = {};2209 DrcoEntryState state = {};
2205 InitDrcoEntry(&state, cfgdata);2210 InitDrcoEntry(&state, cfgdata);
2211+ state.ctx.ioAddressArena = (inputs != 0) ? reinterpret_cast<__gm__ uint64_t*>(inputs) : nullptr;
2206 TraceInit(&state);2212 TraceInit(&state);
2207 2213 
2208 bool isFirstTask = true;2214 bool isFirstTask = true;
@@ -234,11 +234,11 @@ INLINE uint64_t GetTensorAddr(CoreFuncParam* ctx, int idx)
234 if constexpr (mode == 2) { // workspace234 if constexpr (mode == 2) { // workspace
235 return func->workspaceAddr + desc->offsetOrIndex;235 return func->workspaceAddr + desc->offsetOrIndex;
236 } else if constexpr (mode == 3) { // root function incast/outcast 内存236 } else if constexpr (mode == 3) { // root function incast/outcast 内存
237- return func->rawTensorAddr[desc->offsetOrIndex] & RAW_TENSOR_ADDR_MASK;237+ return ctx->rawTensorAddr[desc->offsetOrIndex] & RAW_TENSOR_ADDR_MASK;
238 } else {238 } else {
239 return (desc->location == npu::tile_fwk::RAW_TENSOR_LOCATION_LOCAL) ?239 return (desc->location == npu::tile_fwk::RAW_TENSOR_LOCATION_LOCAL) ?
240 func->workspaceAddr + desc->offsetOrIndex :240 func->workspaceAddr + desc->offsetOrIndex :
241- func->rawTensorAddr[desc->offsetOrIndex] & RAW_TENSOR_ADDR_MASK;241+ ctx->rawTensorAddr[desc->offsetOrIndex] & RAW_TENSOR_ADDR_MASK;
242 }242 }
243}243}
244 244 
@@ -42,6 +42,8 @@ struct CoreFuncParam {
42 __gm__ uint64_t* exprTbl;42 __gm__ uint64_t* exprTbl;
43 uint32_t taskId;43 uint32_t taskId;
44 LogContext* ctx;44 LogContext* ctx;
45+ /* Per-leaf table base: arena+elemIndex, or embedded rawTensorAddr when no arena. */
46+ __gm__ uint64_t* rawTensorAddr;
45};47};
46 48 
47/*49/*
@@ -26,6 +26,9 @@ namespace npu::tile_fwk {
26struct DevStartArgsBase;26struct DevStartArgsBase;
27 27 
28constexpr uint64_t DRCO_ROOT_FUNC_MEMORY_REUSE_STITCHED_BIT = ((uint64_t)1) << (uint64_t)60;28constexpr uint64_t DRCO_ROOT_FUNC_MEMORY_REUSE_STITCHED_BIT = ((uint64_t)1) << (uint64_t)60;
29+/* DynFuncData.ioAddressArenaOffset sentinel: not laid out into the per-launch arena
30+ * (device stitch, or a no-arena launch after the embedded table is refreshed). */
31+constexpr uint32_t kIoAddressArenaOffsetInvalid = 0xFFFFFFFFu;
29 32 
30struct DrcoRootFuncData {33struct DrcoRootFuncData {
31 // funcDynamicDataOffset 打包一个 u64(偏移本身平移不变):34 // funcDynamicDataOffset 打包一个 u64(偏移本身平移不变):
@@ -58,6 +61,8 @@ struct DynFuncData {
58 uint64_t rawTensorAddrSize;61 uint64_t rawTensorAddrSize;
59 uint64_t workspaceAddr;62 uint64_t workspaceAddr;
60 __gm__ int* cceBinaryIndexList;63 __gm__ int* cceBinaryIndexList;
64+ /* Element index into the per-launch AICore host-args IO arena (uint64_t units, not bytes). */
65+ uint32_t ioAddressArenaOffset;
61};66};
62 67 
63struct DynFuncBin {68struct DynFuncBin {
@@ -129,8 +129,19 @@ void DeviceExecuteContext::GELaunchRunCached(DevStartArgs* startArgs, PushTaskEn
129 for (size_t index = 0; index < devProg->ctrlFlowCacheAnchor->deviceTaskCount; index++) {129 for (size_t index = 0; index < devProg->ctrlFlowCacheAnchor->deviceTaskCount; index++) {
130 DynDeviceTask* dynTask = reinterpret_cast<DynDeviceTask*>(130 DynDeviceTask* dynTask = reinterpret_cast<DynDeviceTask*>(
131 devProg->ctrlFlowCacheAnchor->deviceTaskCacheList[index].dynTaskBase);131 devProg->ctrlFlowCacheAnchor->deviceTaskCacheList[index].dynTaskBase);
132- devProg->ctrlFlowCacheAnchor->RelocIncastOutcastTask(static_cast<uint32_t>(index), 0,132+ // Arena path: host Materialize fills the AICore launch-args table; the leaf reads
133- startArgs->contextWorkspaceAddr, startArgs);133+ // arena + ioAddressArenaOffset. Emulation and aicore-model copies clear
134+ // ioAddressArenaBytes so this fallback refreshes the embedded table and marks offsets Invalid.
135+ // AICPU still reads the embedded rawTensorAddr (dump / shmem / schema). Skip Reloc only when
136+ // nothing on the device needs that table refreshed for this launch.
137+ const bool arenaLive = (devProg->ctrlFlowCacheAnchor->ioAddressArenaBytes != 0);
138+ const bool needEmbeddedIo = (devProg->devArgs.hostPid != 0) || (startArgs->commGroupNum != 0);
139+ if (arenaLive && !needEmbeddedIo) {
140+ dynTask->dynFuncDataList->startArgs = startArgs;
141+ } else {
142+ devProg->ctrlFlowCacheAnchor->RelocIncastOutcastTask(static_cast<uint32_t>(index), 0,
143+ startArgs->contextWorkspaceAddr, startArgs);
144+ }
134 devProg->ctrlFlowCacheAnchor->PredCountPingPongSwap(dynTask);145 devProg->ctrlFlowCacheAnchor->PredCountPingPongSwap(dynTask);
135 if (startArgs->devProg->devArgs.enableAicoreResolve) {146 if (startArgs->devProg->devArgs.enableAicoreResolve) {
136 devProg->ctrlFlowCacheAnchor->DrcoPredCountPingPongSwap(dynTask);147 devProg->ctrlFlowCacheAnchor->DrcoPredCountPingPongSwap(dynTask);
@@ -45,6 +45,8 @@ inline void FillOneDynFuncData(DynFuncData* dyndata, DevAscendFunctionDupped& du
45 dyndata->rawTensorAddr = reinterpret_cast<uint64_t*>(&dupFunc.GetIncastAddress(0));45 dyndata->rawTensorAddr = reinterpret_cast<uint64_t*>(&dupFunc.GetIncastAddress(0));
46 dyndata->rawTensorDesc = source->GetRawTensorDesc(0);46 dyndata->rawTensorDesc = source->GetRawTensorDesc(0);
47 dyndata->workspaceAddr = dupFunc.RuntimeWorkspace();47 dyndata->workspaceAddr = dupFunc.RuntimeWorkspace();
48+ // Stitch / non-layout funcs must not participate in the host arena leaf resolve.
49+ dyndata->ioAddressArenaOffset = npu::tile_fwk::kIoAddressArenaOffsetInvalid;
48 DEV_IF_NONDEVICE50 DEV_IF_NONDEVICE
49 {51 {
50 dyndata->exprNum = source->expressionList.size();52 dyndata->exprNum = source->expressionList.size();
@@ -34,13 +34,16 @@
34#include "machine/runtime/runner/runtime_utils.h"34#include "machine/runtime/runner/runtime_utils.h"
35#include "machine/runtime/runner/load_aicpu_op.h"35#include "machine/runtime/runner/load_aicpu_op.h"
36#include "machine/runtime/runner/host_prof.h"36#include "machine/runtime/runner/host_prof.h"
37+#include "machine/runtime/runner/aicore_launch_args.h"
37#include "machine/runtime/launcher/device_launcher.h"38#include "machine/runtime/launcher/device_launcher.h"
38#include "machine/runtime/launcher/cell_match_dynamic.h"39#include "machine/runtime/launcher/cell_match_dynamic.h"
40+#include "machine/runtime/memory_utils/device_memory_utils.h"
41+#include "machine/utils/dynamic/dev_encode_program_ctrlflow_cache.h"
42+#include "machine/utils/dynamic/dev_encode_tensor.h"
39 43 
40namespace npu::tile_fwk::dynamic {44namespace npu::tile_fwk::dynamic {
41 45 
42namespace {46namespace {
43-// aicpu launch primitive (topology from devProg), kept here so device_launcher stays free of bundle code.
44int BundleLaunchAicpu(AicpuLaunchDesc& launchDesc, DevAscendProgram* devProg)47int BundleLaunchAicpu(AicpuLaunchDesc& launchDesc, DevAscendProgram* devProg)
45{48{
46 auto ctrlStream = GetStreamContext().GetCtrlStream();49 auto ctrlStream = GetStreamContext().GetCtrlStream();
@@ -76,7 +79,6 @@ int BundleLaunchAicpu(AicpuLaunchDesc& launchDesc, DevAscendProgram* devProg)
76 return ret;79 return ret;
77}80}
78 81 
79-// aicore launch primitive: bundle always runs debugEnable=false, so the debug-sync branch is omitted.
80int BundleLaunchAicore(AclRtStream aicoreStream, void* kernel, RtArgsEx& rtArgs, RtTaskCfgInfo& rtTaskCfg,82int BundleLaunchAicore(AclRtStream aicoreStream, void* kernel, RtArgsEx& rtArgs, RtTaskCfgInfo& rtTaskCfg,
81 DevAscendProgram* devProg)83 DevAscendProgram* devProg)
82{84{
@@ -104,62 +106,47 @@ std::string MakeAicpuOpName(const std::string& displayName, uint64_t bundleKey)
104 const size_t prefixSize = maxNameSize - std::strlen(keySuffix);106 const size_t prefixSize = maxNameSize - std::strlen(keySuffix);
105 return displayName.substr(0, prefixSize) + keySuffix;107 return displayName.substr(0, prefixSize) + keySuffix;
106}108}
107-} // namespace
108 109 
109-int LaunchBundleKernelOnce(const std::vector<uint8_t>& devProgBinary, void* binHandle, uint64_t cacheKey,110+size_t BundleAicpuArgsBytes(size_t tensorCount, size_t cellMatchPatchCount)
110- const std::vector<DeviceTensorData>& tensorList,
111- const std::vector<uint8_t>& hostCtrlFlowCache, const std::string& displayName,
112- const std::vector<DevDynamicCellMatchStridePatch>& cellMatchStridePatches,
113- void* workspaceAddr, RtStream aicoreStream, bool streamSynchronize,
114- const DeviceLauncherConfig& config)
115{111{
116- (void)config;112+ return sizeof(AiCpuArgs) + 2 * sizeof(int64_t) + tensorCount * sizeof(DevTensorData) + sizeof(uint64_t) +
117- MACHINE_LOGI("Kernel Launch (bundle)");113+ cellMatchPatchCount * sizeof(DevDynamicCellMatchStridePatch);
118- if (binHandle == nullptr) {114+}
119- MACHINE_LOGE(HostLauncherErr::REGISTER_KERNEL_FAILED, "[kernel-bundle] null kernel bin handle.");
120- return -1;
121- }
122- aicoreStream = aicoreStream == nullptr ? GetContextAiCoreStream() : aicoreStream;
123 115 
116+int BundleInitRuntime()
117+{
124 int rc = AclInit(nullptr);118 int rc = AclInit(nullptr);
125 if (rc != 0 && rc != ACLRT_ERROR_REPEAT_INITIALIZE) {119 if (rc != 0 && rc != ACLRT_ERROR_REPEAT_INITIALIZE) {
126 return rc;120 return rc;
127 }121 }
128 DeviceLauncher::CheckAscendDriverVersionOnboard();122 DeviceLauncher::CheckAscendDriverVersionOnboard();
129 CheckDeviceId();123 CheckDeviceId();
124+ return 0;
125+}
130 126 
131- auto* devProg = reinterpret_cast<DevAscendProgram*>(const_cast<uint8_t*>(devProgBinary.data()));127+AiCpuArgs* BundleBuildAicpuArgs(std::vector<int64_t>& aicpuArgBuf, size_t tensorCount, size_t cellMatchPatchCount,
132- 128+ const std::string& aicpuOpName)
133- // Control-flow cache: copied host->device once per bundle, reused across launches (freed at process exit).129+{
134- uint8_t* devCtrlCache = bundle::KernelBundleDevCache::Instance().GetOrCopy(cacheKey, hostCtrlFlowCache);130+ const size_t argSize = BundleAicpuArgsBytes(tensorCount, cellMatchPatchCount);
135- 131+ aicpuArgBuf.assign((argSize + sizeof(int64_t) - 1) / sizeof(int64_t), 0);
136- // Build AiCpuArgs buffer: one unified operand list ([nTensors, 0], outputs folded in), then the trailing
137- // cell-match stride patch count + patches (device applies via ApplyDynamicCellMatchDescPatchesFromLaunchArgs).
138- const uint64_t tensorCount = tensorList.size();
139- const size_t argSize = sizeof(AiCpuArgs) + 2 * sizeof(int64_t) + tensorCount * sizeof(DevTensorData) +
140- sizeof(uint64_t) + cellMatchStridePatches.size() * sizeof(DevDynamicCellMatchStridePatch);
141- std::vector<int64_t> aicpuArgBuf((argSize + sizeof(int64_t) - 1) / sizeof(int64_t), 0);
142 auto* aicpuArgs = new (aicpuArgBuf.data()) AiCpuArgs();132 auto* aicpuArgs = new (aicpuArgBuf.data()) AiCpuArgs();
143 aicpuArgs->kArgs.inputs = nullptr;133 aicpuArgs->kArgs.inputs = nullptr;
144 aicpuArgs->kArgs.outputs = nullptr;134 aicpuArgs->kArgs.outputs = nullptr;
145- const std::string aicpuOpName = MakeAicpuOpName(displayName, cacheKey);
146 if (strcpy_s(aicpuArgs->opName, sizeof(aicpuArgs->opName), aicpuOpName.c_str()) != 0) {135 if (strcpy_s(aicpuArgs->opName, sizeof(aicpuArgs->opName), aicpuOpName.c_str()) != 0) {
147 MACHINE_LOGE(DevCommonErr::PARAM_CHECK_FAILED, "[kernel-bundle] invalid AICPU op name: %s",136 MACHINE_LOGE(DevCommonErr::PARAM_CHECK_FAILED, "[kernel-bundle] invalid AICPU op name: %s",
148 aicpuOpName.c_str());137 aicpuOpName.c_str());
149- return -1;138+ return nullptr;
150 }139 }
140+ return aicpuArgs;
141+}
151 142 
152- // Fill device-side kArgs: cfgdata (base-0 devProg), metadata, distributed ctx. Topology is re-derived from143+void BundleFillTensorList(AiCpuArgs* aicpuArgs, const std::vector<DeviceTensorData>& tensorList,
153- // the target platform in DeviceInitTilingData.144+ const std::vector<DevDynamicCellMatchStridePatch>& cellMatchStridePatches)
154- DeviceMemoryUtils devMem;145+{
155- DeviceLauncher::FillDeviceKernelArgs(devMem, const_cast<std::vector<uint8_t>&>(devProgBinary), aicpuArgs->kArgs,
156- std::vector<std::string>{});
157- 
158- // Fill tensor descriptors: [nTensors, 0] then the flat tensor array (kernel addresses operands by position).
159 int64_t* inputp = reinterpret_cast<int64_t*>(aicpuArgs + 1);146 int64_t* inputp = reinterpret_cast<int64_t*>(aicpuArgs + 1);
160- inputp[0] = static_cast<int64_t>(tensorCount);147+ inputp[0] = static_cast<int64_t>(tensorList.size());
161 inputp[1] = 0; // nOut: outputs are folded into tensorList148 inputp[1] = 0; // nOut: outputs are folded into tensorList
162- auto* tensorData = reinterpret_cast<DevTensorData*>(inputp + 2);149+ auto* tensorData = reinterpret_cast<DevTensorData*>(inputp + DEV_TENSOR_DATA_OFFSET);
163 for (const auto& t : tensorList) {150 for (const auto& t : tensorList) {
164 tensorData->address = reinterpret_cast<uint64_t>(t.GetAddr());151 tensorData->address = reinterpret_cast<uint64_t>(t.GetAddr());
165 tensorData->dataType = t.GetDataType();152 tensorData->dataType = t.GetDataType();
@@ -170,10 +157,12 @@ int LaunchBundleKernelOnce(const std::vector<uint8_t>& devProgBinary, void* binH
170 }157 }
171 tensorData++;158 tensorData++;
172 }159 }
173- // Trailing cell-match stride patch count (0 when empty) + patch array, after the flat tensor list.
174 WriteDynamicCellMatchStridePatchesToLaunchArgs(inputp, cellMatchStridePatches);160 WriteDynamicCellMatchStridePatchesToLaunchArgs(inputp, cellMatchStridePatches);
161+}
175 162 
176- // Per-launch kArgs (ctrl cache device ptr / workspace / monotonic round / dynamic mem budgets).163+void BundleFillPerLaunchKArgs(AiCpuArgs* aicpuArgs, DevAscendProgram* devProg, uint8_t* devCtrlCache,
164+ void* workspaceAddr, uint64_t cacheKey)
165+{
177 static std::atomic<int64_t> bundleSequence{0};166 static std::atomic<int64_t> bundleSequence{0};
178 aicpuArgs->kArgs.ctrlFlowCache = reinterpret_cast<int64_t*>(devCtrlCache);167 aicpuArgs->kArgs.ctrlFlowCache = reinterpret_cast<int64_t*>(devCtrlCache);
179 aicpuArgs->kArgs.workspace = reinterpret_cast<int64_t*>(workspaceAddr);168 aicpuArgs->kArgs.workspace = reinterpret_cast<int64_t*>(workspaceAddr);
@@ -181,41 +170,90 @@ int LaunchBundleKernelOnce(const std::vector<uint8_t>& devProgBinary, void* binH
181 aicpuArgs->kArgs.maxDynamicAssembleOutcastMem = devProg->memBudget.tensor.maxDynamicAssembleOutcastMem;170 aicpuArgs->kArgs.maxDynamicAssembleOutcastMem = devProg->memBudget.tensor.maxDynamicAssembleOutcastMem;
182 aicpuArgs->kArgs.maxDynamicCellMatchTableMem = devProg->memBudget.metadata.maxDynamicCellMatchTableMem;171 aicpuArgs->kArgs.maxDynamicCellMatchTableMem = devProg->memBudget.metadata.maxDynamicCellMatchTableMem;
183 172 
184- // Dynamic cell-match metadata pool: a standalone device buffer (size = memBudget.metadata.dynamicCellMatch,
185- // computed in EvalWorkspaceForShapes), allocated once per bundle and reused. The device (device_ctrl InitDyn)
186- // overwrites devArgs.dynamicCellMatch{Addr,Capacity} from these kArgs and inits the pool in place.
187 const uint64_t dynamicCellMatchBytes = devProg->memBudget.metadata.dynamicCellMatch;173 const uint64_t dynamicCellMatchBytes = devProg->memBudget.metadata.dynamicCellMatch;
188 uint8_t* cellMatchAddr = bundle::KernelBundleDevCache::Instance().GetOrAllocCellMatch(cacheKey,174 uint8_t* cellMatchAddr = bundle::KernelBundleDevCache::Instance().GetOrAllocCellMatch(cacheKey,
189 dynamicCellMatchBytes);175 dynamicCellMatchBytes);
190 aicpuArgs->kArgs.runtimeDynamicCellMatchAddr = reinterpret_cast<uint64_t>(cellMatchAddr);176 aicpuArgs->kArgs.runtimeDynamicCellMatchAddr = reinterpret_cast<uint64_t>(cellMatchAddr);
191 aicpuArgs->kArgs.runtimeDynamicCellMatchCapacity = cellMatchAddr != nullptr ? dynamicCellMatchBytes : 0;177 aicpuArgs->kArgs.runtimeDynamicCellMatchCapacity = cellMatchAddr != nullptr ? dynamicCellMatchBytes : 0;
178+}
192 179 
193- // Resolve the entry through PyptoRun; only the input tensor pointer needs host-args relocation.180+struct BundleAicpuLaunchState {
194- AicpuLaunchDesc aicpuLaunchDesc{};181+ std::vector<int64_t> argBuf;
195- AicpuHostInput hostInfo{};182+ AiCpuArgs* args{nullptr};
196- hostInfo.addrOffset = offsetof(AiCpuArgs, kArgs.inputs);183+ AicpuLaunchDesc launchDesc{};
197- hostInfo.dataOffset = sizeof(AiCpuArgs);184+ RtHostInputInfo hostInfo{};
198- aicpuLaunchDesc.hostInputs = &hostInfo;185+};
199- aicpuLaunchDesc.hostInputNum = 1;
200- aicpuLaunchDesc.timeout = AICPU_EXECUTE_TIMEOUT;
201- aicpuLaunchDesc.args = aicpuArgs;
202- aicpuLaunchDesc.argsSize = static_cast<uint32_t>(aicpuArgBuf.size() * sizeof(int64_t));
203 186 
204- std::vector<void*> kernelArgs(0x7, nullptr);187+bool BundlePrepareAicpuLaunch(BundleAicpuLaunchState& state, const std::vector<uint8_t>& devProgBinary,
205- RtArgsEx rtAicoreArgs;188+ DevAscendProgram* devProg, const std::vector<DeviceTensorData>& tensorList,
206- (void)memset_s(&rtAicoreArgs, sizeof(RtArgsEx), 0, sizeof(RtArgsEx));189+ const std::vector<DevDynamicCellMatchStridePatch>& cellMatchStridePatches,
207- rtAicoreArgs.args = kernelArgs.data();190+ uint8_t* devCtrlCache, void* workspaceAddr, uint64_t cacheKey,
208- rtAicoreArgs.argsSize = static_cast<uint32_t>(kernelArgs.size() * sizeof(void*));191+ const std::string& aicpuOpName)
192+{
193+ state.args = BundleBuildAicpuArgs(state.argBuf, tensorList.size(), cellMatchStridePatches.size(), aicpuOpName);
194+ if (state.args == nullptr) {
195+ return false;
196+ }
197+ DeviceMemoryUtils devMem;
198+ DeviceLauncher::FillDeviceKernelArgs(devMem, const_cast<std::vector<uint8_t>&>(devProgBinary), state.args->kArgs,
199+ std::vector<std::string>{});
200+ BundleFillTensorList(state.args, tensorList, cellMatchStridePatches);
201+ BundleFillPerLaunchKArgs(state.args, devProg, devCtrlCache, workspaceAddr, cacheKey);
209 202 
210- RtTaskCfgInfo rtTaskCfg;203+ state.hostInfo.addrOffset = offsetof(AiCpuArgs, kArgs.inputs);
211- (void)memset_s(&rtTaskCfg, sizeof(RtTaskCfgInfo), 0, sizeof(RtTaskCfgInfo));204+ state.hostInfo.dataOffset = sizeof(AiCpuArgs);
212- rtTaskCfg.schemMode = static_cast<uint8_t>(RtSchemModeType::BATCH);205+ state.launchDesc = {};
213- rtTaskCfg.localMemorySize = GetAicoreLocalMemorySize(static_cast<NPUArch>(devProg->devArgs.archInfo),206+ state.launchDesc.hostInputs = &state.hostInfo;
214- devProg->requiresSimt);207+ state.launchDesc.hostInputNum = 1;
208+ state.launchDesc.timeout = AICPU_EXECUTE_TIMEOUT;
209+ state.launchDesc.args = state.args;
210+ state.launchDesc.argsSize = static_cast<uint32_t>(state.argBuf.size() * sizeof(int64_t));
211+ return true;
212+}
215 213 
216- // Launch (mirrors KernelModule::Launch), reusing the public DeviceLauncher helpers.214+struct BundleAicoreLaunchState {
215+ std::vector<uint8_t> argBuf;
216+ RtArgsEx rtArgs{};
217+ RtHostInputInfo hostInfo{};
218+ RtTaskCfgInfo taskCfg{};
219+ DevControlFlowCache* hostCache{nullptr};
220+ size_t arenaBytes{0};
221+};
222+ 
223+void BundlePrepareAicoreArgs(BundleAicoreLaunchState& state, AiCpuArgs* aicpuArgs, DevAscendProgram* devProg,
224+ std::vector<uint8_t>& hostCtrlFlowCache, const std::string& displayName)
225+{
226+ if (!hostCtrlFlowCache.empty()) {
227+ state.hostCache = reinterpret_cast<DevControlFlowCache*>(hostCtrlFlowCache.data());
228+ state.arenaBytes = static_cast<size_t>(state.hostCache->ioAddressArenaBytes);
229+ }
230+ // Size/slots only here. Materialize stays after AICPU launch (same order as DeviceLauncher::LaunchKernel).
231+ PrepareAicoreLaunchArgsBuffer(state.argBuf, aicpuArgs, displayName.c_str(), state.arenaBytes, state.rtArgs);
232+ 
233+ (void)memset_s(&state.taskCfg, sizeof(RtTaskCfgInfo), 0, sizeof(RtTaskCfgInfo));
234+ state.taskCfg.schemMode = static_cast<uint8_t>(RtSchemModeType::BATCH);
235+ state.taskCfg.localMemorySize = GetAicoreLocalMemorySize(static_cast<NPUArch>(devProg->devArgs.archInfo),
236+ devProg->requiresSimt);
237+}
238+ 
239+void BundleMaterializeAicoreIoArena(BundleAicoreLaunchState& state, AiCpuArgs* aicpuArgs, DevAscendProgram* devProg)
240+{
241+ if (state.arenaBytes == 0 || state.hostCache == nullptr) {
242+ return;
243+ }
244+ EnsureHostCtrlFlowCacheRebased(state.hostCache, devProg);
245+ // Packed ABI: nIn/nOut come from the recording cache, not the folded [nTensors,0] launch list.
246+ FillAicoreIoAddressArenaBuffer(state.argBuf, aicpuArgs, state.hostCache,
247+ state.hostCache->inputTensorDataList.size(),
248+ state.hostCache->outputTensorDataList.size(), state.rtArgs, state.hostInfo);
249+}
250+ 
251+int BundleDispatchKernels(AclRtStream aicoreStream, void* binHandle, AicpuLaunchDesc& aicpuLaunchDesc,
252+ AiCpuArgs* aicpuArgs, DevAscendProgram* devProg, BundleAicoreLaunchState& aicoreState,
253+ bool streamSynchronize)
254+{
217 const bool isCaptureMode = DeviceLauncher::IsCaptureMode();255 const bool isCaptureMode = DeviceLauncher::IsCaptureMode();
218- rc = DeviceLauncher::LaunchSyncTask(aicoreStream, isCaptureMode, /*launchEarlyMode=*/0);256+ int rc = DeviceLauncher::LaunchSyncTask(aicoreStream, isCaptureMode, /*launchEarlyMode=*/0);
219 if (rc != RT_SUCCESS) {257 if (rc != RT_SUCCESS) {
220 return rc;258 return rc;
221 }259 }
@@ -230,12 +268,10 @@ int LaunchBundleKernelOnce(const std::vector<uint8_t>& devProgBinary, void* binH
230 return rc;268 return rc;
231 }269 }
232 270 
233- kernelArgs[0] = const_cast<char*>(displayName.c_str());271+ BundleMaterializeAicoreIoArena(aicoreState, aicpuArgs, devProg);
234- kernelArgs[4] = reinterpret_cast<int64_t*>(aicpuArgs + 1); // inputp
235- kernelArgs[5] = aicpuArgs->kArgs.cfgdata; // 5 is cfgdata
236- kernelArgs[6] = reinterpret_cast<DevTensorData*>(reinterpret_cast<int64_t*>(aicpuArgs + 1) + 2);
237 272 
238- rc = BundleLaunchAicore(aicoreStream, static_cast<RtBinHandle>(binHandle), rtAicoreArgs, rtTaskCfg, devProg);273+ rc = BundleLaunchAicore(aicoreStream, static_cast<RtBinHandle>(binHandle), aicoreState.rtArgs, aicoreState.taskCfg,
274+ devProg);
239 if (rc != RT_SUCCESS) {275 if (rc != RT_SUCCESS) {
240 MACHINE_LOGE(HostLauncherErr::REGISTER_KERNEL_FAILED, "[kernel-bundle] launch aicore failed: %d", rc);276 MACHINE_LOGE(HostLauncherErr::REGISTER_KERNEL_FAILED, "[kernel-bundle] launch aicore failed: %d", rc);
241 return rc;277 return rc;
@@ -244,6 +280,44 @@ int LaunchBundleKernelOnce(const std::vector<uint8_t>& devProgBinary, void* binH
244 if (streamSynchronize) {280 if (streamSynchronize) {
245 rc = DeviceLauncher::DynamicLaunchSynchronize(GetContextScheStream(), GetContextCtrlStream(), aicoreStream);281 rc = DeviceLauncher::DynamicLaunchSynchronize(GetContextScheStream(), GetContextCtrlStream(), aicoreStream);
246 }282 }
283+ return rc;
284+}
285+} // namespace
286+ 
287+int LaunchBundleKernelOnce(const std::vector<uint8_t>& devProgBinary, void* binHandle, uint64_t cacheKey,
288+ const std::vector<DeviceTensorData>& tensorList, std::vector<uint8_t>& hostCtrlFlowCache,
289+ const std::string& displayName,
290+ const std::vector<DevDynamicCellMatchStridePatch>& cellMatchStridePatches,
291+ void* workspaceAddr, RtStream aicoreStream, bool streamSynchronize,
292+ const DeviceLauncherConfig& config)
293+{
294+ (void)config;
295+ MACHINE_LOGI("Kernel Launch (bundle)");
296+ if (binHandle == nullptr) {
297+ MACHINE_LOGE(HostLauncherErr::REGISTER_KERNEL_FAILED, "[kernel-bundle] null kernel bin handle.");
298+ return -1;
299+ }
300+ aicoreStream = aicoreStream == nullptr ? GetContextAiCoreStream() : aicoreStream;
301+ int rc = BundleInitRuntime();
302+ if (rc != 0) {
303+ return rc;
304+ }
305+ 
306+ auto* devProg = reinterpret_cast<DevAscendProgram*>(const_cast<uint8_t*>(devProgBinary.data()));
307+ // H2D before host rebase so Materialize cannot leak absolute host pointers into device cache.
308+ uint8_t* devCtrlCache = bundle::KernelBundleDevCache::Instance().GetOrCopy(cacheKey, hostCtrlFlowCache);
309+ 
310+ BundleAicpuLaunchState aicpuState;
311+ if (!BundlePrepareAicpuLaunch(aicpuState, devProgBinary, devProg, tensorList, cellMatchStridePatches, devCtrlCache,
312+ workspaceAddr, cacheKey, MakeAicpuOpName(displayName, cacheKey))) {
313+ return -1;
314+ }
315+ 
316+ BundleAicoreLaunchState aicoreState;
317+ BundlePrepareAicoreArgs(aicoreState, aicpuState.args, devProg, hostCtrlFlowCache, displayName);
318+ 
319+ rc = BundleDispatchKernels(aicoreStream, binHandle, aicpuState.launchDesc, aicpuState.args, devProg, aicoreState,
320+ streamSynchronize);
247 MACHINE_LOGI("finish Kernel Launch (bundle).");321 MACHINE_LOGI("finish Kernel Launch (bundle).");
248 return rc;322 return rc;
249}323}
@@ -34,9 +34,11 @@ namespace npu::tile_fwk::dynamic {
34// operand list ([nTensors, 0], outputs folded in). `cellMatchStridePatches` are the per-shape patches from34// operand list ([nTensors, 0], outputs folded in). `cellMatchStridePatches` are the per-shape patches from
35// EvalWorkspaceForShapes (empty when no cell-match table), which must already have patched `devProgBinary`'s35// EvalWorkspaceForShapes (empty when no cell-match table), which must already have patched `devProgBinary`'s
36// memBudget for the launch shape. Returns 0 on success.36// memBudget for the launch shape. Returns 0 on success.
37+// `hostCtrlFlowCache` is non-const: the first arena materialize rebases the base-0 blob in place
38+// (isRelocMetaDev / isRelocDataDev), matching KernelBinary::MaterializeIoAddressArenaForAicore.
37int LaunchBundleKernelOnce(const std::vector<uint8_t>& devProgBinary, void* binHandle, uint64_t cacheKey,39int LaunchBundleKernelOnce(const std::vector<uint8_t>& devProgBinary, void* binHandle, uint64_t cacheKey,
38- const std::vector<DeviceTensorData>& tensorList,40+ const std::vector<DeviceTensorData>& tensorList, std::vector<uint8_t>& hostCtrlFlowCache,
39- const std::vector<uint8_t>& hostCtrlFlowCache, const std::string& displayName,41+ const std::string& displayName,
40 const std::vector<DevDynamicCellMatchStridePatch>& cellMatchStridePatches,42 const std::vector<DevDynamicCellMatchStridePatch>& cellMatchStridePatches,
41 void* workspaceAddr, RtStream aicoreStream, bool streamSynchronize,43 void* workspaceAddr, RtStream aicoreStream, bool streamSynchronize,
42 const DeviceLauncherConfig& config = DeviceLauncherConfig());44 const DeviceLauncherConfig& config = DeviceLauncherConfig());
@@ -255,6 +255,8 @@ int AicoreModelLauncher::AicoreModelRunOnce(Function* function, DevControlFlowCa
255 "OK" :255 "OK" :
256 "MISALIGNED");256 "MISALIGNED");
257 MemcpyS(launchCtrlFlowCache, inputCtrlCache->usedCacheSize, inputCtrlCache, inputCtrlCache->usedCacheSize);257 MemcpyS(launchCtrlFlowCache, inputCtrlCache->usedCacheSize, inputCtrlCache, inputCtrlCache->usedCacheSize);
258+ // No AICore host-args arena here. Clear the size so GELaunch refreshes the embedded table.
259+ launchCtrlFlowCache->ioAddressArenaBytes = 0;
258 }260 }
259 }261 }
260 int rc = AicoreModelLaunchOnceWithHostTensorData(function, inputDeviceDataList, outputDeviceDataList,262 int rc = AicoreModelLaunchOnceWithHostTensorData(function, inputDeviceDataList, outputDeviceDataList,
@@ -94,14 +94,13 @@ uint8_t* CtrlFlowCacheManager::FindOrBuildDevCache(KernelBinary* kernel, std::ve
94 uint64_t cachedHash = kernel->GetCachedCtrlFlowHash();94 uint64_t cachedHash = kernel->GetCachedCtrlFlowHash();
95 if (cachedHash == currentHash && kernel->GetValueDependDevCache() != nullptr) {95 if (cachedHash == currentHash && kernel->GetValueDependDevCache() != nullptr) {
96 kernel->SetCtrlFlowCacheReplay(true);96 kernel->SetCtrlFlowCacheReplay(true);
97+ kernel->BindValueDependActiveHost();
97 return kernel->GetValueDependDevCache();98 return kernel->GetValueDependDevCache();
98 }99 }
99- // Hash mismatch or first build: free old, rebuild, update hash.100+ // Hash mismatch or first build: free old, rebuild. Build commits hash, device ptr, and host mirror together.
100 kernel->FreeAndClearValueDependCache();101 kernel->FreeAndClearValueDependCache();
101 AclModeGuard guard(AclMdlRICaptureMode::RELAXED);102 AclModeGuard guard(AclMdlRICaptureMode::RELAXED);
102- auto devCache = kernel->BuildControlFlowCache(tensors, true, false);103+ auto devCache = kernel->BuildControlFlowCache(tensors, true, false, currentHash);
103- kernel->SetValueDependDevCache(devCache);
104- kernel->SetCachedCtrlFlowHash(currentHash);
105 kernel->SetCtrlFlowCacheReplay(devCache != nullptr);104 kernel->SetCtrlFlowCacheReplay(devCache != nullptr);
106 return devCache;105 return devCache;
107}106}
@@ -110,7 +109,7 @@ DevControlFlowCache* CtrlFlowCacheManager::GetHostCtrlFlowCache(KernelBinary* ke
110 std::vector<DeviceTensorData>& tensors,109 std::vector<DeviceTensorData>& tensors,
111 uint8_t* devCache, CtrlFlowCacheBlob& hostCache)110 uint8_t* devCache, CtrlFlowCacheBlob& hostCache)
112{111{
113- DevControlFlowCache* ctrlCache = FindHostCtrlFlowCache(kernel, tensors, hostCache);112+ DevControlFlowCache* ctrlCache = kernel->FindHostCtrlFlowCache(tensors, hostCache);
114 if (ctrlCache == nullptr && devCache != nullptr) {113 if (ctrlCache == nullptr && devCache != nullptr) {
115 auto devProg = reinterpret_cast<DevAscendProgram*>(114 auto devProg = reinterpret_cast<DevAscendProgram*>(
116 kernel->GetFunction()->GetDyndevAttribute()->devProgBinary.data());115 kernel->GetFunction()->GetDyndevAttribute()->devProgBinary.data());
@@ -127,38 +126,19 @@ DevControlFlowCache* CtrlFlowCacheManager::GetHostCtrlFlowCache(KernelBinary* ke
127 "MISALIGNED");126 "MISALIGNED");
128 AclModeGuard guard(AclMdlRICaptureMode::RELAXED);127 AclModeGuard guard(AclMdlRICaptureMode::RELAXED);
129 RuntimeMemcpy(hostCacheVec.data(), ctrlCacheSize, devCache, ctrlCacheSize, RtMemcpyKind::DEVICE_TO_HOST);128 RuntimeMemcpy(hostCacheVec.data(), ctrlCacheSize, devCache, ctrlCacheSize, RtMemcpyKind::DEVICE_TO_HOST);
130- AddHostCtrlFlowCache(kernel, tensors, std::move(hostCacheVec));129+ kernel->AttachHostCtrlFlowCache(tensors, std::move(hostCacheVec));
131- ctrlCache = FindHostCtrlFlowCache(kernel, tensors, hostCache);130+ ctrlCache = kernel->FindHostCtrlFlowCache(tensors, hostCache);
131+ }
132+ if (ctrlCache != nullptr) {
133+ MACHINE_LOGI("#ctrl.cache.align: site=GetHostCtrlFlowCache.copy base=%p size=%zu align64=%lu %s",
134+ static_cast<void*>(hostCache.data()), hostCache.size(),
135+ static_cast<unsigned long>(reinterpret_cast<uintptr_t>(hostCache.data()) %
136+ npu::tile_fwk::DUPPED_STITCH_NODE_ALIGN),
137+ reinterpret_cast<uintptr_t>(hostCache.data()) % npu::tile_fwk::DUPPED_STITCH_NODE_ALIGN == 0 ?
138+ "OK" :
139+ "MISALIGNED");
132 }140 }
133 return ctrlCache;141 return ctrlCache;
134}142}
135 143 
136-DevControlFlowCache* CtrlFlowCacheManager::FindHostCtrlFlowCache(KernelBinary* kernel,
137- std::vector<DeviceTensorData>& tensors,
138- CtrlFlowCacheBlob& hostCache)
139-{
140- int64_t hash = ControlFlowCache::Hash(tensors);
141- for (auto& cache : kernel->GetHostCtrlFlowCaches()) {
142- if (cache.hash == hash) {
143- hostCache = cache.hostCache;
144- // 维测:值拷贝后 data() 是新地址,必须仍然 64B 对齐(同一 allocator,故成立)
145- MACHINE_LOGI("#ctrl.cache.align: site=FindHostCtrlFlowCache.copy base=%p size=%zu align64=%lu %s",
146- static_cast<void*>(hostCache.data()), hostCache.size(),
147- static_cast<unsigned long>(reinterpret_cast<uintptr_t>(hostCache.data()) %
148- npu::tile_fwk::DUPPED_STITCH_NODE_ALIGN),
149- reinterpret_cast<uintptr_t>(hostCache.data()) % npu::tile_fwk::DUPPED_STITCH_NODE_ALIGN == 0 ?
150- "OK" :
151- "MISALIGNED");
152- return reinterpret_cast<DevControlFlowCache*>(hostCache.data());
153- }
154- }
155- return nullptr;
156-}
157- 
158-void CtrlFlowCacheManager::AddHostCtrlFlowCache(KernelBinary* kernel, std::vector<DeviceTensorData>& tensors,
159- CtrlFlowCacheBlob&& hostCache)
160-{
161- kernel->GetHostCtrlFlowCaches().emplace_back(tensors, std::move(hostCache));
162-}
163- 
164} // namespace npu::tile_fwk::dynamic144} // namespace npu::tile_fwk::dynamic
@@ -34,8 +34,12 @@ struct ControlFlowCache {
34 int64_t hash;34 int64_t hash;
35 std::vector<DeviceTensorData> inputs;35 std::vector<DeviceTensorData> inputs;
36 uint8_t* devCache{nullptr};36 uint8_t* devCache{nullptr};
37+ /* Host mirror of the same CF blob; used for per-launch IO arena Materialize. */
38+ CtrlFlowCacheBlob hostCache;
37 39 
38- ControlFlowCache(std::vector<DeviceTensorData>& datas, uint8_t* tcache) : inputs(datas), devCache(tcache)40+ ControlFlowCache(std::vector<DeviceTensorData>& datas, uint8_t* tcache,
41+ CtrlFlowCacheBlob&& hcache = CtrlFlowCacheBlob{})
42+ : inputs(datas), devCache(tcache), hostCache(std::move(hcache))
39 {43 {
40 hash = Hash(inputs);44 hash = Hash(inputs);
41 }45 }
@@ -65,17 +69,6 @@ struct ControlFlowCache {
65 }69 }
66};70};
67 71 
68-struct HostControlFlowCache {
69- int64_t hash;
70- CtrlFlowCacheBlob hostCache;
71- 
72- HostControlFlowCache(std::vector<DeviceTensorData>& datas, CtrlFlowCacheBlob&& hcache)
73- : hostCache(std::move(hcache))
74- {
75- hash = ControlFlowCache::Hash(datas);
76- }
77-};
78- 
79class CtrlFlowCacheManager {72class CtrlFlowCacheManager {
80public:73public:
81 static CtrlFlowCacheManager& Instance();74 static CtrlFlowCacheManager& Instance();
@@ -91,11 +84,6 @@ public:
91private:84private:
92 CtrlFlowCacheManager() = default;85 CtrlFlowCacheManager() = default;
93 ~CtrlFlowCacheManager() = default;86 ~CtrlFlowCacheManager() = default;
94- 
95- DevControlFlowCache* FindHostCtrlFlowCache(KernelBinary* kernel, std::vector<DeviceTensorData>& tensors,
96- CtrlFlowCacheBlob& hostCache);
97- void AddHostCtrlFlowCache(KernelBinary* kernel, std::vector<DeviceTensorData>& tensors,
98- CtrlFlowCacheBlob&& hostCache);
99};87};
100 88 
101} // namespace npu::tile_fwk::dynamic89} // namespace npu::tile_fwk::dynamic
@@ -626,7 +626,6 @@ int DeviceLauncher::LaunchKernel(AclRtStream aicoreStream, uint8_t* ctrlFlowCach
626 auto& aicpuLaunchDesc = kernel->GetAicpuLaunchDesc();626 auto& aicpuLaunchDesc = kernel->GetAicpuLaunchDesc();
627 auto& rtAicoreArgs = kernel->GetRtAicoreArgs();627 auto& rtAicoreArgs = kernel->GetRtAicoreArgs();
628 auto& rtTaskCfg = kernel->GetRtTaskCfg();628 auto& rtTaskCfg = kernel->GetRtTaskCfg();
629- auto& kernelArgs = kernel->GetKernelArgs();
630 629 
631 auto [args, argsSize] = kernel->BuildKernelArgs(tensors);630 auto [args, argsSize] = kernel->BuildKernelArgs(tensors);
632 aicpuLaunchDesc.args = args;631 aicpuLaunchDesc.args = args;
@@ -678,10 +677,8 @@ int DeviceLauncher::LaunchKernel(AclRtStream aicoreStream, uint8_t* ctrlFlowCach
678 ret = LaunchAicpuKernel(aicpuLaunchDesc, debugEnable, kernel->GetFunction(), tensors);677 ret = LaunchAicpuKernel(aicpuLaunchDesc, debugEnable, kernel->GetFunction(), tensors);
679 MACHINE_ASSERT(ret == RT_SUCCESS) << "launch aicpu failed: " << ret;678 MACHINE_ASSERT(ret == RT_SUCCESS) << "launch aicpu failed: " << ret;
680 679 
681- kernelArgs[5] = args->kArgs.cfgdata;680+ // Materialize IO arena into AICore launch host-args (lifetime matches AICore, not ctrl AICPU).
682- kernelArgs[0] = const_cast<char*>(kernel->GetKernelname().c_str());681+ kernel->MaterializeIoAddressArenaForAicore(args);
683- kernelArgs[4] = (int64_t*)(args + 1);
684- kernelArgs[6] = (DevTensorData*)((int64_t*)(args + 1) + 2);
685 ret = LaunchAicoreKernel(aicoreStream, kernel->GetKernelBin(), rtAicoreArgs, rtTaskCfg, debugEnable,682 ret = LaunchAicoreKernel(aicoreStream, kernel->GetKernelBin(), rtAicoreArgs, rtTaskCfg, debugEnable,
686 kernel->GetFunction());683 kernel->GetFunction());
687 MACHINE_ASSERT(ret == RT_SUCCESS) << "launch aicore failed: " << ret;684 MACHINE_ASSERT(ret == RT_SUCCESS) << "launch aicore failed: " << ret;
@@ -152,6 +152,8 @@ int EmulationLauncher::EmulationRunOnce(Function* function, DevControlFlowCache*
152 "OK" :152 "OK" :
153 "MISALIGNED");153 "MISALIGNED");
154 MemcpyS(launchCtrlFlowCache, inputCtrlCache->usedCacheSize, inputCtrlCache, inputCtrlCache->usedCacheSize);154 MemcpyS(launchCtrlFlowCache, inputCtrlCache->usedCacheSize, inputCtrlCache, inputCtrlCache->usedCacheSize);
155+ // No AICore host-args arena here. Clear the size so GELaunch refreshes the embedded table.
156+ launchCtrlFlowCache->ioAddressArenaBytes = 0;
155 }157 }
156 }158 }
157 int rc = EmulationLaunchOnceWithHostTensorData(function, inputDeviceDataList, outputDeviceDataList,159 int rc = EmulationLaunchOnceWithHostTensorData(function, inputDeviceDataList, outputDeviceDataList,
@@ -273,7 +275,7 @@ int EmulationLauncher::BuildControlFlowCacheWithEmulationTensorData(
273 TryResetBlockDimForPreLaunch(hostCtrlFlowCache, devProg, config);275 TryResetBlockDimForPreLaunch(hostCtrlFlowCache, devProg, config);
274 uint64_t contextWorkspaceAddr = hostCtrlFlowCache->contextWorkspaceAddr;276 uint64_t contextWorkspaceAddr = hostCtrlFlowCache->contextWorkspaceAddr;
275 hostCtrlFlowCache->IncastOutcastAddrReloc(contextWorkspaceAddr, 0, nullptr);277 hostCtrlFlowCache->IncastOutcastAddrReloc(contextWorkspaceAddr, 0, nullptr);
276- hostCtrlFlowCache->BuildIncastOutcastRelocTable();278+ hostCtrlFlowCache->AssignIoAddressArenaLayout();
277 hostCtrlFlowCache->CalcUsedCacheSize();279 hostCtrlFlowCache->CalcUsedCacheSize();
278 hostCtrlFlowCache->RuntimeAddrRelocWorkspace(contextWorkspaceAddr, 0, nullptr, nullptr, nullptr,280 hostCtrlFlowCache->RuntimeAddrRelocWorkspace(contextWorkspaceAddr, 0, nullptr, nullptr, nullptr,
279 devProg->GetParallelism());281 devProg->GetParallelism());
@@ -0,0 +1,103 @@
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+#include "machine/runtime/runner/aicore_launch_args.h"
12+ 
13+#include <algorithm>
14+#include <cstring>
15+ 
16+#include "securec.h"
17+#include "machine/utils/dynamic/dev_encode_program.h"
18+#include "machine/utils/dynamic/dev_encode_program_ctrlflow_cache.h"
19+#include "machine/utils/dynamic/dev_encode_tensor.h"
20+ 
21+namespace npu::tile_fwk::dynamic {
22+ 
23+void InitAicoreHostInputInfo(RtHostInputInfo& info)
24+{
25+ info.addrOffset = static_cast<uint32_t>(kAicoreInputsSlot * sizeof(void*));
26+ info.dataOffset = static_cast<uint32_t>(AicoreLaunchSlotsBytes());
27+}
28+ 
29+void PrepareAicoreLaunchArgsBuffer(std::vector<uint8_t>& aicoreArgBuf, AiCpuArgs* aicpuArgs, const char* displayName,
30+ size_t arenaBytes, RtArgsEx& rtAicoreArgs)
31+{
32+ if (aicpuArgs == nullptr || displayName == nullptr) {
33+ rtAicoreArgs.args = nullptr;
34+ rtAicoreArgs.argsSize = 0;
35+ rtAicoreArgs.hostInputInfoNum = 0;
36+ rtAicoreArgs.hostInputInfoPtr = nullptr;
37+ return;
38+ }
39+ const size_t needTotal = AicoreLaunchArgsBytes(arenaBytes);
40+ if (aicoreArgBuf.capacity() < needTotal) {
41+ const size_t growTo = std::max(needTotal, aicoreArgBuf.capacity() + (aicoreArgBuf.capacity() / 2));
42+ aicoreArgBuf.reserve(growTo);
43+ }
44+ if (aicoreArgBuf.size() != needTotal) {
45+ aicoreArgBuf.resize(needTotal);
46+ }
47+ 
48+ auto* slots = reinterpret_cast<void**>(aicoreArgBuf.data());
49+ int64_t* inputp = reinterpret_cast<int64_t*>(aicpuArgs + 1);
50+ slots[0] = const_cast<char*>(displayName);
51+ // slots[1] is RT-patched to the arena device addr when hostInputInfoNum==1; must be null otherwise.
52+ slots[1] = nullptr;
53+ slots[2] = nullptr;
54+ slots[3] = nullptr;
55+ slots[4] = inputp;
56+ slots[5] = aicpuArgs->kArgs.cfgdata;
57+ slots[6] = reinterpret_cast<DevTensorData*>(inputp + DEV_TENSOR_DATA_OFFSET);
58+ 
59+ rtAicoreArgs.args = aicoreArgBuf.data();
60+ rtAicoreArgs.argsSize = static_cast<uint32_t>(needTotal);
61+ rtAicoreArgs.isNoNeedH2DCopy = 0;
62+ rtAicoreArgs.hostInputInfoNum = 0;
63+ rtAicoreArgs.hostInputInfoPtr = nullptr;
64+}
65+ 
66+void EnsureHostCtrlFlowCacheRebased(DevControlFlowCache* hostCache, DevAscendProgram* devProg)
67+{
68+ if (hostCache == nullptr || devProg == nullptr) {
69+ return;
70+ }
71+ const uint64_t hostBase = reinterpret_cast<uint64_t>(hostCache);
72+ if (!hostCache->isRelocMetaDev) {
73+ hostCache->RelocMetaCache(0, hostBase);
74+ hostCache->isRelocMetaDev = true;
75+ }
76+ if (!hostCache->isRelocDataDev) {
77+ hostCache->TaskAddrRelocProgramAndCtrlCache(0, 0, reinterpret_cast<uint64_t>(devProg), hostBase);
78+ hostCache->isRelocDataDev = true;
79+ }
80+}
81+ 
82+void FillAicoreIoAddressArenaBuffer(std::vector<uint8_t>& aicoreArgBuf, AiCpuArgs* aicpuArgs,
83+ DevControlFlowCache* hostCache, uint64_t inputTensorSize, uint64_t outputTensorSize,
84+ RtArgsEx& rtAicoreArgs, RtHostInputInfo& aicoreHostInfo)
85+{
86+ if (hostCache == nullptr || aicpuArgs == nullptr) {
87+ return;
88+ }
89+ int64_t* inputp = reinterpret_cast<int64_t*>(aicpuArgs + 1);
90+ auto* arena = reinterpret_cast<uint64_t*>(aicoreArgBuf.data() + AicoreLaunchSlotsBytes());
91+ DevStartArgsBase startBase{};
92+ startBase.devTensorList = reinterpret_cast<DevTensorData*>(inputp + DEV_TENSOR_DATA_OFFSET);
93+ startBase.inputTensorSize = inputTensorSize;
94+ startBase.outputTensorSize = outputTensorSize;
95+ hostCache->MaterializeIncastOutcastAddrs(0, reinterpret_cast<uint64_t>(aicpuArgs->kArgs.workspace), &startBase,
96+ arena);
97+ 
98+ InitAicoreHostInputInfo(aicoreHostInfo);
99+ rtAicoreArgs.hostInputInfoPtr = &aicoreHostInfo;
100+ rtAicoreArgs.hostInputInfoNum = 1;
101+}
102+ 
103+} // namespace npu::tile_fwk::dynamic
@@ -0,0 +1,58 @@
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+ * \file aicore_launch_args.h
12+ * \brief Shared AICore host-args layout + IO-arena Materialize helpers for KernelBinary and kernel-bundle.
13+ */
14+ 
15+#pragma once
16+ 
17+#include <cstddef>
18+#include <cstdint>
19+#include <vector>
20+ 
21+#include "adapter/api/runtime_define.h"
22+#include "machine/utils/machine_ws_intf.h"
23+ 
24+namespace npu::tile_fwk::dynamic {
25+ 
26+class DevControlFlowCache;
27+struct DevAscendProgram;
28+ 
29+inline constexpr size_t kAicoreLaunchArgSlots = 7;
30+inline constexpr size_t kAicoreInputsSlot = 1; // KernelEntry `inputs`
31+ 
32+inline size_t AicoreLaunchSlotsBytes() { return kAicoreLaunchArgSlots * sizeof(void*); }
33+ 
34+inline size_t AicoreLaunchArgsBytes(size_t arenaBytes)
35+{
36+ const size_t slotsBytes = AicoreLaunchSlotsBytes();
37+ if (arenaBytes == 0) {
38+ return slotsBytes;
39+ }
40+ return (slotsBytes + arenaBytes + 7ULL) & ~static_cast<size_t>(7ULL);
41+}
42+ 
43+void InitAicoreHostInputInfo(RtHostInputInfo& info);
44+ 
45+/* Size buffer, fill 7 launch slots, wire rtAicoreArgs (host-input disabled until Fill). */
46+void PrepareAicoreLaunchArgsBuffer(std::vector<uint8_t>& aicoreArgBuf, AiCpuArgs* aicpuArgs, const char* displayName,
47+ size_t arenaBytes, RtArgsEx& rtAicoreArgs);
48+ 
49+/* Rebase host CF cache mirror once so Materialize can dereference pointers. */
50+void EnsureHostCtrlFlowCacheRebased(DevControlFlowCache* hostCache, DevAscendProgram* devProg);
51+ 
52+/* Write absolute IO addrs into the arena region and enable RtHostInputInfo for `inputs`.
53+ * inputTensorSize/outputTensorSize must match the recording ABI used by RelocDescFromCache. */
54+void FillAicoreIoAddressArenaBuffer(std::vector<uint8_t>& aicoreArgBuf, AiCpuArgs* aicpuArgs,
55+ DevControlFlowCache* hostCache, uint64_t inputTensorSize, uint64_t outputTensorSize,
56+ RtArgsEx& rtAicoreArgs, RtHostInputInfo& aicoreHostInfo);
57+ 
58+} // namespace npu::tile_fwk::dynamic
@@ -15,6 +15,7 @@
15 15 
16#include "machine/runtime/runner/kernel_binary.h"16#include "machine/runtime/runner/kernel_binary.h"
17 17 
18+#include <algorithm>
18#include <cstdlib>19#include <cstdlib>
19#include <mutex>20#include <mutex>
20#include <sstream>21#include <sstream>
@@ -29,6 +30,7 @@
29#include "interface/utils/common.h"30#include "interface/utils/common.h"
30#include "interface/configs/config_manager.h"31#include "interface/configs/config_manager.h"
31#include "interface/machine/host/perf_analysis.h"32#include "interface/machine/host/perf_analysis.h"
33+#include "machine/runtime/runner/aicore_launch_args.h"
32#include "machine/runtime/runner/host_prof.h"34#include "machine/runtime/runner/host_prof.h"
33#include "machine/runtime/runner/fed_prof_manager.h"35#include "machine/runtime/runner/fed_prof_manager.h"
34#include "machine/runtime/runner/runtime_agent.h"36#include "machine/runtime/runner/runtime_agent.h"
@@ -160,9 +162,13 @@ uint8_t* KernelBinary::FindCtrlFlowCache(std::vector<std::vector<int64_t>>& inpu
160 auto& caches = isOriginShape ? originShapeCaches : inferShapeCaches;162 auto& caches = isOriginShape ? originShapeCaches : inferShapeCaches;
161 for (auto& cache : caches) {163 for (auto& cache : caches) {
162 if (cache.hash == inHash) {164 if (cache.hash == inHash) {
165+ activeHostCtrlFlowCache_ = cache.hostCache.empty() ?
166+ nullptr :
167+ reinterpret_cast<DevControlFlowCache*>(cache.hostCache.data());
163 return cache.devCache;168 return cache.devCache;
164 }169 }
165 }170 }
171+ activeHostCtrlFlowCache_ = nullptr;
166 return nullptr;172 return nullptr;
167}173}
168 174 
@@ -172,14 +178,18 @@ uint8_t* KernelBinary::FindCtrlFlowCache(std::vector<DeviceTensorData>& inputs,
172 auto& caches = isOriginShape ? originShapeCaches : inferShapeCaches;178 auto& caches = isOriginShape ? originShapeCaches : inferShapeCaches;
173 for (auto& cache : caches) {179 for (auto& cache : caches) {
174 if (cache.hash == inHash) {180 if (cache.hash == inHash) {
181+ activeHostCtrlFlowCache_ = cache.hostCache.empty() ?
182+ nullptr :
183+ reinterpret_cast<DevControlFlowCache*>(cache.hostCache.data());
175 return cache.devCache;184 return cache.devCache;
176 }185 }
177 }186 }
187+ activeHostCtrlFlowCache_ = nullptr;
178 return nullptr;188 return nullptr;
179}189}
180 190 
181uint8_t* KernelBinary::BuildControlFlowCache(std::vector<DeviceTensorData>& inputs, bool isOriginShape,191uint8_t* KernelBinary::BuildControlFlowCache(std::vector<DeviceTensorData>& inputs, bool isOriginShape,
182- bool storeToCache)192+ bool storeToCache, uint64_t valueDependHash)
183{193{
184 DeviceLauncherConfig config;194 DeviceLauncherConfig config;
185 DeviceLauncher::DeviceLauncherConfigFillDeviceInfo(config);195 DeviceLauncher::DeviceLauncherConfigFillDeviceInfo(config);
@@ -203,13 +213,20 @@ uint8_t* KernelBinary::BuildControlFlowCache(std::vector<DeviceTensorData>& inpu
203 213 
204 uint8_t* devCache = DeviceLauncher::CopyControlFlowCache(ctrlCache);214 uint8_t* devCache = DeviceLauncher::CopyControlFlowCache(ctrlCache);
205 COMPILER_LOGD("control flow cache: %p", devCache);215 COMPILER_LOGD("control flow cache: %p", devCache);
216+ // Host mirror paired with device cache; Find binds it to activeHostCtrlFlowCache_.
217+ CtrlFlowCacheBlob* hostSlot = nullptr;
206 if (storeToCache) {218 if (storeToCache) {
207- if (isOriginShape) {219+ auto& caches = isOriginShape ? originShapeCaches : inferShapeCaches;
208- originShapeCaches.emplace_back(inputs, devCache);220+ caches.emplace_back(inputs, devCache);
209- } else {221+ hostSlot = &caches.back().hostCache;
210- inferShapeCaches.emplace_back(inputs, devCache);222+ } else {
211- }223+ valueDependCache_.hash = valueDependHash;
224+ valueDependCache_.devCache = devCache;
225+ hostSlot = &valueDependCache_.hostCache;
212 }226 }
227+ hostSlot->resize(ctrlCache->usedCacheSize);
228+ (void)memcpy_s(hostSlot->data(), hostSlot->size(), ctrlCache, ctrlCache->usedCacheSize);
229+ activeHostCtrlFlowCache_ = reinterpret_cast<DevControlFlowCache*>(hostSlot->data());
213 return devCache;230 return devCache;
214}231}
215 232 
@@ -286,6 +303,77 @@ std::pair<AiCpuArgs*, int64_t> KernelBinary::BuildKernelArgs(const std::vector<D
286 return {aicpuArgs, aicpuArgBuf.size() * sizeof(int64_t)};303 return {aicpuArgs, aicpuArgBuf.size() * sizeof(int64_t)};
287}304}
288 305 
306+void KernelBinary::MaterializeIoAddressArenaForAicore(AiCpuArgs* aicpuArgs)
307+{
308+ DevControlFlowCache* hostCache = nullptr;
309+ size_t arenaBytes = 0;
310+ if (ctrlFlowCacheReplay_ && aicpuArgs != nullptr && activeHostCtrlFlowCache_ != nullptr) {
311+ hostCache = activeHostCtrlFlowCache_;
312+ arenaBytes = static_cast<size_t>(hostCache->ioAddressArenaBytes);
313+ if (arenaBytes != 0) {
314+ EnsureHostCtrlFlowCacheRebased(hostCache, devProg);
315+ }
316+ }
317+ 
318+ PrepareAicoreLaunchArgsBuffer(aicoreArgBuf_, aicpuArgs, kernelName_.c_str(), arenaBytes, rtAicoreArgs_);
319+ if (arenaBytes != 0) {
320+ int64_t* inputp = reinterpret_cast<int64_t*>(aicpuArgs + 1);
321+ FillAicoreIoAddressArenaBuffer(aicoreArgBuf_, aicpuArgs, hostCache, static_cast<uint64_t>(inputp[0]),
322+ static_cast<uint64_t>(inputp[1]), rtAicoreArgs_, aicoreHostInfo_);
323+ }
324+}
325+ 
326+DevControlFlowCache* KernelBinary::FindHostCtrlFlowCache(const std::vector<DeviceTensorData>& tensors,
327+ CtrlFlowCacheBlob& hostCacheOut)
328+{
329+ const int64_t hash = ControlFlowCache::Hash(tensors);
330+ auto tryCopy = [&](CtrlFlowCacheBlob& blob) -> DevControlFlowCache* {
331+ if (blob.empty()) {
332+ return nullptr;
333+ }
334+ hostCacheOut = blob;
335+ return reinterpret_cast<DevControlFlowCache*>(hostCacheOut.data());
336+ };
337+ for (auto& cache : originShapeCaches) {
338+ if (cache.hash == hash) {
339+ return tryCopy(cache.hostCache);
340+ }
341+ }
342+ for (auto& cache : inferShapeCaches) {
343+ if (cache.hash == hash) {
344+ return tryCopy(cache.hostCache);
345+ }
346+ }
347+ if (!valueDependCache_.hostCache.empty() &&
348+ activeHostCtrlFlowCache_ == reinterpret_cast<DevControlFlowCache*>(valueDependCache_.hostCache.data())) {
349+ return tryCopy(valueDependCache_.hostCache);
350+ }
351+ return nullptr;
352+}
353+ 
354+void KernelBinary::AttachHostCtrlFlowCache(const std::vector<DeviceTensorData>& tensors, CtrlFlowCacheBlob&& hostCache)
355+{
356+ const int64_t hash = ControlFlowCache::Hash(tensors);
357+ for (auto& cache : originShapeCaches) {
358+ if (cache.hash == hash) {
359+ cache.hostCache = std::move(hostCache);
360+ activeHostCtrlFlowCache_ = reinterpret_cast<DevControlFlowCache*>(cache.hostCache.data());
361+ return;
362+ }
363+ }
364+ for (auto& cache : inferShapeCaches) {
365+ if (cache.hash == hash) {
366+ cache.hostCache = std::move(hostCache);
367+ activeHostCtrlFlowCache_ = reinterpret_cast<DevControlFlowCache*>(cache.hostCache.data());
368+ return;
369+ }
370+ }
371+ valueDependCache_.hostCache = std::move(hostCache);
372+ activeHostCtrlFlowCache_ = valueDependCache_.hostCache.empty() ?
373+ nullptr :
374+ reinterpret_cast<DevControlFlowCache*>(valueDependCache_.hostCache.data());
375+}
376+ 
289bool KernelBinary::CheckArgs(const std::vector<DeviceTensorData>& tensors) const377bool KernelBinary::CheckArgs(const std::vector<DeviceTensorData>& tensors) const
290{378{
291 if (tensors.size() != argTypes.size()) {379 if (tensors.size() != argTypes.size()) {
@@ -337,10 +425,23 @@ const std::vector<size_t>& KernelBinary::GetValueDependInputIndices() const
337 425 
338void KernelBinary::FreeAndClearValueDependCache()426void KernelBinary::FreeAndClearValueDependCache()
339{427{
340- if (valueDependDevCache_ != nullptr) {428+ if (valueDependCache_.devCache != nullptr) {
341- DeviceLauncher::FreeControlFlowCache(valueDependDevCache_);429+ DeviceLauncher::FreeControlFlowCache(valueDependCache_.devCache);
342- valueDependDevCache_ = nullptr;430+ valueDependCache_.devCache = nullptr;
343 }431 }
432+ if (!valueDependCache_.hostCache.empty() &&
433+ activeHostCtrlFlowCache_ == reinterpret_cast<DevControlFlowCache*>(valueDependCache_.hostCache.data())) {
434+ activeHostCtrlFlowCache_ = nullptr;
435+ }
436+ valueDependCache_.hostCache.clear();
437+ valueDependCache_.hash = 0;
438+}
439+ 
440+void KernelBinary::BindValueDependActiveHost()
441+{
442+ activeHostCtrlFlowCache_ = valueDependCache_.hostCache.empty() ?
443+ nullptr :
444+ reinterpret_cast<DevControlFlowCache*>(valueDependCache_.hostCache.data());
344}445}
345 446 
346uint64_t KernelBinary::GetMaxDynamicAssembleOutcastMem() const447uint64_t KernelBinary::GetMaxDynamicAssembleOutcastMem() const
@@ -433,9 +534,14 @@ void KernelBinary::InitLaunchArgs()
433 aicpuLaunchDesc_.hostInputs = &hostInfo_;534 aicpuLaunchDesc_.hostInputs = &hostInfo_;
434 aicpuLaunchDesc_.timeout = AICPU_EXECUTE_TIMEOUT;535 aicpuLaunchDesc_.timeout = AICPU_EXECUTE_TIMEOUT;
435 memset_s(&rtAicoreArgs_, sizeof(RtArgsEx), 0, sizeof(RtArgsEx));536 memset_s(&rtAicoreArgs_, sizeof(RtArgsEx), 0, sizeof(RtArgsEx));
436- kernelArgs_.resize(0x7, nullptr);537+ // Pre-size to the no-arena footprint; Materialize grows capacity once and reuses it.
437- rtAicoreArgs_.args = kernelArgs_.data();538+ const size_t slotsBytes = AicoreLaunchSlotsBytes();
438- rtAicoreArgs_.argsSize = kernelArgs_.size() * sizeof(void*);539+ aicoreArgBuf_.reserve(slotsBytes);
540+ aicoreArgBuf_.resize(slotsBytes);
541+ (void)memset_s(aicoreArgBuf_.data(), slotsBytes, 0, slotsBytes);
542+ rtAicoreArgs_.args = aicoreArgBuf_.data();
543+ rtAicoreArgs_.argsSize = static_cast<uint32_t>(slotsBytes);
544+ InitAicoreHostInputInfo(aicoreHostInfo_);
439 545 
440 memset_s(&rtTaskCfg_, sizeof(RtTaskCfgInfo), 0, sizeof(RtTaskCfgInfo));546 memset_s(&rtTaskCfg_, sizeof(RtTaskCfgInfo), 0, sizeof(RtTaskCfgInfo));
441 rtTaskCfg_.schemMode = static_cast<uint8_t>(RtSchemModeType::BATCH);547 rtTaskCfg_.schemMode = static_cast<uint8_t>(RtSchemModeType::BATCH);
@@ -48,11 +48,16 @@ public:
48 48 
49 uint8_t* FindCtrlFlowCache(std::vector<std::vector<int64_t>>& inputs, bool isOriginShape);49 uint8_t* FindCtrlFlowCache(std::vector<std::vector<int64_t>>& inputs, bool isOriginShape);
50 uint8_t* FindCtrlFlowCache(std::vector<DeviceTensorData>& inputs, bool isOriginShape);50 uint8_t* FindCtrlFlowCache(std::vector<DeviceTensorData>& inputs, bool isOriginShape);
51- uint8_t* BuildControlFlowCache(std::vector<DeviceTensorData>& inputs, bool isOriginShape, bool storeToCache = true);51+ /* storeToCache=false commits the value-depend slot (hash + device ptr + host mirror) in one write. */
52+ uint8_t* BuildControlFlowCache(std::vector<DeviceTensorData>& inputs, bool isOriginShape, bool storeToCache = true,
53+ uint64_t valueDependHash = 0);
52 54 
53 int64_t GetWorkspaceSize(const std::vector<DeviceTensorData>& tensors);55 int64_t GetWorkspaceSize(const std::vector<DeviceTensorData>& tensors);
54 56 
55 std::pair<AiCpuArgs*, int64_t> BuildKernelArgs(const std::vector<DeviceTensorData>& tensors);57 std::pair<AiCpuArgs*, int64_t> BuildKernelArgs(const std::vector<DeviceTensorData>& tensors);
58+ /* After workspace is set: materialize IO addrs into AICore launch host-args arena.
59+ * Uses activeHostCtrlFlowCache_ bound by FindOrBuildDevCache (no second hash lookup). */
60+ void MaterializeIoAddressArenaForAicore(AiCpuArgs* aicpuArgs);
56 61 
57 bool CheckArgs(const std::vector<DeviceTensorData>& tensors) const;62 bool CheckArgs(const std::vector<DeviceTensorData>& tensors) const;
58 63 
@@ -63,19 +68,27 @@ public:
63 bool DisableHostCtrlFlowCacheBuild() const;68 bool DisableHostCtrlFlowCacheBuild() const;
64 bool HasValueDepend() const { return devProg != nullptr && devProg->hasValueDepend != 0; }69 bool HasValueDepend() const { return devProg != nullptr && devProg->hasValueDepend != 0; }
65 const std::vector<size_t>& GetValueDependInputIndices() const;70 const std::vector<size_t>& GetValueDependInputIndices() const;
66- uint64_t GetCachedCtrlFlowHash() const { return cachedCtrlFlowHash_; }71+ uint64_t GetCachedCtrlFlowHash() const { return valueDependCache_.hash; }
67- void SetCachedCtrlFlowHash(uint64_t hash) { cachedCtrlFlowHash_ = hash; }72+ uint8_t* GetValueDependDevCache() const { return valueDependCache_.devCache; }
68- uint8_t* GetValueDependDevCache() const { return valueDependDevCache_; }
69- void SetValueDependDevCache(uint8_t* cache) { valueDependDevCache_ = cache; }
70 void FreeAndClearValueDependCache();73 void FreeAndClearValueDependCache();
74+ void BindValueDependActiveHost();
71 uint64_t GetMaxDynamicAssembleOutcastMem() const;75 uint64_t GetMaxDynamicAssembleOutcastMem() const;
72 uint64_t GetMaxDynamicCellMatchTableMem() const;76 uint64_t GetMaxDynamicCellMatchTableMem() const;
73 uint64_t GetRuntimeDynamicCellMatchAddr() const;77 uint64_t GetRuntimeDynamicCellMatchAddr() const;
74 uint64_t GetRuntimeDynamicCellMatchCapacity() const;78 uint64_t GetRuntimeDynamicCellMatchCapacity() const;
75- auto& GetHostCtrlFlowCaches() { return hostCtrlFlowCaches_; }79+ void SetCtrlFlowCacheReplay(bool replay)
76- 80+ {
77- void SetCtrlFlowCacheReplay(bool replay) { ctrlFlowCacheReplay_ = replay; }81+ ctrlFlowCacheReplay_ = replay;
82+ if (!replay) {
83+ activeHostCtrlFlowCache_ = nullptr;
84+ }
85+ }
78 bool IsCtrlFlowCacheReplay() const { return ctrlFlowCacheReplay_; }86 bool IsCtrlFlowCacheReplay() const { return ctrlFlowCacheReplay_; }
87+ DevControlFlowCache* GetActiveHostCtrlFlowCache() const { return activeHostCtrlFlowCache_; }
88+ /* Emulation path: copy out host mirror by shape hash; D2H attach when missing. */
89+ DevControlFlowCache* FindHostCtrlFlowCache(const std::vector<DeviceTensorData>& tensors,
90+ CtrlFlowCacheBlob& hostCacheOut);
91+ void AttachHostCtrlFlowCache(const std::vector<DeviceTensorData>& tensors, CtrlFlowCacheBlob&& hostCache);
79 92 
80 // Eager and aclgraph cannot share one record/wait pair. epoch=0 is eager;93 // Eager and aclgraph cannot share one record/wait pair. epoch=0 is eager;
81 // a non-zero epoch is the capture model. Switching epoch restarts sequence94 // a non-zero epoch is the capture model. Switching epoch restarts sequence
@@ -99,7 +112,6 @@ public:
99 AicpuLaunchDesc& GetAicpuLaunchDesc() { return aicpuLaunchDesc_; }112 AicpuLaunchDesc& GetAicpuLaunchDesc() { return aicpuLaunchDesc_; }
100 RtArgsEx& GetRtAicoreArgs() { return rtAicoreArgs_; }113 RtArgsEx& GetRtAicoreArgs() { return rtAicoreArgs_; }
101 RtTaskCfgInfo& GetRtTaskCfg() { return rtTaskCfg_; }114 RtTaskCfgInfo& GetRtTaskCfg() { return rtTaskCfg_; }
102- std::vector<void*>& GetKernelArgs() { return kernelArgs_; }
103 115 
104private:116private:
105 void InitCachedArgs();117 void InitCachedArgs();
@@ -123,7 +135,16 @@ private:
123 int64_t workspaceSize{0}; // static workspace size135 int64_t workspaceSize{0}; // static workspace size
124 std::vector<ControlFlowCache> inferShapeCaches;136 std::vector<ControlFlowCache> inferShapeCaches;
125 std::vector<ControlFlowCache> originShapeCaches;137 std::vector<ControlFlowCache> originShapeCaches;
126- std::vector<HostControlFlowCache> hostCtrlFlowCaches_;138+ /* Single value-depend slot: data+shape hash, device cache, and host mirror. */
139+ struct ValueDependCtrlFlowCache {
140+ uint64_t hash{0};
141+ uint8_t* devCache{nullptr};
142+ CtrlFlowCacheBlob hostCache;
143+ };
144+ 
145+ /* Bound when Find/Build hits; Materialize reads this without re-hashing. */
146+ DevControlFlowCache* activeHostCtrlFlowCache_{nullptr};
147+ ValueDependCtrlFlowCache valueDependCache_;
127 bool ctrlFlowCacheReplay_{false};148 bool ctrlFlowCacheReplay_{false};
128 int64_t ringSequence_{0};149 int64_t ringSequence_{0};
129 uintptr_t ringEpoch_{0};150 uintptr_t ringEpoch_{0};
@@ -150,10 +171,10 @@ private:
150 AicpuLaunchDesc aicpuLaunchDesc_;171 AicpuLaunchDesc aicpuLaunchDesc_;
151 RtArgsEx rtAicoreArgs_;172 RtArgsEx rtAicoreArgs_;
152 RtTaskCfgInfo rtTaskCfg_;173 RtTaskCfgInfo rtTaskCfg_;
153- std::vector<void*> kernelArgs_;174+ /* Contiguous AICore launch buffer: 7 void* slots + optional IO arena. */
154- AicpuHostInput hostInfo_;175+ std::vector<uint8_t> aicoreArgBuf_;
155- uint64_t cachedCtrlFlowHash_{0};176+ RtHostInputInfo hostInfo_{};
156- uint8_t* valueDependDevCache_{nullptr};177+ RtHostInputInfo aicoreHostInfo_{};
157 static std::vector<size_t> emptyIndices_;178 static std::vector<size_t> emptyIndices_;
158};179};
159 180 
@@ -37,7 +37,7 @@ RtAicpuArgsEx BuildRtAicpuArgs(const AicpuLaunchDesc& desc)
37 RtAicpuArgsEx rt{};37 RtAicpuArgsEx rt{};
38 rt.args = desc.args;38 rt.args = desc.args;
39 rt.argsSize = desc.argsSize;39 rt.argsSize = desc.argsSize;
40- rt.hostInputInfoPtr = reinterpret_cast<RtHostInputInfo*>(desc.hostInputs);40+ rt.hostInputInfoPtr = desc.hostInputs;
41 rt.hostInputInfoNum = desc.hostInputNum;41 rt.hostInputInfoNum = desc.hostInputNum;
42 rt.timeout = desc.timeout;42 rt.timeout = desc.timeout;
43 rt.kernelNameAddrOffset = desc.kernelNameOffset;43 rt.kernelNameAddrOffset = desc.kernelNameOffset;
@@ -97,8 +97,7 @@ int LoadAicpuOp::LaunchWithHostArgs(void* funcHandle, const AicpuLaunchDesc& des
97 kernelLaunchCfg.numAttrs = 1U;97 kernelLaunchCfg.numAttrs = 1U;
98 }98 }
99 return RuntimeLaunchKernelWithHostArgs(aicpuFuncHandle, desc.blockDim, desc.stream, &kernelLaunchCfg, desc.args,99 return RuntimeLaunchKernelWithHostArgs(aicpuFuncHandle, desc.blockDim, desc.stream, &kernelLaunchCfg, desc.args,
100- desc.argsSize, reinterpret_cast<RtHostInputInfo*>(desc.hostInputs),100+ desc.argsSize, desc.hostInputs, desc.hostInputNum);
101- desc.hostInputNum);
102}101}
103 102 
104int LoadAicpuOp::LaunchCustomOp([[maybe_unused]] const AicpuLaunchDesc& desc,103int LoadAicpuOp::LaunchCustomOp([[maybe_unused]] const AicpuLaunchDesc& desc,
@@ -24,20 +24,13 @@
24#include "machine/utils/machine_ws_intf.h"24#include "machine/utils/machine_ws_intf.h"
25 25 
26namespace npu::tile_fwk {26namespace npu::tile_fwk {
27-struct AicpuHostInput {
28- // device 上待刷新的位置, launch时。rt
29- // 会申请Device内存并将该device内存地址刷新到hostArgs中,该参数描述就是这个待刷新的位置的偏移
30- uint32_t addrOffset = 0;
31- // 数据偏移区,指向的数据去需要拷贝到device侧, 该参数用于指定数据区基于hostArgs的地址偏移(主要描述input 信息)
32- uint32_t dataOffset = 0;
33-};
34- 
35struct AicpuLaunchDesc {27struct AicpuLaunchDesc {
36 void* stream = nullptr;28 void* stream = nullptr;
37 // args 表示的host侧 DeviceKernelArgs + input info 等组装的info29 // args 表示的host侧 DeviceKernelArgs + input info 等组装的info
38 AiCpuArgs* args = nullptr;30 AiCpuArgs* args = nullptr;
39 uint32_t argsSize = 0;31 uint32_t argsSize = 0;
40- AicpuHostInput* hostInputs = nullptr;32+ /* AICPU / AICore launch 共用 RT host-input 描述(随路 H2D 槽位)。 */
33+ RtHostInputInfo* hostInputs = nullptr;
41 uint16_t hostInputNum = 0;34 uint16_t hostInputNum = 0;
42 uint16_t timeout = 0;35 uint16_t timeout = 0;
43 uint32_t blockDim = 1;36 uint32_t blockDim = 1;
@@ -3731,8 +3731,7 @@ void DevControlFlowCache::Init(void* dyndevAttrPtr, uint64_t cacheSize, uint64_t
3731 deviceTaskSkippedCount = 0;3731 deviceTaskSkippedCount = 0;
3732 cacheDataOffset = 0;3732 cacheDataOffset = 0;
3733 workspaceAddr = 0;3733 workspaceAddr = 0;
3734- taskRelocTableOffset = 0;3734+ ioAddressArenaBytes = 0;
3735- taskRelocTableCount = 0;
3736 dataSize = initOffset - reinterpret_cast<uintdevptr_t>(data);3735 dataSize = initOffset - reinterpret_cast<uintdevptr_t>(data);
3737}3736}
3738 3737 
@@ -38,31 +38,6 @@ bool ForEachIncastOutcastAddr(DynDeviceTaskBase* base, Func func)
38 }38 }
39 return true;39 return true;
40}40}
41- 
42-template <AddressCacheKind Kind>
43-void RelocLoop(uint32_t descCount, const uint16_t* idxList, uint64_t* dst, const uint64_t* src, uint64_t wsShift,
44- DevStartArgsBase* devStartArgs)
45-{
46- for (uint32_t k = 0; k < descCount; k++) {
47- uint32_t i = idxList[k];
48- uint64_t srcVal = src[i];
49- if constexpr (Kind == AddressCacheKind::Workspace) {
50- dst[i] = srcVal + wsShift;
51- } else if constexpr (Kind == AddressCacheKind::Input) {
52- dst[i] = devStartArgs->GetInputTensor(static_cast<int>(srcVal & AddressDescriptor::kCacheValueMask))
53- .address;
54- } else if constexpr (Kind == AddressCacheKind::Output) {
55- dst[i] = devStartArgs->GetOutputTensor(static_cast<int>(srcVal & AddressDescriptor::kCacheValueMask))
56- .address;
57- } else if constexpr (Kind == AddressCacheKind::Communication) {
58- dst[i] = srcVal & AddressDescriptor::kCacheValueMask;
59- } else {
60- DEV_ERROR(ProgEncodeErr::CACHE_RELOC_KIND_INVALID,
61- "#ctrl.task.pre.cache.reloc: [RelocDescFromCache] Invalid kind: %u\n",
62- static_cast<uint32_t>(Kind));
63- }
64- }
65-}
66} // namespace41} // namespace
67 42 
68void DevControlFlowCache::MatchInputOutputDump(DevStartArgsBase* startArgs) const43void DevControlFlowCache::MatchInputOutputDump(DevStartArgsBase* startArgs) const
@@ -621,157 +596,78 @@ void DevControlFlowCache::IncastOutcastAddrReloc(uint64_t srcWorkspace, uint64_t
621 }596 }
622}597}
623 598 
624-namespace {599+void DevControlFlowCache::AssignIoAddressArenaLayout()
625- 
626-uint32_t RelocTableCountDupKinds(const AddressDescriptor* backup, uint32_t descNum, uint32_t* present,
627- std::vector<uint8_t>& kinds)
628{600{
629- for (size_t k = 0; k < static_cast<size_t>(AddressCacheKind::MaxKind); k++) {601+ uint64_t elemIndex = 0;
630- present[k] = 0;602+ for (uint64_t deviceIndex = 0; deviceIndex < deviceTaskCount; deviceIndex++) {
631- }603+ DynDeviceTaskBase* dynTaskBase = deviceTaskCacheList[deviceIndex].dynTaskBase;
632- for (uint32_t i = 0; i < descNum; i++) {604+ DynFuncHeader* dynFuncDataList = dynTaskBase->dynFuncDataList;
633- uint32_t rawKind = backup[i].cacheKind;605+ DynFuncDataCache* dynFuncDataCacheList = dynTaskBase->dynFuncDataCacheList;
634- DEV_ASSERT(ProgEncodeErr::CTRL_CACHE_RELOC_BUILD_FAILED,606+ for (uint32_t dupIndex = 0; dupIndex < dynFuncDataList->funcNum; dupIndex++) {
635- rawKind < static_cast<uint32_t>(AddressCacheKind::MaxKind));607+ DevAscendFunctionDuppedData* duppedData = dynFuncDataCacheList->At(dupIndex).duppedData;
636- present[rawKind]++;608+ DynFuncData* dynData = &dynFuncDataList->At(dupIndex);
637- kinds.push_back(static_cast<uint8_t>(rawKind));609+ const uint64_t slotElems = duppedData->GetIncastSize() + duppedData->GetOutcastSize();
638- }610+ // Device leaf entry: param.rawTensorAddr = ioAddressArena + ioAddressArenaOffset (no /8).
639- uint32_t kindsPresent = 0;611+ dynData->ioAddressArenaOffset = static_cast<uint32_t>(elemIndex);
640- for (size_t k = 0; k < static_cast<size_t>(AddressCacheKind::MaxKind); k++) {612+ elemIndex += slotElems;
641- kindsPresent += (present[k] > 0) ? 1U : 0U;
642- }
643- return kindsPresent;
644-}
645- 
646-/* Sizes of the per-task reloc block: one batch per (dup, kind) with at least one
647- * descriptor, plus one uint16 index per descriptor. */
648-struct RelocTableTaskBatchSizes {
649- uint32_t batchCount;
650- uint32_t totalIdx;
651-};
652- 
653-/* Per-dup data captured by the scan pass, so the fill pass never re-reads
654- * backup descriptors. */
655-struct RelocTableDupRelocInfo {
656- uint32_t descNum;
657- uint32_t present[static_cast<size_t>(AddressCacheKind::MaxKind)];
658- uint64_t srcBase;
659- uint64_t dstBase;
660-};
661- 
662-/* Pass 1 of the reloc-table build: measure the per-task batch block, capturing
663- * the per-dup census and base offsets along the way. */
664-RelocTableTaskBatchSizes RelocTableScanTaskBatches(const DevControlFlowCache& cache, DynDeviceTaskBase* dynTaskBase,
665- std::vector<RelocTableDupRelocInfo>& infos,
666- std::vector<uint8_t>& kinds)
667-{
668- const uint8_t* cacheBase = reinterpret_cast<const uint8_t*>(&cache);
669- DynFuncHeader* dynFuncDataList = dynTaskBase->dynFuncDataList;
670- DynFuncDataCache* dynFuncDataCacheList = dynTaskBase->dynFuncDataCacheList;
671- DynFuncDataBackup* dynFuncDataBackupList = dynTaskBase->dynFuncDataBackupList;
672- infos.clear();
673- kinds.clear();
674- RelocTableTaskBatchSizes sizes{0, 0};
675- for (uint32_t dupIndex = 0; dupIndex < dynFuncDataList->funcNum; dupIndex++) {
676- DevAscendFunctionDuppedData* duppedData = dynFuncDataCacheList->At(dupIndex).duppedData;
677- uint32_t descNum = duppedData->GetIncastSize() + duppedData->GetOutcastSize();
678- DEV_ASSERT(ProgEncodeErr::CTRL_CACHE_RELOC_BUILD_FAILED, descNum <= UINT16_MAX);
679- uint64_t* rawTensorAddrBackup = dynFuncDataBackupList->At(dupIndex).rawTensorAddrBackup;
680- const AddressDescriptor* backup = reinterpret_cast<const AddressDescriptor*>(rawTensorAddrBackup);
681- RelocTableDupRelocInfo info{};
682- info.descNum = descNum;
683- sizes.batchCount += RelocTableCountDupKinds(backup, descNum, info.present, kinds);
684- info.srcBase = reinterpret_cast<uint8_t*>(rawTensorAddrBackup) - cacheBase;
685- info.dstBase = reinterpret_cast<uint8_t*>(dynFuncDataList->At(dupIndex).rawTensorAddr) - cacheBase;
686- infos.push_back(info);
687- sizes.totalIdx += descNum;
688- }
689- return sizes;
690-}
691- 
692-/* Pass 2 of the reloc-table build: fill the allocated per-task block with
693- * batch records and their descriptor-index segments, reading only the captured per-dup info. */
694-void RelocTableEmitTaskRelocBatches(const DevControlFlowCache& cache, const std::vector<RelocTableDupRelocInfo>& infos,
695- const std::vector<uint8_t>& kinds,
696- DevControlFlowCache::IncastOutcastRelocBatch* batches, uint16_t* idxList)
697-{
698- const uint8_t* cacheBase = reinterpret_cast<const uint8_t*>(&cache);
699- uint32_t batchWritePos = 0;
700- uint32_t idxWritePos = 0;
701- uint32_t kindReadPos = 0;
702- for (const RelocTableDupRelocInfo& info : infos) {
703- for (uint32_t kind = 0; kind < static_cast<uint32_t>(AddressCacheKind::MaxKind); kind++) {
704- if (info.present[kind] == 0) {
705- continue;
706- }
707- batches[batchWritePos] = {
708- info.srcBase, info.dstBase,
709- static_cast<uint64_t>(reinterpret_cast<uint8_t*>(idxList + idxWritePos) - cacheBase),
710- info.present[kind], static_cast<AddressCacheKind>(kind)};
711- batchWritePos++;
712- for (uint32_t i = 0; i < info.descNum; i++) {
713- if (kinds[kindReadPos + i] == kind) {
714- idxList[idxWritePos++] = static_cast<uint16_t>(i);
715- }
716- }
717 }613 }
718- kindReadPos += info.descNum;
719 }614 }
615+ ioAddressArenaBytes = elemIndex * sizeof(uint64_t);
720}616}
721 617 
722-} // namespace618+void DevControlFlowCache::ResolveLeafIncastOutcastAddrs(const AddressDescriptor* backupAddr,
723- 619+ DevAscendFunctionDuppedData* duppedData,
724-/* Reloc table memory layout620+ const RelocRange& relocWorkspace,
725- * [TaskRelocEntry x deviceTaskCount]621+ DevStartArgsBase* devStartArgs, uint64_t* absDst,
726- * [IncastOutcastRelocBatch x batchCount | uint16 x totalIdx]622+ bool writeEmbedded)
727- * batch (dup-major kind-ascending, only (dup, kind) with descriptors):
728- * +---------------+---------------+---------------+-----------+------+
729- * | srcBaseOffset | dstBaseOffset | idxListOffset | descCount | kind |
730- * +---------------+---------------+---------------+-----------+------+
731- * uint16 idx (ascending within each batch, appended in batch order):
732- * +---------------------------+---------------------------+-----+
733- * | batch0: i0 i1 .. iN-1 | batch1: i0 i1 .. iM-1 | ... |
734- * +---------------------------+---------------------------+-----+
735- */
736-void DevControlFlowCache::BuildIncastOutcastRelocTable()
737{623{
738- taskRelocTableOffset = 0;624+ const uint64_t incastSize = duppedData->GetIncastSize();
739- taskRelocTableCount = 0;625+ const uint64_t outcastSize = duppedData->GetOutcastSize();
740- if (deviceTaskCount == 0) {626+ for (uint64_t i = 0; i < incastSize; i++) {
741- return;627+ AddressDescriptor resolved;
742- }628+ RelocDescFromCache(backupAddr[i], resolved, relocWorkspace, devStartArgs);
743- void* indexBlock = AllocateCache(deviceTaskCount * sizeof(TaskRelocEntry));629+ if (absDst != nullptr) {
744- if (indexBlock == nullptr) {630+ absDst[i] = resolved.GetAddressValue();
745- return;631+ }
746- }632+ if (writeEmbedded) {
747- taskRelocTableOffset = reinterpret_cast<uint8_t*>(indexBlock) - reinterpret_cast<uint8_t*>(this);633+ duppedData->GetIncastAddress(static_cast<int>(i)) = resolved;
748- TaskRelocEntry* taskEntries = static_cast<TaskRelocEntry*>(indexBlock);634+ }
749- std::vector<RelocTableDupRelocInfo> infos;635+ }
750- std::vector<uint8_t> kinds;636+ for (uint64_t i = 0; i < outcastSize; i++) {
751- for (size_t index = 0; index < deviceTaskCount; index++) {637+ AddressDescriptor resolved;
752- DynDeviceTaskBase* dynTaskBase = deviceTaskCacheList[index].dynTaskBase;638+ RelocDescFromCache(backupAddr[incastSize + i], resolved, relocWorkspace, devStartArgs);
753- const RelocTableTaskBatchSizes sizes = RelocTableScanTaskBatches(*this, dynTaskBase, infos, kinds);639+ if (absDst != nullptr) {
754- void* block = AllocateCache(sizes.batchCount * sizeof(IncastOutcastRelocBatch) +640+ absDst[incastSize + i] = resolved.GetAddressValue();
755- sizes.totalIdx * sizeof(uint16_t));641+ }
756- if (block == nullptr) {642+ if (writeEmbedded) {
757- taskRelocTableOffset = 0;643+ duppedData->GetOutcastAddress(static_cast<int>(i)) = resolved;
758- taskRelocTableCount = 0;
759- return;
760 }644 }
761- taskEntries[index] = {
762- static_cast<uint64_t>(reinterpret_cast<uint8_t*>(block) - reinterpret_cast<uint8_t*>(this)),
763- static_cast<uint64_t>(reinterpret_cast<uint8_t*>(dynTaskBase->dynFuncDataList) -
764- reinterpret_cast<uint8_t*>(this)),
765- sizes.batchCount};
766- RelocTableEmitTaskRelocBatches(
767- *this, infos, kinds, static_cast<IncastOutcastRelocBatch*>(block),
768- reinterpret_cast<uint16_t*>(static_cast<IncastOutcastRelocBatch*>(block) + sizes.batchCount));
769 }645 }
770- taskRelocTableCount = static_cast<uint32_t>(deviceTaskCount);
771}646}
772 647 
773-void DevControlFlowCache::RelocIncastOutcastTaskStructural(uint32_t taskIndex, uint64_t srcWorkspace,648+void DevControlFlowCache::MaterializeIncastOutcastAddrs(uint64_t srcWorkspace, uint64_t dstWorkspace,
774- uint64_t dstWorkspace, DevStartArgsBase* devStartArgs)649+ DevStartArgsBase* devStartArgs, uint64_t* arena) const
650+{
651+ // Caller (FillAicoreIoAddressArena) only invokes when ioAddressArenaBytes != 0 with non-null arena/args.
652+ RelocRange relocWorkspace(srcWorkspace, dstWorkspace);
653+ for (uint64_t deviceIndex = 0; deviceIndex < deviceTaskCount; deviceIndex++) {
654+ DynDeviceTaskBase* dynTaskBase = deviceTaskCacheList[deviceIndex].dynTaskBase;
655+ DynFuncHeader* dynFuncDataList = dynTaskBase->dynFuncDataList;
656+ DynFuncDataCache* dynFuncDataCacheList = dynTaskBase->dynFuncDataCacheList;
657+ DynFuncDataBackup* dynFuncDataBackupList = dynTaskBase->dynFuncDataBackupList;
658+ for (uint32_t dupIndex = 0; dupIndex < dynFuncDataList->funcNum; dupIndex++) {
659+ DevAscendFunctionDuppedData* duppedData = dynFuncDataCacheList->At(dupIndex).duppedData;
660+ const DynFuncData& dynData = dynFuncDataList->At(dupIndex);
661+ const AddressDescriptor* backupAddr = reinterpret_cast<const AddressDescriptor*>(
662+ dynFuncDataBackupList->At(dupIndex).rawTensorAddrBackup);
663+ ResolveLeafIncastOutcastAddrs(backupAddr, duppedData, relocWorkspace, devStartArgs,
664+ arena + dynData.ioAddressArenaOffset, false);
665+ }
666+ }
667+}
668+ 
669+void DevControlFlowCache::RelocIncastOutcastTask(uint32_t taskIndex, uint64_t srcWorkspace, uint64_t dstWorkspace,
670+ DevStartArgsBase* devStartArgs)
775{671{
776 RelocRange relocWorkspace(srcWorkspace, dstWorkspace);672 RelocRange relocWorkspace(srcWorkspace, dstWorkspace);
777 DynDeviceTaskBase* dynTaskBase = deviceTaskCacheList[taskIndex].dynTaskBase;673 DynDeviceTaskBase* dynTaskBase = deviceTaskCacheList[taskIndex].dynTaskBase;
@@ -782,58 +678,14 @@ void DevControlFlowCache::RelocIncastOutcastTaskStructural(uint32_t taskIndex, u
782 DevAscendFunctionDuppedData* duppedData = dynFuncDataCacheList->At(dupIndex).duppedData;678 DevAscendFunctionDuppedData* duppedData = dynFuncDataCacheList->At(dupIndex).duppedData;
783 const AddressDescriptor* backupAddr = reinterpret_cast<const AddressDescriptor*>(679 const AddressDescriptor* backupAddr = reinterpret_cast<const AddressDescriptor*>(
784 dynFuncDataBackupList->At(dupIndex).rawTensorAddrBackup);680 dynFuncDataBackupList->At(dupIndex).rawTensorAddrBackup);
785- for (uint64_t i = 0; i < duppedData->GetIncastSize(); i++) {681+ ResolveLeafIncastOutcastAddrs(backupAddr, duppedData, relocWorkspace, devStartArgs, nullptr, true);
786- RelocDescFromCache(backupAddr[i], duppedData->GetIncastAddress(i), relocWorkspace, devStartArgs);682+ // Embedded table is the leaf source here. Drop the arena offset so a null inputs
787- }683+ // pointer (emulation / aicore model) cannot be indexed by a still-valid layout offset.
788- for (uint64_t i = 0; i < duppedData->GetOutcastSize(); i++) {684+ dynFuncDataList->At(dupIndex).ioAddressArenaOffset = npu::tile_fwk::kIoAddressArenaOffsetInvalid;
789- RelocDescFromCache(backupAddr[duppedData->GetIncastSize() + i], duppedData->GetOutcastAddress(i),
790- relocWorkspace, devStartArgs);
791- }
792 }685 }
793 dynFuncDataList->startArgs = devStartArgs;686 dynFuncDataList->startArgs = devStartArgs;
794}687}
795 688 
796-void DevControlFlowCache::RelocIncastOutcastTask(uint32_t taskIndex, uint64_t srcWorkspace, uint64_t dstWorkspace,
797- DevStartArgsBase* devStartArgs)
798-{
799- // Cache memory insufficient, taskRelocTabl construction failed
800- if (taskRelocTableCount != deviceTaskCount) {
801- RelocIncastOutcastTaskStructural(taskIndex, srcWorkspace, dstWorkspace, devStartArgs);
802- return;
803- }
804- uint8_t* cacheBase = reinterpret_cast<uint8_t*>(this);
805- TaskRelocEntry& entry = reinterpret_cast<TaskRelocEntry*>(cacheBase + taskRelocTableOffset)[taskIndex];
806- reinterpret_cast<DynFuncHeader*>(cacheBase + entry.dynFuncHeaderOffset)->startArgs = devStartArgs;
807- const IncastOutcastRelocBatch* batches = reinterpret_cast<const IncastOutcastRelocBatch*>(cacheBase +
808- entry.batchListOffset);
809- const uint64_t wsShift = dstWorkspace - srcWorkspace;
810- for (uint32_t j = 0; j < entry.batchCount; j++) {
811- const IncastOutcastRelocBatch& batch = batches[j];
812- const uint16_t* idxList = reinterpret_cast<const uint16_t*>(cacheBase + batch.idxListOffset);
813- const uint64_t* src = reinterpret_cast<const uint64_t*>(cacheBase + batch.srcBaseOffset);
814- uint64_t* dst = reinterpret_cast<uint64_t*>(cacheBase + batch.dstBaseOffset);
815- switch (batch.kind) {
816- case AddressCacheKind::Workspace:
817- RelocLoop<AddressCacheKind::Workspace>(batch.descCount, idxList, dst, src, wsShift, devStartArgs);
818- break;
819- case AddressCacheKind::Input:
820- RelocLoop<AddressCacheKind::Input>(batch.descCount, idxList, dst, src, wsShift, devStartArgs);
821- break;
822- case AddressCacheKind::Output:
823- RelocLoop<AddressCacheKind::Output>(batch.descCount, idxList, dst, src, wsShift, devStartArgs);
824- break;
825- case AddressCacheKind::Communication:
826- RelocLoop<AddressCacheKind::Communication>(batch.descCount, idxList, dst, src, wsShift, devStartArgs);
827- break;
828- default:
829- DEV_ERROR(ProgEncodeErr::CACHE_RELOC_KIND_INVALID,
830- "#ctrl.task.pre.cache.reloc: [RelocDescFromCache] Invalid kind: %u\n",
831- static_cast<uint32_t>(batch.kind));
832- break;
833- }
834- }
835-}
836- 
837void DevControlFlowCache::RuntimeAddrBackup(DeviceExecuteSlot* runtimeSlotList,689void DevControlFlowCache::RuntimeAddrBackup(DeviceExecuteSlot* runtimeSlotList,
838 ItemPool<RuntimeOutcastTensor>* runtimeOutcastTensorPool, uint64_t slotSize,690 ItemPool<RuntimeOutcastTensor>* runtimeOutcastTensorPool, uint64_t slotSize,
839 uint64_t runtimeOutcastTensorSize, TensorAllocator* allocator,691 uint64_t runtimeOutcastTensorSize, TensorAllocator* allocator,
@@ -283,8 +283,9 @@ struct DevControlFlowCache {
283 283 
284 uint64_t workspaceAddr;284 uint64_t workspaceAddr;
285 285 
286- uint64_t taskRelocTableOffset{0};286+ /* Total bytes of absolute IO addresses materialized per launch into AICore host-args arena.
287- uint32_t taskRelocTableCount{0};287+ * 0 means this launch has no arena: device refreshes the embedded rawTensorAddr table. */
288+ uint64_t ioAddressArenaBytes{0};
288#define ctrlFlowLastField cacheData289#define ctrlFlowLastField cacheData
289 uint64_t dataSize;290 uint64_t dataSize;
290 uint8_t data[0];291 uint8_t data[0];
@@ -501,21 +502,16 @@ struct DevControlFlowCache {
501 static void RelocDescFromCache(const AddressDescriptor& desc, AddressDescriptor& result,502 static void RelocDescFromCache(const AddressDescriptor& desc, AddressDescriptor& result,
502 const RelocRange& relocWorkspace, DevStartArgsBase* devStartArgs);503 const RelocRange& relocWorkspace, DevStartArgsBase* devStartArgs);
503 504 
504- struct IncastOutcastRelocBatch {505+ /* Shared resolve: backup cache-form → absolute AddressDescriptor.
505- uint64_t srcBaseOffset; /* rawTensorAddrBackup (cache-form descriptors, read-only) */506+ * absDst: optional arena words (GetAddressValue); writeEmbedded: optional incast/outcast table. */
506- uint64_t dstBaseOffset; /* rawTensorAddr (live addresses, rewritten per launch) */507+ static void ResolveLeafIncastOutcastAddrs(const AddressDescriptor* backupAddr,
507- uint64_t idxListOffset; /* uint16 descriptor indices covered by this batch */508+ DevAscendFunctionDuppedData* duppedData, const RelocRange& relocWorkspace,
508- uint32_t descCount; /* number of descriptors in this batch */509+ DevStartArgsBase* devStartArgs, uint64_t* absDst, bool writeEmbedded);
509- AddressCacheKind kind;
510- };
511 510 
512- struct TaskRelocEntry {511+ void AssignIoAddressArenaLayout();
513- uint64_t batchListOffset;512+ /* Host: write absolute addresses for every dup into the AICore launch host-args arena. */
514- uint64_t dynFuncHeaderOffset;513+ void MaterializeIncastOutcastAddrs(uint64_t srcWorkspace, uint64_t dstWorkspace, DevStartArgsBase* devStartArgs,
515- uint32_t batchCount;514+ uint64_t* arena) const;
516- };
517- 
518- void BuildIncastOutcastRelocTable();
519 void IncastOutcastAddrBackup(DynDeviceTaskBase* base);515 void IncastOutcastAddrBackup(DynDeviceTaskBase* base);
520 516 
521 void TaskAddrBackupWorkspace(DynDeviceTaskBase* base);517 void TaskAddrBackupWorkspace(DynDeviceTaskBase* base);
@@ -531,9 +527,6 @@ struct DevControlFlowCache {
531 void RelocIncastOutcastTask(uint32_t taskIndex, uint64_t srcWorkspace, uint64_t dstWorkspace,527 void RelocIncastOutcastTask(uint32_t taskIndex, uint64_t srcWorkspace, uint64_t dstWorkspace,
532 DevStartArgsBase* devStartArgs);528 DevStartArgsBase* devStartArgs);
533 529 
534- void RelocIncastOutcastTaskStructural(uint32_t taskIndex, uint64_t srcWorkspace, uint64_t dstWorkspace,
535- DevStartArgsBase* devStartArgs);
536- 
537 void RuntimeAddrBackup(DeviceExecuteSlot* runtimeSlotList, ItemPool<RuntimeOutcastTensor>* runtimeOutcastTensorPool,530 void RuntimeAddrBackup(DeviceExecuteSlot* runtimeSlotList, ItemPool<RuntimeOutcastTensor>* runtimeOutcastTensorPool,
538 uint64_t slotSize, uint64_t runtimeOutcastTensorSize, TensorAllocator* allocator,531 uint64_t slotSize, uint64_t runtimeOutcastTensorSize, TensorAllocator* allocator,
539 uint32_t parallelism);532 uint32_t parallelism);
@@ -174,6 +174,7 @@ private:
174 functionDevProg->controlFlowCache.isRecording = false;174 functionDevProg->controlFlowCache.isRecording = false;
175 uint64_t contextWorkspaceAddr = functionDevProg->controlFlowCache.contextWorkspaceAddr;175 uint64_t contextWorkspaceAddr = functionDevProg->controlFlowCache.contextWorkspaceAddr;
176 functionDevProg->controlFlowCache.IncastOutcastAddrReloc(contextWorkspaceAddr, 0, nullptr);176 functionDevProg->controlFlowCache.IncastOutcastAddrReloc(contextWorkspaceAddr, 0, nullptr);
177+ functionDevProg->controlFlowCache.AssignIoAddressArenaLayout();
177 functionDevProg->controlFlowCache.RuntimeAddrRelocWorkspace(contextWorkspaceAddr, 0, nullptr, nullptr,178 functionDevProg->controlFlowCache.RuntimeAddrRelocWorkspace(contextWorkspaceAddr, 0, nullptr, nullptr,
178 nullptr, functionDevProg->GetParallelism());179 nullptr, functionDevProg->GetParallelism());
179 functionDevProg->controlFlowCache.RuntimeAddrRelocProgram(reinterpret_cast<uint64_t>(functionDevProg), 0);180 functionDevProg->controlFlowCache.RuntimeAddrRelocProgram(reinterpret_cast<uint64_t>(functionDevProg), 0);
@@ -811,52 +811,7 @@ TEST(CtrlFlowCacheDrcoUt, DrcoReadyQueueDataRestore_WithMixWraps)
811 EXPECT_EQ(drco.root.devTaskFinishFlagList.flag[DRCO_QUEUE_AIV].devTaskFinishFlag, 1U);811 EXPECT_EQ(drco.root.devTaskFinishFlagList.flag[DRCO_QUEUE_AIV].devTaskFinishFlag, 1U);
812}812}
813 813 
814-TEST(CtrlFlowCacheRelocUt, BuildIncastOutcastRelocTable_EmitsKindOrderedBatches)814+TEST(CtrlFlowCacheRelocUt, RelocIncastOutcastTask_ResolvesAllKinds)
815-{
816- RelocTableFixture f;
817- f.ctrl->BuildIncastOutcastRelocTable();
818- 
819- ASSERT_EQ(f.ctrl->taskRelocTableCount, 1U);
820- ASSERT_NE(f.ctrl->taskRelocTableOffset, 0U);
821- 
822- const uint8_t* base = f.blob.data();
823- auto* table = reinterpret_cast<const DevControlFlowCache::TaskRelocEntry*>(base + f.ctrl->taskRelocTableOffset);
824- EXPECT_EQ(table[0].batchCount, 4U);
825- EXPECT_EQ(table[0].dynFuncHeaderOffset, static_cast<uint64_t>(reinterpret_cast<const uint8_t*>(f.header) - base));
826- 
827- // Batches must be dup-major and kind-ascending, each carrying the base offsets of
828- // the dup's backup (src) and live (dst) arrays and a compact index segment.
829- auto* batches = reinterpret_cast<const DevControlFlowCache::IncastOutcastRelocBatch*>(base +
830- table[0].batchListOffset);
831- const AddressCacheKind kExpectedKinds[4] = {AddressCacheKind::Workspace, AddressCacheKind::Input,
832- AddressCacheKind::Output, AddressCacheKind::Communication};
833- const uint16_t kExpectedIdx[4] = {1, 0, 2, 3};
834- for (uint32_t j = 0; j < table[0].batchCount; ++j) {
835- EXPECT_EQ(batches[j].kind, kExpectedKinds[j]);
836- EXPECT_EQ(batches[j].descCount, 1U);
837- EXPECT_EQ(batches[j].srcBaseOffset, static_cast<uint64_t>(reinterpret_cast<const uint8_t*>(f.backup) - base));
838- EXPECT_EQ(batches[j].dstBaseOffset, static_cast<uint64_t>(reinterpret_cast<const uint8_t*>(f.live) - base));
839- auto* idx = reinterpret_cast<const uint16_t*>(base + batches[j].idxListOffset);
840- EXPECT_EQ(idx[0], kExpectedIdx[j]);
841- }
842-}
843- 
844-TEST(CtrlFlowCacheRelocUt, RelocIncastOutcastTask_TablePath_ResolvesAllKinds)
845-{
846- RelocTableFixture f;
847- f.ctrl->BuildIncastOutcastRelocTable();
848- 
849- f.ctrl->RelocIncastOutcastTask(0, 0, RelocTableFixture::kDstWorkspace, &f.args);
850- 
851- // live layout: [0]=Input#1, [1]=Workspace offset, [2]=Output#0, [3]=Comm.
852- EXPECT_EQ(f.live[0], RelocTableFixture::kInputAddr);
853- EXPECT_EQ(f.live[1], RelocTableFixture::kDstWorkspace + RelocTableFixture::kWsOffset);
854- EXPECT_EQ(f.live[2], RelocTableFixture::kOutputAddr);
855- EXPECT_EQ(f.live[3], RelocTableFixture::kCommAddr);
856- EXPECT_EQ(f.dyntask->dynFuncDataList->startArgs, &f.args);
857-}
858- 
859-TEST(CtrlFlowCacheRelocUt, RelocIncastOutcastTask_NoTable_FallsBackToStructural)
860{815{
861 DeviceWorkspaceAllocator workspace;816 DeviceWorkspaceAllocator workspace;
862 auto dyntask = std::make_unique<DynDeviceTask>(workspace);817 auto dyntask = std::make_unique<DynDeviceTask>(workspace);
@@ -875,9 +830,7 @@ TEST(CtrlFlowCacheRelocUt, RelocIncastOutcastTask_NoTable_FallsBackToStructural)
875 backup[3] = CacheFormWord(AddressCacheKind::Communication, RelocTableFixture::kCommAddr);830 backup[3] = CacheFormWord(AddressCacheKind::Communication, RelocTableFixture::kCommAddr);
876 dyntask->dynFuncDataBackupList[0].rawTensorAddrBackup = backup.data();831 dyntask->dynFuncDataBackupList[0].rawTensorAddrBackup = backup.data();
877 832 
878- // No BuildIncastOutcastRelocTable: taskRelocTableCount(0) != deviceTaskCount(1)833+ // Resolves cache-form descriptors into the dupped data incast/outcast arrays.
879- // must route the call into RelocIncastOutcastTaskStructural, which resolves the
880- // descriptors into the dupped data's own incast/outcast arrays.
881 DevControlFlowCache ctrl;834 DevControlFlowCache ctrl;
882 DeviceTaskCache entry;835 DeviceTaskCache entry;
883 entry.dynTaskBase = dyntask.get();836 entry.dynTaskBase = dyntask.get();
@@ -901,4 +854,68 @@ TEST(CtrlFlowCacheRelocUt, RelocIncastOutcastTask_NoTable_FallsBackToStructural)
901 EXPECT_EQ(duppedData->GetOutcastAddress(0).GetAddressValue(), RelocTableFixture::kOutputAddr);854 EXPECT_EQ(duppedData->GetOutcastAddress(0).GetAddressValue(), RelocTableFixture::kOutputAddr);
902 EXPECT_EQ(duppedData->GetOutcastAddress(1).GetAddressValue(), RelocTableFixture::kCommAddr);855 EXPECT_EQ(duppedData->GetOutcastAddress(1).GetAddressValue(), RelocTableFixture::kCommAddr);
903 EXPECT_EQ(dyntask->dynFuncDataList->startArgs, &args);856 EXPECT_EQ(dyntask->dynFuncDataList->startArgs, &args);
857+ EXPECT_EQ(dyntask->dynFuncDataList->At(0).ioAddressArenaOffset, npu::tile_fwk::kIoAddressArenaOffsetInvalid);
858+}
859+ 
860+TEST(CtrlFlowCacheRelocUt, MaterializeIoAddressArena)
861+{
862+ RelocTableFixture f;
863+ f.ctrl->AssignIoAddressArenaLayout();
864+ ASSERT_EQ(f.ctrl->ioAddressArenaBytes, 4U * sizeof(uint64_t));
865+ EXPECT_EQ(f.header->At(0).ioAddressArenaOffset, 0U);
866+ 
867+ std::array<uint64_t, 4> arena{};
868+ f.ctrl->MaterializeIncastOutcastAddrs(0, RelocTableFixture::kDstWorkspace, &f.args, arena.data());
869+ EXPECT_EQ(arena[0], RelocTableFixture::kInputAddr);
870+ EXPECT_EQ(arena[1], RelocTableFixture::kDstWorkspace + RelocTableFixture::kWsOffset);
871+ EXPECT_EQ(arena[2], RelocTableFixture::kOutputAddr);
872+ EXPECT_EQ(arena[3], RelocTableFixture::kCommAddr);
873+ 
874+ // Simulate leaf entry: param.rawTensorAddr = arena + element index (no /8).
875+ uint64_t* table = arena.data() + f.header->At(0).ioAddressArenaOffset;
876+ EXPECT_EQ(table, arena.data());
877+ EXPECT_EQ(table[0], RelocTableFixture::kInputAddr);
878+ EXPECT_EQ(table[2], RelocTableFixture::kOutputAddr);
879+}
880+ 
881+// Materialize (arena words) and Reloc (embedded AddressDescriptors) must resolve the same
882+// absolute addresses from the same backup + startArgs. Guards the shared ResolveLeaf path.
883+TEST(CtrlFlowCacheRelocUt, MaterializeAndReloc_ResolveSameAbsoluteAddrs)
884+{
885+ RelocTableFixture f;
886+ f.ctrl->AssignIoAddressArenaLayout();
887+ ASSERT_EQ(f.ctrl->ioAddressArenaBytes, 4U * sizeof(uint64_t));
888+ 
889+ std::array<uint64_t, 4> arena{};
890+ f.ctrl->MaterializeIncastOutcastAddrs(0, RelocTableFixture::kDstWorkspace, &f.args, arena.data());
891+ f.ctrl->RelocIncastOutcastTask(0, 0, RelocTableFixture::kDstWorkspace, &f.args);
892+ 
893+ EXPECT_EQ(f.duppedData->GetIncastAddress(0).GetAddressValue(), arena[0]);
894+ EXPECT_EQ(f.duppedData->GetIncastAddress(1).GetAddressValue(), arena[1]);
895+ EXPECT_EQ(f.duppedData->GetOutcastAddress(0).GetAddressValue(), arena[2]);
896+ EXPECT_EQ(f.duppedData->GetOutcastAddress(1).GetAddressValue(), arena[3]);
897+ 
898+ EXPECT_EQ(arena[0], RelocTableFixture::kInputAddr);
899+ EXPECT_EQ(arena[1], RelocTableFixture::kDstWorkspace + RelocTableFixture::kWsOffset);
900+ EXPECT_EQ(arena[2], RelocTableFixture::kOutputAddr);
901+ EXPECT_EQ(arena[3], RelocTableFixture::kCommAddr);
902+ EXPECT_EQ(f.header->At(0).ioAddressArenaOffset, npu::tile_fwk::kIoAddressArenaOffsetInvalid);
903+ EXPECT_EQ(f.dyntask->dynFuncDataList->startArgs, &f.args);
904+}
905+ 
906+// Single ResolveLeaf call writing both sinks must keep arena words == embedded GetAddressValue.
907+TEST(CtrlFlowCacheRelocUt, ResolveLeaf_ArenaAndEmbedded_Consistent)
908+{
909+ RelocTableFixture f;
910+ RelocRange relocWorkspace(0, RelocTableFixture::kDstWorkspace);
911+ const AddressDescriptor* backupAddr = reinterpret_cast<const AddressDescriptor*>(f.backup);
912+ std::array<uint64_t, 4> arena{};
913+ 
914+ DevControlFlowCache::ResolveLeafIncastOutcastAddrs(backupAddr, f.duppedData, relocWorkspace, &f.args, arena.data(),
915+ true);
916+ 
917+ EXPECT_EQ(f.duppedData->GetIncastAddress(0).GetAddressValue(), arena[0]);
918+ EXPECT_EQ(f.duppedData->GetIncastAddress(1).GetAddressValue(), arena[1]);
919+ EXPECT_EQ(f.duppedData->GetOutcastAddress(0).GetAddressValue(), arena[2]);
920+ EXPECT_EQ(f.duppedData->GetOutcastAddress(1).GetAddressValue(), arena[3]);
904}921}
@@ -0,0 +1,100 @@
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+#include <gtest/gtest.h>
12+#include <cstdint>
13+#include <cstring>
14+#include <new>
15+#include <vector>
16+ 
17+#include "interface/machine/device/tilefwk/aikernel_tensor.h"
18+#include "machine/runtime/runner/aicore_launch_args.h"
19+#include "machine/utils/dynamic/dev_encode_program.h"
20+#include "machine/utils/dynamic/dev_encode_program_ctrlflow_cache.h"
21+#include "machine/utils/dynamic/dev_encode_tensor.h"
22+ 
23+using namespace npu::tile_fwk;
24+using namespace npu::tile_fwk::dynamic;
25+ 
26+TEST(AicoreLaunchArgsTest, LayoutBytes)
27+{
28+ EXPECT_EQ(AicoreLaunchSlotsBytes(), kAicoreLaunchArgSlots * sizeof(void*));
29+ EXPECT_EQ(AicoreLaunchArgsBytes(0), AicoreLaunchSlotsBytes());
30+ EXPECT_EQ(AicoreLaunchArgsBytes(8), AicoreLaunchSlotsBytes() + 8);
31+ EXPECT_EQ(AicoreLaunchArgsBytes(1) % 8, 0u);
32+}
33+ 
34+TEST(AicoreLaunchArgsTest, InitAicoreHostInputInfo)
35+{
36+ RtHostInputInfo info{};
37+ InitAicoreHostInputInfo(info);
38+ EXPECT_EQ(info.addrOffset, static_cast<uint32_t>(kAicoreInputsSlot * sizeof(void*)));
39+ EXPECT_EQ(info.dataOffset, static_cast<uint32_t>(AicoreLaunchSlotsBytes()));
40+}
41+ 
42+TEST(AicoreLaunchArgsTest, PrepareNullArgsIsNoOp)
43+{
44+ std::vector<uint8_t> buf;
45+ RtArgsEx rtArgs{};
46+ rtArgs.argsSize = 123;
47+ PrepareAicoreLaunchArgsBuffer(buf, nullptr, "op", 0, rtArgs);
48+ EXPECT_EQ(rtArgs.args, nullptr);
49+ EXPECT_EQ(rtArgs.argsSize, 0u);
50+ EXPECT_EQ(rtArgs.hostInputInfoNum, 0u);
51+}
52+ 
53+TEST(AicoreLaunchArgsTest, PrepareFillsSevenSlots)
54+{
55+ alignas(AiCpuArgs) uint8_t raw[sizeof(AiCpuArgs) + 2 * sizeof(int64_t) + sizeof(DevTensorData)] = {};
56+ auto* aicpuArgs = new (raw) AiCpuArgs();
57+ aicpuArgs->kArgs.cfgdata = reinterpret_cast<int64_t*>(0x1000);
58+ int64_t* inputp = reinterpret_cast<int64_t*>(aicpuArgs + 1);
59+ inputp[0] = 1;
60+ inputp[1] = 0;
61+ 
62+ std::vector<uint8_t> buf;
63+ RtArgsEx rtArgs{};
64+ PrepareAicoreLaunchArgsBuffer(buf, aicpuArgs, "demo_op", 0, rtArgs);
65+ 
66+ ASSERT_EQ(buf.size(), AicoreLaunchSlotsBytes());
67+ ASSERT_EQ(rtArgs.argsSize, static_cast<uint32_t>(AicoreLaunchSlotsBytes()));
68+ ASSERT_EQ(rtArgs.hostInputInfoNum, 0u);
69+ auto* slots = reinterpret_cast<void**>(buf.data());
70+ EXPECT_STREQ(static_cast<const char*>(slots[0]), "demo_op");
71+ EXPECT_EQ(slots[1], nullptr);
72+ EXPECT_EQ(slots[4], inputp);
73+ EXPECT_EQ(slots[5], aicpuArgs->kArgs.cfgdata);
74+ EXPECT_EQ(slots[6], reinterpret_cast<DevTensorData*>(inputp + DEV_TENSOR_DATA_OFFSET));
75+}
76+ 
77+TEST(AicoreLaunchArgsTest, PrepareGrowsForArenaThenFillNoCrashOnNullHostCache)
78+{
79+ alignas(AiCpuArgs) uint8_t raw[sizeof(AiCpuArgs) + 2 * sizeof(int64_t)] = {};
80+ auto* aicpuArgs = new (raw) AiCpuArgs();
81+ aicpuArgs->kArgs.workspace = reinterpret_cast<int64_t*>(0x2000);
82+ 
83+ std::vector<uint8_t> buf;
84+ RtArgsEx rtArgs{};
85+ RtHostInputInfo hostInfo{};
86+ constexpr size_t kArenaBytes = 32;
87+ PrepareAicoreLaunchArgsBuffer(buf, aicpuArgs, "op", kArenaBytes, rtArgs);
88+ ASSERT_EQ(buf.size(), AicoreLaunchArgsBytes(kArenaBytes));
89+ 
90+ // Null hostCache must not enable host-input.
91+ FillAicoreIoAddressArenaBuffer(buf, aicpuArgs, nullptr, 1, 0, rtArgs, hostInfo);
92+ EXPECT_EQ(rtArgs.hostInputInfoNum, 0u);
93+}
94+ 
95+TEST(AicoreLaunchArgsTest, EnsureHostCtrlFlowCacheRebasedNullSafe)
96+{
97+ EnsureHostCtrlFlowCacheRebased(nullptr, nullptr);
98+ DevAscendProgram prog{};
99+ EnsureHostCtrlFlowCacheRebased(nullptr, &prog);
100+}
@@ -67,11 +67,13 @@ TEST(CtrlFlowCacheManagerTest, ControlFlowCache_Constructor)
67 EXPECT_NE(cache.hash, 0);67 EXPECT_NE(cache.hash, 0);
68}68}
69 69 
70-TEST(CtrlFlowCacheManagerTest, HostControlFlowCache_Constructor)70+TEST(CtrlFlowCacheManagerTest, ControlFlowCache_WithHostMirror)
71{71{
72 std::vector<DeviceTensorData> datas = {{DT_FP32, nullptr, {2, 4}}};72 std::vector<DeviceTensorData> datas = {{DT_FP32, nullptr, {2, 4}}};
73 CtrlFlowCacheBlob hostCache = {1, 2, 3, 4, 5};73 CtrlFlowCacheBlob hostCache = {1, 2, 3, 4, 5};
74- HostControlFlowCache cache(datas, std::move(hostCache));74+ auto* cachePtr = reinterpret_cast<uint8_t*>(0x2000);
75+ ControlFlowCache cache(datas, cachePtr, std::move(hostCache));
76+ EXPECT_EQ(cache.devCache, cachePtr);
75 EXPECT_EQ(cache.hostCache.size(), 5u);77 EXPECT_EQ(cache.hostCache.size(), 5u);
76 EXPECT_EQ(cache.hostCache[0], 1);78 EXPECT_EQ(cache.hostCache[0], 1);
77 EXPECT_NE(cache.hash, 0);79 EXPECT_NE(cache.hash, 0);
@@ -27,23 +27,23 @@ struct KernelBinaryTestHelper {
27 new (&kb->pinnedGraph_) std::vector<std::shared_ptr<Function>>();27 new (&kb->pinnedGraph_) std::vector<std::shared_ptr<Function>>();
28 new (&kb->inferShapeCaches) std::vector<ControlFlowCache>();28 new (&kb->inferShapeCaches) std::vector<ControlFlowCache>();
29 new (&kb->originShapeCaches) std::vector<ControlFlowCache>();29 new (&kb->originShapeCaches) std::vector<ControlFlowCache>();
30- new (&kb->hostCtrlFlowCaches_) std::vector<HostControlFlowCache>();30+ new (&kb->valueDependCache_) KernelBinary::ValueDependCtrlFlowCache();
31 new (&kb->aicpuArgBuf) std::vector<int64_t>();31 new (&kb->aicpuArgBuf) std::vector<int64_t>();
32 new (&kb->argTypes) std::vector<DeviceTensorData>();32 new (&kb->argTypes) std::vector<DeviceTensorData>();
33 new (&kb->dynamicCellMatchDescPatches_) std::vector<DevDynamicCellMatchStridePatch>();33 new (&kb->dynamicCellMatchDescPatches_) std::vector<DevDynamicCellMatchStridePatch>();
34 new (&kb->kernelName_) std::string();34 new (&kb->kernelName_) std::string();
35- new (&kb->kernelArgs_) std::vector<void*>();35+ new (&kb->aicoreArgBuf_) std::vector<uint8_t>();
36 }36 }
37 37 
38 ~KernelBinaryTestHelper()38 ~KernelBinaryTestHelper()
39 {39 {
40 if (kb) {40 if (kb) {
41- kb->kernelArgs_.~vector();41+ kb->aicoreArgBuf_.~vector();
42 kb->kernelName_.~basic_string();42 kb->kernelName_.~basic_string();
43 kb->dynamicCellMatchDescPatches_.~vector();43 kb->dynamicCellMatchDescPatches_.~vector();
44 kb->argTypes.~vector();44 kb->argTypes.~vector();
45 kb->aicpuArgBuf.~vector();45 kb->aicpuArgBuf.~vector();
46- kb->hostCtrlFlowCaches_.~vector();46+ kb->valueDependCache_.~ValueDependCtrlFlowCache();
47 kb->originShapeCaches.~vector();47 kb->originShapeCaches.~vector();
48 kb->inferShapeCaches.~vector();48 kb->inferShapeCaches.~vector();
49 kb->pinnedGraph_.~vector();49 kb->pinnedGraph_.~vector();
@@ -77,7 +77,7 @@ TEST(KernelBinaryTest, RefReturningGetters)
77 KernelBinaryTestHelper helper;77 KernelBinaryTestHelper helper;
78 auto& config = helper.kb->GetMachineConfig();78 auto& config = helper.kb->GetMachineConfig();
79 (void)config;79 (void)config;
80- EXPECT_TRUE(helper.kb->GetHostCtrlFlowCaches().empty());80+ EXPECT_EQ(helper.kb->GetActiveHostCtrlFlowCache(), nullptr);
81 EXPECT_TRUE(helper.kb->GetArgTypes().empty());81 EXPECT_TRUE(helper.kb->GetArgTypes().empty());
82 auto& aicpuLaunchDesc = helper.kb->GetAicpuLaunchDesc();82 auto& aicpuLaunchDesc = helper.kb->GetAicpuLaunchDesc();
83 (void)aicpuLaunchDesc;83 (void)aicpuLaunchDesc;
@@ -85,7 +85,7 @@ TEST(KernelBinaryTest, RefReturningGetters)
85 (void)aicoreArgs;85 (void)aicoreArgs;
86 auto& taskCfg = helper.kb->GetRtTaskCfg();86 auto& taskCfg = helper.kb->GetRtTaskCfg();
87 (void)taskCfg;87 (void)taskCfg;
88- EXPECT_TRUE(helper.kb->GetKernelArgs().empty());88+ EXPECT_TRUE(helper.kb->aicoreArgBuf_.empty());
89}89}
90 90 
91TEST(KernelBinaryTest, SetSyncMode_And_GetSyncMode)91TEST(KernelBinaryTest, SetSyncMode_And_GetSyncMode)
@@ -103,7 +103,7 @@ extern "C" [aicore] void TENSOR_PATH0_4_0(CoreFuncParam* param, int64_t GMStackB
103 103 
104extern "C" __global__ [aicore] void PvModelKernelEntry(__gm__ npu::tile_fwk::DynFuncHeader *funcHeader, __gm__ uint64_t *opAttrs) {104extern "C" __global__ [aicore] void PvModelKernelEntry(__gm__ npu::tile_fwk::DynFuncHeader *funcHeader, __gm__ uint64_t *opAttrs) {
105 __gm__ npu::tile_fwk::DynFuncData *funcData = (__gm__ npu::tile_fwk::DynFuncData*)(funcHeader + 1);105 __gm__ npu::tile_fwk::DynFuncData *funcData = (__gm__ npu::tile_fwk::DynFuncData*)(funcHeader + 1);
106- CoreFuncParam param = {funcData, funcHeader, opAttrs, funcData->exprTbl};106+ CoreFuncParam param = {funcData, funcHeader, opAttrs, funcData->exprTbl, 0, nullptr, funcData->rawTensorAddr};
107 TENSOR_PATH0_4_0(&param, funcHeader->stackWorkSpaceAddr, (__gm__ int64_t *)funcHeader->startArgs->commContexts, (__gm__ FedProfLeafTaskProf*)NULL);107 TENSOR_PATH0_4_0(&param, funcHeader->stackWorkSpaceAddr, (__gm__ int64_t *)funcHeader->startArgs->commContexts, (__gm__ FedProfLeafTaskProf*)NULL);
108}108}
109 109 
@@ -90,7 +90,10 @@ _SUBPROCESS_SCRIPT = textwrap.dedent(
90 torch_npu.npu.synchronize()90 torch_npu.npu.synchronize()
91 91 
92 assert torch.allclose(output_data, golden), "onboard dump kernel result mismatch"92 assert torch.allclose(output_data, golden), "onboard dump kernel result mismatch"
93- print("SUBPROCESS_OK")93+ print("SUBPROCESS_OK", flush=True)
94+ # Skip Ascend/platform static destructors that can abort after a successful run
95+ # (seen as free(): invalid size in PlatformManagerV2::~PlatformManagerV2).
96+ os._exit(0)
94 """97 """
95)98)
96 99