Closed
[Task|任务跟踪]: 优化一下MIX_HUB逻辑,统一一下 #2516
xuyi_37Add on  Jul 2Closed at  Jul 29
xuyi_37
xuyi_37Collaborators
Jul 2 Create

Welcome to submit task tracking issues and collaborate with team members.

任务描述

MIX_HUB逻辑,统一一下

任务目标

MIX_HUB逻辑,统一一下

MixHub Encode Simplify 设计文档

  • 提交: 18cc65004e5b2ad418422f181c5479922f0b0310
  • 标题: perf(machine): MixHub encode simplify
  • 修改文件: framework/src/machine/utils/dynamic/dev_encode.cpp(+61 / −135,净减 74 行)
  • 所属模块: machine 动态编码层(EncodeDevAscendFunctionInfo)

1. 概述

本次提交对 dev_encode.cpp 中 为 mix 任务按 wrapId 插入 HUB_MIX 同步节点 的逻辑进行重构简化:

  1. 消除重复:原先 AddHubMixForIncastMixOp 与 AddHubMixForInnerMixOp 两段几乎相同的「汇聚前驱 → 建 HUB_MIX → 重接依赖图」代码,抽取出公共方法 InsertHubMixForWrapGroup。
  2. 合并双 pass:原先「先算 incast 消费者分组映射 → 再分别处理 inner/incast 两类 wrap」的两遍扫描 + 两个分支,合并为「一遍分组 + 单循环按 wrap 统一处理」。
  3. 行为调整:非 incast(inner)wrap 中无前驱的分组,旧逻辑会跳过不插 HUB_MIX;新逻辑统一插入一个零前驱同步屏障 HUB_MIX,使所有 wrap 都拥有同步节点。
  4. 接口收敛:删除 ComputeWrapIdToConsumerOpIdxSetMap、AddHubMixForIncastMixOp、AddHubMixForInnerMixOp 三个私有方法,仅保留 InsertHubMixForWrapGroup 与 AddHubMixForWrapTask 两个。

最终函数数量 4 → 2,核心算法行数大幅下降,同时为后续 MixHub support WAR/WAW(54153eed6)铺平了统一入口。


2. 背景知识

2.1 涉及的数据结构

名称 类型 含义
callopList std::vector<Operation*>& 当前 Device Function 的全部 call op 列表(编码时会被追加 dummy/HUB 节点)
callOpSuccDict unordered_map<Operation*, OrderedSet<Operation*>> call op → 后继集合(依赖图正向边)
callOpPredDict unordered_map<Operation*, uint64_t> call op → 前驱计数(入度)
incastList / outcastList vector<shared_ptr<LogicalTensor>> 跨 RootFunction 的入/出张量
wrapId(CallOpAttribute) int mix 任务所属的 wrap 分组标识;INVALID_WRAPID(-1) 表示不属于 mix wrap
opIdxToHubOpIdx_ unordered_map<int,int> consumer op idx → 其所属 wrap 的 HUB_MIX op idx,供 incast/outcast 消费者查表替换
CoreType::HUB_MIX enum HUB_MIX 同步节点核类型,由 MakeDummyCallHubMix() 创建(calleeHash = HUB_MIX_DUMMY_HASH)

2.2 HUB_MIX 的作用

mix 任务(同一个 wrapId 下的一组 call op)在执行时需要组内同步:组内所有 op 的公共前驱完成后,才能开始执行本组 mix 任务。HUB_MIX 充当该同步屏障节点,依赖图重接为:

pred -> [callop...]   变为   pred -> HUB_MIX -> [callop...]
  • 公共前驱 pred 的后继由原 callop 列表改指 HUB_MIX;
  • HUB_MIX 的入度 = 公共前驱数;
  • HUB_MIX 的后继 = 组内全部 callop,且这些 callop 的入度被重置为 1(只依赖 HUB_MIX)。

2.3 incast wrap 与 inner wrap

  • incast wrap:组内至少有一个 op 的输入 operand 的 rawmagic 命中 incastList(即消费跨 RootFunction 的 incast 张量)。这类 wrap 的 HUB_MIX 映射需要记录到 opIdxToHubOpIdx_,供 FillIncastUseList/FillOutcastUseList 在编码 incast/outcast 消费者时填充 wrapTaskHubOpIdx(dev_encode.cpp:876、:900)。
  • inner wrap:不消费 incast 张量的 mix wrap,仅在组内同步,无需记录映射。

2.4 调用上下文

AddHubMixForWrapTask 在 EncodeDevAscendFunctionInfo::Init 流程中被调用(dev_encode.cpp:2127),位于 EraseRedundantColorEdges / RemoveDeadHubCall / ReplaceSuccessorWithHub / AddDummyCallsAtBeginningAndEnding 之后、EncodeZeroPredCount 之前。其返回的 opToHubOp 随后转换为 opIdxToHubOpIdx_(:2135),最终在 InitIncastOutcast(:2280)消费。


3. 修改前设计

旧实现由 4 个方法协作:

AddHubMixForWrapTask            // 编排
 ├─ ComputeWrapIdToConsumerOpIdxSetMap   // 第一遍:算 incast wrap 分组(op idx 集合)
 ├─ AddHubMixForInnerMixOp      // 处理 inner wrap(非 incast)
 └─ AddHubMixForIncastMixOp     // 处理 incast wrap

3.1 ComputeWrapIdToConsumerOpIdxSetMap

  • 扫描 callopList,第一遍找出消费 incast 张量的 op,按 wrapId 收集 op 索引到 result[wrapId];
  • 第二遍把同 wrapId 的所有 op(无论是否消费 incast)都并入该集合;
  • 返回 map<int, set<int>>,仅包含存在 incast 消费者的 wrap。

3.2 AddHubMixForInnerMixOp(inner wrap)

  • 入参 incastWrapIds(来自 3.1 的 key 集合),用于排除 incast wrap;
  • 分组时额外过滤:跳过 predListDict 中无前驱或前驱为空的 op(if (it == predListDict.end() || it->second.empty()) continue;);
  • 对每个 inner wrap 分组,计算 predSet,若 predSet.empty() 则 continue 不插 HUB_MIX;
  • 插入 HUB_MIX 并重接边,不记录 opToHubOp。

3.3 AddHubMixForIncastMixOp(incast wrap)

  • 遍历 3.1 的结果,对每个 incast wrap 取全部 op(含无前驱的);
  • 计算 predSet,无条件插入 HUB_MIX(即便 predSet 为空,也建一个零入度 HUB_MIX);
  • 重接边,记录 opToHubOp。

3.4 AddHubMixForWrapTask(编排)

构建 predListDict(由 callOpSuccDict 反转得到),由 3.1 推出 incastWrapIds,先调 AddHubMixForInnerMixOp,再调 AddHubMixForIncastMixOp,返回 opToHubOp。

3.5 旧设计的问题

  1. 代码重复:3.2 与 3.3 的「predSet 汇聚 → 建 HUB_MIX → 前驱改指 → 后继重置入度」逻辑几乎逐行相同,仅差 predSet.empty() 跳过判断与是否记录映射。
  2. 两遍扫描 + 双分支:3.1 用两遍遍历 + set<int> 索引集合,再分 inner/incast 两路处理,分组信息被拆散在三个结构里(map<int,set<int>>、incastWrapIds、predListDict)。
  3. inner wrap 零前驱跳过:inner wrap 若整组无前驱则不建 HUB_MIX,导致这类 mix 任务缺少显式同步屏障,调度上不一致。

4. 修改后设计

新实现仅 2 个方法:

AddHubMixForWrapTask            // 编排 + 分组 + 分类
 └─ InsertHubMixForWrapGroup    // 单 wrap 插入 HUB_MIX(公共逻辑)

4.1 InsertHubMixForWrapGroup(公共逻辑)

void InsertHubMixForWrapGroup(
    std::vector<Operation*>& callopList,
    const std::vector<Operation*>& callops,            // 本 wrap 的全部 op
    const std::unordered_map<Operation*, std::vector<Operation*>>& predListDict,
    bool recordMapping,                                // 是否记录 opToHubOp
    std::unordered_map<Operation*, Operation*>& opToHubOp)

步骤:

  1. 汇聚 callops 内所有 op 的前驱到 predSet(去重);
  2. MakeDummyCallHubMix() 创建 HUB_MIX,追加到 callopList;
  3. 每个 pred 的后继:Remove(callops) 后 Insert(hubMixOp);hubMixOp 入度 = predSet.size();
  4. 每个 callOp:作为 hubMixOp 后继,入度重置为 1;若 recordMapping 则写入 opToHubOp[callOp] = hubMixOp。

关键点:不再有 predSet.empty() 跳过分支——零前驱 wrap 也会得到一个入度为 0 的 HUB_MIX 同步屏障。

4.2 AddHubMixForWrapTask(编排)

std::unordered_map<Operation*, Operation*> AddHubMixForWrapTask(std::vector<Operation*>& callopList)

步骤:

  1. 由 callOpSuccDict 反转构建 predListDict;
  2. 一遍遍历 callopList:按 wrapId(跳过 INVALID_WRAPID)收集到 wrapIdToCallops;同时检测 incast 消费——若某 op 的任一 operand rawmagic 命中 incastRawmagics,则标记该 wrapId 入 incastWrapIds;
  3. 单循环:对每个 wrap 调用 InsertHubMixForWrapGroup(..., recordMapping = isIncastWrap, opToHubOp);
  4. 返回 opToHubOp。

incast 检测从「3.1 的两遍扫描 + 第二遍全量并入」简化为「分组时顺带标记」,分组与分类在一次遍历内完成。


5. 行为差异分析

5.1 incast wrap:完全等价

维度 旧(3.1 + 3.3) 新(4.2) 结论
incast wrap 识别 第一遍命中 incast 消费者 → 第二遍并入同 wrap 全部 op 分组时顺带标记 incastWrapIds 同一 wrap 集合
组内 op 集合 全部 op(含零前驱) wrapIdToCallops 全部 op 一致
是否插 HUB_MIX 无条件插 无条件插 一致
predSet/重接边 同 同(抽出公共方法) 一致
opToHubOp 记录 记录 recordMapping=true 记录 一致

5.2 inner wrap:行为变更(有意为之)

