Closed
[Requirement|需求建议]: Mix Pending方案(Mix+非Mix混合全场景) #2670
xuyi_37Add on  Jul 16Closed at  Jul 31
xuyi_37
xuyi_37Collaborators
Jul 16 Create

Mix Pending方案(Mix+非Mix混合全场景)

1. 需求分析

1.1 需求背景

在 SWA、FA、FAG 等算子的 A5 版本中,使能 CVC 的 Mix 合图后,发现 Mix 子图任务间的调度间隙较大(约 13us)。根因是 Machine 层的任务调度器不支持 Mix 类型任务的 Pending 机制——当前一个 Mix 任务在 AICore 上执行时,后续 Mix 任务无法提前绑定到 Pending 槽,导致前一个任务释放核后,下一个任务存在明显的调度空窗期。
image.png

1.2 规格分析

本需求在 Machine 层为 Mix 任务实现完整的 Pending 支持,使后续 Mix 任务能在前序任务运行期间预先绑定到 Pending 槽,实现任务流水线化,降低调度缝隙。主要需要支持以下规格:

  • Mix和非Mix的混和Pending机制
  • Mix需要支持1C2V和1C1V

2 方案设计

2.1 调度流程

任务下发流程图:
任务下发流程图

主要适配点:

  1. 在DispatchMixCoreTask中增加了Binding pendingIds和SendTaskToAicore步骤。为此,需要Mix需要感知到pending核(之前在ReleaseCore时遇到是mix任务的核, pendingCnt都不会++, 加上对应的wrapAvail[i]=false, 非mix任务无法使用这些pending核去做任务下发)。
  • 1.1 Binding pendingIds当前不依赖pendingCnt,而是直接遍历[coreStart, coreEnd),所有都处于pending状态才下发。
  1. 在ReleaseCore时,对于Mix类型的任务,遇到CopyOut或者ACK状态,也要释放pending核。
  2. 在ReleaseCore时,遇到pendingId=FIN或RuningId=FIN时,增加UpdateFinishForMixCore处理。
  3. wrapAvail含义不变,表示是否可以给非mix任务使用,但是赋值的场景做修改:pending槽被mix占用时设置为false,pending槽释放是设置为true,具体场景参照第2章。

关于pending的任务管理,涉及以下几个关键参数

  • wrapCoreAvail_[CoreNum]:保护被Mix占用的核不被非Mix任务抢占,由于Mix任务不是同步的,所以存在提前锁核(当前只有1C任务,实际会把1C2V的核都锁掉),让其它非Mix任务无法占用,如果被占用,会导致Mix和非Mix的混合调用,引起精度和性能问题
  • corePendReadyCnt_:当前Pending的核数,用于计算多少可以下发Pending任务
  • coreIdxPosition_: coreIdx到pos的映射,pos表是在runReadyCoreIdx_的索引,如果是不可用核,那么存储的是INVALID_COREIDX_POSITION
  • pendingIds:每个核的pending的Task的taskId,taskId=AICORE_TASK_INIT的表示没有任务
  • coreRunReadyCnt_: 表示pending和running槽位都为空的核的个数
  • runReadyCoreIdx_: 存储可用核,总个数为coreRunCnt,后空闲的核放在尾部
  • runningIds:每个核的running的Task的taskId,taskId=AICORE_TASK_INIT的表示没有任务

其中,wrapCoreAvail_的使用场景:

  • TrySendTaskDirectly 找pending核
  • BatchSendTask找pending核
  • ReleaseCoreByRegValByAsyncMode中判断要不要更新corePendReadyCnt_等字段

2.2 Mix pending状态管理

任务状态转换图:
任务状态转换图

2.2.1 mix pending感知时机

ReleaseCoreByRegVal时

  1. CopyOut状态,finTaskId == pendingIdRef && aicpuCallCode != 0
  2. ACK状态,finTaskId == pendingIdRef && finTaskState == TASK_ACK_STATE

2.2.2 状态管理

wrapCoreAvail_的状态:(这个字段主要是mix任务提前占核后防止被非mix任务抢占,有了MixHub之后,mix的几个task都是一起下发的,不存在提前占核不使用的情况,所以这个字段可以删除)
pending槽被mix占用时设置为false。具体的:

  • Bind runningIds时(mix任务)
  • Bind pendingIds时(mix任务)

pending槽释放是设置为true。具体的:

  • 下发mix任务时或绑核时,wrapCoreAvail_设为false,也即状态0->状态1,状态2->状态3
  • 状态1->状态2,wrapCoreAvail_设为true
  • 状态1->状态4 或 状态2->状态4,wrapCoreAvail_设为true

corePendReadyCnt_的状态:
pend核被使用或被mix锁定时,corePendReadyCnt_--。具体的:

  • Bind runningIds时(mix任务)
  • Bind pendingIds时(mix任务)
  • DirectSendTask时(非mix任务)
  • BatchSendTask时(非mix任务)

pend核释放时,corePendReadyCnt_++。具体的:

  • 对应状态1->4, 状态3->状态4
  • 状态1->状态2

pendingIds的状态:
下发任务时,id由AICORE_TASK_INIT变成下发的taskId,具体的:

  • SendTaskToCore时(Mix和非Mix任务)

