Merged
feat(Operation): Add input tile shape resolver. #5126
高前程Add on Jul 27
feat(Operation): Add input tile shape resolver. #5126
Merged
高前程Add on Jul 27
高前程
高前程Collaborators
Jul 27

TileShapeResolver:算子输入/输出 Tile 形状解析器

1. 背景与目标

PyPTO 的 tensor-graph 算子在展开(ExpandFunction)前只携带一个 op 级 TileShape(描述"输出怎么切")。但算子的每个输入/输出 tensor 实际被切成的第一刀 tile 形状并不等于 op 级 TileShape:

  • 广播算子的输入要按自身 shape 做 min clamp;
  • reduce 算子的 reduce 轴保持 full、非 reduce 轴按 vecTile 切;
  • gather/scatter/sort/topk/matmul/transdata 等各有专属切法;
  • 输出侧 cube 算子按 CubeTile 切、transdata 输出维度与输入不同……

下游(内存估算、调度、合轴等)需要在不真正展开的前提下,直接从一个 Operation 推断其每个输入/输出的真实 tile 形状。TileShapeResolver 就是提供这个能力的单例工具类。

2. 整体设计

framework/src/interface/operation/tile_shape_resolver.h

class TileShapeResolver {
public:
    static TileShapeResolver& Instance();
    // 由 op 的 opcode + op 级 TileShape + 各 operand 自身 shape,推算第 index 个输入的真实 tile 形状
    TileShape GetInputTileShape(const Operation& op, int index) const;
    // 由 op 的 opcode + op 级 TileShape + 各 operand 自身 shape,推算第 index 个输出的真实 tile 形状
    TileShape GetOutputTileShape(const Operation& op, int index) const;
private:
    TileShapeResolver() = default;
    TileShapeResolver(const TileShapeResolver&) = delete;
    TileShapeResolver& operator=(const TileShapeResolver&) = delete;
};
  • 单例 + 无状态:所有信息从 Operation 现取,线程安全。
  • 只覆盖 tensor op:只对有 REGISTER_OPERATION_TILED_FUNC(即有 tile 展开的 tensor op)的 opcode 给出语义;tile op 不在本解析器职责内。
  • 返回 TileShape:当前只填 VecTile(cube 算子填 CubeTile),其余 sub-tile 保持默认。

3. 实现侧:GetInputTileShape

framework/src/interface/operation/tile_shape_resolver.cpp

3.1 公共辅助

辅助 作用
ElementwiseInputVecTile(inShape, opVecTile) 逐轴 min(inShape, vecTile),超出 vecTile 维数的轴保持 full。elementwise 默认。
VecTileAxisFull(inShape, clampShape, opVecTile, fullAxis) 指定轴保持 full,其余轴 min(clampShape, vecTile)。用于 reduce/gather/scatter 的"轴 full"语义。
TransDataInputVecTile(inShape, opVecTile, group, groupAxis) groupAxis 按 inShape/group 切,其余 elementwise。用于 TransData 系列。
MakeTileShapeFromVec(vec) 把 vector<int64_t> 包成 TileShape(只设 VecTile)。

3.2 分支策略

按 opcode switch,默认分支为 ElementwiseInputVecTile(覆盖所有 elementwise 算子:Add/Div/Cast/Expand/Axpy/Where/OneHot/PReLU…)。特殊分支:

类别 opcode 输入 tile 规则
轴 full 类 OP_ROW*_SINGLE(Sum/Amax/Amin/Prod/ArgMax/ArgMin) reduce 轴 full,其余 min。axis 取 OP_ATTR_PREFIX+"AXIS"(缺失回退 0)。
OP_ROWEXPMAX / OP_ROWEXPSUM 2-D 专用,axis=1 full,axis0 min。
OP_BITSORT / OP_MRGSORT sort 轴(OP_ATTR_PREFIX+"axis")full,其余 min。
OP_ARGSORT sort 轴 full;axis 取裸键 "axis"(与 ArgSortOperationTileFunc 实际读取一致,非注册声明的带前缀键)。
OP_EXTRACT 末轴 full,其余 min。
OP_SORT_UB sort 轴 full。
OP_INDEX_ADD / OP_INDEX_ADD_UB self(index 0)轴 full;src(index 1)elementwise;indices full。
gather/scatter 类 OP_GATHER params:axis full,其余按输出轴映射 min;indices:按 axis+j 映射 min。
OP_GATHER_ELEMENT params 轴 full;indices elementwise。
OP_SCATTER / OP_SCATTER_ELEMENT self 与 idx 都按 idx.shape 在 axis full、其余 min。
OP_INDEX_OUTCAST [src, index, dst]:src/dst 轴 full、非轴 min;index(2-D)axis full,字面 axis 0 仅当 axis!=0 时按 vecTile[0] 切,其余非轴 full(对齐 TiledScatterUpdate)。axis 取裸键 "axis"。
OP_INDEX_PUT self 前导轴 full、尾部按 values 轴 min;values elementwise;其余输入按 {min(in[0], vecTile[0])}。
topk OP_TOPK 非轴 elementwise;axis 按 32 对齐 chunk(复刻 TopkOperationTileFunc 的 align 逻辑:maxNumValue=8192、kBlockSize=32 阈值)。
where OP_WHERE_TT/TS/ST/SS cond(index 0)若为 DT_UINT8 末轴按 vecTile/8 切(mask 位宽);其余 elementwise。
transdata OP_NCHW2NC1HWC0 等 6 个 TransDataInputVecTile,groupAxis 按输入 layout 定(NCHW 系列为 1,NCDHW 系列为 2)。
pack OP_PACK 输出 1-D,输入 tile = {min(in[0], ∏vecTile)}。
prelu OP_PRELU input elementwise;weight 取 {min(weight[0], vecTile[1])}(channel 轴)。
cube matmul OP_A_MUL_B / A_MUL_BT / A_MULACC_B / A_MULACC_BT A={m[0],k[0]}(transA 反转),B={k[0],n[0]}(transB 反转);MX/bias/scale 等附加输入按 Matrix::CopyInMode::DN2NZ 等属性决定 scale 的 NZ 排布与 ceil(k/64)。属性键统一用 Matrix:: 限定。
其它 OP_RANGE / OP_UNIFORM / OP_VEC_DUP / OP_CUBE_CONV_D2S / OP_CUBE_CONCAT_C 无 tensor 输入或非 vec 切,直接返回 op 级 TileShape。

属性键一致性:解析器严格对齐各 TileFunc 实际读取的键。OP_INDEX_OUTCAST/OP_ARGSORT 用裸 "axis"(与 TileFunc 一致),OP_BITSORT/OP_MRGSORT/OP_GATHER/... 用 OP_ATTR_PREFIX+"axis",reduce 单算子用 OP_ATTR_PREFIX+"AXIS"。

4. 实现侧:GetOutputTileShape

与输入侧对称,按 opcode switch,默认分支为 ElementwiseInputVecTile(outShape, opVecTile)(逐轴 min(outShape, vecTile))。默认分支正确的前提:① op 级 VecTile 维数 == 输出维数;② 输出按 VecTile 逐轴 elementwise 切("必须 full 的轴"在合法展开下 vecTile[fullAxis] >= shape[fullAxis],min 自然得 full,故 scatter/sort/indexadd/inplace 等无需专门分支)。

需要专门分支的输出:

opcode 输出 tile 规则
OP_A_MUL_B / A_MUL_BT / A_MULACC_B / A_MULACC_BT 输出 C 按 CubeTile 的 L0 {m[0], n[0]} 切,clamp 到真实 {M, N}(参考 SetVecTileBasedOnUbSize)。
TransData 6 个 输出是变换后 layout(C0/N0/group),输出维数 ≠ 输入维数,op 级 VecTile 维数跟输入走,逐轴 min 对不上。Handle*Format 把整张 dstTensor 作为 tile op 的 oOperand(非切片 View),即每个 tile op 写整份输出,故 first-cut 输出 tile = 完整 outShape。
OP_PACK 输出 1-D 字节流:outShape[0] = inShape[0]*byte。PackOperationTileFunc 产 outputShape{ min(inShape[0], tile)*byte }(tile = ∏vecTile),故 first-cut 输出 tile = {min(outShape[0], tile*byte)},byte = BytesOf(input[0])。
OP_PERMUTE / OP_PERMUTE_ELEMENT 输出轴 i ← 输入轴 perm[i],op 级 VecTile 跟输入轴序,故输出 tile = VecTile 按 perm 重排后逐轴 clamp 到 outShape(TiledPermuteOperation:resultTileShape = PermuteTileVector(inputTile.shape, perm))。
OP_TRANSPOSE_MOVEOUT / MOVEIN / VNCHWCONV 二轴转置:输出 tile = op 级 VecTile 的 shape[0]/shape[1] 两轴互换后 clamp 到 outShape(TiledInnerTranspose:resultTileShape = inputTile.shape 交换 shape[0]/shape[1])。
OP_UNPACK 输出 1-D:outShape[0] = inShape[0]/dstByte。UnPackOperationTileFunc 产 outputShape{ min(inShape[0], vecTile[0]) / dstByte },dstByte = BytesOf(output)。
OP_DEINTERLEAVE_SINGLE 末轴减半:outShape[last] = inShape[last]/2,末轴 tile = min(outShape[last], vecTile[last]/2),其余 min(两输出同形)。
OP_EXTRACT 末轴不切(full),其余 min(TiledExtract 跳过末轴)——与输入侧一致。
OP_BITSORT / OP_MRGSORT sort 轴(OP_ATTR_PREFIX+"axis")不切(full),其余 min(TiledBitSort/TiledMrgSort 跳过 sort 轴)——与输入侧一致。
OP_GATHER_MASK_BUILDIN 末轴按 patternMode 缩:mode 1/2 → vecTile/2,mode 3-6 → vecTile/4,其余 vecTile;其它轴 min。
OP_CUBE_CONV_D2S / OP_CUBE_CONCAT_C OpCalcType::CONV 且无注册 TileFunc,不被 ExpandFunction 展开,tiling 由 ConvTile 驱动——不在本解析器职责内,返回 op 级 TileShape 作安全占位(tensor-graph 路径不会调到)。

