Merged
Cdist算子性能优化 #5021
YanWenkaiAdd on Aug 25
Cdist算子性能优化 #5021
Merged
YanWenkaiAdd on Aug 25
Total: 9 files changed+2153-60
@@ -14,6 +14,7 @@
14 */14 */
15 15 
16#include <array>16#include <array>
17+#include <cmath>
17#include "log/log.h"18#include "log/log.h"
18#include "util/math_util.h"19#include "util/math_util.h"
19#include "op_host/tiling_base_util.h"20#include "op_host/tiling_base_util.h"
@@ -21,6 +22,51 @@
21#include "cdist_tiling_arch35.h"22#include "cdist_tiling_arch35.h"
22 23 
23namespace optiling {24namespace optiling {
25+// ============================================================
26+// M==1 broadcast 路由标定常量
27+// broadcast 赢亏由 (plane, min(P,R), 对齐, B) 四维决定
28+// ============================================================
29+// ① OneDim:plane==1(P=R=1)输出塌一维,broadcast 快 ~11 倍
30+constexpr int64_t kOneDimPlane = 1;
31+// ② UB-BRC:P 或 R 任一超 64 → 分块处理任意大 plane
32+constexpr int64_t kUbBrcMinSide = 64;
33+// ③ 中小 plane (P,R<=64):broadcast 净赢的平面起点
34+constexpr int64_t kBrcMidMinPlane = 256;
35+// ③ min(P,R) 下限:排除扁长劣化
36+constexpr int64_t kBrcMidMinSide = 9;
37+// ③ 非对齐 plane 拐点:plane%8!=0 时需 >=485
38+constexpr int64_t kBrcMidMinPlaneUnaligned = 485;
39+// ④ 过渡区补充 (plane 100~255 && 对齐8 && B>=1000)
40+constexpr int64_t kTransitionMinPlane = 100;
41+constexpr int64_t kTransitionMinBatch = 1000;
42+ 
43+// ============================================================
44+// M∈(2,256) HL(ReduceRepeat) 路由标定常量
45+// ============================================================
46+// 场景A: R<=10 时 HL 写放大无法摊薄;扩展 R∈[11,15] & M<=150
47+constexpr int64_t kHlSmallR = 10;
48+constexpr int64_t kHlSmallREx = 15;
49+constexpr int64_t kHlSmallRExMaxM = 150;
50+// 场景B: p==2.0 且 M<24 时 MAlign 利用率低。
51+constexpr int64_t kHlP2SmallMMaxM = 24;
52+// 场景C: M<24 且 M*R<1000(小 MR 区域 HL 劣化)。
53+constexpr int64_t kHlSmallMRMaxM = 24;
54+constexpr int64_t kHlSmallMRMaxMR = 1000;
55+// 场景D: 66<M<70 且 R>=300 且 p==2 且 B<=112(M=67~69 连续劣化带)。
56+constexpr int64_t kHlMidMLo = 66;
57+constexpr int64_t kHlMidMHi = 70;
58+constexpr int64_t kHlMidMMinR = 300;
59+constexpr int64_t kHlMidMMaxB = 112;
60+// 场景E: p==1 且 M∈[17,22](p=1 小 M 大面积劣化)。
61+constexpr int64_t kHlP1SmallMLo = 17;
62+constexpr int64_t kHlP1SmallMHi = 22;
63+// 场景F: 一般 p (p∉{1,2,inf}) 且 M<32 → HL 的 exp/log 链在 FTZ_FALSE 下失去对 SIMT 优势
64+constexpr int64_t kHlSmallMGenPMaxM = 32;
65+// 矢量启用主门槛:M>=32,或 M>=16 且 P*R<=262144。
66+constexpr int64_t kHlVectorMMin = 32;
67+constexpr int64_t kHlVectorMEx = 16;
68+constexpr int64_t kHlVectorMaxPR = 262144;
69+ 
24ge::graphStatus CdistTiling::CheckParams()70ge::graphStatus CdistTiling::CheckParams()
25{71{
26 OP_LOGD(tilingContext_->GetNodeName(), "Start CheckParams.");72 OP_LOGD(tilingContext_->GetNodeName(), "Start CheckParams.");
@@ -249,7 +295,33 @@ void CdistTiling::DoNormalUbTiling()
249 int64_t R0BlockAlign = Ops::Base::CeilAlign(R0 * dtypeSize_, BLOCK_BYTES) / dtypeSize_;295 int64_t R0BlockAlign = Ops::Base::CeilAlign(R0 * dtypeSize_, BLOCK_BYTES) / dtypeSize_;
250 296 
251 std::vector<DimConfig> configs;297 std::vector<DimConfig> configs;
252- if (dtypeSize_ == B4) {298+ if (use_reduce_hl_ == 1) {
299+ // 方案三 (round3): HL 内核不再有 cast queue —— x1/x2/y 队列直接按 sizeof(float) 分配(fp16 的
300+ // T-typed staging 复用同一 buffer 的上半部,无额外 UB)。队列字节数 BUFFER_NUM*N*sizeof(float)
301+ // 换算回 T 元素单位即 BUFFER_NUM*fp32Ratio*N。
302+ const int64_t fp32Ratio = static_cast<int64_t>(sizeof(float)) / dtypeSize_; // fp16:2, fp32:1
303+ configs = {{&tilingData_.ubLoopNumM, &tilingData_.ubFactorM, &tilingData_.ubTailFactorM, M_,
304+ [this, blockElements, fp32Ratio](int64_t i) {
305+ int64_t iBlockAlign = Ops::Base::CeilAlign(i * dtypeSize_, BLOCK_BYTES) / dtypeSize_;
306+ return BUFFER_NUM * fp32Ratio * (iBlockAlign + iBlockAlign + blockElements) + blockElements;
307+ }},
308+ {&tilingData_.ubLoopNumR, &tilingData_.ubFactorR, &tilingData_.ubTailFactorR, R0,
309+ [this, MBlockAlign, blockElements, fp32Ratio](int64_t i) {
310+ int64_t iBlockAlign = Ops::Base::CeilAlign(i * dtypeSize_, BLOCK_BYTES) / dtypeSize_;
311+ return BUFFER_NUM * fp32Ratio * (MBlockAlign + i * MBlockAlign + iBlockAlign) + blockElements;
312+ }},
313+ {&tilingData_.ubLoopNumP, &tilingData_.ubFactorP, &tilingData_.ubTailFactorP, P0,
314+ [this, MBlockAlign, R0BlockAlign, R0, blockElements, fp32Ratio](int64_t i) {
315+ return BUFFER_NUM * fp32Ratio * (i * MBlockAlign + R0 * MBlockAlign + i * R0BlockAlign) +
316+ blockElements;
317+ }},
318+ {&tilingData_.ubLoopNumB, &tilingData_.ubFactorB, &tilingData_.ubTailFactorB, B0,
319+ [this, MBlockAlign, R0BlockAlign, R0, P0, blockElements, fp32Ratio](int64_t i) {
320+ return BUFFER_NUM * fp32Ratio *
321+ (i * P0 * MBlockAlign + i * R0 * MBlockAlign + i * P0 * R0BlockAlign) +
322+ blockElements;
323+ }}};
324+ } else if (dtypeSize_ == B4) {
253 configs = {{&tilingData_.ubLoopNumM, &tilingData_.ubFactorM, &tilingData_.ubTailFactorM, M_,325 configs = {{&tilingData_.ubLoopNumM, &tilingData_.ubFactorM, &tilingData_.ubTailFactorM, M_,
254 [this, blockElements](int64_t i) {326 [this, blockElements](int64_t i) {
255 int64_t iBlockAlign = Ops::Base::CeilAlign(i * dtypeSize_, BLOCK_BYTES) / dtypeSize_;327 int64_t iBlockAlign = Ops::Base::CeilAlign(i * dtypeSize_, BLOCK_BYTES) / dtypeSize_;
@@ -340,7 +412,71 @@ void CdistTiling::DoNormalTiling()
340void CdistTiling::DoTiling()412void CdistTiling::DoTiling()
341{413{
342 OP_LOGD(tilingContext_->GetNodeName(), "Start DoTiling.");414 OP_LOGD(tilingContext_->GetNodeName(), "Start DoTiling.");
343- if (M_ <= M_SIZE) {415+ // 方案2: M==1 命中 Broadcast 快路径(OneDim ④ / 静态 rank UB-BRC ③ / multi-batch);其余走原 SIMT/Normal。
416+ if (M_ == 1) {
417+ // 路由谓词:
418+ // ① OneDim (plane==1):broadcast 快 ~11 倍
419+ // ② UB-BRC (P>64 或 R>64):分块处理任意大 plane
420+ // ③ 中小 plane (P,R<=64):plane>=256 且 min(P,R)>=9 后 broadcast 净赢;
421+ // 对齐 plane(plane%8==0) 直接放行;
422+ // 非对齐 plane 需 >=485;
423+ // min(P,R)>=9 排除扁长劣化;
424+ // plane<256 全输 <100:17%、100-255:26%,回退 SIMT。
425+ // ④ 过渡区补充 (plane 100~255 && 对齐8 && B>=1000)。
426+ int64_t plane = P_ * R_;
427+ int64_t minPr = (P_ < R_) ? P_ : R_;
428+ bool planeAligned8 = (plane % 8 == 0);
429+ bool brcWins = (plane == kOneDimPlane) || (P_ > kUbBrcMinSide || R_ > kUbBrcMinSide) ||
430+ (plane >= kBrcMidMinPlane && minPr >= kBrcMidMinSide &&
431+ (planeAligned8 || plane >= kBrcMidMinPlaneUnaligned)) ||
432+ (plane >= kTransitionMinPlane && planeAligned8 && B_ >= kTransitionMinBatch);
433+ if (brcWins) {
434+ use_broadcast_ = 1;
435+ is_small_m_ = 1; // fallback flag; not launched when use_broadcast_ set
436+ DoSimtTiling(); // compute SIMT tiling as safety fallback
437+ DoBrcTiling();
438+ } else {
439+ use_broadcast_ = 0;
440+ is_small_m_ = 1; // SIMT 标量路径 (KERNEL_MODE=1)
441+ DoSimtTiling();
442+ }
443+ return;
444+ }
445+ // 方案三 (round2 crossover): M∈[2,256] broadcast+高层 ReduceRepeat 归约内核(复用 Normal 的 block/UB 切分)
446+ // 而非 SIMT 标量路径 —— 仅在矢量胜出时。谓词按 msprof 实测标定:矢量 if M>=32 || (M>=16 && P*R<=262144),
447+ // 否则(小 M 或 M∈[16,32) 且 P*R 巨大)走 SIMT。
448+ // M==1 走 Broadcast 快路径(上面已 return),M>256 仍走 Normal(VF)(下面 else)。
449+ bool isInf = std::isinf(tilingData_.p);
450+ // 路由谓词优化:
451+ // 场景A: R<=10 时 HL broadcast 写放大无法摊薄, SIMT 标量更优;
452+ // 扩展 R∈[11,15] & M<=150
453+ // 场景B: p==2.0 且 M<24 时 MAlign 利用率低, SIMT 更优
454+ // 场景C: M<24 且 M*R<1000 —— 小 MR 区域 HL 劣化
455+ // 场景D: 66<M<70 且 R>=300 且 p==2 且 B<=112 —— M=67~69 连续劣化带
456+ // 场景E: p==1 且 M∈[17,22] —— p=1 小 M 大面积劣化
457+ bool smallRBad = (R_ <= kHlSmallR) || (R_ <= kHlSmallREx && M_ <= kHlSmallRExMaxM);
458+ bool p2SmallMBad = (tilingData_.p == 2.0f) && (M_ < kHlP2SmallMMaxM);
459+ bool smallMRBad = (M_ < kHlSmallMRMaxM) && (M_ * R_ < kHlSmallMRMaxMR);
460+ bool midMBad = (M_ > kHlMidMLo && M_ < kHlMidMHi) && (R_ >= kHlMidMMinR) && (tilingData_.p == 2.0f) &&
461+ (B_ <= kHlMidMMaxB);
462+ bool p1SmallMBad = (tilingData_.p == 1.0f) && (M_ >= kHlP1SmallMLo && M_ <= kHlP1SmallMHi);
463+ bool genpSmallMBad = (!isInf && tilingData_.p != 1.0f && tilingData_.p != 2.0f && M_ < kHlSmallMGenPMaxM);
464+ bool hlVectorWins = !isInf && !smallRBad && !p2SmallMBad && !smallMRBad && !midMBad && !p1SmallMBad &&
465+ !genpSmallMBad &&
466+ ((M_ >= kHlVectorMMin) || (M_ >= kHlVectorMEx && (P_ * R_) <= kHlVectorMaxPR));
467+ if (M_ >= 2 && M_ <= M_SIZE && hlVectorWins) {
468+ is_small_m_ = 0; // launch on the Normal-shaped tiling
469+ use_reduce_hl_ = 1; // but dispatch to the high-level reduce kernel (KERNEL_MODE=3)
470+ // Reserve UB for the two fixed HL fp32 compute planes (x1exp + diff, 4096 elems each = 32KB) plus
471+ // the fp32 M-split accumulator margin, so the extra planes never overflow UB on large P·R tiles.
472+ int64_t savedUb = ubSize_;
473+ ubSize_ = ubSize_ - HL_UB_RESERVE;
474+ if (ubSize_ < BLOCK_BYTES)
475+ ubSize_ = BLOCK_BYTES;
476+ DoNormalTiling();
477+ ubSize_ = savedUb;
478+ CapUbFactorRForHL();
479+ } else if (M_ <= M_SIZE) {
344 is_small_m_ = 1;480 is_small_m_ = 1;
345 DoSimtTiling();481 DoSimtTiling();
346 } else {482 } else {
@@ -349,6 +485,240 @@ void CdistTiling::DoTiling()
349 }485 }
350}486}
351 487 
488+// 方案三 (round2): cap ubFactorR so the HL kernel processes each R UB-tile in ONE broadcast/reduce pass
489+// (no internal R-chunk). 逐行照抄直调 cdist_host_tiling.cpp CapUbFactorRForHL 363-385 行,只把裸接口换成
490+// register 侧同名成员(dtypeSize_ / tilingData_ 字段名与 Normal 一致)。
491+void CdistTiling::CapUbFactorRForHL()
492+{
493+ // MAlign used by the HL kernel for the broadcast/reduce plane: for ubLoopNumM==1 it's M_, else ubFactorM.
494+ int64_t mForAlign = (tilingData_.ubLoopNumM == 1) ? M_ : tilingData_.ubFactorM;
495+ int64_t mAlign = Ops::Base::CeilAlign(mForAlign * dtypeSize_, BLOCK_BYTES) / dtypeSize_;
496+ if (mAlign < 1)
497+ mAlign = 1;
498+ int64_t maxUbR = HL_PLANE_ELEMS / mAlign;
499+ // Align the cap down to a 32B row multiple so DataCopyPad / reduce strides stay block-aligned.
500+ int64_t alignEle = BLOCK_BYTES / dtypeSize_;
501+ maxUbR = (maxUbR / alignEle) * alignEle;
502+ if (maxUbR < alignEle)
503+ maxUbR = alignEle; // at least one aligned row-group
504+ 
505+ int64_t curUbR = tilingData_.ubFactorR;
506+ if (curUbR <= maxUbR) {
507+ return; // already fits in one pass
508+ }
509+ // Shrink ubFactorR to maxUbR and recompute the R UB-loop over the per-core R factor (blockMainFactorR).
510+ int64_t r0 = tilingData_.blockMainFactorR;
511+ tilingData_.ubFactorR = maxUbR;
512+ tilingData_.ubLoopNumR = Ops::Base::CeilDiv(r0, maxUbR);
513+ tilingData_.ubTailFactorR = r0 % maxUbR; // 0 => last chunk is a full ubFactorR (kernel derives via subtraction)
514+}
515+ 
516+// 方案2: 填充 Broadcast fast path tiling(逐行照抄直调 operators/cdist/final_optimized/cdist_host_tiling.cpp
517+// 的 DoBrcTiling,选型/守卫/切分/strides 数学一字不改,只把 SimpleShape 裸接口换成 register 接口 dtypeSize_/
518+// ubSize_/coreNum_/tilingData_.p)。合 batch 后 out=(B,P,R), x1=(B,P), x2=(B,R), M==1。
519+void CdistTiling::DoBrcTiling()
520+{
521+ CdistBrcTilingData& t = brcTilingData_;
522+ t.B = B_;
523+ t.P = P_;
524+ t.R = R_;
525+ t.p = tilingData_.p;
526+ 
527+ const int64_t alignEle = BLOCK_BYTES / dtypeSize_; // elements per 32B block (dtype T)
528+ 
529+ if (P_ == 1 && R_ == 1) {
530+ // ---- OneDim (④): output collapses to 1D length B ----
531+ t.brcBranch = 0;
532+ int64_t dimLen = B_;
533+ // aliveBuf: x1(DB)+x2(DB)+out(DB) T-planes + fp32 scratch(x1f,x2f,yfp). Conservative => 6.
534+ const int64_t aliveBuf = 6;
535+ int64_t tileNum = (ubSize_ / (aliveBuf * dtypeSize_ * BUFFER_NUM));
536+ tileNum = (tileNum / alignEle) * alignEle;
537+ if (tileNum < alignEle)
538+ tileNum = alignEle;
539+ int64_t ubOuter = Ops::Base::CeilDiv(dimLen, tileNum);
540+ int64_t cn = coreNum_;
541+ if (ubOuter < cn)
542+ cn = (ubOuter < 1) ? 1 : ubOuter;
543+ t.dimLen = dimLen;
544+ t.tileNum = static_cast<int32_t>(tileNum);
545+ t.blockNum = static_cast<int32_t>(cn);
546+ return;
547+ }
548+ 
549+ // ---- UB-BRC (③) static rank=2 : tile = (rowsP, R) plane per batch ----
550+ t.brcBranch = 1;
551+ // UB 必须容纳所有 InitBuffer 分配:
552+ // qLoad1_(2*src1Ele*T) + qLoad2_(2*src2Ele*T) + bufSrc1_(src1Ele*4) + bufSrc2_(src2Ele*4)
553+ // + bufX1Exp_(elemNum*4) + bufX2Exp_(elemNum*4) + qY_(2*elemNum*T)
554+ // 其中 src1Ele=AlignUp(ubFormerP,alignT), src2Ele=AlignUp(rSeg,alignT),ubFormerP/rSeg 依赖 elemNum。
555+ // 用迭代收敛求 elemNum。
556+ const int64_t fp32Bytes = 4;
557+ int64_t alignFp = BLOCK_BYTES / fp32Bytes; // 8
558+ int64_t alignT = BLOCK_BYTES / dtypeSize_;
559+ // 大 buffer 的 fp32-plane 等效数:x1exp(1) + x2exp(1) + qY DB(2*dtypeSize/4)
560+ int64_t aliveBig = 2 + 2 * dtypeSize_ / fp32Bytes;
561+ // GetRuntimeUBSize() = get_shmem_sz() - 8KB,InitBuffer 可用 UB 须扣除系统保留区。
562+ constexpr int64_t UB_RESERVED_FOR_SYSTEM = 8 * 1024;
563+ int64_t usableUb = ubSize_ - UB_RESERVED_FOR_SYSTEM;
564+ if (usableUb < alignFp * aliveBig * fp32Bytes)
565+ usableUb = alignFp * aliveBig * fp32Bytes;
566+ int64_t elemNum = usableUb / (aliveBig * fp32Bytes);
567+ elemNum = (elemNum / alignFp) * alignFp;
568+ if (elemNum < alignFp)
569+ elemNum = alignFp;
570+ for (int iter = 0; iter < 8; ++iter) {
571+ int64_t rSegTmp, rowsPTmp;
572+ if (R_ <= elemNum) {
573+ rSegTmp = R_;
574+ rowsPTmp = elemNum / R_;
575+ } else {
576+ rowsPTmp = 1;
577+ rSegTmp = (elemNum / alignFp) * alignFp;
578+ }
579+ if (rowsPTmp < 1)
580+ rowsPTmp = 1;
581+ int64_t s1 = ((rowsPTmp + alignT - 1) / alignT) * alignT;
582+ int64_t s2 = ((rSegTmp + alignT - 1) / alignT) * alignT;
583+ int64_t bigBytes = aliveBig * elemNum * fp32Bytes;
584+ int64_t srcBytes = (2 * dtypeSize_ + fp32Bytes) * (s1 + s2);
585+ if (bigBytes + srcBytes <= usableUb)
586+ break;
587+ int64_t availForBig = usableUb - srcBytes;
588+ if (availForBig < alignFp * aliveBig * fp32Bytes) {
589+ elemNum = alignFp;
590+ break;
591+ }
592+ int64_t newElem = (availForBig / (aliveBig * fp32Bytes) / alignFp) * alignFp;
593+ if (newElem < alignFp)
594+ newElem = alignFp;
595+ if (newElem >= elemNum)
596+ break;
597+ elemNum = newElem;
598+ }
599+ 
600+ // 缺陷② 修复:小 tile 场景(whole (P,R) plane 装得下 UB,且 P*R 小到可打包 >=2 个 batch)走
601+ // multi-batch(brcBranch==2),把每 tile 只处理 1 batch 的 256 元素小 tile 打包成每 tile 多 batch,
602+ // 消除 30896 次 per-tile 固定开销。门槛与 issue 小 tile 思路一致(P,R 都很小时才打包)。
603+ {
604+ int64_t plane = P_ * R_; // 单 batch 输出元素数
605+ const int64_t alignFp32 = BLOCK_BYTES / 4; // fp32 32B = 8 元素
606+ // 打包需求:整块 (P,R) 装得下 UB(R<=elemNum 且 P*R<=elemNum),且能装 >=2 个 batch;
607+ // 且 plane 必须 32B(fp32 8 元素)对齐——否则逐 batch Broadcast 的 dst 局部偏移 j*plane 未对齐,
608+ // Broadcast 在小 plane+大 batchPerTile 下会 aicore 异常(507035)。非对齐 plane 回落 brcBranch==1
609+ // (原正确 UB-BRC 路径)。181 plane=256 对齐 → 走快路径。
610+ // B 极小(<128)时回退 UB-BRC:multi-batch 每 tile 打包 batchPerTile=min(elemNum/plane,B) 个 batch,
611+ // B 小意味着 plane 大(plane>=485 才进 broadcast),UB 被少数大 plane 撑满,Broadcast 高阶 API 内部
612+ // 栈(PopStackBuffer)申请越界 → 507035/VEC_ERROR(实测 plane=648 B=50、plane=1936 B=32 触发);
613+ // 且 B 小时 multi-batch 摊薄/并行收益消失(实测与 SIMT 持平),回退 UB-BRC 更安全。
614+ if (plane > 0 && (plane % alignFp32 == 0) && R_ <= elemNum && plane * 2 <= elemNum && P_ <= 64 && R_ <= 64 &&
615+ B_ >= 128) {
616+ int64_t batchPerTile = elemNum / plane; // 每 tile 打包的 batch 数
617+ if (batchPerTile > B_)
618+ batchPerTile = B_;
619+ // UB 检查:brcBranch==2 的 src buffer 随 batchPerTile 增长,需验证不超 UB
620+ for (int gIter = 0; gIter < 8 && batchPerTile >= 2; ++gIter) {
621+ int64_t g = batchPerTile;
622+ int64_t s1 = ((g * P_ + alignT - 1) / alignT) * alignT;
623+ int64_t s2 = ((g * R_ + alignT - 1) / alignT) * alignT;
624+ int64_t bigBytes2 = aliveBig * elemNum * fp32Bytes;
625+ int64_t srcBytes2 = (2 * dtypeSize_ + fp32Bytes) * (s1 + s2);
626+ if (bigBytes2 + srcBytes2 <= usableUb)
627+ break;
628+ int64_t overshoot = bigBytes2 + srcBytes2 - usableUb;
629+ int64_t shrinkG = (overshoot / ((2 * dtypeSize_ + fp32Bytes) * (P_ + R_))) + 1;
630+ batchPerTile -= shrinkG;
631+ }
632+ if (batchPerTile >= 2) {
633+ t.brcBranch = 2;
634+ t.B = B_;
635+ t.P = P_;
636+ t.R = R_;
637+ t.elemNum = elemNum;
638+ t.batchPerTile = batchPerTile;
639+ int64_t totalTiles2 = Ops::Base::CeilDiv(B_, batchPerTile);
640+ int64_t cn2 = coreNum_ < 1 ? 1 : coreNum_;
641+ int64_t blockFormer2 = Ops::Base::CeilDiv(totalTiles2, cn2);
642+ if (blockFormer2 < 1)
643+ blockFormer2 = 1;
644+ int64_t coreNumT2 = Ops::Base::CeilDiv(totalTiles2, blockFormer2);
645+ int64_t blockTail2 = totalTiles2 - (coreNumT2 - 1) * blockFormer2;
646+ t.totalTiles = totalTiles2;
647+ t.blockFormerT = blockFormer2;
648+ t.coreNumT = coreNumT2;
649+ t.blockTailT = blockTail2;
650+ return;
651+ }
652+ }
653+ }
654+ 
655+ int64_t rSeg, rOuter, rTail;
656+ int64_t ubFormerP, ubOuterP, ubTailP;
657+ if (R_ <= elemNum) {
658+ rSeg = R_;
659+ rOuter = 1;
660+ rTail = R_;
661+ int64_t rowsP = elemNum / R_;
662+ if (rowsP < 1)
663+ rowsP = 1;
664+ if (rowsP > P_)
665+ rowsP = P_;
666+ ubFormerP = rowsP;
667+ ubOuterP = Ops::Base::CeilDiv(P_, rowsP);
668+ ubTailP = P_ - (ubOuterP - 1) * rowsP;
669+ } else {
670+ ubFormerP = 1;
671+ ubOuterP = P_;
672+ ubTailP = 1;
673+ rSeg = (elemNum / alignFp) * alignFp;
674+ if (rSeg < alignFp)
675+ rSeg = alignFp;
676+ rOuter = Ops::Base::CeilDiv(R_, rSeg);
677+ rTail = R_ - (rOuter - 1) * rSeg;
678+ }
679+ t.elemNum = elemNum;
680+ t.ubFormerP = ubFormerP;
681+ t.ubOuterP = ubOuterP;
682+ t.ubTailP = ubTailP;
683+ t.rSeg = rSeg;
684+ t.rOuter = rOuter;
685+ t.rTail = rTail;
686+ 
687+ int64_t totalTiles = B_ * ubOuterP * rOuter;
688+ int64_t cn = coreNum_ < 1 ? 1 : coreNum_;
689+ int64_t blockFormer = Ops::Base::CeilDiv(totalTiles, cn);
690+ if (blockFormer < 1)
691+ blockFormer = 1;
692+ int64_t coreNumT = Ops::Base::CeilDiv(totalTiles, blockFormer);
693+ int64_t blockTail = totalTiles - (coreNumT - 1) * blockFormer;
694+ t.totalTiles = totalTiles;
695+ t.blockFormerT = blockFormer;
696+ t.coreNumT = coreNumT;
697+ t.blockTailT = blockTail;
698+}
699+ 
700+int64_t CdistTiling::GetBrcBlockDim() const
701+{
702+ if (brcTilingData_.brcBranch == 0) {
703+ return brcTilingData_.blockNum < 1 ? 1 : brcTilingData_.blockNum;
704+ }
705+ // brcBranch 1 & 2 both use coreNumT.
706+ return brcTilingData_.coreNumT < 1 ? 1 : brcTilingData_.coreNumT;
707+}
708+ 
709+void CdistTiling::PrintBrcTilingData() const
710+{
711+ const CdistBrcTilingData& t = brcTilingData_;
712+ std::stringstream ss;
713+ ss << " brcBranch: " << t.brcBranch << " B: " << t.B << " P: " << t.P << " R: " << t.R << " p: " << t.p
714+ << " dimLen: " << t.dimLen << " tileNum: " << t.tileNum << " blockNum: " << t.blockNum
715+ << " elemNum: " << t.elemNum << " ubFormerP: " << t.ubFormerP << " ubOuterP: " << t.ubOuterP
716+ << " ubTailP: " << t.ubTailP << " rSeg: " << t.rSeg << " rOuter: " << t.rOuter << " rTail: " << t.rTail
717+ << " batchPerTile: " << t.batchPerTile << " totalTiles: " << t.totalTiles << " blockFormerT: " << t.blockFormerT
718+ << " coreNumT: " << t.coreNumT << " blockTailT: " << t.blockTailT;
719+ OP_LOGI(tilingContext_->GetNodeName(), "CdistBrcTilingData: %s", ss.str().c_str());
720+}
721+ 
352ge::graphStatus CdistTiling::RunCdistTiling()722ge::graphStatus CdistTiling::RunCdistTiling()
353{723{
354 OP_LOGD(tilingContext_->GetNodeName(), "Start RunCdistTiling.");724 OP_LOGD(tilingContext_->GetNodeName(), "Start RunCdistTiling.");
@@ -361,7 +731,11 @@ ge::graphStatus CdistTiling::RunCdistTiling()
361 OP_CHECK_IF(SetTilingData() != ge::GRAPH_SUCCESS,731 OP_CHECK_IF(SetTilingData() != ge::GRAPH_SUCCESS,
362 OP_LOGE(tilingContext_->GetNodeName(), "RunCdistTiling failed to set tiling data!"),732 OP_LOGE(tilingContext_->GetNodeName(), "RunCdistTiling failed to set tiling data!"),
363 return ge::GRAPH_FAILED);733 return ge::GRAPH_FAILED);
364- PrintTilingData();734+ if (use_broadcast_) {
735+ PrintBrcTilingData();
736+ } else {
737+ PrintTilingData();
738+ }
365 return ge::GRAPH_SUCCESS;739 return ge::GRAPH_SUCCESS;
366}740}
367 741 
@@ -369,11 +743,22 @@ ge::graphStatus CdistTiling::Init()
369{743{
370 OP_LOGD(tilingContext_->GetNodeName(), "Start init CdistTiling.");744 OP_LOGD(tilingContext_->GetNodeName(), "Start init CdistTiling.");
371 auto compileInfo = reinterpret_cast<const CdistCompileInfo*>(tilingContext_->GetCompileInfo());745 auto compileInfo = reinterpret_cast<const CdistCompileInfo*>(tilingContext_->GetCompileInfo());
372- OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, compileInfo);746+ if (compileInfo != nullptr) {
373- coreNum_ = compileInfo->coreNum;747+ coreNum_ = compileInfo->coreNum;
748+ ubSize_ = compileInfo->ubSize;
749+ } else {
750+ // Fallback: nnopbase single-op path may not invoke TilingParse (compile info null). Read the
751+ // platform directly from the tiling context (same source TilingParse would use).
752+ auto platformInfo = tilingContext_->GetPlatformInfo();
753+ OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, platformInfo);
754+ auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo);
755+ coreNum_ = static_cast<int64_t>(ascendcPlatform.GetCoreNumAiv());
756+ uint64_t ubSize = 0;
757+ ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize);
758+ ubSize_ = static_cast<int64_t>(ubSize);
759+ }
374 OP_CHECK_IF((coreNum_ <= 0), OP_LOGE(tilingContext_->GetNodeName(), "Failed to get core num."),760 OP_CHECK_IF((coreNum_ <= 0), OP_LOGE(tilingContext_->GetNodeName(), "Failed to get core num."),
375 return ge::GRAPH_FAILED);761 return ge::GRAPH_FAILED);
376- ubSize_ = compileInfo->ubSize;
377 OP_CHECK_IF((ubSize_ <= 0), OP_LOGE(tilingContext_->GetNodeName(), "Failed to get ub size."),762 OP_CHECK_IF((ubSize_ <= 0), OP_LOGE(tilingContext_->GetNodeName(), "Failed to get ub size."),
378 return ge::GRAPH_FAILED);763 return ge::GRAPH_FAILED);
379 OP_LOGD(tilingContext_->GetNodeName(), "Init CdistTiling success.");764 OP_LOGD(tilingContext_->GetNodeName(), "Init CdistTiling success.");
@@ -383,15 +768,33 @@ ge::graphStatus CdistTiling::Init()
383ge::graphStatus CdistTiling::SetTilingData()768ge::graphStatus CdistTiling::SetTilingData()
384{769{
385 OP_LOGD(tilingContext_->GetNodeName(), "Start SetTilingData.");770 OP_LOGD(tilingContext_->GetNodeName(), "Start SetTilingData.");
386- tilingData_.B = B_;
387- tilingData_.P = P_;
388- tilingData_.R = R_;
389- tilingData_.M = M_;
390 auto ptrTilingData = tilingContext_->GetRawTilingData();771 auto ptrTilingData = tilingContext_->GetRawTilingData();
391 OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, ptrTilingData);772 OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, ptrTilingData);
392 auto capSize = ptrTilingData->GetCapacity();773 auto capSize = ptrTilingData->GetCapacity();
393 void* ptrData = ptrTilingData->GetData();774 void* ptrData = ptrTilingData->GetData();
394 OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, ptrData);775 OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, ptrData);
776+ size_t* workspaces = tilingContext_->GetWorkspaceSizes(1);
777+ OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, workspaces);
778+ workspaces[0] = WORK_SPACE_SIZE;
779+ 
780+ // 方案2: M==1 命中 Broadcast 快路径 → 写 CdistBrcTilingData + SetTilingKey(KERNEL_MODE=2)。
781+ if (use_broadcast_) {
782+ void* ptrBrc = static_cast<void*>(&brcTilingData_);
783+ OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, ptrBrc);
784+ OP_CHECK_IF(memcpy_s(ptrData, capSize, ptrBrc, sizeof(brcTilingData_)) != 0,
785+ OP_LOGE(tilingContext_->GetNodeName(), "Set brc tiling data failed!"), return ge::GRAPH_FAILED);
786+ ptrTilingData->SetDataSize(sizeof(brcTilingData_));
787+ tilingContext_->SetBlockDim(GetBrcBlockDim());
788+ const uint64_t tilingKey = GET_TPL_TILING_KEY(static_cast<uint64_t>(2)); // KERNEL_MODE == 2
789+ tilingContext_->SetTilingKey(tilingKey);
790+ return ge::GRAPH_SUCCESS;
791+ }
792+ 
793+ // 原路径(M>1):Normal(is_small_m_==0 -> KERNEL_MODE 0) / SIMT(is_small_m_==1 -> KERNEL_MODE 1)。
794+ tilingData_.B = B_;
795+ tilingData_.P = P_;
796+ tilingData_.R = R_;
797+ tilingData_.M = M_;
395 void* ptrStruct = static_cast<void*>(&tilingData_);798 void* ptrStruct = static_cast<void*>(&tilingData_);
396 OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, ptrStruct);799 OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, ptrStruct);
397 OP_CHECK_IF(memcpy_s(ptrData, capSize, ptrStruct, sizeof(tilingData_)) != 0,800 OP_CHECK_IF(memcpy_s(ptrData, capSize, ptrStruct, sizeof(tilingData_)) != 0,
@@ -399,11 +802,12 @@ ge::graphStatus CdistTiling::SetTilingData()
399 ptrTilingData->SetDataSize(sizeof(tilingData_));802 ptrTilingData->SetDataSize(sizeof(tilingData_));
400 803 
401 tilingContext_->SetBlockDim(tilingData_.realCoreNum);804 tilingContext_->SetBlockDim(tilingData_.realCoreNum);
402- const uint64_t tilingKey = GET_TPL_TILING_KEY(static_cast<uint64_t>(is_small_m_));805+ // 方案三 (round2): use_reduce_hl_ 命中 → 数据仍是 Normal 主结构 CdistTilingData(DoNormalTiling 已填好),
806+ // block dim 用 Normal 的 realCoreNum(同 mode0),仅 tilingKey 派发到 KERNEL_MODE=3 的高层 reduce 内核。
807+ // 与 use_broadcast_ 互斥(M==1 前者 return / M∈[2,256]矢量胜 use_reduce_hl_ / 其余 is_small_m_ 0|1)。
808+ const uint64_t tilingKey = use_reduce_hl_ ? GET_TPL_TILING_KEY(static_cast<uint64_t>(3)) :
809+ GET_TPL_TILING_KEY(static_cast<uint64_t>(is_small_m_));
403 tilingContext_->SetTilingKey(tilingKey);810 tilingContext_->SetTilingKey(tilingKey);
404- size_t* workspaces = tilingContext_->GetWorkspaceSizes(1);
405- OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, workspaces);
406- workspaces[0] = WORK_SPACE_SIZE;
407 return ge::GRAPH_SUCCESS;811 return ge::GRAPH_SUCCESS;
408}812}
409 813 
@@ -16,6 +16,7 @@
16#include "op_host/tiling_base_util.h"16#include "op_host/tiling_base_util.h"
17#include "op_host/math_tiling_templates_registry.h"17#include "op_host/math_tiling_templates_registry.h"
18#include "../../op_kernel/cdist_tiling_data.h"18#include "../../op_kernel/cdist_tiling_data.h"
19+#include "../../op_kernel/cdist_brc_tilingdata.h" // 方案2: POD CdistBrcTilingData
19#include "../../op_kernel/cdist_tiling_key.h"20#include "../../op_kernel/cdist_tiling_key.h"
20 21 
21namespace optiling {22namespace optiling {
@@ -24,13 +25,20 @@ constexpr int64_t MIN_DIM_LEN = 2;
24constexpr int64_t M_SIZE = 256;25constexpr int64_t M_SIZE = 256;
25constexpr int64_t BUFFER_NUM = 2;26constexpr int64_t BUFFER_NUM = 2;
26constexpr int64_t BLOCK_BYTES = 32;27constexpr int64_t BLOCK_BYTES = 32;
28+// 方案三 (round2): UB bytes reserved (subtracted from ubSize before the Normal UB-split solves) to hold
29+// the two fixed HL fp32 compute planes (2 * 8192 * 4 = 64KB) + partBuf scratch (1KB) + fp32 M-split
30+// accumulator margin (~16KB).
31+constexpr int64_t HL_UB_RESERVE = 96 * 1024;
32+// 方案三 (round2): fp32 element capacity of each HL compute plane (x1exp / diff), matching kernel HL_PLANE_ELEMS.
33+// Capping ubFactorR so (ubFactorR * MAlign) <= HL_PLANE_ELEMS guarantees the kernel never R-chunks internally.
34+constexpr int64_t HL_PLANE_ELEMS = 8192;
27constexpr int64_t B4 = 4;35constexpr int64_t B4 = 4;
28constexpr int64_t CAST_BUFFER_RATIO = 2;36constexpr int64_t CAST_BUFFER_RATIO = 2;
29constexpr int64_t SIMT_MIN_BYTE = 128;37constexpr int64_t SIMT_MIN_BYTE = 128;
30 38 
31struct CdistCompileInfo {39struct CdistCompileInfo {
32- int64_t coreNum;40+ int64_t coreNum;
33- int64_t ubSize;41+ int64_t ubSize;
34};42};
35 43 
36struct DimConfig {44struct DimConfig {
@@ -59,9 +67,20 @@ public:
59 ge::graphStatus SetTilingData();67 ge::graphStatus SetTilingData();
60 void PrintTilingData();68 void PrintTilingData();
61 69 
70+ // 方案2: M==1 Broadcast fast path selection + tiling (逐行照抄直调 cdist_host_tiling.cpp)。
71+ void DoBrcTiling();
72+ int64_t GetBrcBlockDim() const;
73+ void PrintBrcTilingData() const;
74+ 
75+ // 方案三 (round2): M∈[2,256] 矢量胜 → broadcast+高层reduce 内核(Normal 形态 tiling),否则回退 SIMT。
76+ void CapUbFactorRForHL(); // cap ubFactorR so the HL kernel never R-chunks internally
77+ 
62private:78private:
63 gert::TilingContext* tilingContext_ = nullptr;79 gert::TilingContext* tilingContext_ = nullptr;
64 CdistTilingData tilingData_;80 CdistTilingData tilingData_;
81+ CdistBrcTilingData brcTilingData_; // 方案2: M==1 快路径 tiling
82+ int64_t use_broadcast_ = 0; // 方案2: 命中 M==1 广播快路径标记
83+ int64_t use_reduce_hl_ = 0; // 方案三 (round2): 命中 M∈[2,256] 矢量胜 broadcast+高层reduce 路径标记
65 gert::Shape x1Shape_;84 gert::Shape x1Shape_;
66 gert::Shape x2Shape_;85 gert::Shape x2Shape_;
67 gert::Shape yShape_;86 gert::Shape yShape_;
@@ -75,4 +94,4 @@ private:
75 int64_t P_ = 0;94 int64_t P_ = 0;
76 int64_t R_ = 0;95 int64_t R_ = 0;
77};96};
78-} // namespace optiling97+} // namespace optiling
@@ -36,9 +36,9 @@ public:
36 36 
37private:37private:
38 __aicore__ inline void ParseTilingData(const CdistTilingData* tilingData);38 __aicore__ inline void ParseTilingData(const CdistTilingData* tilingData);
39- __aicore__ inline void CopyInX1(uint32_t Offset);39+ __aicore__ inline void CopyInX1(uint64_t Offset);
40- __aicore__ inline void CopyInX2(uint32_t Offset);40+ __aicore__ inline void CopyInX2(uint64_t Offset);
41- __aicore__ inline void CopyOut(uint32_t Offset);41+ __aicore__ inline void CopyOut(uint64_t Offset);
42 __aicore__ inline void CastY();42 __aicore__ inline void CastY();
43 __aicore__ inline void CastXToB32();43 __aicore__ inline void CastXToB32();
44 __aicore__ inline void Compute();44 __aicore__ inline void Compute();
@@ -208,7 +208,7 @@ __aicore__ inline void Cdist<T>::ParseTilingData(const CdistTilingData* tdPtr)
208}208}
209 209 
210template <typename T>210template <typename T>
211-__aicore__ inline void Cdist<T>::CopyInX1(uint32_t Offset)211+__aicore__ inline void Cdist<T>::CopyInX1(uint64_t Offset)
212{212{
213 LocalTensor<T> x1Local = x1Queue_.AllocTensor<T>();213 LocalTensor<T> x1Local = x1Queue_.AllocTensor<T>();
214 copyInParamsX1_.blockCount = static_cast<uint16_t>(pSize_);214 copyInParamsX1_.blockCount = static_cast<uint16_t>(pSize_);
@@ -218,7 +218,7 @@ __aicore__ inline void Cdist<T>::CopyInX1(uint32_t Offset)
218 copyInParamsX1_.dstStride = 0; // unit block(32byte)218 copyInParamsX1_.dstStride = 0; // unit block(32byte)
219 loopParamX1_.loop1Size = static_cast<uint32_t>(bSize_);219 loopParamX1_.loop1Size = static_cast<uint32_t>(bSize_);
220 loopParamX1_.loop2Size = 1;220 loopParamX1_.loop2Size = 1;
221- loopParamX1_.loop1SrcStride = static_cast<uint64_t>((M_ * P_) * sizeof(T));221+ loopParamX1_.loop1SrcStride = static_cast<uint64_t>((uint64_t)M_ * P_ * sizeof(T));
222 loopParamX1_.loop2SrcStride = 0;222 loopParamX1_.loop2SrcStride = 0;
223 loopParamX1_.loop1DstStride = static_cast<uint64_t>((pSize_ * MAlign_) * sizeof(T));223 loopParamX1_.loop1DstStride = static_cast<uint64_t>((pSize_ * MAlign_) * sizeof(T));
224 loopParamX1_.loop2DstStride = 0;224 loopParamX1_.loop2DstStride = 0;
@@ -229,7 +229,7 @@ __aicore__ inline void Cdist<T>::CopyInX1(uint32_t Offset)
229}229}
230 230 
231template <typename T>231template <typename T>
232-__aicore__ inline void Cdist<T>::CopyInX2(uint32_t Offset)232+__aicore__ inline void Cdist<T>::CopyInX2(uint64_t Offset)
233{233{
234 LocalTensor<T> x2Local = x2Queue_.AllocTensor<T>();234 LocalTensor<T> x2Local = x2Queue_.AllocTensor<T>();
235 copyInParamsX2_.blockCount = static_cast<uint16_t>(rSize_);235 copyInParamsX2_.blockCount = static_cast<uint16_t>(rSize_);
@@ -239,7 +239,7 @@ __aicore__ inline void Cdist<T>::CopyInX2(uint32_t Offset)
239 copyInParamsX2_.dstStride = 0; // unit block(32byte)239 copyInParamsX2_.dstStride = 0; // unit block(32byte)
240 loopParamX2_.loop1Size = static_cast<uint32_t>(bSize_);240 loopParamX2_.loop1Size = static_cast<uint32_t>(bSize_);
241 loopParamX2_.loop2Size = 1;241 loopParamX2_.loop2Size = 1;
242- loopParamX2_.loop1SrcStride = static_cast<uint64_t>((M_ * R_) * sizeof(T));242+ loopParamX2_.loop1SrcStride = static_cast<uint64_t>((uint64_t)M_ * R_ * sizeof(T));
243 loopParamX2_.loop2SrcStride = 0;243 loopParamX2_.loop2SrcStride = 0;
244 loopParamX2_.loop1DstStride = static_cast<uint64_t>((rSize_ * MAlign_) * sizeof(T));244 loopParamX2_.loop1DstStride = static_cast<uint64_t>((rSize_ * MAlign_) * sizeof(T));
245 loopParamX2_.loop2DstStride = 0;245 loopParamX2_.loop2DstStride = 0;
@@ -250,7 +250,7 @@ __aicore__ inline void Cdist<T>::CopyInX2(uint32_t Offset)
250}250}
251 251 
252template <typename T>252template <typename T>
253-__aicore__ inline void Cdist<T>::CopyOut(uint32_t Offset)253+__aicore__ inline void Cdist<T>::CopyOut(uint64_t Offset)
254{254{
255 LocalTensor<T> yLocal = yQueue_.DeQue<T>();255 LocalTensor<T> yLocal = yQueue_.DeQue<T>();
256 copyOutParams_.blockCount = static_cast<uint16_t>(pSize_);256 copyOutParams_.blockCount = static_cast<uint16_t>(pSize_);
@@ -261,7 +261,7 @@ __aicore__ inline void Cdist<T>::CopyOut(uint32_t Offset)
261 loopParamOut_.loop2Size = 1;261 loopParamOut_.loop2Size = 1;
262 loopParamOut_.loop1SrcStride = static_cast<uint64_t>((pSize_ * RAlign_) * sizeof(T));262 loopParamOut_.loop1SrcStride = static_cast<uint64_t>((pSize_ * RAlign_) * sizeof(T));
263 loopParamOut_.loop2SrcStride = 0;263 loopParamOut_.loop2SrcStride = 0;
264- loopParamOut_.loop1DstStride = static_cast<uint64_t>((P_ * R_) * sizeof(T));264+ loopParamOut_.loop1DstStride = static_cast<uint64_t>((uint64_t)P_ * R_ * sizeof(T));
265 loopParamOut_.loop2DstStride = 0;265 loopParamOut_.loop2DstStride = 0;
266 SetLoopModePara(loopParamOut_, DataCopyMVType::UB_TO_OUT);266 SetLoopModePara(loopParamOut_, DataCopyMVType::UB_TO_OUT);
267 DataCopyPad(yGM_[Offset], yLocal, copyOutParams_);267 DataCopyPad(yGM_[Offset], yLocal, copyOutParams_);
@@ -699,11 +699,11 @@ template <typename T>
699__aicore__ inline void Cdist<T>::ProcessNoSplitM(uint32_t bOffset, uint32_t pOffset, uint32_t rOffsetBlock,699__aicore__ inline void Cdist<T>::ProcessNoSplitM(uint32_t bOffset, uint32_t pOffset, uint32_t rOffsetBlock,
700 uint32_t blockFactorR)700 uint32_t blockFactorR)
701{701{
702- uint32_t offsetX1 = 0;702+ uint64_t offsetX1 = 0;
703- uint32_t offsetX2 = 0;703+ uint64_t offsetX2 = 0;
704- uint32_t offsetY = 0;704+ uint64_t offsetY = 0;
705- uint32_t rOffset = 0;705+ uint64_t rOffset = 0;
706- offsetX1 = bOffset * P_ * M_ + pOffset * M_;706+ offsetX1 = (uint64_t)bOffset * P_ * M_ + (uint64_t)pOffset * M_;
707 MAlign_ = ((M_ * sizeof(T) + BLOCK_SIZE - 1) / BLOCK_SIZE * BLOCK_SIZE) / sizeof(T);707 MAlign_ = ((M_ * sizeof(T) + BLOCK_SIZE - 1) / BLOCK_SIZE * BLOCK_SIZE) / sizeof(T);
708 CopyInX1(offsetX1);708 CopyInX1(offsetX1);
709 for (uint32_t rIdx = 0; rIdx < ubLoopNumR_; rIdx++) {709 for (uint32_t rIdx = 0; rIdx < ubLoopNumR_; rIdx++) {
@@ -713,8 +713,8 @@ __aicore__ inline void Cdist<T>::ProcessNoSplitM(uint32_t bOffset, uint32_t pOff
713 continue;713 continue;
714 }714 }
715 RAlign_ = ((rSize_ * sizeof(T) + BLOCK_SIZE - 1) / BLOCK_SIZE * BLOCK_SIZE) / sizeof(T);715 RAlign_ = ((rSize_ * sizeof(T) + BLOCK_SIZE - 1) / BLOCK_SIZE * BLOCK_SIZE) / sizeof(T);
716- offsetX2 = bOffset * R_ * M_ + rOffset * M_;716+ offsetX2 = (uint64_t)bOffset * R_ * M_ + (uint64_t)rOffset * M_;
717- offsetY = bOffset * P_ * R_ + pOffset * R_ + rOffset;717+ offsetY = (uint64_t)bOffset * P_ * R_ + (uint64_t)pOffset * R_ + rOffset;
718 CopyInX2(offsetX2);718 CopyInX2(offsetX2);
719 event_t eventID = static_cast<event_t>(GetTPipePtr()->FetchEventID(AscendC::HardEvent::MTE3_V));719 event_t eventID = static_cast<event_t>(GetTPipePtr()->FetchEventID(AscendC::HardEvent::MTE3_V));
720 AscendC::SetFlag<AscendC::HardEvent::MTE3_V>(eventID);720 AscendC::SetFlag<AscendC::HardEvent::MTE3_V>(eventID);
@@ -730,12 +730,12 @@ template <typename T>
730__aicore__ inline void Cdist<T>::ProcessSplitM(uint32_t bOffset, uint32_t pOffset, uint32_t rOffsetBlock,730__aicore__ inline void Cdist<T>::ProcessSplitM(uint32_t bOffset, uint32_t pOffset, uint32_t rOffsetBlock,
731 uint32_t blockFactorR)731 uint32_t blockFactorR)
732{732{
733- uint32_t offsetX1 = 0;733+ uint64_t offsetX1 = 0;
734- uint32_t offsetX2 = 0;734+ uint64_t offsetX2 = 0;
735- uint32_t offsetY = 0;735+ uint64_t offsetY = 0;
736 int32_t processNum = 0;736 int32_t processNum = 0;
737- uint32_t mOffset = 0;737+ uint64_t mOffset = 0;
738- uint32_t rOffset = 0;738+ uint64_t rOffset = 0;
739 for (uint32_t rIdx = 0; rIdx < ubLoopNumR_; rIdx++) {739 for (uint32_t rIdx = 0; rIdx < ubLoopNumR_; rIdx++) {
740 rOffset = rOffsetBlock + rIdx * ubFactorR_;740 rOffset = rOffsetBlock + rIdx * ubFactorR_;
741 rSize_ = (rIdx == ubLoopNumR_ - 1) ? (blockFactorR - ubFactorR_ * rIdx) : ubFactorR_;741 rSize_ = (rIdx == ubLoopNumR_ - 1) ? (blockFactorR - ubFactorR_ * rIdx) : ubFactorR_;
@@ -743,7 +743,7 @@ __aicore__ inline void Cdist<T>::ProcessSplitM(uint32_t bOffset, uint32_t pOffse
743 continue;743 continue;
744 }744 }
745 processNum = bSize_ * pSize_ * rSize_;745 processNum = bSize_ * pSize_ * rSize_;
746- offsetY = bOffset * P_ * R_ + pOffset * R_ + rOffset;746+ offsetY = (uint64_t)bOffset * P_ * R_ + (uint64_t)pOffset * R_ + rOffset;
747 if constexpr (sizeof(T) != sizeof(float)) {747 if constexpr (sizeof(T) != sizeof(float)) {
748 yFp32_ = yCastQueue_.DeQue<float>();748 yFp32_ = yCastQueue_.DeQue<float>();
749 Duplicate<float>(yFp32_, (float)0, processNum);749 Duplicate<float>(yFp32_, (float)0, processNum);
@@ -757,8 +757,8 @@ __aicore__ inline void Cdist<T>::ProcessSplitM(uint32_t bOffset, uint32_t pOffse
757 mOffset = mIdx * ubFactorM_;757 mOffset = mIdx * ubFactorM_;
758 mSize_ = (mIdx == ubLoopNumM_ - 1) ? ubTailFactorM_ : ubFactorM_;758 mSize_ = (mIdx == ubLoopNumM_ - 1) ? ubTailFactorM_ : ubFactorM_;
759 MAlign_ = ((mSize_ * sizeof(T) + BLOCK_SIZE - 1) / BLOCK_SIZE * BLOCK_SIZE) / sizeof(T);759 MAlign_ = ((mSize_ * sizeof(T) + BLOCK_SIZE - 1) / BLOCK_SIZE * BLOCK_SIZE) / sizeof(T);
760- offsetX1 = bOffset * P_ * M_ + pOffset * M_ + mOffset;760+ offsetX1 = (uint64_t)bOffset * P_ * M_ + (uint64_t)pOffset * M_ + mOffset;
761- offsetX2 = bOffset * R_ * M_ + rOffset * M_ + mOffset;761+ offsetX2 = (uint64_t)bOffset * R_ * M_ + (uint64_t)rOffset * M_ + mOffset;
762 CopyInX1(offsetX1);762 CopyInX1(offsetX1);
763 CopyInX2(offsetX2);763 CopyInX2(offsetX2);
764 CastXToB32();764 CastXToB32();
@@ -0,0 +1,469 @@
1+/**
2+ * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file cdist_broadcast.h
13+ * \brief 方案2: cdist M==1 Broadcast 融合内核 —— OneDim(④) + 静态 rank UB-BRC(③).
14+ *
15+ * 语义 (M==1):y[b,p,r] = ( |x1[b,p]-x2[b,r]|^p )^(1/p)
16+ * - 一般 p (0<p<∞, p∉{1,2}):用 Ln/Muls/Exp 复现 (|d|^p)^(1/p),与 golden(torch.cdist)
17+ * 的数值行为对齐(含极端 |d| 下上溢 inf / 下溢 0),避免精度对比 FAIL。
18+ * - p∈{1,2,inf}:M==1 数学恒等于 |d|,直接输出(golden 亦精确)。
19+ * - p==0 :min(ceil(|d|), 1)(非零计数)
20+ *
21+ * 实现分支:
22+ * brcBranch==0 OneDim (P==R==1):输出塌一维长度 B,逐块 |x1-x2|,M==1 归一恒 |d|/count。
23+ * brcBranch==1 UB-BRC :每 batch 取 (rowsP, R) tile;x1[rowsP,1]、x2[1,R] 紧凑搬入 UB 后用
24+ * 编译期静态 rank Broadcast<T,2>/GetBroadcastTilingInfo<T,2> 展开到
25+ * [rowsP, R],再 Sub->Abs(->p0 归一)。相对方案1(运行期 Broadcast<T>)
26+ * 差异仅在 constRank 编译期固化,减少派发/tiling 开销。
27+ *
28+ * 计算走 fp32(与 golden 一致:fp32 计算后 cast back)。x1/x2 均可能广播 → 各配独立 bufSrc(避免 RAW 冒险)。
29+ */
30+#ifndef CDIST_BROADCAST_H
31+#define CDIST_BROADCAST_H
32+ 
33+#include "kernel_operator.h" // adv_api Broadcast/GetBroadcastTilingInfo (register-invoke: no cdist_local_deps.h)
34+#include "../cdist_brc_tilingdata.h"
35+ 
36+#if !defined(__NPU_HOST__)
37+ 
38+#ifndef INFINITY
39+#define INFINITY (__builtin_inff())
40+#endif
41+ 
42+namespace NsCdist {
43+using namespace AscendC;
44+ 
45+constexpr int32_t CDIST_BRC_BLOCK = 32;
46+constexpr int32_t CDIST_STATIC_RANK = 2; // 编译期固定 rank(方案2 核心)
47+ 
48+template <typename T>
49+class CdistBroadcast {
50+public:
51+ __aicore__ inline CdistBroadcast(TPipe* pipe, const CdistBrcTilingData* tiling) : pipe_(pipe), td_(tiling) {}
52+ __aicore__ inline void Init(GM_ADDR x1, GM_ADDR x2, GM_ADDR y);
53+ __aicore__ inline void Process();
54+ 
55+private:
56+ __aicore__ inline void ProcessOneDim();
57+ __aicore__ inline void ProcessUbBrc();
58+ __aicore__ inline void ProcessUbBrcMulti();
59+ __aicore__ inline void ComputeTile(const LocalTensor<float>& x1exp, const LocalTensor<float>& x2exp,
60+ const LocalTensor<float>& yfp, int32_t count);
61+ __aicore__ inline int32_t AlignUp(int32_t n, int32_t align) { return (n + align - 1) / align * align; }
62+ 
63+ TPipe* pipe_ = nullptr;
64+ const CdistBrcTilingData* td_ = nullptr;
65+ GlobalTensor<T> x1Gm_, x2Gm_, yGm_;
66+ float p_ = 1.0f;
67+ static constexpr bool IS_FP32 = (sizeof(T) == sizeof(float));
68+ 
69+ // Staging buffers (T-typed load region for fp16/bf16 before cast to fp32).
70+ TQue<TPosition::VECIN, 2> qLoad1_, qLoad2_; // OneDim inputs (T)
71+ // fp32 compute planes
72+ TBuf<TPosition::VECCALC> bufSrc1_; // x1 紧凑源 fp32 (rowsP,1) / OneDim x1 fp32
73+ TBuf<TPosition::VECCALC> bufSrc2_; // x2 紧凑源 fp32 (1,R) / OneDim x2 fp32
74+ TBuf<TPosition::VECCALC> bufX1Exp_; // x1 展开 (rowsP,R) fp32 / OneDim yfp32
75+ TBuf<TPosition::VECCALC> bufX2Exp_; // x2 展开 (rowsP,R) fp32
76+ TBuf<TPosition::VECCALC> bufStage_; // T-typed staging for UB-BRC compact load
77+ TQue<TPosition::VECOUT, 2> qY_; // output (T)
78+};
79+ 
80+template <typename T>
81+__aicore__ inline void CdistBroadcast<T>::Init(GM_ADDR x1, GM_ADDR x2, GM_ADDR y)
82+{
83+ p_ = td_->p;
84+ x1Gm_.SetGlobalBuffer((__gm__ T*)x1);
85+ x2Gm_.SetGlobalBuffer((__gm__ T*)x2);
86+ yGm_.SetGlobalBuffer((__gm__ T*)y);
87+ 
88+ if (td_->brcBranch == 0) {
89+ int32_t tn = (int32_t)td_->tileNum;
90+ int32_t tnAlignF = AlignUp(tn, CDIST_BRC_BLOCK / (int32_t)sizeof(float));
91+ pipe_->InitBuffer(qLoad1_, 2, tn * (int32_t)sizeof(T));
92+ pipe_->InitBuffer(qLoad2_, 2, tn * (int32_t)sizeof(T));
93+ pipe_->InitBuffer(qY_, 2, tn * (int32_t)sizeof(T));
94+ pipe_->InitBuffer(bufSrc1_, tnAlignF * (int32_t)sizeof(float)); // x1 fp32
95+ pipe_->InitBuffer(bufSrc2_, tnAlignF * (int32_t)sizeof(float)); // x2 fp32
96+ pipe_->InitBuffer(bufX1Exp_, tnAlignF * (int32_t)sizeof(float)); // yfp32
97+ } else if (td_->brcBranch == 2) {
98+ // multi-batch: pack G=batchPerTile 个 batch/一个 tile。P*R 小(<=64x64),整块 (P,R) 装得下。
99+ int64_t en = td_->elemNum; // 每个 fp32 平面容量(>= G*P*R)
100+ int32_t alignT = CDIST_BRC_BLOCK / (int32_t)sizeof(T);
101+ int64_t G = td_->batchPerTile;
102+ int32_t src1Ele = AlignUp((int32_t)(G * td_->P), alignT); // x1 块 G*P
103+ int32_t src2Ele = AlignUp((int32_t)(G * td_->R), alignT); // x2 块 G*R
104+ if (src1Ele < alignT)
105+ src1Ele = alignT;
106+ if (src2Ele < alignT)
107+ src2Ele = alignT;
108+ pipe_->InitBuffer(qLoad1_, 2, src1Ele * (int32_t)sizeof(T)); // x1 batched load (T)
109+ pipe_->InitBuffer(qLoad2_, 2, src2Ele * (int32_t)sizeof(T)); // x2 batched load (T)
110+ pipe_->InitBuffer(bufSrc1_, src1Ele * (int32_t)sizeof(float)); // x1 batched fp32
111+ pipe_->InitBuffer(bufSrc2_, src2Ele * (int32_t)sizeof(float)); // x2 batched fp32
112+ pipe_->InitBuffer(bufX1Exp_, en * (int64_t)sizeof(float)); // x1 expand fp32 (also result)
113+ pipe_->InitBuffer(bufX2Exp_, en * (int64_t)sizeof(float)); // x2 expand fp32
114+ pipe_->InitBuffer(qY_, 2, en * (int64_t)sizeof(T)); // output G*P*R (T)
115+ } else {
116+ int64_t en = td_->elemNum;
117+ int32_t alignT = CDIST_BRC_BLOCK / (int32_t)sizeof(T);
118+ int32_t src1Ele = AlignUp((int32_t)td_->ubFormerP, alignT);
119+ int32_t src2Ele = AlignUp((int32_t)td_->rSeg, alignT);
120+ if (src1Ele < alignT)
121+ src1Ele = alignT;
122+ if (src2Ele < alignT)
123+ src2Ele = alignT;
124+ // Compact loads go through double-buffered VECIN queues (auto MTE2<->V sync, avoids
125+ // cross-iteration WAR on a single TBuf staging). qLoad1_=x1(rows), qLoad2_=x2(rlen).
126+ pipe_->InitBuffer(qLoad1_, 2, src1Ele * (int32_t)sizeof(T)); // x1 compact (T)
127+ pipe_->InitBuffer(qLoad2_, 2, src2Ele * (int32_t)sizeof(T)); // x2 compact (T)
128+ pipe_->InitBuffer(bufSrc1_, src1Ele * (int32_t)sizeof(float)); // x1 compact fp32
129+ pipe_->InitBuffer(bufSrc2_, src2Ele * (int32_t)sizeof(float)); // x2 compact fp32
130+ pipe_->InitBuffer(bufX1Exp_, en * (int64_t)sizeof(float)); // x1 expand fp32 (also result)
131+ pipe_->InitBuffer(bufX2Exp_, en * (int64_t)sizeof(float)); // x2 expand fp32
132+ pipe_->InitBuffer(qY_, 2, en * (int64_t)sizeof(T));
133+ }
134+}
135+ 
136+// count 个元素的 cdist 单元素归一:p>0 时与 golden(torch.cdist) 对齐,p==0 时非零计数。
137+template <typename T>
138+__aicore__ inline void CdistBroadcast<T>::ComputeTile(const LocalTensor<float>& x1exp, const LocalTensor<float>& x2exp,
139+ const LocalTensor<float>& yfp, int32_t count)
140+{
141+ // |x1 - x2|:AbsSub 合并 sub+abs(与 golden 输入语义一致)
142+ AbsSub(yfp, x1exp, x2exp, count);
143+ 
144+ if (p_ == 0.0f) {
145+ // L0:M==1 => d==0 ? 0 : 1(非零计数)
146+ Ceil(yfp, yfp, (uint32_t)count);
147+ Mins(yfp, yfp, (float)1, count);
148+ } else if (p_ != 1.0f && p_ != 2.0f && p_ != INFINITY) {
149+ // 一般 p (0<p<∞, p∉{1,2}):与 golden(torch.cdist) 数值行为对齐,复现 (|d|^p)^(1/p)。
150+ // 中间 |d|^p 在极端 |d| 下上溢(inf)/下溢(0)——与 torch 的 pow 溢出行为一致,
151+ // 避免 broadcast 直接输出 |d| 导致与 golden 的 inf/0 对比 FAIL。
152+ // 用 FTZ_FALSE(不 flush denormal):exp 链中间值 |d|^p 需保住 denormal
153+ constexpr static ExpConfig expConfig = {ExpAlgo::PRECISION_1ULP_FTZ_FALSE};
154+ constexpr static LnConfig lnConfig = {LnAlgo::PRECISION_1ULP_FTZ_FALSE};
155+ Ln<float, lnConfig>(x2exp, yfp, count); // log|d|
156+ Muls(x2exp, x2exp, p_, count); // p·log|d|
157+ Exp<float, expConfig>(yfp, x2exp, count); // |d|^p (极端 d 时 inf/0)
158+ Ln<float, lnConfig>(x2exp, yfp, count); // log(|d|^p) (inf→inf, 0→-inf)
159+ Muls(x2exp, x2exp, 1.0f / p_, count); // (1/p)·log(...)
160+ Exp<float, expConfig>(yfp, x2exp, count); // (|d|^p)^(1/p) (inf→inf, 0→0)
161+ }
162+ // p==1 / p==2 / p==inf:M==1 数学上恒等于 |d|,golden 亦精确,保持 |d|。
163+}
164+ 
165+// ---------------- OneDim (P==R==1) ----------------
166+template <typename T>
167+__aicore__ inline void CdistBroadcast<T>::ProcessOneDim()
168+{
169+ int64_t dimLen = td_->dimLen;
170+ int64_t tn = td_->tileNum;
171+ int64_t bn = td_->blockNum;
172+ if (tn < 1)
173+ tn = 1;
174+ if (bn < 1)
175+ bn = 1;
176+ // 缺陷① 修复:每核负责一段连续区间 [blockStart, blockEnd),blockEnd 对 dimLen 做全局 clamp,
177+ // 每个 tile 的 len 取 min(tn, blockEnd-off)。旧实现按 (blockFormer,blockTail) 独立算每核尾块,
178+ // 当 ubOuter 不足以填满 bn*blockFormer 时 blockTail 为负、且非末核用满 tn 写超 dimLen(OOB
179+ // DataCopyPad 踩踏相邻 GM,msprof 多次 launch 下累积成精度 FAIL)。全局 clamp 后 missing/oob/dup 均为 0。
180+ int64_t ubOuter = (dimLen + tn - 1) / tn;
181+ int64_t blockFormer = (ubOuter + bn - 1) / bn; // 每核最多承担的 tile 数
182+ int64_t bid = GetBlockIdx();
183+ if (bid >= bn)
184+ return;
185+ int64_t blockStart = blockFormer * tn * bid;
186+ if (blockStart >= dimLen)
187+ return; // 本核无有效数据
188+ int64_t blockEnd = blockStart + blockFormer * tn;
189+ if (blockEnd > dimLen)
190+ blockEnd = dimLen; // 末核 clamp,杜绝越界写
191+ int32_t alignFp = CDIST_BRC_BLOCK / (int32_t)sizeof(float);
192+ 
193+ LocalTensor<float> x1f = bufSrc1_.Get<float>();
194+ LocalTensor<float> x2f = bufSrc2_.Get<float>();
195+ LocalTensor<float> yfp = bufX1Exp_.Get<float>();
196+ 
197+ for (int64_t off = blockStart; off < blockEnd; off += tn) {
198+ int64_t len = blockEnd - off;
199+ if (len > tn)
200+ len = tn; // 每 tile 长度对本核剩余量 clamp
201+ if (len <= 0)
202+ break;
203+ LocalTensor<T> x1l = qLoad1_.template AllocTensor<T>();
204+ LocalTensor<T> x2l = qLoad2_.template AllocTensor<T>();
205+ DataCopyExtParams inExt{1, (uint32_t)(len * sizeof(T)), 0, 0, 0};
206+ DataCopyPadExtParams<T> pad{false, 0, 0, 0};
207+ DataCopyPad(x1l, x1Gm_[off], inExt, pad);
208+ DataCopyPad(x2l, x2Gm_[off], inExt, pad);
209+ qLoad1_.EnQue(x1l);
210+ qLoad2_.EnQue(x2l);
211+ LocalTensor<T> x1v = qLoad1_.template DeQue<T>();
212+ LocalTensor<T> x2v = qLoad2_.template DeQue<T>();
213+ if constexpr (!IS_FP32) {
214+ Cast(x1f, x1v, RoundMode::CAST_NONE, (int32_t)len);
215+ Cast(x2f, x2v, RoundMode::CAST_NONE, (int32_t)len);
216+ ComputeTile(x1f, x2f, yfp, (int32_t)len);
217+ } else {
218+ ComputeTile(x1v.template ReinterpretCast<float>(), x2v.template ReinterpretCast<float>(), yfp,
219+ (int32_t)len);
220+ }
221+ qLoad1_.FreeTensor(x1v);
222+ qLoad2_.FreeTensor(x2v);
223+ LocalTensor<T> yl = qY_.template AllocTensor<T>();
224+ if constexpr (!IS_FP32) {
225+ Cast(yl, yfp, RoundMode::CAST_RINT, (int32_t)len);
226+ } else {
227+ DataCopy(yl.template ReinterpretCast<float>(), yfp, AlignUp((int32_t)len, alignFp));
228+ }
229+ qY_.EnQue(yl);
230+ LocalTensor<T> yo = qY_.template DeQue<T>();
231+ DataCopyExtParams outExt{1, (uint32_t)(len * sizeof(T)), 0, 0, 0};
232+ DataCopyPad(yGm_[off], yo, outExt);
233+ qY_.FreeTensor(yo);
234+ }
235+}
236+ 
237+// ---------------- UB-BRC (静态 rank=2) ----------------
238+template <typename T>
239+__aicore__ inline void CdistBroadcast<T>::ProcessUbBrc()
240+{
241+ int64_t B = td_->B, P = td_->P, R = td_->R;
242+ int64_t ubFormerP = td_->ubFormerP, ubOuterP = td_->ubOuterP;
243+ int64_t rSeg = td_->rSeg, rOuter = td_->rOuter;
244+ int64_t totalTiles = td_->totalTiles;
245+ int64_t bn = td_->coreNumT;
246+ int64_t blockFormer = td_->blockFormerT;
247+ if (bn < 1)
248+ bn = 1;
249+ if (blockFormer < 1)
250+ blockFormer = 1;
251+ int64_t bid = GetBlockIdx();
252+ if (bid >= bn)
253+ return;
254+ int64_t tileStart = blockFormer * bid;
255+ int64_t loops = (bid == bn - 1) ? (totalTiles - blockFormer * (bn - 1)) : blockFormer;
256+ 
257+ int32_t alignFp = CDIST_BRC_BLOCK / (int32_t)sizeof(float);
258+ 
259+ LocalTensor<float> src1 = bufSrc1_.Get<float>();
260+ LocalTensor<float> src2 = bufSrc2_.Get<float>();
261+ LocalTensor<float> x1exp = bufX1Exp_.Get<float>();
262+ LocalTensor<float> x2exp = bufX2Exp_.Get<float>();
263+ 
264+ for (int64_t t = 0; t < loops; t++) {
265+ int64_t lin = tileStart + t;
266+ if (lin >= totalTiles)
267+ break;
268+ int64_t rTile = lin % rOuter;
269+ int64_t tmp = lin / rOuter;
270+ int64_t pTile = tmp % ubOuterP;
271+ int64_t b = tmp / ubOuterP;
272+ 
273+ int64_t p0 = pTile * ubFormerP;
274+ int64_t rows = (pTile == ubOuterP - 1) ? (P - p0) : ubFormerP;
275+ int64_t r0 = rTile * rSeg;
276+ int64_t rlen = (rTile == rOuter - 1) ? (R - r0) : rSeg;
277+ if (rows <= 0 || rlen <= 0)
278+ continue;
279+ 
280+ DataCopyPadExtParams<T> pad{false, 0, 0, 0};
281+ 
282+ // --- x1 compact load (rows) via double-buffered queue (auto MTE2<->V sync) ---
283+ LocalTensor<T> x1t = qLoad1_.template AllocTensor<T>();
284+ {
285+ DataCopyExtParams e1{1, (uint32_t)(rows * sizeof(T)), 0, 0, 0};
286+ DataCopyPad(x1t, x1Gm_[b * P + p0], e1, pad);
287+ }
288+ qLoad1_.EnQue(x1t);
289+ // --- x2 compact load (rlen) ---
290+ LocalTensor<T> x2t = qLoad2_.template AllocTensor<T>();
291+ {
292+ DataCopyExtParams e2{1, (uint32_t)(rlen * sizeof(T)), 0, 0, 0};
293+ DataCopyPad(x2t, x2Gm_[b * R + r0], e2, pad);
294+ }
295+ qLoad2_.EnQue(x2t);
296+ 
297+ LocalTensor<T> x1v = qLoad1_.template DeQue<T>();
298+ LocalTensor<T> x2v = qLoad2_.template DeQue<T>();
299+ if constexpr (!IS_FP32) {
300+ Cast(src1, x1v, RoundMode::CAST_NONE, (int32_t)rows);
301+ Cast(src2, x2v, RoundMode::CAST_NONE, (int32_t)rlen);
302+ } else {
303+ DataCopy(src1, x1v.template ReinterpretCast<float>(), AlignUp((int32_t)rows, alignFp));
304+ DataCopy(src2, x2v.template ReinterpretCast<float>(), AlignUp((int32_t)rlen, alignFp));
305+ }
306+ qLoad1_.FreeTensor(x1v);
307+ qLoad2_.FreeTensor(x2v);
308+ 
309+ // --- Broadcast x1: [rows,1] -> [rows,rlen] (static rank=2) ---
310+ uint32_t d1Shape[CDIST_STATIC_RANK] = {(uint32_t)rows, (uint32_t)rlen};
311+ uint32_t s1Shape[CDIST_STATIC_RANK] = {(uint32_t)rows, 1u};
312+ BroadcastTiling bt1;
313+ GetBroadcastTilingInfo<float, CDIST_STATIC_RANK>((uint32_t)CDIST_STATIC_RANK, d1Shape, s1Shape, false, bt1);
314+ Broadcast<float, CDIST_STATIC_RANK>(x1exp, src1, d1Shape, s1Shape, &bt1);
315+ 
316+ // --- Broadcast x2: [1,rlen] -> [rows,rlen] (static rank=2) ---
317+ uint32_t d2Shape[CDIST_STATIC_RANK] = {(uint32_t)rows, (uint32_t)rlen};
318+ uint32_t s2Shape[CDIST_STATIC_RANK] = {1u, (uint32_t)rlen};
319+ BroadcastTiling bt2;
320+ GetBroadcastTilingInfo<float, CDIST_STATIC_RANK>((uint32_t)CDIST_STATIC_RANK, d2Shape, s2Shape, false, bt2);
321+ Broadcast<float, CDIST_STATIC_RANK>(x2exp, src2, d2Shape, s2Shape, &bt2);
322+ 
323+ // --- compute |x1-x2| (p0: count) into x1exp ---
324+ int32_t count = (int32_t)(rows * rlen);
325+ ComputeTile(x1exp, x2exp, x1exp, count);
326+ 
327+ LocalTensor<T> yl = qY_.template AllocTensor<T>();
328+ if constexpr (!IS_FP32) {
329+ Cast(yl, x1exp, RoundMode::CAST_RINT, count);
330+ } else {
331+ DataCopy(yl.template ReinterpretCast<float>(), x1exp, AlignUp(count, alignFp));
332+ }
333+ qY_.EnQue(yl);
334+ LocalTensor<T> yo = qY_.template DeQue<T>();
335+ // Tiling 保证二选一,输出 GM 段恒连续,用单块 DataCopyPad(UB src 也是 packed 连续):
336+ // R-fits (rOuter==1, rlen==R): (rows×R) 行连续 → y[b,p0*R .. +rows*R] 连续。
337+ // R-split (rlen<R): rows==1 → 单行 rlen 连续。
338+ // 避免 blockCount>1 且 blockLen 非 32B 对齐时对 UB packed 源的错位读取。
339+ DataCopyExtParams outExt{1, (uint32_t)(count * sizeof(T)), 0, 0, 0};
340+ DataCopyPad(yGm_[b * P * R + p0 * R + r0], yo, outExt);
341+ qY_.FreeTensor(yo);
342+ }
343+}
344+ 
345+// ---------------- UB-BRC multi-batch (缺陷② 修复, brcBranch==2) ----------------
346+// 小 tile 场景:P*R 小,把 G=batchPerTile 个 batch 打包进一个 UB tile。
347+// 一次 DataCopyPad 搬 G*P(x1) / G*R(x2),逐 batch 静态 rank Broadcast 展开到 (P,R) 平面,
348+// 计算后一次 DataCopyPad 写 G*P*R。相比每 tile 1 batch,把 per-tile 固定开销摊薄 G 倍。
349+template <typename T>
350+__aicore__ inline void CdistBroadcast<T>::ProcessUbBrcMulti()
351+{
352+ int64_t B = td_->B, P = td_->P, R = td_->R;
353+ int64_t G = td_->batchPerTile;
354+ int64_t totalTiles = td_->totalTiles;
355+ int64_t bn = td_->coreNumT;
356+ int64_t blockFormer = td_->blockFormerT;
357+ if (G < 1)
358+ G = 1;
359+ if (bn < 1)
360+ bn = 1;
361+ if (blockFormer < 1)
362+ blockFormer = 1;
363+ int64_t bid = GetBlockIdx();
364+ if (bid >= bn)
365+ return;
366+ int64_t tileStart = blockFormer * bid;
367+ int64_t loops = (bid == bn - 1) ? (totalTiles - blockFormer * (bn - 1)) : blockFormer;
368+ 
369+ int32_t alignFp = CDIST_BRC_BLOCK / (int32_t)sizeof(float);
370+ int64_t plane = P * R;
371+ 
372+ LocalTensor<float> src1 = bufSrc1_.Get<float>(); // x1 batched fp32 (G*P)
373+ LocalTensor<float> src2 = bufSrc2_.Get<float>(); // x2 batched fp32 (G*R)
374+ LocalTensor<float> x1exp = bufX1Exp_.Get<float>(); // (G*P*R) fp32 & result
375+ LocalTensor<float> x2exp = bufX2Exp_.Get<float>(); // (G*P*R) fp32
376+ 
377+ // x2 平面 (1,R)->(P,R) 对每 batch 恒相同 → tiling 外提,仍需逐 batch 调用(packed [g][p][r] 中
378+ // x2 在 p 维复制,无法用 rank2 一次覆盖)。x1 则可整块一次广播(见下 bt1All)。
379+ uint32_t dShape[CDIST_STATIC_RANK] = {(uint32_t)P, (uint32_t)R};
380+ uint32_t s2Shape[CDIST_STATIC_RANK] = {1u, (uint32_t)R};
381+ BroadcastTiling bt2;
382+ GetBroadcastTilingInfo<float, CDIST_STATIC_RANK>((uint32_t)CDIST_STATIC_RANK, dShape, s2Shape, false, bt2);
383+ 
384+ for (int64_t t = 0; t < loops; t++) {
385+ int64_t lin = tileStart + t;
386+ if (lin >= totalTiles)
387+ break;
388+ int64_t b0 = lin * G;
389+ int64_t g = (b0 + G <= B) ? G : (B - b0); // 尾块:本 tile 实际 batch 数
390+ if (g <= 0)
391+ break;
392+ 
393+ DataCopyPadExtParams<T> pad{false, 0, 0, 0};
394+ 
395+ // --- x1 batched load: G*P 连续 (x1 layout (B,P)) ---
396+ LocalTensor<T> x1t = qLoad1_.template AllocTensor<T>();
397+ {
398+ DataCopyExtParams e1{1, (uint32_t)(g * P * sizeof(T)), 0, 0, 0};
399+ DataCopyPad(x1t, x1Gm_[b0 * P], e1, pad);
400+ }
401+ qLoad1_.EnQue(x1t);
402+ // --- x2 batched load: G*R 连续 (x2 layout (B,R)) ---
403+ LocalTensor<T> x2t = qLoad2_.template AllocTensor<T>();
404+ {
405+ DataCopyExtParams e2{1, (uint32_t)(g * R * sizeof(T)), 0, 0, 0};
406+ DataCopyPad(x2t, x2Gm_[b0 * R], e2, pad);
407+ }
408+ qLoad2_.EnQue(x2t);
409+ 
410+ LocalTensor<T> x1v = qLoad1_.template DeQue<T>();
411+ LocalTensor<T> x2v = qLoad2_.template DeQue<T>();
412+ if constexpr (!IS_FP32) {
413+ Cast(src1, x1v, RoundMode::CAST_NONE, (int32_t)(g * P));
414+ Cast(src2, x2v, RoundMode::CAST_NONE, (int32_t)(g * R));
415+ } else {
416+ DataCopy(src1, x1v.template ReinterpretCast<float>(), AlignUp((int32_t)(g * P), alignFp));
417+ DataCopy(src2, x2v.template ReinterpretCast<float>(), AlignUp((int32_t)(g * R), alignFp));
418+ }
419+ qLoad1_.FreeTensor(x1v);
420+ qLoad2_.FreeTensor(x2v);
421+ 
422+ // --- x1: 整块一次广播 (g*P, 1) -> (g*P, R),packed [g][p][r] 恰为 x1exp(一次调用覆盖全部 g)---
423+ {
424+ uint32_t d1All[CDIST_STATIC_RANK] = {(uint32_t)(g * P), (uint32_t)R};
425+ uint32_t s1All[CDIST_STATIC_RANK] = {(uint32_t)(g * P), 1u};
426+ BroadcastTiling bt1All;
427+ GetBroadcastTilingInfo<float, CDIST_STATIC_RANK>((uint32_t)CDIST_STATIC_RANK, d1All, s1All, false, bt1All);
428+ Broadcast<float, CDIST_STATIC_RANK>(x1exp, src1, d1All, s1All, &bt1All);
429+ }
430+ // --- x2: packed [g][p][r] 中 x2 在 p 维复制 → 逐 batch (1,R)->(P,R)(tiling 已外提) ---
431+ for (int64_t j = 0; j < g; j++) {
432+ Broadcast<float, CDIST_STATIC_RANK>(x2exp[j * plane], src2[j * R], dShape, s2Shape, &bt2);
433+ }
434+ 
435+ // --- compute |x1-x2| (+p0 归一) 整块 g*P*R ---
436+ int32_t count = (int32_t)(g * plane);
437+ ComputeTile(x1exp, x2exp, x1exp, count);
438+ 
439+ LocalTensor<T> yl = qY_.template AllocTensor<T>();
440+ if constexpr (!IS_FP32) {
441+ Cast(yl, x1exp, RoundMode::CAST_RINT, count);
442+ } else {
443+ DataCopy(yl.template ReinterpretCast<float>(), x1exp, AlignUp(count, alignFp));
444+ }
445+ qY_.EnQue(yl);
446+ LocalTensor<T> yo = qY_.template DeQue<T>();
447+ // 输出 y[b0..b0+g] 的 (P,R) 平面在 GM 连续 (out layout (B,P,R)) → 单块 DataCopyPad。
448+ DataCopyExtParams outExt{1, (uint32_t)(count * sizeof(T)), 0, 0, 0};
449+ DataCopyPad(yGm_[b0 * plane], yo, outExt);
450+ qY_.FreeTensor(yo);
451+ }
452+}
453+ 
454+template <typename T>
455+__aicore__ inline void CdistBroadcast<T>::Process()
456+{
457+ if (td_->brcBranch == 0) {
458+ ProcessOneDim();
459+ } else if (td_->brcBranch == 2) {
460+ ProcessUbBrcMulti();
461+ } else {
462+ ProcessUbBrc();
463+ }
464+}
465+ 
466+} // namespace NsCdist
467+ 
468+#endif // !defined(__NPU_HOST__)
469+#endif // CDIST_BROADCAST_H
@@ -0,0 +1,402 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file broadcast_common.h
13+ * \brief AscendC 广播算子通用件:常量 / TilingData / 切分辅助 helper / 四类广播原语。
14+ * 纯 AscendC API,不依赖任何模板调度框架,可直接拷入自定义算子工程裁剪使用。
15+ * 平台:DAV_3510(A5 / Ascend950,C310)。
16+ *
17+ * 四类广播实现:
18+ * ④ OneDim(前置) —— 合轴塌一维时整算子走此路:标量首块 Duplicate 铺满、满输入直搬,tiling 退化 1D
19+ * ① BroadcastNddma —— GM→UB 多维 DMA,广播轴 srcStride=0 由引擎复制(不占 Vector)
20+ * ② DataCopyPadCompact —— 每轮紧凑搬入,广播由 GetGmOffset 的 stride=0 寻址实现(外层广播轴用);
21+ * offset 相同时复用为可选优化(本样例未启用)
22+ * ③ UbBroadcast —— DataCopyPad 搬紧凑源后用 Broadcast 矢量指令在 UB 内展开
23+ */
24+#ifndef BROADCAST_COMMON_H
25+#define BROADCAST_COMMON_H
26+ 
27+#include "kernel_operator.h"
28+ 
29+namespace BrcDemo {
30+using namespace AscendC;
31+ 
32+constexpr int64_t BROADCAST_MAX_DIMS = 8; // 支持的最大维数
33+constexpr int64_t NDDMA_DIM = 5; // 单次多维 DMA 维数上限
34+constexpr int64_t BLOCK_LENGTH = 32; // 对齐字节
35+ 
36+// brcMode:每个输入由 Host tiling 选定的广播实现
37+enum BrcMode { BRC_NONE = 0, BRC_NDDMA = 1, BRC_DATACOPYPAD = 2, BRC_UB = 3 };
38+ 
39+// 自定义算子可直接照搬这组字段(与框架无关)。IN_NUM 由具体算子定。
40+template <int IN_NUM>
41+struct BroadcastTilingData {
42+ int32_t brcMode[IN_NUM]; // 每个输入的广播实现(见 BrcMode)
43+ int32_t shapeLen; // 输出维数
44+ int32_t ubSplitAxis; // UB 切分轴
45+ int32_t ubFormer, ubTail; // UB 主块/尾块(沿 ubSplitAxis)
46+ int64_t ubOuter; // UB 外循环次数
47+ int64_t blockNum; // 核数
48+ int64_t blockFormer, blockTail; // 每核外循环单元数(主/尾核)
49+ int64_t dimProductBeforeUbInner; // UB tile 总数 = ∏outputDims[0..ubSplitAxis-1] × ubOuter
50+ int64_t elemNum; // 单 buffer 可容纳元素数
51+ 
52+ int64_t outputDims[BROADCAST_MAX_DIMS];
53+ int64_t outputStrides[BROADCAST_MAX_DIMS];
54+ int64_t inputDims[IN_NUM][BROADCAST_MAX_DIMS]; // 广播轴长度=1
55+ int64_t inputStrides[IN_NUM][BROADCAST_MAX_DIMS]; // 广播轴 stride=0 ★关键
56+};
57+ 
58+// ============================ Host 侧通用切分 ============================
59+// 除数用「(x > 0 ? x : 1)」内联钳制,保证静态分析可证除数恒 >=1(G.EXP.22-CPP);
60+// 正常调用 b/al 恒 >=1,钳制恒取原值,行为不变。
61+static inline int64_t BrcCeilDiv(int64_t a, int64_t b)
62+{
63+ int64_t d = (b > 0) ? b : 1;
64+ return (a + d - 1) / d;
65+}
66+static inline int64_t BrcAlignDown(int64_t a, int64_t al)
67+{
68+ int64_t d = (al > 0) ? al : 1;
69+ return (a / d) * d;
70+}
71+ 
72+// 通用两层切分:自动选 ubSplitAxis 并算 ubFormer/ubOuter/ubTail/dimProductBeforeUbInner/多核切分。
73+// 适用任意 rank、任意输出 shape,含「尾轴超 UB 容量」「大 shape 无广播」等场景(替代写死 ubSplitAxis=0)。
74+// 前置:td.shapeLen / td.outputDims / td.outputStrides(连续布局)已填。aliveBuf=存活 buffer 数。
75+template <int IN_NUM>
76+inline void ComputeTiling(BroadcastTilingData<IN_NUM>& td, int dtSize, int64_t coreNum, int64_t ubSize,
77+ int64_t aliveBuf)
78+{
79+ int rank = td.shapeLen;
80+ int64_t dtBytes = (dtSize > 0) ? dtSize : 1; // 钳制除数,保证静态可证 >=1(G.EXP.22-CPP)
81+ int64_t alignEle = BLOCK_LENGTH / dtBytes;
82+ td.elemNum = BrcAlignDown(ubSize / (aliveBuf * dtBytes * 2 /*DoubleBuffer*/), alignEle);
83+ if (td.elemNum < alignEle)
84+ td.elemNum = alignEle;
85+ 
86+ // 1) 从尾轴向外选切分轴:尽量把内层整轴塞进 UB
87+ int splitAxis = 0;
88+ int64_t innerBelow = 1; // ∏ outputDims[splitAxis+1 .. rank-1]
89+ for (int ax = rank - 1; ax >= 0; ax--) {
90+ if (innerBelow * td.outputDims[ax] > td.elemNum) {
91+ splitAxis = ax;
92+ break;
93+ }
94+ innerBelow *= td.outputDims[ax];
95+ splitAxis = ax;
96+ }
97+ // 2) 切分轴每行(inner)元素数 = innerBelow(= outputStrides[splitAxis])
98+ int64_t ubFormer;
99+ if (innerBelow > td.elemNum) { // 连一行都放不下 → 退到最后一轴按 elemNum 分块
100+ td.ubSplitAxis = rank - 1;
101+ innerBelow = 1;
102+ ubFormer = td.elemNum; // 已对齐
103+ } else {
104+ td.ubSplitAxis = splitAxis;
105+ ubFormer = td.elemNum / innerBelow; // 一次能放几行
106+ }
107+ int64_t splitDim = td.outputDims[td.ubSplitAxis];
108+ if (ubFormer > splitDim)
109+ ubFormer = splitDim;
110+ if (ubFormer < 1)
111+ ubFormer = 1;
112+ td.ubFormer = ubFormer;
113+ td.ubOuter = BrcCeilDiv(splitDim, ubFormer);
114+ td.ubTail = splitDim - (td.ubOuter - 1) * ubFormer; // 可能非 alignEle 倍数,DataCopyPad 自动处理
115+ 
116+ // 3) dimProductBeforeUbInner = ∏outputDims[0..ubSplitAxis-1] × ubOuter(UB tile 总数,通用公式)
117+ int64_t outerProd = 1;
118+ for (int j = 0; j < td.ubSplitAxis; j++)
119+ outerProd *= td.outputDims[j];
120+ td.dimProductBeforeUbInner = outerProd * td.ubOuter;
121+ 
122+ // 4) 多核:先按核数算每核 tile 数(blockFormer),再回收用不上的核(blockNum),避免 blockTail 为负。
123+ // (错误写法:先 blockNum=min(core,total) 再 blockFormer=ceil(total/blockNum) → 末核 blockTail 可能<0)
124+ int64_t totalTiles = td.dimProductBeforeUbInner;
125+ int64_t cn = (coreNum < 1) ? 1 : coreNum;
126+ td.blockFormer = BrcCeilDiv(totalTiles, cn); // 每核最多几个 tile
127+ if (td.blockFormer < 1)
128+ td.blockFormer = 1;
129+ td.blockNum = BrcCeilDiv(totalTiles, td.blockFormer); // 回收无效核
130+ td.blockTail = totalTiles - (td.blockNum - 1) * td.blockFormer; // ∈[1, blockFormer]
131+}
132+ 
133+// ============================ 切分辅助 helper(纯标量) ============================
134+ 
135+// ① 线性 tile 序号 → 多维下标。axes[ubSplitAxis] ∈ [0, ubOuter),以 ubFormer 行为单位。
136+// tileLinear = blockFormer*GetBlockIdx() + loop;tileTotal = dimProductBeforeUbInner
137+__aicore__ inline void GetAxesIndices(int64_t (&axes)[BROADCAST_MAX_DIMS], int64_t tileLinear,
138+ const int64_t (&outputDims)[BROADCAST_MAX_DIMS], int64_t ubSplitAxis,
139+ int64_t tileTotal)
140+{
141+ int64_t rem = tileTotal;
142+ for (int64_t idx = 0; idx < ubSplitAxis; idx++) {
143+ rem /= outputDims[idx];
144+ axes[idx] = tileLinear / rem;
145+ tileLinear -= axes[idx] * rem;
146+ }
147+ axes[ubSplitAxis] = tileLinear;
148+}
149+ 
150+// ② 外循环每轮 +1(带进位)。切分轴上界 ubOuter,其余轴 outputDims。ubSplitAxis=0 时无外层轴可进位。
151+__aicore__ inline void UpdateAxesIndices(int64_t (&axes)[BROADCAST_MAX_DIMS],
152+ const int64_t (&outputDims)[BROADCAST_MAX_DIMS], int64_t ubSplitAxis,
153+ int64_t ubOuter)
154+{
155+ axes[ubSplitAxis]++;
156+ if (axes[ubSplitAxis] == ubOuter) {
157+ axes[ubSplitAxis] = 0;
158+ if (ubSplitAxis > 0)
159+ axes[ubSplitAxis - 1]++; // 防 ubSplitAxis=0 时 axes[-1] 越界
160+ }
161+ for (int64_t idx = ubSplitAxis - 1; idx >= 1; idx--) {
162+ if (axes[idx] == outputDims[idx]) {
163+ axes[idx] = 0;
164+ axes[idx - 1]++;
165+ }
166+ }
167+}
168+ 
169+// ③ 多维下标 → GM 线性偏移。广播轴 stride=0 → 该轴自动原地复用,无需特殊分支
170+__aicore__ inline int64_t GetGmOffset(const int64_t (&axes)[BROADCAST_MAX_DIMS],
171+ const int64_t (&strides)[BROADCAST_MAX_DIMS], int64_t ubSplitAxis,
172+ int64_t ubFormer)
173+{
174+ int64_t off = 0;
175+ for (int64_t idx = 0; idx < ubSplitAxis; idx++)
176+ off += axes[idx] * strides[idx];
177+ off += axes[ubSplitAxis] * strides[ubSplitAxis] * ubFormer; // 切分轴以 ubFormer 行为步长
178+ return off;
179+}
180+ 
181+// ④ 填 UB 内 Broadcast 的 dst/src shape(首轴随主块/尾块变化),供 ③ 使用
182+__aicore__ inline void FillUbShape(uint32_t (&dstShape)[BROADCAST_MAX_DIMS], uint32_t (&srcShape)[BROADCAST_MAX_DIMS],
183+ const int64_t (&outputDims)[BROADCAST_MAX_DIMS],
184+ const int64_t (&inDims)[BROADCAST_MAX_DIMS], int64_t ubSplitAxis, int64_t shapeLen,
185+ int64_t curRows)
186+{
187+ dstShape[0] = (uint32_t)curRows;
188+ srcShape[0] = (inDims[ubSplitAxis] == 1) ? 1u : (uint32_t)curRows; // 切分轴广播则源首轴=1
189+ for (int64_t i = ubSplitAxis + 1, j = 1; i < shapeLen; i++, j++) {
190+ dstShape[j] = (uint32_t)outputDims[i];
191+ srcShape[j] = (uint32_t)inDims[i]; // 广播轴在源上=1
192+ }
193+}
194+ 
195+// ③ 用:当前 tile 紧凑源的元素数 = 源行数 × 切分轴以下各源轴乘积(广播轴在源上为 1)。
196+// 注意:不能用输出 tile 长度(那是展开后的),否则 [M,1] 这类尾轴广播会多搬。
197+__aicore__ inline int64_t UbSrcLen(const int64_t (&inStrides)[BROADCAST_MAX_DIMS],
198+ const int64_t (&inDims)[BROADCAST_MAX_DIMS], int64_t ubSplitAxis, int64_t shapeLen,
199+ int64_t rows)
200+{
201+ int64_t srcRows = (inStrides[ubSplitAxis] != 0) ? rows : 1; // 切分轴广播则源只 1 行
202+ int64_t inner = 1;
203+ for (int64_t j = ubSplitAxis + 1; j < shapeLen; j++)
204+ inner *= inDims[j];
205+ return srcRows * inner;
206+}
207+ 
208+// ============================ 实现①:NDDMA 搬入即广播 ============================
209+ 
210+// 装配多维 DMA 参数:广播轴 loopSrcStride 天然=0 → 引擎复制(逻辑同 atvoss WithoutLoop)
211+template <typename T>
212+__aicore__ inline AscendC::MultiCopyParams<T, NDDMA_DIM> MakeNddmaParams(
213+ const int64_t (&outputDims)[BROADCAST_MAX_DIMS], const int64_t (&outputStrides)[BROADCAST_MAX_DIMS],
214+ const int64_t (&inputStrides)[BROADCAST_MAX_DIMS], int64_t shapeLen, int64_t ubSplitAxis, int64_t ubSplitSize)
215+{
216+ AscendC::MultiCopyLoopInfo<NDDMA_DIM> loop;
217+ int64_t axisInsideUb = NDDMA_DIM - (shapeLen - ubSplitAxis); // 高位需补几个 size=1 的轴
218+ // 防御:rank=shapeLen-ubSplitAxis>NDDMA_DIM 时 axisInsideUb<0,下面 NDDMA_DIM-1-axisInsideUb 会越界。
219+ // Host 选型已对 rank>5 回退 BRC_UB(见 broadcast_add_tiling.cpp / PickBroadcastMode),此处再夹一道。
220+ if (axisInsideUb < 0)
221+ axisInsideUb = 0; // 仅防越界;rank>5 应由 Host 拦截
222+ 
223+ for (int64_t i = 0; i < axisInsideUb; i++) {
224+ loop.loopSize[NDDMA_DIM - 1 - i] = 1;
225+ loop.loopSrcStride[NDDMA_DIM - 1 - i] = inputStrides[ubSplitAxis];
226+ loop.loopDstStride[NDDMA_DIM - 1 - i] = outputStrides[ubSplitAxis];
227+ }
228+ loop.loopSize[NDDMA_DIM - 1 - axisInsideUb] = ubSplitSize;
229+ loop.loopSrcStride[NDDMA_DIM - 1 - axisInsideUb] = inputStrides[ubSplitAxis];
230+ loop.loopDstStride[NDDMA_DIM - 1 - axisInsideUb] = outputStrides[ubSplitAxis];
231+ for (int64_t i = axisInsideUb + 1; i < NDDMA_DIM; i++) {
232+ int64_t axis = ubSplitAxis + i - axisInsideUb;
233+ loop.loopSize[NDDMA_DIM - 1 - i] = outputDims[axis];
234+ loop.loopSrcStride[NDDMA_DIM - 1 - i] = inputStrides[axis]; // 广播轴=0
235+ loop.loopDstStride[NDDMA_DIM - 1 - i] = outputStrides[axis];
236+ }
237+ return AscendC::MultiCopyParams<T, NDDMA_DIM>{loop, (T)0};
238+}
239+ 
240+// gm 已按当前 tile 偏移;UB tile 内存在广播(split 轴源/目的跨度不一致)→ 多维 DMA 复制,
241+// 否则退化为连续搬运(即②)。前置条件:rank = shapeLen - ubSplitAxis <= NDDMA_DIM(=5),
242+// rank>5 需 with-loop 版本(本头未实现);Host 选型须保证(见 broadcast_add_tiling.cpp 的 rank 兜底)。
243+template <typename T>
244+__aicore__ inline void BroadcastNddma(const GlobalTensor<T>& gm, const LocalTensor<T>& ub,
245+ const int64_t (&outputDims)[BROADCAST_MAX_DIMS],
246+ const int64_t (&outputStrides)[BROADCAST_MAX_DIMS],
247+ const int64_t (&inputStrides)[BROADCAST_MAX_DIMS], int64_t shapeLen,
248+ int64_t ubSplitAxis, int64_t ubSplitSize)
249+{
250+ if (outputStrides[ubSplitAxis] != inputStrides[ubSplitAxis]) {
251+ auto params = MakeNddmaParams<T>(outputDims, outputStrides, inputStrides, shapeLen, ubSplitAxis, ubSplitSize);
252+ static constexpr AscendC::MultiCopyConfig cfg = {false, 0, 0, false}; // 必须 static:模板参为 const&
253+ AscendC::DataCopy<T, NDDMA_DIM, cfg>(ub, gm, params);
254+ } else {
255+ AscendC::DataCopyExtParams ext{1, (uint32_t)(ubSplitSize * inputStrides[ubSplitAxis] * sizeof(T)), 0, 0, 0};
256+ AscendC::DataCopyPadExtParams<T> pad{false, 0, 0, 0};
257+ AscendC::DataCopyPad(ub, gm, ext, pad);
258+ }
259+}
260+ 
261+// ============================ 实现②:DataCopyPad 紧凑搬入 ============================
262+ 
263+// 紧凑连续搬一段(不复制,lenEle 可非 32B 对齐,DataCopyPad 自动 pad)。② 广播效果不在这里,
264+// 而在 GM offset:外层广播轴 stride=0,GetGmOffset 会让这些轴推进时仍指向同一段 GM(见 GetGmOffset)。
265+template <typename T>
266+__aicore__ inline void DataCopyPadCompact(const GlobalTensor<T>& gm, const LocalTensor<T>& ub, int64_t lenEle)
267+{
268+ AscendC::DataCopyExtParams ext{1, (uint32_t)(lenEle * sizeof(T)), 0, 0, 0};
269+ AscendC::DataCopyPadExtParams<T> pad{false, 0, 0, 0};
270+ AscendC::DataCopyPad(ub, gm, ext, pad);
271+}
272+ 
273+// 可选优化(本样例未启用,正确性见 datacopypad_design.md):当某广播输入本轮 GM offset 与上轮相同
274+// (仅外层广播轴推进、切分轴未变)时可跳过搬运、复用上轮 UB。DoubleBuffer 下需按 buffer 槽位分别记录
275+// 已填 offset,比"切分轴 stride"判据更通用——后者在 ② 路径恒为真,会让复用永不生效(死路径)。
276+ 
277+// ============================ 实现③:UB 内 Broadcast 指令 ============================
278+ 
279+// src 已是 UB 内紧凑源(GM 输入先 DataCopyPadCompact,或上游计算结果);dst 为展开目标
280+template <typename T>
281+__aicore__ inline void UbBroadcast(const LocalTensor<T>& dst, const LocalTensor<T>& src,
282+ const int64_t (&outputDims)[BROADCAST_MAX_DIMS],
283+ const int64_t (&inDims)[BROADCAST_MAX_DIMS], int64_t ubSplitAxis, int64_t shapeLen,
284+ int64_t curRows)
285+{
286+ uint32_t dShape[BROADCAST_MAX_DIMS], sShape[BROADCAST_MAX_DIMS];
287+ FillUbShape(dShape, sShape, outputDims, inDims, ubSplitAxis, shapeLen, curRows);
288+ int64_t rank = shapeLen - ubSplitAxis;
289+ // 退化守卫:无任何可展开维(所有 dShape==sShape,如切分轴广播但 tile 内仅 1 行)时,
290+ // Broadcast 会变成 src==dst 的空广播并产生 nan。此时直接拷贝 src→dst(src 已是该 tile 正确数据)。
291+ bool anyExpand = false;
292+ int64_t cnt = 1;
293+ for (int64_t k = 0; k < rank; k++) {
294+ if (dShape[k] > sShape[k])
295+ anyExpand = true;
296+ cnt *= dShape[k];
297+ }
298+ if (!anyExpand) { // 无可展开维:直接 UB→UB 拷贝(dtype 无关,避免空广播 nan)
299+ int32_t alignEle = BLOCK_LENGTH / sizeof(T);
300+ int32_t cntAlign = ((int32_t)cnt + alignEle - 1) / alignEle * alignEle; // 向上对齐;buffer=elemNum 不越界
301+ AscendC::DataCopy(dst, src, cntAlign); // CopyOut 只写真实 tile,多拷的对齐尾部无害
302+ return;
303+ }
304+ AscendC::BroadcastTiling bt;
305+ AscendC::GetBroadcastTilingInfo<T>(rank, dShape, sShape, false, bt);
306+ AscendC::Broadcast<T>(dst, src, dShape, sShape, &bt);
307+}
308+ 
309+// ============================ 实现④:OneDim 合轴塌一维快路径(标量广播) ============================
310+// 适用:合轴后塌成一维——每个输入要么满 shape(连续)、要么纯标量,全连续。是 scalar 广播(lr/scale/
311+// alpha 等)与同 shape elementwise 的最快实现:标量首块 Duplicate 铺满 UB 后复用,不走逐块 DMA;多维
312+// tiling 退化成 1D,固定成本最低(对标 atvoss SCH_MODE_ONE_DIM_ADVANCE,schMode 202)。
313+// 注意:[M,1]→[M,N] 这类"部分轴广播"合轴后仍是多维,不属本路径,走 ①②③。
314+ 
315+// 极简 TilingData(对标 Advance):只携带 1D 总长 + 块大小 + 核数 + 标量位,切分由 kernel 运行期推导。
316+struct OneDimTilingData {
317+ int64_t dimLen; // 输出总元素数(合轴后一维长度)
318+ int32_t tileNum; // 单块 UB 元素数(已对齐)
319+ int32_t blockNum; // 实际启用核数
320+ int32_t scalarFlag; // bit i = 1 → 第 i 个输入是标量(首块 Duplicate)
321+};
322+ 
323+// Host 选型:判断能否走 OneDim,并求 dimLen / scalarFlag。
324+// 规则:每个输入要么纯标量(∏inputDims==1)要么满 shape(∏inputDims==dimLen),否则塌不成一维返回 false。
325+template <int IN_NUM>
326+inline bool TryOneDim(const BroadcastTilingData<IN_NUM>& td, int64_t& dimLen, int32_t& scalarFlag)
327+{
328+ dimLen = 1;
329+ for (int j = 0; j < td.shapeLen; j++)
330+ dimLen *= td.outputDims[j];
331+ scalarFlag = 0;
332+ for (int i = 0; i < IN_NUM; i++) {
333+ int64_t cnt = 1;
334+ for (int j = 0; j < td.shapeLen; j++)
335+ cnt *= td.inputDims[i][j];
336+ if (cnt == 1)
337+ scalarFlag |= (1 << i); // 纯标量
338+ else if (cnt != dimLen)
339+ return false; // 既非标量又非满 shape → 不能塌一维
340+ }
341+ return true;
342+}
343+ 
344+// Host tiling(对标 Advance):只算 dimLen / tileNum / blockNum,其余切分留给 kernel 运行期推。
345+// aliveBuf=存活 buffer 数(满输入双缓冲计 1,标量首块单块也计 1,输出双缓冲计 1;保守取上界即可)。
346+inline void ComputeOneDimTiling(OneDimTilingData& t, int64_t dimLen, int32_t scalarFlag, int dtSize, int64_t coreNum,
347+ int64_t ubSize, int64_t aliveBuf)
348+{
349+ t.dimLen = dimLen;
350+ t.scalarFlag = scalarFlag;
351+ int64_t dtBytes = (dtSize > 0) ? dtSize : 1; // 钳制除数,保证静态可证 >=1(G.EXP.22-CPP)
352+ int64_t alignEle = BLOCK_LENGTH / dtBytes;
353+ int64_t tileNum = BrcAlignDown(ubSize / (aliveBuf * dtBytes * 2 /*DoubleBuffer*/), alignEle);
354+ if (tileNum < alignEle)
355+ tileNum = alignEle;
356+ int64_t ubOuter = BrcCeilDiv(dimLen, tileNum); // 一维共几块
357+ int64_t cn = (coreNum < 1) ? 1 : coreNum;
358+ if (ubOuter < cn)
359+ cn = (ubOuter < 1) ? 1 : ubOuter; // 块数不足核数 → 减核(小 shape 自适应)
360+ t.tileNum = (int32_t)tileNum;
361+ t.blockNum = (int32_t)cn;
362+}
363+ 
364+// Kernel 端运行期推导当前核的循环参数(对标 Advance:tiling 只给 dimLen/tileNum/blockNum)。
365+// baseOffset = 本核起始元素偏移;loops = 本核块数;tailLen = 本核最后一块的元素数。
366+struct OneDimCoreParam {
367+ int64_t baseOffset;
368+ int64_t loops;
369+ int64_t tailLen;
370+};
371+__aicore__ inline OneDimCoreParam OneDimCalcCore(int64_t dimLen, int64_t tileNum, int64_t blockNum)
372+{
373+ int64_t tn = (tileNum > 0) ? tileNum : 1; // 钳制除数,保证静态可证 >=1(G.EXP.22-CPP)
374+ int64_t bn = (blockNum > 0) ? blockNum : 1;
375+ int64_t ubOuter = (dimLen + tn - 1) / tn;
376+ int64_t ubTail = dimLen - (ubOuter - 1) * tn; // 最后一块元素数(可非对齐)
377+ int64_t blockFormer = (ubOuter + bn - 1) / bn; // 每核块数(先定块数)
378+ int64_t blockTail = ubOuter - (bn - 1) * blockFormer; // 尾核块数 ∈[1, blockFormer]
379+ int64_t bid = AscendC::GetBlockIdx();
380+ OneDimCoreParam p;
381+ p.baseOffset = blockFormer * tn * bid;
382+ bool lastCore = (bid == bn - 1);
383+ p.loops = lastCore ? blockTail : blockFormer;
384+ p.tailLen = lastCore ? ubTail : tn; // 非尾核最后一块仍是整块
385+ return p;
386+}
387+ 
388+// OneDim 单输入搬入:标量仅首块 Duplicate 铺满(后续块复用同一 UB,调用方勿重 Alloc);满 shape 逐块连续搬。
389+template <typename T>
390+__aicore__ inline void OneDimLoadInput(const LocalTensor<T>& dst, const GlobalTensor<T>& gm, int64_t offset,
391+ int64_t len, bool isScalar, bool firstTile)
392+{
393+ if (isScalar) {
394+ if (firstTile)
395+ AscendC::Duplicate(dst, gm.GetValue(0), len); // 标量值铺满;之后复用
396+ } else {
397+ DataCopyPadCompact(gm[offset], dst, len); // 满输入:连续搬,非对齐 Pad 兜底
398+ }
399+}
400+ 
401+} // namespace BrcDemo
402+#endif // BROADCAST_COMMON_H
@@ -15,23 +15,40 @@
15 15 
16#include "arch35/cdist_simt.h"16#include "arch35/cdist_simt.h"
17#include "arch35/cdist.h"17#include "arch35/cdist.h"
18+#include "arch35/cdist_broadcast.h" // 方案2: NsCdist::CdistBroadcast<T> (M==1 Broadcast fast path)
19+#include "arch35/cdist_reduce_hl.h" // 方案三: NsCdist::CdistReduceHL<T> (M∈[2,256] broadcast+高层reduce, round2 crossover)
18#include "cdist_tiling_data.h"20#include "cdist_tiling_data.h"
21+#include "cdist_brc_tilingdata.h" // 方案2: POD CdistBrcTilingData (host/kernel 共用)
19#include "cdist_tiling_key.h"22#include "cdist_tiling_key.h"
20 23 
21-template <uint32_t isSmallM>24+// KERNEL_MODE 模板轴:0=Normal(M>256) / 1=SIMT(M<=256 && M>1) / 2=Broadcast(M==1 快路径)。
25+// 与 op_host RunTiling 的 SetTilingKey(KERNEL_MODE) 及 cdist_tiling_key.h 的 TPL_SEL 一一对应。
26+template <uint32_t KERNEL_MODE>
22__global__ __aicore__ void cdist(GM_ADDR x1, GM_ADDR x2, GM_ADDR y, GM_ADDR workspace, GM_ADDR tiling)27__global__ __aicore__ void cdist(GM_ADDR x1, GM_ADDR x2, GM_ADDR y, GM_ADDR workspace, GM_ADDR tiling)
23{28{
24- REGISTER_TILING_DEFAULT(CdistTilingData);29+ // 全 kernel 只能有一个 REGISTER_TILING_DEFAULT(opc EB0500)。注册主结构 CdistTilingData;
25- GET_TILING_DATA_WITH_STRUCT(CdistTilingData, tilingData, tiling);30+ // Broadcast 分支用 GET_TILING_DATA_WITH_STRUCT 把同一 tiling GM 按 CdistBrcTilingData 解读即可。
26- 31+ REGISTER_NONE_TILING;
27 AscendC::TPipe pipe;32 AscendC::TPipe pipe;
28- if constexpr (isSmallM) { // SIMT 场景33+ if constexpr (KERNEL_MODE == 2) { // 方案2: M==1 Broadcast 快路径(用独立 CdistBrcTilingData)
34+ GET_TILING_DATA_WITH_STRUCT(CdistBrcTilingData, brcTilingData, tiling);
35+ NsCdist::CdistBroadcast<DTYPE_X1> op(&pipe, &brcTilingData);
36+ op.Init(x1, x2, y);
37+ op.Process();
38+ } else if constexpr (KERNEL_MODE == 3) { // 方案三: M∈[2,256] 矢量胜 broadcast+高层reduce(复用主 CdistTilingData)
39+ GET_TILING_DATA_WITH_STRUCT(CdistTilingData, tilingData, tiling);
40+ NsCdist::CdistReduceHL<DTYPE_X1> op;
41+ op.Init(x1, x2, y, &tilingData, &pipe);
42+ op.Process();
43+ } else if constexpr (KERNEL_MODE == 1) { // SIMT 场景
44+ GET_TILING_DATA_WITH_STRUCT(CdistTilingData, tilingData, tiling);
29 NsCdist::CdistSimt<DTYPE_X1> op(&pipe, &tilingData);45 NsCdist::CdistSimt<DTYPE_X1> op(&pipe, &tilingData);
30 op.Init(x1, x2, y);46 op.Init(x1, x2, y);
31 op.Process();47 op.Process();
32- } else { // Normal 场景48+ } else { // Normal 场景 (KERNEL_MODE == 0)
49+ GET_TILING_DATA_WITH_STRUCT(CdistTilingData, tilingData, tiling);
33 NsCdist::Cdist<DTYPE_X1> op;50 NsCdist::Cdist<DTYPE_X1> op;
34- op.Init(x1, x2, y, &tilingData, &pipe); 51+ op.Init(x1, x2, y, &tilingData, &pipe);
35- op.Process(); 52+ op.Process();
36 }53 }
37-}54+}
@@ -0,0 +1,58 @@
1+/**
2+ * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file cdist_brc_tilingdata.h
13+ * \brief POD tiling struct for the M==1 Broadcast fast path (方案2: 静态 rank UB-BRC + OneDim).
14+ * y[b,p,r] = |x1[b,p] - x2[b,r]| (M==1: p-norm degenerates to |d|), p!=1 normalizes on
15+ * the single element in scalar. Layout after batch-merge: out (B,P,R), x1 (B,P), x2 (B,R).
16+ *
17+ * Branch selection (brcBranch):
18+ * 0 = OneDim : P==1 && R==1 -> output collapses to 1D length B; elementwise |x1-x2| then p-norm.
19+ * 1 = UB-BRC : P>1 || R>1 -> per-batch (rowsP, R) tile, static-rank(=2) Broadcast on x1/x2.
20+ */
21+#ifndef CDIST_BRC_TILINGDATA_H
22+#define CDIST_BRC_TILINGDATA_H
23+ 
24+#include <cstdint>
25+ 
26+struct CdistBrcTilingData {
27+ int64_t B = 0; // merged batch
28+ int64_t P = 0; // x1 rows
29+ int64_t R = 0; // x2 rows
30+ float p = 1.0f; // norm order (M==1 => |d| for p in {1,2,inf}; 0 => min(ceil,1); else exp(ln|d|))
31+ 
32+ int32_t brcBranch = 1; // 0=OneDim, 1=UB-BRC, 2=UB-BRC multi-batch (small P*R tile)
33+ 
34+ // ---- OneDim (brcBranch==0) : 1D length = B ----
35+ int64_t dimLen = 0; // = B (P==R==1)
36+ int32_t tileNum = 0; // elements per UB block (aligned)
37+ int32_t blockNum = 0; // active cores
38+ 
39+ // ---- UB-BRC (brcBranch==1) ----
40+ // Tiling unit = (rowsP within one batch) x R plane. Static in-tile broadcast rank = 2.
41+ int64_t elemNum = 0; // per-buffer element capacity (aligned)
42+ int64_t ubFormerP = 0; // rows of P per main tile (rowsP)
43+ int64_t ubOuterP = 0; // number of P-tiles per batch = ceil(P/ubFormerP)
44+ int64_t ubTailP = 0; // rows in the last P-tile
45+ int64_t rSeg = 0; // R segment per tile ( == R when R fits UB; else <=elemNum split )
46+ int64_t rOuter = 0; // number of R segments = ceil(R/rSeg)
47+ int64_t rTail = 0; // last R segment length
48+ int64_t totalTiles = 0; // = B * ubOuterP * rOuter (brcBranch==1) / = ceil(B/batchPerTile) (brcBranch==2)
49+ int64_t blockFormerT = 0; // tiles per main core
50+ int64_t coreNumT = 0; // active cores for UB-BRC
51+ int64_t blockTailT = 0; // tiles on last core
52+ 
53+ // ---- UB-BRC multi-batch (brcBranch==2): P*R small, pack batchPerTile full batches per UB tile ----
54+ // 缺陷② 修复:小 tile(P*R 小)场景下按 batch 打包,把 30896 个 256 元素小 tile 合并成少量大 tile,
55+ // 大幅减少 per-tile DataCopyPad/Broadcast/EnQue 固定开销(181: 525us→接近方案1)。
56+ int64_t batchPerTile = 0; // batches packed into one UB tile (G)
57+};
58+#endif // CDIST_BRC_TILINGDATA_H
@@ -18,15 +18,12 @@
18 18 
19#include "ascendc/host_api/tiling/template_argument.h"19#include "ascendc/host_api/tiling/template_argument.h"
20 20 
21-ASCENDC_TPL_ARGS_DECL(21+// KERNEL_MODE: 0=Normal(M>256) / 1=SIMT(M<=256 && M>1) / 2=Broadcast(M==1 快路径, 方案2)
22- Cdist,22+// / 3=ReduceHL(M∈[2,256] 矢量胜: broadcast + 高层 ReduceRepeat reduce, 方案三 round2 crossover)。
23- ASCENDC_TPL_BOOL_DECL(IS_SMALL_M, 0, 1)23+// 原为 ASCENDC_TPL_BOOL_DECL(IS_SMALL_M,0,1),为新增 Broadcast/ReduceHL 路径扩为 4 取值 UINT 轴;
24-);24+// 值 0/1 与原 IS_SMALL_M 的 0(Normal)/1(SIMT) 语义完全对应,新增值 2/3 为优化路径标记。
25+ASCENDC_TPL_ARGS_DECL(Cdist, ASCENDC_TPL_UINT_DECL(KERNEL_MODE, 8, ASCENDC_TPL_UI_LIST, 0, 1, 2, 3));
25 26 
26-ASCENDC_TPL_SEL(27+ASCENDC_TPL_SEL(ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(KERNEL_MODE, ASCENDC_TPL_UI_LIST, 0, 1, 2, 3)));
27- ASCENDC_TPL_ARGS_SEL(
28- ASCENDC_TPL_BOOL_SEL(IS_SMALL_M, 0, 1)
29- )
30-);
31 28 
32-#endif29+#endif