pending槽上的任务结束时,id由taskId变成AICORE_TASK_INIT,具体的:

  • 状态1->状态2, 即pending转running
  • 状态1->状态4, 状态3->状态4, 即pending任务结束

其它字段的含义核状态转换维持不变。

2.3 mix何时使用Pending

DispatchMixTask,当runingIds核都下发后,可以使用pendingIds核下发。参照流程图中黄色部分。

2.3.1 计算可用核

inline uint32_t GetWrapCorePendingCnt(uint32_t& core1c1vCnt, uint32_t& core1c2vCnt) {
        for (uint32_t idx = aicStart_; idx < aicEnd_; idx++) {
            uint32_t aivIdx0 = GetWrapAiv0CoreIdx(idx);
            uint32_t aivIdx1 = GetWrapAiv1CoreIdx(aivIdx0);
            if (pendingIds_[idx] == AICORE_TASK_INIT && pendingIds_[aivIdx0] == AICORE_TASK_INIT) {
                if (pendingIds_[aivIdx1] == AICORE_TASK_INIT) {
                    core1c2vCnt++;
                } else {
                    core1c1vCnt++;
                }
            }
        }
        return core1c1vCnt + core1c2vCnt;
    }

2.3.2 绑核下发

    inline void UpdateWrapQueueForThreadByPending(WrapInfo* wrap1c2vTasks[], uint32_t task1c2vCnt,
                                                  WrapInfo* wrap1c1vTasks[], uint32_t task1c1vCnt)
    {
        uint32_t idx = aicStart_;
        for (uint32_t taskIdx = 0; taskIdx < task1c2vCnt; taskIdx++) {
            WrapInfo* wrapInfo = wrap1c2vTasks[taskIdx];
            wrapQueueForThread_->elem[wrapQueueForThread_->tail++] = reinterpret_cast<uint64_t>(wrapInfo);
            for (; idx < aicEnd_; idx++) {
                uint32_t aicIdx = idx;
                uint32_t aivIdx0 = GetWrapAiv0CoreIdx(aicIdx);
                uint32_t aivIdx1 = GetWrapAiv1CoreIdx(aivIdx0);

                if (pendingIds_[aicIdx] == AICORE_TASK_INIT && pendingIds_[aivIdx0] == AICORE_TASK_INIT &&
                    pendingIds_[aivIdx1] == AICORE_TASK_INIT) {
                    wrapInfo->aicCoreIdx = aicIdx;
                    CheckAndSendTask(wrapInfo, WRAP_IDX_AIC, CoreType::AIC, aicIdx);
                    CheckAndSendTask(wrapInfo, WRAP_IDX_AIV0, CoreType::AIV, aivIdx0);
                    CheckAndSendTask(wrapInfo, WRAP_IDX_AIV1, CoreType::AIV, aivIdx1);
                    TryRemoveCoreIdxFromPending(aicIdx, CORE_IDX_AIC);
                    TryRemoveCoreIdxFromPending(aivIdx0, CORE_IDX_AIV);
                    TryRemoveCoreIdxFromPending(aivIdx1, CORE_IDX_AIV);
                    idx++;
                    break;
                }
            }
        }

        idx = aicStart_;
        for (uint32_t taskIdx = 0; taskIdx < task1c1vCnt; taskIdx++) {
            WrapInfo* wrapInfo = wrap1c1vTasks[taskIdx];
            wrapQueueForThread_->elem[wrapQueueForThread_->tail++] = reinterpret_cast<uint64_t>(wrapInfo);
            for (; idx < aicEnd_; idx++) {
                uint32_t aicIdx = idx;
                uint32_t aivIdx0 = GetWrapAiv0CoreIdx(aicIdx);

                if (pendingIds_[aicIdx] == AICORE_TASK_INIT && pendingIds_[aivIdx0] == AICORE_TASK_INIT) {
                    wrapInfo->aicCoreIdx = aicIdx;
                    CheckAndSendTask(wrapInfo, WRAP_IDX_AIC, CoreType::AIC, aicIdx);
                    CheckAndSendTask(wrapInfo, WRAP_IDX_AIV0, CoreType::AIV, aivIdx0);
                    TryRemoveCoreIdxFromPending(aicIdx, CORE_IDX_AIC);
                    TryRemoveCoreIdxFromPending(aivIdx0, CORE_IDX_AIV);
                    idx++;
                    break;
                }
            }
        }
    }

2.4 同步问题及其解决方案

2.4.1 同步问题

image.png
使用Pending之后存在同步问题,主要表现在以下两个方面:

  1. 第一个Mix的V正在处理UB上的数据,第二个Mix的C往V上写东西,导致UB上出现脏数据。
  2. 关于死锁问题:一个mix的C先结束了,下一个mix的C立刻开始的话,有没有可能两个都有set 1, 被前一个mix的V的wait 1给消掉了。导致下个mix的V的wait 1死锁。——实际上,当前使用的set_intra_block的锁,是计数器类型, 4bit计数,只要>=16就不会有溢出风险,不存在死锁问题。

image.png
注:

  1. set_intra和wait_intra是CCE内的核间同步
  2. 1C2V也是同理

2.4.2 解决方案

在第二个Mix任务开始的位置插入同步。