走默认分支的代表性类目(已逐一核对 TileFunc 源码):

  • elementwise:Add/Div/Cast/Expand/Axpy/Where/OneHot/PReLU …
  • reduction:tensor-graph reduce 算子恒把 reduce 轴置为 dim 1(ProcessResultShape 把 keepDim=false 的 squeeze 放到独立的 OP_RESHAPE 里做,而 OP_RESHAPE 不是 tensor op),故 min(1, vecTile[axis]) = 1,默认分支正确——keepDim=false 不是缺口。
  • gather/scatter/topk:op 级 VecTile 维数已与输出维数对齐,默认 min 即可。
  • cumsum/cumprod/interleave/pad/fillpad/quantize/dequantize/expand_exp_dif:输出按 min(outShape, vecTile) 逐轴切,默认即可。
  • 生成型 1-D 算子 OP_RANGE / OP_UNIFORM / OP_VEC_DUP:TiledRange/TiledUniformBuildIn/TiledFull 各自按 vecTile[0] 切 1-D 输出,正是 min(outShape[0], vecTile[0])——归入默认分支(原先误放到"返回 op 级"分支,已修正)。

5. 测试方案

framework/tests/ut/interface/src/operation/test_tile_shape_resolver.cpp

核心思想:用 DSL 在 FUNCTION{} 里建单算子 tensor graph,让算子吃 TileShape::Current();展开前用 resolver 算"期望"的 per-input/per-output tile,展开后扫 tile op 找首个消费/产出对应 RawTensor 的 View 取"实际"first-cut tile,逐 operand 比对。

harness 关键点:

  1. 输出 Tensor 提到 FUNCTION{} 外持有——其底层 LogicalTensor 因此存活,可被 harness 捕获身份。
  2. oOperand 补挂:本 harness 语境下 tensor-graph 算子的 oOperand 在展开前还是空的(输出要等展开流水线里才挂上)。harness 在 op->GetOOperands() 为空时把 fixture 提供的输出 LogicalTensor 挂上去——这正是 ExpandFunction/TileFunc 实际消费的输出;inplace 算子(oOperand 已非空 {self})则不动。
  3. 展开失败显式断言:ASSERT_NE(expandFunction.RunOnFunction(*fn), Status::FAILED),避免展开失败被后续扫描误判为 tile 形状不匹配。
  4. RawTensor 身份匹配:LogicalTensor::View 共享底层 RawTensor,故输入/输出身份用 GetRawTensor().get() 唯一标识。

覆盖 26 个 representative fixture:elementwise(Div/Where/OneHot/Cast/Expand/Axpy)、permute(Permute_AxisSwap,判别性 fixture:默认分支会产 {2,4,8},正确分支产 {4,2,8})、gather/scatter(Gather/Scatter/GatherElements/ScatterElement)、index(IndexAdd/IndexAddUb)、reduce 单算子(Sum/Amax/Amin/Prod/ArgMax/ArgMin 6 个)、rowexp(RowExpMax/RowExpSum,手动构建)、sort(MrgSort/BitSort/Extract)、topk(TopK 双输出)、prelu。多输出用 std::tie,inplace 用 self 作输出,手动构建用外部 Tensor out。