维度 旧(3.2) 新(4.2) 差异
分组过滤 排除 predList 为空的 op 包含全部 op 新代码组内含零前驱 op
predSet 为空时 continue,不建 HUB_MIX 建 入度 0 的 HUB_MIX 新增零前驱同步屏障
predSet 非空时 建 HUB_MIX,组内仅含有前驱 op 建 HUB_MIX,组内含全部 op HUB_MIX 后继多了零前驱 op,其入度被置 1
opToHubOp 记录 不记录 recordMapping=false 不记录 一致

变更影响:原先无前驱的 inner mix 任务不挂同步节点;新代码统一为其挂一个零入度 HUB_MIX,使所有 mix wrap 都拥有显式同步屏障,调度路径更规整、一致。这是一项性能/调度语义调整,而非纯重构——与提交信息 perf(machine) 一致。代码注释明确写道:「为所有 mix 任务按 wrapId 统一插入 HUB_MIX 同步节点(含无前驱的,作为零前驱同步屏障)」。

5.3 删除的方法无外部调用

ComputeWrapIdToConsumerOpIdxSetMap、AddHubMixForIncastMixOp、AddHubMixForInnerMixOp 均为该文件私有,仅被 AddHubMixForWrapTask 调用(grep 全仓确认无其他引用),删除安全。


6. 等价性论证(incast 路径)

对任一 incast wrap W:

  1. op 集合相等:旧路径第二遍把 W 下全部 op 并入集合;新路径 wrapIdToCallops[W] 同样含 W 下全部 op(遍历 callopList 时按 wrapId 收集,无前驱过滤)。
  2. predSet 相等:两边都从同一 predListDict 对同一 op 集合求并集。
  3. 边重接相等:pred -> hubMix、hubMix -> callops、callop 入度置 1 三步操作在抽出公共方法后逐行一致。
  4. 映射相等:两边都为 W 下每个 callop 写 opToHubOp[callOp] = hubMixOp,供 opIdxToHubOpIdx_ 使用。

故 incast 路径输出二进制级等价。inner 路径的差异见 §5.2,属预期调整。


7. 代码结构改进

指标 修改前 修改后
私有方法数 4(Compute/Inner/Incast/WrapTask) 2(InsertHubMixForWrapGroup/WrapTask)
核心逻辑行数 ~135 ~61(净减 74)
重复的「建 HUB_MIX + 重接边」块 2 处 1 处(公共方法)
分组扫描遍数 2 遍(Compute 内两 pass) 1 遍
incast 分类时机 分组后用 key 集合反推 分组时顺带标记

可维护性提升:后续若需调整 HUB_MIX 重接策略(如 54153eed6 引入 WAR/WAW 支持),只需改 InsertHubMixForWrapGroup 一处,并在 AddHubMixForWrapTask 调用处调整 recordMapping 参数即可——事实上 54153eed6 正是把 recordMapping 统一改为 true 并简化循环。


8. 风险与影响评估

  1. 正确性风险(低):incast 路径二进制级等价;inner 路径新增零前驱 HUB_MIX,对依赖图是「加边/加节点」操作,不影响原有 predSet 非空 wrap 的同步语义。零前驱 HUB_MIX 入度为 0,会被 EncodeZeroPredCount(紧随其后执行)正常纳入无前驱 op 处理流程。
  2. 调度/性能(正向):统一同步屏障消除 inner mix 任务「无屏障」的特例,调度器无需对无前驱 mix 任务做特殊判断;与提交目标 perf 一致。
  3. 下游消费:opIdxToHubOpIdx_ 的消费方(FillIncastUseList:876、FillOutcastUseList:900、stitchPolicyFullCoverProducerList:1026、:1046)仅做「命中则替换为 wrapTaskHubOpIdx」查表,incast wrap 映射集合不变,下游行为不变。
  4. 测试:本次提交未附带测试改动;依赖既有 mix/Hub 编码用例回归(仓内 session-ses_hubmix_waw_war.md 等会话记录覆盖后续 WAR/WAW 扩展)。

9. 关键代码位置索引

  • 公共插入逻辑:framework/src/machine/utils/dynamic/dev_encode.cpp:1718(InsertHubMixForWrapGroup)
  • 编排入口:framework/src/machine/utils/dynamic/dev_encode.cpp:1757(AddHubMixForWrapTask)
  • 调用点:framework/src/machine/utils/dynamic/dev_encode.cpp:2127
  • 映射转换:framework/src/machine/utils/dynamic/dev_encode.cpp:2135(opToHubOp → opIdxToHubOpIdx_)
  • 映射消费:framework/src/machine/utils/dynamic/dev_encode.cpp:876 / :900 / :1026 / :1046
  • HUB_MIX 构造:framework/src/machine/utils/dynamic/dev_encode.cpp:1544(MakeDummyCallHubMix)
  • 后续扩展提交:54153eed6(MixHub support WAR/WAW,将 recordMapping 统一为 true)
likedislike
xuyi_37xuyi_37Collaborators
Jul 2 Assign xuyi_37 as responsible person
gaoxingwang
gaoxingwangCollaborators
Jul 2 Comments:

要求:统一先基于rootfunction 所有callop加上mixhub, 输出 mixop 和 mixhub的映射表 , 作为后续encode incast时候,判断consumer op的mix hub 使用 后续整改下这块代码 更清晰

likedislike
gaoxingwanggaoxingwangCollaborators
Jul 2 associated Kanban: PyPTO
gaoxingwanggaoxingwangCollaborators
Jul 2 Added label: Machine
xuyi_37
xuyi_37Collaborators
Jul 2 Comments:
xuyi_37
xuyi_37Collaborators
Jul 2 Comments:

当前的代码逻辑详细

    // =========================================================================
    // ComputeWrapIdToConsumerOpIdxSetMap
    // 功能:计算每个 wrapId 到其消费者 op 索引集合的映射(仅针对消费了 incast 数据的 wrap)。
    //
    // 采用两遍遍历:
    //   第一遍:找出所有"输入操作数中存在 incast 数据"的 op,记录其 wrapId -> {opIdx}。
    //           仅这些 wrapId 才被纳入结果(即仅 incast 消费型 wrap 会被返回)。
    //   第二遍:把与第一遍命中的 wrapId 相同的所有 op(即使自身不直接读 incast)也归入
    //           对应集合,使得同一 wrap 下的全部 op 统一通过 HUB_MIX 汇聚。
    //
    // 入参:callopList —— call op 列表
    // 返回:wrapId -> 消费者 op 索引集合(有序,便于后续稳定处理)
    // =========================================================================
    std::map<int, std::set<int>> ComputeWrapIdToConsumerOpIdxSetMap(std::vector<Operation*>& callopList) const
    {
        // 收集所有 incast 数据的 rawmagic 标识,用于判断 op 是否消费 incast
        std::unordered_set<int> incastRawmagics;
        for (auto& incast : incastList) {
            incastRawmagics.insert(incast->tensor->rawmagic);
        }
        std::map<int, std::set<int>> result;
        // 第一遍:仅记录"直接消费 incast 数据"的 op 所属 wrapId
        for (int j = 0; j < static_cast<int>(callopList.size()); j++) {
            auto& op = *callopList[j];
            auto callAttr = dynamic_cast<CallOpAttribute*>(op.GetOpAttribute().get());
            if (!callAttr || callAttr->wrapId == INVALID_WRAPID) { continue; }
            for (size_t k = 0; k < op.GetIOperands().size(); ++k) {
                auto& iOperand = op.GetIOperands()[k];
                if (incastRawmagics.count(iOperand->tensor->rawmagic) == 0) {
                    continue;
                }
                result[callAttr->wrapId].insert(j);
                break;
            }
        }
        // 第二遍:将同 wrapId 的所有 op(含未直接读 incast 的)补充进集合
        for (int j = 0; j < static_cast<int>(callopList.size()); j++) {
            auto& op = *callopList[j];
            auto callAttr = dynamic_cast<CallOpAttribute*>(op.GetOpAttribute().get());
            if (!callAttr || callAttr->wrapId == INVALID_WRAPID) { continue; }
            auto it = result.find(callAttr->wrapId);
            if (it == result.end() || it->second.empty()) { continue; }
            it->second.insert(j);
        }
        return result;
    }
    
    // =========================================================================
    // AddHubMixForIncastMixOp
    // 功能:为消费 incast(跨 RootFunction 输入)数据的 wrap 任务插入 HUB_MIX 汇聚节点。
    //
    // 设计要点:即使一组 callops 没有前驱依赖(predSet 为空),也必须创建 HUB_MIX。
    //   原因:incast 数据来自外部 RootFunction,需经 HUB 中转后再扇出到同 wrap 的各 op。
    //   HUB_MIX 在此承担"数据分发汇"角色,而非单纯"依赖汇聚"角色,因此不能因无前驱而跳过。
    //   这与 AddHubMixForInnerMixOp(无前驱则跳过)形成刻意区别。
    //
    // 依赖图重定向(每个 wrapId 组):
    //   原始:pred --(多对多)--> callops
    //   重定向:pred --> hubMixOp --> callops
    //   - 前驱边:callOpSuccDict[pred] 移除指向 callops 的边,改为指向 hubMixOp
    //   - hubMixOp 前驱数 = predSet.size()(可能为 0)
    //   - 后继边:callOpSuccDict[hubMixOp] 加入所有 callops,callops 前驱数统一置 1
    //
    // 入参:callopList —— call op 列表(会被追加 HUB_MIX dummy 节点)
    //       wrapIdToConsumerSet —— wrapId -> 消费者 op 索引集合
    //       predListDict —— op -> 前驱列表(由 callOpSuccDict 反转构建)
    // 返回:opToHubOp —— 每个 consumer op 到其 HUB_MIX 节点的映射
    // =========================================================================
    std::unordered_map<Operation*, Operation*> AddHubMixForIncastMixOp(
        std::vector<Operation*>& callopList,
        const std::map<int, std::set<int>>& wrapIdToConsumerSet,
        std::unordered_map<Operation*, std::vector<Operation*>>& predListDict)
    {
        std::unordered_map<Operation*, Operation*> opToHubOp;
        for (auto& [wrapId, consumerIdxSet] : wrapIdToConsumerSet) {
            (void)wrapId;
            // 取出该 wrap 下的所有 callops
            std::vector<Operation*> callops;
            for (auto opIdx : consumerIdxSet) {
                callops.push_back(callopList[opIdx]);
            }
            // 汇集这些 callops 的全部前驱(并集去重)
            std::unordered_set<Operation*> predSet;
            for (auto* callOp : callops) {
                auto it = predListDict.find(callOp);
                if (it != predListDict.end()) {
                    for (auto* pred : it->second) {
                        predSet.insert(pred);
                    }
                }
            }
            // 注意:此处不判断 predSet.empty(),即使无前驱也创建 HUB_MIX
            //       (incast 数据分发需要 HUB 中转,见函数头说明)

            auto* hubMixOp = MakeDummyCallHubMix();
            callopList.push_back(hubMixOp);

            // 重定向前驱边:pred -> callops 改为 pred -> hubMixOp
            for (auto* pred : predSet) {
                callOpSuccDict[pred].Remove(callops);
                callOpSuccDict[pred].Insert(hubMixOp);
            }
            callOpPredDict[hubMixOp] = static_cast<uint64_t>(predSet.size());

            // 建立后继边:hubMixOp -> callops,callops 前驱数统一置 1
            for (auto* callOp : callops) {
                callOpSuccDict[hubMixOp].Insert(callOp);
                callOpPredDict[callOp] = 1;
                opToHubOp[callOp] = hubMixOp;
            }
        }
        return opToHubOp;
    }

    // =========================================================================
    // AddHubMixForInnerMixOp
    // 功能:为同一 RootFunction 内、不消费 incast 数据的 wrap 任务插入 HUB_MIX 汇聚节点。
    //
    // 设计要点:仅当一组 callops 存在前驱依赖(predSet 非空)时才创建 HUB_MIX。
    //   原因:Inner Mix 的数据来自本 RootFunction 内部,无需 HUB 中转分发;
    //         插入 HUB_MIX 仅用于"依赖汇聚"以减少扇出边数,若无前驱则无依赖可汇聚,跳过。
    //         这与 AddHubMixForIncastMixOp(无前驱也创建)形成刻意区别。
    //
    // 依赖图重定向(每个 wrapId 组,逻辑与 IncastMixOp 一致):
    //   原始:pred --(多对多)--> callops
    //   重定向:pred --> hubMixOp --> callops
    //
    // 入参:callopList —— call op 列表(会被追加 HUB_MIX dummy 节点)
    //       incastWrapIds —— 已标记为 incast 的 wrapId 集合,本函数跳过这些 wrap
    //       predListDict —— op -> 前驱列表
    // 返回:无(Inner Mix 不需要 op->hub 映射)
    // =========================================================================
    void AddHubMixForInnerMixOp(
        std::vector<Operation*>& callopList,
        const std::unordered_set<int>& incastWrapIds,
        std::unordered_map<Operation*, std::vector<Operation*>>& predListDict)
    {
        // 固定原始长度,避免遍历时处理到新插入的 HUB_MIX 节点
        size_t originalSize = callopList.size();
        // 按 wrapId 分组收集"非 incast 且有前驱"的 callops
        std::map<int, std::vector<Operation*>> wrapIdToCallops;
        for (size_t i = 0; i < originalSize; i++) {
            Operation* op = callopList[i];
            auto callAttr = dynamic_cast<CallOpAttribute*>(op->GetOpAttribute().get());
            if (callAttr == nullptr || callAttr->wrapId == INVALID_WRAPID) {
                continue;
            }
            // 跳过 incast 类型的 wrap(交由 AddHubMixForIncastMixOp 处理)
            if (incastWrapIds.count(callAttr->wrapId) != 0) {
                continue;
            }
            // 仅收集有前驱依赖的 op
            auto it = predListDict.find(op);
            if (it == predListDict.end() || it->second.empty()) {
                continue;
            }
            wrapIdToCallops[callAttr->wrapId].push_back(op);
        }

        for (auto& [wrapId, callops] : wrapIdToCallops) {
            (void)wrapId;
            // 汇集这些 callops 的全部前驱(并集去重)
            std::unordered_set<Operation*> predSet;
            for (auto* op : callops) {
                auto it = predListDict.find(op);
                if (it != predListDict.end()) {
                    for (auto* pred : it->second) {
                        predSet.insert(pred);
                    }
                }
            }
            // 无前驱则无依赖可汇聚,跳过(与 IncastMixOp 的关键区别)
            if (predSet.empty()) {
                continue;
            }

            Operation* hubMixOp = MakeDummyCallHubMix();
            callopList.push_back(hubMixOp);

            // 重定向前驱边:pred -> callops 改为 pred -> hubMixOp
            for (auto* pred : predSet) {
                callOpSuccDict[pred].Remove(callops);
                callOpSuccDict[pred].Insert(hubMixOp);
            }
            callOpPredDict[hubMixOp] = static_cast<uint64_t>(predSet.size());

            // 建立后继边:hubMixOp -> callops,callops 前驱数统一置 1
            for (auto* op : callops) {
                callOpSuccDict[hubMixOp].Insert(op);
                callOpPredDict[op] = 1;
            }
        }
    }

    // =========================================================================
    // AddHubMixForWrapTask
    // 功能:为 Wrap Task(包裹任务)插入 HUB_MIX 汇聚节点,优化调度依赖图。
    //
    // 背景:同一 wrapId 下的多个 call op 往往共享前驱,若前驱直接扇出到所有后继,
    //       依赖边数为 |pred| * |succ|。插入一个 HUB_MIX dummy 节点将 fan-out 收敛为
    //       pred -> hubMix -> succ(两层),把边数降为 |pred| + |succ|,降低调度开销。
    //
    // 处理两类场景:
    //   1. Inner Mix  —— 同一 RootFunction 内、不消费 incast 数据的 wrap 任务
    //      (由 AddHubMixForInnerMixOp 处理):仅当存在前驱依赖时才插入 HUB_MIX。
    //   2. Incast Mix —— 消费 incast(跨 RootFunction 输入)数据的 wrap 任务
    //      (由 AddHubMixForIncastMixOp 处理):即使无前驱依赖也必须插入 HUB_MIX,
    //      因为 incast 数据需经 HUB 中转分发,HUB_MIX 负责把 incast 数据扇出到同 wrap 的各 op。
    //
    // 入参:callopList —— 当前 RootFunction 的 call op 列表(会被追加 HUB_MIX dummy 节点)
    // 返回:opToHubOp —— consumer op 到其对应 HUB_MIX 节点的映射(仅 incast 场景返回,
    //       供后续编码阶段建立 opIdx->hubOpIdx 映射使用)
    //
    // 注意:两个子函数处理互斥的 wrapId 集合(inner 处理非 incastWrapIds,
    //       incast 处理 incastWrapIds),因此 predListDict 在 inner 阶段被修改后
    //       不会影响 incast 阶段所用的前驱信息。
    // =========================================================================
    std::unordered_map<Operation*, Operation*> AddHubMixForWrapTask(std::vector<Operation*>& callopList)
    {
        // 步骤1:计算每个 wrapId 的消费者 op 索引集合(仅含消费了 incast 数据的 wrap)
        auto wrapIdToConsumerSet = ComputeWrapIdToConsumerOpIdxSetMap(callopList);

        // 步骤2:由 callOpSuccDict 反转构建前驱字典 predListDict(op -> 前驱列表)
        std::unordered_map<Operation*, std::vector<Operation*>> predListDict;
        for (auto& [producer, succSet] : callOpSuccDict) {
            for (auto& succ : succSet) {
                predListDict[succ].push_back(producer);
            }
        }

        // 步骤3:incastWrapIds 即 wrapIdToConsumerSet 的 key 集合,
        //       标记"消费了 incast 数据"的 wrap,用于区分两类场景。
        std::unordered_set<int> incastWrapIds;
        for (auto& [wrapId, consumerSet] : wrapIdToConsumerSet) {
            (void)consumerSet;
            incastWrapIds.insert(wrapId);
        }

        // 步骤4:为 Inner Mix(非 incast 的 wrap)插入 HUB_MIX 节点
        AddHubMixForInnerMixOp(callopList, incastWrapIds, predListDict);

        // 步骤5:为 Incast Mix(消费 incast 的 wrap)插入 HUB_MIX 节点,并返回 op->hub 映射
        auto opToHubOp = AddHubMixForIncastMixOp(callopList, wrapIdToConsumerSet, predListDict);
        return opToHubOp;
    }
likedislike
xuyi_37xuyi_37Collaborators
Jul 2 changed custom category from 任务 to 需求
xuyi_37xuyi_37Collaborators
Jul 24 Associated pull request
xuyi_37
xuyi_37Collaborators
Jul 27 Comments:

WAW/WAR 场景下 HUB_MIX 节点正确建立方案

日期: 2026-07-27
测试用例: python/tests/st/operator/flash_attention_mha/test_flash_attention_mha.py (test_03)
状态: 已实施并验证通过
关联文档: session-ses_cellmatch_false_waw.md(假 WAW 根因分析), session-ses_stitch_producer_hub.md(2026-07-25 历史 leaf→hub 修复,已合并)


一、背景

1.1 cellMatch 依赖机制

PyPTO device 侧通过 cellMatch 机制检测跨 wrap 的 GM 张量访问冲突:将 GM 按 cellShape 划分为 cell,多个 wrap 实例访问同一 cell 时建立 stitch 依赖(先访问者为 producer,后访问者为 consumer),保证数据一致性。

三种访问冲突场景:

场景 先访问者 (producer) 后访问者 (consumer) 数据依赖语义
RAW (先写后读) outcast W incast R 写→读,consumer 需等 producer 写完
WAR (先读后写) incast R outcast W 读→写,consumer 需等 producer 读完
WAW (先写后写) outcast W outcast W 写→写,consumer 需等 producer 写完

1.2 HUB_MIX 节点的作用

HUB_MIX(CoreType::HUB_MIX,opmagic=10009)是 wrap 内的同步调度节点。每个 wrap(共享 wrapId 的一组 mix leaf op)插入一个 HUB_MIX,将外部 stitch 依赖统一汇聚到 hub,hub 再分发给 wrap 内的 leaf op:

外部 producer → HUB_MIX → [leaf0, leaf1, leaf2]   (wrap 内)