** 废弃,以下分析基于set_intra_block是bool类型,可能存在死锁问题 的分析**
image.png
注:

  1. 蓝色同步为Machine尝试插入的指令,如果Mix0最后一条wait_intra指令(后面没有set_intra的是最后一条)在V(即C->V的同步), 那么Mix1的C要先插wait_intra(即V->C的同步);反之,Mix1要插C->V的同步。
  2. 由1可知,Mix1需要知道Mix0的最后同步方向即可,eventId不重要, 并且只用插单向同步,无需双向同步(图中第二组蓝色同步不需要)
  3. 插反的情况,如果V的最后有1~多个wait_intra, idx与他们的eventId都不相同,那么应该也不会出问题,否则可能出现死锁
  4. wait_intra插在S上,阻塞后续指令下发,不会有内存踩踏问题
  5. 1C2V的情况,如果也采用这种同步,需要考虑1C和2V的方向不一致的场景

实际上,不存在死锁的情况下,只要在第二个Mix的开头插一对正反向同步即可。1c1v和1c2v都采用模式4的统一同步方式。

当前1C2V的同步,不再使用

INLINE void PipeSyncPre(uint8_t mixResourceType, uint8_t lastMixResourceType)
{
  // only lastTask is mix should insert sync
  if (lastMixResourceType == static_cast<uint8_t>(MixResourceType::MIX_UNKNOWN) || mixResourceType != static_cast<uint8_t>(MixResourceType::MIX_1C2V)) {
      return;
  }
#if defined(__AIV__)
  wait_flag_dev(PIPE_S, EVENT_ID7);
  ffts_cross_core_sync(PIPE_MTE3, GetffstMsg(2, EVENT_ID7)); // 模式2:Block内CV之间的同步,插在callop开始,这里pipe不重要,前面流水必然已执行完
#else
  ffts_cross_core_sync(PIPE_FIX, GetffstMsg(2, EVENT_ID7)); // 模式2:Block内CV之间的同步,插在callop开始,这里pipe不重要,前面流水必然已执行完
  wait_flag_dev(PIPE_S, EVENT_ID7);
#endif
}

统一同步方式:1C1V,1C2V统一采用模式4

#ifdef __DAV_V310
INLINE void PipeSyncPre(uint8_t mixResourceType, uint8_t lastMixResourceType)
{
  // only lastTask and curTask are mix should insert sync
  if (lastMixResourceType == static_cast<uint8_t>(MixResourceType::MIX_UNKNOWN) ||
      mixResourceType == static_cast<uint8_t>(MixResourceType::MIX_UNKNOWN)) {
      return;
  }
#if defined(__AIV__)
  set_intra_block(
          PIPE_S, EVNET_ID15); // 模式4:Block内C和V之间的同步,插在callop开始,这里pipe不重要,前面流水必然已执行完
  wait_intra_block(PIPE_S, EVNET_ID15); // PIPE_S阻塞后续指令下发,避免与后续的CCE指令EventId冲突
#else
  if (mixResourceType == static_cast<uint8_t>(MixResourceType::MIX_1C2V)) {
      set_intra_block(PIPE_S, EVNET_ID15);                       // 作用于Vec0
      set_intra_block(PIPE_S, EVNET_ID15 + EVNET_NUMS_PER_AIV);  // 作用与Vec1
      wait_intra_block(PIPE_S, EVNET_ID15);                      // 等待Vec0
      wait_intra_block(PIPE_S, EVNET_ID15 + EVNET_NUMS_PER_AIV); // 等待Vec1
  } else {
      set_intra_block(PIPE_S, EVNET_ID15);  // 作用于Vec0
      wait_intra_block(PIPE_S, EVNET_ID15); // 等待Vec0
  }
#endif
}
#endif

同步存在问题,由于mix的几个任务共用一份gmStack,所以一个block上必须全部mix任务结束才能开始下一个mix任务,否则mix+mix场景可能出现两个Vector踩踏gmStack:参见https://gitcode.com/cann/pypto/pull/6909 https://gitcode.com/cann/pypto/issues/3563
image.png

所以正确的同步方式如下:

#ifdef __DAV_V310
INLINE void PipeSyncPre(uint8_t mixResourceType, uint8_t lastMixResourceType)
{
  // only lastTask and curTask are mix should insert sync
  if (lastMixResourceType == static_cast<uint8_t>(MixResourceType::MIX_UNKNOWN) ||
      mixResourceType == static_cast<uint8_t>(MixResourceType::MIX_UNKNOWN)) {
      return;
  }
#if defined(__AIV__)
  set_intra_block(
          PIPE_S, EVNET_ID15); // 模式4:Block内C和V之间的同步,插在callop开始,这里pipe不重要,前面流水必然已执行完
  wait_intra_block(PIPE_S, EVNET_ID15); // PIPE_S阻塞后续指令下发,避免与后续的CCE指令EventId冲突
#else
  if (mixResourceType == static_cast<uint8_t>(MixResourceType::MIX_1C2V)) {
      wait_intra_block(PIPE_S, EVNET_ID15);                      // 等待Vec0
      wait_intra_block(PIPE_S, EVNET_ID15 + EVNET_NUMS_PER_AIV); // 等待Vec1
      set_intra_block(PIPE_S, EVNET_ID15);                       // 作用于Vec0
      set_intra_block(PIPE_S, EVNET_ID15 + EVNET_NUMS_PER_AIV);  // 作用与Vec1
  } else {
      wait_intra_block(PIPE_S, EVNET_ID15); // 等待Vec0
      set_intra_block(PIPE_S, EVNET_ID15);  // 作用于Vec0
  }
#endif
}
#endif