likedislike
Pull Request has been successfully merged by CANN-robot.
(Thank you for 高前程's contribution.)
高前程高前程Collaborators
Jul 27 Created pull request, commit a48e21ec
atomgit-bot
atomgit-bot
Jul 27 Comments:

变更摘要

此 PR 新增了 InputTileShapeResolver 单例类,用于根据算子的 opcode、算子级 tile shape 和输入张量形状,解析每个输入操作数的实际 per-axis tile shape。核心入口方法 GetInputTileShape 通过一个覆盖大量 opcode 的 switch-case 分支,实现各算子特定的分 tile 规则(如 elementwise 默认按 min(inShape, vecTile) 裁剪、reduction 类保持归约轴完整、cube matmul 按 CubeTile 推导 A/B/scale 的 tile、Gather/Scatter 类保持 scatter 轴完整等),并回退到 elementwise 通用规则。同时新增了单测文件,通过对比 ExpandFunction 实际膨胀出的首层 tile 形状与 resolver 的预期值来验证正确性。

主要改动

  • 新增 InputTileShapeResolver 单例类:在 input_tile_shape_resolver.h 中定义了 InputTileShapeResolver,提供 GetInputTileShape(const Operation& op, int index) 方法,用于根据 opcode 和算子 tile 推导指定输入操作数的 tile shape。
  • 实现覆盖 30+ 种 opcode 的 tile 推导逻辑:在 input_tile_shape_resolver.cpp 中通过大段 switch-case 实现了 elementwise 默认规则、Gather/Scatter/IndexAdd 族的轴完整策略、Reduction 族的归约轴保持、TransData 族的 group 分片、OP_TOPK 的 32 对齐 chunk、OP_A_MUL_B 族的 cube matmul A/B/aScale/bScale/bias 分 tile、OP_WHERE 的 bit 模式处理等具体规则。
  • 新增单元测试验证 resolver 与 ExpandFunction 一致性:在 test_input_tile_shape_resolver.cpp 中通过 ExpectResolverMatchesExpansion 核心 harness,构建单算子函数、记录 resolver 预期 tile、执行 ExpandFunction 膨胀后捕获首层 tile 操作数的实际形状,逐输入比对并断言一致,覆盖 Elementwise、Gather/Scatter、Where、OneHot、TopK、PReLU、Cast、Expand、Axpy、Sort、Reduction、Extract、IndexAdd 等场景。
likedislike
Incorrect?
atomgit-bot
atomgit-bot
Jul 27 Comments:

代码审查

审查总结

各文件审查结果

文件 审查结论
framework/src/interface/operation/input_tile_shape_resolver.cpp 发现 3 个问题(2×P1,1×P2)
framework/src/interface/operation/input_tile_shape_resolver.h 无问题
framework/tests/ut/interface/src/operation/test_input_tile_shape_resolver.cpp 无问题

问题按优先级统计

  • P0: 0
  • P1: 2(属性键不匹配导致始终回退默认轴)
  • P2: 1(OP_INDEX_OUTCAST index==1 在 axis==0 时 tiling 逻辑缺失)
  • P3: 0

整体风险评估

中高风险。 两个 P1 问题均涉及属性键的不一致:OP_ARGSORT 和 OP_INDEX_OUTCAST 的 axis 属性查找键与各自实际存储/读取键不匹配,导致解析器在 axis≠0 的场景下始终回退到默认轴 0,产出的 per-input tile shape 与实际 tiling 行为不一致。P2 问题为 OP_INDEX_OUTCAST 中 index tensor 在 axis==0 时的 tiling 逻辑缺陷。由于目前测试用例未覆盖 OP_ARGSORT 和 OP_INDEX_OUTCAST 的非零轴场景,这些问题不会被现有测试捕获,建议在修复的同时补充对应测试。

类型 数量
🔴 阻塞 2
🟡 建议 2

⛔ 需要修改

likedislike
Incorrect?
CANN-robotCANN-robotCollaborators
Jul 27 Added label: cann-cla/yes
CANN-robot
CANN-robotCollaborators
Jul 27 Comments:

Thanks for your pull-request.
The full list of commands accepted by me can be found at here。
You can get sig-info at here


PR Approval Progress

✅ Congratulations! All modules have met the lgtm and approve requirements.

Module Approval Details

module lgtm status approve status
repo-cann/pypto ✅ zhangyuebing, DCGDDD (2/2) ✅ zhangyuebing (1/1)

💡 Tip:

  • Committer can comment /approve or /lgtm
  • Commenting /approve implies both code review (lgtm) and intent to merge (approve)

CLA Signature Pass

Immutable01, thanks for your pull request. All authors of the commits have signed the CLA. 👍

likedislike
78 messages are collapsed here。 See more
zhangyuebing
zhangyuebingCollaborators
Jul 28 Comments:

/approve

likedislike
CANN-robotCANN-robotCollaborators
Jul 28 Added label: approved
杨旭
杨旭Collaborators
Jul 28 Comments:

/lgtm

likedislike
CANN-robotCANN-robotCollaborators
Jul 28 Added label: lgtm
CANN-robotCANN-robotCollaborators
Jul 28 Merged pull request