目的: 让 wrap 整体作为调度单元。若外部 stitch 依赖直接连到单个 leaf(leaf→leaf),会破坏 wrap 级调度粒度,降低流水并行度。

1.3 问题现象

test_03 (batch=8, heads=16, s1=32, s2=32, dim=32) 的 dyn_topo.txt 中,WAW/WAR 场景的 stitch 依赖为 leaf→leaf,而非 leaf→hub。

典型样例:taskId 2293763 (funcIdx=35, opIdx=3, leaf, opmagic=10001) 的 stitch 后继为 2818051 (funcIdx=43, opIdx=3, leaf),应为 2818052 (funcIdx=43, opIdx=4, hub, opmagic=10009)。

全量统计:288 条 stitch 边中,224 条为 leaf→leaf(异常),0 条为 leaf→hub。


二、HUB_MIX 建立与 hub 替换机制

2.1 HUB_MIX 节点建立(编码期)

AddHubMixForWrapTask (dev_encode.cpp:1757):

  1. 按 wrapId 分组所有 callop
  2. 对每个 wrap 调用 InsertHubMixForWrapGroup,无条件建立 HUB_MIX 节点,将 pred -> [callop...] 重接为 pred -> hubMix -> [callop...]
  3. recordMapping=true 时记录 opToHubOp[callOp] = hubMixOp

opToHubOp → opIdxToHubOpIdx_ (dev_encode.cpp:2140-2143): 建立 leaf op idx → hub op idx 的查表映射。

2.2 wrapTaskHubOpIdx 机制

DevAscendFunctionCallOperandUse 有两个字段 (dev_encode_operation.h:53-71):

  • operationIdx: leaf op 的 idx(用于张量偏移计算)
  • wrapTaskHubOpIdx: 对应 HUB_MIX op 的 idx(默认 INVALID_WRAP_TASK_HUB_OP_IDX = -1,用于依赖建立时替换)

stitch 依赖建立时的两条独立职责:

  • 张量偏移计算 (GetTensorOffsetAndValidShape): 始终用 operationIdx(leaf op)
  • 依赖建立 (CellMatchStitchEnhance → HandleOneStitch): 用 wrapTaskHubOpIdx 替换(hub op),若为 INVALID 则用 operationIdx(leaf op)

2.3 RAW 路径(已正确,本次未改动)

RAW 场景的 consumer 是 incast op(后读者),走 PartialUpdateStitchConsumer 路径,hub 替换已完整:

环节 位置 状态
编码期设置 wrapTaskHubOpIdx FillIncastUseList (dev_encode.cpp:876-879) ✓ 已有
编码期 FullCover consumer 替换 stitchPolicyFullCoverConsumerAllOpIdxList 填充 (dev_encode.cpp:1037-1039) ✓ 已有
运行时 hub 替换 PartialUpdateStitchConsumer (device_stitch_context.cpp:343-350) ✓ 已有
运行时 hub 替换 FullCoverDefaultUpdateStitch (device_stitch_context.cpp:393-400) ✓ 已有

三、WAW/WAR 路径的三重缺陷(本次修复)

WAW/WAR 场景的 consumer 是 outcast op(后写者),走 PartialUpdateStitchProducer 路径。该路径的 hub 替换存在三重缺陷:

缺陷1: FillOutcastUseList 未设置 wrapTaskHubOpIdx

dev_encode.cpp:886-903 不接收 opIdxToHubOpIdx 参数,直接复制 useList 不做 hub 替换。对比 FillIncastUseList(RAW 路径)有完整的替换逻辑。

缺陷2: stitchPolicyFullCoverProducerList 填充未设置 wrapTaskHubOpIdx

dev_encode.cpp:1019-1020 直接复制,无 hub 替换。

缺陷3: PartialUpdateStitchProducer 运行时不做 hub 替换

device_stitch_context.cpp:503-506 直接用 producer.operationIdx(leaf),未像 PartialUpdateStitchConsumer 那样查 wrapTaskHubOpIdx 替换为 hub。

命名澄清: outcast.producerConsumerList 的元素虽名为 "producer"(outcast 张量的产出 op),但在 cellMatch 依赖建立中实际扮演 consumer(后访问者) 角色:

  • CellMatchStitchEnhance 的 operationIdx 参数传入 HandleOneStitch 作为 consumerOperationIdx
  • cellMatchTable 中存的是先访问者(真正的 producer),当前 outcast op 是后访问者(consumer)

因此缺陷3 中 producer.operationIdx 实为 consumer 端 op idx,需要替换为 hub。

缺陷4(通用性): recordMapping = isIncastWrap 限制

AddHubMixForWrapTask 中仅对消费 incast 张量的 wrap 记录 opToHubOp 映射。纯 WAW/WAR 场景(wrap 只 outcast 不 incast)的 wrap 无映射,即使修复缺陷1-3 也不生效。在当前 flash_attention case 中 k_tile_loop 既读又写(isIncastWrap=true),此缺陷不触发,但从框架通用性角度需修复。


四、修复方案(6 处改动,3 个文件)

改动1: dev_encode.cpp — recordMapping 始终为 true

移除 isIncastWrap 判断及相关的 incastWrapIds/incastRawmagics 收集逻辑,InsertHubMixForWrapGroup 始终以 recordMapping=true 调用,让所有 wrap 都记录 opToHubOp 映射。

改动2: dev_encode_function.h — FillOutcastUseList 声明添加参数

  void FillOutcastUseList(..., bool fillContent,
+                         const std::unordered_map<int, int>& opIdxToHubOpIdx);

改动3: dev_encode.cpp — FillOutcastUseList 实现添加 hub 替换

  At(outcast.producerConsumerList, k) = attr.useList[k];
+ auto it = opIdxToHubOpIdx.find(attr.useList[k].operationIdx);
+ if (it != opIdxToHubOpIdx.end()) {
+     At(outcast.producerConsumerList, k).wrapTaskHubOpIdx = it->second;
+ }

改动4: dev_encode.cpp — InitIncastOutcast 调用传入 opIdxToHubOpIdx

- FillOutcastUseList(useList, useSize, outcastTensorList, outcastOpAttrDict, fillContent);
+ FillOutcastUseList(useList, useSize, outcastTensorList, outcastOpAttrDict, fillContent, opIdxToHubOpIdx);

改动5: dev_encode.cpp — stitchPolicyFullCoverProducerList 填充添加 hub 替换

  At(outcast.stitchPolicyFullCoverProducerList, k) = outAttr.stitchPolicyFullCoverProducerList[k];
+ auto it = opIdxToHubOpIdx.find(outAttr.stitchPolicyFullCoverProducerList[k].operationIdx);
+ if (it != opIdxToHubOpIdx.end()) {
+     At(outcast.stitchPolicyFullCoverProducerList, k).wrapTaskHubOpIdx = it->second;
+ }

改动6: device_stitch_context.cpp — PartialUpdateStitchProducer 添加运行时 hub 替换

+ int producerOpIdx = producer.operationIdx;
+ if (producer.wrapTaskHubOpIdx != INVALID_WRAP_TASK_HUB_OP_IDX) {
+     DEV_VERBOSE_DEBUG(...);
+     producerOpIdx = producer.wrapTaskHubOpIdx;
+ }
  CellMatchStitchEnhance(..., producer.operationIdx, slotIdx, &matchCount);
+                       ..., producerOpIdx, slotIdx, &matchCount);

关键: GetTensorOffsetAndValidShape 保持使用 producer.operationIdx(leaf op idx,张量偏移按 leaf 计算),仅 CellMatchStitchEnhance 使用替换后的 producerOpIdx(hub op idx,依赖按 wrap 整体建立)。


五、修复后的依赖模式

场景 先访问者 (producer) 后访问者 (consumer) 依赖建立路径 consumer 端 hub 替换
RAW (先写后读) outcast W (leaf) incast R PartialUpdateStitchConsumer ✓ 已有(FillIncastUseList + 运行时替换)
WAR (先读后写) incast R (leaf) outcast W PartialUpdateStitchProducer ✓ 本次新增(FillOutcastUseList + 运行时替换)
WAW (先写后写) outcast W (leaf) outcast W PartialUpdateStitchProducer ✓ 本次新增(FillOutcastUseList + 运行时替换)

三种场景的 consumer 端(后访问者)均替换为 hub,producer 端(先访问者,cellMatchTable 中记录的)保持 leaf,形成 leaf(producer) → hub(consumer) 依赖。


六、验证结果

6.1 编译与 UT

  • 6 处改动应用后 make -j32 编译通过
  • UT TestDevEncode.test_add_hub_mix_for_wrap_task PASSED
  • 通过 python3 build_ci.py -s --disable_auto_execute --frontend=python3 -j=32 完整构建并安装到 build_out

6.2 精度验证

test_03 (batch=8, heads=16, s1=32, s2=32, dim=32):

  test_03: batch=8, heads=16, Q:s1_size=32, KV:s2_size=32, dim=32  => PASSED
Overall: ALL PASSED

精度无回归。

6.3 依赖拓扑验证(dyn_topo.txt)

funcIdx 35 opIdx 3 (taskId 2293763) 的 stitch 后继对比:

修复前 修复后
staticSucc 2293765(出口) 2293765(出口)
stitch 后继 2818051(funcIdx 43 opIdx 3, leaf, opmagic=10001) 2818052(funcIdx 43 opIdx 4, hub, opmagic=10009)

funcIdx 35 的三个 leaf op 的 stitch 后继全部从 leaf→leaf 变为 leaf→hub:

  • 2293761 (opIdx1, opmagic=10003) → 2818052 (hub)
  • 2293762 (opIdx2, opmagic=10002) → 2818052 (hub)
  • 2293763 (opIdx3, opmagic=10001) → 2818052 (hub)

6.4 整体统计

dyn_topo.txt 全量 stitch 边统计:

指标 修复前 修复后
total stitch edges 288 288
leaf→leaf(异常) 224 0
leaf→hub(正常) 0 224

所有 WAW/WAR 场景的 leaf→leaf 依赖已全部修正为 leaf→hub。


七、与 cellShape 修复的关系

本方案与 session-ses_cellmatch_false_waw.md 中的 cellShape 修复互补:

维度 修 cellShape 修 HUB_MIX(本方案)
目标 消除假 WAW 依赖 接受依赖,让依赖正确连到 hub
效果 减少串行化(无冲突则无依赖) 恢复 wrap 级调度粒度(leaf→hub)
影响范围 cellMatch 冲突检测 stitch 依赖建立
  • 只修 HUB_MIX: 依赖仍串行(冲突仍在),但粒度从 leaf→leaf 变为 leaf→hub,恢复 wrap 级调度语义
  • 只修 cellShape: 不重叠的写入不再冲突,无 stitch 边,实例可并行
  • 两者都修: 必要的 WAW/WAR 依赖正确连 hub,不必要的假依赖消除

八、关键代码路径索引

HUB_MIX 建立

  • dev_encode.cpp:1535-1544: MakeDummyCallHubMix (创建 HUB_MIX dummy op)
  • dev_encode.cpp:1714-1744: InsertHubMixForWrapGroup (插入 HUB_MIX,重接依赖图)
  • dev_encode.cpp:1757-1786: AddHubMixForWrapTask (按 wrapId 统一插入,recordMapping 始终 true)
  • dev_encode.cpp:2140-2143: opToHubOp → opIdxToHubOpIdx_

RAW consumer 端 hub 替换(未改动,已有)

  • dev_encode.cpp:862-884: FillIncastUseList (设置 incast.consumerList.wrapTaskHubOpIdx)
  • dev_encode.cpp:1034-1044: stitchPolicyFullCoverConsumerAllOpIdxList 填充 (编码期替换)
  • device_stitch_context.cpp:343-350: PartialUpdateStitchConsumer (运行时替换)
  • device_stitch_context.cpp:393-400: FullCoverDefaultUpdateStitch (运行时替换)

WAW/WAR consumer 端 hub 替换(本次新增)

  • dev_encode.cpp:886-909: FillOutcastUseList (新增 opIdxToHubOpIdx 参数 + hub 替换)
  • dev_encode.cpp:1026-1031: stitchPolicyFullCoverProducerList 填充 (新增 hub 替换)
  • dev_encode.cpp:989: InitIncastOutcast 调用传入 opIdxToHubOpIdx (新增)
  • device_stitch_context.cpp:503-510: PartialUpdateStitchProducer (新增运行时 hub 替换)

数据结构

  • dev_encode_operation.h:24: INVALID_WRAP_TASK_HUB_OP_IDX = -1
  • dev_encode_operation.h:53-71: DevAscendFunctionCallOperandUse (operationIdx + wrapTaskHubOpIdx)
  • dev_encode_operation.h:85-101: DevAscendFunctionOutcast (producerConsumerList + stitchPolicyFullCoverProducerList)
  • common.h:194: CoreType::HUB_MIX = 6
  • common.h:196: HUB_MIX_DUMMY_HASH = 0xFFFFFFFFFFFFFFFEULL

likedislike
xuyi_37xuyi_37Collaborators
Jul 28 Modify description of issue
xuyi_37
xuyi_37Collaborators
Jul 28 Comments:

Flash Attention 用例 WAW 依赖建立机制分析(用例验证)

日期: 2026-07-28
测试入口: myRun.sh → python/tests/st/operator/flash_attention_mha/test_flash_attention_mha.py
分析对象: test_03 (batch=8, heads=16, s1=32, s2=32, dim=32)
状态: 分析文档(无代码改动)
关联文档:

  • session-ses_cellmatch_false_waw.md(cellShape 过粗导致假 WAW 根因)
  • session-ses_hubmix_waw_war.md(WAW/WAR 路径 HUB_MIX 替换修复)
  • session-ses_stitch_producer_hub.md(Stitch producer hub 替换历史修复)

一、用例与 kernel 结构

1.1 myRun.sh 入口

myRun.sh:51 执行:

python3 python/tests/st/operator/flash_attention_mha/test_flash_attention_mha.py

main()(test_flash_attention_mha.py:396)顺序执行 test_01..test_06。本文以 test_03 为例:

# test_flash_attention_mha.py:373
def test_03():
    """batch=8, heads=16, s1=32, s2=32, dim=32"""
    return run_test(batch_size=8, num_heads=16, s1_size=32, s2_size=32, dim=32)

1.2 kernel 循环结构

flash_attention_mha_impl.py:131-160 定义 4 层循环:

batch_loop(8) × head_loop(8) × q_tile_loop(?) × k_tile_loop(?)

test_03 参数下:

  • s1=32, Q_TILE=320 → q_tile_count = ceil(32/320) = 1
  • s2=32, K_TILE=320 → k_tile_count = ceil(32/320) = 1
  • h_num = num_heads // 2 = 8,内层 h_s_idx in range(2) 每次处理 2 个 head

故总实例数 = 8 × 8 × 1 × 1 = 64,来自 batch × head 外层展开,无 tile 迭代。

1.3 GM 写入点

每个实例在 k_tile_loop 的 is_loop_begin && is_loop_end 分支(flash_attention_mha_impl.py:215-228)用 pypto.assemble 写回 3 个 GM 张量:

pypto.assemble(lij,     [q_start + q_tile_start, h_act_idx], l_output)  # [32,1] FP32
pypto.assemble(mij,     [q_start + q_tile_start, h_act_idx], m_output)  # [32,1] FP32
pypto.assemble(out_bf16,[q_start + q_tile_start, h_offset],   output)   # [32,32] BF16
  • q_start = cu_seqlens_q[b_idx] = b_idx × 32(每 batch 32 行)
  • h_act_idx = h_idx × 2 + h_s_idx,h_offset = h_act_idx × head_dim
  • 64 个实例写的是 不同 GM 区域,理论上无数据冲突

二、WAW 依赖的来源:假 WAW

2.1 cellMatch 机制回顾

PyPTO device 侧通过 cellMatch 检测跨 wrap 的 GM 访问冲突:

  • 把 GM 张量按 cellShape 切分为 cell
  • 每个 slot 维护一张 cellMatchRuntimePartialUpdateTable,记录"谁先访问了哪个 cell、以什么 opType"
  • 后访问者查表,若与先访问者互斥(CellMatchIsMutexOp=true)则建立 stitch 依赖边

opType 与互斥规则(dev_cell_match_mem_layout.h:160-166):

opType 值 含义
CELL_MATCH_OP_TYPE_NORMAL_WRITE 0 普通写
CELL_MATCH_OP_TYPE_ATOMIC_WRITE 1 原子写
CELL_MATCH_OP_TYPE_READ 2 读
CELL_MATCH_OP_TYPE_NONE 0xF 空
inline bool CellMatchIsMutexOp(uint32_t curOpType, uint32_t prepType) {
    if (curOpType == prepType) {
        return (curOpType == CELL_MATCH_OP_TYPE_NORMAL_WRITE);  // 同类型仅普通写互斥 (WAW)
    }
    return true;  // 不同类型一律互斥 (RAW/WAR/ATOMIC 与任何)
}

2.2 cellShape 过粗导致假 WAW

l_output shape [256, 16],实际 cellShape = [64, 1](来源见 session-ses_cellmatch_false_waw.md:137-148,怀疑来自 vec tile shape v1_tile=[64,512],未完全定位):

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

每次 assemble 写入仅 [32, 1],两个相邻 batch 的 32 行写入共同落入同一 64 行的 row_cell:

实例 batch head 写入行范围 写入列 落入 cell
funcIdx 35 b=4 h_act=4 [128, 160) col 4 cell 36
funcIdx 43 b=5 h_act=4 [160, 192) col 4 cell 36

行范围 [128,160) 与 [160,192) 相邻但不重叠,却因 cellShape[0]=64 被划入同一 cell → 假 WAW。

若 cellShape[0]=32(与每次写入 shape 一致):b4→row_cell 4,b5→row_cell 5,无冲突,无 stitch 边。

2.3 串行化影响

  • 8 条平行链(funcIdx % 8 相同的实例构成一条链,间隔 8 = 不同 batch 同 head_loop 位置)
  • 每条链 8 个实例顺序执行(因 WAW stitch 边)
  • 实际并行度从 64 降至 8,性能损失约 8 倍(理论值)

三、WAW 依赖建立的两阶段流程

WAW 边由 device 侧 cellMatch 在运行时建立(session-ses_cellmatch_false_waw.md:82),分两阶段:

3.1 阶段 A:先访问者登记(funcIdx 35 提交时)

调用链:

device_execute_context.cpp:591  slotContext.UpdateSlots(...)
  → device_slot_context.cpp:213  UpdateSlotsImpl
    → device_slot_context.cpp:131  UpdateSlotsForOutCastStitch
      → device_slot_context.cpp:82   UpdateSlotsForOutCastPartialStitch
        → dev_encode_function_stitch.h:411  CellMatchFillIncastOutcast
          → dev_encode_function_stitch.h:313 CellMatchFillEnhanceExec

CellMatchFillEnhanceExec(dev_encode_function_stitch.h:313-359)核心逻辑:

  1. 读 cell 当前 meta:curActiveOpType、curActiveOpCount、curTagId
  2. CellMatchIsMutexOp(myOpType=NORMAL_WRITE, curActiveOpType) 判定:
    • 互斥 → SetCurrentOpType(myOpType)、SetPrevMutexOpType(curActiveOpType)、targetCount=1(覆盖登记)
    • 不互斥(同批次累加)→ targetCount = curActiveOpCount + 1
  3. 写入:SetCurrentOpCount(targetCount)、SetTagId(updateTagId)、CellMatchAddOpId(taskID)

funcIdx 35 的 WRITE op 把以下信息写入 slot 4(l_output) 的 cellMatch 表 cell 36:

cellMatchRuntimePartialUpdateTable[slot 4][cell 36]:
  meta:
    currentOpType  = NORMAL_WRITE (0)
    currentOpCount = 1
    tagId          = CellMatchBuildTagId(slotAllocIterId, cellMatchTagSeq)
  opId 槽:
    = MakeTaskID(funcIdx=35, operationIdx=leaf_op_idx)

3.2 阶段 B:后访问者查表建依赖(funcIdx 43 提交时)

调用链:

device_execute_context.cpp:589  stitchContext.Stitch(...)
  → device_stitch_context.cpp:108  Stitch
    → device_stitch_context.cpp:658  FastStitch
      → device_stitch_context.cpp:630  FastStitchProducer
        → device_stitch_context.cpp:464  PartialUpdateStitchProducer
          → dev_stitch_dependency_enhanced.h:131  CellMatchStitchEnhance
            → dev_stitch_dependency_enhanced.h:81   CellMatchStitchHandle
              → EstablishDependenciesWithType
                → device_stitch_context.cpp:293  HandleOneStitch

PartialUpdateStitchProducer(device_stitch_context.cpp:464-525)核心步骤:

  1. 遍历 outcast.producerConsumerList(编码期由 FillOutcastUseList 填充,每条记录一个 WRITE op)
  2. 跳过 READ(:482-484):只处理 opType != READ 的生产者
  3. 算 cell 范围:GetTensorOffsetAndValidShape(:487)用 leaf op idx(producer.operationIdx)算出 funcIdx 43 的写区域 rows[160,192)×col4 → cell 36
    • 张量偏移始终按 leaf 计算(session-ses_hubmix_waw_war.md:158)
  4. Hub 替换(:503-510):
    int producerOpIdx = producer.operationIdx;
    if (producer.wrapTaskHubOpIdx != INVALID_WRAP_TASK_HUB_OP_IDX) {
        producerOpIdx = producer.wrapTaskHubOpIdx;  // 替换为 funcIdx 43 的 HUB_MIX op idx
    }
    
  5. CellMatchStitchEnhance(:511)→ CellMatchStitchHandle(dev_stitch_dependency_enhanced.h:81-128) 逐 cell 查表:
    • 读 meta:curActiveOpType = NORMAL_WRITE(funcIdx 35 登记)
    • myOpType = NORMAL_WRITE(funcIdx 43)
    • CellMatchIsMutexOp(NORMAL_WRITE, NORMAL_WRITE) = true(同类型普通写互斥)
    • → EstablishDependenciesWithType(:111)→ HandleOneStitch(:293)建立依赖边

3.3 依赖边方向

HandleOneStitch(device_stitch_context.cpp:293-301) 建立的边:

producer(先访问者): funcIdx 35 的 WRITE leaf op
                     cellMatch 表中存的是 leaf idx(operationIdx)
consumer(后访问者): funcIdx 43 的 HUB_MIX op
                     Hub 替换后的 producerOpIdx(wrapTaskHubOpIdx)

形成 leaf(producer) → hub(consumer) 边。

命名澄清(session-ses_hubmix_waw_war.md:94-98):outcast.producerConsumerList 的元素虽名为 "producer"(outcast 张量的产出 op),但在 cellMatch 依赖建立中实际扮演 consumer(后访问者) 角色。cellMatch 表中存的是先访问者(真正的 producer),当前 outcast op 是后访问者(consumer)。


四、示意图

图1:循环展开与 64 个实例的 GM 写入

batch_loop(8) × head_loop(8) × {q_tile_loop(1), k_tile_loop(1)}
   │              │
   │              └─ 每次处理 2 head (h_s_idx∈range(2)),8次覆盖16 head
   └─ 每批 s1=32 行
                    ↓
   64 个 (batch,head) 实例 = 64 个 funcIdx (运行时 stitchedList 索引)
                    ↓
   每个实例 assemble 写 3 个 GM 张量:
        l_output[256,16]  m_output[256,16]  output[256,512]
                    ↓
   写入区域: rows [b*32, b*32+32) × col {h_act_idx}   ← 每个 32 行

图2:cellShape 过粗导致假 WAW(以 l_output slot 为例)

l_output shape=[256,16]   cellShape=[64,1]   → cell [row/64][col/1]

        col 0      col 4      col 5     ...  col 15
      ┌─────────┬─────────┬─────────┬─────┬────────┐
row   │         │         │         │     │        │
[0,64)│  cell 0 │  cell 4 │  cell 5 │ ... │ cell 15│  ← b0(rows0-31) & b1(rows32-63) 都落此行
      ├─────────┼─────────┼─────────┼─────┼────────┤
row   │         │         │         │     │        │
[64, │  cell16 │  cell20 │  cell21 │ ... │ cell 31│  ← b2 & b3
128)  │         │         │         │     │        │
      ├─────────┼─────────┼─────────┼─────┼────────┤
row   │         │  ╔═════╗│  ╔═════╗│     │        │
[128,│  cell32 │  ║cell36║  ║cell37║ ... │ cell 47│  ← b4(rows128-159) & b5(rows160-191)
192)  │         │  ╚═════╝│  ╚═════╝│     │        │
      ├─────────┼─────────┼─────────┼─────┼────────┤
row   │         │         │         │     │        │
[192,│  cell48 │  cell52 │  cell53 │ ... │ cell 63│  ← b6 & b7
256)  │         │         │         │     │        │
      └─────────┴─────────┴─────────┴─────┴────────┘

  funcIdx 35 (b=4): assemble 写 [128,160)×col4 → cell 36 ┐ 同 cell → 假 WAW
  funcIdx 43 (b=5): assemble 写 [160,192)×col4 → cell 36 ┘ (实际行不重叠)

  若 cellShape[0]=32(=写入shape): b4→cell(row4), b5→cell(row5), 无冲突, 无 stitch 边

图3:WAW 依赖建立时序(funcIdx 35 → 43)

时间轴 ──────────────────────────────────────────────────────►

[funcIdx 35 提交]                    [funcIdx 43 提交]
    │                                     │
    ▼                                     ▼
┌─────────────────────┐         ┌─────────────────────────────┐
│ UpdateSlots         │         │ Stitch → FastStitch         │
│ (阶段A: 登记)       │         │  → FastStitchProducer       │
│                     │         │  → PartialUpdateStitchProducer│
│ 写 cell 36:         │         │                             │
│  opType=NORMAL_WRITE│         │ 1.算写区域 → cell 36         │
│  opId=taskID(35,leaf)│        │ 2.Hub替换: opIdx→43的HUB_MIX │
│  tagId=T            │         │ 3.查 cell 36:               │
│                     │         │   cur=NORMAL_WRITE(35登记)  │
│                     │         │   my =NORMAL_WRITE(43)      │
│                     │         │   IsMutexOp(W,W)=true       │
│                     │         │ 4.HandleOneStitch 建边      │
└─────────────────────┘         └─────────────────────────────┘
        │                                     │
        ▼                                     ▼
   cellMatch 表[cell 36]              stitch 依赖边
   ┌───────────────────┐         ┌────────────────────────┐
   │meta: cur=NORMAL_W │         │ funcIdx35              │
   │      cnt=1        │         │   WRITE leaf op        │
   │      tagId=T      │  ──────►│   (先访问者,leaf)      │
   │opId: taskID(35,   │  建边   │         │              │
   │  leaf_opIdx)      │         │         ▼              │
   └───────────────────┘         │ funcIdx43 HUB_MIX      │
                                 │   (后访问者,hub)       │
                                 └────────────────────────┘

图4:Hub 替换形成 leaf(producer)→hub(consumer) 边

   funcIdx 35 (先写者)               funcIdx 43 (后写者)
   ┌──────────────────┐              ┌──────────────────────┐
   │  leaf WRITE op   │              │  HUB_MIX op (hub)    │
   │  (opIdx 3)       │              │  ┌────────────────┐  │
   │  operationIdx=3  │              │  │ opIdx 4        │  │
   │  wrapTaskHubOpIdx│              │  │ (汇聚wrap依赖) │  │
   │  (cellMatch表中  │   WAW 边     │  └───────┬────────┘  │
   │   存的是 leaf)   │──────────────►│          │ dispatch  │
   │                  │              │          ▼           │
   │  保持 leaf idx   │              │  [leaf0,leaf1,leaf2] │
   │  (张量偏移计算用)│              │  (wrap内3个mix leaf) │
   └──────────────────┘              └──────────────────────┘
   cellMatch 表记录:                  Hub替换后建边:
   producer = leaf(35)                consumer = hub(43)

修复前(session-ses_hubmix_waw_war.md:36-40):边为 leaf(35)→leaf(43),破坏 wrap 级调度。
修复后(改动6,device_stitch_context.cpp:503-510):边为 leaf(35)→hub(43),恢复 wrap 级粒度。

图5:8 条串行链的全局视图

funcIdx % 8 分组(每条链 8 个实例,间隔 8 = 不同 batch 同 head_loop 位置)

chain 0: funcIdx 0  → 8  → 16 → 24 → 32 → 40 → 48 → 56
chain 1: funcIdx 1  → 9  → 17 → 25 → 33 → 41 → 49 → 57
chain 2: funcIdx 2  → 10 → 18 → 26 → 34 → 42 → 50 → 58
chain 3: funcIdx 3  → 11 → 19 → 27 → 35  →43 → 51 → 59   ← 本文样例
chain 4: funcIdx 4  → 12 → 20 → 28 → 36 → 44 → 52 → 60
chain 5: funcIdx 5  → 13 → 21 → 29 → 37 → 45 → 53 → 61
chain 6: funcIdx 6  → 14 → 22 → 30 → 38 → 46 → 54 → 62
chain 7: funcIdx 7  → 15 → 23 → 31 → 39 → 47 → 55 → 63

每条链内: 8 个实例顺序执行 (WAW stitch 边串行化)
8 条链之间: 可并行

实际并行度 = 8 (链数), 而非 64 (实例总数)

五、关键代码路径索引

5.1 cellMatch 机制核心

  • framework/src/machine/utils/dynamic/dev_cell_match_mem_layout.h:160-166: CellMatchIsMutexOp(互斥判定)
  • framework/src/machine/utils/dynamic/dev_cell_match_mem_layout.h:42-45: opType 常量定义
  • framework/src/machine/utils/dynamic/dev_stitch_dependency_enhanced.h:81-128: CellMatchStitchHandle(查表建依赖)
  • framework/src/machine/utils/dynamic/dev_stitch_dependency_enhanced.h:131-164: CellMatchStitchEnhance(入口模板)
  • framework/src/machine/utils/dynamic/dev_encode_function_stitch.h:313-359: CellMatchFillEnhanceExec(登记先访问者)
  • framework/src/machine/utils/dynamic/dev_encode_function_stitch.h:411-447: CellMatchFillIncastOutcast(填充入口)