由于开放了Mix+非Mix的混合Pending,mix1的两个V前面插了非mix,C中间的前面是mix,导致mix1只有C会插同步,死锁了。mix1c1v+mix1c2v的场景也有类似的问题。 解决方案:在所有mix前插同步。
image.png

2.5 全字段管理

在SchduleContext中控核相关字段: wrapCoreAvail_、corePendReadyCnt_、 coreIdxPosition_、coreRunReadyCnt_ 、runReadyCoreIdx_。这些字段相互关联,可以提供统一的接口进行管理。

2.5.1 接口统一

在SchduleContext中提供统一的接口, 管理上述字段。
现状:

  1. 当前在aicore_manager.h和wrap_manager.h中各提供了接口,对上述字段进行了修改
  2. 用于计算上述字段的入参coreIdx和type这两个字段当前类型比较乱,coreIdx有三种类型:int、uint32_t、uint16_t, type也有三种:int、uint32_t、uint8_t

提供接口如下:

  1. 提供3个Add接口
// 向Running槽添加空闲核
	inline void AddRunReadyCoreIdx(int coreIdx, int type)
  {
      coreIdxPosition_[coreIdx] = coreRunReadyCnt_[type];
      runReadyCoreIdx_[type][coreRunReadyCnt_[type]++] = coreIdx;
  }
  
  // 向Pending槽添加空闲核
	inline void AddPendReadyCoreIdx(int coreIdx, int type)
  {
      corePendReadyCnt_[static_cast<int>(type)]++;
      wrapCoreAvail_[coreIdx] = true;
  }
  
  // 向Running和Pending槽添加空闲核
  inline void AddRunAndPendCoreIdx(int coreIdx, int type)
  {
      AddRunReadyCoreIdx(coreIdx, type);
      AddPendReadyCoreIdx(coreIdx, type);
  }
  1. 提供4个Remove接口
	// 从 Pending和Running槽删除
    inline void RemoveRunAndPendCoreIdx(int coreIdx, int type)
  {
      RemoveRunReadyCoreIdx(coreIdx, type);
      RemovePendReadyCoreIdx(coreIdx, type);
  }

  // 从Pending槽 删除
  inline void RemovePendReadyCoreIdx(int coreIdx, int type)
  {
      corePendReadyCnt_[type]--;
      wrapCoreAvail_[coreIdx] = false;
  }

  //  从Running槽删除
  inline void RemoveRunReadyCoreIdx(int coreIdx, int type)
  {
      uint8_t pos = coreIdxPosition_[coreIdx];
      if (pos == INVALID_COREIDX_POSITION) {
          DEV_WARN("RemoveRunReadyCoreIdx: coreIdx %d not in runReady list (pos=INVALID)", coreIdx);
          return;
      }

      uint32_t tail = --coreRunReadyCnt_[type];
      if (pos != tail) {
          runReadyCoreIdx_[type][pos] = runReadyCoreIdx_[type][tail];
          coreIdxPosition_[runReadyCoreIdx_[type][pos]] = pos;
      }
      coreIdxPosition_[coreIdx] = INVALID_COREIDX_POSITION;
  }

//  从Running槽尾块删除,是RemoveRunReadyCoreIdx的特殊场景
  inline void RemoveRunReadyCoreIdxTail(int coreIdx, int type)
  {
      if (coreIdxPosition_[coreIdx] == INVALID_COREIDX_POSITION) {
          DEV_WARN("RemoveReadyCoreIdxTail: coreIdx %d not in runReady list (pos=INVALID)", coreIdx);
          return;
      }
      coreRunReadyCnt_[type]--;
      coreIdxPosition_[coreIdx] = INVALID_COREIDX_POSITION;
  }

2.5.2 循环依赖问题

现状:
device_sche_context.h文件中:ScheduleContext的成员SchDeviceTaskContext* curSchDevTaskCtx依赖wrap_manager.h中的WrapManager类

wrap_manager.h依赖ScheduleContext的wrapCoreAvail_、corePendReadyCnt_、 coreIdxPosition_、coreRunReadyCnt_ 、runReadyCoreIdx_

aicore_manager.h依赖 device_sche_context.h和wrap_manger.h

修改方法一:(优选)
将ScheduleContext的这几个字段单独提个结构体,放在一个新的文件core_status_manager.h中,并将统一封装的接口也放在这里。即这个文件专门用来维护aicore的状态。在wrap_manger.h和device_sche_context.h中分别依赖这个头文件

修改方法二:
将wrap_manager.h 拆成2个头文件,一个依赖SchDeviceTaskContext,另一个不依赖SchDeviceTaskContext继续被SchDeviceTaskContext依赖

3. 优化效果

image.png

likedislike
xuyi_37xuyi_37Collaborators
Jul 16 Added label: Machinerequirement
xuyi_37xuyi_37Collaborators
Jul 16 Modify description of issue
xuyi_37xuyi_37Collaborators
Jul 16 Modify description of issue
xuyi_37
xuyi_37Collaborators
Jul 16 Comments:

/assign

likedislike
CANN-robot
CANN-robotCollaborators
Jul 16 Comments:

Notice

