Merged
TopkV2算子bitonic排序性能优化 #5939
cy_hwAdd on Sep 22
TopkV2算子bitonic排序性能优化 #5939
Merged
Total: 18 files changed+4963-1531
| @@ -34,25 +34,24 @@ using namespace ge; | |||
| 34 | using std::map; | 34 | using std::map; |
| 35 | using std::string; | 35 | using std::string; |
| 36 | using std::vector; | 36 | using std::vector; |
| 37 | -#define ADD_INPUT(intputIndex, intputName, intputDtype, inputShape) \ | 37 | +#define ADD_INPUT(intputIndex, intputName, intputDtype, inputShape) \ |
| 38 | - vector<int64_t> placeholder##intputIndex##_shape = inputShape; \ | 38 | + vector<int64_t> placeholder##intputIndex##_shape = inputShape; \ |
| 39 | - auto placeholder##intputIndex = op::Data("placeholder" + intputIndex).set_attr_index(0); \ | 39 | + auto placeholder##intputIndex = op::Data("placeholder" + intputIndex).set_attr_index(0); \ |
| 40 | - TensorDesc placeholder##intputIndex##_desc = \ | 40 | + TensorDesc placeholder##intputIndex##_desc = TensorDesc(ge::Shape(placeholder##intputIndex##_shape), FORMAT_ND, \ |
| 41 | - TensorDesc(ge::Shape(placeholder##intputIndex##_shape), FORMAT_ND, intputDtype); \ | 41 | + intputDtype); \ |
| 42 | - placeholder##intputIndex##_desc.SetPlacement(ge::kPlacementHost); \ | 42 | + placeholder##intputIndex##_desc.SetPlacement(ge::kPlacementHost); \ |
| 43 | - placeholder##intputIndex##_desc.SetFormat(FORMAT_ND); \ | 43 | + placeholder##intputIndex##_desc.SetFormat(FORMAT_ND); \ |
| 44 | - Tensor tensor_placeholder##intputIndex; \ | 44 | + Tensor tensor_placeholder##intputIndex; \ |
| 45 | - ret = GenOnesData( \ | 45 | + ret = GenOnesData(placeholder##intputIndex##_shape, tensor_placeholder##intputIndex, \ |
| 46 | - placeholder##intputIndex##_shape, tensor_placeholder##intputIndex, placeholder##intputIndex##_desc, \ | 46 | + placeholder##intputIndex##_desc, intputDtype, 1); \ |
| 47 | - intputDtype, 1); \ | 47 | + if (ret != SUCCESS) { \ |
| 48 | - if (ret != SUCCESS) { \ | 48 | + printf("%s - ERROR - [XIR]: Generate input data failed\n", GetTime().c_str()); \ |
| 49 | - printf("%s - ERROR - [XIR]: Generate input data failed\n", GetTime().c_str()); \ | 49 | + return FAILED; \ |
| 50 | - return FAILED; \ | 50 | + } \ |
| 51 | - } \ | 51 | + placeholder##intputIndex.update_input_desc_x(placeholder##intputIndex##_desc); \ |
| 52 | - placeholder##intputIndex.update_input_desc_x(placeholder##intputIndex##_desc); \ | 52 | + input.push_back(tensor_placeholder##intputIndex); \ |
| 53 | - input.push_back(tensor_placeholder##intputIndex); \ | 53 | + graph.AddOp(placeholder##intputIndex); \ |
| 54 | - graph.AddOp(placeholder##intputIndex); \ | 54 | + sortWithIndex.set_input_##intputName(placeholder##intputIndex); \ |
| 55 | - sortWithIndex.set_input_##intputName(placeholder##intputIndex); \ | ||
| 56 | inputs.push_back(placeholder##intputIndex) | 55 | inputs.push_back(placeholder##intputIndex) |
| 57 | 56 | ||
| 58 | #define ADD_OUTPUT(outputIndex, outputName, outputDtype, outputShape) \ | 57 | #define ADD_OUTPUT(outputIndex, outputName, outputDtype, outputShape) \ |
| @@ -120,8 +119,8 @@ int32_t GenOnesDataFloat32(vector<int64_t> shapes, Tensor& input_tensor, TensorD | |||
| 120 | return SUCCESS; | 119 | return SUCCESS; |
| 121 | } | 120 | } |
| 122 | 121 | ||
| 123 | -int32_t GenOnesData( | 122 | +int32_t GenOnesData(vector<int64_t> shapes, Tensor& input_tensor, TensorDesc& input_tensor_desc, DataType data_type, |
| 124 | - vector<int64_t> shapes, Tensor& input_tensor, TensorDesc& input_tensor_desc, DataType data_type, int value) | 123 | + int value) |
| 125 | { | 124 | { |
| 126 | input_tensor_desc.SetRealDimCnt(shapes.size()); | 125 | input_tensor_desc.SetRealDimCnt(shapes.size()); |
| 127 | size_t size = 1; | 126 | size_t size = 1; |
| @@ -130,8 +129,16 @@ int32_t GenOnesData( | |||
| 130 | } | 129 | } |
| 131 | uint32_t data_len = size * GetDataTypeSize(data_type); | 130 | uint32_t data_len = size * GetDataTypeSize(data_type); |
| 132 | int32_t* pData = new (std::nothrow) int32_t[data_len]; | 131 | int32_t* pData = new (std::nothrow) int32_t[data_len]; |
| 133 | - for (uint32_t i = 0; i < size; ++i) { | 132 | + if (data_type == ge::DT_FLOAT) { |
| 134 | - *(pData + i) = value; | 133 | + // float 输入需按 float 位填充,写入 int32 位模式会得到非规格化小数而非期望的浮点值 |
| 134 | + float* pFloatData = reinterpret_cast<float*>(pData); | ||
| 135 | + for (size_t i = 0; i < size; ++i) { | ||
| 136 | + *(pFloatData + i) = static_cast<float>(value); | ||
| 137 | + } | ||
| 138 | + } else { | ||
| 139 | + for (size_t i = 0; i < size; ++i) { | ||
| 140 | + *(pData + i) = value; | ||
| 141 | + } | ||
| 135 | } | 142 | } |
| 136 | input_tensor = Tensor(input_tensor_desc, reinterpret_cast<uint8_t*>(pData), data_len); | 143 | input_tensor = Tensor(input_tensor_desc, reinterpret_cast<uint8_t*>(pData), data_len); |
| 137 | return SUCCESS; | 144 | return SUCCESS; |
| @@ -145,9 +152,8 @@ int32_t WriteDataToFile(string bin_file, uint64_t data_size, uint8_t* inputData) | |||
| 145 | return SUCCESS; | 152 | return SUCCESS; |
| 146 | } | 153 | } |
| 147 | 154 | ||
| 148 | -int CreateOppInGraph( | 155 | +int CreateOppInGraph(DataType dataType, DataType indexType, std::vector<ge::Tensor>& input, |
| 149 | - DataType dataType, DataType indexType, std::vector<ge::Tensor>& input, std::vector<Operator>& inputs, std::vector<Operator>& outputs, | 156 | + std::vector<Operator>& inputs, std::vector<Operator>& outputs, Graph& graph) |
| 150 | - Graph& graph) | ||
| 151 | { | 157 | { |
| 152 | Status ret = SUCCESS; | 158 | Status ret = SUCCESS; |
| 153 | // 自定义代码:添加单算子定义到图中 | 159 | // 自定义代码:添加单算子定义到图中 |
| @@ -162,7 +168,7 @@ int CreateOppInGraph( | |||
| 162 | return SUCCESS; | 168 | return SUCCESS; |
| 163 | } | 169 | } |
| 164 | 170 | ||
| 165 | -int InitializeAndSetupGraph(Graph& graph, std::vector<ge::Tensor>& input, DataType dataType, DataType indexType) | 171 | +int InitializeAndSetupGraph(Graph& graph, std::vector<ge::Tensor>& input, DataType dataType, DataType indexType) |
| 166 | { | 172 | { |
| 167 | printf("%s - INFO - [XIR]: Start to initialize ge using ge global options\n", GetTime().c_str()); | 173 | printf("%s - INFO - [XIR]: Start to initialize ge using ge global options\n", GetTime().c_str()); |
| 168 | std::map<AscendString, AscendString> global_options = {{"ge.exec.deviceId", "0"}, {"ge.graphRunMode", "1"}}; | 174 | std::map<AscendString, AscendString> global_options = {{"ge.exec.deviceId", "0"}, {"ge.graphRunMode", "1"}}; |
| @@ -261,7 +267,9 @@ int main(int argc, char* argv[]) | |||
| 261 | Graph graph(graph_name); | 267 | Graph graph(graph_name); |
| 262 | std::vector<ge::Tensor> input; | 268 | std::vector<ge::Tensor> input; |
| 263 | 269 | ||
| 264 | - std::cout << argv[1] << std::endl; | 270 | + if (argc > 1) { |
| 271 | + std::cout << argv[1] << std::endl; | ||
| 272 | + } | ||
| 265 | 273 | ||
| 266 | DataType dataType = DT_FLOAT; | 274 | DataType dataType = DT_FLOAT; |
| 267 | DataType indexType = DT_INT32; | 275 | DataType indexType = DT_INT32; |
| @@ -297,4 +305,4 @@ int main(int argc, char* argv[]) | |||
| 297 | } | 305 | } |
| 298 | printf("%s - INFO - [XIR]: Finalize ir graph session success\n", GetTime().c_str()); | 306 | printf("%s - INFO - [XIR]: Finalize ir graph session success\n", GetTime().c_str()); |
| 299 | return SUCCESS; | 307 | return SUCCESS; |
| 300 | -} | 308 | +} |
| @@ -1344,6 +1344,226 @@ ge::graphStatus FillTopkNonLastSmallAxisTilingData(gert::TilingContext* context, | |||
| 1344 | return ge::GRAPH_SUCCESS; | 1344 | return ge::GRAPH_SUCCESS; |
| 1345 | } | 1345 | } |
| 1346 | 1346 | ||
| 1347 | +/** | ||
| 1348 | + * @brief 初始化TopKV2小轴排序路由信息 | ||
| 1349 | + * @details 填充数据类型、UB、核心数等基础字段,并计算轴维乘积。 | ||
| 1350 | + * @param info 排序Tiling信息 | ||
| 1351 | + * @param computeInfo TopK计算信息 | ||
| 1352 | + * @param inputShape 输入张量的形状 | ||
| 1353 | + * @param axis TopK操作的目标轴索引 | ||
| 1354 | + * @param originUbSize 原始UB大小 | ||
| 1355 | + */ | ||
| 1356 | +static void InitTopKSmallAxisTileInfo(TopKSmallAxisRouteInfo& info, | ||
| 1357 | + const topkV2DataInfo::TopkComputeNowTileSizeInfo& computeInfo, | ||
| 1358 | + const gert::Shape& inputShape, int32_t axis, uint64_t originUbSize) | ||
| 1359 | +{ | ||
| 1360 | + info.dataType = computeInfo.dataType; | ||
| 1361 | + info.dtypeSize = GetDataTypeSize(computeInfo.dataType); | ||
| 1362 | + // UB内索引固定为uint32_t,与kernel侧IDX_T一致,保证段占用估算与实际UB分配吻合 | ||
| 1363 | + info.y2DtypeSize = static_cast<uint32_t>(sizeof(uint32_t)); | ||
| 1364 | + info.blockUbSize = static_cast<uint32_t>(computeInfo.ubBlockAlignSize); | ||
| 1365 | + info.maxCoreNum = computeInfo.maxCoreNum; | ||
| 1366 | + // 传入未扣SIMT预留的原始UB,sort路由函数内部自行扣除SIMT_UB | ||
| 1367 | + info.ubSize = static_cast<uint32_t>(originUbSize); | ||
| 1368 | + int64_t rank = static_cast<int64_t>(inputShape.GetDimNum()); | ||
| 1369 | + info.isNonLastAxis = (axis != rank - 1); | ||
| 1370 | + info.outerSize = 1; | ||
| 1371 | + info.innerSize = 1; | ||
| 1372 | + for (int64_t i = 0; i < rank; ++i) { | ||
| 1373 | + if (i < axis) { | ||
| 1374 | + info.outerSize *= inputShape.GetDim(i); | ||
| 1375 | + } else if (i > axis) { | ||
| 1376 | + info.innerSize *= inputShape.GetDim(i); | ||
| 1377 | + } | ||
| 1378 | + } | ||
| 1379 | + info.lastAxis = inputShape.GetDim(axis); | ||
| 1380 | + info.unsortedDim = info.outerSize * info.innerSize; | ||
| 1381 | +} | ||
| 1382 | + | ||
| 1383 | +/** | ||
| 1384 | + * @brief 选择小轴排序路由,仅接管INSERTION/TWO_STAGE两种kind | ||
| 1385 | + * @param info 排序Tiling信息 | ||
| 1386 | + * @param plan 待填充的小轴路由方案 | ||
| 1387 | + * @param isTwoStage 出参,是否为TWO_STAGE路由 | ||
| 1388 | + * @return true 表示命中可接管的排序路由;false 表示未命中,需回落原有模式 | ||
| 1389 | + */ | ||
| 1390 | +static bool SelectTopKSmallAxisRoute(const TopKSmallAxisRouteInfo& info, SmallAxisRoutePlan& plan, bool& isTwoStage) | ||
| 1391 | +{ | ||
| 1392 | + bool selected = info.isNonLastAxis ? SelectNonLastSmallAxisRoute(info, plan) : SelectSmallAxisRoute(info, plan); | ||
| 1393 | + if (!selected || (plan.kind != SmallAxisRouteKind::INSERTION && plan.kind != SmallAxisRouteKind::TWO_STAGE)) { | ||
| 1394 | + return false; | ||
| 1395 | + } | ||
| 1396 | + isTwoStage = plan.kind == SmallAxisRouteKind::TWO_STAGE; | ||
| 1397 | + return true; | ||
| 1398 | +} | ||
| 1399 | + | ||
| 1400 | +/** | ||
| 1401 | + * @brief 填充小轴排序路由的公共Tiling字段并判定bitonic终排 | ||
| 1402 | + * @param topkTilingData TopK Tiling数据结构 | ||
| 1403 | + * @param computeInfo TopK计算信息 | ||
| 1404 | + * @param info 排序Tiling信息 | ||
| 1405 | + * @param plan 已选定的小轴路由方案 | ||
| 1406 | + * @param isTwoStage 是否为TWO_STAGE路由 | ||
| 1407 | + * @param useBitonicFinalize 出参,是否追加bitonic确定性终排 | ||
| 1408 | + */ | ||
| 1409 | +static void FillTopKSmallAxisCommonTiling(TopKV2TilingDataSimd& topkTilingData, | ||
| 1410 | + const topkV2DataInfo::TopkComputeNowTileSizeInfo& computeInfo, | ||
| 1411 | + const TopKSmallAxisRouteInfo& info, const SmallAxisRoutePlan& plan, | ||
| 1412 | + bool isTwoStage, bool& useBitonicFinalize) | ||
| 1413 | +{ | ||
| 1414 | + // sort_policy=1(且sorted)时对已选出的k个候选追加bitonic确定性终排。 | ||
| 1415 | + // k>32时bitonic网络(32通道)放不下,不接管终排照常输出; 终排只重排值与索引,不改变UB布局。 | ||
| 1416 | + useBitonicFinalize = IsBitonicSmallTopkMode(computeInfo.kValue, topkTilingData.get_sortPolicy(), | ||
| 1417 | + computeInfo.isSort); | ||
| 1418 | + | ||
| 1419 | + topkTilingData.set_modeType(isTwoStage ? topkV2DataInfo::SMALL_AXIS_TWO_STAGE_MODE : | ||
| 1420 | + topkV2DataInfo::SMALL_AXIS_INSERTION_MODE); | ||
| 1421 | + topkTilingData.set_isLargest(computeInfo.isLargest); | ||
| 1422 | + topkTilingData.set_isSort(computeInfo.isSort); | ||
| 1423 | + topkTilingData.set_isInInt32Range(computeInfo.isInInt32Range); | ||
| 1424 | + topkTilingData.set_lastAxisNum(info.lastAxis); | ||
| 1425 | + topkTilingData.set_numTileDataSize(static_cast<uint32_t>(info.lastAxis)); | ||
| 1426 | + topkTilingData.set_topKRealValue(computeInfo.kValue); | ||
| 1427 | + topkTilingData.set_outputLastDimValue(computeInfo.kValue); | ||
| 1428 | + topkTilingData.set_platformCoreNum(computeInfo.maxCoreNum); | ||
| 1429 | + topkTilingData.set_keyParams0(plan.batchSize); | ||
| 1430 | + topkTilingData.set_keyParams1(plan.batchNum); | ||
| 1431 | + // INSERTION: keyParams2复用为非last的innerLoopNum;TWO_STAGE: keyParams2为rank-inverse标志(sort sch6同款) | ||
| 1432 | + topkTilingData.set_keyParams2(!isTwoStage ? 0U : (plan.useRankInverse ? 1U : 0U)); | ||
| 1433 | + topkTilingData.set_keyParams4(0U); | ||
| 1434 | + topkTilingData.set_tmpUbSize(isTwoStage ? plan.tmpUbSize : 0U); | ||
| 1435 | + topkTilingData.set_unsortedDimParallel(plan.blockDim); | ||
| 1436 | + topkTilingData.set_sortLoopTimes(1); | ||
| 1437 | + topkTilingData.set_lastDimTileNum(1); | ||
| 1438 | + topkTilingData.set_lastDimNeedCore(1); | ||
| 1439 | +} | ||
| 1440 | + | ||
| 1441 | +/** | ||
| 1442 | + * @brief 填充小轴排序路由的last/非last布局字段 | ||
| 1443 | + * @details 非last轴按模式8同款约定填充unsortedDimNum/oneCoreRowNum并计算innerLoopNum, | ||
| 1444 | + * 再按路由kind将innerLoopNum写入keyParams4(TWO_STAGE)或keyParams2(INSERTION)。 | ||
| 1445 | + * @param topkTilingData TopK Tiling数据结构 | ||
| 1446 | + * @param info 排序Tiling信息 | ||
| 1447 | + * @param plan 已选定的小轴路由方案 | ||
| 1448 | + * @param isTwoStage 是否为TWO_STAGE路由 | ||
| 1449 | + * @return true 表示布局字段填充成功;false 表示innerChunk为0或innerLoop溢出,需回落原有模式 | ||
| 1450 | + */ | ||
| 1451 | +static bool FillTopKSmallAxisAxisLayout(TopKV2TilingDataSimd& topkTilingData, const TopKSmallAxisRouteInfo& info, | ||
| 1452 | + const SmallAxisRoutePlan& plan, bool isTwoStage) | ||
| 1453 | +{ | ||
| 1454 | + uint32_t innerLoopNum = 0U; | ||
| 1455 | + if (info.isNonLastAxis) { | ||
| 1456 | + // 模式8同款约定:unsortedDimNum=innerSize,oneCoreRowNum=outerSize | ||
| 1457 | + uint32_t innerChunk = static_cast<uint32_t>(std::min<int64_t>(plan.batchSize, info.innerSize)); | ||
| 1458 | + if (innerChunk == 0U) { | ||
| 1459 | + return false; | ||
| 1460 | + } | ||
| 1461 | + uint64_t innerLoop = Ops::Base::CeilDiv(static_cast<uint64_t>(info.innerSize), | ||
| 1462 | + static_cast<uint64_t>(innerChunk)); | ||
| 1463 | + if (innerLoop == 0U || innerLoop > static_cast<uint64_t>(std::numeric_limits<uint32_t>::max())) { | ||
| 1464 | + return false; | ||
| 1465 | + } | ||
| 1466 | + innerLoopNum = static_cast<uint32_t>(innerLoop); | ||
| 1467 | + topkTilingData.set_keyParams3(1U); | ||
| 1468 | + topkTilingData.set_unsortedDimNum(static_cast<uint64_t>(info.innerSize)); | ||
| 1469 | + topkTilingData.set_oneCoreRowNum(static_cast<uint64_t>(info.outerSize)); | ||
| 1470 | + } else { | ||
| 1471 | + topkTilingData.set_keyParams3(0U); | ||
| 1472 | + topkTilingData.set_unsortedDimNum(static_cast<uint64_t>(info.unsortedDim)); | ||
| 1473 | + topkTilingData.set_oneCoreRowNum(1U); | ||
| 1474 | + } | ||
| 1475 | + if (isTwoStage) { | ||
| 1476 | + // TWO_STAGE的非last innerLoopNum放在keyParams4(keyParams2已被rank-inverse占用) | ||
| 1477 | + topkTilingData.set_keyParams4(innerLoopNum); | ||
| 1478 | + } else { | ||
| 1479 | + topkTilingData.set_keyParams2(innerLoopNum); | ||
| 1480 | + } | ||
| 1481 | + return true; | ||
| 1482 | +} | ||
| 1483 | + | ||
| 1484 | +/** | ||
| 1485 | + * @brief 设置小轴排序路由的Context参数并保存TilingData | ||
| 1486 | + * @details 依次设置TilingKey/BlockDim/LocalMemorySize/ScheduleMode与workspace, | ||
| 1487 | + * 保存TilingData并打印已选路由的关键参数日志。 | ||
| 1488 | + * @param context Tiling上下文 | ||
| 1489 | + * @param topkTilingData TopK Tiling数据结构 | ||
| 1490 | + * @param computeInfo TopK计算信息 | ||
| 1491 | + * @param info 排序Tiling信息 | ||
| 1492 | + * @param plan 已选定的小轴路由方案 | ||
| 1493 | + * @param dataTypeKey 数据类型对应的Tiling Key | ||
| 1494 | + * @param axis TopK操作的目标轴索引 | ||
| 1495 | + * @param isTwoStage 是否为TWO_STAGE路由 | ||
| 1496 | + * @param useBitonicFinalize 是否追加bitonic确定性终排 | ||
| 1497 | + * @return true 表示已完成Context设置与TilingData保存 | ||
| 1498 | + */ | ||
| 1499 | +static bool FinalizeTopKSmallAxisContext(gert::TilingContext* context, TopKV2TilingDataSimd& topkTilingData, | ||
| 1500 | + const topkV2DataInfo::TopkComputeNowTileSizeInfo& computeInfo, | ||
| 1501 | + const TopKSmallAxisRouteInfo& info, const SmallAxisRoutePlan& plan, | ||
| 1502 | + uint32_t dataTypeKey, int32_t axis, bool isTwoStage, bool useBitonicFinalize) | ||
| 1503 | +{ | ||
| 1504 | + context->SetTilingKey(dataTypeKey); | ||
| 1505 | + context->SetBlockDim(plan.blockDim); | ||
| 1506 | + // SIMT kernel需预留32K(sort路由内部按ubSize-SIMT_UB规划批量,此处LocalMemory同步扣减) | ||
| 1507 | + context->SetLocalMemorySize(computeInfo.ubSizePlatForm); | ||
| 1508 | + context->SetScheduleMode(1); | ||
| 1509 | + size_t* userWorkSpaceSize = context->GetWorkspaceSizes(1); | ||
| 1510 | + OP_CHECK_NULL_WITH_CONTEXT(context, userWorkSpaceSize); | ||
| 1511 | + userWorkSpaceSize[0] = topkV2DataInfo::SYS_WORK_SPACE_SIZE; | ||
| 1512 | + topkTilingData.SaveToBuffer(context->GetRawTilingData()->GetData(), context->GetRawTilingData()->GetCapacity()); | ||
| 1513 | + context->GetRawTilingData()->SetDataSize(topkTilingData.GetDataSize()); | ||
| 1514 | + OP_LOGI(context->GetNodeName(), | ||
| 1515 | + "TopKV2 small-axis %s selected axis=%d axisLen=%ld k=%ld outer=%ld inner=%ld batchSize=%u " | ||
| 1516 | + "batchNum=%u blockDim=%u useRankInverse=%d tmpUbSize=%u bitonicFinalize=%d", | ||
| 1517 | + isTwoStage ? "two-stage" : "insertion", axis, info.lastAxis, computeInfo.kValue, info.outerSize, | ||
| 1518 | + info.innerSize, plan.batchSize, plan.batchNum, plan.blockDim, static_cast<int>(plan.useRankInverse), | ||
| 1519 | + plan.tmpUbSize, static_cast<int>(useBitonicFinalize)); | ||
| 1520 | + return true; | ||
| 1521 | +} | ||
| 1522 | + | ||
| 1523 | +/** | ||
| 1524 | + * @brief 小轴排序路由(复用sort的SmallAxisInsertionBase/SmallAxisTwoStageBase实现) | ||
| 1525 | + * @details 编排层,步骤见各helper | ||
| 1526 | + * @return true 表示已接管并完成Tiling填充;false 表示未命中,需回落原有模式 | ||
| 1527 | + */ | ||
| 1528 | +static bool TryTopKSmallAxisSort(gert::TilingContext* context, TopKV2TilingDataSimd& topkTilingData, | ||
| 1529 | + const topkV2DataInfo::TopkComputeNowTileSizeInfo& computeInfo, | ||
| 1530 | + const gert::Shape& inputShape, int32_t axis, uint32_t dataTypeKey, | ||
| 1531 | + uint64_t originUbSize) | ||
| 1532 | +{ | ||
| 1533 | + // 步骤1:小轴排序仅覆盖小轴;轴长为1或超过小轴阈值时直接回落 | ||
| 1534 | + if (computeInfo.lastAxisNum <= 1 || computeInfo.kValue <= 0 || computeInfo.kValue > computeInfo.lastAxisNum || | ||
| 1535 | + computeInfo.lastAxisNum > static_cast<int64_t>(SMALL_AXIS_THRESHOLD)) { | ||
| 1536 | + return false; | ||
| 1537 | + } | ||
| 1538 | + | ||
| 1539 | + // 步骤2:初始化排序Tiling基础字段并计算轴维乘积 | ||
| 1540 | + TopKSmallAxisRouteInfo info; | ||
| 1541 | + InitTopKSmallAxisTileInfo(info, computeInfo, inputShape, axis, originUbSize); | ||
| 1542 | + | ||
| 1543 | + // 步骤3:选择小轴排序路由,仅接管INSERTION/TWO_STAGE | ||
| 1544 | + SmallAxisRoutePlan plan; | ||
| 1545 | + bool isTwoStage = false; | ||
| 1546 | + if (!SelectTopKSmallAxisRoute(info, plan, isTwoStage)) { | ||
| 1547 | + return false; | ||
| 1548 | + } | ||
| 1549 | + | ||
| 1550 | + // 步骤4:填充公共Tiling字段并判定bitonic终排 | ||
| 1551 | + bool useBitonicFinalize = false; | ||
| 1552 | + FillTopKSmallAxisCommonTiling(topkTilingData, computeInfo, info, plan, isTwoStage, useBitonicFinalize); | ||
| 1553 | + | ||
| 1554 | + // 步骤5:填充last/非last布局字段 | ||
| 1555 | + if (!FillTopKSmallAxisAxisLayout(topkTilingData, info, plan, isTwoStage)) { | ||
| 1556 | + return false; | ||
| 1557 | + } | ||
| 1558 | + | ||
| 1559 | + // keyParams5: bitonic终排标志(policy=1且sorted且k∈[2,32]时置1,kernel侧store前终排) | ||
| 1560 | + topkTilingData.set_keyParams5(useBitonicFinalize ? 1U : 0U); | ||
| 1561 | + | ||
| 1562 | + // 步骤6:设置Context参数并保存TilingData | ||
| 1563 | + return FinalizeTopKSmallAxisContext(context, topkTilingData, computeInfo, info, plan, dataTypeKey, axis, isTwoStage, | ||
| 1564 | + useBitonicFinalize); | ||
| 1565 | +} | ||
| 1566 | + | ||
| 1347 | /** | 1567 | /** |
| 1348 | * @brief 非尾轴小轴TopK模式的Tiling主函数(优化版本,不超过50行) | 1568 | * @brief 非尾轴小轴TopK模式的Tiling主函数(优化版本,不超过50行) |
| 1349 | * @details 该函数通过调用多个辅助函数,完成非尾轴小轴TopK场景的Tiling参数计算。 | 1569 | * @details 该函数通过调用多个辅助函数,完成非尾轴小轴TopK场景的Tiling参数计算。 |
| @@ -1437,14 +1657,17 @@ ge::graphStatus TopKV2Tiling(gert::TilingContext* context, int32_t maxCoreNum) | |||
| 1437 | static_cast<int64_t>(indicesDType)); | 1657 | static_cast<int64_t>(indicesDType)); |
| 1438 | 1658 | ||
| 1439 | const int* sortPolicy = attrs->GetAttrPointer<int>(topkV2DataInfo::SORT_POLICY_ATTR_INDEX); | 1659 | const int* sortPolicy = attrs->GetAttrPointer<int>(topkV2DataInfo::SORT_POLICY_ATTR_INDEX); |
| 1440 | - OP_CHECK_NULL_WITH_CONTEXT(context, sortPolicy); | 1660 | + int sortPolicyValue = 0; |
| 1441 | - OP_LOGD(context->GetNodeName(), "topk sortPolicy=%d.", *sortPolicy); | 1661 | + if (sortPolicy != nullptr) { |
| 1442 | - OP_CHECK_IF(*sortPolicy != 0 && *sortPolicy != 1, | 1662 | + OP_LOGD(context->GetNodeName(), "topk sortPolicy=%d.", *sortPolicy); |
| 1443 | - OP_LOGE_WITH_INVALID_ATTR(context->GetNodeName(), "sort_policy", std::to_string(*sortPolicy).c_str(), | 1663 | + OP_CHECK_IF(*sortPolicy != 0 && *sortPolicy != 1, |
| 1444 | - "range [0, 1]"), | 1664 | + OP_LOGE_WITH_INVALID_ATTR(context->GetNodeName(), "sort_policy", |
| 1445 | - return ge::GRAPH_FAILED); | 1665 | + std::to_string(*sortPolicy).c_str(), "range [0, 1]"), |
| 1666 | + return ge::GRAPH_FAILED); | ||
| 1667 | + sortPolicyValue = *sortPolicy; | ||
| 1668 | + } | ||
| 1446 | // 设置排序策略 | 1669 | // 设置排序策略 |
| 1447 | - topkTilingData.set_sortPolicy(*sortPolicy); | 1670 | + topkTilingData.set_sortPolicy(sortPolicyValue); |
| 1448 | 1671 | ||
| 1449 | // 获取输入张量的维度数量 | 1672 | // 获取输入张量的维度数量 |
| 1450 | size_t inputDimNum = inputShape.GetDimNum(); | 1673 | size_t inputDimNum = inputShape.GetDimNum(); |
| @@ -1519,6 +1742,10 @@ ge::graphStatus TopKV2Tiling(gert::TilingContext* context, int32_t maxCoreNum) | |||
| 1519 | computeNowTileSizeInfo.lastAxisNum = inputShape.GetDim(dimValue); | 1742 | computeNowTileSizeInfo.lastAxisNum = inputShape.GetDim(dimValue); |
| 1520 | computeNowTileSizeInfo.kValue = outShape.GetDim(dimValue); | 1743 | computeNowTileSizeInfo.kValue = outShape.GetDim(dimValue); |
| 1521 | computeNowTileSizeInfo.isInInt32Range = computeNowTileSizeInfo.lastAxisNum <= int32Max; | 1744 | computeNowTileSizeInfo.isInInt32Range = computeNowTileSizeInfo.lastAxisNum <= int32Max; |
| 1745 | + if (TryTopKSmallAxisSort(context, topkTilingData, computeNowTileSizeInfo, inputShape, dimValue, dataTypeKey, | ||
| 1746 | + originUbSizePlatForm)) { | ||
| 1747 | + return ge::GRAPH_SUCCESS; | ||
| 1748 | + } | ||
| 1522 | if (IsBitonicSmallTopkMode(computeNowTileSizeInfo.kValue, topkTilingData.get_sortPolicy(), | 1749 | if (IsBitonicSmallTopkMode(computeNowTileSizeInfo.kValue, topkTilingData.get_sortPolicy(), |
| 1523 | computeNowTileSizeInfo.isSort)) { | 1750 | computeNowTileSizeInfo.isSort)) { |
| 1524 | dataTypeKey += topkV2DataInfo::BITONIC_SORT_TILING_OFFSET; | 1751 | dataTypeKey += topkV2DataInfo::BITONIC_SORT_TILING_OFFSET; |
| @@ -1527,13 +1754,18 @@ ge::graphStatus TopKV2Tiling(gert::TilingContext* context, int32_t maxCoreNum) | |||
| 1527 | dataTypeKey, originUbSizePlatForm); | 1754 | dataTypeKey, originUbSizePlatForm); |
| 1528 | } | 1755 | } |
| 1529 | 1756 | ||
| 1757 | + // 处理尾轴的场景:先尝试小轴排序快路径(复用sort实现),未命中回落现有链路 | ||
| 1758 | + if (TryTopKSmallAxisSort(context, topkTilingData, computeNowTileSizeInfo, inputShape, | ||
| 1759 | + static_cast<int32_t>(inputDimNum) - 1, dataTypeKey, originUbSizePlatForm)) { | ||
| 1760 | + return ge::GRAPH_SUCCESS; | ||
| 1761 | + } | ||
| 1762 | + | ||
| 1530 | // 尾轴场景:kValue 已正确设置为 outLastAxisNum | 1763 | // 尾轴场景:kValue 已正确设置为 outLastAxisNum |
| 1531 | if (IsBitonicSmallTopkMode(computeNowTileSizeInfo.kValue, topkTilingData.get_sortPolicy(), | 1764 | if (IsBitonicSmallTopkMode(computeNowTileSizeInfo.kValue, topkTilingData.get_sortPolicy(), |
| 1532 | computeNowTileSizeInfo.isSort)) { | 1765 | computeNowTileSizeInfo.isSort)) { |
| 1533 | dataTypeKey += topkV2DataInfo::BITONIC_SORT_TILING_OFFSET; | 1766 | dataTypeKey += topkV2DataInfo::BITONIC_SORT_TILING_OFFSET; |
| 1534 | } | 1767 | } |
| 1535 | 1768 | ||
| 1536 | - // 处理尾轴的场景 | ||
| 1537 | if (IsSmallSizeMergeSortMode(dataType, lastAxisNum)) { | 1769 | if (IsSmallSizeMergeSortMode(dataType, lastAxisNum)) { |
| 1538 | TileModeSmallSizeOptim(context, topkTilingData, topkTileInfo, computeNowTileSizeInfo); | 1770 | TileModeSmallSizeOptim(context, topkTilingData, topkTileInfo, computeNowTileSizeInfo); |
| 1539 | dataTypeKey += topkV2DataInfo::MERGE_SORT_TILING_OFFSET; | 1771 | dataTypeKey += topkV2DataInfo::MERGE_SORT_TILING_OFFSET; |
| @@ -15,6 +15,7 @@ | |||
| 15 | #include "top_k_v2_tiling_base.h" | 15 | #include "top_k_v2_tiling_base.h" |
| 16 | 16 | ||
| 17 | #include <algorithm> | 17 | #include <algorithm> |
| 18 | +#include <cmath> | ||
| 18 | #include <string> | 19 | #include <string> |
| 19 | 20 | ||
| 20 | #include "log/log.h" | 21 | #include "log/log.h" |
| @@ -57,6 +58,480 @@ bool CeilAlignUint32(uint64_t rawSize, uint32_t alignSize, uint32_t& alignedSize | |||
| 57 | return true; | 58 | return true; |
| 58 | } | 59 | } |
| 59 | 60 | ||
| 61 | +namespace { | ||
| 62 | + | ||
| 63 | +constexpr uint32_t SMALL_AXIS_MAX_DATACOPY_BLOCK_COUNT = 4095; | ||
| 64 | +constexpr uint32_t TWO_STAGE_RANK_INVERSE_MAX_N = 64; | ||
| 65 | +constexpr uint32_t SMALL_AXIS_TIER_COUNT = 4; | ||
| 66 | +constexpr uint32_t SMALL_AXIS_TIER_WIDTH = 2; | ||
| 67 | +constexpr uint32_t TWO_STAGE_VALUE_BUFFER_COUNT = 2; | ||
| 68 | +constexpr uint32_t TWO_STAGE_RANK_INVERSE_INDEX_BUFFER_COUNT = 2; | ||
| 69 | +constexpr uint32_t TWO_STAGE_RADIX_INDEX_BUFFER_COUNT = 3; | ||
| 70 | + | ||
| 71 | +struct SmallAxisRule { | ||
| 72 | + ge::DataType dtype; | ||
| 73 | + uint32_t insertionMaxN; | ||
| 74 | + uint32_t twoStageMaxN; | ||
| 75 | + uint32_t insertionTiers[SMALL_AXIS_TIER_COUNT][SMALL_AXIS_TIER_WIDTH]; | ||
| 76 | + uint32_t twoStageTiers[SMALL_AXIS_TIER_COUNT][SMALL_AXIS_TIER_WIDTH]; | ||
| 77 | +}; | ||
| 78 | + | ||
| 79 | +// Each tier is {maximum axis length, minimum segments per core}; the values are empirical route thresholds. | ||
| 80 | +constexpr SmallAxisRule SMALL_AXIS_RULES[] = { | ||
| 81 | + {ge::DT_INT64, 16, 512, {{8, 1}, {16, 4}, {0, 0}}, {{15, 8}, {128, 4}, {512, 8}, {0, 0}}}, | ||
| 82 | + {ge::DT_UINT64, 16, 512, {{8, 1}, {16, 4}, {0, 0}}, {{15, 8}, {128, 4}, {512, 8}, {0, 0}}}, | ||
| 83 | + {ge::DT_INT32, 11, 384, {{8, 2}, {11, 4}, {0, 0}}, {{11, 8}, {64, 4}, {384, 8}, {0, 0}}}, | ||
| 84 | + {ge::DT_UINT32, 11, 384, {{8, 2}, {11, 4}, {0, 0}}, {{11, 8}, {64, 4}, {384, 8}, {0, 0}}}, | ||
| 85 | + {ge::DT_INT16, 8, 192, {{4, 2}, {8, 4}, {0, 0}}, {{7, 8}, {64, 4}, {192, 12}, {0, 0}}}, | ||
| 86 | + {ge::DT_UINT16, 8, 192, {{4, 2}, {8, 4}, {0, 0}}, {{7, 8}, {64, 4}, {192, 12}, {0, 0}}}, | ||
| 87 | + {ge::DT_INT8, 8, 128, {{4, 2}, {8, 7}, {0, 0}}, {{3, 8}, {64, 7}, {128, 16}, {0, 0}}}, | ||
| 88 | + {ge::DT_UINT8, 8, 128, {{4, 2}, {8, 7}, {0, 0}}, {{3, 8}, {64, 7}, {128, 16}, {0, 0}}}, | ||
| 89 | + {ge::DT_FLOAT, 8, 24, {{4, 16}, {8, 48}, {0, 0}}, {{24, 64}, {0, 0}}}, | ||
| 90 | + {ge::DT_BF16, 8, 54, {{4, 16}, {8, 48}, {0, 0}}, {{54, 64}, {0, 0}}}, | ||
| 91 | + {ge::DT_FLOAT16, 8, 54, {{4, 16}, {8, 48}, {0, 0}}, {{54, 64}, {0, 0}}}, | ||
| 92 | +}; | ||
| 93 | + | ||
| 94 | +struct TwoStageBatchPlan { | ||
| 95 | + uint32_t batchSize = 0; | ||
| 96 | + uint32_t batchNum = 0; | ||
| 97 | + uint32_t blockDim = 0; | ||
| 98 | + uint32_t tmpUbSize = 0; | ||
| 99 | +}; | ||
| 100 | + | ||
| 101 | +bool CeilDivUint32(uint64_t value, uint64_t divisor, uint32_t& result) | ||
| 102 | +{ | ||
| 103 | + if (divisor == 0U) { | ||
| 104 | + return false; | ||
| 105 | + } | ||
| 106 | + uint64_t quotient = Ops::Base::CeilDiv(value, divisor); | ||
| 107 | + if (quotient > static_cast<uint64_t>(std::numeric_limits<uint32_t>::max())) { | ||
| 108 | + return false; | ||
| 109 | + } | ||
| 110 | + result = static_cast<uint32_t>(quotient); | ||
| 111 | + return true; | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +uint32_t LookupMinSegs(const uint32_t (*tiers)[SMALL_AXIS_TIER_WIDTH], uint32_t axisNum) | ||
| 115 | +{ | ||
| 116 | + for (uint32_t i = 0; i < SMALL_AXIS_TIER_COUNT && tiers[i][0] != 0U; ++i) { | ||
| 117 | + if (axisNum <= tiers[i][0]) { | ||
| 118 | + return tiers[i][1]; | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | + return std::numeric_limits<uint32_t>::max(); | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +const SmallAxisRule* FindSmallAxisRule(ge::DataType dataType) | ||
| 125 | +{ | ||
| 126 | + for (const SmallAxisRule& rule : SMALL_AXIS_RULES) { | ||
| 127 | + if (rule.dtype == dataType) { | ||
| 128 | + return &rule; | ||
| 129 | + } | ||
| 130 | + } | ||
| 131 | + return nullptr; | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +bool UseTwoStageRankInverse(uint32_t axisLen) { return axisLen <= TWO_STAGE_RANK_INVERSE_MAX_N; } | ||
| 135 | + | ||
| 136 | +static bool ComputeBf16InsertionBytesPerSeg(uint32_t axisLen, uint64_t idxBytes, uint32_t blockUbSize, | ||
| 137 | + uint64_t& bytesPerSeg) | ||
| 138 | +{ | ||
| 139 | + uint64_t castRawBytes = 0U; | ||
| 140 | + if (ge::MulOverflow(axisLen, sizeof(int16_t), castRawBytes)) { | ||
| 141 | + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON("ComputeInsertionBytesPerSeg", "axisLen", std::to_string(axisLen).c_str(), | ||
| 142 | + "The value of axisLen must not cause cast raw byte size overflow."); | ||
| 143 | + return false; | ||
| 144 | + } | ||
| 145 | + uint64_t castBytes = Ops::Base::CeilAlign<uint64_t>(castRawBytes, blockUbSize); | ||
| 146 | + if (castBytes == 0U) { | ||
| 147 | + return false; | ||
| 148 | + } | ||
| 149 | + uint64_t castRowElems = castBytes / sizeof(int16_t); | ||
| 150 | + uint64_t valueBytes = 0U; | ||
| 151 | + if (ge::MulOverflow(castRowElems, sizeof(float), valueBytes) || | ||
| 152 | + ge::AddOverflow(valueBytes, idxBytes, bytesPerSeg) || ge::AddOverflow(bytesPerSeg, castBytes, bytesPerSeg)) { | ||
| 153 | + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( | ||
| 154 | + "ComputeInsertionBytesPerSeg", "bytesPerSeg", | ||
| 155 | + (std::to_string(castRowElems) + ", " + std::to_string(idxBytes) + ", " + std::to_string(castBytes)).c_str(), | ||
| 156 | + "The value of bf16 bytesPerSeg must not overflow."); | ||
| 157 | + return false; | ||
| 158 | + } | ||
| 159 | + return true; | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +uint32_t ComputeInsertionBytesPerSeg(ge::DataType dataType, uint32_t axisLen, uint32_t dtypeSize, | ||
| 163 | + uint32_t indexDtypeSize, uint32_t blockUbSize) | ||
| 164 | +{ | ||
| 165 | + uint64_t valueRawBytes = 0U; | ||
| 166 | + uint64_t idxRawBytes = 0U; | ||
| 167 | + if (ge::MulOverflow(axisLen, dtypeSize, valueRawBytes) || ge::MulOverflow(axisLen, indexDtypeSize, idxRawBytes)) { | ||
| 168 | + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON("ComputeInsertionBytesPerSeg", "axisLen", std::to_string(axisLen).c_str(), | ||
| 169 | + "The value of axisLen must not cause raw byte size overflow."); | ||
| 170 | + return 0U; | ||
| 171 | + } | ||
| 172 | + uint64_t valueBytes = Ops::Base::CeilAlign<uint64_t>(valueRawBytes, blockUbSize); | ||
| 173 | + uint64_t idxBytes = Ops::Base::CeilAlign<uint64_t>(idxRawBytes, blockUbSize); | ||
| 174 | + if (valueBytes == 0U || idxBytes == 0U) { | ||
| 175 | + return 0U; | ||
| 176 | + } | ||
| 177 | + uint64_t bytesPerSeg = 0U; | ||
| 178 | + if (ge::AddOverflow(valueBytes, idxBytes, bytesPerSeg)) { | ||
| 179 | + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON("ComputeInsertionBytesPerSeg", "bytesPerSeg", | ||
| 180 | + (std::to_string(valueBytes) + ", " + std::to_string(idxBytes)).c_str(), | ||
| 181 | + "The value of valueBytes plus idxBytes must not overflow."); | ||
| 182 | + return 0U; | ||
| 183 | + } | ||
| 184 | + if (dataType == ge::DT_BF16 && !ComputeBf16InsertionBytesPerSeg(axisLen, idxBytes, blockUbSize, bytesPerSeg)) { | ||
| 185 | + return 0U; | ||
| 186 | + } | ||
| 187 | + if (bytesPerSeg > static_cast<uint64_t>(std::numeric_limits<uint32_t>::max())) { | ||
| 188 | + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON("ComputeInsertionBytesPerSeg", "bytesPerSeg", | ||
| 189 | + std::to_string(bytesPerSeg).c_str(), | ||
| 190 | + "The value of bytesPerSeg must be less than or equal to uint32 max."); | ||
| 191 | + return 0U; | ||
| 192 | + } | ||
| 193 | + return static_cast<uint32_t>(bytesPerSeg); | ||
| 194 | +} | ||
| 195 | + | ||
| 196 | +static bool ComputeNonLastBatchNum(int64_t outerSize, int64_t innerSize, uint32_t innerChunk, uint32_t& batchNum) | ||
| 197 | +{ | ||
| 198 | + if (outerSize <= 0 || innerSize <= 0 || innerChunk == 0U) { | ||
| 199 | + return false; | ||
| 200 | + } | ||
| 201 | + uint32_t innerLoop = 0U; | ||
| 202 | + if (!CeilDivUint32(static_cast<uint64_t>(innerSize), static_cast<uint64_t>(innerChunk), innerLoop)) { | ||
| 203 | + return false; | ||
| 204 | + } | ||
| 205 | + uint64_t batchNum64 = static_cast<uint64_t>(outerSize) * static_cast<uint64_t>(innerLoop); | ||
| 206 | + if (batchNum64 == 0U || batchNum64 > static_cast<uint64_t>(std::numeric_limits<uint32_t>::max())) { | ||
| 207 | + return false; | ||
| 208 | + } | ||
| 209 | + batchNum = static_cast<uint32_t>(batchNum64); | ||
| 210 | + return true; | ||
| 211 | +} | ||
| 212 | + | ||
| 213 | +bool QuerySortTmpSizeRadix(ge::DataType dataType, uint32_t sortAxisNum, uint32_t& tmpUbSize) | ||
| 214 | +{ | ||
| 215 | + std::vector<int64_t> shapeVec = {static_cast<int64_t>(sortAxisNum)}; | ||
| 216 | + ge::Shape srcShape(shapeVec); | ||
| 217 | + AscendC::SortConfig config; | ||
| 218 | + config.type = AscendC::SortType::RADIX_SORT; | ||
| 219 | + config.isDescend = false; | ||
| 220 | + config.hasSrcIndex = false; | ||
| 221 | + config.hasDstIndex = true; | ||
| 222 | + uint32_t maxValue = 0U; | ||
| 223 | + uint32_t minValue = 0U; | ||
| 224 | + AscendC::GetSortMaxMinTmpSize(srcShape, dataType, ge::DT_UINT32, false, config, maxValue, minValue); | ||
| 225 | + tmpUbSize = maxValue; | ||
| 226 | + return maxValue > 0U; | ||
| 227 | +} | ||
| 228 | + | ||
| 229 | +uint32_t MaxTwoStageU16SafeBatch(uint32_t axisLen) | ||
| 230 | +{ | ||
| 231 | + if (axisLen == 0U || axisLen > static_cast<uint32_t>(std::numeric_limits<uint16_t>::max())) { | ||
| 232 | + return 0U; | ||
| 233 | + } | ||
| 234 | + uint32_t maxBatch = static_cast<uint32_t>( | ||
| 235 | + std::sqrt(static_cast<double>(std::numeric_limits<uint16_t>::max()) / axisLen)); | ||
| 236 | + while (static_cast<uint64_t>(maxBatch) * maxBatch * axisLen > | ||
| 237 | + static_cast<uint64_t>(std::numeric_limits<uint16_t>::max())) { | ||
| 238 | + --maxBatch; | ||
| 239 | + } | ||
| 240 | + while (static_cast<uint64_t>(maxBatch + 1U) * (maxBatch + 1U) * axisLen <= | ||
| 241 | + static_cast<uint64_t>(std::numeric_limits<uint16_t>::max())) { | ||
| 242 | + ++maxBatch; | ||
| 243 | + } | ||
| 244 | + return maxBatch; | ||
| 245 | +} | ||
| 246 | + | ||
| 247 | +bool ComputeTwoStageSortTmpUb(ge::DataType dataType, uint32_t axisLen, uint32_t totalElems, uint32_t blockUbSize, | ||
| 248 | + uint32_t& tmpUbSize) | ||
| 249 | +{ | ||
| 250 | + tmpUbSize = 0U; | ||
| 251 | + QuerySortTmpSizeRadix(dataType, totalElems, tmpUbSize); | ||
| 252 | + uint32_t aligned = 0U; | ||
| 253 | + if (!CeilAlignUint32(tmpUbSize, blockUbSize, aligned)) { | ||
| 254 | + return false; | ||
| 255 | + } | ||
| 256 | + tmpUbSize = aligned; | ||
| 257 | + bool useRankInverse = UseTwoStageRankInverse(axisLen); | ||
| 258 | + if (!useRankInverse) { | ||
| 259 | + uint32_t stage2TmpUbSize = 0U; | ||
| 260 | + QuerySortTmpSizeRadix(ge::DT_UINT16, totalElems, stage2TmpUbSize); | ||
| 261 | + uint32_t stage2Aligned = 0U; | ||
| 262 | + if (!CeilAlignUint32(stage2TmpUbSize, blockUbSize, stage2Aligned)) { | ||
| 263 | + return false; | ||
| 264 | + } | ||
| 265 | + tmpUbSize = std::max(tmpUbSize, stage2Aligned); | ||
| 266 | + } | ||
| 267 | + return true; | ||
| 268 | +} | ||
| 269 | + | ||
| 270 | +uint64_t EstimateTwoStageUbBytes(const TopKSmallAxisRouteInfo& info, uint32_t totalElems, uint32_t sortTmpUb) | ||
| 271 | +{ | ||
| 272 | + uint64_t valueRawBytes = 0U; | ||
| 273 | + uint64_t idxRawBytes = 0U; | ||
| 274 | + uint64_t finalIdxRawBytes = 0U; | ||
| 275 | + if (ge::MulOverflow(totalElems, info.dtypeSize, valueRawBytes) || | ||
| 276 | + ge::MulOverflow(totalElems, sizeof(uint32_t), idxRawBytes) || | ||
| 277 | + ge::MulOverflow(totalElems, info.y2DtypeSize, finalIdxRawBytes)) { | ||
| 278 | + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON("EstimateTwoStageUbBytes", "totalElems", | ||
| 279 | + std::to_string(totalElems).c_str(), | ||
| 280 | + "The value of totalElems must not cause raw byte size overflow."); | ||
| 281 | + return std::numeric_limits<uint64_t>::max(); | ||
| 282 | + } | ||
| 283 | + uint64_t valueBytes = Ops::Base::CeilAlign<uint64_t>(valueRawBytes, info.blockUbSize); | ||
| 284 | + uint64_t idxBytes = Ops::Base::CeilAlign<uint64_t>(idxRawBytes, info.blockUbSize); | ||
| 285 | + uint64_t finalIdxBytes = Ops::Base::CeilAlign<uint64_t>(finalIdxRawBytes, info.blockUbSize); | ||
| 286 | + if (valueBytes == 0U || idxBytes == 0U || finalIdxBytes == 0U) { | ||
| 287 | + return std::numeric_limits<uint64_t>::max(); | ||
| 288 | + } | ||
| 289 | + uint32_t idxBufferCount = UseTwoStageRankInverse(static_cast<uint32_t>(info.lastAxis)) ? | ||
| 290 | + TWO_STAGE_RANK_INVERSE_INDEX_BUFFER_COUNT : | ||
| 291 | + TWO_STAGE_RADIX_INDEX_BUFFER_COUNT; | ||
| 292 | + uint64_t totalBytes = 0U; | ||
| 293 | + uint64_t idxTotalBytes = 0U; | ||
| 294 | + if (ge::MulOverflow(valueBytes, TWO_STAGE_VALUE_BUFFER_COUNT, totalBytes) || | ||
| 295 | + ge::MulOverflow(idxBytes, idxBufferCount, idxTotalBytes) || | ||
| 296 | + ge::AddOverflow(totalBytes, idxTotalBytes, totalBytes) || | ||
| 297 | + ge::AddOverflow(totalBytes, finalIdxBytes, totalBytes) || ge::AddOverflow(totalBytes, sortTmpUb, totalBytes)) { | ||
| 298 | + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( | ||
| 299 | + "EstimateTwoStageUbBytes", "totalBytes", | ||
| 300 | + (std::to_string(valueBytes) + ", " + std::to_string(idxBytes) + ", " + std::to_string(idxBufferCount) + | ||
| 301 | + ", " + std::to_string(finalIdxBytes) + ", " + std::to_string(sortTmpUb)) | ||
| 302 | + .c_str(), | ||
| 303 | + "The value of totalBytes must not overflow."); | ||
| 304 | + return std::numeric_limits<uint64_t>::max(); | ||
| 305 | + } | ||
| 306 | + return totalBytes; | ||
| 307 | +} | ||
| 308 | + | ||
| 309 | +bool PrepareTwoStageBatchCandidate(const TopKSmallAxisRouteInfo& info, uint32_t candidate, uint32_t& totalElems, | ||
| 310 | + uint32_t& tmpUbSize, bool& useRankInverse, uint64_t& totalBytes) | ||
| 311 | +{ | ||
| 312 | + uint32_t axisLen = static_cast<uint32_t>(info.lastAxis); | ||
| 313 | + uint64_t totalElems64 = static_cast<uint64_t>(candidate) * axisLen; | ||
| 314 | + if (totalElems64 > std::numeric_limits<uint32_t>::max()) { | ||
| 315 | + return false; | ||
| 316 | + } | ||
| 317 | + totalElems = static_cast<uint32_t>(totalElems64); | ||
| 318 | + tmpUbSize = 0U; | ||
| 319 | + if (!ComputeTwoStageSortTmpUb(info.dataType, axisLen, totalElems, info.blockUbSize, tmpUbSize)) { | ||
| 320 | + return false; | ||
| 321 | + } | ||
| 322 | + useRankInverse = UseTwoStageRankInverse(axisLen); | ||
| 323 | + totalBytes = EstimateTwoStageUbBytes(info, totalElems, tmpUbSize); | ||
| 324 | + return true; | ||
| 325 | +} | ||
| 326 | + | ||
| 327 | +bool SearchTwoStageBatchPlan(uint32_t maxBatch, std::function<bool(uint32_t, TwoStageBatchPlan&)> tryCandidate, | ||
| 328 | + TwoStageBatchPlan& result) | ||
| 329 | +{ | ||
| 330 | + if (maxBatch == 0U) { | ||
| 331 | + return false; | ||
| 332 | + } | ||
| 333 | + TwoStageBatchPlan maxPlan; | ||
| 334 | + TwoStageBatchPlan bestPlan; | ||
| 335 | + bool hasMaxPlan = false; | ||
| 336 | + uint32_t maxPlanBatchesPerCore = 0U; | ||
| 337 | + uint64_t bestIdleSlots = std::numeric_limits<uint64_t>::max(); | ||
| 338 | + for (uint32_t candidate = maxBatch; candidate >= 1U; --candidate) { | ||
| 339 | + TwoStageBatchPlan candidatePlan; | ||
| 340 | + if (!tryCandidate(candidate, candidatePlan)) { | ||
| 341 | + continue; | ||
| 342 | + } | ||
| 343 | + if (!hasMaxPlan) { | ||
| 344 | + maxPlan = candidatePlan; | ||
| 345 | + hasMaxPlan = true; | ||
| 346 | + maxPlanBatchesPerCore = Ops::Base::CeilDiv(maxPlan.batchNum, maxPlan.blockDim); | ||
| 347 | + bestPlan = maxPlan; | ||
| 348 | + bestIdleSlots = static_cast<uint64_t>(maxPlanBatchesPerCore) * maxPlan.blockDim - maxPlan.batchNum; | ||
| 349 | + continue; | ||
| 350 | + } | ||
| 351 | + uint32_t batchesPerCore = Ops::Base::CeilDiv(candidatePlan.batchNum, candidatePlan.blockDim); | ||
| 352 | + if (batchesPerCore != maxPlanBatchesPerCore) { | ||
| 353 | + break; | ||
| 354 | + } | ||
| 355 | + uint64_t idleSlots = static_cast<uint64_t>(batchesPerCore) * candidatePlan.blockDim - candidatePlan.batchNum; | ||
| 356 | + if (idleSlots < bestIdleSlots) { | ||
| 357 | + bestPlan = candidatePlan; | ||
| 358 | + bestIdleSlots = idleSlots; | ||
| 359 | + } | ||
| 360 | + } | ||
| 361 | + if (!hasMaxPlan) { | ||
| 362 | + return false; | ||
| 363 | + } | ||
| 364 | + result = bestPlan; | ||
| 365 | + return true; | ||
| 366 | +} | ||
| 367 | + | ||
| 368 | +static bool ComputeSmallAxisInsertionBatchParams(const TopKSmallAxisRouteInfo& info, uint32_t axisLen, | ||
| 369 | + uint32_t& bytesPerSeg, uint32_t& usableUb, uint32_t& maxBatchByUb) | ||
| 370 | +{ | ||
| 371 | + if (info.ubSize <= topkV2DataInfo::SIMT_UB) { | ||
| 372 | + return false; | ||
| 373 | + } | ||
| 374 | + bytesPerSeg = ComputeInsertionBytesPerSeg(info.dataType, axisLen, info.dtypeSize, info.y2DtypeSize, | ||
| 375 | + info.blockUbSize); | ||
| 376 | + if (bytesPerSeg == 0U) { | ||
| 377 | + return false; | ||
| 378 | + } | ||
| 379 | + usableUb = info.ubSize - topkV2DataInfo::SIMT_UB; | ||
| 380 | + maxBatchByUb = usableUb / bytesPerSeg; | ||
| 381 | + return true; | ||
| 382 | +} | ||
| 383 | + | ||
| 384 | +template <typename ComputeBatchNumFn> | ||
| 385 | +static bool EstimateSmallAxisInsertionBatching(const TopKSmallAxisRouteInfo& info, uint32_t batchSizeCap, | ||
| 386 | + ComputeBatchNumFn computeBatchNum, SmallAxisRoutePlan& plan) | ||
| 387 | +{ | ||
| 388 | + uint32_t axisLen = static_cast<uint32_t>(info.lastAxis); | ||
| 389 | + uint32_t bytesPerSeg = 0U; | ||
| 390 | + uint32_t usableUb = 0U; | ||
| 391 | + uint32_t maxBatchByUb = 0U; | ||
| 392 | + if (!ComputeSmallAxisInsertionBatchParams(info, axisLen, bytesPerSeg, usableUb, maxBatchByUb) || | ||
| 393 | + maxBatchByUb == 0U) { | ||
| 394 | + return false; | ||
| 395 | + } | ||
| 396 | + uint32_t batchSize = std::min({batchSizeCap, maxBatchByUb, SMALL_AXIS_MAX_DATACOPY_BLOCK_COUNT}); | ||
| 397 | + if (batchSize == 0U) { | ||
| 398 | + return false; | ||
| 399 | + } | ||
| 400 | + plan.batchSize = batchSize; | ||
| 401 | + if (!computeBatchNum(batchSize, plan.batchNum)) { | ||
| 402 | + return false; | ||
| 403 | + } | ||
| 404 | + plan.blockDim = std::min(info.maxCoreNum, plan.batchNum); | ||
| 405 | + return plan.batchNum > 0U && plan.blockDim > 0U; | ||
| 406 | +} | ||
| 407 | + | ||
| 408 | +template <typename ComputeBatchNumFn> | ||
| 409 | +static bool TrySmallAxisTwoStageBatchCandidate(const TopKSmallAxisRouteInfo& info, uint32_t candidate, | ||
| 410 | + ComputeBatchNumFn computeBatchNum, SmallAxisRoutePlan& plan) | ||
| 411 | +{ | ||
| 412 | + // Reject candidates unsupported by the batch mapping before querying Sort temporary UB. | ||
| 413 | + plan.batchSize = candidate; | ||
| 414 | + if (!computeBatchNum(candidate, plan.batchNum)) { | ||
| 415 | + return false; | ||
| 416 | + } | ||
| 417 | + uint32_t totalElems = 0U; | ||
| 418 | + uint32_t tmpUbSize = 0U; | ||
| 419 | + bool useRankInverse = false; | ||
| 420 | + uint64_t totalBytes = 0U; | ||
| 421 | + if (!PrepareTwoStageBatchCandidate(info, candidate, totalElems, tmpUbSize, useRankInverse, totalBytes)) { | ||
| 422 | + return false; | ||
| 423 | + } | ||
| 424 | + if (totalBytes + topkV2DataInfo::SIMT_UB > info.ubSize) { | ||
| 425 | + return false; | ||
| 426 | + } | ||
| 427 | + plan.blockDim = std::min(info.maxCoreNum, plan.batchNum); | ||
| 428 | + plan.tmpUbSize = tmpUbSize; | ||
| 429 | + plan.useRankInverse = useRankInverse; | ||
| 430 | + return plan.batchNum > 0U && plan.blockDim > 0U; | ||
| 431 | +} | ||
| 432 | + | ||
| 433 | +template <typename ComputeBatchNumFn> | ||
| 434 | +static bool EstimateSmallAxisTwoStageBatching(const TopKSmallAxisRouteInfo& info, uint32_t batchSizeCap, | ||
| 435 | + ComputeBatchNumFn computeBatchNum, SmallAxisRoutePlan& plan) | ||
| 436 | +{ | ||
| 437 | + uint32_t axisLen = static_cast<uint32_t>(info.lastAxis); | ||
| 438 | + if (info.ubSize <= topkV2DataInfo::SIMT_UB || axisLen == 0U || batchSizeCap == 0U) { | ||
| 439 | + return false; | ||
| 440 | + } | ||
| 441 | + bool useRankInverse = UseTwoStageRankInverse(axisLen); | ||
| 442 | + uint32_t idxBufferCount = useRankInverse ? TWO_STAGE_RANK_INVERSE_INDEX_BUFFER_COUNT : | ||
| 443 | + TWO_STAGE_RADIX_INDEX_BUFFER_COUNT; | ||
| 444 | + uint64_t minBytesPerElem = static_cast<uint64_t>(info.dtypeSize) * TWO_STAGE_VALUE_BUFFER_COUNT + | ||
| 445 | + static_cast<uint64_t>(sizeof(uint32_t)) * idxBufferCount + info.y2DtypeSize; | ||
| 446 | + uint64_t maxElemsByUb = (info.ubSize - topkV2DataInfo::SIMT_UB) / minBytesPerElem; | ||
| 447 | + uint64_t maxBatchByUb = maxElemsByUb / axisLen; | ||
| 448 | + uint32_t maxBatch = static_cast<uint32_t>(std::min<uint64_t>(static_cast<uint64_t>(batchSizeCap), maxBatchByUb)); | ||
| 449 | + if (!useRankInverse) { | ||
| 450 | + maxBatch = std::min(maxBatch, MaxTwoStageU16SafeBatch(axisLen)); | ||
| 451 | + } | ||
| 452 | + | ||
| 453 | + TwoStageBatchPlan result; | ||
| 454 | + auto tryCandidate = [&info, &computeBatchNum](uint32_t candidate, TwoStageBatchPlan& candidatePlan) -> bool { | ||
| 455 | + SmallAxisRoutePlan routePlan; | ||
| 456 | + if (!TrySmallAxisTwoStageBatchCandidate(info, candidate, computeBatchNum, routePlan)) { | ||
| 457 | + return false; | ||
| 458 | + } | ||
| 459 | + candidatePlan.batchSize = routePlan.batchSize; | ||
| 460 | + candidatePlan.batchNum = routePlan.batchNum; | ||
| 461 | + candidatePlan.blockDim = routePlan.blockDim; | ||
| 462 | + candidatePlan.tmpUbSize = routePlan.tmpUbSize; | ||
| 463 | + return true; | ||
| 464 | + }; | ||
| 465 | + if (!SearchTwoStageBatchPlan(maxBatch, tryCandidate, result)) { | ||
| 466 | + return false; | ||
| 467 | + } | ||
| 468 | + plan.batchSize = result.batchSize; | ||
| 469 | + plan.batchNum = result.batchNum; | ||
| 470 | + plan.blockDim = result.blockDim; | ||
| 471 | + plan.tmpUbSize = result.tmpUbSize; | ||
| 472 | + plan.useRankInverse = useRankInverse; | ||
| 473 | + return true; | ||
| 474 | +} | ||
| 475 | + | ||
| 476 | +static bool SelectSmallAxisRouteImpl(const TopKSmallAxisRouteInfo& info, uint32_t batchSizeCap, | ||
| 477 | + std::function<bool(uint32_t, uint32_t&)> computeBatchNum, SmallAxisRoutePlan& plan) | ||
| 478 | +{ | ||
| 479 | + uint32_t axisLen = static_cast<uint32_t>(info.lastAxis); | ||
| 480 | + if (axisLen <= 1U) { | ||
| 481 | + return false; | ||
| 482 | + } | ||
| 483 | + const SmallAxisRule* rule = FindSmallAxisRule(info.dataType); | ||
| 484 | + if (rule == nullptr) { | ||
| 485 | + return false; | ||
| 486 | + } | ||
| 487 | + uint32_t fullCoreSegs = 0U; | ||
| 488 | + if (!CeilDivUint32(static_cast<uint64_t>(info.unsortedDim), static_cast<uint64_t>(info.maxCoreNum), fullCoreSegs)) { | ||
| 489 | + return false; | ||
| 490 | + } | ||
| 491 | + SmallAxisRoutePlan twoStagePlan; | ||
| 492 | + if (rule->twoStageMaxN > 0U && axisLen <= rule->twoStageMaxN && axisLen <= SMALL_AXIS_THRESHOLD && | ||
| 493 | + fullCoreSegs >= LookupMinSegs(rule->twoStageTiers, axisLen) && | ||
| 494 | + EstimateSmallAxisTwoStageBatching(info, batchSizeCap, computeBatchNum, twoStagePlan)) { | ||
| 495 | + plan = twoStagePlan; | ||
| 496 | + plan.kind = SmallAxisRouteKind::TWO_STAGE; | ||
| 497 | + return true; | ||
| 498 | + } | ||
| 499 | + if (axisLen > rule->insertionMaxN || fullCoreSegs < LookupMinSegs(rule->insertionTiers, axisLen)) { | ||
| 500 | + return false; | ||
| 501 | + } | ||
| 502 | + SmallAxisRoutePlan insertionPlan; | ||
| 503 | + if (!EstimateSmallAxisInsertionBatching(info, batchSizeCap, computeBatchNum, insertionPlan)) { | ||
| 504 | + return false; | ||
| 505 | + } | ||
| 506 | + plan = insertionPlan; | ||
| 507 | + plan.kind = SmallAxisRouteKind::INSERTION; | ||
| 508 | + return true; | ||
| 509 | +} | ||
| 510 | + | ||
| 511 | +} // namespace | ||
| 512 | + | ||
| 513 | +bool SelectSmallAxisRoute(const TopKSmallAxisRouteInfo& info, SmallAxisRoutePlan& plan) | ||
| 514 | +{ | ||
| 515 | + uint32_t fullCoreSegs = 0U; | ||
| 516 | + if (!CeilDivUint32(static_cast<uint64_t>(info.unsortedDim), static_cast<uint64_t>(info.maxCoreNum), fullCoreSegs)) { | ||
| 517 | + return false; | ||
| 518 | + } | ||
| 519 | + auto computeBatchNum = [&info](uint32_t batchSize, uint32_t& batchNum) -> bool { | ||
| 520 | + return CeilDivUint32(static_cast<uint64_t>(info.unsortedDim), batchSize, batchNum); | ||
| 521 | + }; | ||
| 522 | + return SelectSmallAxisRouteImpl(info, fullCoreSegs, computeBatchNum, plan); | ||
| 523 | +} | ||
| 524 | + | ||
| 525 | +bool SelectNonLastSmallAxisRoute(const TopKSmallAxisRouteInfo& info, SmallAxisRoutePlan& plan) | ||
| 526 | +{ | ||
| 527 | + uint32_t batchSizeCap = static_cast<uint32_t>( | ||
| 528 | + std::min<int64_t>(info.innerSize, static_cast<int64_t>(std::numeric_limits<uint32_t>::max()))); | ||
| 529 | + auto computeBatchNum = [&info](uint32_t batchSize, uint32_t& batchNum) -> bool { | ||
| 530 | + return ComputeNonLastBatchNum(info.outerSize, info.innerSize, batchSize, batchNum); | ||
| 531 | + }; | ||
| 532 | + return SelectSmallAxisRouteImpl(info, batchSizeCap, computeBatchNum, plan); | ||
| 533 | +} | ||
| 534 | + | ||
| 60 | // ==================== FP32 MergeSort Helpers ==================== | 535 | // ==================== FP32 MergeSort Helpers ==================== |
| 61 | 536 | ||
| 62 | uint32_t AlignTopkMergeMoreCoreWorkspaceElems(int64_t elementNum) | 537 | uint32_t AlignTopkMergeMoreCoreWorkspaceElems(int64_t elementNum) |
| @@ -15,6 +15,7 @@ | |||
| 15 | #ifndef TOP_K_V2_TILING_BASE_H | 15 | #ifndef TOP_K_V2_TILING_BASE_H |
| 16 | #define TOP_K_V2_TILING_BASE_H | 16 | #define TOP_K_V2_TILING_BASE_H |
| 17 | 17 | ||
| 18 | +#include <cstdint> | ||
| 18 | #include <functional> | 19 | #include <functional> |
| 19 | #include <limits> | 20 | #include <limits> |
| 20 | #include <map> | 21 | #include <map> |
| @@ -30,7 +31,6 @@ namespace topkV2DataInfo { | |||
| 30 | const uint32_t CONST_ZERO = 0; | 31 | const uint32_t CONST_ZERO = 0; |
| 31 | const uint32_t CONST_TWO = 2; | 32 | const uint32_t CONST_TWO = 2; |
| 32 | const uint32_t CONST_THREE = 3; | 33 | const uint32_t CONST_THREE = 3; |
| 33 | -// TopKV2属性在IR中的索引,顺序与config json中attrs定义一致: sorted/dim/largest/indices_dtype/sort_policy | ||
| 34 | const uint32_t SORTED_ATTR_INDEX = 0; | 34 | const uint32_t SORTED_ATTR_INDEX = 0; |
| 35 | const uint32_t DIM_ATTR_INDEX = 1; | 35 | const uint32_t DIM_ATTR_INDEX = 1; |
| 36 | const uint32_t LARGEST_ATTR_INDEX = 2; | 36 | const uint32_t LARGEST_ATTR_INDEX = 2; |
| @@ -62,6 +62,8 @@ const uint32_t FP32_MERGE_INTRA_CORE_MODE = 7; | |||
| 62 | const uint32_t NON_LAST_SMALL_AXIS_MODE = 8; | 62 | const uint32_t NON_LAST_SMALL_AXIS_MODE = 8; |
| 63 | const uint32_t NON_LAST_SMALL_AXIS_RADIX_SELECT = 0; | 63 | const uint32_t NON_LAST_SMALL_AXIS_RADIX_SELECT = 0; |
| 64 | const uint32_t NON_LAST_SMALL_AXIS_MERGE_SORT = 1; | 64 | const uint32_t NON_LAST_SMALL_AXIS_MERGE_SORT = 1; |
| 65 | +const uint32_t SMALL_AXIS_INSERTION_MODE = 9; | ||
| 66 | +const uint32_t SMALL_AXIS_TWO_STAGE_MODE = 10; | ||
| 65 | const uint32_t INT64_BYTE = 8; | 67 | const uint32_t INT64_BYTE = 8; |
| 66 | const uint32_t INT32_BYTE = 4; | 68 | const uint32_t INT32_BYTE = 4; |
| 67 | // SortAndTopk的阈值,排序轴大于该阈值的场景,走sortAndTopK模板 | 69 | // SortAndTopk的阈值,排序轴大于该阈值的场景,走sortAndTopK模板 |
| @@ -179,6 +181,37 @@ inline const std::map<ge::DataType, uint32_t> optDataTypeBitMap = { | |||
| 179 | inline const std::map<ge::DataType, uint32_t> b64DataTypeBitMap = {{ge::DT_INT64, 8}, {ge::DT_UINT64, 8}}; | 181 | inline const std::map<ge::DataType, uint32_t> b64DataTypeBitMap = {{ge::DT_INT64, 8}, {ge::DT_UINT64, 8}}; |
| 180 | } // namespace topkV2DataInfo | 182 | } // namespace topkV2DataInfo |
| 181 | 183 | ||
| 184 | +// Small-axis routing used by the TopKV2 insertion and two-stage kernels. | ||
| 185 | +constexpr uint32_t SMALL_AXIS_THRESHOLD = 512; | ||
| 186 | + | ||
| 187 | +enum class SmallAxisRouteKind : uint8_t { NONE = 0, INSERTION, TWO_STAGE }; | ||
| 188 | + | ||
| 189 | +struct SmallAxisRoutePlan { | ||
| 190 | + SmallAxisRouteKind kind = SmallAxisRouteKind::NONE; | ||
| 191 | + uint32_t batchSize = 0; | ||
| 192 | + uint32_t batchNum = 0; | ||
| 193 | + uint32_t blockDim = 0; | ||
| 194 | + uint32_t tmpUbSize = 0; | ||
| 195 | + bool useRankInverse = false; | ||
| 196 | +}; | ||
| 197 | + | ||
| 198 | +struct TopKSmallAxisRouteInfo { | ||
| 199 | + uint32_t ubSize = 0; | ||
| 200 | + uint32_t blockUbSize = 0; | ||
| 201 | + uint32_t dtypeSize = 0; | ||
| 202 | + uint32_t y2DtypeSize = 0; | ||
| 203 | + uint32_t maxCoreNum = 0; | ||
| 204 | + ge::DataType dataType = ge::DT_UINT8; | ||
| 205 | + bool isNonLastAxis = false; | ||
| 206 | + int64_t lastAxis = 1; | ||
| 207 | + int64_t unsortedDim = 1; | ||
| 208 | + int64_t outerSize = 1; | ||
| 209 | + int64_t innerSize = 1; | ||
| 210 | +}; | ||
| 211 | + | ||
| 212 | +bool SelectSmallAxisRoute(const TopKSmallAxisRouteInfo& info, SmallAxisRoutePlan& plan); | ||
| 213 | +bool SelectNonLastSmallAxisRoute(const TopKSmallAxisRouteInfo& info, SmallAxisRoutePlan& plan); | ||
| 214 | + | ||
| 182 | struct TopkNonLastSmallAxisTileInfo { | 215 | struct TopkNonLastSmallAxisTileInfo { |
| 183 | int64_t rank = 0; | 216 | int64_t rank = 0; |
| 184 | int64_t sortAxis = 0; | 217 | int64_t sortAxis = 0; |
| @@ -0,0 +1,286 @@ | |||
| 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 top_k_small_axis_insertion_base.h | ||
| 13 | + * \brief SIMT kernels and constants for the top_k_v2 small_axis_insertion kernel. | ||
| 14 | + * Self-owned copy of the insertion-sort base, decoupled from the sort-side | ||
| 15 | + * small_axis_insertion_base.h. | ||
| 16 | + */ | ||
| 17 | + | ||
| 18 | +#ifndef TOP_K_SMALL_AXIS_INSERTION_BASE_H | ||
| 19 | +#define TOP_K_SMALL_AXIS_INSERTION_BASE_H | ||
| 20 | + | ||
| 21 | +#include <type_traits> | ||
| 22 | + | ||
| 23 | +#include "kernel_operator.h" | ||
| 24 | +#include "op_kernel/platform_util.h" | ||
| 25 | +#include "simt_api/asc_simt.h" | ||
| 26 | +#include "../top_k_util_type_simd.h" | ||
| 27 | + | ||
| 28 | +namespace TopKSmallAxis { | ||
| 29 | +using namespace AscendC; | ||
| 30 | +using namespace topkV2; | ||
| 31 | + | ||
| 32 | +constexpr uint32_t INSERTION_THREAD_NUM = 1024; | ||
| 33 | +// DataCopy hardware limit for blockCount (batch mode max segments per transfer). | ||
| 34 | +constexpr uint32_t MAX_DATACOPY_BLOCK_COUNT = 4095; | ||
| 35 | + | ||
| 36 | +struct TopKCandidateOrder { | ||
| 37 | + // TopK candidate-selection semantics: floating-point NaNs are | ||
| 38 | + // treated as the largest value and join the candidate ordering; -0.0 sorts | ||
| 39 | + // strictly before +0.0. | ||
| 40 | + static constexpr bool kOrderNan = true; | ||
| 41 | + static constexpr bool kOrderSignedZero = true; | ||
| 42 | +}; | ||
| 43 | + | ||
| 44 | +/** | ||
| 45 | + * @brief SIMT gather kernel for non-last-axis insertion-sort batches. | ||
| 46 | + * @tparam T Input storage data type | ||
| 47 | + */ | ||
| 48 | +template <typename T> | ||
| 49 | +__simt_vf__ LAUNCH_BOUND(INSERTION_THREAD_NUM) __aicore__ | ||
| 50 | + void SimtLoadNonLastInsertionBatch(uint32_t totalElems, uint32_t validSegs, uint32_t segmentLen, | ||
| 51 | + uint32_t valueRowElems, uint64_t outerBaseOffset, uint64_t innerStart, | ||
| 52 | + uint64_t innerSize, __gm__ volatile T* input, __ubuf__ T* output) | ||
| 53 | +{ | ||
| 54 | + // Load a non-last-axis tile as sort-major segments: | ||
| 55 | + // GM [axis, inner] -> UB [inner segment, axis]. | ||
| 56 | + for (uint32_t idx = static_cast<uint32_t>(threadIdx.x); idx < totalElems; idx += INSERTION_THREAD_NUM) { | ||
| 57 | + uint32_t axis = idx / validSegs; | ||
| 58 | + uint32_t seg = idx - axis * validSegs; | ||
| 59 | + output[seg * valueRowElems + axis] = input[outerBaseOffset + static_cast<uint64_t>(axis) * innerSize + | ||
| 60 | + innerStart + seg]; | ||
| 61 | + } | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +/** | ||
| 65 | + * @brief Decide whether the previous slot must move after the key in one insertion step. | ||
| 66 | + * NaN-aware comparison (OrderPolicy::kOrderNan with floating-point T) treats NaN | ||
| 67 | + * as the largest value under IsDescend, so NaNs move to the front in descending | ||
| 68 | + * order (and to the back in ascending order). Numerically equal values keep the | ||
| 69 | + * plain -0/+0 equivalence unless the policy selects the radix-key ordering, | ||
| 70 | + * where -0.0 sorts strictly before +0.0; the previous slot's sign bit is then | ||
| 71 | + * read lazily, only when the compared values are numerically equal. | ||
| 72 | + */ | ||
| 73 | +template <typename T, bool IsDescend, typename OrderPolicy, typename BitsT> | ||
| 74 | +__simt_callee__ __aicore__ inline bool SmallAxisInsertionNeedMove(T keyValue, T prevValue, bool keyNegZero, | ||
| 75 | + __ubuf__ BitsT* valueBitsBase, uint32_t prevBitsIndex, | ||
| 76 | + BitsT signBitPattern) | ||
| 77 | +{ | ||
| 78 | + // Signed-zero ordering is only defined for floating-point compare types; the guard | ||
| 79 | + // keeps integer instantiations on the plain comparisons. | ||
| 80 | + constexpr bool kOrderSignedZero = OrderPolicy::kOrderSignedZero && | ||
| 81 | + (IsSameType<T, float>::value || IsSameType<T, half>::value || | ||
| 82 | + IsSameType<T, bfloat16_t>::value); | ||
| 83 | + bool needMove; | ||
| 84 | + if constexpr (OrderPolicy::kOrderNan && | ||
| 85 | + (IsSameType<T, float>::value || IsSameType<T, half>::value || IsSameType<T, bfloat16_t>::value)) { | ||
| 86 | + bool prevNan = prevValue != prevValue; | ||
| 87 | + bool keyNan = keyValue != keyValue; | ||
| 88 | + if (prevNan != keyNan) { | ||
| 89 | + needMove = IsDescend ? keyNan : prevNan; | ||
| 90 | + } else if (prevNan) { | ||
| 91 | + needMove = false; | ||
| 92 | + } else if constexpr (IsDescend) { | ||
| 93 | + needMove = prevValue < keyValue; | ||
| 94 | + } else { | ||
| 95 | + needMove = prevValue > keyValue; | ||
| 96 | + } | ||
| 97 | + } else if constexpr (IsDescend) { | ||
| 98 | + needMove = prevValue < keyValue; | ||
| 99 | + } else { | ||
| 100 | + needMove = prevValue > keyValue; | ||
| 101 | + } | ||
| 102 | + if constexpr (kOrderSignedZero) { | ||
| 103 | + if (!needMove && prevValue == keyValue) { | ||
| 104 | + bool prevNegZero = valueBitsBase[prevBitsIndex] == signBitPattern; | ||
| 105 | + needMove = IsDescend ? (prevNegZero && !keyNegZero) : (!prevNegZero && keyNegZero); | ||
| 106 | + } | ||
| 107 | + } | ||
| 108 | + return needMove; | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +/** | ||
| 112 | + * @brief SIMT per-segment insertion sort used by the top_k_v2 small-axis kernel. | ||
| 113 | + */ | ||
| 114 | +template <typename T, typename IDX_T, bool IsDescend, typename OrderPolicy> | ||
| 115 | +__simt_vf__ LAUNCH_BOUND(INSERTION_THREAD_NUM) __aicore__ | ||
| 116 | + void SimtInsertionSortSegments(uint32_t validSegs, uint32_t segmentLen, uint32_t valueRowElems, | ||
| 117 | + uint32_t idxRowElems, __ubuf__ T* valueBase, __ubuf__ IDX_T* idxBase) | ||
| 118 | +{ | ||
| 119 | + // Signed-zero radix ordering is only defined for floating-point compare types. | ||
| 120 | + constexpr bool kOrderSignedZero = OrderPolicy::kOrderSignedZero && | ||
| 121 | + (IsSameType<T, float>::value || IsSameType<T, half>::value || | ||
| 122 | + IsSameType<T, bfloat16_t>::value); | ||
| 123 | + // Same-width bit view of the value rows; dereferenced only when kOrderSignedZero. | ||
| 124 | + using SignedZeroBitsT = std::conditional_t< | ||
| 125 | + sizeof(T) == 1, uint8_t, | ||
| 126 | + std::conditional_t<sizeof(T) == 2, uint16_t, std::conditional_t<sizeof(T) == 4, uint32_t, uint64_t>>>; | ||
| 127 | + constexpr SignedZeroBitsT signBitPattern = static_cast<SignedZeroBitsT>(SignedZeroBitsT{1} | ||
| 128 | + << (sizeof(T) * 8U - 1U)); | ||
| 129 | + __ubuf__ SignedZeroBitsT* valueBitsBase = reinterpret_cast<__ubuf__ SignedZeroBitsT*>(valueBase); | ||
| 130 | + for (int32_t seg = threadIdx.x; seg < static_cast<int32_t>(validSegs); | ||
| 131 | + seg += static_cast<int32_t>(INSERTION_THREAD_NUM)) { | ||
| 132 | + uint32_t segId = static_cast<uint32_t>(seg); | ||
| 133 | + uint32_t valueBaseOffset = segId * valueRowElems; | ||
| 134 | + uint32_t idxBaseOffset = segId * idxRowElems; | ||
| 135 | + for (uint32_t elem = 0; elem < segmentLen; ++elem) { | ||
| 136 | + idxBase[idxBaseOffset + elem] = static_cast<IDX_T>(elem); | ||
| 137 | + } | ||
| 138 | + | ||
| 139 | + for (uint32_t elem = 1; elem < segmentLen; ++elem) { | ||
| 140 | + T keyValue = valueBase[valueBaseOffset + elem]; | ||
| 141 | + IDX_T keyIdx = idxBase[idxBaseOffset + elem]; | ||
| 142 | + bool keyNegZero = false; | ||
| 143 | + if constexpr (kOrderSignedZero) { | ||
| 144 | + // Capture the sign bit before the first shift overwrites slot elem. | ||
| 145 | + keyNegZero = valueBitsBase[valueBaseOffset + elem] == signBitPattern; | ||
| 146 | + } | ||
| 147 | + uint32_t insertPos = elem; | ||
| 148 | + while (insertPos > 0) { | ||
| 149 | + T prevValue = valueBase[valueBaseOffset + insertPos - 1]; | ||
| 150 | + bool needMove = SmallAxisInsertionNeedMove<T, IsDescend, OrderPolicy>( | ||
| 151 | + keyValue, prevValue, keyNegZero, valueBitsBase, valueBaseOffset + insertPos - 1U, signBitPattern); | ||
| 152 | + if (!needMove) { | ||
| 153 | + break; | ||
| 154 | + } | ||
| 155 | + valueBase[valueBaseOffset + insertPos] = prevValue; | ||
| 156 | + idxBase[idxBaseOffset + insertPos] = idxBase[idxBaseOffset + insertPos - 1]; | ||
| 157 | + --insertPos; | ||
| 158 | + } | ||
| 159 | + valueBase[valueBaseOffset + insertPos] = keyValue; | ||
| 160 | + idxBase[idxBaseOffset + insertPos] = keyIdx; | ||
| 161 | + } | ||
| 162 | + } | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +/** | ||
| 166 | + * @brief CRTP base class for the top_k_v2 small-axis insertion-sort kernel. | ||
| 167 | + * Contains shared Process loop, UB buffer setup, data loading, dtype conversion, and insertion sort. | ||
| 168 | + * Derived classes provide batch mapping details and output store behavior. | ||
| 169 | + */ | ||
| 170 | +template <typename Derived, typename T, typename CONVERT_TYPE, typename IDX_T, bool IsDescend, typename OrderPolicy> | ||
| 171 | +class SmallAxisInsertionBase { | ||
| 172 | +public: | ||
| 173 | + __aicore__ inline void Process() | ||
| 174 | + { | ||
| 175 | + Derived* op = static_cast<Derived*>(this); | ||
| 176 | + if (op->IsProcessInvalid()) { | ||
| 177 | + return; | ||
| 178 | + } | ||
| 179 | + uint32_t batchesPerCore = (batchNum_ + blockDim_ - 1U) / blockDim_; | ||
| 180 | + uint32_t startBatch = blockIdx_ * batchesPerCore; | ||
| 181 | + uint32_t endBatch = batchNum_ < startBatch + batchesPerCore ? batchNum_ : startBatch + batchesPerCore; | ||
| 182 | + for (uint32_t batchId = startBatch; batchId < endBatch; ++batchId) { | ||
| 183 | + uint32_t validSegs = op->ComputeValidSegs(batchId); | ||
| 184 | + if (validSegs == 0U) { | ||
| 185 | + continue; | ||
| 186 | + } | ||
| 187 | + op->ProcessBatch(batchId, validSegs); | ||
| 188 | + } | ||
| 189 | + } | ||
| 190 | + | ||
| 191 | + __aicore__ inline void InitInsertionBuffers(TPipe* pipe) | ||
| 192 | + { | ||
| 193 | + pipe_ = pipe; | ||
| 194 | + if constexpr (!IsSameType<T, CONVERT_TYPE>::value) { | ||
| 195 | + castRowStride_ = ROUND_UP_AGLIN(segmentLen_ * sizeof(T)) / sizeof(T); | ||
| 196 | + valueRowStride_ = castRowStride_; | ||
| 197 | + } else { | ||
| 198 | + valueRowStride_ = ROUND_UP_AGLIN(segmentLen_ * sizeof(CONVERT_TYPE)) / sizeof(CONVERT_TYPE); | ||
| 199 | + } | ||
| 200 | + indexRowStride_ = ROUND_UP_AGLIN(segmentLen_ * sizeof(IDX_T)) / sizeof(IDX_T); | ||
| 201 | + | ||
| 202 | + pipe_->InitBuffer(valueBuf_, segmentsPerBatch_ * valueRowStride_ * sizeof(CONVERT_TYPE)); | ||
| 203 | + pipe_->InitBuffer(idxBuf_, segmentsPerBatch_ * indexRowStride_ * sizeof(IDX_T)); | ||
| 204 | + if constexpr (!IsSameType<T, CONVERT_TYPE>::value) { | ||
| 205 | + pipe_->InitBuffer(castBuf_, segmentsPerBatch_ * castRowStride_ * sizeof(T)); | ||
| 206 | + } | ||
| 207 | + | ||
| 208 | + values_ = valueBuf_.template Get<CONVERT_TYPE>(); | ||
| 209 | + indices_ = idxBuf_.template Get<IDX_T>(); | ||
| 210 | + } | ||
| 211 | + | ||
| 212 | + __aicore__ inline void LoadContiguousBatch(GlobalTensor<T>& inputGm, int64_t inputStart, uint32_t validSegs, | ||
| 213 | + bool padTail) | ||
| 214 | + { | ||
| 215 | + if (validSegs == 0U) { | ||
| 216 | + return; | ||
| 217 | + } | ||
| 218 | + uint32_t dstRowStride = IsSameType<T, CONVERT_TYPE>::value ? valueRowStride_ : castRowStride_; | ||
| 219 | + uint32_t copiedRowElems = padTail ? ROUND_UP_AGLIN(segmentLen_ * sizeof(T)) / sizeof(T) : segmentLen_; | ||
| 220 | + uint32_t dstStrideBlocks = ((dstRowStride - copiedRowElems) * sizeof(T)) / UB_BLOCK_SIZE; | ||
| 221 | + DataCopyExtParams copyParam{static_cast<uint16_t>(validSegs), static_cast<uint32_t>(segmentLen_ * sizeof(T)), 0, | ||
| 222 | + dstStrideBlocks, 0}; | ||
| 223 | + DataCopyPadExtParams<T> padParams{ | ||
| 224 | + padTail, 0, static_cast<uint8_t>(padTail ? (copiedRowElems - segmentLen_) : 0U), static_cast<T>(0)}; | ||
| 225 | + if constexpr (!IsSameType<T, CONVERT_TYPE>::value) { | ||
| 226 | + LocalTensor<T> loadBuf = castBuf_.template Get<T>(); | ||
| 227 | + DataCopyPad(loadBuf, inputGm[inputStart], copyParam, padParams); | ||
| 228 | + event_t eventId = static_cast<event_t>(pipe_->FetchEventID(HardEvent::MTE2_V)); | ||
| 229 | + SetFlag<HardEvent::MTE2_V>(eventId); | ||
| 230 | + WaitFlag<HardEvent::MTE2_V>(eventId); | ||
| 231 | + Cast(values_, loadBuf, RoundMode::CAST_NONE, validSegs * valueRowStride_); | ||
| 232 | + } else { | ||
| 233 | + DataCopyPad(values_, inputGm[inputStart], copyParam, padParams); | ||
| 234 | + event_t eventId = static_cast<event_t>(pipe_->FetchEventID(HardEvent::MTE2_V)); | ||
| 235 | + SetFlag<HardEvent::MTE2_V>(eventId); | ||
| 236 | + WaitFlag<HardEvent::MTE2_V>(eventId); | ||
| 237 | + } | ||
| 238 | + } | ||
| 239 | + | ||
| 240 | + __aicore__ inline void LoadNonLastBatch(GlobalTensor<T>& inputGm, uint64_t outerBaseOffset, uint64_t innerStart, | ||
| 241 | + uint64_t innerSize, uint32_t validSegs) | ||
| 242 | + { | ||
| 243 | + uint32_t totalElems = validSegs * segmentLen_; | ||
| 244 | + if constexpr (!IsSameType<T, CONVERT_TYPE>::value) { | ||
| 245 | + LocalTensor<T> loadBuf = castBuf_.template Get<T>(); | ||
| 246 | + asc_vf_call<SimtLoadNonLastInsertionBatch<T>>( | ||
| 247 | + dim3(INSERTION_THREAD_NUM), totalElems, validSegs, segmentLen_, castRowStride_, outerBaseOffset, | ||
| 248 | + innerStart, innerSize, (__gm__ volatile T*)inputGm.GetPhyAddr(), (__ubuf__ T*)loadBuf.GetPhyAddr()); | ||
| 249 | + Cast(values_, loadBuf, RoundMode::CAST_NONE, validSegs * valueRowStride_); | ||
| 250 | + } else { | ||
| 251 | + asc_vf_call<SimtLoadNonLastInsertionBatch<T>>( | ||
| 252 | + dim3(INSERTION_THREAD_NUM), totalElems, validSegs, segmentLen_, valueRowStride_, outerBaseOffset, | ||
| 253 | + innerStart, innerSize, (__gm__ volatile T*)inputGm.GetPhyAddr(), (__ubuf__ T*)values_.GetPhyAddr()); | ||
| 254 | + } | ||
| 255 | + } | ||
| 256 | + | ||
| 257 | + __aicore__ inline void SortBatch(uint32_t validSegs) | ||
| 258 | + { | ||
| 259 | + asc_vf_call<SimtInsertionSortSegments<CONVERT_TYPE, IDX_T, IsDescend, OrderPolicy>>( | ||
| 260 | + dim3(INSERTION_THREAD_NUM), validSegs, segmentLen_, valueRowStride_, indexRowStride_, | ||
| 261 | + (__ubuf__ CONVERT_TYPE*)values_.GetPhyAddr(), (__ubuf__ IDX_T*)indices_.GetPhyAddr()); | ||
| 262 | + } | ||
| 263 | + | ||
| 264 | +protected: | ||
| 265 | + TPipe* pipe_ = nullptr; | ||
| 266 | + | ||
| 267 | + TBuf<TPosition::VECCALC> valueBuf_; // CONVERT_TYPE buffer for sort operations | ||
| 268 | + TBuf<TPosition::VECCALC> castBuf_; // T buffer for GM ↔ UB cast (bf16↔float transfer) | ||
| 269 | + TBuf<TPosition::VECCALC> idxBuf_; | ||
| 270 | + | ||
| 271 | + LocalTensor<CONVERT_TYPE> values_; | ||
| 272 | + LocalTensor<IDX_T> indices_; | ||
| 273 | + | ||
| 274 | + uint32_t blockIdx_ = 0; | ||
| 275 | + uint32_t blockDim_ = 0; | ||
| 276 | + uint32_t segmentLen_ = 0; | ||
| 277 | + uint32_t segmentsPerBatch_ = 0; | ||
| 278 | + uint32_t batchNum_ = 0; | ||
| 279 | + uint32_t valueRowStride_ = 0; | ||
| 280 | + uint32_t castRowStride_ = 0; | ||
| 281 | + uint32_t indexRowStride_ = 0; | ||
| 282 | +}; | ||
| 283 | + | ||
| 284 | +} // namespace TopKSmallAxis | ||
| 285 | + | ||
| 286 | +#endif | ||
| @@ -33,6 +33,8 @@ struct MergeSort { | |||
| 33 | uint32_t oneCoreRowNum); | 33 | uint32_t oneCoreRowNum); |
| 34 | __aicore__ inline void CopyValue2Gm(uint64_t gmOffset, uint64_t tileOffset, uint32_t ouputLastDimValue, | 34 | __aicore__ inline void CopyValue2Gm(uint64_t gmOffset, uint64_t tileOffset, uint32_t ouputLastDimValue, |
| 35 | uint32_t oneCoreRowNum); | 35 | uint32_t oneCoreRowNum); |
| 36 | + __aicore__ inline void CastIndexToInt64(AscendC::LocalTensor<int64_t> indexInt64Local, | ||
| 37 | + AscendC::LocalTensor<int32_t> indexInt32Local, uint32_t nowCoreRealRowNum); | ||
| 36 | 38 | ||
| 37 | protected: | 39 | protected: |
| 38 | __aicore__ inline void InitTilingData(const TILING_DATA_TYPE* tilingData); | 40 | __aicore__ inline void InitTilingData(const TILING_DATA_TYPE* tilingData); |
| @@ -173,8 +175,7 @@ __aicore__ inline void MergeSort<T, CONVERT_TYPE, TILING_DATA_TYPE, IS_LARGEST, | |||
| 173 | if constexpr (is_same<int64_t, INDEX_TYPE>::value) { | 175 | if constexpr (is_same<int64_t, INDEX_TYPE>::value) { |
| 174 | AscendC::LocalTensor<int32_t> sortedValueIndexInt32Local = sortedValueIndexLocal | 176 | AscendC::LocalTensor<int32_t> sortedValueIndexInt32Local = sortedValueIndexLocal |
| 175 | .template ReinterpretCast<int32_t>(); | 177 | .template ReinterpretCast<int32_t>(); |
| 176 | - AscendC::Cast(sortedValueIndexInt64Local, sortedValueIndexInt32Local, AscendC::RoundMode::CAST_NONE, | 178 | + CastIndexToInt64(sortedValueIndexInt64Local, sortedValueIndexInt32Local, nowCoreRealRowNum); |
| 177 | - nowCoreRealRowNum * ROUND_UP_AGLIN(numTileData_)); | ||
| 178 | outIndexQueue_.EnQue<int64_t>(sortedValueIndexInt64Local); | 179 | outIndexQueue_.EnQue<int64_t>(sortedValueIndexInt64Local); |
| 179 | } else { | 180 | } else { |
| 180 | outIndexQueue_.EnQue<uint32_t>(sortedValueIndexLocal); | 181 | outIndexQueue_.EnQue<uint32_t>(sortedValueIndexLocal); |
| @@ -188,6 +189,27 @@ __aicore__ inline void MergeSort<T, CONVERT_TYPE, TILING_DATA_TYPE, IS_LARGEST, | |||
| 188 | CopyValue2Gm(gmOffset, answerTileOffset, outputLastDimValue_, nowCoreRealRowNum); | 189 | CopyValue2Gm(gmOffset, answerTileOffset, outputLastDimValue_, nowCoreRealRowNum); |
| 189 | } | 190 | } |
| 190 | 191 | ||
| 192 | +template <typename T, typename CONVERT_TYPE, typename TILING_DATA_TYPE, bool IS_LARGEST, typename INDEX_TYPE, | ||
| 193 | + bool IS_BITONIC_SORT> | ||
| 194 | +__aicore__ inline void MergeSort<T, CONVERT_TYPE, TILING_DATA_TYPE, IS_LARGEST, INDEX_TYPE, | ||
| 195 | + IS_BITONIC_SORT>::CastIndexToInt64(AscendC::LocalTensor<int64_t> indexInt64Local, | ||
| 196 | + AscendC::LocalTensor<int32_t> indexInt32Local, | ||
| 197 | + uint32_t nowCoreRealRowNum) | ||
| 198 | +{ | ||
| 199 | + if constexpr (IS_BITONIC_SORT) { | ||
| 200 | + if (outputLastDimValue_ > 0) { | ||
| 201 | + uint32_t aglinOneRow = ROUND_UP_AGLIN(numTileData_); | ||
| 202 | + for (uint32_t row = 0; row < nowCoreRealRowNum; row++) { | ||
| 203 | + AscendC::Cast(indexInt64Local[row * aglinOneRow], indexInt32Local[row * aglinOneRow], | ||
| 204 | + AscendC::RoundMode::CAST_NONE, outputLastDimValue_); | ||
| 205 | + } | ||
| 206 | + } | ||
| 207 | + } else { | ||
| 208 | + AscendC::Cast(indexInt64Local, indexInt32Local, AscendC::RoundMode::CAST_NONE, | ||
| 209 | + nowCoreRealRowNum * ROUND_UP_AGLIN(numTileData_)); | ||
| 210 | + } | ||
| 211 | +} | ||
| 212 | + | ||
| 191 | template <typename T, typename CONVERT_TYPE, typename TILING_DATA_TYPE, bool IS_LARGEST, typename INDEX_TYPE, | 213 | template <typename T, typename CONVERT_TYPE, typename TILING_DATA_TYPE, bool IS_LARGEST, typename INDEX_TYPE, |
| 192 | bool IS_BITONIC_SORT> | 214 | bool IS_BITONIC_SORT> |
| 193 | __aicore__ inline void MergeSort<T, CONVERT_TYPE, TILING_DATA_TYPE, IS_LARGEST, INDEX_TYPE, | 215 | __aicore__ inline void MergeSort<T, CONVERT_TYPE, TILING_DATA_TYPE, IS_LARGEST, INDEX_TYPE, |
| @@ -198,11 +220,23 @@ __aicore__ inline void MergeSort<T, CONVERT_TYPE, TILING_DATA_TYPE, IS_LARGEST, | |||
| 198 | uint32_t aglinOneRowTileSize = ROUND_UP_AGLIN(currTileSize); | 220 | uint32_t aglinOneRowTileSize = ROUND_UP_AGLIN(currTileSize); |
| 199 | uint32_t localTensorLen = aglinOneRowTileSize * oneCoreRowNum; | 221 | uint32_t localTensorLen = aglinOneRowTileSize * oneCoreRowNum; |
| 200 | T defaultValue = IS_LARGEST ? static_cast<T>(-INFINITY) : static_cast<T>(NAN); | 222 | T defaultValue = IS_LARGEST ? static_cast<T>(-INFINITY) : static_cast<T>(NAN); |
| 201 | - Duplicate(xLocal, defaultValue, localTensorLen); | ||
| 202 | - event_t eventId = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::V_MTE2)); | ||
| 203 | - SetFlag<HardEvent::V_MTE2>(eventId); | ||
| 204 | - WaitFlag<HardEvent::V_MTE2>(eventId); | ||
| 205 | uint32_t currTileSizeAlign = ROUND_UP_AGLIN(currTileSize * sizeof(T)) / sizeof(T); | 223 | uint32_t currTileSizeAlign = ROUND_UP_AGLIN(currTileSize * sizeof(T)) / sizeof(T); |
| 224 | + if constexpr (IS_BITONIC_SORT) { | ||
| 225 | + uint32_t gapLen = aglinOneRowTileSize - currTileSizeAlign; | ||
| 226 | + if (gapLen > 0) { | ||
| 227 | + for (uint32_t r = 0; r < oneCoreRowNum; r++) { | ||
| 228 | + Duplicate(xLocal[r * aglinOneRowTileSize + currTileSizeAlign], defaultValue, gapLen); | ||
| 229 | + } | ||
| 230 | + event_t eventId = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::V_MTE2)); | ||
| 231 | + SetFlag<HardEvent::V_MTE2>(eventId); | ||
| 232 | + WaitFlag<HardEvent::V_MTE2>(eventId); | ||
| 233 | + } | ||
| 234 | + } else { | ||
| 235 | + Duplicate(xLocal, defaultValue, localTensorLen); | ||
| 236 | + event_t eventId = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::V_MTE2)); | ||
| 237 | + SetFlag<HardEvent::V_MTE2>(eventId); | ||
| 238 | + WaitFlag<HardEvent::V_MTE2>(eventId); | ||
| 239 | + } | ||
| 206 | uint32_t dstStride = ((aglinOneRowTileSize - currTileSizeAlign) * sizeof(T)) / UB_AGLIN_VALUE; | 240 | uint32_t dstStride = ((aglinOneRowTileSize - currTileSizeAlign) * sizeof(T)) / UB_AGLIN_VALUE; |
| 207 | DataCopyPadExtParams<T> padParams; | 241 | DataCopyPadExtParams<T> padParams; |
| 208 | padParams.isPad = true; | 242 | padParams.isPad = true; |
| @@ -99,19 +99,17 @@ __aicore__ inline void KernelVbsMergeSort<T, CONVERT_TYPE, IS_DESCEND, IS_BITONI | |||
| 99 | } | 99 | } |
| 100 | AscendC::LocalTensor<CONVERT_TYPE> concatLocal; | 100 | AscendC::LocalTensor<CONVERT_TYPE> concatLocal; |
| 101 | AscendC::Concat(concatLocal, xLocal[offsetOneRow], concatTmpLocal, concatRepeatTimes); | 101 | AscendC::Concat(concatLocal, xLocal[offsetOneRow], concatTmpLocal, concatRepeatTimes); |
| 102 | - // sort API中,index必须是int32_t | ||
| 103 | AscendC::Sort<CONVERT_TYPE, true>(sortedLocal, concatLocal, indexLocal_, sortTmpLocal, sortRepeatTimes); | 102 | AscendC::Sort<CONVERT_TYPE, true>(sortedLocal, concatLocal, indexLocal_, sortTmpLocal, sortRepeatTimes); |
| 104 | - // 处理sort后的结果数据,输出排序后的value和index | ||
| 105 | AscendC::Extract(sortedValueLocal[offsetOneRow], sortedValueIndexLocal[offsetOneRow], sortedLocal, | 103 | AscendC::Extract(sortedValueLocal[offsetOneRow], sortedValueIndexLocal[offsetOneRow], sortedLocal, |
| 106 | extractRepeatTimes); | 104 | extractRepeatTimes); |
| 107 | if constexpr (!IS_DESCEND) { | 105 | if constexpr (!IS_DESCEND) { |
| 108 | flipSignBit(sortedValueLocal, offsetOneRow, aglinTileSize); | 106 | flipSignBit(sortedValueLocal, offsetOneRow, aglinTileSize); |
| 109 | } | 107 | } |
| 110 | - if constexpr (IS_BITONIC_SORT) { | 108 | + } |
| 111 | - RunBitonicSmallTopKFinalize<T, uint32_t, IS_DESCEND>(sortedValueLocal[offsetOneRow], | 109 | + if constexpr (IS_BITONIC_SORT) { |
| 112 | - sortedValueIndexLocal[offsetOneRow], outputK, 1U, | 110 | + RunBitonicSmallTopKFinalizeWithFlags<T, uint32_t, IS_DESCEND>( |
| 113 | - aglinTileSize, aglinTileSize); | 111 | + sortedValueLocal, sortedValueIndexLocal, (__ubuf__ uint32_t*)sortTmpLocal.GetPhyAddr(), outputK, |
| 114 | - } | 112 | + static_cast<uint32_t>(nowCoreRealRowNum), aglinTileSize, aglinTileSize); |
| 115 | } | 113 | } |
| 116 | } | 114 | } |
| 117 | 115 | ||
| @@ -148,9 +146,9 @@ __aicore__ inline void KernelVbsMergeSort<T, CONVERT_TYPE, IS_DESCEND, IS_BITONI | |||
| 148 | AscendC::Cast(sortedValueLocal, sortedValueLocalCast, AscendC::RoundMode::CAST_RINT, | 146 | AscendC::Cast(sortedValueLocal, sortedValueLocalCast, AscendC::RoundMode::CAST_RINT, |
| 149 | aglinTileSize * nowCoreRealRowNum); | 147 | aglinTileSize * nowCoreRealRowNum); |
| 150 | if constexpr (IS_BITONIC_SORT) { | 148 | if constexpr (IS_BITONIC_SORT) { |
| 151 | - RunBitonicSmallTopKFinalize<T, uint32_t, IS_DESCEND>(sortedValueLocal, sortedValueIndexLocal, outputK, | 149 | + RunBitonicSmallTopKFinalizeWithFlags<T, uint32_t, IS_DESCEND>( |
| 152 | - static_cast<uint32_t>(nowCoreRealRowNum), aglinTileSize, | 150 | + sortedValueLocal, sortedValueIndexLocal, (__ubuf__ uint32_t*)sortTmpLocal.GetPhyAddr(), outputK, |
| 153 | - aglinTileSize); | 151 | + static_cast<uint32_t>(nowCoreRealRowNum), aglinTileSize, aglinTileSize); |
| 154 | } | 152 | } |
| 155 | } | 153 | } |
| 156 | 154 | ||
| @@ -0,0 +1,267 @@ | |||
| 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 top_k_small_axis_insertion.h | ||
| 13 | + * @brief TopK小轴插入排序模板 | ||
| 14 | + * @details 适用场景:轴长极小(N ≤ insertionMaxN),排序语义为TopK候选序 | ||
| 15 | + */ | ||
| 16 | + | ||
| 17 | +#ifndef TOP_K_SMALL_AXIS_INSERTION_H | ||
| 18 | +#define TOP_K_SMALL_AXIS_INSERTION_H | ||
| 19 | + | ||
| 20 | +#include <type_traits> | ||
| 21 | + | ||
| 22 | +#include "kernel_operator.h" | ||
| 23 | +#include "kernel_tiling/kernel_tiling.h" | ||
| 24 | +#include "op_kernel/platform_util.h" | ||
| 25 | +#include "simt_api/asc_simt.h" | ||
| 26 | +#include "common/top_k_small_axis_insertion_base.h" | ||
| 27 | +#include "top_k_small_size_bitonic_sort.h" | ||
| 28 | + | ||
| 29 | +namespace topkV2 { | ||
| 30 | +using namespace AscendC; | ||
| 31 | + | ||
| 32 | +/** | ||
| 33 | + * @brief SIMT store:last轴,每段写前k个,输出GM布局 [totalSegs, k] | ||
| 34 | + */ | ||
| 35 | +template <typename T, typename CONVERT_TYPE, typename OUT_IDX_T> | ||
| 36 | +__simt_vf__ LAUNCH_BOUND(TopKSmallAxis::INSERTION_THREAD_NUM) __aicore__ | ||
| 37 | + void SimtStoreTopKInsertionBatch(uint32_t validSegs, uint32_t kValue, uint32_t valueRowElems, | ||
| 38 | + uint32_t indexRowElems, uint64_t outputStart, __ubuf__ CONVERT_TYPE* values, | ||
| 39 | + __ubuf__ uint32_t* indices, __gm__ volatile T* outputValue, | ||
| 40 | + __gm__ volatile OUT_IDX_T* outputIndex) | ||
| 41 | +{ | ||
| 42 | + uint32_t total = validSegs * kValue; | ||
| 43 | + for (uint32_t idx = static_cast<uint32_t>(threadIdx.x); idx < total; idx += TopKSmallAxis::INSERTION_THREAD_NUM) { | ||
| 44 | + uint32_t seg = idx / kValue; | ||
| 45 | + uint32_t rank = idx - seg * kValue; | ||
| 46 | + outputValue[outputStart + idx] = static_cast<T>(values[seg * valueRowElems + rank]); | ||
| 47 | + outputIndex[outputStart + idx] = static_cast<OUT_IDX_T>(indices[seg * indexRowElems + rank]); | ||
| 48 | + } | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/** | ||
| 52 | + * @brief SIMT store:非last轴,输出GM布局 [outer, k, inner] | ||
| 53 | + */ | ||
| 54 | +template <typename T, typename CONVERT_TYPE, typename OUT_IDX_T> | ||
| 55 | +__simt_vf__ LAUNCH_BOUND(TopKSmallAxis::INSERTION_THREAD_NUM) __aicore__ | ||
| 56 | + void SimtStoreTopKNonLastInsertionBatch(uint32_t validSegs, uint32_t kValue, uint32_t valueRowElems, | ||
| 57 | + uint32_t indexRowElems, uint64_t outerBaseOffset, uint64_t innerStart, | ||
| 58 | + uint64_t innerSize, __ubuf__ CONVERT_TYPE* values, | ||
| 59 | + __ubuf__ uint32_t* indices, __gm__ volatile T* outputValue, | ||
| 60 | + __gm__ volatile OUT_IDX_T* outputIndex) | ||
| 61 | +{ | ||
| 62 | + uint32_t total = validSegs * kValue; | ||
| 63 | + for (uint32_t idx = static_cast<uint32_t>(threadIdx.x); idx < total; idx += TopKSmallAxis::INSERTION_THREAD_NUM) { | ||
| 64 | + uint32_t rank = idx / validSegs; | ||
| 65 | + uint32_t seg = idx - rank * validSegs; | ||
| 66 | + uint64_t gmOffset = outerBaseOffset + static_cast<uint64_t>(rank) * innerSize + innerStart + seg; | ||
| 67 | + outputValue[gmOffset] = static_cast<T>(values[seg * valueRowElems + rank]); | ||
| 68 | + outputIndex[gmOffset] = static_cast<OUT_IDX_T>(indices[seg * indexRowElems + rank]); | ||
| 69 | + } | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +template <typename T, typename CONVERT_TYPE, typename OUT_IDX_T, bool IsDescend> | ||
| 73 | +class TopKSmallAxisInsertion | ||
| 74 | + : public TopKSmallAxis::SmallAxisInsertionBase<TopKSmallAxisInsertion<T, CONVERT_TYPE, OUT_IDX_T, IsDescend>, T, | ||
| 75 | + CONVERT_TYPE, uint32_t, IsDescend, | ||
| 76 | + TopKSmallAxis::TopKCandidateOrder> { | ||
| 77 | + using Base = TopKSmallAxis::SmallAxisInsertionBase<TopKSmallAxisInsertion<T, CONVERT_TYPE, OUT_IDX_T, IsDescend>, T, | ||
| 78 | + CONVERT_TYPE, uint32_t, IsDescend, | ||
| 79 | + TopKSmallAxis::TopKCandidateOrder>; | ||
| 80 | + | ||
| 81 | +public: | ||
| 82 | + __aicore__ inline TopKSmallAxisInsertion() {} | ||
| 83 | + __aicore__ inline void Init(GM_ADDR x, GM_ADDR values, GM_ADDR indices, const TopKV2TilingDataSimd* tilingData, | ||
| 84 | + TPipe* pipe); | ||
| 85 | + __aicore__ inline void Process() { Base::Process(); } | ||
| 86 | + | ||
| 87 | + friend Base; | ||
| 88 | + | ||
| 89 | +private: | ||
| 90 | + using Base::batchNum_; | ||
| 91 | + using Base::blockDim_; | ||
| 92 | + using Base::blockIdx_; | ||
| 93 | + using Base::castBuf_; | ||
| 94 | + using Base::castRowStride_; | ||
| 95 | + using Base::indexRowStride_; | ||
| 96 | + using Base::indices_; | ||
| 97 | + using Base::pipe_; | ||
| 98 | + using Base::segmentLen_; | ||
| 99 | + using Base::segmentsPerBatch_; | ||
| 100 | + using Base::valueRowStride_; | ||
| 101 | + using Base::values_; | ||
| 102 | + | ||
| 103 | + // Main pipeline functions (in call order) | ||
| 104 | + __aicore__ inline bool IsProcessInvalid() const; | ||
| 105 | + __aicore__ inline uint32_t ComputeValidSegs(uint32_t batchId) const; | ||
| 106 | + __aicore__ inline void ProcessBatch(uint32_t batchId, uint32_t validSegs); | ||
| 107 | + __aicore__ inline void RunBitonicFinalize(uint32_t validSegs); | ||
| 108 | + __aicore__ inline void StoreTopK(int64_t segStart, uint32_t validSegs); | ||
| 109 | + __aicore__ inline void StoreNonLastTopK(uint64_t outerId, uint64_t innerStart, uint32_t validSegs); | ||
| 110 | + | ||
| 111 | + GlobalTensor<T> inputGm_; | ||
| 112 | + GlobalTensor<T> outValueGm_; | ||
| 113 | + GlobalTensor<OUT_IDX_T> outIdxGm_; | ||
| 114 | + | ||
| 115 | + uint32_t kValue_ = 0; | ||
| 116 | + bool useBitonicFinalize_ = false; | ||
| 117 | + int64_t totalSegs_ = 0; | ||
| 118 | + int64_t outerSize_ = 1; | ||
| 119 | + int64_t innerSize_ = 1; | ||
| 120 | + uint32_t innerLoopNum_ = 1; | ||
| 121 | + bool isNonLastAxis_ = false; | ||
| 122 | +}; | ||
| 123 | + | ||
| 124 | +template <typename T, typename CONVERT_TYPE, typename OUT_IDX_T, bool IsDescend> | ||
| 125 | +__aicore__ inline void TopKSmallAxisInsertion<T, CONVERT_TYPE, OUT_IDX_T, IsDescend>::Init( | ||
| 126 | + GM_ADDR x, GM_ADDR values, GM_ADDR indices, const TopKV2TilingDataSimd* tilingData, TPipe* pipe) | ||
| 127 | +{ | ||
| 128 | + if (tilingData == nullptr || pipe == nullptr) { | ||
| 129 | + return; | ||
| 130 | + } | ||
| 131 | + blockIdx_ = GetBlockIdx(); | ||
| 132 | + blockDim_ = GetBlockNum(); | ||
| 133 | + segmentLen_ = tilingData->numTileDataSize; | ||
| 134 | + segmentsPerBatch_ = tilingData->keyParams0; | ||
| 135 | + batchNum_ = tilingData->keyParams1; | ||
| 136 | + kValue_ = static_cast<uint32_t>(tilingData->topKRealValue); | ||
| 137 | + useBitonicFinalize_ = tilingData->keyParams5 != 0U; | ||
| 138 | + isNonLastAxis_ = tilingData->keyParams3 != 0U; | ||
| 139 | + innerLoopNum_ = tilingData->keyParams2; | ||
| 140 | + if (isNonLastAxis_) { | ||
| 141 | + // Mode-8 convention: unsortedDimNum is innerSize and oneCoreRowNum is outerSize. | ||
| 142 | + outerSize_ = static_cast<int64_t>(tilingData->oneCoreRowNum); | ||
| 143 | + innerSize_ = static_cast<int64_t>(tilingData->unsortedDimNum); | ||
| 144 | + } else { | ||
| 145 | + totalSegs_ = static_cast<int64_t>(tilingData->unsortedDimNum); | ||
| 146 | + } | ||
| 147 | + | ||
| 148 | + inputGm_.SetGlobalBuffer((__gm__ T*)x); | ||
| 149 | + outValueGm_.SetGlobalBuffer((__gm__ T*)values); | ||
| 150 | + outIdxGm_.SetGlobalBuffer((__gm__ OUT_IDX_T*)indices); | ||
| 151 | + | ||
| 152 | + if (segmentLen_ == 0 || segmentsPerBatch_ == 0 || segmentsPerBatch_ > TopKSmallAxis::MAX_DATACOPY_BLOCK_COUNT || | ||
| 153 | + kValue_ == 0 || kValue_ > segmentLen_) { | ||
| 154 | + return; | ||
| 155 | + } | ||
| 156 | + | ||
| 157 | + Base::InitInsertionBuffers(pipe); | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +template <typename T, typename CONVERT_TYPE, typename OUT_IDX_T, bool IsDescend> | ||
| 161 | +__aicore__ inline bool TopKSmallAxisInsertion<T, CONVERT_TYPE, OUT_IDX_T, IsDescend>::IsProcessInvalid() const | ||
| 162 | +{ | ||
| 163 | + return blockIdx_ >= blockDim_ || segmentLen_ == 0 || segmentsPerBatch_ == 0 || kValue_ == 0 || | ||
| 164 | + kValue_ > segmentLen_ || (isNonLastAxis_ && (innerLoopNum_ == 0 || outerSize_ <= 0 || innerSize_ <= 0)); | ||
| 165 | +} | ||
| 166 | + | ||
| 167 | +template <typename T, typename CONVERT_TYPE, typename OUT_IDX_T, bool IsDescend> | ||
| 168 | +__aicore__ inline uint32_t TopKSmallAxisInsertion<T, CONVERT_TYPE, OUT_IDX_T, IsDescend>::ComputeValidSegs( | ||
| 169 | + uint32_t batchId) const | ||
| 170 | +{ | ||
| 171 | + if (isNonLastAxis_) { | ||
| 172 | + // Non-last batching iterates inner tiles inside each outer slice; the tail tile | ||
| 173 | + // may contain fewer segments than the configured batch size. | ||
| 174 | + uint32_t innerTileId = batchId % innerLoopNum_; | ||
| 175 | + int64_t innerStart = static_cast<int64_t>(innerTileId) * static_cast<int64_t>(segmentsPerBatch_); | ||
| 176 | + int64_t innerRemain = innerSize_ - innerStart; | ||
| 177 | + if (innerRemain <= 0) { | ||
| 178 | + return 0; | ||
| 179 | + } | ||
| 180 | + return innerRemain >= static_cast<int64_t>(segmentsPerBatch_) ? segmentsPerBatch_ : | ||
| 181 | + static_cast<uint32_t>(innerRemain); | ||
| 182 | + } | ||
| 183 | + int64_t segStart = static_cast<int64_t>(batchId) * static_cast<int64_t>(segmentsPerBatch_); | ||
| 184 | + int64_t segRemain = totalSegs_ - segStart; | ||
| 185 | + if (segRemain <= 0) { | ||
| 186 | + return 0; | ||
| 187 | + } | ||
| 188 | + if (segRemain >= static_cast<int64_t>(segmentsPerBatch_)) { | ||
| 189 | + return segmentsPerBatch_; | ||
| 190 | + } | ||
| 191 | + return static_cast<uint32_t>(segRemain); | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +template <typename T, typename CONVERT_TYPE, typename OUT_IDX_T, bool IsDescend> | ||
| 195 | +__aicore__ inline void TopKSmallAxisInsertion<T, CONVERT_TYPE, OUT_IDX_T, IsDescend>::ProcessBatch(uint32_t batchId, | ||
| 196 | + uint32_t validSegs) | ||
| 197 | +{ | ||
| 198 | + int64_t segStart = static_cast<int64_t>(batchId) * static_cast<int64_t>(segmentsPerBatch_); | ||
| 199 | + uint64_t outerId = 0; | ||
| 200 | + uint64_t innerStart = 0; | ||
| 201 | + if (isNonLastAxis_) { | ||
| 202 | + // batchId is linearized as [outerId, innerTileId] for non-last-axis work. | ||
| 203 | + outerId = static_cast<uint64_t>(batchId / innerLoopNum_); | ||
| 204 | + uint32_t innerTileId = batchId % innerLoopNum_; | ||
| 205 | + innerStart = static_cast<uint64_t>(innerTileId) * static_cast<uint64_t>(segmentsPerBatch_); | ||
| 206 | + uint64_t outerBaseOffset = outerId * static_cast<uint64_t>(segmentLen_) * static_cast<uint64_t>(innerSize_); | ||
| 207 | + Base::LoadNonLastBatch(inputGm_, outerBaseOffset, innerStart, static_cast<uint64_t>(innerSize_), validSegs); | ||
| 208 | + } else { | ||
| 209 | + Base::LoadContiguousBatch(inputGm_, segStart * static_cast<int64_t>(segmentLen_), validSegs, false); | ||
| 210 | + } | ||
| 211 | + Base::SortBatch(validSegs); | ||
| 212 | + RunBitonicFinalize(validSegs); | ||
| 213 | + if (isNonLastAxis_) { | ||
| 214 | + StoreNonLastTopK(outerId, innerStart, validSegs); | ||
| 215 | + } else { | ||
| 216 | + StoreTopK(segStart, validSegs); | ||
| 217 | + } | ||
| 218 | +} | ||
| 219 | + | ||
| 220 | +template <typename T, typename CONVERT_TYPE, typename OUT_IDX_T, bool IsDescend> | ||
| 221 | +__aicore__ inline void TopKSmallAxisInsertion<T, CONVERT_TYPE, OUT_IDX_T, IsDescend>::RunBitonicFinalize( | ||
| 222 | + uint32_t validSegs) | ||
| 223 | +{ | ||
| 224 | + if (!useBitonicFinalize_ || validSegs == 0U) { | ||
| 225 | + return; | ||
| 226 | + } | ||
| 227 | + RunBitonicFinalizeSelectionRows<CONVERT_TYPE, uint32_t, IsDescend>(values_, indices_, kValue_, validSegs, | ||
| 228 | + valueRowStride_, indexRowStride_); | ||
| 229 | +} | ||
| 230 | + | ||
| 231 | +template <typename T, typename CONVERT_TYPE, typename OUT_IDX_T, bool IsDescend> | ||
| 232 | +__aicore__ inline void TopKSmallAxisInsertion<T, CONVERT_TYPE, OUT_IDX_T, IsDescend>::StoreTopK(int64_t segStart, | ||
| 233 | + uint32_t validSegs) | ||
| 234 | +{ | ||
| 235 | + if (validSegs == 0U) { | ||
| 236 | + return; | ||
| 237 | + } | ||
| 238 | + // Output layout is [totalSegs, k]; each sorted segment contributes its first k elements. | ||
| 239 | + uint64_t outputStart = static_cast<uint64_t>(segStart) * static_cast<uint64_t>(kValue_); | ||
| 240 | + asc_vf_call<SimtStoreTopKInsertionBatch<T, CONVERT_TYPE, OUT_IDX_T>>( | ||
| 241 | + dim3(TopKSmallAxis::INSERTION_THREAD_NUM), validSegs, kValue_, valueRowStride_, indexRowStride_, outputStart, | ||
| 242 | + (__ubuf__ CONVERT_TYPE*)values_.GetPhyAddr(), (__ubuf__ uint32_t*)indices_.GetPhyAddr(), | ||
| 243 | + (__gm__ volatile T*)outValueGm_.GetPhyAddr(), (__gm__ volatile OUT_IDX_T*)outIdxGm_.GetPhyAddr()); | ||
| 244 | + event_t eventId = static_cast<event_t>(pipe_->FetchEventID(HardEvent::V_S)); | ||
| 245 | + SetFlag<HardEvent::V_S>(eventId); | ||
| 246 | + WaitFlag<HardEvent::V_S>(eventId); | ||
| 247 | +} | ||
| 248 | + | ||
| 249 | +template <typename T, typename CONVERT_TYPE, typename OUT_IDX_T, bool IsDescend> | ||
| 250 | +__aicore__ inline void TopKSmallAxisInsertion<T, CONVERT_TYPE, OUT_IDX_T, IsDescend>::StoreNonLastTopK( | ||
| 251 | + uint64_t outerId, uint64_t innerStart, uint32_t validSegs) | ||
| 252 | +{ | ||
| 253 | + // Output layout is [outer, k, inner]; the topk axis replaces segmentLen with kValue_. | ||
| 254 | + uint64_t outputBase = outerId * static_cast<uint64_t>(kValue_) * static_cast<uint64_t>(innerSize_); | ||
| 255 | + asc_vf_call<SimtStoreTopKNonLastInsertionBatch<T, CONVERT_TYPE, OUT_IDX_T>>( | ||
| 256 | + dim3(TopKSmallAxis::INSERTION_THREAD_NUM), validSegs, kValue_, valueRowStride_, indexRowStride_, outputBase, | ||
| 257 | + innerStart, static_cast<uint64_t>(innerSize_), (__ubuf__ CONVERT_TYPE*)values_.GetPhyAddr(), | ||
| 258 | + (__ubuf__ uint32_t*)indices_.GetPhyAddr(), (__gm__ volatile T*)outValueGm_.GetPhyAddr(), | ||
| 259 | + (__gm__ volatile OUT_IDX_T*)outIdxGm_.GetPhyAddr()); | ||
| 260 | + event_t eventId = static_cast<event_t>(pipe_->FetchEventID(HardEvent::V_S)); | ||
| 261 | + SetFlag<HardEvent::V_S>(eventId); | ||
| 262 | + WaitFlag<HardEvent::V_S>(eventId); | ||
| 263 | +} | ||
| 264 | + | ||
| 265 | +} // namespace topkV2 | ||
| 266 | + | ||
| 267 | +#endif | ||
| @@ -0,0 +1,274 @@ | |||
| 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 top_k_small_axis_two_stage.h | ||
| 13 | + * @brief TopK小轴两段排序模板(复用sort的SmallAxisTwoStageBase实现) | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#ifndef TOP_K_SMALL_AXIS_TWO_STAGE_H | ||
| 17 | +#define TOP_K_SMALL_AXIS_TWO_STAGE_H | ||
| 18 | + | ||
| 19 | +#include <type_traits> | ||
| 20 | + | ||
| 21 | +#include "kernel_operator.h" | ||
| 22 | +#include "kernel_tiling/kernel_tiling.h" | ||
| 23 | +#include "op_kernel/platform_util.h" | ||
| 24 | +#include "simt_api/asc_simt.h" | ||
| 25 | +#include "../../sort/arch35/common/small_axis_two_stage_base.h" | ||
| 26 | +#include "top_k_small_size_bitonic_sort.h" | ||
| 27 | + | ||
| 28 | +namespace topkV2 { | ||
| 29 | +using namespace AscendC; | ||
| 30 | + | ||
| 31 | +/** | ||
| 32 | + * @brief SIMT store:last轴,每段写前k个,输出GM布局 [totalSegs, k] | ||
| 33 | + */ | ||
| 34 | +template <typename T, typename OUT_IDX_T> | ||
| 35 | +__simt_vf__ LAUNCH_BOUND(SmallAxisCommon::TWO_STAGE_THREAD_NUM) __aicore__ | ||
| 36 | + void SimtStoreTopKTwoStageBatch(uint32_t validSegs, uint32_t segmentLen, uint32_t kValue, uint64_t outputStart, | ||
| 37 | + __ubuf__ T* finalValues, __ubuf__ uint32_t* finalIdx, | ||
| 38 | + __gm__ volatile T* outputValue, __gm__ volatile OUT_IDX_T* outputIndex) | ||
| 39 | +{ | ||
| 40 | + uint32_t total = validSegs * kValue; | ||
| 41 | + for (uint32_t idx = static_cast<uint32_t>(threadIdx.x); idx < total; idx += SmallAxisCommon::TWO_STAGE_THREAD_NUM) { | ||
| 42 | + uint32_t seg = idx / kValue; | ||
| 43 | + uint32_t rank = idx - seg * kValue; | ||
| 44 | + uint32_t srcOffset = seg * segmentLen + rank; | ||
| 45 | + outputValue[outputStart + idx] = finalValues[srcOffset]; | ||
| 46 | + outputIndex[outputStart + idx] = static_cast<OUT_IDX_T>(finalIdx[srcOffset]); | ||
| 47 | + } | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/** | ||
| 51 | + * @brief SIMT store:非last轴,输出GM布局 [outer, k, inner] | ||
| 52 | + */ | ||
| 53 | +template <typename T, typename OUT_IDX_T> | ||
| 54 | +__simt_vf__ LAUNCH_BOUND(SmallAxisCommon::TWO_STAGE_THREAD_NUM) __aicore__ | ||
| 55 | + void SimtStoreTopKNonLastTwoStageBatch(uint32_t validSegs, uint32_t segmentLen, uint32_t kValue, | ||
| 56 | + uint64_t outerBaseOffset, uint64_t innerStart, uint64_t innerSize, | ||
| 57 | + __ubuf__ T* finalValues, __ubuf__ uint32_t* finalIdx, | ||
| 58 | + __gm__ volatile T* outputValue, __gm__ volatile OUT_IDX_T* outputIndex) | ||
| 59 | +{ | ||
| 60 | + uint32_t total = validSegs * kValue; | ||
| 61 | + for (uint32_t idx = static_cast<uint32_t>(threadIdx.x); idx < total; idx += SmallAxisCommon::TWO_STAGE_THREAD_NUM) { | ||
| 62 | + uint32_t rank = idx / validSegs; | ||
| 63 | + uint32_t seg = idx - rank * validSegs; | ||
| 64 | + uint32_t srcOffset = seg * segmentLen + rank; | ||
| 65 | + uint64_t gmOffset = outerBaseOffset + static_cast<uint64_t>(rank) * innerSize + innerStart + seg; | ||
| 66 | + outputValue[gmOffset] = finalValues[srcOffset]; | ||
| 67 | + outputIndex[gmOffset] = static_cast<OUT_IDX_T>(finalIdx[srcOffset]); | ||
| 68 | + } | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +template <typename T, typename OUT_IDX_T, bool IsDescend> | ||
| 72 | +class TopKSmallAxisTwoStage | ||
| 73 | + : public SmallAxisCommon::SmallAxisTwoStageBase<TopKSmallAxisTwoStage<T, OUT_IDX_T, IsDescend>, T, uint32_t, | ||
| 74 | + IsDescend> { | ||
| 75 | + using Base = SmallAxisCommon::SmallAxisTwoStageBase<TopKSmallAxisTwoStage<T, OUT_IDX_T, IsDescend>, T, uint32_t, | ||
| 76 | + IsDescend>; | ||
| 77 | + | ||
| 78 | +public: | ||
| 79 | + __aicore__ inline TopKSmallAxisTwoStage() {} | ||
| 80 | + __aicore__ inline void Init(GM_ADDR x, GM_ADDR values, GM_ADDR indices, const TopKV2TilingDataSimd* tilingData, | ||
| 81 | + TPipe* pipe); | ||
| 82 | + __aicore__ inline void Process() { Base::Process(); } | ||
| 83 | + | ||
| 84 | + friend Base; | ||
| 85 | + | ||
| 86 | +private: | ||
| 87 | + using Base::batchNum_; | ||
| 88 | + using Base::batchSize_; | ||
| 89 | + using Base::blockDim_; | ||
| 90 | + using Base::blockIdx_; | ||
| 91 | + using Base::finalIdx_; | ||
| 92 | + using Base::finalValues_; | ||
| 93 | + using Base::maxFlatElems_; | ||
| 94 | + using Base::pipe_; | ||
| 95 | + using Base::segmentLen_; | ||
| 96 | + | ||
| 97 | + // Main pipeline functions (in call order) | ||
| 98 | + __aicore__ inline bool IsProcessInvalid() const; | ||
| 99 | + __aicore__ inline uint32_t ComputeValidSegs(uint32_t batchId) const; | ||
| 100 | + __aicore__ inline void ProcessBatch(uint32_t batchId, uint32_t validSegs); | ||
| 101 | + __aicore__ inline void RunBitonicFinalize(uint32_t validSegs); | ||
| 102 | + __aicore__ inline void StoreTopK(int64_t segStart, uint32_t validSegs); | ||
| 103 | + __aicore__ inline void StoreNonLastTopK(uint64_t outerId, uint64_t innerStart, uint32_t validSegs); | ||
| 104 | + | ||
| 105 | + GlobalTensor<T> inputGm_; | ||
| 106 | + GlobalTensor<T> outValueGm_; | ||
| 107 | + GlobalTensor<OUT_IDX_T> outIdxGm_; | ||
| 108 | + | ||
| 109 | + uint32_t kValue_ = 0; | ||
| 110 | + bool useBitonicFinalize_ = false; | ||
| 111 | + int64_t totalSegs_ = 0; | ||
| 112 | + int64_t outerSize_ = 1; | ||
| 113 | + int64_t innerSize_ = 1; | ||
| 114 | + uint32_t innerLoopNum_ = 1; | ||
| 115 | + bool isNonLastAxis_ = false; | ||
| 116 | +}; | ||
| 117 | + | ||
| 118 | +template <typename T, typename OUT_IDX_T, bool IsDescend> | ||
| 119 | +__aicore__ inline void TopKSmallAxisTwoStage<T, OUT_IDX_T, IsDescend>::Init(GM_ADDR x, GM_ADDR values, GM_ADDR indices, | ||
| 120 | + const TopKV2TilingDataSimd* tilingData, | ||
| 121 | + TPipe* pipe) | ||
| 122 | +{ | ||
| 123 | + if (tilingData == nullptr || pipe == nullptr) { | ||
| 124 | + return; | ||
| 125 | + } | ||
| 126 | + pipe_ = pipe; | ||
| 127 | + blockIdx_ = GetBlockIdx(); | ||
| 128 | + blockDim_ = GetBlockNum(); | ||
| 129 | + batchSize_ = tilingData->keyParams0; | ||
| 130 | + batchNum_ = tilingData->keyParams1; | ||
| 131 | + segmentLen_ = tilingData->numTileDataSize; | ||
| 132 | + maxFlatElems_ = batchSize_ * segmentLen_; | ||
| 133 | + kValue_ = static_cast<uint32_t>(tilingData->topKRealValue); | ||
| 134 | + useBitonicFinalize_ = tilingData->keyParams5 != 0U; | ||
| 135 | + isNonLastAxis_ = tilingData->keyParams3 != 0U; | ||
| 136 | + innerLoopNum_ = tilingData->keyParams4; | ||
| 137 | + if (isNonLastAxis_) { | ||
| 138 | + // Mode-8 convention: unsortedDimNum is innerSize and oneCoreRowNum is outerSize. | ||
| 139 | + outerSize_ = static_cast<int64_t>(tilingData->oneCoreRowNum); | ||
| 140 | + innerSize_ = static_cast<int64_t>(tilingData->unsortedDimNum); | ||
| 141 | + } else { | ||
| 142 | + totalSegs_ = static_cast<int64_t>(tilingData->unsortedDimNum); | ||
| 143 | + } | ||
| 144 | + | ||
| 145 | + inputGm_.SetGlobalBuffer((__gm__ T*)x); | ||
| 146 | + outValueGm_.SetGlobalBuffer((__gm__ T*)values); | ||
| 147 | + outIdxGm_.SetGlobalBuffer((__gm__ OUT_IDX_T*)indices); | ||
| 148 | + | ||
| 149 | + if (batchSize_ == 0 || segmentLen_ == 0 || maxFlatElems_ == 0 || kValue_ == 0 || kValue_ > segmentLen_) { | ||
| 150 | + return; | ||
| 151 | + } | ||
| 152 | + | ||
| 153 | + constexpr uint32_t kAliasElemBytes = static_cast<uint32_t>(sizeof(uint32_t)); | ||
| 154 | + Base::InitSortBuffers(pipe, maxFlatElems_, tilingData->tmpUbSize, tilingData->keyParams2 != 0U, kAliasElemBytes); | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +template <typename T, typename OUT_IDX_T, bool IsDescend> | ||
| 158 | +__aicore__ inline bool TopKSmallAxisTwoStage<T, OUT_IDX_T, IsDescend>::IsProcessInvalid() const | ||
| 159 | +{ | ||
| 160 | + return blockIdx_ >= blockDim_ || batchSize_ == 0 || segmentLen_ == 0 || kValue_ == 0 || kValue_ > segmentLen_ || | ||
| 161 | + (isNonLastAxis_ && (innerLoopNum_ == 0 || outerSize_ <= 0 || innerSize_ <= 0)); | ||
| 162 | +} | ||
| 163 | + | ||
| 164 | +template <typename T, typename OUT_IDX_T, bool IsDescend> | ||
| 165 | +__aicore__ inline uint32_t TopKSmallAxisTwoStage<T, OUT_IDX_T, IsDescend>::ComputeValidSegs(uint32_t batchId) const | ||
| 166 | +{ | ||
| 167 | + if (isNonLastAxis_) { | ||
| 168 | + // Non-last batches are grouped by outer slice, then by inner tile. | ||
| 169 | + // The last inner tile can be shorter than batchSize_. | ||
| 170 | + uint32_t tileInOuter = batchId % innerLoopNum_; | ||
| 171 | + int64_t tileStart = static_cast<int64_t>(tileInOuter) * static_cast<int64_t>(batchSize_); | ||
| 172 | + int64_t remainingInTile = innerSize_ - tileStart; | ||
| 173 | + if (remainingInTile <= 0) { | ||
| 174 | + return 0; | ||
| 175 | + } | ||
| 176 | + return remainingInTile >= static_cast<int64_t>(batchSize_) ? batchSize_ : | ||
| 177 | + static_cast<uint32_t>(remainingInTile); | ||
| 178 | + } | ||
| 179 | + int64_t batchStart = static_cast<int64_t>(batchId) * static_cast<int64_t>(batchSize_); | ||
| 180 | + int64_t remainingSegs = totalSegs_ - batchStart; | ||
| 181 | + if (remainingSegs <= 0) { | ||
| 182 | + return 0; | ||
| 183 | + } | ||
| 184 | + if (remainingSegs >= static_cast<int64_t>(batchSize_)) { | ||
| 185 | + return batchSize_; | ||
| 186 | + } | ||
| 187 | + return static_cast<uint32_t>(remainingSegs); | ||
| 188 | +} | ||
| 189 | + | ||
| 190 | +template <typename T, typename OUT_IDX_T, bool IsDescend> | ||
| 191 | +__aicore__ inline void TopKSmallAxisTwoStage<T, OUT_IDX_T, IsDescend>::ProcessBatch(uint32_t batchId, | ||
| 192 | + uint32_t validSegs) | ||
| 193 | +{ | ||
| 194 | + uint32_t totalElems = validSegs * segmentLen_; | ||
| 195 | + int64_t segStart = static_cast<int64_t>(batchId) * static_cast<int64_t>(batchSize_); | ||
| 196 | + // Pipeline: load -> two-stage sort (Stage1 flat sort + Stage2 per-segment restore) -> topk store. | ||
| 197 | + uint64_t outerId = 0; | ||
| 198 | + uint64_t innerStart = 0; | ||
| 199 | + if (isNonLastAxis_) { | ||
| 200 | + // batchId is linearized as outerId * innerLoopNum_ + innerTileId. | ||
| 201 | + outerId = static_cast<uint64_t>(batchId / innerLoopNum_); | ||
| 202 | + uint32_t innerTileId = batchId % innerLoopNum_; | ||
| 203 | + innerStart = static_cast<uint64_t>(innerTileId) * static_cast<uint64_t>(batchSize_); | ||
| 204 | + uint64_t outerBaseOffset = outerId * static_cast<uint64_t>(segmentLen_) * static_cast<uint64_t>(innerSize_); | ||
| 205 | + Base::LoadNonLastBatch(inputGm_, outerBaseOffset, innerStart, static_cast<uint64_t>(innerSize_), validSegs, | ||
| 206 | + totalElems); | ||
| 207 | + } else { | ||
| 208 | + Base::LoadContiguousBatch(inputGm_, segStart * static_cast<int64_t>(segmentLen_), totalElems); | ||
| 209 | + } | ||
| 210 | + Base::RunTwoStageSort(totalElems); | ||
| 211 | + RunBitonicFinalize(validSegs); | ||
| 212 | + if (isNonLastAxis_) { | ||
| 213 | + StoreNonLastTopK(outerId, innerStart, validSegs); | ||
| 214 | + } else { | ||
| 215 | + StoreTopK(segStart, validSegs); | ||
| 216 | + } | ||
| 217 | +} | ||
| 218 | + | ||
| 219 | +template <typename T, typename OUT_IDX_T, bool IsDescend> | ||
| 220 | +__aicore__ inline void TopKSmallAxisTwoStage<T, OUT_IDX_T, IsDescend>::RunBitonicFinalize(uint32_t validSegs) | ||
| 221 | +{ | ||
| 222 | + if (!useBitonicFinalize_ || validSegs == 0U) { | ||
| 223 | + return; | ||
| 224 | + } | ||
| 225 | + RunBitonicFinalizeSelectionRows<T, uint32_t, IsDescend>(finalValues_, finalIdx_, kValue_, validSegs, segmentLen_, | ||
| 226 | + segmentLen_); | ||
| 227 | +} | ||
| 228 | + | ||
| 229 | +template <typename T, typename OUT_IDX_T, bool IsDescend> | ||
| 230 | +__aicore__ inline void TopKSmallAxisTwoStage<T, OUT_IDX_T, IsDescend>::StoreTopK(int64_t segStart, uint32_t validSegs) | ||
| 231 | +{ | ||
| 232 | + if (validSegs == 0U) { | ||
| 233 | + return; | ||
| 234 | + } | ||
| 235 | + // Rank-inverse writes final buffers via SIMT VF; BuildOutputs writes them via vector APIs. | ||
| 236 | + // Wait for the producing VF/vector work before the SIMT topk store reads them. | ||
| 237 | + event_t eventIdVToS = static_cast<event_t>(pipe_->FetchEventID(HardEvent::V_S)); | ||
| 238 | + SetFlag<HardEvent::V_S>(eventIdVToS); | ||
| 239 | + WaitFlag<HardEvent::V_S>(eventIdVToS); | ||
| 240 | + | ||
| 241 | + // Output layout is [totalSegs, k]; each sorted segment contributes its first k elements. | ||
| 242 | + uint64_t outputStart = static_cast<uint64_t>(segStart) * static_cast<uint64_t>(kValue_); | ||
| 243 | + asc_vf_call<SimtStoreTopKTwoStageBatch<T, OUT_IDX_T>>( | ||
| 244 | + dim3(SmallAxisCommon::TWO_STAGE_THREAD_NUM), validSegs, segmentLen_, kValue_, outputStart, | ||
| 245 | + (__ubuf__ T*)finalValues_.GetPhyAddr(), (__ubuf__ uint32_t*)finalIdx_.GetPhyAddr(), | ||
| 246 | + (__gm__ volatile T*)outValueGm_.GetPhyAddr(), (__gm__ volatile OUT_IDX_T*)outIdxGm_.GetPhyAddr()); | ||
| 247 | + eventIdVToS = static_cast<event_t>(pipe_->FetchEventID(HardEvent::V_S)); | ||
| 248 | + SetFlag<HardEvent::V_S>(eventIdVToS); | ||
| 249 | + WaitFlag<HardEvent::V_S>(eventIdVToS); | ||
| 250 | +} | ||
| 251 | + | ||
| 252 | +template <typename T, typename OUT_IDX_T, bool IsDescend> | ||
| 253 | +__aicore__ inline void TopKSmallAxisTwoStage<T, OUT_IDX_T, IsDescend>::StoreNonLastTopK(uint64_t outerId, | ||
| 254 | + uint64_t innerStart, | ||
| 255 | + uint32_t validSegs) | ||
| 256 | +{ | ||
| 257 | + // Output layout is [outer, k, inner]; the topk axis replaces segmentLen with kValue_. | ||
| 258 | + uint64_t outputBase = outerId * static_cast<uint64_t>(kValue_) * static_cast<uint64_t>(innerSize_); | ||
| 259 | + event_t eventIdVToS = static_cast<event_t>(pipe_->FetchEventID(HardEvent::V_S)); | ||
| 260 | + SetFlag<HardEvent::V_S>(eventIdVToS); | ||
| 261 | + WaitFlag<HardEvent::V_S>(eventIdVToS); | ||
| 262 | + asc_vf_call<SimtStoreTopKNonLastTwoStageBatch<T, OUT_IDX_T>>( | ||
| 263 | + dim3(SmallAxisCommon::TWO_STAGE_THREAD_NUM), validSegs, segmentLen_, kValue_, outputBase, innerStart, | ||
| 264 | + static_cast<uint64_t>(innerSize_), (__ubuf__ T*)finalValues_.GetPhyAddr(), | ||
| 265 | + (__ubuf__ uint32_t*)finalIdx_.GetPhyAddr(), (__gm__ volatile T*)outValueGm_.GetPhyAddr(), | ||
| 266 | + (__gm__ volatile OUT_IDX_T*)outIdxGm_.GetPhyAddr()); | ||
| 267 | + eventIdVToS = static_cast<event_t>(pipe_->FetchEventID(HardEvent::V_S)); | ||
| 268 | + SetFlag<HardEvent::V_S>(eventIdVToS); | ||
| 269 | + WaitFlag<HardEvent::V_S>(eventIdVToS); | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +} // namespace topkV2 | ||
| 273 | + | ||
| 274 | +#endif | ||
| @@ -0,0 +1,245 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | +/*! | ||
| 11 | + * \file top_k_small_bitonic_common.h | ||
| 12 | + * \brief 小规模 (2 <= k <= 32) 双调收尾排序的公共常量、类型别名与比较 key 语义。 | ||
| 13 | + */ | ||
| 14 | +#ifndef TOP_K_SMALL_BITONIC_COMMON_H | ||
| 15 | +#define TOP_K_SMALL_BITONIC_COMMON_H | ||
| 16 | + | ||
| 17 | +#include <type_traits> | ||
| 18 | + | ||
| 19 | +#include "kernel_operator.h" | ||
| 20 | +#include "simt_api/asc_bf16.h" | ||
| 21 | +#include "simt_api/asc_fp16.h" | ||
| 22 | +#include "simt_api/asc_simt.h" | ||
| 23 | +#include "simt_api/device_warp_functions.h" | ||
| 24 | +#include "simt_api/math_functions.h" | ||
| 25 | +#include "top_k_constant_var_simd.h" | ||
| 26 | +#include "top_k_util_type_simd.h" | ||
| 27 | + | ||
| 28 | +namespace topkV2 { | ||
| 29 | +using namespace AscendC; | ||
| 30 | + | ||
| 31 | +constexpr uint32_t BITONIC_SMALL_TOPK_MAX_ROWS = 32U; | ||
| 32 | +constexpr uint32_t BITONIC_SMALL_TOPK_THREADS = BITONIC_SMALL_TOPK_SIZE * BITONIC_SMALL_TOPK_MAX_ROWS; | ||
| 33 | +constexpr uint32_t BITONIC_SMALL_TOPK_ROWS_PER_LAUNCH = 1024U; | ||
| 34 | +constexpr uint32_t BITONIC_SMALL_TOPK_PACKED_MAX_K = 16U; | ||
| 35 | +constexpr uint32_t BITONIC_SMALL_TOPK_ALLEQ_PERM_SRC0[BITONIC_SMALL_TOPK_SIZE - 1U] = { | ||
| 36 | + 1U, 2U, 1U, 1U, 1U, // k = 2..6 | ||
| 37 | + 5U, 5U, 5U, 5U, 5U, 5U, 5U, 5U, 5U, 5U, 5U, 5U, 5U, 5U, 5U, // k = 7..21 | ||
| 38 | + 21U, 21U, 21U, 21U, 21U, 21U, 21U, 21U, 21U, 21U, 21U}; // k = 22..32 | ||
| 39 | + | ||
| 40 | +// 重复检测行状态位 (BitonicSmallRegCombineRowFlag 合成,2 bit 协议): | ||
| 41 | +// bit0 = 存在相邻值等价对 (NaN 感知归一);bit1 = 存在相邻逐位不等对。 | ||
| 42 | +// 组合语义:0=clean(防御值) / 1=allEq(行内逐位全等,走全等快路径) / | ||
| 43 | +// 2=clean(严格序,早退) / 3=full(有重复且位模式不齐,走全量 finalize)。 | ||
| 44 | +constexpr uint32_t BITONIC_SMALL_TOPK_ROW_FLAG_HAS_DUPLICATE = 1U; | ||
| 45 | +constexpr uint32_t BITONIC_SMALL_TOPK_ROW_FLAG_HAS_VALUE_BREAK = 2U; | ||
| 46 | +// allEq = 有值等价对且无逐位不等对 | ||
| 47 | +constexpr uint32_t BITONIC_SMALL_TOPK_ROW_FLAG_ALL_EQ = BITONIC_SMALL_TOPK_ROW_FLAG_HAS_DUPLICATE; | ||
| 48 | + | ||
| 49 | +template <typename T> | ||
| 50 | +using BitonicSmallGatherIndexType = std::conditional_t< | ||
| 51 | + sizeof(T) == sizeof(uint8_t), uint8_t, std::conditional_t<sizeof(T) == sizeof(uint16_t), uint16_t, uint32_t>>; | ||
| 52 | + | ||
| 53 | +template <typename T> | ||
| 54 | +using BitonicSmallGatherSignedIndexType = std::conditional_t< | ||
| 55 | + sizeof(T) == sizeof(uint8_t), int8_t, std::conditional_t<sizeof(T) == sizeof(uint16_t), int16_t, int32_t>>; | ||
| 56 | + | ||
| 57 | +template <typename T> | ||
| 58 | +using BitonicSmallRegType = std::conditional_t< | ||
| 59 | + std::is_same_v<T, int8_t> || std::is_same_v<T, int16_t> || std::is_same_v<T, int32_t>, int32_t, | ||
| 60 | + std::conditional_t<std::is_same_v<T, uint8_t> || std::is_same_v<T, uint16_t> || std::is_same_v<T, uint32_t>, | ||
| 61 | + uint32_t, T>>; | ||
| 62 | + | ||
| 63 | +template <typename T> | ||
| 64 | +constexpr bool IsBitonicFloatType = std::is_same_v<T, float> || std::is_same_v<T, half> || | ||
| 65 | + std::is_same_v<T, bfloat16_t>; | ||
| 66 | + | ||
| 67 | +constexpr Reg::CastTrait BITONIC_SMALL_CAST_U16_TO_U32_EVEN = {Reg::RegLayout::ZERO, Reg::SatMode::UNKNOWN, | ||
| 68 | + Reg::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; | ||
| 69 | +constexpr Reg::CastTrait BITONIC_SMALL_CAST_U16_TO_U32_ODD = {Reg::RegLayout::ONE, Reg::SatMode::UNKNOWN, | ||
| 70 | + Reg::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; | ||
| 71 | +constexpr Reg::CastTrait BITONIC_SMALL_CAST_U32_TO_U16 = {Reg::RegLayout::ZERO, Reg::SatMode::NO_SAT, | ||
| 72 | + Reg::MaskMergeMode::ZEROING, RoundMode::CAST_RINT}; | ||
| 73 | + | ||
| 74 | +/*! | ||
| 75 | + * \brief 将 16 位数据从 UB 加载到 32 位向量寄存器,并把位模式展开为 uint32。 | ||
| 76 | + * | ||
| 77 | + * \param[out] valueBits 输出的 32 位位模式寄存器,每通道一个 16 位元素的 bits | ||
| 78 | + * \param[in] valueAddr UB 中 16 位数据的起始地址 | ||
| 79 | + * \param[in] validCount 有效元素个数 (<= 32) | ||
| 80 | + */ | ||
| 81 | +template <typename T> | ||
| 82 | +__simd_callee__ inline void BitonicSmallRegLoadB16Bits(Reg::RegTensor<uint32_t>& valueBits, __ubuf__ T* valueAddr, | ||
| 83 | + uint32_t validCount) | ||
| 84 | +{ | ||
| 85 | + uint32_t valueCount = validCount; | ||
| 86 | + Reg::MaskReg valueMask = Reg::UpdateMask<T>(valueCount); | ||
| 87 | + Reg::RegTensor<uint16_t> rawValue; | ||
| 88 | + Reg::RegTensor<uint32_t> evenValue; | ||
| 89 | + Reg::RegTensor<uint32_t> oddValue; | ||
| 90 | + Reg::RegTensor<uint32_t> unusedValue; | ||
| 91 | + Reg::LoadAlign<T, Reg::DataCopyMode::DATA_BLOCK_COPY>((Reg::RegTensor<T>&)rawValue, valueAddr, 1U, valueMask); | ||
| 92 | + Reg::Cast<uint32_t, uint16_t, BITONIC_SMALL_CAST_U16_TO_U32_EVEN>(evenValue, rawValue, valueMask); | ||
| 93 | + Reg::Cast<uint32_t, uint16_t, BITONIC_SMALL_CAST_U16_TO_U32_ODD>(oddValue, rawValue, valueMask); | ||
| 94 | + Reg::Interleave<uint32_t>(valueBits, unusedValue, evenValue, oddValue); | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +/*! | ||
| 98 | + * \brief 将 32 位位模式寄存器还原为 16 位数据并存回 UB。 | ||
| 99 | + * | ||
| 100 | + * 这是 BitonicSmallRegLoadB16Bits 的逆操作:把每通道一个 16 位元素位模式的 | ||
| 101 | + * uint32 寄存器,重新打包为 16 位连续存储后写回 UB。 | ||
| 102 | + * | ||
| 103 | + * | ||
| 104 | + * \param[out] valueAddr UB 目标地址 | ||
| 105 | + * \param[in] valueBits 排序后的 32 位位模式寄存器 | ||
| 106 | + * \param[in] validCount 有效元素个数 | ||
| 107 | + * \param[in] validMask 有效通道掩码 | ||
| 108 | + */ | ||
| 109 | +template <typename T> | ||
| 110 | +__simd_callee__ inline void BitonicSmallRegStoreB16Bits(__ubuf__ T* valueAddr, Reg::RegTensor<uint32_t>& valueBits, | ||
| 111 | + uint32_t validCount, Reg::MaskReg& validMask) | ||
| 112 | +{ | ||
| 113 | + uint32_t valueCount = validCount; | ||
| 114 | + Reg::MaskReg valueMask = Reg::UpdateMask<T>(valueCount); | ||
| 115 | + Reg::RegTensor<uint16_t> rawValue; | ||
| 116 | + Reg::Cast<uint16_t, uint32_t, BITONIC_SMALL_CAST_U32_TO_U16>(rawValue, valueBits, validMask); | ||
| 117 | + Reg::Pack(rawValue, (Reg::RegTensor<uint32_t>&)rawValue); | ||
| 118 | + Reg::StoreAlign<T, Reg::DataCopyMode::DATA_BLOCK_COPY>(valueAddr, (Reg::RegTensor<T>&)rawValue, 1U, valueMask); | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +/*! | ||
| 122 | + * \brief 浮点类型构建单调有序 key (±0 归一后,NaN 覆盖前) (Reg/SIMD 路径)。 | ||
| 123 | + * | ||
| 124 | + * ±0 位模式先归一为 +0,避免 -0 翻转后越过普通负数;负数全位翻转、 | ||
| 125 | + * 正数仅翻符号位,使 uint32 无符号比较与浮点序一致。 | ||
| 126 | + * absoluteBits 输出原始绝对值位模式,供 NaN 哨兵覆盖段复用。 | ||
| 127 | + */ | ||
| 128 | +template <typename T, bool IsLargest> | ||
| 129 | +__simd_callee__ inline void BitonicSmallRegBuildFloatOrderedKey32(Reg::RegTensor<uint32_t>& key, | ||
| 130 | + Reg::RegTensor<uint32_t>& rawBits, | ||
| 131 | + Reg::RegTensor<uint32_t>& absoluteBits, | ||
| 132 | + Reg::RegTensor<uint32_t>& allBitsReg, | ||
| 133 | + uint32_t signBit, Reg::MaskReg& activeMask) | ||
| 134 | +{ | ||
| 135 | + Reg::RegTensor<uint32_t> exponentBits; | ||
| 136 | + Reg::RegTensor<uint32_t> positiveXor; | ||
| 137 | + Reg::RegTensor<uint32_t> xorMask; | ||
| 138 | + Reg::RegTensor<uint32_t> signMask; | ||
| 139 | + Reg::RegTensor<uint32_t> zeroReg; | ||
| 140 | + Reg::MaskReg zeroMask; | ||
| 141 | + Reg::MaskReg negativeMask; | ||
| 142 | + Reg::Duplicate(zeroReg, 0U); | ||
| 143 | + Reg::Duplicate(signMask, signBit); | ||
| 144 | + Reg::And(absoluteBits, rawBits, allBitsReg, activeMask); | ||
| 145 | + Reg::And(exponentBits, rawBits, signMask, activeMask); | ||
| 146 | + Reg::Xor(absoluteBits, rawBits, exponentBits, activeMask); | ||
| 147 | + Reg::Compares<uint32_t, CMPMODE::EQ>(zeroMask, absoluteBits, 0U, activeMask); | ||
| 148 | + Reg::Select<uint32_t>(rawBits, zeroReg, rawBits, zeroMask); | ||
| 149 | + Reg::And(exponentBits, rawBits, signMask, activeMask); | ||
| 150 | + Reg::Compares<uint32_t, CMPMODE::NE>(negativeMask, exponentBits, 0U, activeMask); | ||
| 151 | + Reg::Duplicate(positiveXor, signBit); | ||
| 152 | + Reg::Select<uint32_t>(xorMask, allBitsReg, positiveXor, negativeMask); | ||
| 153 | + Reg::Xor(key, rawBits, xorMask, activeMask); | ||
| 154 | + if constexpr (!IsLargest) { | ||
| 155 | + Reg::Xor(key, key, allBitsReg, activeMask); | ||
| 156 | + } | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +/*! | ||
| 160 | + * \brief 浮点类型 NaN 哨兵覆盖 (Reg/SIMD 路径)。 | ||
| 161 | + * | ||
| 162 | + * 指数位全 1 且尾数非 0 判定为 NaN,key 覆盖为序边界哨兵 | ||
| 163 | + * (IsLargest 取 allBits,否则取 1),保证 NaN 与任意数值可比。 | ||
| 164 | + */ | ||
| 165 | +template <typename T, bool IsLargest> | ||
| 166 | +__simd_callee__ inline void BitonicSmallRegOverwriteNanKey32(Reg::RegTensor<uint32_t>& key, | ||
| 167 | + Reg::RegTensor<uint32_t>& absoluteBits, uint32_t allBits, | ||
| 168 | + Reg::MaskReg& activeMask) | ||
| 169 | +{ | ||
| 170 | + constexpr uint32_t exponentMask = std::is_same_v<T, half> ? 0x7c00U : | ||
| 171 | + (std::is_same_v<T, bfloat16_t> ? 0x7f80U : 0x7f800000U); | ||
| 172 | + constexpr uint32_t fractionMask = std::is_same_v<T, half> ? 0x03ffU : | ||
| 173 | + (std::is_same_v<T, bfloat16_t> ? 0x007fU : 0x007fffffU); | ||
| 174 | + Reg::RegTensor<uint32_t> exponentBits; | ||
| 175 | + Reg::RegTensor<uint32_t> fractionBits; | ||
| 176 | + Reg::RegTensor<uint32_t> nanKey; | ||
| 177 | + Reg::RegTensor<uint32_t> signMask; | ||
| 178 | + Reg::MaskReg exponentMaskReg; | ||
| 179 | + Reg::MaskReg fractionMaskReg; | ||
| 180 | + Reg::MaskReg nanMask; | ||
| 181 | + Reg::Duplicate(signMask, exponentMask); | ||
| 182 | + Reg::And(exponentBits, absoluteBits, signMask, activeMask); | ||
| 183 | + Reg::Duplicate(signMask, fractionMask); | ||
| 184 | + Reg::And(fractionBits, absoluteBits, signMask, activeMask); | ||
| 185 | + Reg::Compares<uint32_t, CMPMODE::EQ>(exponentMaskReg, exponentBits, exponentMask, activeMask); | ||
| 186 | + Reg::Compares<uint32_t, CMPMODE::NE>(fractionMaskReg, fractionBits, 0U, activeMask); | ||
| 187 | + Reg::And(nanMask, exponentMaskReg, fractionMaskReg, activeMask); | ||
| 188 | + Reg::Duplicate(nanKey, IsLargest ? allBits : 1U); | ||
| 189 | + Reg::Select<uint32_t>(key, nanKey, key, nanMask); | ||
| 190 | +} | ||
| 191 | + | ||
| 192 | +/*! | ||
| 193 | + * \brief 整数类型构建单调有序 key (Reg/SIMD 路径)。 | ||
| 194 | + * | ||
| 195 | + * 有符号类型翻转符号位,使 uint32 无符号比较与有符号序一致; | ||
| 196 | + * 求最小值时再整体取反,统一为最大值语义的降序 key。 | ||
| 197 | + */ | ||
| 198 | +template <typename T, bool IsLargest> | ||
| 199 | +__simd_callee__ inline void BitonicSmallRegBuildIntegerKey32(Reg::RegTensor<uint32_t>& key, | ||
| 200 | + Reg::RegTensor<uint32_t>& rawBits, | ||
| 201 | + Reg::RegTensor<uint32_t>& allBitsReg, uint32_t signBit, | ||
| 202 | + Reg::MaskReg& activeMask) | ||
| 203 | +{ | ||
| 204 | + Reg::RegTensor<uint32_t> xorMask; | ||
| 205 | + Reg::Duplicate(xorMask, std::is_signed_v<T> ? signBit : 0U); | ||
| 206 | + Reg::Xor(key, rawBits, xorMask, activeMask); | ||
| 207 | + if constexpr (!IsLargest) { | ||
| 208 | + Reg::Xor(key, key, allBitsReg, activeMask); | ||
| 209 | + } | ||
| 210 | +} | ||
| 211 | + | ||
| 212 | +/*! | ||
| 213 | + * \brief 将任意类型数据的位模式转换为可单调比较的 32 位无符号整数 key。 | ||
| 214 | + * | ||
| 215 | + * 按 dtype 位模式分支:浮点类型走有序 key 构建 + NaN 哨兵覆盖, | ||
| 216 | + * 整数类型走符号位翻转,分支语义与拆分前完全一致。 | ||
| 217 | + * | ||
| 218 | + * \param[out] key 生成的 32 位排序 key | ||
| 219 | + * \param[in] valueBits 原始数据的 32 位位模式 | ||
| 220 | + * \param[in] activeMask 活跃通道掩码 | ||
| 221 | + */ | ||
| 222 | +template <typename T, bool IsLargest> | ||
| 223 | +__simd_callee__ inline void BitonicSmallRegBuildKey32(Reg::RegTensor<uint32_t>& key, | ||
| 224 | + Reg::RegTensor<uint32_t>& valueBits, Reg::MaskReg& activeMask) | ||
| 225 | +{ | ||
| 226 | + constexpr uint32_t bitWidth = sizeof(T) * 8U; | ||
| 227 | + constexpr uint32_t signBit = 1U << (bitWidth - 1U); | ||
| 228 | + constexpr uint32_t allBits = sizeof(T) == sizeof(uint32_t) ? UINT32_MAX : ((1U << bitWidth) - 1U); | ||
| 229 | + Reg::RegTensor<uint32_t> rawBits; | ||
| 230 | + Reg::RegTensor<uint32_t> allBitsReg; | ||
| 231 | + Reg::Duplicate(allBitsReg, allBits); | ||
| 232 | + Reg::And(rawBits, valueBits, allBitsReg, activeMask); | ||
| 233 | + if constexpr (IsBitonicFloatType<T>) { | ||
| 234 | + Reg::RegTensor<uint32_t> absoluteBits; | ||
| 235 | + BitonicSmallRegBuildFloatOrderedKey32<T, IsLargest>(key, rawBits, absoluteBits, allBitsReg, signBit, | ||
| 236 | + activeMask); | ||
| 237 | + BitonicSmallRegOverwriteNanKey32<T, IsLargest>(key, absoluteBits, allBits, activeMask); | ||
| 238 | + } else { | ||
| 239 | + BitonicSmallRegBuildIntegerKey32<T, IsLargest>(key, rawBits, allBitsReg, signBit, activeMask); | ||
| 240 | + } | ||
| 241 | +} | ||
| 242 | + | ||
| 243 | +} // namespace topkV2 | ||
| 244 | + | ||
| 245 | +#endif // TOP_K_SMALL_BITONIC_COMMON_H | ||
| @@ -28,6 +28,8 @@ | |||
| 28 | #include "arch35/radix_sort_top_k_inter_core_template_optimization.h" | 28 | #include "arch35/radix_sort_top_k_inter_core_template_optimization.h" |
| 29 | #include "arch35/sort_and_top_k_more_core.h" | 29 | #include "arch35/sort_and_top_k_more_core.h" |
| 30 | #include "arch35/top_k_non_last_small_non_transpose.h" | 30 | #include "arch35/top_k_non_last_small_non_transpose.h" |
| 31 | +#include "arch35/top_k_small_axis_insertion.h" | ||
| 32 | +#include "arch35/top_k_small_axis_two_stage.h" | ||
| 31 | 33 | ||
| 32 | using namespace AscendC; | 34 | using namespace AscendC; |
| 33 | using namespace SortAndTopK; | 35 | using namespace SortAndTopK; |
| @@ -68,6 +70,38 @@ const uint32_t MULT_CORE_OPTIM_MODE = 4; | |||
| 68 | const uint32_t SORT_AND_TOP_K_MODE = 5; | 70 | const uint32_t SORT_AND_TOP_K_MODE = 5; |
| 69 | const uint32_t NON_LAST_SMALL_AXIS_MODE = 8; | 71 | const uint32_t NON_LAST_SMALL_AXIS_MODE = 8; |
| 70 | const uint32_t NON_LAST_SMALL_AXIS_MERGE_SORT = 1; | 72 | const uint32_t NON_LAST_SMALL_AXIS_MERGE_SORT = 1; |
| 73 | +const uint32_t SMALL_AXIS_INSERTION_MODE = 9; | ||
| 74 | +const uint32_t SMALL_AXIS_TWO_STAGE_MODE = 10; | ||
| 75 | + | ||
| 76 | +template <typename T, typename T_INDEX_TO> | ||
| 77 | +__aicore__ inline void TopKSmallAxisInsertionOpObject(GM_ADDR x, GM_ADDR values, GM_ADDR indices, GM_ADDR tiling) | ||
| 78 | +{ | ||
| 79 | + GET_TILING_DATA(tilingData, tiling); | ||
| 80 | + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIV_1_0); | ||
| 81 | + bool isLargest = (tilingData.isLargest > 0) ? true : false; | ||
| 82 | + TPipe pipe; | ||
| 83 | + if (isLargest) { | ||
| 84 | + if constexpr (std::is_same_v<bfloat16_t, T>) { | ||
| 85 | + TopKSmallAxisInsertion<T, float, T_INDEX_TO, true> op; | ||
| 86 | + op.Init(x, values, indices, &tilingData, &pipe); | ||
| 87 | + op.Process(); | ||
| 88 | + } else { | ||
| 89 | + TopKSmallAxisInsertion<T, T, T_INDEX_TO, true> op; | ||
| 90 | + op.Init(x, values, indices, &tilingData, &pipe); | ||
| 91 | + op.Process(); | ||
| 92 | + } | ||
| 93 | + } else { | ||
| 94 | + if constexpr (std::is_same_v<bfloat16_t, T>) { | ||
| 95 | + TopKSmallAxisInsertion<T, float, T_INDEX_TO, false> op; | ||
| 96 | + op.Init(x, values, indices, &tilingData, &pipe); | ||
| 97 | + op.Process(); | ||
| 98 | + } else { | ||
| 99 | + TopKSmallAxisInsertion<T, T, T_INDEX_TO, false> op; | ||
| 100 | + op.Init(x, values, indices, &tilingData, &pipe); | ||
| 101 | + op.Process(); | ||
| 102 | + } | ||
| 103 | + } | ||
| 104 | +} | ||
| 71 | 105 | ||
| 72 | template <typename T, typename UNSINGED_TYPE, int32_t NUM_PASS, typename T_INDEX, typename T_INDEX_TO, | 106 | template <typename T, typename UNSINGED_TYPE, int32_t NUM_PASS, typename T_INDEX, typename T_INDEX_TO, |
| 73 | bool IS_BITONIC_SORT> | 107 | bool IS_BITONIC_SORT> |
| @@ -260,6 +294,24 @@ __aicore__ inline void RadixSortTopKSingleBlockOpObject(GM_ADDR x, GM_ADDR k, GM | |||
| 260 | } | 294 | } |
| 261 | } | 295 | } |
| 262 | 296 | ||
| 297 | +template <typename T, typename T_INDEX_TO> | ||
| 298 | +__aicore__ inline void TopKSmallAxisTwoStageOpObject(GM_ADDR x, GM_ADDR values, GM_ADDR indices, GM_ADDR tiling) | ||
| 299 | +{ | ||
| 300 | + GET_TILING_DATA(tilingData, tiling); | ||
| 301 | + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIV_1_0); | ||
| 302 | + bool isLargest = (tilingData.isLargest > 0) ? true : false; | ||
| 303 | + TPipe pipe; | ||
| 304 | + if (isLargest) { | ||
| 305 | + TopKSmallAxisTwoStage<T, T_INDEX_TO, true> op; | ||
| 306 | + op.Init(x, values, indices, &tilingData, &pipe); | ||
| 307 | + op.Process(); | ||
| 308 | + } else { | ||
| 309 | + TopKSmallAxisTwoStage<T, T_INDEX_TO, false> op; | ||
| 310 | + op.Init(x, values, indices, &tilingData, &pipe); | ||
| 311 | + op.Process(); | ||
| 312 | + } | ||
| 313 | +} | ||
| 314 | + | ||
| 263 | template <typename T, typename UNSINGED_TYPE, int32_t NUM_PASS, typename T_INDEX_TO, bool IS_BITONIC_SORT> | 315 | template <typename T, typename UNSINGED_TYPE, int32_t NUM_PASS, typename T_INDEX_TO, bool IS_BITONIC_SORT> |
| 264 | __aicore__ inline void generateOpObject(GM_ADDR x, GM_ADDR k, GM_ADDR values, GM_ADDR indices, GM_ADDR globalWorkGm, | 316 | __aicore__ inline void generateOpObject(GM_ADDR x, GM_ADDR k, GM_ADDR values, GM_ADDR indices, GM_ADDR globalWorkGm, |
| 265 | GM_ADDR tiling) | 317 | GM_ADDR tiling) |
| @@ -273,6 +325,20 @@ __aicore__ inline void generateOpObject(GM_ADDR x, GM_ADDR k, GM_ADDR values, GM | |||
| 273 | bool isInInt32Range = (tilingData.isInInt32Range > 0) ? true : false; | 325 | bool isInInt32Range = (tilingData.isInInt32Range > 0) ? true : false; |
| 274 | bool isMultiCoreOptimMode = (tilingData.modeType == MULT_CORE_OPTIM_MODE) ? true : false; | 326 | bool isMultiCoreOptimMode = (tilingData.modeType == MULT_CORE_OPTIM_MODE) ? true : false; |
| 275 | bool isNonLastSmallAxis = (tilingData.modeType == NON_LAST_SMALL_AXIS_MODE) ? true : false; | 327 | bool isNonLastSmallAxis = (tilingData.modeType == NON_LAST_SMALL_AXIS_MODE) ? true : false; |
| 328 | + bool isSmallAxisInsertion = (tilingData.modeType == SMALL_AXIS_INSERTION_MODE) ? true : false; | ||
| 329 | + bool isSmallAxisTwoStage = (tilingData.modeType == SMALL_AXIS_TWO_STAGE_MODE) ? true : false; | ||
| 330 | + | ||
| 331 | + if (isSmallAxisInsertion) { | ||
| 332 | + // 插入排序 | ||
| 333 | + TopKSmallAxisInsertionOpObject<T, T_INDEX_TO>(x, values, indices, tiling); | ||
| 334 | + return; | ||
| 335 | + } | ||
| 336 | + | ||
| 337 | + if (isSmallAxisTwoStage) { | ||
| 338 | + // two stage | ||
| 339 | + TopKSmallAxisTwoStageOpObject<T, T_INDEX_TO>(x, values, indices, tiling); | ||
| 340 | + return; | ||
| 341 | + } | ||
| 276 | 342 | ||
| 277 | if (isNonLastSmallAxis) { | 343 | if (isNonLastSmallAxis) { |
| 278 | if (tilingData.keyParams0 == NON_LAST_SMALL_AXIS_MERGE_SORT) { | 344 | if (tilingData.keyParams0 == NON_LAST_SMALL_AXIS_MERGE_SORT) { |
| @@ -330,7 +396,7 @@ __aicore__ inline void generateOpObject(GM_ADDR x, GM_ADDR k, GM_ADDR values, GM | |||
| 330 | return; | 396 | return; |
| 331 | } | 397 | } |
| 332 | 398 | ||
| 333 | - // 多核处理排序轴模板(老模板) | 399 | + // 多核处理排序轴模板 |
| 334 | if (isInInt32Range) { | 400 | if (isInInt32Range) { |
| 335 | RadixSortTopKOpObject<T, UNSINGED_TYPE, NUM_PASS, int32_t, T_INDEX_TO, IS_BITONIC_SORT>(x, k, values, indices, | 401 | RadixSortTopKOpObject<T, UNSINGED_TYPE, NUM_PASS, int32_t, T_INDEX_TO, IS_BITONIC_SORT>(x, k, values, indices, |
| 336 | globalWorkGm, tiling); | 402 | globalWorkGm, tiling); |
| @@ -11,7 +11,7 @@ | |||
| 11 | """TopKV2 Kernel/GEIR reference and PyTorch benchmark. | 11 | """TopKV2 Kernel/GEIR reference and PyTorch benchmark. |
| 12 | 12 | ||
| 13 | PyTorch ``torch.topk`` is the native GPU competitor where its dtype support | 13 | PyTorch ``torch.topk`` is the native GPU competitor where its dtype support |
| 14 | -permits. The CPU golden reproduces CUDA's threshold gather and | 14 | +permits. The CPU golden reproduces NPU's threshold gather and |
| 15 | SmallBitonicSort for ``sorted=True`` and ``k<=32``. For larger ``k``, equal | 15 | SmallBitonicSort for ``sorted=True`` and ``k<=32``. For larger ``k``, equal |
| 16 | value tie indices are checked semantically; for ``sorted=False``, output order | 16 | value tie indices are checked semantically; for ``sorted=False``, output order |
| 17 | is handled the same way. ACLNN and E2E (torch.topk) pathways are covered by the Aclnn/Torch spec | 17 | is handled the same way. ACLNN and E2E (torch.topk) pathways are covered by the Aclnn/Torch spec |
| @@ -108,7 +108,7 @@ def _normalize_axis(axis, ndim): | |||
| 108 | 108 | ||
| 109 | 109 | ||
| 110 | def _radix_keys(values): | 110 | def _radix_keys(values): |
| 111 | - """Match CUDA TopKTypeConfig ordering for the supported dtypes.""" | 111 | + """Match NPU TopKTypeConfig ordering for the supported dtypes.""" |
| 112 | if values.is_floating_point(): | 112 | if values.is_floating_point(): |
| 113 | width = values.element_size() * 8 | 113 | width = values.element_size() * 8 |
| 114 | view_dtype = torch.int16 if width == 16 else torch.int32 | 114 | view_dtype = torch.int16 if width == 16 else torch.int32 |
| @@ -147,7 +147,7 @@ def _gather_values(x, axis, indices): | |||
| 147 | 147 | ||
| 148 | 148 | ||
| 149 | def _small_bitonic_sort(values, indices, largest): | 149 | def _small_bitonic_sort(values, indices, largest): |
| 150 | - """Reproduce CUDA bitonicSort<32>, including invalid and equal swaps.""" | 150 | + """Reproduce NPU bitonicSort<32>, including invalid and equal swaps.""" |
| 151 | slots = 32 | 151 | slots = 32 |
| 152 | count = values.numel() | 152 | count = values.numel() |
| 153 | keys = torch.zeros(slots, dtype=values.dtype) | 153 | keys = torch.zeros(slots, dtype=values.dtype) |
| @@ -199,7 +199,153 @@ def _small_bitonic_sort(values, indices, largest): | |||
| 199 | return keys[:count], result_indices[:count] | 199 | return keys[:count], result_indices[:count] |
| 200 | 200 | ||
| 201 | 201 | ||
| 202 | -def _cuda_topk_row(row, k, largest, index_dtype): | 202 | +_BITONIC_SCHEDULE_CACHE = {} |
| 203 | + | ||
| 204 | + | ||
| 205 | +def _bitonic_network_schedule(slots=32): | ||
| 206 | + """Compare-exchange levels of the reference 32-slot bitonic network. | ||
| 207 | + | ||
| 208 | + Each level is (pos_list, other_list, direction_list, invert): the reference | ||
| 209 | + swaps a pair when ``swap == direction`` (first phase) or when ``not swap`` | ||
| 210 | + (final merge). Pairs inside one level touch disjoint slots, so a level can | ||
| 211 | + be applied to a whole row batch with advanced indexing. | ||
| 212 | + """ | ||
| 213 | + cached = _BITONIC_SCHEDULE_CACHE.get(slots) | ||
| 214 | + if cached is not None: | ||
| 215 | + return cached | ||
| 216 | + levels = [] | ||
| 217 | + size = 2 | ||
| 218 | + while size < slots: | ||
| 219 | + stride = size // 2 | ||
| 220 | + while stride > 0: | ||
| 221 | + pos_l, other_l, dir_l = [], [], [] | ||
| 222 | + for thread in range(slots // 2): | ||
| 223 | + pos = 2 * thread - (thread & (stride - 1)) | ||
| 224 | + pos_l.append(pos) | ||
| 225 | + other_l.append(pos + stride) | ||
| 226 | + dir_l.append(bool(thread & (size // 2))) | ||
| 227 | + levels.append((pos_l, other_l, dir_l, False)) | ||
| 228 | + stride //= 2 | ||
| 229 | + size *= 2 | ||
| 230 | + stride = slots // 2 | ||
| 231 | + while stride > 0: | ||
| 232 | + pos_l, other_l = [], [] | ||
| 233 | + for thread in range(slots // 2): | ||
| 234 | + pos = 2 * thread - (thread & (stride - 1)) | ||
| 235 | + pos_l.append(pos) | ||
| 236 | + other_l.append(pos + stride) | ||
| 237 | + levels.append((pos_l, other_l, [False] * (slots // 2), True)) | ||
| 238 | + stride //= 2 | ||
| 239 | + for pos_l, other_l, _, _ in levels: | ||
| 240 | + touched = pos_l + other_l | ||
| 241 | + if len(touched) != len(set(touched)): | ||
| 242 | + raise AssertionError("bitonic level pairs overlap; batched apply invalid") | ||
| 243 | + _BITONIC_SCHEDULE_CACHE[slots] = levels | ||
| 244 | + return levels | ||
| 245 | + | ||
| 246 | + | ||
| 247 | +def _small_bitonic_sort_batch(values, indices, largest): | ||
| 248 | + """Batched _small_bitonic_sort: bit-exact with the per-row reference. | ||
| 249 | + | ||
| 250 | + Integer dtypes are carried in an int64 working representation (uint64 via | ||
| 251 | + bit-view) because torch CPU advanced indexing is not implemented for the | ||
| 252 | + unsigned dtypes; comparisons use int64 radix keys, matching _value_better. | ||
| 253 | + Padding values in invalid slots never influence swaps (validity-masked) | ||
| 254 | + nor the returned head (same data movement as the reference). | ||
| 255 | + """ | ||
| 256 | + batch, count = values.shape | ||
| 257 | + slots = 32 | ||
| 258 | + orig_dtype = values.dtype | ||
| 259 | + is_float = orig_dtype.is_floating_point | ||
| 260 | + if is_float: | ||
| 261 | + cmp_keys = torch.zeros((batch, slots), dtype=orig_dtype) | ||
| 262 | + cmp_keys[:, :count] = values | ||
| 263 | + store = cmp_keys | ||
| 264 | + else: | ||
| 265 | + cmp_keys = torch.zeros((batch, slots), dtype=torch.int64) | ||
| 266 | + cmp_keys[:, :count] = _radix_keys(values) | ||
| 267 | + store = torch.zeros((batch, slots), dtype=torch.int64) | ||
| 268 | + if orig_dtype == torch.uint64: | ||
| 269 | + store[:, :count] = values.view(torch.int64) | ||
| 270 | + else: | ||
| 271 | + store[:, :count] = values.to(torch.int64) | ||
| 272 | + result_indices = torch.zeros((batch, slots), dtype=indices.dtype) | ||
| 273 | + result_indices[:, :count] = indices | ||
| 274 | + valid = torch.zeros((batch, slots), dtype=torch.bool) | ||
| 275 | + valid[:, :count] = True | ||
| 276 | + for pos_l, other_l, dir_l, invert in _bitonic_network_schedule(slots): | ||
| 277 | + a = cmp_keys[:, pos_l] | ||
| 278 | + b = cmp_keys[:, other_l] | ||
| 279 | + va = valid[:, pos_l] | ||
| 280 | + vb = valid[:, other_l] | ||
| 281 | + if is_float: | ||
| 282 | + a_nan = torch.isnan(a) | ||
| 283 | + b_nan = torch.isnan(b) | ||
| 284 | + if largest: | ||
| 285 | + better = (a_nan & ~b_nan) | (a > b) | ||
| 286 | + else: | ||
| 287 | + better = (b_nan & ~a_nan) | (a < b) | ||
| 288 | + else: | ||
| 289 | + better = a > b if largest else a < b | ||
| 290 | + swap = (better & va) | ~vb | ||
| 291 | + if invert: | ||
| 292 | + do_swap = ~swap | ||
| 293 | + else: | ||
| 294 | + do_swap = swap == torch.tensor(dir_l, dtype=torch.bool) | ||
| 295 | + a_new = torch.where(do_swap, b, a) | ||
| 296 | + b_new = torch.where(do_swap, a, b) | ||
| 297 | + sa = store[:, pos_l] | ||
| 298 | + sb = store[:, other_l] | ||
| 299 | + sa_new = torch.where(do_swap, sb, sa) | ||
| 300 | + sb_new = torch.where(do_swap, sa, sb) | ||
| 301 | + va_new = torch.where(do_swap, vb, va) | ||
| 302 | + vb_new = torch.where(do_swap, va, vb) | ||
| 303 | + ia = result_indices[:, pos_l] | ||
| 304 | + ib = result_indices[:, other_l] | ||
| 305 | + ia_new = torch.where(do_swap, ib, ia) | ||
| 306 | + ib_new = torch.where(do_swap, ia, ib) | ||
| 307 | + cmp_keys[:, pos_l] = a_new | ||
| 308 | + cmp_keys[:, other_l] = b_new | ||
| 309 | + if store is not cmp_keys: | ||
| 310 | + store[:, pos_l] = sa_new | ||
| 311 | + store[:, other_l] = sb_new | ||
| 312 | + valid[:, pos_l] = va_new | ||
| 313 | + valid[:, other_l] = vb_new | ||
| 314 | + result_indices[:, pos_l] = ia_new | ||
| 315 | + result_indices[:, other_l] = ib_new | ||
| 316 | + out_values = store[:, :count] | ||
| 317 | + if not is_float: | ||
| 318 | + if orig_dtype == torch.uint64: | ||
| 319 | + out_values = out_values.contiguous().view(torch.uint64) | ||
| 320 | + else: | ||
| 321 | + out_values = out_values.to(orig_dtype) | ||
| 322 | + return out_values, result_indices[:, :count] | ||
| 323 | + | ||
| 324 | + | ||
| 325 | +def _npu_topk_rows_batch(rows, k, largest, index_dtype): | ||
| 326 | + """Batched _npu_topk_row: threshold gather + bitonic sort, bit-exact.""" | ||
| 327 | + n, length = rows.shape | ||
| 328 | + keys = _radix_keys(rows) | ||
| 329 | + threshold_pos = length - k if largest else k - 1 | ||
| 330 | + threshold = torch.kthvalue(keys, threshold_pos + 1, dim=1).values | ||
| 331 | + strict = keys > threshold.unsqueeze(1) if largest else keys < threshold.unsqueeze(1) | ||
| 332 | + equal = keys == threshold.unsqueeze(1) | ||
| 333 | + strict_count = strict.sum(dim=1, keepdim=True) | ||
| 334 | + strict_rank = strict.cumsum(dim=1) - 1 | ||
| 335 | + equal_rank = equal.cumsum(dim=1) - 1 | ||
| 336 | + concat_pos = torch.where(strict, strict_rank, strict_count + equal_rank) | ||
| 337 | + # candidates are exactly the strict positions (ascending) followed by the | ||
| 338 | + # equal positions (ascending), mirroring cat(nonzero(strict), nonzero(eq)) | ||
| 339 | + chosen = (strict | equal) & (concat_pos < k) | ||
| 340 | + columns = torch.arange(length).expand(n, length) | ||
| 341 | + order_key = torch.where(chosen, concat_pos, 2 * length + columns) | ||
| 342 | + gathered = torch.argsort(order_key, dim=1)[:, :k] | ||
| 343 | + values = _gather_values(rows, 1, gathered) | ||
| 344 | + indices = gathered.to(index_dtype) | ||
| 345 | + return _small_bitonic_sort_batch(values, indices, largest) | ||
| 346 | + | ||
| 347 | + | ||
| 348 | +def _npu_topk_row(row, k, largest, index_dtype): | ||
| 203 | keys = _radix_keys(row) | 349 | keys = _radix_keys(row) |
| 204 | threshold_pos = len(keys) - k if largest else k - 1 | 350 | threshold_pos = len(keys) - k if largest else k - 1 |
| 205 | threshold = torch.kthvalue(keys, threshold_pos + 1).values | 351 | threshold = torch.kthvalue(keys, threshold_pos + 1).values |
| @@ -212,7 +358,11 @@ def _cuda_topk_row(row, k, largest, index_dtype): | |||
| 212 | return _small_bitonic_sort(values, indices, largest) | 358 | return _small_bitonic_sort(values, indices, largest) |
| 213 | 359 | ||
| 214 | 360 | ||
| 215 | -def _cuda_small_topk(x, k, dim, largest, index_dtype): | 361 | +_NPU_SMALL_TOPK_PER_ROW_MAX = 4096 |
| 362 | +_NPU_SMALL_TOPK_CHUNK = 200_000 | ||
| 363 | + | ||
| 364 | + | ||
| 365 | +def _npu_small_topk(x, k, dim, largest, index_dtype): | ||
| 216 | axis = _normalize_axis(dim, x.ndim) | 366 | axis = _normalize_axis(dim, x.ndim) |
| 217 | moved = torch.movedim(x, axis, -1).contiguous() | 367 | moved = torch.movedim(x, axis, -1).contiguous() |
| 218 | rows = moved.reshape(-1, moved.shape[-1]) | 368 | rows = moved.reshape(-1, moved.shape[-1]) |
| @@ -220,9 +370,25 @@ def _cuda_small_topk(x, k, dim, largest, index_dtype): | |||
| 220 | shape = list(x.shape) | 370 | shape = list(x.shape) |
| 221 | shape[axis] = k | 371 | shape[axis] = k |
| 222 | return torch.empty(shape, dtype=x.dtype), torch.empty(shape, dtype=index_dtype) | 372 | return torch.empty(shape, dtype=x.dtype), torch.empty(shape, dtype=index_dtype) |
| 223 | - outputs = [_cuda_topk_row(row, k, bool(largest), index_dtype) for row in rows] | 373 | + if rows.shape[0] <= _NPU_SMALL_TOPK_PER_ROW_MAX: |
| 224 | - values = torch.stack([output[0] for output in outputs]) | 374 | + outputs = [_npu_topk_row(row, k, bool(largest), index_dtype) for row in rows] |
| 225 | - indices = torch.stack([output[1] for output in outputs]) | 375 | + values = torch.stack([output[0] for output in outputs]) |
| 376 | + indices = torch.stack([output[1] for output in outputs]) | ||
| 377 | + else: | ||
| 378 | + # Large row counts: batched chunked path (bit-exact with the per-row | ||
| 379 | + # reference, verified by differential tests; the per-row loop costs | ||
| 380 | + # ~10ms/row which is infeasible for million-row rig cases). | ||
| 381 | + value_chunks = [] | ||
| 382 | + index_chunks = [] | ||
| 383 | + for begin in range(0, rows.shape[0], _NPU_SMALL_TOPK_CHUNK): | ||
| 384 | + chunk = rows[begin : begin + _NPU_SMALL_TOPK_CHUNK] | ||
| 385 | + chunk_values, chunk_indices = _npu_topk_rows_batch( | ||
| 386 | + chunk, k, bool(largest), index_dtype | ||
| 387 | + ) | ||
| 388 | + value_chunks.append(chunk_values) | ||
| 389 | + index_chunks.append(chunk_indices) | ||
| 390 | + values = torch.cat(value_chunks, dim=0) | ||
| 391 | + indices = torch.cat(index_chunks, dim=0) | ||
| 226 | moved_shape = (*moved.shape[:-1], k) | 392 | moved_shape = (*moved.shape[:-1], k) |
| 227 | return ( | 393 | return ( |
| 228 | torch.movedim(values.reshape(moved_shape), -1, axis).contiguous(), | 394 | torch.movedim(values.reshape(moved_shape), -1, axis).contiguous(), |
| @@ -257,7 +423,7 @@ def top_k_v2_golden( | |||
| 257 | k_value = _k_value(k) | 423 | k_value = _k_value(k) |
| 258 | index_dtype = _index_dtype(indices_dtype, output_dtypes) | 424 | index_dtype = _index_dtype(indices_dtype, output_dtypes) |
| 259 | if bool(sorted) and 0 < k_value <= 32: | 425 | if bool(sorted) and 0 < k_value <= 32: |
| 260 | - values, indices = _cuda_small_topk(tensor, k_value, dim, largest, index_dtype) | 426 | + values, indices = _npu_small_topk(tensor, k_value, dim, largest, index_dtype) |
| 261 | else: | 427 | else: |
| 262 | values, indices = _topk(tensor, k_value, dim, largest, sorted) | 428 | values, indices = _topk(tensor, k_value, dim, largest, sorted) |
| 263 | indices = indices.to(index_dtype) | 429 | indices = indices.to(index_dtype) |
| @@ -292,6 +458,85 @@ def top_k_v2_input(x, k, *, dim=-1, testcase_name="", **kwargs): | |||
| 292 | shape = [1] * tensor.ndim | 458 | shape = [1] * tensor.ndim |
| 293 | shape[axis] = tensor.shape[axis] | 459 | shape[axis] = tensor.shape[axis] |
| 294 | tensor.copy_(axis_values.reshape(shape).expand(tensor.shape)) | 460 | tensor.copy_(axis_values.reshape(shape).expand(tensor.shape)) |
| 461 | + elif name.endswith("_nan_mixed"): | ||
| 462 | + if tensor.dtype == torch.float32: | ||
| 463 | + pattern = torch.tensor( | ||
| 464 | + [0x7FC00000, 0x7FC00001] * 2, dtype=torch.int32 | ||
| 465 | + ).view(torch.float32) | ||
| 466 | + elif tensor.dtype == torch.float16: | ||
| 467 | + pattern = torch.tensor([0x7E00, 0x7E01] * 2, dtype=torch.int16).view( | ||
| 468 | + torch.float16 | ||
| 469 | + ) | ||
| 470 | + elif tensor.dtype == torch.bfloat16: | ||
| 471 | + pattern = torch.tensor([0x7FC0, 0x7FC1] * 2, dtype=torch.int16).view( | ||
| 472 | + torch.bfloat16 | ||
| 473 | + ) | ||
| 474 | + else: | ||
| 475 | + pattern = None | ||
| 476 | + if pattern is not None: | ||
| 477 | + repeats = (tensor.shape[axis] + pattern.numel() - 1) // pattern.numel() | ||
| 478 | + axis_values = pattern.repeat(repeats)[: tensor.shape[axis]] | ||
| 479 | + shape = [1] * tensor.ndim | ||
| 480 | + shape[axis] = tensor.shape[axis] | ||
| 481 | + tensor.copy_(axis_values.reshape(shape).expand(tensor.shape)) | ||
| 482 | + elif name.endswith("_nan_finite_mixed"): | ||
| 483 | + # Deterministic NaN/finite interleaved segments with the P1 trigger shape: | ||
| 484 | + # a small finite before a NaN and a larger finite after it ([1, NaN, 3, 2, ...]). | ||
| 485 | + # NaN payloads alternate (0x...00/0x...01) so distinct-payload NaN pairs meet | ||
| 486 | + # the double-NaN stable branch; truncation to N=4 keeps the minimal [1, NaN, 3, 2]. | ||
| 487 | + # Bit patterns (hex, as signed literals): 1.0, NaN, 3.0, 2.0, NaN', 5.0, -4.0, 0.0. | ||
| 488 | + if tensor.dtype == torch.float32: | ||
| 489 | + pattern = torch.tensor( | ||
| 490 | + [ | ||
| 491 | + 1065353216, | ||
| 492 | + 2143289344, | ||
| 493 | + 1077936128, | ||
| 494 | + 1073741824, | ||
| 495 | + 2143289345, | ||
| 496 | + 1084227584, | ||
| 497 | + -1065353216, | ||
| 498 | + 0, | ||
| 499 | + ], | ||
| 500 | + dtype=torch.int32, | ||
| 501 | + ).view(torch.float32) | ||
| 502 | + elif tensor.dtype == torch.float16: | ||
| 503 | + pattern = torch.tensor( | ||
| 504 | + [15360, 32256, 16896, 16384, 32257, 17664, -15360, 0], dtype=torch.int16 | ||
| 505 | + ).view(torch.float16) | ||
| 506 | + elif tensor.dtype == torch.bfloat16: | ||
| 507 | + pattern = torch.tensor( | ||
| 508 | + [16256, 32704, 16448, 16384, 32705, 16544, -16256, 0], dtype=torch.int16 | ||
| 509 | + ).view(torch.bfloat16) | ||
| 510 | + else: | ||
| 511 | + pattern = None | ||
| 512 | + if pattern is not None: | ||
| 513 | + repeats = (tensor.shape[axis] + pattern.numel() - 1) // pattern.numel() | ||
| 514 | + axis_values = pattern.repeat(repeats)[: tensor.shape[axis]] | ||
| 515 | + shape = [1] * tensor.ndim | ||
| 516 | + shape[axis] = tensor.shape[axis] | ||
| 517 | + tensor.copy_(axis_values.reshape(shape).expand(tensor.shape)) | ||
| 518 | + elif name.endswith("_signed_zero_mixed"): | ||
| 519 | + axis_len = int(tensor.shape[axis]) | ||
| 520 | + half = (axis_len + 1) // 2 | ||
| 521 | + pos = torch.zeros(half, dtype=tensor.dtype) | ||
| 522 | + neg = torch.full((axis_len - half,), -0.0, dtype=tensor.dtype) | ||
| 523 | + axis_values = torch.cat((pos, neg)) | ||
| 524 | + shape = [1] * tensor.ndim | ||
| 525 | + shape[axis] = axis_len | ||
| 526 | + tensor.copy_(axis_values.reshape(shape).expand(tensor.shape)) | ||
| 527 | + elif name.endswith("_rowmixed"): | ||
| 528 | + axis_len = tensor.shape[axis] | ||
| 529 | + pattern = torch.tensor(patterns["duplicate"], dtype=tensor.dtype) | ||
| 530 | + dup_row = pattern.repeat((axis_len + pattern.numel() - 1) // pattern.numel())[ | ||
| 531 | + :axis_len | ||
| 532 | + ] | ||
| 533 | + unique_row = torch.arange(axis_len, dtype=torch.int64).to(tensor.dtype) | ||
| 534 | + rows = int(tensor.numel() // axis_len) | ||
| 535 | + moved_shape = (*tensor.shape[:axis], *tensor.shape[axis + 1 :], axis_len) | ||
| 536 | + data = torch.stack( | ||
| 537 | + [unique_row if (row % 2 == 0) else dup_row for row in range(rows)] | ||
| 538 | + ).reshape(moved_shape) | ||
| 539 | + tensor.copy_(torch.movedim(data, -1, axis)) | ||
| 295 | return x, k | 540 | return x, k |
| 296 | 541 | ||
| 297 | 542 | ||
| @@ -303,7 +548,7 @@ def _equal_values(lhs, rhs): | |||
| 303 | 548 | ||
| 304 | 549 | ||
| 305 | def _exact_indices(compare_context): | 550 | def _exact_indices(compare_context): |
| 306 | - """Only the Kernel/GEIR golden reproduces CUDA bitonic index order; | 551 | + """Only the Kernel/GEIR golden reproduces NPU bitonic index order; |
| 307 | ACLNN/E2E goldens use torch.topk semantics, so ties are semantic.""" | 552 | ACLNN/E2E goldens use torch.topk semantics, so ties are semantic.""" |
| 308 | api_name = str(getattr(compare_context, "api_name", "") or "") | 553 | api_name = str(getattr(compare_context, "api_name", "") or "") |
| 309 | return not (api_name.startswith("aclnn") or api_name.startswith("torch.")) | 554 | return not (api_name.startswith("aclnn") or api_name.startswith("torch.")) |
| @@ -1,22 +1,16 @@ | |||
| 1 | testcase_name,network_name,op_name,input_shapes,input_dtypes,input_formats,output_shapes,output_dtypes,output_formats,input_ori_shapes,input_ori_formats,output_ori_shapes,output_ori_formats,attributes,input_data_ranges,precision_tolerances,absolute_precision,output_inplace_indexes,output_shape_unknown_indexes,is_enabled,remark,soc_series,priority,dump_file_prefix,manual_input_binaries,manual_golden_binaries | 1 | testcase_name,network_name,op_name,input_shapes,input_dtypes,input_formats,output_shapes,output_dtypes,output_formats,input_ori_shapes,input_ori_formats,output_ori_shapes,output_ori_formats,attributes,input_data_ranges,precision_tolerances,absolute_precision,output_inplace_indexes,output_shape_unknown_indexes,is_enabled,remark,soc_series,priority,dump_file_prefix,manual_input_binaries,manual_golden_binaries |
| 2 | -top_k_v2_small_merge_f32_unique,,top_k_v2,"((1, 2, 1, 2, 1, 2, 1, 32), (1,))","('float32', 'int32')","('ND', 'ND')","((1, 2, 1, 2, 1, 2, 1, 8), (1, 2, 1, 2, 1, 2, 1, 8))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9}","((-100, 100), (8, 8))",,,(),(),True,small_merge rank8 cuda_bitonic,,0,,(),() | ||
| 3 | top_k_v2_small_merge_f16_signed_zero,,top_k_v2,"((4, 33), (1,))","('float16', 'int64')","('ND', 'ND')","((4, 17), (4, 17))","('float16', 'int32')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': False, 'indices_dtype': 3}","((-100, 100), (17, 17))",,,(),(),True,small_merge signed_zero unsorted,,0,,(),() | 2 | top_k_v2_small_merge_f16_signed_zero,,top_k_v2,"((4, 33), (1,))","('float16', 'int64')","('ND', 'ND')","((4, 17), (4, 17))","('float16', 'int32')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': False, 'indices_dtype': 3}","((-100, 100), (17, 17))",,,(),(),True,small_merge signed_zero unsorted,,0,,(),() |
| 4 | -top_k_v2_small_merge_bf16_nan,,top_k_v2,"((3, 257), (1,))","('bfloat16', 'int32')","('ND', 'ND')","((3, 31), (3, 31))","('bfloat16', 'int64')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': True, 'indices_dtype': 9}","((-100, 100), (31, 31))",,,(),(),True,small_merge nan unsorted,,0,,(),() | ||
| 5 | top_k_v2_single_block_i32_unique,,top_k_v2,"((10, 3234), (1,))","('int32', 'int64')","('ND', 'ND')","((10, 258), (10, 258))","('int32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9}","((-100, 100), (258, 258))",,,(),(),True,single_block,,0,,(),() | 3 | top_k_v2_single_block_i32_unique,,top_k_v2,"((10, 3234), (1,))","('int32', 'int64')","('ND', 'ND')","((10, 258), (10, 258))","('int32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9}","((-100, 100), (258, 258))",,,(),(),True,single_block,,0,,(),() |
| 6 | top_k_v2_merge_more_f32_unique,,top_k_v2,"((1, 22340), (1,))","('float32', 'int32')","('ND', 'ND')","((1, 6258), (1, 6258))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9}","((-100, 100), (6258, 6258))",,,(),(),True,fp32_merge_more_core key23003,,0,,(),() | 4 | top_k_v2_merge_more_f32_unique,,top_k_v2,"((1, 22340), (1,))","('float32', 'int32')","('ND', 'ND')","((1, 6258), (1, 6258))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9}","((-100, 100), (6258, 6258))",,,(),(),True,fp32_merge_more_core key23003,,0,,(),() |
| 7 | top_k_v2_merge_intra_f32_unique,,top_k_v2,"((35, 52340), (1,))","('float32', 'int64')","('ND', 'ND')","((35, 21321), (35, 21321))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': False, 'indices_dtype': 9}","((-100, 100), (21321, 21321))",,,(),(),True,fp32_merge_intra_core key33003,,0,,(),() | 5 | top_k_v2_merge_intra_f32_unique,,top_k_v2,"((35, 52340), (1,))","('float32', 'int64')","('ND', 'ND')","((35, 21321), (35, 21321))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': False, 'indices_dtype': 9}","((-100, 100), (21321, 21321))",,,(),(),True,fp32_merge_intra_core key33003,,0,,(),() |
| 8 | -top_k_v2_radix_optim_f32_unique,,top_k_v2,"((10, 22340), (1,))","('float32', 'int32')","('ND', 'ND')","((10, 2), (10, 2))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9}","((-100, 100), (2, 2))",,,(),(),True,radix_multi_core_optim cuda_bitonic,,0,,(),() | 6 | +top_k_v2_radix_optim_f32_unique,,top_k_v2,"((10, 22340), (1,))","('float32', 'int32')","('ND', 'ND')","((10, 2), (10, 2))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((-100, 100), (2, 2))",,,(),(),True,radix_multi_core_optim npu_bitonic,,0,,(),() |
| 9 | top_k_v2_radix_medium_f32_unique,,top_k_v2,"((10, 22340), (1,))","('float32', 'int64')","('ND', 'ND')","((10, 3000), (10, 3000))","('float32', 'int32')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 3}","((-100, 100), (3000, 3000))",,,(),(),True,radix_multi_core_medium,,0,,(),() | 7 | top_k_v2_radix_medium_f32_unique,,top_k_v2,"((10, 22340), (1,))","('float32', 'int64')","('ND', 'ND')","((10, 3000), (10, 3000))","('float32', 'int32')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 3}","((-100, 100), (3000, 3000))",,,(),(),True,radix_multi_core_medium,,0,,(),() |
| 10 | -top_k_v2_radix_big_f32_unique,,top_k_v2,"((1, 3222340), (1,))","('float32', 'int32')","('ND', 'ND')","((1, 1258), (1, 1258))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': False, 'indices_dtype': 9}","((-100, 100), (1258, 1258))",,,(),(),True,radix_multi_core_big,,0,,(),() | ||
| 11 | top_k_v2_sort_topk_f32_unique,,top_k_v2,"((1, 10000001), (1,))","('float32', 'int64')","('ND', 'ND')","((1, 17), (1, 17))","('float32', 'int32')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 3}","((-100, 100), (17, 17))",,,(),(),True,sort_and_topk threshold,,0,,(),() | 8 | top_k_v2_sort_topk_f32_unique,,top_k_v2,"((1, 10000001), (1,))","('float32', 'int64')","('ND', 'ND')","((1, 17), (1, 17))","('float32', 'int32')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 3}","((-100, 100), (17, 17))",,,(),(),True,sort_and_topk threshold,,0,,(),() |
| 12 | top_k_v2_single_core_f16,,top_k_v2,"((64, 20000), (1,))","('float16', 'int32')","('ND', 'ND')","((64, 17), (64, 17))","('float16', 'int32')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': True, 'indices_dtype': 3}","((-100, 100), (17, 17))",,,(),(),True,single_core unsorted,,0,,(),() | 9 | top_k_v2_single_core_f16,,top_k_v2,"((64, 20000), (1,))","('float16', 'int32')","('ND', 'ND')","((64, 17), (64, 17))","('float16', 'int32')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': True, 'indices_dtype': 3}","((-100, 100), (17, 17))",,,(),(),True,single_core unsorted,,0,,(),() |
| 13 | top_k_v2_single_core_u8,,top_k_v2,"((64, 20000), (1,))","('uint8', 'int64')","('ND', 'ND')","((64, 17), (64, 17))","('uint8', 'int64')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': False, 'indices_dtype': 9}","((0, 100), (17, 17))",,,(),(),True,single_core unsigned,,0,,(),() | 10 | top_k_v2_single_core_u8,,top_k_v2,"((64, 20000), (1,))","('uint8', 'int64')","('ND', 'ND')","((64, 17), (64, 17))","('uint8', 'int64')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': False, 'indices_dtype': 9}","((0, 100), (17, 17))",,,(),(),True,single_core unsigned,,0,,(),() |
| 14 | top_k_v2_nonlast_merge_f32_unique,,top_k_v2,"((2, 129, 7), (1,))","('float32', 'int32')","('ND', 'ND')","((2, 31, 7), (2, 31, 7))","('float32', 'int32')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': 1, 'largest': True, 'indices_dtype': 3}","((-100, 100), (31, 31))",,,(),(),True,nonlast_merge,,0,,(),() | 11 | top_k_v2_nonlast_merge_f32_unique,,top_k_v2,"((2, 129, 7), (1,))","('float32', 'int32')","('ND', 'ND')","((2, 31, 7), (2, 31, 7))","('float32', 'int32')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': 1, 'largest': True, 'indices_dtype': 3}","((-100, 100), (31, 31))",,,(),(),True,nonlast_merge,,0,,(),() |
| 15 | -top_k_v2_nonlast_merge_bf16_nan,,top_k_v2,"((4, 512, 3), (1,))","('bfloat16', 'int64')","('ND', 'ND')","((4, 16, 3), (4, 16, 3))","('bfloat16', 'int64')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': 1, 'largest': False, 'indices_dtype': 9}","((-100, 100), (16, 16))",,,(),(),True,nonlast_merge nan unsorted,,0,,(),() | ||
| 16 | top_k_v2_nonlast_radix_i32_duplicate,,top_k_v2,"((2, 2048, 5), (1,))","('int32', 'int32')","('ND', 'ND')","((2, 32, 5), (2, 32, 5))","('int32', 'int32')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': 1, 'largest': True, 'indices_dtype': 3}","((-100, 100), (32, 32))",,,(),(),True,nonlast_radix unsorted,,0,,(),() | 12 | top_k_v2_nonlast_radix_i32_duplicate,,top_k_v2,"((2, 2048, 5), (1,))","('int32', 'int32')","('ND', 'ND')","((2, 32, 5), (2, 32, 5))","('int32', 'int32')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': 1, 'largest': True, 'indices_dtype': 3}","((-100, 100), (32, 32))",,,(),(),True,nonlast_radix unsorted,,0,,(),() |
| 17 | -top_k_v2_nonlast_radix_f16_signed_zero,,top_k_v2,"((2, 2048, 5), (1,))","('float16', 'int64')","('ND', 'ND')","((2, 31, 5), (2, 31, 5))","('float16', 'int64')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': 1, 'largest': True, 'indices_dtype': 9}","((-100, 100), (31, 31))",,,(),(),True,nonlast_radix signed_zero unsorted,,0,,(),() | ||
| 18 | top_k_v2_tail_i8_unsorted,,top_k_v2,"((2, 4097), (1,))","('int8', 'int32')","('ND', 'ND')","((2, 127), (2, 127))","('int8', 'int32')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': True, 'indices_dtype': 3}","((-100, 100), (127, 127))",,,(),(),True,dtype_int8 tail,,0,,(),() | 13 | top_k_v2_tail_i8_unsorted,,top_k_v2,"((2, 4097), (1,))","('int8', 'int32')","('ND', 'ND')","((2, 127), (2, 127))","('int8', 'int32')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': True, 'indices_dtype': 3}","((-100, 100), (127, 127))",,,(),(),True,dtype_int8 tail,,0,,(),() |
| 19 | -top_k_v2_radix_more_u8_unsorted,,top_k_v2,"((1, 221130), (1,))","('uint8', 'int64')","('ND', 'ND')","((1, 131372), (1, 131372))","('uint8', 'int64')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': True, 'indices_dtype': 9}","((0, 100), (131372, 131372))",,,(),(),True,radix_more large_k,,0,,(),() | ||
| 20 | top_k_v2_tail_i16_unique,,top_k_v2,"((4, 4097), (1,))","('int16', 'int32')","('ND', 'ND')","((4, 32), (4, 32))","('int16', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': False, 'indices_dtype': 9}","((-100, 100), (32, 32))",,,(),(),True,dtype_int16 boundary_k32,,0,,(),() | 14 | top_k_v2_tail_i16_unique,,top_k_v2,"((4, 4097), (1,))","('int16', 'int32')","('ND', 'ND')","((4, 32), (4, 32))","('int16', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': False, 'indices_dtype': 9}","((-100, 100), (32, 32))",,,(),(),True,dtype_int16 boundary_k32,,0,,(),() |
| 21 | top_k_v2_tail_u16_unsorted,,top_k_v2,"((3, 16384), (1,))","('uint16', 'int64')","('ND', 'ND')","((3, 63), (3, 63))","('uint16', 'int32')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': False, 'indices_dtype': 3}","((0, 100), (63, 63))",,,(),(),True,dtype_uint16 unsorted,,0,,(),() | 15 | top_k_v2_tail_u16_unsorted,,top_k_v2,"((3, 16384), (1,))","('uint16', 'int64')","('ND', 'ND')","((3, 63), (3, 63))","('uint16', 'int32')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': False, 'indices_dtype': 3}","((0, 100), (63, 63))",,,(),(),True,dtype_uint16 unsorted,,0,,(),() |
| 22 | top_k_v2_tail_u32_unsorted,,top_k_v2,"((2, 65536), (1,))","('uint32', 'int32')","('ND', 'ND')","((2, 257), (2, 257))","('uint32', 'int64')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': True, 'indices_dtype': 9}","((0, 100), (257, 257))",,,(),(),True,dtype_uint32 unsorted,,0,,(),() | 16 | top_k_v2_tail_u32_unsorted,,top_k_v2,"((2, 65536), (1,))","('uint32', 'int32')","('ND', 'ND')","((2, 257), (2, 257))","('uint32', 'int64')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': True, 'indices_dtype': 9}","((0, 100), (257, 257))",,,(),(),True,dtype_uint32 unsorted,,0,,(),() |
| @@ -24,3 +18,37 @@ top_k_v2_rank1_i64_unique,,top_k_v2,"((1025,), (1,))","('int64', 'int64')","('ND | |||
| 24 | top_k_v2_nonlast_u64_unique,,top_k_v2,"((2, 129, 5), (1,))","('uint64', 'int32')","('ND', 'ND')","((2, 31, 5), (2, 31, 5))","('uint64', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': 1, 'largest': False, 'indices_dtype': 9}","((0, 100), (31, 31))",,,(),(),True,dtype_uint64 nonlast,,0,,(),() | 18 | top_k_v2_nonlast_u64_unique,,top_k_v2,"((2, 129, 5), (1,))","('uint64', 'int32')","('ND', 'ND')","((2, 31, 5), (2, 31, 5))","('uint64', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': 1, 'largest': False, 'indices_dtype': 9}","((0, 100), (31, 31))",,,(),(),True,dtype_uint64 nonlast,,0,,(),() |
| 25 | top_k_v2_k_zero_f32,,top_k_v2,"((2, 65), (1,))","('float32', 'int64')","('ND', 'ND')","((2, 0), (2, 0))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': True, 'indices_dtype': 9}","((-100, 100), (0, 0))",,,(),(),True,k_zero,,0,,(),() | 19 | top_k_v2_k_zero_f32,,top_k_v2,"((2, 65), (1,))","('float32', 'int64')","('ND', 'ND')","((2, 0), (2, 0))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': True, 'indices_dtype': 9}","((-100, 100), (0, 0))",,,(),(),True,k_zero,,0,,(),() |
| 26 | top_k_v2_k_full_i32_unique,,top_k_v2,"((2, 33), (1,))","('int32', 'int32')","('ND', 'ND')","((2, 33), (2, 33))","('int32', 'int32')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': False, 'indices_dtype': 3}","((-100, 100), (33, 33))",,,(),(),True,k_full,,0,,(),() | 20 | top_k_v2_k_full_i32_unique,,top_k_v2,"((2, 33), (1,))","('int32', 'int32')","('ND', 'ND')","((2, 33), (2, 33))","('int32', 'int32')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': False, 'indices_dtype': 3}","((-100, 100), (33, 33))",,,(),(),True,k_full,,0,,(),() |
| 21 | +top_k_v2_small_merge_boundary_f32_unique,,top_k_v2,"((640, 1000), (1,))","('float32', 'int32')","('ND', 'ND')","((640, 32), (640, 32))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((-100, 100), (32, 32))",,,(),(),True,small_merge rank2 near_limit key13003 npu_bitonic,,0,,(),() | ||
| 22 | +top_k_v2_small_merge_boundary_f32_duplicate,,top_k_v2,"((640, 1000), (1,))","('float32', 'int32')","('ND', 'ND')","((640, 32), (640, 32))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((-100, 100), (32, 32))",,,(),(),True,small_merge rank2 near_limit duplicate full-network npu_bitonic,,0,,(),() | ||
| 23 | +top_k_v2_small_axis_two_stage_f32_last_sorted_unique,,top_k_v2,"((3584, 16), (1,))","('float32', 'int32')","('ND', 'ND')","((3584, 8), (3584, 8))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((-100, 100), (8, 8))",,,(),(),True,small-axis two-stage mode10 last fp32 segs=64 rank-inverse bitonicFinalize=1,,0,,(),() | ||
| 24 | +top_k_v2_small_axis_two_stage_f32_last_unsorted_unique,,top_k_v2,"((3584, 16), (1,))","('float32', 'int32')","('ND', 'ND')","((3584, 8), (3584, 8))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': True, 'indices_dtype': 9}","((-100, 100), (8, 8))",,,(),(),True,small-axis two-stage mode10 last fp32 unsorted no finalize (keyParams5=0),,0,,(),() | ||
| 25 | +top_k_v2_small_axis_two_stage_bf16_last_bitonic_nan,,top_k_v2,"((3584, 54), (1,))","('bfloat16', 'int32')","('ND', 'ND')","((3584, 2), (3584, 2))","('bfloat16', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((-100, 100), (2, 2))",,,(),(),True,small-axis two-stage mode10 last bf16 N=54 twoStageMaxN boundary k=2 NaN head finalize,,0,,(),() | ||
| 26 | +top_k_v2_small_axis_two_stage_i32_last_u16alias_bitonic_unique,,top_k_v2,"((448, 128), (1,))","('int32', 'int32')","('ND', 'ND')","((448, 32), (448, 32))","('int32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((-100, 100), (32, 32))",,,(),(),True,small-axis two-stage mode10 last int32 u16-alias k=32 boundary finalize=1,,0,,(),() | ||
| 27 | +top_k_v2_small_axis_insertion_f16_last_bitonic_duplicate,,top_k_v2,"((2688, 8), (1,))","('float16', 'int64')","('ND', 'ND')","((2688, 8), (2688, 8))","('float16', 'int32')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 3, 'sort_policy':1}","((-100, 100), (8, 8))",,,(),(),True,small-axis insertion mode9 last fp16 finalize Reg batch path tie-by-index,,0,,(),() | ||
| 28 | +top_k_v2_small_axis_insertion_f32_last_bitonic_unique,,top_k_v2,"((896, 4), (1,))","('float32', 'int32')","('ND', 'ND')","((896, 2), (896, 2))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((-100, 100), (2, 2))",,,(),(),True,small-axis insertion mode9 last fp32 k=2 boundary finalize=1,,0,,(),() | ||
| 29 | +top_k_v2_small_axis_insertion_bf16_last_bitonic_signed_zero,,top_k_v2,"((2688, 8), (1,))","('bfloat16', 'int32')","('ND', 'ND')","((2688, 4), (2688, 4))","('bfloat16', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': False, 'indices_dtype': 9, 'sort_policy':1}","((-100, 100), (4, 4))",,,(),(),True,small-axis insertion mode9 last bf16 CONVERT_TYPE float cast -0/+0 equivalence finalize smallest,,0,,(),() | ||
| 30 | +top_k_v2_small_axis_insertion_f16_last_tailbatch_unsorted_unique,,top_k_v2,"((2690, 8), (1,))","('float16', 'int32')","('ND', 'ND')","((2690, 4), (2690, 4))","('float16', 'int32')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': True, 'indices_dtype': 3}","((-100, 100), (4, 4))",,,(),(),True,small-axis insertion mode9 last fp16 batchNum=55 tail batch 44/49 partial,,0,,(),() | ||
| 31 | +top_k_v2_small_axis_two_stage_f32_nonlast_bitonic_unique,,top_k_v2,"((64, 16, 64), (1,))","('float32', 'int32')","('ND', 'ND')","((64, 8, 64), (64, 8, 64))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': 1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((-100, 100), (8, 8))",,,(),(),True,small-axis two-stage mode10 nonlast fp32 dim=1 unsortedDim=4096 finalize=1,,0,,(),() | ||
| 32 | +top_k_v2_aclnn_nd_qwen3_000016,,top_k_v2,"((8192, 128), (1,))","('bfloat16', 'int32')","('ND', 'ND')","((8192, 30), (8192, 30))","('bfloat16', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': False, 'indices_dtype': 9, 'sort_policy':1}","((-100000, 100000), (30, 30))",,,(),(),True,aclnn rig 复刻 policy=1,,0,,(),() | ||
| 33 | +top_k_v2_aclnn_tx_tp4_7865_000009,,top_k_v2,"((3186, 8), (1,))","('float32', 'int32')","('ND', 'ND')","((3186, 6), (3186, 6))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((-100000, 100000), (6, 6))",,,(),(),True,aclnn rig 复刻 policy=1,,0,,(),() | ||
| 34 | +top_k_v2_aclnn_tx_ds_7325_000026,,top_k_v2,"((3115, 8), (1,))","('float32', 'int32')","('ND', 'ND')","((3115, 4), (3115, 4))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((2, 10), (4, 4))",,,(),(),True,aclnn rig 复刻 policy=1,,0,,(),() | ||
| 35 | +top_k_v2_rig2_f32_cus_000106,,top_k_v2,"((3038, 26), (1,))","('float32', 'int32')","('ND', 'ND')","((3038, 11), (3038, 11))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((1.1754943508e-38, 1.1754943508e-38), (11, 11))",,,(),(),True,rig gen/cus 复刻 policy=1,,0,,(),() | ||
| 36 | +top_k_v2_rig2_f32_cus_000207,,top_k_v2,"((4756, 43), (1,))","('float32', 'int32')","('ND', 'ND')","((4756, 30), (4756, 30))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((0, 0), (30, 30))",,,(),(),True,rig gen/cus 复刻 policy=1,,0,,(),() | ||
| 37 | +top_k_v2_alleq_f32_bigseg,,top_k_v2,"((200000, 700), (1,))","('float32', 'int32')","('ND', 'ND')","((200000, 32), (200000, 32))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((0.5, 0.5), (32, 32))",,,(),(),True,alleq Reg 全等快路径基线,,0,,(),() | ||
| 38 | +top_k_v2_alleq_bf16_bigseg,,top_k_v2,"((50, 100, 200, 80), (1,))","('bfloat16', 'int32')","('ND', 'ND')","((50, 100, 200, 16), (50, 100, 200, 16))","('bfloat16', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((-2.5, -2.5), (16, 16))",,,(),(),True,alleq Reg 全等快路径基线,,0,,(),() | ||
| 39 | +top_k_v2_alleq_i32_bigseg,,top_k_v2,"((400, 250, 500), (1,))","('int32', 'int32')","('ND', 'ND')","((400, 250, 9), (400, 250, 9))","('int32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((-2147483648, -2147483648), (9, 9))",,,(),(),True,alleq Reg 全等快路径基线,,0,,(),() | ||
| 40 | +top_k_v2_alleq_f32_midseg,,top_k_v2,"((5000, 333), (1,))","('float32', 'int32')","('ND', 'ND')","((5000, 9), (5000, 9))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((-100000, -100000), (9, 9))",,,(),(),True,alleq Reg 全等快路径基线,,0,,(),() | ||
| 41 | +top_k_v2_alleq_f16_midseg,,top_k_v2,"((63, 80, 96), (1,))","('float16', 'int32')","('ND', 'ND')","((63, 80, 31), (63, 80, 31))","('float16', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((7.5, 7.5), (31, 31))",,,(),(),True,alleq Reg 全等快路径基线,,0,,(),() | ||
| 42 | +top_k_v2_alleq_i64_midseg,,top_k_v2,"((3, 1300, 640), (1,))","('int64', 'int32')","('ND', 'ND')","((3, 1300, 32), (3, 1300, 32))","('int64', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((100000, 100000), (32, 32))",,,(),(),True,alleq Reg 全等快路径基线,,0,,(),() | ||
| 43 | +top_k_v2_alleq_bf16_smallseg,,top_k_v2,"((4096, 96), (1,))","('bfloat16', 'int32')","('ND', 'ND')","((4096, 2), (4096, 2))","('bfloat16', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((0, 0), (2, 2))",,,(),(),True,alleq Reg 全等快路径基线,,0,,(),() | ||
| 44 | +top_k_v2_aclnn_tx_tp4_7472_000007_alleq,,top_k_v2,"((165, 8), (1,))","('float32', 'int32')","('ND', 'ND')","((165, 6), (165, 6))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((inf, inf), (6, 6))",,,(),(),True,aclnn rig 全等形态复刻 policy=1,,0,,(),() | ||
| 45 | +top_k_v2_aclnn_tx_tp4_7865_000009_alleq,,top_k_v2,"((3186, 8), (1,))","('float32', 'int32')","('ND', 'ND')","((3186, 6), (3186, 6))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((inf, inf), (6, 6))",,,(),(),True,aclnn rig 全等形态复刻 policy=1,,0,,(),() | ||
| 46 | +top_k_v2_aclnn_tx_tp4_4034_000011_alleq,,top_k_v2,"((2647, 8), (1,))","('float32', 'int32')","('ND', 'ND')","((2647, 8), (2647, 8))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy':1}","((inf, inf), (8, 8))",,,(),(),True,aclnn rig 全等形态复刻 policy=1,,0,,(),() | ||
| 47 | +top_k_v2_small_axis_insertion_f32_last_largest_bitonic_nan_finite_mixed,,top_k_v2,"((896, 4), (1,))","('float32', 'int32')","('ND', 'ND')","((896, 2), (896, 2))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': True, 'indices_dtype': 9, 'sort_policy': 1}","((-100, 100), (2, 2))",,,(),(),True,"insertion mode9 last f32 k=2<N mixed NaN/finite [1,NaN,3,2] largest policy=1 bitonic finalize R9",,0,,(),() | ||
| 48 | +top_k_v2_small_axis_insertion_f32_last_smallest_unsorted_nan_finite_mixed,,top_k_v2,"((896, 4), (1,))","('float32', 'int32')","('ND', 'ND')","((896, 2), (896, 2))","('float32', 'int64')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': False, 'indices_dtype': 9, 'sort_policy': 0}","((-100, 100), (2, 2))",,,(),(),True,"insertion mode9 last f32 k=2<N mixed NaN/finite [1,NaN,3,2] smallest policy=0 no finalize R9",,0,,(),() | ||
| 49 | +top_k_v2_small_axis_insertion_f16_last_largest_unsorted_nan_finite_mixed,,top_k_v2,"((2688, 8), (1,))","('float16', 'int32')","('ND', 'ND')","((2688, 4), (2688, 4))","('float16', 'int32')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': True, 'indices_dtype': 3, 'sort_policy': 0}","((-100, 100), (4, 4))",,,(),(),True,"insertion mode9 last f16 k=4<N mixed NaN/finite [1,NaN,3,2,NaN,5,-4,0] largest policy=0 no finalize R9",,0,,(),() | ||
| 50 | +top_k_v2_small_axis_insertion_f16_last_smallest_bitonic_nan_finite_mixed,,top_k_v2,"((2688, 8), (1,))","('float16', 'int32')","('ND', 'ND')","((2688, 4), (2688, 4))","('float16', 'int32')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': False, 'indices_dtype': 3, 'sort_policy': 1}","((-100, 100), (4, 4))",,,(),(),True,"insertion mode9 last f16 k=4<N mixed NaN/finite [1,NaN,3,2,NaN,5,-4,0] smallest policy=1 bitonic finalize R9",,0,,(),() | ||
| 51 | +top_k_v2_small_axis_insertion_bf16_last_largest_unsorted_nan_finite_mixed,,top_k_v2,"((2688, 8), (1,))","('bfloat16', 'int32')","('ND', 'ND')","((2688, 4), (2688, 4))","('bfloat16', 'int32')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': -1, 'largest': True, 'indices_dtype': 3, 'sort_policy': 0}","((-100, 100), (4, 4))",,,(),(),True,"insertion mode9 last bf16 k=4<N mixed NaN/finite [1,NaN,3,2,NaN,5,-4,0] largest policy=0 no finalize R9",,0,,(),() | ||
| 52 | +top_k_v2_small_axis_insertion_bf16_last_smallest_bitonic_nan_finite_mixed,,top_k_v2,"((2688, 8), (1,))","('bfloat16', 'int32')","('ND', 'ND')","((2688, 4), (2688, 4))","('bfloat16', 'int32')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': -1, 'largest': False, 'indices_dtype': 3, 'sort_policy': 1}","((-100, 100), (4, 4))",,,(),(),True,"insertion mode9 last bf16 k=4<N mixed NaN/finite [1,NaN,3,2,NaN,5,-4,0] smallest policy=1 bitonic finalize R9",,0,,(),() | ||
| 53 | +top_k_v2_small_axis_insertion_f32_nonlast_largest_unsorted_nan_finite_mixed,,top_k_v2,"((42, 4, 64), (1,))","('float32', 'int32')","('ND', 'ND')","((42, 2, 64), (42, 2, 64))","('float32', 'int32')","('ND', 'ND')",,,,,"{'sorted': False, 'dim': 1, 'largest': True, 'indices_dtype': 3, 'sort_policy': 0}","((-100, 100), (2, 2))",,,(),(),True,"insertion mode9 nonlast f32 k=2<N mixed NaN/finite [1,NaN,3,2] largest policy=0 no finalize R9",,0,,(),() | ||
| 54 | +top_k_v2_small_axis_insertion_bf16_nonlast_largest_bitonic_nan_finite_mixed,,top_k_v2,"((42, 8, 64), (1,))","('bfloat16', 'int32')","('ND', 'ND')","((42, 4, 64), (42, 4, 64))","('bfloat16', 'int64')","('ND', 'ND')",,,,,"{'sorted': True, 'dim': 1, 'largest': True, 'indices_dtype': 9, 'sort_policy': 1}","((-100, 100), (4, 4))",,,(),(),True,"insertion mode9 nonlast bf16 k=4<N mixed NaN/finite [1,NaN,3,2,NaN,5,-4,0] largest policy=1 bitonic finalize R9",,0,,(),() | ||
| @@ -25,7 +25,7 @@ | |||
| 25 | 25 | ||
| 26 | ## 功能说明 | 26 | ## 功能说明 |
| 27 | 27 | ||
| 28 | -- 算子功能:返回输入Tensor在指定维度上的k个极值及索引。 | 28 | +- 接口功能:返回输入Tensor在指定维度上的k个极值及索引。 |
| 29 | 29 | ||
| 30 | ## 函数原型 | 30 | ## 函数原型 |
| 31 | 31 | ||
| @@ -25,7 +25,11 @@ | |||
| 25 | 25 | ||
| 26 | ## 功能说明 | 26 | ## 功能说明 |
| 27 | 27 | ||
| 28 | -- 算子功能:返回输入Tensor在指定维度上的k个极值及索引。 | 28 | +- 接口功能:返回输入Tensor在指定维度上的k个极值及索引。 |
| 29 | +- 与aclnnTopk的差异:aclnnTopkV2与aclnnTopk功能相同,核心差异是新增sortPolicy输入参数(位于sorted之后、valuesOut之前),用于指定TopK候选结果的排序策略。 | ||
| 30 | + - sortPolicy=0:使用原有排序行为,与aclnnTopk一致; | ||
| 31 | + - sortPolicy=1:在sorted=True且小k值(2≤k≤32)场景下启用Bitonic双调算法对结果进行处理;k≥33时结果与aclnnTopk一致。 | ||
| 32 | +- 其余参数、支持的数据类型与约束均与aclnnTopk一致。 | ||
| 29 | 33 | ||
| 30 | ## 函数原型 | 34 | ## 函数原型 |
| 31 | 35 | ||
| @@ -133,7 +137,7 @@ aclnnStatus aclnnTopkV2( | |||
| 133 | <td>sortPolicy(int64_t)</td> | 137 | <td>sortPolicy(int64_t)</td> |
| 134 | <td>输入</td> | 138 | <td>输入</td> |
| 135 | <td>表示TopK候选结果的排序策略。</td> | 139 | <td>表示TopK候选结果的排序策略。</td> |
| 136 | - <td>0表示使用原有排序行为,1表示在sorted=True且小k值(2≤k≤32)场景下启用Bitonic Small TopK路径,对相等值的索引按原始顺序排列,对齐GPU行为。</td> | 140 | + <td>0表示使用原有排序行为,sorted=True时结果为稳定排序;1表示在sorted=True且小k值(2≤k≤32)场景下启用Bitonic Small TopK路径,对相等值的索引按原始顺序排列,对齐GPU行为;k≥33时结果与aclnnTopk一致。</td> |
| 137 | <td>-</td> | 141 | <td>-</td> |
| 138 | <td>-</td> | 142 | <td>-</td> |
| 139 | <td>-</td> | 143 | <td>-</td> |