5.2 运行时两阶段调用链

  • 阶段 A(登记):
    • framework/src/machine/device/dynamic/context/device_execute_context.cpp:591: UpdateSlots 调用点
    • framework/src/machine/device/dynamic/context/device_slot_context.cpp:213: UpdateSlotsImpl
    • framework/src/machine/device/dynamic/context/device_slot_context.cpp:131: UpdateSlotsForOutCastStitch
    • framework/src/machine/device/dynamic/context/device_slot_context.cpp:82: UpdateSlotsForOutCastPartialStitch
  • 阶段 B(建依赖):
    • framework/src/machine/device/dynamic/context/device_execute_context.cpp:589: Stitch 调用点
    • framework/src/machine/device/dynamic/context/device_stitch_context.cpp:108: Stitch
    • framework/src/machine/device/dynamic/context/device_stitch_context.cpp:658: FastStitch
    • framework/src/machine/device/dynamic/context/device_stitch_context.cpp:630: FastStitchProducer
    • framework/src/machine/device/dynamic/context/device_stitch_context.cpp:464: PartialUpdateStitchProducer(WAW/WAR 路径)
    • framework/src/machine/device/dynamic/context/device_stitch_context.cpp:303: PartialUpdateStitchConsumer(RAW 路径,对比参考)
    • framework/src/machine/device/dynamic/context/device_stitch_context.cpp:293: HandleOneStitch(建边)

5.3 编码期 use 列表填充

  • framework/src/machine/utils/dynamic/dev_encode.cpp:862-884: FillIncastUseList(incast consumerList,含 hub 替换)
  • framework/src/machine/utils/dynamic/dev_encode.cpp:886-908: FillOutcastUseList(outcast producerConsumerList,含 hub 替换)
  • framework/src/machine/utils/dynamic/dev_encode.cpp:905-945: InitIncastOutcast(调用填充)
  • framework/src/machine/utils/dynamic/dev_encode.cpp:1319: outcast consumer use emplace_back(READ)
  • framework/src/machine/utils/dynamic/dev_encode.cpp:1352: outcast producer use emplace_back(WRITE/ATOMIC_WRITE)
  • framework/src/machine/utils/dynamic/dev_encode.cpp:1488: incast consumer use emplace_back(READ)

5.4 HUB_MIX 建立与 hub 替换

  • framework/src/machine/utils/dynamic/dev_encode.cpp:1535-1544: MakeDummyCallHubMix(创建 HUB_MIX dummy op)
  • framework/src/machine/utils/dynamic/dev_encode.cpp:1714-1744: InsertHubMixForWrapGroup(插入 HUB_MIX,重接依赖图)
  • framework/src/machine/utils/dynamic/dev_encode.cpp:1757-1786: AddHubMixForWrapTask(按 wrapId 统一插入,recordMapping 始终 true)
  • framework/src/machine/utils/dynamic/dev_encode.cpp:2140-2143: opToHubOp → opIdxToHubOpIdx_
  • framework/src/machine/utils/dynamic/dev_encode_operation.h:53-71: DevAscendFunctionCallOperandUse(operationIdx + wrapTaskHubOpIdx)
  • framework/src/machine/utils/dynamic/dev_encode_operation.h:24: INVALID_WRAP_TASK_HUB_OP_IDX = -1

5.5 cellShape 计算

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

5.6 数据结构

  • framework/src/machine/utils/dynamic/dev_encode_operation.h:85-101: DevAscendFunctionOutcast(producerConsumerList + stitchPolicyFullCoverProducerList)
  • framework/src/machine/utils/dynamic/dev_encode_operation.h:103-115: InoutOperationAttr(useList 字段)
  • framework/src/machine/utils/dynamic/dev_encode_function.h:106: DevAscendFunction::useList(设备端全局 use 列表)
  • framework/include/tilefwk/common.h:194: CoreType::HUB_MIX = 6
  • framework/include/tilefwk/common.h:196: HUB_MIX_DUMMY_HASH = 0xFFFFFFFFFFFFFFFEULL

六、三种冲突场景的路径对比

场景 先访问者(登记) 后访问者(查表建依赖) 后访问者走的路径 互斥判定
RAW 写后读 outcast W incast R FastStitchConsumer → PartialUpdateStitchConsumer(:303) IsMutexOp(READ, WRITE)=true
WAR 读后写 incast R outcast W FastStitchProducer → PartialUpdateStitchProducer(:464) IsMutexOp(WRITE, READ)=true
WAW 写后写 outcast W outcast W FastStitchProducer → PartialUpdateStitchProducer(:464) IsMutexOp(WRITE, WRITE)=true(仅 NORMAL_WRITE 互斥,ATOMIC_WRITE 自身不互斥)

三种场景的 consumer 端(后访问者)均替换为 hub,producer 端(先访问者,cellMatch 表中记录的)保持 leaf,形成 leaf(producer) → hub(consumer) 依赖(session-ses_hubmix_waw_war.md:170)。


七、关键设计点

  1. 两阶段分离:先访问者只"登记"(UpdateSlots,填 opType + taskID 到 cellMatch 表);后访问者才"查表建依赖"(FastStitch)。先访问者无需知道后续谁会来,只管记录自己的访问。

  2. opType 双重作用:编码期 FillIncastUseList/FillOutcastUseList 给每条 use 打 opType 标签(READ/NORMAL_WRITE/ATOMIC_WRITE,见 dev_encode.cpp:1319,1352,1488);运行期填表和查表都按 opType 判互斥。

  3. Hub 替换只在后访问者(consumer 端):先访问者保持 leaf idx(cellMatch 表中存的是 leaf),后访问者替换为 hub idx,形成 leaf(producer) → hub(consumer) 边,保持 wrap 级调度粒度(session-ses_hubmix_waw_war.md:170)。

  4. tagId 隔离批次:CellMatchBuildTagId(slot.slotAllocIterId, cellMatchTagSeq) 合成 tagId,CellMatchStitchHandle 中 CellMatchGetTagId(meta) != tagId 直接跳过(dev_stitch_dependency_enhanced.h:100-104),避免跨拼接批次误匹配。

  5. 张量偏移 vs 依赖建立分离:GetTensorOffsetAndValidShape 始终用 operationIdx(leaf op,张量偏移按 leaf 计算);CellMatchStitchEnhance 用替换后的 producerOpIdx(hub op,依赖按 wrap 整体建立)。两条职责独立(session-ses_hubmix_waw_war.md:62-63,158)。


likedislike
xuyi_37
xuyi_37Collaborators
Jul 28 Comments:

OrderedSet::Remove 非确定性修复文档

  • 基线提交: 54153eed6(MixHub support WAR/WAW)
  • 分支: dev_mixhub_opt
  • 修改文件: framework/src/interface/utils/common.h(OrderedSet<T>::Remove,+8 / −8 行)
  • 所属模块: interface/utils(数据结构)→ 影响面 machine/utils/dynamic/dev_encode.cpp(动态编码层)
  • 问题等级: 高(kBinary 不确定性 / 同输入不同输出)

1. 概述

OrderedSet<T>::Remove 在删除元素后重建 order 向量时,遍历了底层 std::unordered_map,遍历顺序依赖指针哈希值,跨运行不确定(ASLR / 分配器状态)。该不确定性通过 AddHubMixForWrapTask → InsertHubMixForWrapGroup → callOpSuccDict[pred].Remove(callops) 路径被触发,最终落入设备函数二进制(operationSuccList_)并影响运行时调度顺序,导致同一份输入图在不同运行中产出不同 kBinary。

修复方式:重建 order 时改为遍历 order 向量本身(保持插入序),用 std::set<T> 仅做成员判定。剩余元素保持原始相对插入顺序,编码结果确定。


2. 背景

2.1 OrderedSet<T> 的结构

定义于 framework/src/interface/utils/common.h:318,继承自 std::unordered_map<T, int>,额外维护一个 std::vector<T> order 成员记录插入顺序:

template <typename T>
struct OrderedSet : std::unordered_map<T, int> {
    bool Insert(const T& data) {
        if (this->count(data) == 0) {
            this->insert(std::make_pair(data, this->size()));
            order.push_back(data);
            return true;
        }
        return false;
    }
    ...
    std::vector<OrderElementType> order;
};

order 是其核心价值——begin()/end()、operator[](int)、GetOrder() 等接口均基于 order 向量提供「按插入序访问」。unordered_map 的 value(int 索引)只是反向查找用的辅助。

2.2 Remove 旧实现

void Remove(const std::vector<T>& items)
{
    bool removed = false;
    for (size_t i = 0; i < items.size(); i++) {
        if (this->count(items[i])) {
            this->erase(items[i]);
            removed = true;
        }
    }
    if (removed) {
        std::vector<T> newOrder;
        for (auto& [key, val] : dynamic_cast<std::unordered_map<T, int>&>(*this)) {  // ← 非确定性遍历
            val = newOrder.size();
            newOrder.push_back(key);
        }
        order = std::move(newOrder);
    }
}

unordered_map 的迭代顺序由桶分布决定,桶分布由 std::hash<T> 值与桶数共同决定;对指针类型(T = Operation*),哈希值直接来自指针,受 ASLR 与分配器状态影响,跨进程、跨运行均不一致。

2.3 callOpSuccDict 的角色

在 EncodeDevAscendFunctionInfo 中,callOpSuccDict 的类型为 std::unordered_map<Operation*, OrderedSet<Operation*>>(dev_encode.cpp:1109),记录每个 call op 的后继集合。它同时是:

  1. 依赖图正向边表:编码时被 PopulateOneEncodedOpGraphEdges(dev_encode.cpp:723)按下标写入 operationSuccList_;
  2. 运行时调度依据:设备侧 ResolveDepDyn(aicore_manager.h:1724)通过 GetOperationDepGraphSuccAddr 读取后继列表,按序原子递减前驱计数、推送就绪任务。

因此 order 向量的顺序会同时落入设备函数二进制并驱动运行时调度顺序。

2.4 AddHubMixForWrapTask 的触发路径

EncodeDevAscendFunctionInfo::Init (dev_encode.cpp:2127)
  └─ AddHubMixForWrapTask (dev_encode.cpp:1757)
       └─ for each wrapId: InsertHubMixForWrapGroup (dev_encode.cpp:1723)
            └─ for each pred in predSet:
                 callOpSuccDict[pred].Remove(callops)   ← 触发 Remove
                 callOpSuccDict[pred].Insert(hubMixOp)  ← hubMixOp 追加到不确定的 order 末尾