This issue is already assigned to xuyi_37. Please do not assign repeatedly.

likedislike
xuyi_37xuyi_37Collaborators
Jul 16 Associated pull request
CANN-robot
CANN-robotCollaborators
Jul 17 Comments:

Notice

This issue is already assigned to xuyi_37. Please do not assign repeatedly.

likedislike
xuyi_37
xuyi_37Collaborators
Jul 17 Comments:

自提需求

likedislike
xuyi_37xuyi_37Collaborators
Jul 17 Modify description of issue
xuyi_37xuyi_37Collaborators
Jul 17 Modify description of issue
杨旭
杨旭Collaborators
Jul 17 Comments:

请跟踪处理

likedislike
xuyi_37xuyi_37Collaborators
Jul 24 Modify description of issue
xuyi_37
xuyi_37Collaborators
Jul 25 Comments:

顺序下乱了,导致精度不对 python/tests/st/operator/flash_attention_mha/test_flash_attention_mha.py test_03
image.png

直接原因是现在出现了CV下混了的情况。多了依赖边,解依赖最后可能不走mixhub,所以三个任务没有一起下发(pending机制依赖mixhub机制)。现在有了pending,以前提前占卡的那一套失效了,具体应该是:root25这个2个V的任务已经下发完了,C的任务还没解依赖完就没有下发,这个时root42的mix发现这三个核有的running可用有的pending可用,就判断整体可用,把C的任务先下发了。

实际上这里面C对C的依赖是一个假的WAW场景建立起来的stitch依赖。

cellMatch cellShape 过粗导致假 WAW stitch 依赖问题根因分析

日期: 2026-07-27
测试用例: python/tests/st/operator/flash_attention_mha/test_flash_attention_mha.py (test_03)
产物: dyn_topo.txt 依赖拓扑 dump, dep_verify_dump/ CSV dumps


一、问题描述

现象

dyn_topo.txt 中存在跨 (batch, head) 实例的 stitch 依赖链:每个 k_tile_loop PATH3 实例的 leaf op(opIdx 1/2/3)都有 stitch 边指向 chain 中下一个实例的对应 leaf op,形成 8 条长度为 8 的串行链。

典型样例: taskId 2293763 (funcIdx=35, opIdx=3) → taskId 2818051 (funcIdx=43, opIdx=3)

  • staticSuccCount=1(静态后继为本 wrap 的 exit op)
  • 额外 1 条 stitch 后继指向 funcIdx=43 的对应 op

链结构

  • 8 条平行链(funcIdx % 8 相同的实例构成一条链)
  • 每条链 8 个实例:如 chain 3 = [3, 11, 19, 27, 35, 43, 51, 59]
  • funcIdx 35 → 43 是 chain 3 中第 5 → 第 6 个实例的 stitch 边

用户质疑

test_03 参数 batch=8, heads=16, s1=32, s2=32, dim=32,理论上:

  • s2=32,K_TILE=320,k_tile_count = ceil(32/320) = 1,只有 1 个 KV tile
  • 不应存在跨 KV tile 的 online softmax 状态传递依赖

二、调查过程

2.1 实例身份确认

dyn_topo.txt 的 funcIdx 是 stitchedList 运行时索引,不等于 program.json 的 functions 数组索引。

属性 值
funcIdx 35 / 43 的 rootHash 6674746990191925579
对应 program.json functions[40] TENSOR_k_tile_loop_Unroll1_PATH3_hiddenfunc0_root
leafHash (opIdx=3) 15310508360404311023 = functions[31] (leaf0_leaf0, AIV)
opmagic (opIdx=3) 10001
coreType 1 (AIV)

结论: funcIdx 35 和 43 都是 k_tile_loop PATH3 的不同实例,对应不同的 (batch, head) 组合,不是 q_tile_loop 或 KV tile 迭代。

2.2 64 个实例的来源

kernel flash_attention_mha_impl.py 的循环结构:

batch_loop(8) × head_loop(8, h_num=num_heads//2=8) × q_tile_loop(1) × k_tile_loop(1)
  • batch_loop(8) × head_loop(8) = 64 个不同 (batch, head) 实例
  • q_tile_count = ceil(32/320) = 1,k_tile_count = ceil(32/320) = 1(无 tile 迭代)
  • 内层 h_s_idx in range(2):每次 head_loop 迭代处理 2 个 head,8 次覆盖 16 个 head

结论: 64 个 funcIdx 实例来自 batch × head 的外层循环展开,不是 KV tile 迭代。stitch 依赖不是 online softmax 跨 tile 状态传递。

2.3 启用 CFG_RUNTIME_DEBUG_VERIFY 获取 dump

将 flash_attention_mha_impl.py:33 的 runtime_debug_mode 从 1 改为 3,重新运行 test PASSED。

新输出目录: pypto/output_20260727_035353_786035_466548_huawei/
生成 dep_verify_dump/ 含 5 个 CSV:

  • slot_mapping.csv (runtimeSlotIdx → tensorName)
  • slot_cell_table.csv (host 侧 cellMatch 配置)
  • static_topo.csv
  • dyn_stitch_edges.csv (288 行,仅 host 侧 stitch 边)
  • dyn_slot_access.csv (1856 行,含 cellIdxList)

2.4 stitch 边 dump 不一致的根因

dyn_topo.txt 中 funcIdx 35 opIdx 3 有 stitch 后继 funcIdx 43 opIdx 3。
dyn_stitch_edges.csv 中 funcIdx 35 从不作为 producer 出现(缺失 funcIdx 1-8, 17-24, 33-40, 49-56 这些偶数位置)。

根因(代码层):

  • framework/src/machine/device/dynamic/context/dump_device_topo.cpp:17,29: 整个文件在 #ifndef __DEVICE__ 内,device 侧 DumpStitchEdge 为空桩 (line 191-193)
  • device_utils.h:45: IsDeviceMode() 在 __DEVICE__ 定义时返回 true
  • device_log.h:45: DEV_IF_NONDEVICE = if constexpr (!IsDeviceMode())
  • device_stitch_context.cpp:276: PushBackTask 在 DEV_IF_NONDEVICE 块外 → host 和 device 都执行 → 边出现在 dyn_topo.txt
  • device_stitch_context.cpp:286-290: ValidateAndDumpStitchEdge(含 DumpStitchEdge)在 DEV_IF_NONDEVICE 块内 → 仅 host 执行 → device 侧创建的边不在 CSV
  • dev_stitch_dependency_enhanced.h:69-71: CellMatchStitchEnhance → EstablishDependenciesWithType → HandleOneStitch 在 device 侧 运行 → chain 边由 device 侧 cellMatch 创建

结论: chain 边 (funcIdx N → funcIdx N+8) 由 device 侧 AIV cellMatch 机制创建,由于 device 侧 dump 为空桩,这些边不写入 dyn_stitch_edges.csv,但通过 PushBackTask 仍出现在 dyn_topo.txt。

2.5 WAW 冲突确认(dyn_slot_access.csv)

slotIdx tensor funcIdx 35 opIdx funcIdx 43 opIdx cellIdxList
4 l_output opIdx 1 (W) opIdx 1 (W) [36]
4 l_output opIdx 2 (W) opIdx 2 (W) [37]
5 m_output opIdx 1 (W) opIdx 1 (W) [36]

两个不同 (batch, head) 实例写入同一 cell → cellMatch 检测到 WAW 冲突 → 创建 stitch 边序列化写入。


三、根因分析

3.1 写入区域实际不重叠

kernel 写入逻辑:

q_start = cu_seqlens_q[b_idx]  # = b_idx * 32 (每 batch 32 行)
# 写入 l_output/m_output:
pypto.assemble(lij, [q_start + q_tile_start, h_act_idx], l_output)  # shape [32, 1]
# 写入 output:
pypto.assemble(out_bf16, [q_start + q_tile_start, h_offset], output)  # shape [32, 32]

funcIdx 35 vs 43 的 (batch, head) 映射(从 dyn_slot_access.csv 逆向):

实例 batch head 写入行范围 写入列
funcIdx 35 b=4 h=2 [128, 160) {4, 5}
funcIdx 43 b=5 h=2 [160, 192) {4, 5}

行范围 [128,160) 与 [160,192) 相邻但不重叠(q_start = b×32,每 batch 32 行)。

3.2 cellShape 过粗是假依赖的直接根因

l_output (shape [256, 16]) 的实际 cellShape = [64, 1]:

  • 4 个 row_cell × 16 个 col_cell = 64 个 cell
  • cellIdx = row_cell × 16 + col_cell
  • cell 36 = rows [128, 192) × col 4

funcIdx 35 (rows 128-159) 和 funcIdx 43 (rows 160-191) 都落入 cell 36(因为 cellShape[0]=64 将 64 行划为一个 cell,而两个 batch 各 32 行共 64 行正好填满一个 row_cell)。

若 cellShape[0]=32(与每次写入的 shape [32,1] 一致):

  • 8 个 row_cell × 16 个 col_cell = 128 个 cell
  • funcIdx 35 (rows 128-159) → row_cell 4
  • funcIdx 43 (rows 160-191) → row_cell 5
  • 无 WAW 冲突,无 stitch 边

output tensor (shape [256, 512]) 同样模式:cellShape = [64, 32],同样产生假 WAW。

3.3 cellShape[0]=64 的来源(未完全定位)

按代码逻辑,cellShape 应取写入 shape 的最小值:

  • UpdateCellMatchShape (dev_encode.cpp:1180-1195): 对每个 consumer/producer 的写入 shape,若 cellShape.dim[i] == -1 || cellShape.dim[i] > dimValue 则 cellShape.dim[i] = dimValue。即 cellShape = 各 consumer 写入 shape 的最小值
  • 写入 shape per instance = [32, 1] (seq_len_q=32) → 期望 cellShape[0] = 32
  • InitPartialUpdateCellMatch (dev_encode.cpp:2481-2532): 对所有 outcast 的 cellShape 取 GCD
    • l_output [32,1], m_output [32,1], output [32,32] → GCD = [32, 1]

理论计算 cellShape[0] 应为 32,但实际为 64。怀疑来自 vec tile shape v1_tile=[64, 512](kernel 中 pypto.set_vec_tile_shapes(64, 512)),但未找到直接代码证据将 vec tile shape 注入 cellShape 的路径。

这部分需进一步调查 dev_encode.cpp 中 cellShape 的完整计算路径。

3.4 假依赖的影响

8 条链 × 8 个实例的串行化导致:

  • 本可并行的 64 个 (batch, head) 实例被迫部分串行
  • 每条链内 8 个实例必须顺序执行(因 WAW stitch 边)
  • 实际并行度从 64 降至 8(8 条链可并行,链内串行)
  • 性能损失约 8 倍(理论值)

四、关键代码路径

4.1 cellMatch 机制

  • framework/src/machine/utils/dynamic/dev_encode_function_stitch.h:250-271: CellMatchHandle
    • rangeBegin[i] = offset[i] / cellShape[i]
    • rangeEnd[i] = (offset[i] + shape[i] - 1) / cellShape[i]
    • 同一 cell 的多个写入产生 WAW stitch 边

4.2 cellShape 确定

  • framework/src/machine/utils/dynamic/dev_encode.cpp:1417: 初始值 InitCellMatchTableDesc(shape, vector<int64_t>(dimSize, 1)) (cellShape = tensor shape)
  • dev_encode.cpp:1180-1195: UpdateCellMatchShape (cellShape = min of write shapes)
  • dev_encode.cpp:2481-2532: InitPartialUpdateCellMatch (merged cellShape = GCD of all outcasts)

4.3 device 侧 stitch 边创建

  • framework/src/machine/utils/dynamic/dev_stitch_dependency_enhanced.h:47-79: EstablishDependenciesWithType → HandleOneStitch
  • dev_stitch_dependency_enhanced.h:81-128: CellMatchStitchHandle
  • framework/src/machine/device/dynamic/context/device_stitch_context.cpp:257-291: HandleOneStitch
    • line 276: PushBackTask (host/device 都执行,边进入 dyn_topo.txt)
    • line 286-290: ValidateAndDumpStitchEdge (仅 host 执行,device 边不进 CSV)

4.4 dump 不一致根因

  • framework/src/machine/device/dynamic/context/dump_device_topo.cpp:17,29: #ifndef __DEVICE__ 包裹整个文件
  • dump_device_topo.cpp:152-179: DumpStitchEdge (host only)
  • dump_device_topo.cpp:59-63: DumpEnabled() 检查 CFG_RUNTIME_DEBUG_VERIFY
  • framework/src/machine/utils/dynamic/dev_encode_function_dupped_data.cpp:62-90: DumpTopo (successors = static + stitch.ForEach)

4.5 配置

  • framework/src/interface/configs/config_manager_ng.h:91: CFG_RUNTIME_DBEUG_MODE = "runtime_debug_mode", CFG_RUNTIME_DEBUG_VERIFY = 3
  • framework/src/machine/host/dump_host_topo.cpp:48-52: host 侧 DumpEnabled() 检查 CFG_RUNTIME_DEBUG_VERIFY

五、修复方向

5.1 直接修复(cellShape 计算)

调查 dev_encode.cpp 中 cellShape[0] 为何从理论值 32 变为 64,定位 vec tile shape 或其他来源的注入点,修正为与实际写入 shape 一致。

5.2 dump 完整性修复

dump_device_topo.cpp 的 DumpStitchEdge 在 device 侧为空桩,导致 device 侧创建的 stitch 边无法在 CSV 中追踪。建议:

  • 在 device 侧实现 stitch 边的 ring buffer 记录,运行后回传 host dump
  • 或在 host 侧重建 device cellMatch 逻辑以生成完整 CSV

5.3 验证方法

修复 cellShape 后重新运行 test_03:

  • 检查 dyn_slot_access.csv 中 cellIdxList 是否区分 funcIdx 35 和 43(应分别落入不同 cell)
  • 检查 dyn_topo.txt 中 chain 边是否消失(funcIdx N → N+8 的 stitch 边应不再存在)
  • 检查性能是否提升(并行度从 8 恢复到 64)

六、复现步骤

环境

  • conda env: xy
  • CANN_PATH=/home/ayl/Ascend
  • PTO_TILE_LIB_CODE_PATH=/home/x00512071/pto-isa
  • TILE_FWK_DEVICE_ID=0

步骤

  1. 修改 python/tests/st/operator/flash_attention_mha/flash_attention_mha_impl.py:33:
    "runtime_debug_mode": 3  # 原值 1,改为 3 启用 VERIFY dump
    
  2. 运行 myRun.sh(执行 test_03: batch=8 heads=16 s1=32 s2=32 dim=32)
  3. 检查输出目录 pypto/output_<timestamp>_<...>_huawei/:
    • dyn_topo.txt: 查看 funcIdx 35 opIdx 3 的 successors(含 stitch 后继 funcIdx 43)
    • dep_verify_dump/dyn_slot_access.csv: 查看 funcIdx 35/43 对 slotIdx 4/5 的写入 cellIdxList(均为 [36]/[37])
    • dep_verify_dump/dyn_stitch_edges.csv: 确认 funcIdx 35 不在 producer 列(device 侧边不 dump)

关键产物路径

  • kernel 实现: python/tests/st/operator/flash_attention_mha/flash_attention_mha_impl.py
  • test 脚本: python/tests/st/operator/flash_attention_mha/test_flash_attention_mha.py
  • 运行输出 (runtime_debug_mode=3): pypto/output_20260727_035353_786035_466548_huawei/
  • 运行输出 (runtime_debug_mode=1): pypto/output_20260727_031654_071238_195300_huawei/

修复方案参照

https://gitcode.com/cann/pypto/issues/2516

likedislike
xuyi_37xuyi_37Collaborators
Jul 30 Modify description of issue
5 event messages are collapsed here。 See more
xuyi_37xuyi_37Collaborators
Jul 30 Modify description of issue
xuyi_37
xuyi_37Collaborators
Jul 30 Comments:

mix_event_info

constexpr int PIPE_SYNC_PRE_EVENT_ID = 15;
constexpr int PIPE_SYNC_PRE_EVENT_ID_AIV1 = 31;

void AppendPipeSyncPreSyncInfo(const std::shared_ptr<LeafFuncAttribute>& leafAttr, CoreTask& leafFuncSyncInfo,
                               uint32_t& totalSetEventCount, uint32_t& totalWaitEventCount)
{
    if (leafAttr->mixResourceType == MixResourceType::UNKNOWN) {
        return;
    }
    auto appendSync = [&](bool isSet, int eventID) {
        leafFuncSyncInfo.syncMsg.push_back({isSet, eventID});
        if (isSet) {
            totalSetEventCount++;
        } else {
            totalWaitEventCount++;
        }
    };
    if (leafAttr->aivCore == AIVCore::UNSPECIFIED) {
        if (leafAttr->mixResourceType == MixResourceType::ONE_CUBE_TWO_VECTOR) {
            appendSync(true, PIPE_SYNC_PRE_EVENT_ID);
            appendSync(true, PIPE_SYNC_PRE_EVENT_ID_AIV1);
            appendSync(false, PIPE_SYNC_PRE_EVENT_ID);
            appendSync(false, PIPE_SYNC_PRE_EVENT_ID_AIV1);
        } else {
            appendSync(true, PIPE_SYNC_PRE_EVENT_ID);
            appendSync(false, PIPE_SYNC_PRE_EVENT_ID);
        }
    } else {
        appendSync(false, PIPE_SYNC_PRE_EVENT_ID);
        appendSync(true, PIPE_SYNC_PRE_EVENT_ID);
    }
}
likedislike
xuyi_37
xuyi_37Collaborators
Jul 30 Comments:
#if defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3510)
#ifdef OPEN_MIX_PERF
INLINE void RecordMixSetEvent(__gm__ TaskStat* taskStat)
{
    __gm__ uint64_t* setEventBase =
        reinterpret_cast<__gm__ uint64_t*>(taskStat->perfDataBaseAddr + taskStat->setEventAddr);
    setEventBase[taskStat->setEventNum++] = get_sys_cnt();
}
INLINE void RecordMixWaitEvent(__gm__ TaskStat* taskStat)
{
    __gm__ uint64_t* waitEventBase =
        reinterpret_cast<__gm__ uint64_t*>(taskStat->perfDataBaseAddr + taskStat->waitEventAddr);
    waitEventBase[taskStat->waitEventNum++] = get_sys_cnt();
}
#else
INLINE void RecordMixSetEvent(__gm__ TaskStat* taskStat) { (void)taskStat; }
INLINE void RecordMixWaitEvent(__gm__ TaskStat* taskStat) { (void)taskStat; }
#endif

INLINE void PipeSyncPre(uint8_t mixResourceType, uint8_t lastMixResourceType, __gm__ TaskStat* taskStat)
{
    // only lastTask and curTask are mix should insert sync
    (void)lastMixResourceType;
    if (mixResourceType == static_cast<uint8_t>(MixResourceType::MIX_UNKNOWN)) {
        return;
    }
#if defined(__AIV__)
    RecordMixSetEvent(taskStat);
    set_intra_block(PIPE_S, EVNET_ID15);  // 插在callop开始,这里pipe不重要,前面流水必然已执行完
    RecordMixWaitEvent(taskStat);
    wait_intra_block(PIPE_S, EVNET_ID15); // PIPE_S阻塞后续指令下发,避免与后续的CCE指令EventId冲突
#else
    if (mixResourceType == static_cast<uint8_t>(MixResourceType::MIX_1C2V)) {
        RecordMixSetEvent(taskStat);
        set_intra_block(PIPE_S, EVNET_ID15);                       // 作用于Vec0
        RecordMixSetEvent(taskStat);
        set_intra_block(PIPE_S, EVNET_ID15 + EVNET_NUMS_PER_AIV);  // 作用与Vec1
        RecordMixWaitEvent(taskStat);
        wait_intra_block(PIPE_S, EVNET_ID15);                      // 等待Vec0
        RecordMixWaitEvent(taskStat);
        wait_intra_block(PIPE_S, EVNET_ID15 + EVNET_NUMS_PER_AIV); // 等待Vec1
    } else {
        RecordMixSetEvent(taskStat);
        set_intra_block(PIPE_S, EVNET_ID15);  // 作用于Vec0
        RecordMixWaitEvent(taskStat);
        wait_intra_block(PIPE_S, EVNET_ID15); // 等待Vec0
    }
#endif
}
#endif
likedislike
xuyi_37xuyi_37Collaborators
Jul 31 changed custom state from 进行中 to 已完成
xuyi_37xuyi_37Collaborators
Jul 31 Close issue
CANN-robotCANN-robotCollaborators
Jul 31 Added label: resolved
xuyi_37xuyi_37Collaborators
Oct 14 Modify description of issue