当某个 pred 的后继集合中存在被本 wrap 组消费的 callop 时,Remove(callops) 删除这些 callop,随后 Insert(hubMixOp) 把 hubMixOp 追加到 order 末尾。由于 Remove 内部遍历 unordered_map 重建 order,hubMixOp 在 order 中的位置之前的剩余后继排列顺序不确定,进而 hubMixOp 之后插入的元素相对位置也不确定。


3. 根因分析

3.1 不确定性入口

Remove 旧实现的非确定性入口唯一:for (auto& [key, val] : dynamic_cast<std::unordered_map<T, int>&>(*this)) 这一行。其余路径均确定:

路径 是否确定 说明
AddHubMixForWrapTask:1760 用 unordered_map 遍历构建 predListDict 确定 producer 顺序被 flatten 进 predSet(unordered_set),只取成员关系
predSet(unordered_set)遍历 确定 各 pred 的 OrderedSet 修改互相独立,处理顺序不影响最终状态
wrapIdToCallops(std::map)遍历 确定 std::map 有序
opToHubOp(unordered_map) 确定 仅作查表,顺序不参与编码
OrderedSet::Remove 内部 unordered_map 遍历 不确定 根因

3.2 传导链路

OrderedSet::Remove 遍历 unordered_map     ← 非确定性源头
  ↓
order 向量中剩余后继排列顺序不确定
  ↓
Insert(hubMixOp) 追加到不确定顺序的末尾
  ↓
PopulateOneEncodedOpGraphEdges (dev_encode.cpp:735)
  for (k = 0; k < opSuccSize; k++)
      succ = callList.GetIndex(callOpSuccDict.find(op)->second[k])   ← order[k]
      At(staticField.depGraphSuccList, k) = succ                     ← 写入 operationSuccList_
  ↓
operationSuccList_ 通过 DevLocalVector::HostInitDataSizeOffset
平铺进 DevAscendFunction.data[] 柔性数组 (dev_encode_function.h:119)
  ↓
设备函数二进制(kBinary)
  ↓
设备运行时 ResolveDepDyn (aicore_manager.h:1744) 按 succList 顺序派发任务

故 Remove 的非确定性既落进设备函数二进制,又驱动运行时调度顺序,表现为 kBinary 不确定。

3.3 影响范围

两处 OrderedSet::Remove 调用点均受影响:

  • dev_encode.cpp:1741:callOpSuccDict[pred].Remove(callops) —— AddHubMixForWrapTask 路径,主触发点。
  • dev_encode.cpp:1591:succOps.Remove(deadCallOps) —— RemoveDeadHubCall 路径,同样会触发非确定性重建。

只要 items 非空且 order 中存在未被删除的元素,就会产生差异。


4. 修复方案

4.1 新实现

void Remove(const std::vector<T>& items)
{
    std::set<T> toRemove(items.begin(), items.end());
    std::vector<T> newOrder;
    bool removed = false;
    for (auto& x : order) {                   // 遍历 order,确定性
        if (toRemove.count(x) != 0) {
            this->erase(x);
            removed = true;
        } else {
            this->at(x) = newOrder.size();
            newOrder.push_back(x);
        }
    }
    if (removed) {
        order = std::move(newOrder);
    }
}

4.2 关键设计点

  1. 遍历对象切换:从遍历 unordered_map 改为遍历 order 向量。order 是 std::vector<T>,遍历顺序就是内存中的连续排列,与插入序一致,确定。
  2. 成员判定用 std::set<T>:std::set 是有序红黑树,查找 O(log n);仅用于「x 是否在删除集合中」的判定,不参与输出顺序,故其内部有序性不影响确定性。
  3. 索引重算:保留元素在 unordered_map 中的 value(int 索引)同步更新为 newOrder 中的新位置,保证 GetIndex 等接口语义不变。
  4. removed 语义保留:仅当真正发生删除时才替换 order,与旧实现的 if (removed) 守卫一致,避免无删除时的无谓拷贝。
  5. std::set<T> 对 T 的要求:T 需支持 operator<。当前两处调用点 T = Operation*,裸指针支持 operator<(地址比较),满足要求;<set> 已在文件头 #include(common.h:27),无新增依赖。

4.3 与旧实现的语义对比

维度 旧实现 新实现 结论
删除集合构造 直接 this->erase(items[i]) std::set<T> toRemove + 遍历时 erase 删除集合成员相同
order 重建来源 遍历 unordered_map(非确定序) 遍历 order(插入序) 核心修复点
剩余元素相对顺序 不确定(依赖哈希) 保持原插入序 新实现确定
unordered_map value 更新 重建时按新序赋值 遍历时按新序赋值 索引语义一致
无删除时行为 不替换 order 不替换 order 一致
时间复杂度 O(n + m)(n=元素数, m=删除数) O(n log m + m log m)(set 查找) 略升,可接受

复杂度从 O(n+m) 升至 O(n log m),但 OrderedSet 主要用于依赖图编码,规模有限(百级),实测无可感知差异。


5. 等价性论证

对任一 OrderedSet 实例 S,设其当前 order = [a_0, a_1, ..., a_{n-1}],删除集合 items 对应的待删元素集合为 D(D ⊆ S),令 R = S \ D 为剩余集合。

命题:新实现产出的 order' 中,R 的元素排列顺序与原 order 中 R 元素的相对顺序一致。

证明:

  1. 新实现遍历 order,对每个 x ∈ order:
    • 若 x ∈ D:从 unordered_map 中 erase(x),不写入 newOrder;
    • 若 x ∈ R:写入 newOrder。
  2. 故 newOrder 中元素的相对顺序 = order 中 R 元素的相对顺序。
  3. 遍历 order 是线性的,无随机访问,顺序确定。
  4. 因此 order' = newOrder 中 R 元素的排列确定,且等于原 order 中 R 元素的子序列。

推论:后续 Insert(hubMixOp) 将 hubMixOp 追加到 order' 末尾,其位置确定;hubMixOp 之后插入的元素也按插入序确定。整个 order 向量在 Remove + Insert 后确定,编码结果确定。□


6. 风险与影响评估

6.1 正确性风险(低)

  1. 剩余元素顺序变更:旧实现剩余元素顺序非确定(实际表现为「按 unordered_map 桶序」),新实现改为「按原插入序」。这是行为变更,但旧实现的「桶序」本就不是任何调用方依赖的契约——OrderedSet 的契约是「按插入序」,旧实现的 Remove 是该契约的 bug。
  2. 下游消费方:callOpSuccDict 的下游(PopulateOneEncodedOpGraphEdges、EncodeCopyOutReslove、MarkDeadEndHubs 等)均通过 order 或 GetOrder() 访问后继,不假设 Remove 后的顺序,仅依赖「成员关系 + 插入序」。
  3. std::set<T> 适用性:当前 OrderedSet 的实例化类型包括 Operation*、std::shared_ptr<RawTensor>、std::shared_ptr<LogicalTensor> 等,均支持 operator<(裸指针或 shared_ptr 的指针比较)。若未来实例化不支持 operator< 的类型,需改用 std::unordered_set + 自定义 hash,但当前无此用例。

6.2 性能影响(可忽略)

  • O(n+m) → O(n log m):OrderedSet 在编码路径规模为百级,log m 约 7,差异在微秒级,不影响编译性能。
  • std::set 构造 O(m log m):m 为删除元素数,同样可忽略。

6.3 kBinary 影响(正向)

  • 修复前:同一输入图跨运行产出不同 kBinary(受 ASLR 影响)。
  • 修复后:同一输入图跨运行产出相同 kBinary(order 确定性强)。
  • 这是本次修复的核心收益,对编译缓存命中、二进制 diff 比对、回归测试稳定性均有正向价值。

7. 关键代码位置索引

  • 修复点:framework/src/interface/utils/common.h:352(OrderedSet<T>::Remove)
  • OrderedSet 定义:framework/src/interface/utils/common.h:318
  • 触发路径入口:framework/src/machine/utils/dynamic/dev_encode.cpp:1757(AddHubMixForWrapTask)
  • Remove 调用点 1:framework/src/machine/utils/dynamic/dev_encode.cpp:1741(InsertHubMixForWrapGroup 内)
  • Remove 调用点 2:framework/src/machine/utils/dynamic/dev_encode.cpp:1591(RemoveDeadHubCall 内)
  • 编码写入点:framework/src/machine/utils/dynamic/dev_encode.cpp:735(PopulateOneEncodedOpGraphEdges)
  • operationSuccList_ 声明:framework/src/machine/utils/dynamic/dev_encode_function.h:98
  • depGraphSuccList 字段:framework/src/machine/utils/dynamic/dev_encode_operation.h:48
  • 设备运行时消费:framework/src/machine/device/dynamic/aicore_manager.h:1744(ResolveDepDyn)

8. 复现与验证建议

8.1 复现

修复前,对同一份含 mix wrap 的计算图多次执行编译,对比产出的 kBinary:

# 伪代码:多次编译同一图,对比 binary
for i in 1 2 3 4 5; do
    python compile_same_graph.py --output binary_$i.bin
done
md5sum binary_*.bin   # 修复前会出现不同 hash

非确定性在 predSet 非空且 order 中有未被删除元素时触发;纯 WAW/WAR 场景若 Remove 的 items 覆盖整个 order(即 R = ∅),则不触发。

8.2 验证

修复后重复上述步骤,md5sum 应全部相同。亦可单测 OrderedSet::Remove:

// 伪测例
OrderedSet<int> s;
s.Insert(1); s.Insert(2); s.Insert(3); s.Insert(4);
s.Remove({2, 4});
assert(s.GetOrder() == std::vector<int>{1, 3});   // 保持插入序
assert(s.GetIndex(1) == 0);
assert(s.GetIndex(3) == 1);

旧实现该断言会间歇性失败(取决于 unordered_map 桶序)。

likedislike
xuyi_37xuyi_37Collaborators
Jul 29 changed custom state from 待办的 to 已解决
xuyi_37xuyi_37Collaborators
Jul 29 Close issue
CANN-robotCANN-robotCollaborators
Jul 29 Added label: resolved