Merged
[QFA][HIFP8]: 支持 HIF8 per-tensor 量化模式 #9573
杨志鹏Add on Aug 4
[QFA][HIFP8]: 支持 HIF8 per-tensor 量化模式 #9573
Merged
Total: 53 files changed+12234-3932
| @@ -0,0 +1,338 @@ | |||
| 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 quant_flash_attn_tiling_hif8.cpp | ||
| 13 | + * \brief QuantFlashAttn arch35 tiling implementation (A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32) | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "quant_flash_attn_tiling_hif8.h" | ||
| 17 | +#include "../quant_flash_attn_tiling.h" | ||
| 18 | +#include <vector> | ||
| 19 | +#include <graph/utils/type_utils.h> | ||
| 20 | +#include "log/log.h" | ||
| 21 | +#include "../quant_flash_attn_tiling_utils.h" | ||
| 22 | +#include "../../op_kernel/arch35/quant_flash_attn_template_tiling_key.h" | ||
| 23 | +#include "../../../common/op_host/fia_tiling_templates_registry.h" | ||
| 24 | +#include "../quant_flash_attn_tiling_constants.h" | ||
| 25 | + | ||
| 26 | +using namespace ge; | ||
| 27 | +using namespace AscendC; | ||
| 28 | +namespace optiling { | ||
| 29 | +namespace quant_flash_attn { | ||
| 30 | +using namespace arch35QFA; | ||
| 31 | + | ||
| 32 | +void QuantFlashAttnTilingHif8Impl::InitTilingInfo(TilingInfo *tilingInfo) | ||
| 33 | +{ | ||
| 34 | + qfaInfo_ = static_cast<QfaTilingInfo *>(tilingInfo); | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +bool QuantFlashAttnTilingHif8Impl::IsCapable() | ||
| 38 | +{ | ||
| 39 | + if (qfaInfo_ == nullptr) { | ||
| 40 | + return false; | ||
| 41 | + } | ||
| 42 | + if (qfaInfo_->quantMode != QfaQuantMode::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32) { | ||
| 43 | + return false; | ||
| 44 | + } | ||
| 45 | + return true; | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +void QuantFlashAttnTilingHif8Impl::CalcScheduleMode() | ||
| 49 | +{ | ||
| 50 | + scheduleMode_ = ScheduleMode::BATCH_MODE; | ||
| 51 | + OP_LOGI(qfaInfo_->opName, "QuantFlashAttn(HIF8) schedule mode: %u.", static_cast<uint32_t>(scheduleMode_)); | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +ge::graphStatus QuantFlashAttnTilingHif8Impl::DoOpTiling() | ||
| 55 | +{ | ||
| 56 | + OP_CHECK_IF(SetPlatMemoryInfo() != ge::GRAPH_SUCCESS, OP_LOGE(qfaInfo_->opName, "Set plat memory info fail."), | ||
| 57 | + return ge::GRAPH_FAILED); | ||
| 58 | + | ||
| 59 | + InitImplParam(); | ||
| 60 | + SplitPolicy(); | ||
| 61 | + FillTiling(); | ||
| 62 | + CalcScheduleMode(); | ||
| 63 | + CalcWorkspaceSize(); | ||
| 64 | + GenTilingKey(); | ||
| 65 | + if ((SetNumBlocks(numBlocks_) != ge::GRAPH_SUCCESS) || (SetTilingKey(tilingKey_) != ge::GRAPH_SUCCESS) || | ||
| 66 | + (SetWorkspaceSize(workspaceSize_) != ge::GRAPH_SUCCESS) || (SetTilingData(tilingData_) != ge::GRAPH_SUCCESS) || | ||
| 67 | + (SetScheduleMode(scheduleMode_) != ge::GRAPH_SUCCESS)) { | ||
| 68 | + return ge::GRAPH_FAILED; | ||
| 69 | + } | ||
| 70 | + return ge::GRAPH_SUCCESS; | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +ge::graphStatus QuantFlashAttnTilingHif8Impl::SetPlatMemoryInfo() | ||
| 74 | +{ | ||
| 75 | + auto platformInfoPtr = context_->GetPlatformInfo(); | ||
| 76 | + OP_CHECK_IF(platformInfoPtr == nullptr, OP_LOGE(qfaInfo_->opName, "The platformInfoPtr is null!"), | ||
| 77 | + return ge::GRAPH_FAILED); | ||
| 78 | + auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfoPtr); | ||
| 79 | + platformInfo_.aivNum = ascendcPlatform.GetCoreNumAiv(); | ||
| 80 | + platformInfo_.aicNum = ascendcPlatform.GetCoreNumAic(); | ||
| 81 | + platformInfo_.cvRatio = platformInfo_.aivNum / platformInfo_.aicNum; | ||
| 82 | + platformInfo_.coreNum = platformInfo_.aivNum; | ||
| 83 | + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, platformInfo_.ubSize); | ||
| 84 | + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L1, platformInfo_.l1Size); | ||
| 85 | + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_C, platformInfo_.l0cSize); | ||
| 86 | + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_A, platformInfo_.l0aSize); | ||
| 87 | + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_B, platformInfo_.l0bSize); | ||
| 88 | + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L2, platformInfo_.l2Size); | ||
| 89 | + | ||
| 90 | + platformInfo_.defaultSysWorkspaceSize = ascendcPlatform.GetLibApiWorkSpaceSize(); | ||
| 91 | + OP_LOGI(qfaInfo_->opName, "HIF8 AIV:%u AIC:%u L0A:%lu L0B:%lu L0C:%lu UB:%lu L1:%lu L2:%lu", platformInfo_.aivNum, | ||
| 92 | + platformInfo_.aicNum, platformInfo_.l0aSize, platformInfo_.l0bSize, platformInfo_.l0cSize, | ||
| 93 | + platformInfo_.ubSize, platformInfo_.l1Size, platformInfo_.l2Size); | ||
| 94 | + | ||
| 95 | + return ge::GRAPH_SUCCESS; | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +void QuantFlashAttnTilingHif8Impl::InitImplParam() | ||
| 99 | +{ | ||
| 100 | + const gert::Tensor *actSeqLenQ = qfaInfo_->opParamInfo.cuSeqlensQ.tensor; | ||
| 101 | + const gert::Tensor *actSeqLenKV = qfaInfo_->opParamInfo.cuSeqlensKv.tensor; | ||
| 102 | + uint32_t actSeqLenQDims = (actSeqLenQ != nullptr) ? actSeqLenQ->GetShapeSize() : 0; | ||
| 103 | + uint32_t actSeqLenKVDims = (actSeqLenKV != nullptr) ? actSeqLenKV->GetShapeSize() : 0; | ||
| 104 | + cuSeqLenQFlag_ = !((actSeqLenQDims == 0) || (actSeqLenQ == nullptr) || (actSeqLenQ->GetData<int32_t>() == nullptr)); | ||
| 105 | + cuSeqLenKVFlag_ = | ||
| 106 | + !((actSeqLenKVDims == 0) || (actSeqLenKV == nullptr) || (actSeqLenKV->GetData<int32_t>() == nullptr)); | ||
| 107 | + | ||
| 108 | + const gert::Tensor *seqUsedQ = qfaInfo_->opParamInfo.sequsedQ.tensor; | ||
| 109 | + const gert::Tensor *seqUsedKv = qfaInfo_->opParamInfo.sequsedKv.tensor; | ||
| 110 | + uint32_t seqUsedQDims = (seqUsedQ != nullptr) ? seqUsedQ->GetShapeSize() : 0; | ||
| 111 | + uint32_t seqUsedKvDims = (seqUsedKv != nullptr) ? seqUsedKv->GetShapeSize() : 0; | ||
| 112 | + seqUsedQFlag_ = !((seqUsedQDims == 0) || (seqUsedQ == nullptr) || (seqUsedQ->GetData<int32_t>() == nullptr)); | ||
| 113 | + seqUsedKvFlag_ = !((seqUsedKvDims == 0) || (seqUsedKv == nullptr) || (seqUsedKv->GetData<int32_t>() == nullptr)); | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +void QuantFlashAttnTilingHif8Impl::SplitPolicy() | ||
| 117 | +{ | ||
| 118 | + sOuterFactor_ = SOUTER_64; | ||
| 119 | + sInnerFactor_ = SINNER_256; | ||
| 120 | + CalcNumBlocks(platformInfo_.aicNum); | ||
| 121 | + flashDecodeFlag_ = false; | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +void QuantFlashAttnTilingHif8Impl::UpdateTilingKeyConfig() | ||
| 125 | +{ | ||
| 126 | + tilingKeyInfo_.config = Config_S1Aligned128_S2Aligned256_DAligned128_DVAligned128; | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +void QuantFlashAttnTilingHif8Impl::UpdateTilingKeyLayout() | ||
| 130 | +{ | ||
| 131 | + if (qfaInfo_->qLayout == QfaLayout::BNSD) { | ||
| 132 | + tilingKeyInfo_.inputLayout = InOutLayoutType_BNSD_BNSD; | ||
| 133 | + } else if (qfaInfo_->qLayout == QfaLayout::TND) { | ||
| 134 | + tilingKeyInfo_.inputLayout = InOutLayoutType_TND_TND; | ||
| 135 | + } else { | ||
| 136 | + tilingKeyInfo_.inputLayout = InOutLayoutType_BSND_BSND; | ||
| 137 | + } | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +void QuantFlashAttnTilingHif8Impl::UpdateTilingKeyKvLayout() | ||
| 141 | +{ | ||
| 142 | + tilingKeyInfo_.kvLayoutType = KvLayoutType_NO_PA; | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +void QuantFlashAttnTilingHif8Impl::UpdateTilingKeyInfo() | ||
| 146 | +{ | ||
| 147 | + UpdateTilingKeyLayout(); | ||
| 148 | + UpdateTilingKeyConfig(); | ||
| 149 | + UpdateTilingKeyQuantMode(); | ||
| 150 | + tilingKeyInfo_.hasAttenMask = (qfaInfo_->maskMode != static_cast<int64_t>(MaskMode::NO_MASK)); | ||
| 151 | + UpdateTilingKeyKvLayout(); | ||
| 152 | + tilingKeyInfo_.isFd = flashDecodeFlag_; | ||
| 153 | +} | ||
| 154 | + | ||
| 155 | +void QuantFlashAttnTilingHif8Impl::UpdateTilingKeyQuantMode() | ||
| 156 | +{ | ||
| 157 | + tilingKeyInfo_.quantMode = static_cast<uint64_t>(QFA_HIF8_FP32); | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +void QuantFlashAttnTilingHif8Impl::GenTilingKey() | ||
| 161 | +{ | ||
| 162 | + UpdateTilingKeyInfo(); | ||
| 163 | + tilingKey_ = GET_TPL_TILING_KEY(tilingKeyInfo_.inputLayout, tilingKeyInfo_.config, tilingKeyInfo_.quantMode, | ||
| 164 | + tilingKeyInfo_.hasAttenMask, tilingKeyInfo_.kvLayoutType, tilingKeyInfo_.isFd); | ||
| 165 | + | ||
| 166 | + OP_LOGI(qfaInfo_->opName, "HIF8 The tilingkey is %llu.", tilingKey_); | ||
| 167 | + OP_LOGI(qfaInfo_->opName, | ||
| 168 | + "HIF8 The tilingkey param is inOutLayoutType: %llu, config: %llu, quantMode: %llu, " | ||
| 169 | + "hasAttenMask: %u, kvLayoutType: %llu, isFd: %u.", | ||
| 170 | + tilingKeyInfo_.inputLayout, tilingKeyInfo_.config, tilingKeyInfo_.quantMode, tilingKeyInfo_.hasAttenMask, | ||
| 171 | + tilingKeyInfo_.kvLayoutType, tilingKeyInfo_.isFd); | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +void QuantFlashAttnTilingHif8Impl::CalcNumBlocks(uint32_t aicNum) | ||
| 175 | +{ | ||
| 176 | + auto ascendcPlatform = platform_ascendc::PlatformAscendC(qfaInfo_->platformInfo); | ||
| 177 | + auto aivNum = aicNum * platformInfo_.cvRatio; | ||
| 178 | + | ||
| 179 | + numBlocks_ = ascendcPlatform.CalcTschBlockDim(aivNum, aicNum, aivNum); | ||
| 180 | + OP_LOGI(qfaInfo_->opName, "HIF8 QuantFlashAttn block dim: %u aiv Num: %u aic Num: %u.", numBlocks_, aivNum, aicNum); | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +void QuantFlashAttnTilingHif8Impl::CalcWorkspaceSize() | ||
| 184 | +{ | ||
| 185 | + size_t sysWorkspaceSize = platformInfo_.defaultSysWorkspaceSize; | ||
| 186 | + uint32_t mSize = sOuterFactor_ * platformInfo_.cvRatio; | ||
| 187 | + uint32_t dSize = qfaInfo_->vHeadDim; | ||
| 188 | + (void)mSize; | ||
不使用的代码,应该直接删除 ![]() ![]() | |||
| 189 | + (void)dSize; | ||
| 190 | + workspaceSize_ = sysWorkspaceSize; | ||
| 191 | + | ||
| 192 | + OP_LOGI(qfaInfo_->opName, "HIF8 Workspaces: %lu", workspaceSize_); | ||
| 193 | +} | ||
| 194 | + | ||
| 195 | +void QuantFlashAttnTilingHif8Impl::FillTiling() | ||
| 196 | +{ | ||
| 197 | + ComputeTilingData(); | ||
| 198 | + SetQFATilingData(); | ||
| 199 | + PrintAllTilingData(); | ||
| 200 | +} | ||
| 201 | + | ||
| 202 | +void QuantFlashAttnTilingHif8Impl::ComputeTilingData() | ||
| 203 | +{ | ||
| 204 | + tilingData_.baseTiling.quantFlashAttnAttenMaskParams.sparseMode = qfaInfo_->maskMode; | ||
| 205 | + | ||
| 206 | + if (qfaInfo_->maskMode != static_cast<int64_t>(MaskMode::NO_MASK)) { | ||
| 207 | + uint64_t maskDimNum = qfaInfo_->opParamInfo.attnMask.tensor->GetStorageShape().GetDimNum(); | ||
| 208 | + uint64_t maskS1Size = qfaInfo_->opParamInfo.attnMask.tensor->GetStorageShape().GetDim(maskDimNum - 2); | ||
| 209 | + uint64_t maskS2Size = qfaInfo_->opParamInfo.attnMask.tensor->GetStorageShape().GetDim(maskDimNum - 1); | ||
| 210 | + tilingData_.baseTiling.quantFlashAttnAttenMaskParams.attenMaskS1Size = maskS1Size; | ||
| 211 | + tilingData_.baseTiling.quantFlashAttnAttenMaskParams.attenMaskS2Size = maskS2Size; | ||
| 212 | + } | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +void QuantFlashAttnTilingHif8Impl::SetQFATilingData() | ||
| 216 | +{ | ||
| 217 | + tilingData_.baseTiling.quantFlashAttnBaseParams.bSize = qfaInfo_->bSize; | ||
| 218 | + tilingData_.baseTiling.quantFlashAttnBaseParams.t1Size = qfaInfo_->qTSize; | ||
| 219 | + tilingData_.baseTiling.quantFlashAttnBaseParams.t2Size = qfaInfo_->kTSize; | ||
| 220 | + tilingData_.baseTiling.quantFlashAttnBaseParams.n2Size = qfaInfo_->n2Size; | ||
| 221 | + tilingData_.baseTiling.quantFlashAttnBaseParams.gSize = qfaInfo_->gSize; | ||
| 222 | + tilingData_.baseTiling.quantFlashAttnBaseParams.s1Size = qfaInfo_->s1Size; | ||
| 223 | + tilingData_.baseTiling.quantFlashAttnBaseParams.s2Size = qfaInfo_->s2Size; | ||
| 224 | + tilingData_.baseTiling.quantFlashAttnBaseParams.dSize = qfaInfo_->qkHeadDim; | ||
| 225 | + tilingData_.baseTiling.quantFlashAttnBaseParams.dSizeV = qfaInfo_->vHeadDim; | ||
| 226 | + tilingData_.baseTiling.quantFlashAttnBaseParams.scaleValue = qfaInfo_->softmaxScale; | ||
| 227 | + tilingData_.baseTiling.quantFlashAttnBaseParams.cuSeqLensQSize = | ||
| 228 | + (qfaInfo_->qLayout == QfaLayout::TND && cuSeqLenQFlag_) ? qfaInfo_->bSize : 0; | ||
| 229 | + tilingData_.baseTiling.quantFlashAttnBaseParams.cuSeqLensKVSize = | ||
| 230 | + (qfaInfo_->kvLayout == QfaLayout::TND && cuSeqLenKVFlag_) ? qfaInfo_->bSize : 0; | ||
此处代码错误,应该直接复制cu_seqlens的长度,TND时为B+1,非TND时为0,否则kernel侧一定有其他不合理的处理 ![]() ![]() | |||
| 231 | + tilingData_.baseTiling.quantFlashAttnBaseParams.seqUsedQSize = seqUsedQFlag_ ? qfaInfo_->bSize : 0; | ||
| 232 | + tilingData_.baseTiling.quantFlashAttnBaseParams.seqUsedKvSize = seqUsedKvFlag_ ? qfaInfo_->bSize : 0; | ||
直接将seq_used的长度赋值上去即可,不需要做判断 ![]() ![]() | |||
| 233 | + tilingData_.baseTiling.quantFlashAttnBaseParams.isKvContinuous = true; | ||
| 234 | + tilingData_.baseTiling.quantFlashAttnBaseParams.isSoftMaxLseEnable = qfaInfo_->softmaxLseFlag; | ||
| 235 | + tilingData_.baseTiling.quantFlashAttnBaseParams.iscuSeqLengthsNull = | ||
| 236 | + !(cuSeqLenQFlag_ && qfaInfo_->qLayout == QfaLayout::TND); | ||
| 237 | + tilingData_.baseTiling.quantFlashAttnBaseParams.iscuSeqLengthsKVNull = | ||
| 238 | + !(cuSeqLenKVFlag_ && qfaInfo_->kvLayout == QfaLayout::TND); | ||
| 239 | + tilingData_.baseTiling.quantFlashAttnBaseParams.coreNum = numBlocks_; | ||
| 240 | + tilingData_.baseTiling.quantFlashAttnBaseParams.outputLayout = static_cast<uint32_t>(qfaInfo_->outLayout); | ||
| 241 | + tilingData_.baseTiling.quantFlashAttnBaseParams.needInitOutput = CheckNeedInitOutput(); | ||
| 242 | + | ||
| 243 | + tilingData_.baseTiling.quantFlashAttnAttenMaskParams.winLefts = qfaInfo_->winLeft; | ||
| 244 | + tilingData_.baseTiling.quantFlashAttnAttenMaskParams.winRights = qfaInfo_->winRight; | ||
| 245 | + if (qfaInfo_->winLeft == -1) { | ||
| 246 | + tilingData_.baseTiling.quantFlashAttnAttenMaskParams.winLefts = MASK_MODE_INT_MAX; | ||
| 247 | + } | ||
| 248 | + if (qfaInfo_->winRight == -1) { | ||
| 249 | + tilingData_.baseTiling.quantFlashAttnAttenMaskParams.winRights = MASK_MODE_INT_MAX; | ||
| 250 | + } | ||
| 251 | + tilingData_.baseTiling.quantFlashAttnPageAttentionParams.blockSize = qfaInfo_->blockSize; | ||
| 252 | + tilingData_.baseTiling.quantFlashAttnPageAttentionParams.maxBlockNumPerBatch = 0; | ||
| 253 | +} | ||
| 254 | + | ||
| 255 | +bool QuantFlashAttnTilingHif8Impl::CheckNeedInitOutput() const | ||
| 256 | +{ | ||
| 257 | + if (seqUsedQFlag_ || seqUsedKvFlag_) { | ||
| 258 | + return true; | ||
| 259 | + } | ||
| 260 | + if (qfaInfo_->qLayout == QfaLayout::TND && qfaInfo_->kvLayout == QfaLayout::TND) { | ||
| 261 | + return qfaInfo_->maskMode != static_cast<int64_t>(MaskMode::NO_MASK); | ||
| 262 | + } | ||
| 263 | + if (qfaInfo_->maskMode == static_cast<int64_t>(MaskMode::NO_MASK)) { | ||
| 264 | + return false; | ||
| 265 | + } | ||
| 266 | + if (qfaInfo_->maskMode == static_cast<int64_t>(MaskMode::CAUSAL)) { | ||
| 267 | + return qfaInfo_->s1Size > qfaInfo_->s2Size; | ||
| 268 | + } | ||
| 269 | + if (qfaInfo_->maskMode == static_cast<int64_t>(MaskMode::SLIDING_WINDOW)) { | ||
| 270 | + if (qfaInfo_->winRight == -1) { | ||
| 271 | + return false; | ||
| 272 | + } | ||
| 273 | + return (qfaInfo_->s1Size - qfaInfo_->s2Size) > qfaInfo_->winRight; | ||
| 274 | + } | ||
| 275 | + return false; | ||
| 276 | +} | ||
| 277 | + | ||
| 278 | +ge::graphStatus QuantFlashAttnTilingHif8Impl::SetTilingData(QuantFlashAttnTilingData &tilingData) | ||
| 279 | +{ | ||
| 280 | + QuantFlashAttnTilingData *tiling = context_->GetTilingData<QuantFlashAttnTilingData>(); | ||
| 281 | + OP_CHECK_IF(tiling == nullptr, OP_LOGE(qfaInfo_->opName, "The tiling data is nullptr"), return ge::GRAPH_FAILED); | ||
| 282 | + *tiling = tilingData; | ||
| 283 | + return ge::GRAPH_SUCCESS; | ||
| 284 | +} | ||
| 285 | + | ||
| 286 | +void QuantFlashAttnTilingHif8Impl::PrintAllTilingData() | ||
| 287 | +{ | ||
| 288 | + QuantFlashAttnQuantTilingArch35 &baseTiling = tilingData_.baseTiling; | ||
| 289 | + QuantFlashAttnBaseParams ¶ms = baseTiling.quantFlashAttnBaseParams; | ||
| 290 | + QuantFlashAttnAttenMaskParams &maskParams = baseTiling.quantFlashAttnAttenMaskParams; | ||
| 291 | + QuantFlashAttnPageAttentionParams &paParams = baseTiling.quantFlashAttnPageAttentionParams; | ||
| 292 | + QuantFlashAttnWorkspaceParams &wsParams = baseTiling.quantFlashAttnWorkspaceParams; | ||
| 293 | + | ||
| 294 | + OP_LOGD(qfaInfo_->opName, "HIF8 bSize:%d", params.bSize); | ||
| 295 | + OP_LOGD(qfaInfo_->opName, "HIF8 t1Size:%d", params.t1Size); | ||
| 296 | + OP_LOGD(qfaInfo_->opName, "HIF8 t2Size:%d", params.t2Size); | ||
| 297 | + OP_LOGD(qfaInfo_->opName, "HIF8 n2Size:%d", params.n2Size); | ||
| 298 | + OP_LOGD(qfaInfo_->opName, "HIF8 gSize:%d", params.gSize); | ||
| 299 | + OP_LOGD(qfaInfo_->opName, "HIF8 s1Size:%d", params.s1Size); | ||
| 300 | + OP_LOGD(qfaInfo_->opName, "HIF8 s2Size:%d", params.s2Size); | ||
| 301 | + OP_LOGD(qfaInfo_->opName, "HIF8 dSize:%d", params.dSize); | ||
| 302 | + OP_LOGD(qfaInfo_->opName, "HIF8 dSizeV:%d", params.dSizeV); | ||
| 303 | + OP_LOGD(qfaInfo_->opName, "HIF8 cuSeqLensQSize:%d", params.cuSeqLensQSize); | ||
| 304 | + OP_LOGD(qfaInfo_->opName, "HIF8 cuSeqLensKVSize:%d", params.cuSeqLensKVSize); | ||
| 305 | + OP_LOGD(qfaInfo_->opName, "HIF8 seqUsedQSize:%d", params.seqUsedQSize); | ||
| 306 | + OP_LOGD(qfaInfo_->opName, "HIF8 seqUsedKvSize:%d", params.seqUsedKvSize); | ||
| 307 | + OP_LOGD(qfaInfo_->opName, "HIF8 scaleValue:%f", params.scaleValue); | ||
| 308 | + OP_LOGD(qfaInfo_->opName, "HIF8 iscuSeqLengthsNull:%d", params.iscuSeqLengthsNull); | ||
| 309 | + OP_LOGD(qfaInfo_->opName, "HIF8 iscuSeqLengthsKVNull:%d", params.iscuSeqLengthsKVNull); | ||
| 310 | + OP_LOGD(qfaInfo_->opName, "HIF8 isKvContinuous:%d", params.isKvContinuous); | ||
| 311 | + OP_LOGD(qfaInfo_->opName, "HIF8 isSoftMaxLseEnable:%d", params.isSoftMaxLseEnable); | ||
| 312 | + OP_LOGD(qfaInfo_->opName, "HIF8 coreNum:%d", params.coreNum); | ||
| 313 | + OP_LOGD(qfaInfo_->opName, "HIF8 outputLayout:%d", params.outputLayout); | ||
| 314 | + OP_LOGD(qfaInfo_->opName, "HIF8 needInitOutput:%d", params.needInitOutput); | ||
| 315 | + | ||
| 316 | + OP_LOGD(qfaInfo_->opName, "HIF8 maskMode:%d", maskParams.sparseMode); | ||
| 317 | + OP_LOGD(qfaInfo_->opName, "HIF8 winLefts:%d", maskParams.winLefts); | ||
| 318 | + OP_LOGD(qfaInfo_->opName, "HIF8 winRights:%d", maskParams.winRights); | ||
| 319 | + OP_LOGD(qfaInfo_->opName, "HIF8 attenMaskS1Size:%d", maskParams.attenMaskS1Size); | ||
| 320 | + OP_LOGD(qfaInfo_->opName, "HIF8 attenMaskS2Size:%d", maskParams.attenMaskS2Size); | ||
| 321 | + | ||
| 322 | + OP_LOGD(qfaInfo_->opName, "HIF8 paLayoutType:%d", paParams.paLayoutType); | ||
| 323 | + OP_LOGD(qfaInfo_->opName, "HIF8 blockSize:%d", paParams.blockSize); | ||
| 324 | + OP_LOGD(qfaInfo_->opName, "HIF8 maxBlockNumPerBatch:%d", paParams.maxBlockNumPerBatch); | ||
| 325 | + | ||
| 326 | + OP_LOGD(qfaInfo_->opName, "HIF8 accumOutSize:%d", wsParams.accumOutSize); | ||
| 327 | + OP_LOGD(qfaInfo_->opName, "HIF8 logSumExpSize:%d", wsParams.logSumExpSize); | ||
| 328 | + | ||
| 329 | + OP_LOGD(qfaInfo_->opName, "HIF8 tilingKey:%llu", tilingKey_); | ||
| 330 | +} | ||
| 331 | + | ||
| 332 | +} // namespace quant_flash_attn | ||
| 333 | + | ||
| 334 | +using quant_flash_attn::QuantFlashAttnTilingHif8Impl; | ||
| 335 | + | ||
| 336 | +REGISTER_TILING_TEMPLATE_FIA(QuantFlashAttn, QuantFlashAttnTilingHif8Impl, | ||
| 337 | + std::vector<int32_t>({static_cast<int32_t>(NpuArch::DAV_3510)}), 3); | ||
| 338 | +} // namespace optiling | ||
| @@ -0,0 +1,80 @@ | |||
| 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 quant_flash_attn_tiling_hif8.h | ||
| 13 | + * \brief QuantFlashAttn arch35 tiling implementation (A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32) | ||
| 14 | + */ | ||
| 15 | +#ifndef QUANT_FLASH_ATTN_TILING_IMPL_HIF8_H_ | ||
| 16 | +#define QUANT_FLASH_ATTN_TILING_IMPL_HIF8_H_ | ||
| 17 | + | ||
| 18 | +#include "register/tilingdata_base.h" | ||
| 19 | +#include "exe_graph/runtime/tiling_context.h" | ||
| 20 | +#include "../qfa_tiling_info.h" | ||
| 21 | +#include "../quant_flash_attn_tiling_common.h" | ||
| 22 | +#include "tiling/tiling_api.h" | ||
| 23 | +#include "../../op_kernel/arch35/quant_flash_attn_tiling_data.h" | ||
| 24 | +#include "../../op_kernel/arch35/quant_flash_attn_template_tiling_key.h" | ||
| 25 | + | ||
| 26 | +namespace optiling { | ||
| 27 | +namespace quant_flash_attn { | ||
| 28 | + | ||
| 29 | +class QuantFlashAttnTilingHif8Impl : public FiaTilingBase { | ||
| 30 | +public: | ||
| 31 | + explicit QuantFlashAttnTilingHif8Impl(gert::TilingContext *context) | ||
| 32 | + : FiaTilingBase(context) | ||
| 33 | + {} | ||
| 34 | + ~QuantFlashAttnTilingHif8Impl() override = default; | ||
| 35 | + | ||
| 36 | + void InitTilingInfo(TilingInfo *tilingInfo) override; | ||
| 37 | + bool IsCapable() override; | ||
| 38 | + ge::graphStatus DoOpTiling() override; | ||
| 39 | + | ||
| 40 | +private: | ||
| 41 | + ge::graphStatus SetPlatMemoryInfo(); | ||
| 42 | + void SplitPolicy(); | ||
| 43 | + void ComputeTilingData(); | ||
| 44 | + void GenTilingKey(); | ||
| 45 | + void CalcWorkspaceSize(); | ||
| 46 | + void UpdateTilingKeyConfig(); | ||
| 47 | + void UpdateTilingKeyLayout(); | ||
| 48 | + void UpdateTilingKeyKvLayout(); | ||
| 49 | + void UpdateTilingKeyQuantMode(); | ||
| 50 | + void UpdateTilingKeyInfo(); | ||
| 51 | + void SetQFATilingData(); | ||
| 52 | + void InitImplParam(); | ||
| 53 | + void PrintAllTilingData(); | ||
| 54 | + void CalcScheduleMode(); | ||
| 55 | + void CalcNumBlocks(uint32_t aicNum); | ||
| 56 | + void FillTiling(); | ||
| 57 | + ge::graphStatus SetTilingData(QuantFlashAttnTilingData &tilingData); | ||
| 58 | + bool CheckNeedInitOutput() const; | ||
| 59 | + | ||
| 60 | + QuantFlashAttnTilingData tilingData_; | ||
| 61 | + QfaTilingKeyInfo tilingKeyInfo_; | ||
| 62 | + QfaPlatFormInfo platformInfo_; | ||
| 63 | + uint32_t sOuterFactor_ = 0; | ||
| 64 | + uint32_t sInnerFactor_ = 0; | ||
| 65 | + bool flashDecodeFlag_ = false; | ||
冗余变量,新接口上不知道是否开启了FD ![]() ![]() | |||
| 66 | + bool cuSeqLenQFlag_ = false; | ||
| 67 | + bool cuSeqLenKVFlag_ = false; | ||
| 68 | + bool seqUsedQFlag_ = false; | ||
| 69 | + bool seqUsedKvFlag_ = false; | ||
| 70 | + uint64_t tilingKey_ = 0; | ||
| 71 | + uint64_t workspaceSize_ = 0; | ||
| 72 | + ScheduleMode scheduleMode_ = ScheduleMode::BATCH_MODE; | ||
| 73 | + uint32_t numBlocks_ = 0; | ||
| 74 | + | ||
| 75 | + QfaTilingInfo *qfaInfo_ = nullptr; | ||
| 76 | +}; | ||
| 77 | + | ||
| 78 | +} // namespace quant_flash_attn | ||
| 79 | +} // namespace optiling | ||
| 80 | +#endif // QUANT_FLASH_ATTN_TILING_IMPL_HIF8_H_ | ||
| @@ -82,42 +82,28 @@ ge::graphStatus CommonChecker::CheckSingleParaLayout(const QfaTilingInfo &qfaInf | |||
| 82 | 82 | ||
| 83 | ge::graphStatus CommonChecker::CheckSingleParaDtype(const QfaTilingInfo &qfaInfo) | 83 | ge::graphStatus CommonChecker::CheckSingleParaDtype(const QfaTilingInfo &qfaInfo) |
| 84 | { | 84 | { |
| 85 | - // q: tensor_type 仅支持 FLOAT8_E4M3FN | 85 | + const std::vector<ge::DataType> supportedQuantDtypes = {ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8}; |
| 86 | - const gert::CompileTimeTensorDesc *queryDesc = qfaInfo.opParamInfo.query.desc; | 86 | + const auto checkQuantDtype = [&](const gert::CompileTimeTensorDesc *desc, |
| 87 | - if (queryDesc != nullptr) { | 87 | + const std::string &name) -> ge::graphStatus { |
| 88 | + if (desc == nullptr) { | ||
| 89 | + return ge::GRAPH_SUCCESS; | ||
| 90 | + } | ||
| 88 | OP_CHECK_IF( | 91 | OP_CHECK_IF( |
| 89 | - queryDesc->GetDataType() != ge::DT_FLOAT8_E4M3FN, | 92 | + std::find(supportedQuantDtypes.begin(), supportedQuantDtypes.end(), desc->GetDataType()) == |
| 90 | - OP_LOGE_FOR_INVALID_DTYPE(qfaInfo.opName, QUERY_NAME.c_str(), | 93 | + supportedQuantDtypes.end(), |
| 91 | - DataTypeToSerialString(queryDesc->GetDataType()).c_str(), "FLOAT8_E4M3FN"), | 94 | + OP_LOGE_FOR_INVALID_DTYPE(qfaInfo.opName, name.c_str(), DataTypeToSerialString(desc->GetDataType()).c_str(), |
| 95 | + "FLOAT8_E4M3FN/HIFLOAT8"), | ||
| 92 | return ge::GRAPH_FAILED); | 96 | return ge::GRAPH_FAILED); |
| 93 | - if (CheckFormatSupport(queryDesc, QUERY_NAME) != ge::GRAPH_SUCCESS) { | 97 | + if (CheckFormatSupport(desc, name) != ge::GRAPH_SUCCESS) { |
| 94 | return ge::GRAPH_FAILED; | 98 | return ge::GRAPH_FAILED; |
| 95 | } | 99 | } |
| 96 | - } | 100 | + return ge::GRAPH_SUCCESS; |
| 101 | + }; | ||
| 97 | 102 | ||
| 98 | - // k: tensor_type 仅支持 FLOAT8_E4M3FN | 103 | + if (checkQuantDtype(qfaInfo.opParamInfo.query.desc, QUERY_NAME) != ge::GRAPH_SUCCESS || |
| 99 | - const gert::CompileTimeTensorDesc *keyDesc = qfaInfo.opParamInfo.key.desc; | 104 | + checkQuantDtype(qfaInfo.opParamInfo.key.desc, KEY_NAME) != ge::GRAPH_SUCCESS || |
| 100 | - if (keyDesc != nullptr) { | 105 | + checkQuantDtype(qfaInfo.opParamInfo.value.desc, VALUE_NAME) != ge::GRAPH_SUCCESS) { |
| 101 | - OP_CHECK_IF(keyDesc->GetDataType() != ge::DT_FLOAT8_E4M3FN, | 106 | + return ge::GRAPH_FAILED; |
| 102 | - OP_LOGE_FOR_INVALID_DTYPE(qfaInfo.opName, KEY_NAME.c_str(), | ||
| 103 | - DataTypeToSerialString(keyDesc->GetDataType()).c_str(), "FLOAT8_E4M3FN"), | ||
| 104 | - return ge::GRAPH_FAILED); | ||
| 105 | - if (CheckFormatSupport(keyDesc, KEY_NAME) != ge::GRAPH_SUCCESS) { | ||
| 106 | - return ge::GRAPH_FAILED; | ||
| 107 | - } | ||
| 108 | - } | ||
| 109 | - | ||
| 110 | - // v: tensor_type 仅支持 FLOAT8_E4M3FN | ||
| 111 | - const gert::CompileTimeTensorDesc *valueDesc = qfaInfo.opParamInfo.value.desc; | ||
| 112 | - if (valueDesc != nullptr) { | ||
| 113 | - OP_CHECK_IF( | ||
| 114 | - valueDesc->GetDataType() != ge::DT_FLOAT8_E4M3FN, | ||
| 115 | - OP_LOGE_FOR_INVALID_DTYPE(qfaInfo.opName, VALUE_NAME.c_str(), | ||
| 116 | - DataTypeToSerialString(valueDesc->GetDataType()).c_str(), "FLOAT8_E4M3FN"), | ||
| 117 | - return ge::GRAPH_FAILED); | ||
| 118 | - if (CheckFormatSupport(valueDesc, VALUE_NAME) != ge::GRAPH_SUCCESS) { | ||
| 119 | - return ge::GRAPH_FAILED; | ||
| 120 | - } | ||
| 121 | } | 107 | } |
| 122 | 108 | ||
| 123 | // attn_out: data_type 仅支持 BFLOAT16 | 109 | // attn_out: data_type 仅支持 BFLOAT16 |
| @@ -142,15 +128,17 @@ ge::graphStatus CommonChecker::CheckSingleParaDtype(const QfaTilingInfo &qfaInfo | |||
| 142 | ge::graphStatus CommonChecker::CheckSingleParaShapeDim(const QfaTilingInfo &qfaInfo) | 128 | ge::graphStatus CommonChecker::CheckSingleParaShapeDim(const QfaTilingInfo &qfaInfo) |
| 143 | { | 129 | { |
| 144 | const std::vector<uint32_t> supportedKvDims = {DIM_NUM_3, DIM_NUM_4, DIM_NUM_5}; | 130 | const std::vector<uint32_t> supportedKvDims = {DIM_NUM_3, DIM_NUM_4, DIM_NUM_5}; |
| 131 | + const std::vector<uint32_t> supportedQOutDims = {DIM_NUM_3, DIM_NUM_4}; | ||
| 145 | 132 | ||
| 146 | - // q: shape dim 仅支持 3 | 133 | + // q: shape dim 支持 3D/4D |
| 147 | const gert::StorageShape *queryShape = qfaInfo.opParamInfo.query.shape; | 134 | const gert::StorageShape *queryShape = qfaInfo.opParamInfo.query.shape; |
| 148 | if (queryShape != nullptr) { | 135 | if (queryShape != nullptr) { |
| 149 | uint32_t queryDimNum = queryShape->GetStorageShape().GetDimNum(); | 136 | uint32_t queryDimNum = queryShape->GetStorageShape().GetDimNum(); |
| 150 | - OP_CHECK_IF(queryDimNum != DIM_NUM_3, | 137 | + OP_CHECK_IF( |
| 151 | - OP_LOGE_FOR_INVALID_SHAPEDIM(qfaInfo.opName, QUERY_NAME.c_str(), | 138 | + std::find(supportedQOutDims.begin(), supportedQOutDims.end(), queryDimNum) == supportedQOutDims.end(), |
| 152 | - (std::to_string(queryDimNum) + "D").c_str(), "3D"), | 139 | + OP_LOGE_FOR_INVALID_SHAPEDIM(qfaInfo.opName, QUERY_NAME.c_str(), |
| 153 | - return ge::GRAPH_FAILED); | 140 | + (std::to_string(queryDimNum) + "D").c_str(), "3D/4D"), |
| 141 | + return ge::GRAPH_FAILED); | ||
| 154 | } | 142 | } |
| 155 | 143 | ||
| 156 | // k: shape dim 支持 3、4、5 | 144 | // k: shape dim 支持 3、4、5 |
| @@ -173,14 +161,15 @@ ge::graphStatus CommonChecker::CheckSingleParaShapeDim(const QfaTilingInfo &qfaI | |||
| 173 | return ge::GRAPH_FAILED); | 161 | return ge::GRAPH_FAILED); |
| 174 | } | 162 | } |
| 175 | 163 | ||
| 176 | - // attn_out: shape dim 仅支持 3 | 164 | + // attn_out: shape dim 支持 3D/4D |
| 177 | const gert::StorageShape *attnOutShape = qfaInfo.opParamInfo.attnOut.shape; | 165 | const gert::StorageShape *attnOutShape = qfaInfo.opParamInfo.attnOut.shape; |
| 178 | if (attnOutShape != nullptr) { | 166 | if (attnOutShape != nullptr) { |
| 179 | uint32_t attnOutDimNum = attnOutShape->GetStorageShape().GetDimNum(); | 167 | uint32_t attnOutDimNum = attnOutShape->GetStorageShape().GetDimNum(); |
| 180 | - OP_CHECK_IF(attnOutDimNum != DIM_NUM_3, | 168 | + OP_CHECK_IF( |
| 181 | - OP_LOGE_FOR_INVALID_SHAPEDIM(qfaInfo.opName, ATTN_OUT_NAME.c_str(), | 169 | + std::find(supportedQOutDims.begin(), supportedQOutDims.end(), attnOutDimNum) == supportedQOutDims.end(), |
| 182 | - (std::to_string(attnOutDimNum) + "D").c_str(), "3D"), | 170 | + OP_LOGE_FOR_INVALID_SHAPEDIM(qfaInfo.opName, ATTN_OUT_NAME.c_str(), |
| 183 | - return ge::GRAPH_FAILED); | 171 | + (std::to_string(attnOutDimNum) + "D").c_str(), "3D/4D"), |
| 172 | + return ge::GRAPH_FAILED); | ||
| 184 | } | 173 | } |
| 185 | 174 | ||
| 186 | return ge::GRAPH_SUCCESS; | 175 | return ge::GRAPH_SUCCESS; |
| @@ -220,7 +209,7 @@ ge::graphStatus CommonChecker::CheckQuantDataType(const QfaTilingInfo &qfaInfo) | |||
| 220 | 209 | ||
| 221 | ge::graphStatus CommonChecker::CheckDtypeConsistency(const QfaTilingInfo &qfaInfo) | 210 | ge::graphStatus CommonChecker::CheckDtypeConsistency(const QfaTilingInfo &qfaInfo) |
| 222 | { | 211 | { |
| 223 | - // 文档约束: q、k、v 的数据类型必须相同(均为 FLOAT8_E4M3FN) | 212 | + // 文档约束: q、k、v 的数据类型必须相同 |
删除注释中的“文档约束:”,写在这里没有意义,整个算子中存在多处类似描述,一并删除 ![]() ![]() | |||
| 224 | const gert::CompileTimeTensorDesc *queryDesc = qfaInfo.opParamInfo.query.desc; | 213 | const gert::CompileTimeTensorDesc *queryDesc = qfaInfo.opParamInfo.query.desc; |
| 225 | const gert::CompileTimeTensorDesc *keyDesc = qfaInfo.opParamInfo.key.desc; | 214 | const gert::CompileTimeTensorDesc *keyDesc = qfaInfo.opParamInfo.key.desc; |
| 226 | const gert::CompileTimeTensorDesc *valueDesc = qfaInfo.opParamInfo.value.desc; | 215 | const gert::CompileTimeTensorDesc *valueDesc = qfaInfo.opParamInfo.value.desc; |
| @@ -228,15 +217,19 @@ ge::graphStatus CommonChecker::CheckDtypeConsistency(const QfaTilingInfo &qfaInf | |||
| 228 | ge::DataType queryDtype = queryDesc->GetDataType(); | 217 | ge::DataType queryDtype = queryDesc->GetDataType(); |
| 229 | 218 | ||
| 230 | OP_CHECK_IF(keyDesc != nullptr && keyDesc->GetDataType() != queryDtype, | 219 | OP_CHECK_IF(keyDesc != nullptr && keyDesc->GetDataType() != queryDtype, |
| 231 | - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( | 220 | + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON(qfaInfo.opName, KEY_NAME.c_str(), |
| 232 | - qfaInfo.opName, KEY_NAME.c_str(), DataTypeToSerialString(keyDesc->GetDataType()).c_str(), | 221 | + DataTypeToSerialString(keyDesc->GetDataType()).c_str(), |
| 233 | - "The dtype of key must be the same as dtype(FLOAT8_E4M3FN) of query"), | 222 | + ("The dtype of key must be the same as dtype(" + |
| 223 | + std::string(DataTypeToSerialString(queryDtype)) + ") of query") | ||
| 224 | + .c_str()), | ||
| 234 | return ge::GRAPH_FAILED); | 225 | return ge::GRAPH_FAILED); |
| 235 | 226 | ||
| 236 | OP_CHECK_IF(valueDesc != nullptr && valueDesc->GetDataType() != queryDtype, | 227 | OP_CHECK_IF(valueDesc != nullptr && valueDesc->GetDataType() != queryDtype, |
| 237 | - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( | 228 | + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON(qfaInfo.opName, VALUE_NAME.c_str(), |
| 238 | - qfaInfo.opName, VALUE_NAME.c_str(), DataTypeToSerialString(valueDesc->GetDataType()).c_str(), | 229 | + DataTypeToSerialString(valueDesc->GetDataType()).c_str(), |
| 239 | - "The dtype of value must be the same as dtype(FLOAT8_E4M3FN) of query"), | 230 | + ("The dtype of value must be the same as dtype(" + |
| 231 | + std::string(DataTypeToSerialString(queryDtype)) + ") of query") | ||
| 232 | + .c_str()), | ||
| 240 | return ge::GRAPH_FAILED); | 233 | return ge::GRAPH_FAILED); |
| 241 | return ge::GRAPH_SUCCESS; | 234 | return ge::GRAPH_SUCCESS; |
| 242 | } | 235 | } |
| @@ -174,10 +174,11 @@ ge::graphStatus MaskChecker::CheckMultiPara(const QfaTilingInfo &qfaInfo) | |||
| 174 | 174 | ||
| 175 | ge::graphStatus MaskChecker::CheckMaskModeQuantMode(const QfaTilingInfo &qfaInfo) | 175 | ge::graphStatus MaskChecker::CheckMaskModeQuantMode(const QfaTilingInfo &qfaInfo) |
| 176 | { | 176 | { |
| 177 | - // 文档约束: MxFP8/GQA_FP8_FULLQUANT 仅支持 mask_mode 取 0 和 3 (不支持 SLIDING_WINDOW=4) | 177 | + // 文档约束: MxFP8/GQA_FP8_FULLQUANT/HIF8 均仅支持 mask_mode 取 0 和 3 (不支持 SLIDING_WINDOW=4) |
删除注释中的“文档约束:”,写在这里没有意义,整个算子中存在多处类似描述,一并删除 ![]() ![]() | |||
| 178 | if (qfaInfo.quantMode == QfaQuantMode::A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32 || | 178 | if (qfaInfo.quantMode == QfaQuantMode::A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32 || |
| 179 | qfaInfo.quantMode == | 179 | qfaInfo.quantMode == |
| 180 | - QfaQuantMode::A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32) { | 180 | + QfaQuantMode::A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32 || |
| 181 | + qfaInfo.quantMode == QfaQuantMode::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32) { | ||
| 181 | OP_CHECK_IF(qfaInfo.maskMode == static_cast<int64_t>(MaskMode::SLIDING_WINDOW), | 182 | OP_CHECK_IF(qfaInfo.maskMode == static_cast<int64_t>(MaskMode::SLIDING_WINDOW), |
| 182 | OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(qfaInfo.opName, MASK_MODE_NAME.c_str(), | 183 | OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(qfaInfo.opName, MASK_MODE_NAME.c_str(), |
| 183 | std::to_string(qfaInfo.maskMode).c_str(), | 184 | std::to_string(qfaInfo.maskMode).c_str(), |
| @@ -36,11 +36,12 @@ using namespace arch35QFA; | |||
| 36 | 36 | ||
| 37 | namespace { | 37 | namespace { |
| 38 | // descale dtype 期望值表: 各量化场景下 q/k/v descale 的 tensor_type 要求 | 38 | // descale dtype 期望值表: 各量化场景下 q/k/v descale 的 tensor_type 要求 |
| 39 | -// MxFP8: FLOAT8_E8M0; GQA_FP8_FULLQUANT: FLOAT32 | 39 | +// MxFP8: FLOAT8_E8M0; GQA_FP8_FULLQUANT: FLOAT32; HIF8: FLOAT32 |
| 40 | const std::map<QfaQuantMode, std::pair<ge::DataType, std::string>> DESCALE_DTYPE_TABLE = { | 40 | const std::map<QfaQuantMode, std::pair<ge::DataType, std::string>> DESCALE_DTYPE_TABLE = { |
| 41 | {QfaQuantMode::A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32, {ge::DT_FLOAT8_E8M0, "FLOAT8_E8M0"}}, | 41 | {QfaQuantMode::A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32, {ge::DT_FLOAT8_E8M0, "FLOAT8_E8M0"}}, |
| 42 | {QfaQuantMode::A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32, | 42 | {QfaQuantMode::A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32, |
| 43 | {ge::DT_FLOAT, "FLOAT32"}}, | 43 | {ge::DT_FLOAT, "FLOAT32"}}, |
| 44 | + {QfaQuantMode::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32, {ge::DT_FLOAT, "FLOAT32"}}, | ||
| 44 | }; | 45 | }; |
| 45 | } // namespace | 46 | } // namespace |
| 46 | 47 | ||
| @@ -50,15 +51,14 @@ const std::map<QfaQuantMode, std::pair<ge::DataType, std::string>> DESCALE_DTYPE | |||
| 50 | 51 | ||
| 51 | ge::graphStatus QuantChecker::CheckSingleParaQuantMode(const QfaTilingInfo &qfaInfo) | 52 | ge::graphStatus QuantChecker::CheckSingleParaQuantMode(const QfaTilingInfo &qfaInfo) |
| 52 | { | 53 | { |
| 53 | - // 文档约束: data_type 支持 INT32;当前仅支持 quant_mode = 1 | 54 | + // 文档约束: data_type 支持 INT32;当前支持 quant_mode = 1、0 |
删除注释中的“文档约束:”,写在这里没有意义,整个算子中存在多处类似描述,一并删除 ![]() ![]() | |||
| 54 | // quantMode 为属性,QfaTilingInfo 中存储为 QfaQuantMode 枚举 | 55 | // quantMode 为属性,QfaTilingInfo 中存储为 QfaQuantMode 枚举 |
| 55 | - const std::vector<uint32_t> supportedQuantModes = {1}; | 56 | + const std::vector<uint32_t> supportedQuantModes = {1, 0}; |
| 56 | uint32_t quantModeVal = static_cast<uint32_t>(qfaInfo.quantMode); | 57 | uint32_t quantModeVal = static_cast<uint32_t>(qfaInfo.quantMode); |
| 57 | OP_CHECK_IF( | 58 | OP_CHECK_IF( |
| 58 | std::find(supportedQuantModes.begin(), supportedQuantModes.end(), quantModeVal) == supportedQuantModes.end(), | 59 | std::find(supportedQuantModes.begin(), supportedQuantModes.end(), quantModeVal) == supportedQuantModes.end(), |
| 59 | OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(qfaInfo.opName, "quant_mode", std::to_string(quantModeVal).c_str(), | 60 | OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(qfaInfo.opName, "quant_mode", std::to_string(quantModeVal).c_str(), |
| 60 | - "The value of quant_mode must be 1 " | 61 | + "The value of quant_mode must be 1 or 0"), |
| 61 | - "(A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32)"), | ||
| 62 | return ge::GRAPH_FAILED); | 62 | return ge::GRAPH_FAILED); |
| 63 | return ge::GRAPH_SUCCESS; | 63 | return ge::GRAPH_SUCCESS; |
| 64 | } | 64 | } |
| @@ -115,7 +115,7 @@ ge::graphStatus QuantChecker::CheckSingleParaQDescale(const QfaTilingInfo &qfaIn | |||
| 115 | return ge::GRAPH_FAILED; | 115 | return ge::GRAPH_FAILED; |
| 116 | } | 116 | } |
| 117 | 117 | ||
| 118 | - // 场景: shape dim 校验 | 118 | + // 场景: shape dim 校验 (MxFP8/FP8) |
| 119 | if (CheckQDescaleDimMxFp8(qfaInfo) != ge::GRAPH_SUCCESS || CheckQDescaleDimGqaFp8(qfaInfo) != ge::GRAPH_SUCCESS) { | 119 | if (CheckQDescaleDimMxFp8(qfaInfo) != ge::GRAPH_SUCCESS || CheckQDescaleDimGqaFp8(qfaInfo) != ge::GRAPH_SUCCESS) { |
| 120 | return ge::GRAPH_FAILED; | 120 | return ge::GRAPH_FAILED; |
| 121 | } | 121 | } |
| @@ -174,7 +174,7 @@ ge::graphStatus QuantChecker::CheckSingleParaKDescale(const QfaTilingInfo &qfaIn | |||
| 174 | return ge::GRAPH_FAILED; | 174 | return ge::GRAPH_FAILED; |
| 175 | } | 175 | } |
| 176 | 176 | ||
| 177 | - // 场景: shape dim 校验 | 177 | + // 场景: shape dim 校验 (MxFP8/FP8) |
| 178 | if (CheckKDescaleDimMxFp8(qfaInfo) != ge::GRAPH_SUCCESS || CheckKDescaleDimGqaFp8(qfaInfo) != ge::GRAPH_SUCCESS) { | 178 | if (CheckKDescaleDimMxFp8(qfaInfo) != ge::GRAPH_SUCCESS || CheckKDescaleDimGqaFp8(qfaInfo) != ge::GRAPH_SUCCESS) { |
| 179 | return ge::GRAPH_FAILED; | 179 | return ge::GRAPH_FAILED; |
| 180 | } | 180 | } |
| @@ -233,7 +233,7 @@ ge::graphStatus QuantChecker::CheckSingleParaVDescale(const QfaTilingInfo &qfaIn | |||
| 233 | return ge::GRAPH_FAILED; | 233 | return ge::GRAPH_FAILED; |
| 234 | } | 234 | } |
| 235 | 235 | ||
| 236 | - // 场景: shape dim 校验 | 236 | + // 场景: shape dim 校验 (MxFP8/FP8) |
| 237 | if (CheckVDescaleDimMxFp8(qfaInfo) != ge::GRAPH_SUCCESS || CheckVDescaleDimGqaFp8(qfaInfo) != ge::GRAPH_SUCCESS) { | 237 | if (CheckVDescaleDimMxFp8(qfaInfo) != ge::GRAPH_SUCCESS || CheckVDescaleDimGqaFp8(qfaInfo) != ge::GRAPH_SUCCESS) { |
| 238 | return ge::GRAPH_FAILED; | 238 | return ge::GRAPH_FAILED; |
| 239 | } | 239 | } |
| @@ -418,13 +418,16 @@ ge::graphStatus QuantChecker::CheckQDescaleShapeGqaFp8(const QfaTilingInfo &qfaI | |||
| 418 | 418 | ||
| 419 | ge::graphStatus QuantChecker::CheckQDescaleShape(const QfaTilingInfo &qfaInfo) const | 419 | ge::graphStatus QuantChecker::CheckQDescaleShape(const QfaTilingInfo &qfaInfo) const |
| 420 | { | 420 | { |
| 421 | - // 公共: 空指针跳过 | ||
| 422 | const gert::StorageShape *shape = qfaInfo.opParamInfo.qDescale.shape; | 421 | const gert::StorageShape *shape = qfaInfo.opParamInfo.qDescale.shape; |
| 423 | if (shape == nullptr) { | 422 | if (shape == nullptr) { |
| 424 | return ge::GRAPH_SUCCESS; | 423 | return ge::GRAPH_SUCCESS; |
| 425 | } | 424 | } |
| 426 | 425 | ||
| 427 | - // 场景: q_descale shape 匹配关系 | 426 | + // HIF8 per-tensor: q_descale shape must be (1,), 1D |
| 427 | + if (qfaInfo.quantMode == QfaQuantMode::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32) { | ||
| 428 | + return CheckShapeEqual(*shape, {1}, Q_DESCALE_NAME, qfaInfo.opName); | ||
| 429 | + } | ||
| 430 | + | ||
| 428 | if (CheckQDescaleShapeMxFp8(qfaInfo) != ge::GRAPH_SUCCESS || | 431 | if (CheckQDescaleShapeMxFp8(qfaInfo) != ge::GRAPH_SUCCESS || |
| 429 | CheckQDescaleShapeGqaFp8(qfaInfo) != ge::GRAPH_SUCCESS) { | 432 | CheckQDescaleShapeGqaFp8(qfaInfo) != ge::GRAPH_SUCCESS) { |
| 430 | return ge::GRAPH_FAILED; | 433 | return ge::GRAPH_FAILED; |
| @@ -499,7 +502,11 @@ ge::graphStatus QuantChecker::CheckKDescaleShape(const QfaTilingInfo &qfaInfo) c | |||
| 499 | return ge::GRAPH_SUCCESS; | 502 | return ge::GRAPH_SUCCESS; |
| 500 | } | 503 | } |
| 501 | 504 | ||
| 502 | - // 场景: k_descale shape 匹配关系 | 505 | + // HIF8 per-tensor: k_descale shape must be (1,), 1D |
| 506 | + if (qfaInfo.quantMode == QfaQuantMode::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32) { | ||
| 507 | + return CheckShapeEqual(*shape, {1}, K_DESCALE_NAME, qfaInfo.opName); | ||
| 508 | + } | ||
| 509 | + | ||
| 503 | if (CheckKDescaleShapeMxFp8(qfaInfo) != ge::GRAPH_SUCCESS || | 510 | if (CheckKDescaleShapeMxFp8(qfaInfo) != ge::GRAPH_SUCCESS || |
| 504 | CheckKDescaleShapeGqaFp8(qfaInfo) != ge::GRAPH_SUCCESS) { | 511 | CheckKDescaleShapeGqaFp8(qfaInfo) != ge::GRAPH_SUCCESS) { |
| 505 | return ge::GRAPH_FAILED; | 512 | return ge::GRAPH_FAILED; |
| @@ -567,13 +574,16 @@ ge::graphStatus QuantChecker::CheckVDescaleShapeGqaFp8(const QfaTilingInfo &qfaI | |||
| 567 | 574 | ||
| 568 | ge::graphStatus QuantChecker::CheckVDescaleShape(const QfaTilingInfo &qfaInfo) const | 575 | ge::graphStatus QuantChecker::CheckVDescaleShape(const QfaTilingInfo &qfaInfo) const |
| 569 | { | 576 | { |
| 570 | - // 公共: 空指针跳过 | ||
| 571 | const gert::StorageShape *shape = qfaInfo.opParamInfo.vDescale.shape; | 577 | const gert::StorageShape *shape = qfaInfo.opParamInfo.vDescale.shape; |
| 572 | if (shape == nullptr) { | 578 | if (shape == nullptr) { |
| 573 | return ge::GRAPH_SUCCESS; | 579 | return ge::GRAPH_SUCCESS; |
| 574 | } | 580 | } |
| 575 | 581 | ||
| 576 | - // 场景: v_descale shape 匹配关系 | 582 | + // HIF8 per-tensor: v_descale shape must be (1,), 1D |
| 583 | + if (qfaInfo.quantMode == QfaQuantMode::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32) { | ||
| 584 | + return CheckShapeEqual(*shape, {1}, V_DESCALE_NAME, qfaInfo.opName); | ||
| 585 | + } | ||
| 586 | + | ||
| 577 | if (CheckVDescaleShapeMxFp8(qfaInfo) != ge::GRAPH_SUCCESS || | 587 | if (CheckVDescaleShapeMxFp8(qfaInfo) != ge::GRAPH_SUCCESS || |
| 578 | CheckVDescaleShapeGqaFp8(qfaInfo) != ge::GRAPH_SUCCESS) { | 588 | CheckVDescaleShapeGqaFp8(qfaInfo) != ge::GRAPH_SUCCESS) { |
| 579 | return ge::GRAPH_FAILED; | 589 | return ge::GRAPH_FAILED; |
| @@ -614,9 +624,11 @@ ge::graphStatus QuantChecker::CheckDescaleDtype(const QfaTilingInfo &qfaInfo) co | |||
| 614 | // 文档约束(一致性校验): | 624 | // 文档约束(一致性校验): |
| 615 | // MxFP8 场景下, q/k/v descale 的 tensor_type 仅支持 FLOAT8_E8M0 | 625 | // MxFP8 场景下, q/k/v descale 的 tensor_type 仅支持 FLOAT8_E8M0 |
| 616 | // GQA_FP8_FULLQUANT 场景下, q/k/v descale 的 tensor_type 仅支持 FLOAT32 | 626 | // GQA_FP8_FULLQUANT 场景下, q/k/v descale 的 tensor_type 仅支持 FLOAT32 |
| 627 | + // HIF8 场景下, q/k/v descale 的 tensor_type 仅支持 FLOAT32 | ||
| 617 | if (qfaInfo.quantMode != QfaQuantMode::A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32 && | 628 | if (qfaInfo.quantMode != QfaQuantMode::A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32 && |
| 618 | qfaInfo.quantMode != | 629 | qfaInfo.quantMode != |
| 619 | - QfaQuantMode::A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32) { | 630 | + QfaQuantMode::A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32 && |
| 631 | + qfaInfo.quantMode != QfaQuantMode::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32) { | ||
| 620 | return ge::GRAPH_SUCCESS; | 632 | return ge::GRAPH_SUCCESS; |
| 621 | } | 633 | } |
| 622 | 634 | ||
| @@ -661,18 +673,28 @@ ge::graphStatus QuantChecker::CheckDescaleDtype(const QfaTilingInfo &qfaInfo) co | |||
| 661 | 673 | ||
| 662 | namespace { | 674 | namespace { |
| 663 | struct QfaLayoutConstraintConfig { | 675 | struct QfaLayoutConstraintConfig { |
| 676 | + std::vector<QfaLayout> supportedQLayouts; | ||
| 664 | std::vector<QfaLayout> supportedKvLayouts; | 677 | std::vector<QfaLayout> supportedKvLayouts; |
| 665 | std::vector<QfaLayout> supportedOutLayouts; | 678 | std::vector<QfaLayout> supportedOutLayouts; |
| 666 | std::vector<QfaLayout> supportedQDescaleLayouts; | 679 | std::vector<QfaLayout> supportedQDescaleLayouts; |
| 680 | + bool requireLayoutConsistent; | ||
| 667 | }; | 681 | }; |
| 668 | 682 | ||
| 669 | const std::map<QfaQuantMode, QfaLayoutConstraintConfig> QFA_LAYOUT_CONSTRAINT_TABLE = { | 683 | const std::map<QfaQuantMode, QfaLayoutConstraintConfig> QFA_LAYOUT_CONSTRAINT_TABLE = { |
| 670 | {QfaQuantMode::A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32, | 684 | {QfaQuantMode::A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32, |
| 671 | - {{QfaLayout::TND, QfaLayout::PA_BBND, QfaLayout::PA_BNBD, QfaLayout::PA_NZ}, | 685 | + {{QfaLayout::TND}, |
| 686 | + {QfaLayout::TND, QfaLayout::PA_BBND, QfaLayout::PA_BNBD, QfaLayout::PA_NZ}, | ||
| 672 | {QfaLayout::TND}, | 687 | {QfaLayout::TND}, |
| 673 | - {QfaLayout::TND, QfaLayout::N2TGD}}}, | 688 | + {QfaLayout::TND, QfaLayout::N2TGD}, |
| 689 | + false}}, | ||
| 674 | {QfaQuantMode::A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32, | 690 | {QfaQuantMode::A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32, |
| 675 | - {{QfaLayout::PA_BNBD}, {QfaLayout::TND}, {QfaLayout::NT}}}, | 691 | + {{QfaLayout::TND}, {QfaLayout::PA_BNBD}, {QfaLayout::TND}, {QfaLayout::NT}, false}}, |
| 692 | + {QfaQuantMode::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32, | ||
| 693 | + {{QfaLayout::TND, QfaLayout::BSND, QfaLayout::BNSD}, | ||
| 694 | + {QfaLayout::TND, QfaLayout::BSND, QfaLayout::BNSD}, | ||
| 695 | + {QfaLayout::TND, QfaLayout::BSND, QfaLayout::BNSD}, | ||
| 696 | + {QfaLayout::BSND}, | ||
| 697 | + true}}, | ||
| 676 | }; | 698 | }; |
| 677 | } // namespace | 699 | } // namespace |
| 678 | 700 | ||
| @@ -682,7 +704,7 @@ ge::graphStatus QuantChecker::CheckLayoutConstraint(const QfaTilingInfo &qfaInfo | |||
| 682 | OP_CHECK_IF(it == QFA_LAYOUT_CONSTRAINT_TABLE.end(), | 704 | OP_CHECK_IF(it == QFA_LAYOUT_CONSTRAINT_TABLE.end(), |
| 683 | OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(qfaInfo.opName, "quant_mode", | 705 | OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(qfaInfo.opName, "quant_mode", |
| 684 | std::to_string(static_cast<uint32_t>(qfaInfo.quantMode)).c_str(), | 706 | std::to_string(static_cast<uint32_t>(qfaInfo.quantMode)).c_str(), |
| 685 | - "The value of quant_mode must be 1 or 6"), | 707 | + "The value of quant_mode must be 1 or 6 or 0"), |
| 686 | return ge::GRAPH_FAILED); | 708 | return ge::GRAPH_FAILED); |
| 687 | 709 | ||
| 688 | const auto &config = it->second; | 710 | const auto &config = it->second; |
| @@ -690,6 +712,12 @@ ge::graphStatus QuantChecker::CheckLayoutConstraint(const QfaTilingInfo &qfaInfo | |||
| 690 | const std::string quantModeStr = std::to_string(static_cast<uint32_t>(qfaInfo.quantMode)) + " (" + | 712 | const std::string quantModeStr = std::to_string(static_cast<uint32_t>(qfaInfo.quantMode)) + " (" + |
| 691 | QfaQuantModeToSerialString(qfaInfo.quantMode) + ")"; | 713 | QfaQuantModeToSerialString(qfaInfo.quantMode) + ")"; |
| 692 | 714 | ||
| 715 | + OP_CHECK_IF(std::find(config.supportedQLayouts.begin(), config.supportedQLayouts.end(), qfaInfo.qLayout) == | ||
| 716 | + config.supportedQLayouts.end(), | ||
| 717 | + OP_LOGE(qfaInfo.opName, "When quant_mode is %s, layout_q must be in supported list, but got %s", | ||
| 718 | + quantModeStr.c_str(), qLayoutStr.c_str()), | ||
| 719 | + return ge::GRAPH_FAILED); | ||
| 720 | + | ||
| 693 | OP_CHECK_IF(std::find(config.supportedKvLayouts.begin(), config.supportedKvLayouts.end(), qfaInfo.kvLayout) == | 721 | OP_CHECK_IF(std::find(config.supportedKvLayouts.begin(), config.supportedKvLayouts.end(), qfaInfo.kvLayout) == |
| 694 | config.supportedKvLayouts.end(), | 722 | config.supportedKvLayouts.end(), |
| 695 | OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( | 723 | OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( |
| @@ -717,6 +745,16 @@ ge::graphStatus QuantChecker::CheckLayoutConstraint(const QfaTilingInfo &qfaInfo | |||
| 717 | .c_str()), | 745 | .c_str()), |
| 718 | return ge::GRAPH_FAILED); | 746 | return ge::GRAPH_FAILED); |
| 719 | 747 | ||
| 748 | + if (config.requireLayoutConsistent) { | ||
| 749 | + OP_CHECK_IF(qfaInfo.qLayout != qfaInfo.kvLayout || qfaInfo.qLayout != qfaInfo.outLayout, | ||
| 750 | + OP_LOGE(qfaInfo.opName, | ||
| 751 | + "When quant_mode is %s, layout_q, layout_kv and layout_out must be the same, " | ||
| 752 | + "but got layout_q=%s, layout_kv=%s, layout_out=%s", | ||
| 753 | + quantModeStr.c_str(), qLayoutStr.c_str(), QfaLayoutToSerialString(qfaInfo.kvLayout).c_str(), | ||
| 754 | + QfaLayoutToSerialString(qfaInfo.outLayout).c_str()), | ||
| 755 | + return ge::GRAPH_FAILED); | ||
| 756 | + } | ||
| 757 | + | ||
| 720 | return ge::GRAPH_SUCCESS; | 758 | return ge::GRAPH_SUCCESS; |
| 721 | } | 759 | } |
| 722 | 760 | ||
| @@ -738,11 +776,17 @@ void QuantChecker::SetQfaShapeCompare(const QfaTilingInfo &qfaInfo) | |||
| 738 | 776 | ||
| 739 | ge::graphStatus QuantChecker::CheckQueryShape(const QfaTilingInfo &qfaInfo) const | 777 | ge::graphStatus QuantChecker::CheckQueryShape(const QfaTilingInfo &qfaInfo) const |
| 740 | { | 778 | { |
| 741 | - // q: TND -> (Q_T, Q_N, D) | 779 | + // q: TND -> (Q_T, Q_N, D) BSND -> (B, S, Q_N, D) BNSD -> (B, Q_N, S, D) |
| 742 | QfaTilingShapeCompareParam shapeParams; | 780 | QfaTilingShapeCompareParam shapeParams; |
| 743 | - shapeParams.T = qfaInfo.qTSize; | ||
| 744 | shapeParams.N = qfaInfo.n1Size; | 781 | shapeParams.N = qfaInfo.n1Size; |
| 745 | shapeParams.D = qfaInfo.qkHeadDim; | 782 | shapeParams.D = qfaInfo.qkHeadDim; |
| 783 | + if (qfaInfo.quantMode == QfaQuantMode::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32 && | ||
| 784 | + (qfaInfo.qLayout == QfaLayout::BSND || qfaInfo.qLayout == QfaLayout::BNSD)) { | ||
| 785 | + shapeParams.B = qfaInfo.bSize; | ||
| 786 | + shapeParams.S = qfaInfo.s1Size; | ||
| 787 | + } else { | ||
| 788 | + shapeParams.T = qfaInfo.qTSize; | ||
| 789 | + } | ||
| 746 | return queryShapeCmp_->CompareShape(shapeParams, __func__); | 790 | return queryShapeCmp_->CompareShape(shapeParams, __func__); |
| 747 | } | 791 | } |
| 748 | 792 | ||
| @@ -760,6 +804,10 @@ ge::graphStatus QuantChecker::CheckKVShape(const QfaTilingInfo &qfaInfo) const | |||
| 760 | qfaInfo.kvLayout == QfaLayout::PA_NZ) { | 804 | qfaInfo.kvLayout == QfaLayout::PA_NZ) { |
| 761 | shapeParams.Bn = qfaInfo.totalBlockNum; | 805 | shapeParams.Bn = qfaInfo.totalBlockNum; |
| 762 | shapeParams.Bs = qfaInfo.blockSize; | 806 | shapeParams.Bs = qfaInfo.blockSize; |
| 807 | + } else if (qfaInfo.quantMode == QfaQuantMode::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32 && | ||
| 808 | + (qfaInfo.kvLayout == QfaLayout::BSND || qfaInfo.kvLayout == QfaLayout::BNSD)) { | ||
| 809 | + shapeParams.B = qfaInfo.bSize; | ||
| 810 | + shapeParams.S = qfaInfo.s2Size; | ||
| 763 | } | 811 | } |
| 764 | // PA_NZ k/v: D0=32, shape 为 (Bn, KV_N, D/32, Bs, 32) | 812 | // PA_NZ k/v: D0=32, shape 为 (Bn, KV_N, D/32, Bs, 32) |
| 765 | if (qfaInfo.kvLayout == QfaLayout::PA_NZ) { | 813 | if (qfaInfo.kvLayout == QfaLayout::PA_NZ) { |
| @@ -780,11 +828,18 @@ ge::graphStatus QuantChecker::CheckKVShape(const QfaTilingInfo &qfaInfo) const | |||
| 780 | 828 | ||
| 781 | ge::graphStatus QuantChecker::CheckAttnOutShape(const QfaTilingInfo &qfaInfo) const | 829 | ge::graphStatus QuantChecker::CheckAttnOutShape(const QfaTilingInfo &qfaInfo) const |
| 782 | { | 830 | { |
| 783 | - // attn_out: TND -> (Q_T, Q_N, D),D 取 vHeadDim(反量化后输出 dtype 为 BF16) | 831 | + // attn_out: TND -> (Q_T, Q_N, D) BSND -> (B, S, Q_N, D) BNSD -> (B, Q_N, S, D) |
| 832 | + // D 取 vHeadDim(反量化后输出 dtype 为 BF16) | ||
| 784 | QfaTilingShapeCompareParam shapeParams; | 833 | QfaTilingShapeCompareParam shapeParams; |
| 785 | - shapeParams.T = qfaInfo.qTSize; | ||
| 786 | shapeParams.N = qfaInfo.n1Size; | 834 | shapeParams.N = qfaInfo.n1Size; |
| 787 | shapeParams.D = qfaInfo.vHeadDim; | 835 | shapeParams.D = qfaInfo.vHeadDim; |
| 836 | + if (qfaInfo.quantMode == QfaQuantMode::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32 && | ||
| 837 | + (qfaInfo.outLayout == QfaLayout::BSND || qfaInfo.outLayout == QfaLayout::BNSD)) { | ||
| 838 | + shapeParams.B = qfaInfo.bSize; | ||
| 839 | + shapeParams.S = qfaInfo.s1Size; | ||
| 840 | + } else { | ||
| 841 | + shapeParams.T = qfaInfo.qTSize; | ||
| 842 | + } | ||
| 788 | return attnOutShapeCmp_->CompareShape(shapeParams, __func__); | 843 | return attnOutShapeCmp_->CompareShape(shapeParams, __func__); |
| 789 | } | 844 | } |
| 790 | 845 | ||
| @@ -800,12 +855,34 @@ ge::graphStatus QuantChecker::CheckShapeMatch(const QfaTilingInfo &qfaInfo) | |||
| 800 | 855 | ||
| 801 | ge::graphStatus QuantChecker::CheckFeature(const QfaTilingInfo &qfaInfo) | 856 | ge::graphStatus QuantChecker::CheckFeature(const QfaTilingInfo &qfaInfo) |
| 802 | { | 857 | { |
| 803 | - // 文档"特性交叉校验"列(rowspan=5)包含三项: | 858 | + // 文档"特性交叉校验"列(rowspan=5)包含: |
| 804 | - // 1. Layout 校验(layout 匹配关系表, 含 layout_q_descale) | 859 | + // 1. q/k/v dtype 与 quant_mode 精确匹配 |
| 805 | - // 2. q/k/v/attn_out shape 校验(shape 匹配关系表) | 860 | + // 2. q/out ShapeDim 与 quant_mode 精确匹配 |
| 861 | + // 3. 非连续 Tensor 支持 | ||
| 862 | + // 4. Layout 校验(layout 匹配关系表, 含 layout_q_descale) | ||
| 863 | + // 5. q/k/v/attn_out shape 校验(shape 匹配关系表) | ||
| 864 | + if (CheckQkvDtype(qfaInfo) != ge::GRAPH_SUCCESS) { | ||
| 865 | + return ge::GRAPH_FAILED; | ||
| 866 | + } | ||
| 867 | + if (CheckQkvShapeDim(qfaInfo) != ge::GRAPH_SUCCESS) { | ||
| 868 | + return ge::GRAPH_FAILED; | ||
| 869 | + } | ||
| 806 | if (CheckLayoutConstraint(qfaInfo) != ge::GRAPH_SUCCESS) { | 870 | if (CheckLayoutConstraint(qfaInfo) != ge::GRAPH_SUCCESS) { |
| 807 | return ge::GRAPH_FAILED; | 871 | return ge::GRAPH_FAILED; |
| 808 | } | 872 | } |
| 873 | + if (qfaInfo.quantMode == QfaQuantMode::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32) { | ||
| 874 | + constexpr int64_t HIF8_HEAD_DIM = 128; | ||
| 875 | + OP_CHECK_IF( | ||
| 876 | + qfaInfo.qkHeadDim != HIF8_HEAD_DIM, | ||
| 877 | + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(qfaInfo.opName, "head_dim", std::to_string(qfaInfo.qkHeadDim).c_str(), | ||
| 878 | + "HIF8 only supports head_dim = 128"), | ||
| 879 | + return ge::GRAPH_FAILED); | ||
| 880 | + OP_CHECK_IF(qfaInfo.vHeadDim != HIF8_HEAD_DIM, | ||
| 881 | + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(qfaInfo.opName, "head_dim_v", | ||
| 882 | + std::to_string(qfaInfo.vHeadDim).c_str(), | ||
| 883 | + "HIF8 only supports head_dim_v = 128"), | ||
| 884 | + return ge::GRAPH_FAILED); | ||
| 885 | + } | ||
| 809 | if (CheckShapeMatch(qfaInfo) != ge::GRAPH_SUCCESS) { | 886 | if (CheckShapeMatch(qfaInfo) != ge::GRAPH_SUCCESS) { |
| 810 | return ge::GRAPH_FAILED; | 887 | return ge::GRAPH_FAILED; |
| 811 | } | 888 | } |
| @@ -854,5 +931,87 @@ ge::graphStatus QuantChecker::CheckInputAxisFullquant(const QfaTilingInfo &qfaIn | |||
| 854 | return ge::GRAPH_SUCCESS; | 931 | return ge::GRAPH_SUCCESS; |
| 855 | } | 932 | } |
| 856 | 933 | ||
| 934 | +// ============================================================================ | ||
| 935 | +// Feature — q/k/v dtype 与 quant_mode 精确匹配校验 (跨参数组特性交叉校验) | ||
| 936 | +// MXFP8/FP8: q/k/v dtype 必须为 FLOAT8_E4M3FN | ||
| 937 | +// HIF8: q/k/v dtype 必须为 HIFLOAT8 | ||
| 938 | +// ============================================================================ | ||
| 939 | + | ||
| 940 | +ge::graphStatus QuantChecker::CheckQkvDtype(const QfaTilingInfo &qfaInfo) const | ||
| 941 | +{ | ||
| 942 | + ge::DataType expectedDtype; | ||
| 943 | + std::string expectedDtypeStr; | ||
| 944 | + if (qfaInfo.quantMode == QfaQuantMode::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32) { | ||
| 945 | + expectedDtype = ge::DT_HIFLOAT8; | ||
| 946 | + expectedDtypeStr = "HIFLOAT8"; | ||
| 947 | + } else { | ||
| 948 | + expectedDtype = ge::DT_FLOAT8_E4M3FN; | ||
| 949 | + expectedDtypeStr = "FLOAT8_E4M3FN"; | ||
| 950 | + } | ||
| 951 | + | ||
| 952 | + const auto checkDtype = [&](const gert::CompileTimeTensorDesc *desc, const std::string &name) -> ge::graphStatus { | ||
| 953 | + if (desc == nullptr) { | ||
| 954 | + return ge::GRAPH_SUCCESS; | ||
| 955 | + } | ||
| 956 | + OP_CHECK_IF(desc->GetDataType() != expectedDtype, | ||
| 957 | + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( | ||
| 958 | + qfaInfo.opName, name.c_str(), DataTypeToSerialString(desc->GetDataType()).c_str(), | ||
| 959 | + ("The dtype of " + name + " must be " + expectedDtypeStr + " when quant_mode is " + | ||
| 960 | + std::to_string(static_cast<uint32_t>(qfaInfo.quantMode)) + " (" + | ||
| 961 | + QfaQuantModeToSerialString(qfaInfo.quantMode) + ")") | ||
| 962 | + .c_str()), | ||
| 963 | + return ge::GRAPH_FAILED); | ||
| 964 | + return ge::GRAPH_SUCCESS; | ||
| 965 | + }; | ||
| 966 | + | ||
| 967 | + if (checkDtype(qfaInfo.opParamInfo.query.desc, QUERY_NAME) != ge::GRAPH_SUCCESS || | ||
| 968 | + checkDtype(qfaInfo.opParamInfo.key.desc, KEY_NAME) != ge::GRAPH_SUCCESS || | ||
| 969 | + checkDtype(qfaInfo.opParamInfo.value.desc, VALUE_NAME) != ge::GRAPH_SUCCESS) { | ||
| 970 | + return ge::GRAPH_FAILED; | ||
| 971 | + } | ||
| 972 | + return ge::GRAPH_SUCCESS; | ||
| 973 | +} | ||
| 974 | + | ||
| 975 | +// ============================================================================ | ||
| 976 | +// Feature — q/out ShapeDim 与 quant_mode 精确匹配校验 (跨参数组特性交叉校验) | ||
| 977 | +// MXFP8/FP8: q/attn_out shape dim 仅支持 3D | ||
| 978 | +// HIF8: q/attn_out shape dim 支持 3D/4D | ||
| 979 | +// ============================================================================ | ||
| 980 | + | ||
| 981 | +ge::graphStatus QuantChecker::CheckQkvShapeDim(const QfaTilingInfo &qfaInfo) const | ||
| 982 | +{ | ||
| 983 | + std::vector<uint32_t> supportedDims; | ||
| 984 | + std::string dimStr; | ||
| 985 | + if (qfaInfo.quantMode == QfaQuantMode::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32) { | ||
| 986 | + supportedDims = {DIM_NUM_3, DIM_NUM_4}; | ||
| 987 | + dimStr = "3D/4D"; | ||
| 988 | + } else { | ||
| 989 | + supportedDims = {DIM_NUM_3}; | ||
| 990 | + dimStr = "3D"; | ||
| 991 | + } | ||
| 992 | + | ||
| 993 | + const auto checkDim = [&](const gert::StorageShape *shape, const std::string &name) -> ge::graphStatus { | ||
| 994 | + if (shape == nullptr) { | ||
| 995 | + return ge::GRAPH_SUCCESS; | ||
| 996 | + } | ||
| 997 | + uint32_t dimNum = shape->GetStorageShape().GetDimNum(); | ||
| 998 | + OP_CHECK_IF(std::find(supportedDims.begin(), supportedDims.end(), dimNum) == supportedDims.end(), | ||
| 999 | + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( | ||
| 1000 | + qfaInfo.opName, name.c_str(), (std::to_string(dimNum) + "D").c_str(), | ||
| 1001 | + ("The shape dim of " + name + " must be " + dimStr + " when quant_mode is " + | ||
| 1002 | + std::to_string(static_cast<uint32_t>(qfaInfo.quantMode)) + " (" + | ||
| 1003 | + QfaQuantModeToSerialString(qfaInfo.quantMode) + ")") | ||
| 1004 | + .c_str()), | ||
| 1005 | + return ge::GRAPH_FAILED); | ||
| 1006 | + return ge::GRAPH_SUCCESS; | ||
| 1007 | + }; | ||
| 1008 | + | ||
| 1009 | + if (checkDim(qfaInfo.opParamInfo.query.shape, QUERY_NAME) != ge::GRAPH_SUCCESS || | ||
| 1010 | + checkDim(qfaInfo.opParamInfo.attnOut.shape, ATTN_OUT_NAME) != ge::GRAPH_SUCCESS) { | ||
| 1011 | + return ge::GRAPH_FAILED; | ||
| 1012 | + } | ||
| 1013 | + return ge::GRAPH_SUCCESS; | ||
| 1014 | +} | ||
| 1015 | + | ||
| 857 | } // namespace quant_flash_attn | 1016 | } // namespace quant_flash_attn |
| 858 | } // namespace optiling | 1017 | } // namespace optiling |
| @@ -74,6 +74,12 @@ private: | |||
| 74 | // 各 batch 实际 KV 序列长度按 64 向上取整后累加,即 Σ ceil(cu_seqlens_kv[b+1]-cu_seqlens_kv[b], 64) | 74 | // 各 batch 实际 KV 序列长度按 64 向上取整后累加,即 Σ ceil(cu_seqlens_kv[b+1]-cu_seqlens_kv[b], 64) |
| 75 | int64_t CalcVDescaleTndDim0(const QfaTilingInfo &qfaInfo) const; | 75 | int64_t CalcVDescaleTndDim0(const QfaTilingInfo &qfaInfo) const; |
| 76 | 76 | ||
| 77 | + // --- Feature: q/k/v dtype 与 quant_mode 精确匹配校验 --- | ||
| 78 | + ge::graphStatus CheckQkvDtype(const QfaTilingInfo &qfaInfo) const; | ||
| 79 | + | ||
| 80 | + // --- Feature: q/out ShapeDim 与 quant_mode 精确匹配校验 --- | ||
| 81 | + ge::graphStatus CheckQkvShapeDim(const QfaTilingInfo &qfaInfo) const; | ||
| 82 | + | ||
| 77 | // --- Feature: layout 匹配关系校验 (文档: layout匹配关系表) --- | 83 | // --- Feature: layout 匹配关系校验 (文档: layout匹配关系表) --- |
| 78 | // MxFP8: layout_q=TND, layout_kv∈{TND,PA_BBND,PA_BNBD,PA_NZ}, layout_out=TND, layout_q_descale∈{TND,N2TGD} | 84 | // MxFP8: layout_q=TND, layout_kv∈{TND,PA_BBND,PA_BNBD,PA_NZ}, layout_out=TND, layout_q_descale∈{TND,N2TGD} |
| 79 | ge::graphStatus CheckLayoutConstraint(const QfaTilingInfo &qfaInfo) const; | 85 | ge::graphStatus CheckLayoutConstraint(const QfaTilingInfo &qfaInfo) const; |
| @@ -53,10 +53,13 @@ inline void AdjustSinnerAndSouter(uint32_t vHeadDim, int64_t maxSeqQ, int64_t ma | |||
| 53 | maxSeqKv = MAX_SEQ_LEN_DEFAULT; | 53 | maxSeqKv = MAX_SEQ_LEN_DEFAULT; |
| 54 | } | 54 | } |
| 55 | if (vHeadDim == DSIZE_256) { | 55 | if (vHeadDim == DSIZE_256) { |
| 56 | - sOuterFactor = SOUTER_64; // mxfp8 D=256 时基本块为128*256 | 56 | + sOuterFactor = SOUTER_64; |
| 57 | + sInnerFactor = SINNER_256; | ||
| 58 | + } else if (quantMode == 0) { // QFA_HIF8_FP32 | ||
| 59 | + sOuterFactor = SOUTER_64; | ||
| 57 | sInnerFactor = SINNER_256; | 60 | sInnerFactor = SINNER_256; |
| 58 | } else { | 61 | } else { |
| 59 | - sOuterFactor = SOUTER_64; // mxfp8 D=128 时基本块为128*512 | 62 | + sOuterFactor = SOUTER_64; |
| 60 | sInnerFactor = SINNER_512; | 63 | sInnerFactor = SINNER_512; |
| 61 | } | 64 | } |
| 62 | } | 65 | } |
| @@ -32,7 +32,7 @@ std::string QfaLayoutToSerialString(QfaLayout layout) | |||
| 32 | return "UNKNOWN"; | 32 | return "UNKNOWN"; |
| 33 | } | 33 | } |
| 34 | 34 | ||
| 35 | -static const std::string QFA_AXIS_SERIAL_STRINGS[] = {"B", "S", "N", "D", "H", "T", "D1", | 35 | +static const std::string QFA_AXIS_SERIAL_STRINGS[] = {"B", "S", "N", "D", "H", "T", "D1", |
| 36 | "D0", "S1", "S2", "Bn", "Bs", "CONST"}; | 36 | "D0", "S1", "S2", "Bn", "Bs", "CONST"}; |
| 37 | 37 | ||
| 38 | std::string QfaAxisToSerialString(QfaAxis axis) | 38 | std::string QfaAxisToSerialString(QfaAxis axis) |
| @@ -48,7 +48,8 @@ std::string QfaQuantModeToSerialString(QfaQuantMode qfaQuantMode) | |||
| 48 | {QfaQuantMode::A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32, | 48 | {QfaQuantMode::A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32, |
| 49 | "A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32"}, | 49 | "A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32"}, |
| 50 | {QfaQuantMode::A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32, | 50 | {QfaQuantMode::A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32, |
| 51 | - "A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32"}}; | 51 | + "A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32"}, |
| 52 | + {QfaQuantMode::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32, "A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32"}}; | ||
| 52 | 53 | ||
| 53 | if (quantMode2Str.find(qfaQuantMode) != quantMode2Str.end()) { | 54 | if (quantMode2Str.find(qfaQuantMode) != quantMode2Str.end()) { |
| 54 | return quantMode2Str.at(qfaQuantMode); | 55 | return quantMode2Str.at(qfaQuantMode); |
| @@ -147,7 +147,8 @@ enum class QfaAxis : uint32_t { | |||
| 147 | 147 | ||
| 148 | enum class QfaQuantMode : uint32_t { | 148 | enum class QfaQuantMode : uint32_t { |
| 149 | A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32 = 1, | 149 | A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32 = 1, |
| 150 | - A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32 = 6 | 150 | + A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32 = 6, |
| 151 | + A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32 = 0 | ||
| 151 | }; | 152 | }; |
| 152 | 153 | ||
| 153 | enum class KvStorageMode : uint32_t { | 154 | enum class KvStorageMode : uint32_t { |
| @@ -363,9 +364,9 @@ const std::map<ge::DataType, std::string> DATATYPE_TO_STRING_MAP = {{ge::DT_UNDE | |||
| 363 | {ge::DT_FLOAT4_E2M1, "DT_FLOAT4_E2M1"}}; | 364 | {ge::DT_FLOAT4_E2M1, "DT_FLOAT4_E2M1"}}; |
| 364 | 365 | ||
| 365 | const std::map<std::string, std::vector<ge::DataType>> DTYPE_SUPPORT_MAP = { | 366 | const std::map<std::string, std::vector<ge::DataType>> DTYPE_SUPPORT_MAP = { |
| 366 | - {QUERY_NAME, {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT8_E4M3FN}}, | 367 | + {QUERY_NAME, {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8}}, |
| 367 | - {KEY_NAME, {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT8_E4M3FN}}, | 368 | + {KEY_NAME, {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8}}, |
| 368 | - {VALUE_NAME, {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT8_E4M3FN}}, | 369 | + {VALUE_NAME, {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8}}, |
| 369 | {Q_DESCALE_NAME, {ge::DT_FLOAT, ge::DT_BF16, ge::DT_FLOAT8_E8M0}}, | 370 | {Q_DESCALE_NAME, {ge::DT_FLOAT, ge::DT_BF16, ge::DT_FLOAT8_E8M0}}, |
| 370 | {K_DESCALE_NAME, {ge::DT_FLOAT, ge::DT_BF16, ge::DT_FLOAT8_E8M0}}, | 371 | {K_DESCALE_NAME, {ge::DT_FLOAT, ge::DT_BF16, ge::DT_FLOAT8_E8M0}}, |
| 371 | {V_DESCALE_NAME, {ge::DT_FLOAT, ge::DT_BF16, ge::DT_FLOAT8_E8M0}}, | 372 | {V_DESCALE_NAME, {ge::DT_FLOAT, ge::DT_BF16, ge::DT_FLOAT8_E8M0}}, |
| @@ -272,13 +272,15 @@ ge::graphStatus QfaInfoParser::GetQuantMode() | |||
| 272 | if (quantModeVal != static_cast<int64_t>(QM::A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32) && | 272 | if (quantModeVal != static_cast<int64_t>(QM::A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32) && |
| 273 | quantModeVal != | 273 | quantModeVal != |
| 274 | static_cast<int64_t>( | 274 | static_cast<int64_t>( |
| 275 | - QM::A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32)) { | 275 | + QM::A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32) && |
| 276 | + quantModeVal != static_cast<int64_t>(QM::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32)) { | ||
| 276 | OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "quant_mode", std::to_string(quantModeVal).c_str(), | 277 | OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "quant_mode", std::to_string(quantModeVal).c_str(), |
| 277 | "quant_mode must be 1 " | 278 | "quant_mode must be 1 " |
| 278 | "(A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32) or " | 279 | "(A8C8_QKV_MXFP8_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32) or " |
| 279 | "6 (A8C8_QK_FP8_" | 280 | "6 (A8C8_QK_FP8_" |
| 280 | "E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_" | 281 | "E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_" |
| 281 | - "P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32)"); | 282 | + "P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32) or " |
| 283 | + "0 (A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32)"); | ||
| 282 | return ge::GRAPH_FAILED; | 284 | return ge::GRAPH_FAILED; |
| 283 | } | 285 | } |
| 284 | quantMode_ = static_cast<QfaQuantMode>(quantModeVal); | 286 | quantMode_ = static_cast<QfaQuantMode>(quantModeVal); |
| @@ -632,6 +634,11 @@ ge::graphStatus QfaInfoParser::ParseAxisInfo() | |||
| 632 | return ge::GRAPH_FAILED; | 634 | return ge::GRAPH_FAILED; |
| 633 | } | 635 | } |
| 634 | 636 | ||
| 637 | + // HIF8 per-tensor: q_descale is 1D with shape (1,), skip MXFP8 dim check | ||
| 638 | + if (quantMode_ == QfaQuantMode::A8C8_QKV_HIF8_P_PER_TENSOR_SOFTMAX_FP32) { | ||
不应该再HIF8时熔断,如果hif8时也传入了q_descale,难道就不需要校验? ![]() ![]() | |||
| 639 | + return ge::GRAPH_SUCCESS; | ||
| 640 | + } | ||
| 641 | + | ||
| 635 | uint32_t qDescaleDimNum = opParamInfo_.qDescale.shape->GetStorageShape().GetDimNum(); | 642 | uint32_t qDescaleDimNum = opParamInfo_.qDescale.shape->GetStorageShape().GetDimNum(); |
| 636 | using QM = QfaQuantMode; | 643 | using QM = QfaQuantMode; |
| 637 | if (quantMode_ == QM::A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32) { | 644 | if (quantMode_ == QM::A8C8_QK_FP8_E4M3_PER_TOKEN_HEAD_V_FP8_E4M3_PER_HEAD_P_FP8_E4M3_PER_TENSOR_SOFTMAX_FP32) { |
| @@ -26,32 +26,32 @@ public: | |||
| 26 | { | 26 | { |
| 27 | this->Input("q") | 27 | this->Input("q") |
| 28 | .ParamType(REQUIRED) | 28 | .ParamType(REQUIRED) |
| 29 | - .DataType({ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN}) | 29 | + .DataType({ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8}) |
| 30 | .FormatList({ge::FORMAT_ND}) | 30 | .FormatList({ge::FORMAT_ND}) |
| 31 | .AutoContiguous(); | 31 | .AutoContiguous(); |
| 32 | this->Input("k") | 32 | this->Input("k") |
| 33 | .ParamType(REQUIRED) | 33 | .ParamType(REQUIRED) |
| 34 | - .DataType({ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN}) | 34 | + .DataType({ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8}) |
| 35 | .FormatList({ge::FORMAT_ND}) | 35 | .FormatList({ge::FORMAT_ND}) |
| 36 | .IgnoreContiguous(); | 36 | .IgnoreContiguous(); |
| 37 | this->Input("v") | 37 | this->Input("v") |
| 38 | .ParamType(REQUIRED) | 38 | .ParamType(REQUIRED) |
| 39 | - .DataType({ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN}) | 39 | + .DataType({ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8}) |
| 40 | .FormatList({ge::FORMAT_ND}) | 40 | .FormatList({ge::FORMAT_ND}) |
| 41 | .IgnoreContiguous(); | 41 | .IgnoreContiguous(); |
| 42 | this->Input("q_descale") | 42 | this->Input("q_descale") |
| 43 | .ParamType(REQUIRED) | 43 | .ParamType(REQUIRED) |
| 44 | - .DataType({ge::DT_FLOAT8_E8M0, ge::DT_FLOAT}) | 44 | + .DataType({ge::DT_FLOAT8_E8M0, ge::DT_FLOAT, ge::DT_FLOAT}) |
| 45 | .FormatList({ge::FORMAT_ND}) | 45 | .FormatList({ge::FORMAT_ND}) |
| 46 | .AutoContiguous(); | 46 | .AutoContiguous(); |
| 47 | this->Input("k_descale") | 47 | this->Input("k_descale") |
| 48 | .ParamType(REQUIRED) | 48 | .ParamType(REQUIRED) |
| 49 | - .DataType({ge::DT_FLOAT8_E8M0, ge::DT_FLOAT}) | 49 | + .DataType({ge::DT_FLOAT8_E8M0, ge::DT_FLOAT, ge::DT_FLOAT}) |
| 50 | .FormatList({ge::FORMAT_ND}) | 50 | .FormatList({ge::FORMAT_ND}) |
| 51 | .IgnoreContiguous(); | 51 | .IgnoreContiguous(); |
| 52 | this->Input("v_descale") | 52 | this->Input("v_descale") |
| 53 | .ParamType(REQUIRED) | 53 | .ParamType(REQUIRED) |
| 54 | - .DataType({ge::DT_FLOAT8_E8M0, ge::DT_FLOAT}) | 54 | + .DataType({ge::DT_FLOAT8_E8M0, ge::DT_FLOAT, ge::DT_FLOAT}) |
| 55 | .FormatList({ge::FORMAT_ND}) | 55 | .FormatList({ge::FORMAT_ND}) |
| 56 | .IgnoreContiguous(); | 56 | .IgnoreContiguous(); |
| 57 | this->Input("block_table") | 57 | this->Input("block_table") |
| @@ -101,7 +101,7 @@ public: | |||
| 101 | .AutoContiguous(); | 101 | .AutoContiguous(); |
| 102 | this->Output("attn_out") | 102 | this->Output("attn_out") |
| 103 | .ParamType(REQUIRED) | 103 | .ParamType(REQUIRED) |
| 104 | - .DataType({ge::DT_BF16, ge::DT_BF16}) | 104 | + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16}) |
| 105 | .FormatList({ge::FORMAT_ND}) | 105 | .FormatList({ge::FORMAT_ND}) |
| 106 | .AutoContiguous(); | 106 | .AutoContiguous(); |
| 107 | this->Output("softmax_lse") | 107 | this->Output("softmax_lse") |
| @@ -109,42 +109,18 @@ public: | |||
| 109 | .DataTypeList({ge::DT_FLOAT}) | 109 | .DataTypeList({ge::DT_FLOAT}) |
| 110 | .FormatList({ge::FORMAT_ND}) | 110 | .FormatList({ge::FORMAT_ND}) |
| 111 | .AutoContiguous(); | 111 | .AutoContiguous(); |
| 112 | - this->Attr("quant_compute_mode") | 112 | + this->Attr("quant_compute_mode").AttrType(REQUIRED).Int(); |
| 113 | - .AttrType(REQUIRED) | 113 | + this->Attr("softmax_scale").AttrType(OPTIONAL).Float(0.0f); |
| 114 | - .Int(); | 114 | + this->Attr("mask_mode").AttrType(OPTIONAL).Int(0); |
| 115 | - this->Attr("softmax_scale") | 115 | + this->Attr("win_left").AttrType(OPTIONAL).Int(-1); |
| 116 | - .AttrType(OPTIONAL) | 116 | + this->Attr("win_right").AttrType(OPTIONAL).Int(-1); |
| 117 | - .Float(0.0f); | 117 | + this->Attr("max_seqlen_q").AttrType(OPTIONAL).Int(-1); |
| 118 | - this->Attr("mask_mode") | 118 | + this->Attr("max_seqlen_kv").AttrType(OPTIONAL).Int(-1); |
| 119 | - .AttrType(OPTIONAL) | 119 | + this->Attr("layout_q").AttrType(OPTIONAL).String("BSND"); |
| 120 | - .Int(0); | 120 | + this->Attr("layout_q_descale").AttrType(OPTIONAL).String("BSND"); |
| 121 | - this->Attr("win_left") | 121 | + this->Attr("layout_kv").AttrType(OPTIONAL).String("BSND"); |
| 122 | - .AttrType(OPTIONAL) | 122 | + this->Attr("layout_out").AttrType(OPTIONAL).String("BSND"); |
| 123 | - .Int(-1); | 123 | + this->Attr("return_softmax_lse").AttrType(OPTIONAL).Bool(false); |
| 124 | - this->Attr("win_right") | ||
| 125 | - .AttrType(OPTIONAL) | ||
| 126 | - .Int(-1); | ||
| 127 | - this->Attr("max_seqlen_q") | ||
| 128 | - .AttrType(OPTIONAL) | ||
| 129 | - .Int(-1); | ||
| 130 | - this->Attr("max_seqlen_kv") | ||
| 131 | - .AttrType(OPTIONAL) | ||
| 132 | - .Int(-1); | ||
| 133 | - this->Attr("layout_q") | ||
| 134 | - .AttrType(OPTIONAL) | ||
| 135 | - .String("BSND"); | ||
| 136 | - this->Attr("layout_q_descale") | ||
| 137 | - .AttrType(OPTIONAL) | ||
| 138 | - .String("BSND"); | ||
| 139 | - this->Attr("layout_kv") | ||
| 140 | - .AttrType(OPTIONAL) | ||
| 141 | - .String("BSND"); | ||
| 142 | - this->Attr("layout_out") | ||
| 143 | - .AttrType(OPTIONAL) | ||
| 144 | - .String("BSND"); | ||
| 145 | - this->Attr("return_softmax_lse") | ||
| 146 | - .AttrType(OPTIONAL) | ||
| 147 | - .Bool(false); | ||
| 148 | 124 | ||
| 149 | OpAICoreConfig aicore_config_95; | 125 | OpAICoreConfig aicore_config_95; |
| 150 | aicore_config_95.DynamicCompileStaticFlag(true) | 126 | aicore_config_95.DynamicCompileStaticFlag(true) |
| @@ -164,10 +164,11 @@ __aicore__ inline void DataCopySoftmaxLseBSNDArch35(GlobalTensor<float> softmaxL | |||
| 164 | uint64_t bN2Offset, uint32_t mOffset, uint32_t dealCount, | 164 | uint64_t bN2Offset, uint32_t mOffset, uint32_t dealCount, |
| 165 | const CONST_INFO_T &constInfo, uint64_t s1LeftPaddingSize = 0) | 165 | const CONST_INFO_T &constInfo, uint64_t s1LeftPaddingSize = 0) |
| 166 | { | 166 | { |
| 167 | - uint32_t startS1Idx = mOffset / constInfo.gSize; | 167 | + // USE_DN时,realGSize=1(G合入N2) |
| 168 | - uint32_t startGIdx = mOffset % constInfo.gSize; | 168 | + uint32_t startS1Idx = mOffset / constInfo.realGSize; |
| 169 | - uint32_t endS1Idx = (mOffset + dealCount - 1) / constInfo.gSize; | 169 | + uint32_t startGIdx = mOffset % constInfo.realGSize; |
| 170 | - uint32_t endGIdx = (mOffset + dealCount - 1) % constInfo.gSize; | 170 | + uint32_t endS1Idx = (mOffset + dealCount - 1) / constInfo.realGSize; |
| 171 | + uint32_t endGIdx = (mOffset + dealCount - 1) % constInfo.realGSize; | ||
| 171 | uint64_t outOffset = 0; | 172 | uint64_t outOffset = 0; |
| 172 | uint64_t ubOffset = 0; | 173 | uint64_t ubOffset = 0; |
| 173 | uint32_t curDealRowCount = 0; | 174 | uint32_t curDealRowCount = 0; |
| @@ -175,7 +176,7 @@ __aicore__ inline void DataCopySoftmaxLseBSNDArch35(GlobalTensor<float> softmaxL | |||
| 175 | for (uint32_t s1Idx = startS1Idx; s1Idx <= endS1Idx; s1Idx++) { | 176 | for (uint32_t s1Idx = startS1Idx; s1Idx <= endS1Idx; s1Idx++) { |
| 176 | outOffset = bN2Offset + startGIdx * constInfo.s1Size + s1Idx + s1LeftPaddingSize; | 177 | outOffset = bN2Offset + startGIdx * constInfo.s1Size + s1Idx + s1LeftPaddingSize; |
| 177 | if (s1Idx != endS1Idx) { | 178 | if (s1Idx != endS1Idx) { |
| 178 | - curDealRowCount = constInfo.gSize - startGIdx; | 179 | + curDealRowCount = constInfo.realGSize - startGIdx; |
| 179 | } else { | 180 | } else { |
| 180 | curDealRowCount = endGIdx + 1 - startGIdx; | 181 | curDealRowCount = endGIdx + 1 - startGIdx; |
| 181 | } | 182 | } |
| @@ -0,0 +1,567 @@ | |||
| 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 quant_flash_attn_block_cube_hif8.h | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | +#ifndef QUANT_FLASH_ATTN_BLOCK_CUBE_HIF8_H_ | ||
| 16 | +#define QUANT_FLASH_ATTN_BLOCK_CUBE_HIF8_H_ | ||
| 17 | +#if __has_include("../../../common/op_kernel/offset_calculator.h") | ||
| 18 | +#include "../../../common/op_kernel/offset_calculator.h" | ||
| 19 | +#include "../../../common/op_kernel/matmul.h" | ||
| 20 | +#include "../../../common/op_kernel/FixpipeOut.h" | ||
| 21 | +#include "../../../common/op_kernel/arch35/infer_flash_attention_comm_arch35.h" | ||
| 22 | +#include "../../../common/op_kernel/arch35/flash_attention_score_common_regbase_arch35.h" | ||
| 23 | +#include "../../../common/op_kernel/arch35/util_regbase.h" | ||
| 24 | +#else | ||
| 25 | +#include "../../common/op_kernel/offset_calculator.h" | ||
| 26 | +#include "../../common/op_kernel/matmul.h" | ||
| 27 | +#include "../../common/op_kernel/FixpipeOut.h" | ||
| 28 | +#include "../../common/op_kernel/arch35/infer_flash_attention_comm_arch35.h" | ||
| 29 | +#include "../../common/op_kernel/arch35/flash_attention_score_common_regbase_arch35.h" | ||
| 30 | +#include "../../common/op_kernel/arch35/util_regbase.h" | ||
| 31 | +#endif | ||
| 32 | +#include "kernel_operator_list_tensor_intf.h" | ||
| 33 | +#include "memory_copy_arch35_quant_flash_attn.h" | ||
| 34 | +using namespace AscendC; | ||
| 35 | +using namespace AscendC::Impl::Detail; | ||
| 36 | +using namespace regbaseutil; | ||
| 37 | +using namespace fa_base_matmul; | ||
| 38 | +using namespace AttentionCommon; | ||
| 39 | + | ||
| 40 | +namespace BaseApi { | ||
| 41 | + | ||
| 42 | +template <LayOutTypeEnum LAYOUT, uint8_t kvLayoutType = 0, bool isPa = false> | ||
| 43 | +__aicore__ inline constexpr GmFormat GetKVGmFormatHif8() | ||
| 44 | +{ | ||
| 45 | + if constexpr (kvLayoutType == 0) { | ||
| 46 | + if constexpr (LAYOUT == LayOutTypeEnum::LAYOUT_BSH) { | ||
| 47 | + return GmFormat::BSND; | ||
| 48 | + } else if constexpr (LAYOUT == LayOutTypeEnum::LAYOUT_SBH) { | ||
| 49 | + return GmFormat::SBND; | ||
| 50 | + } else if constexpr (LAYOUT == LayOutTypeEnum::LAYOUT_BNSD) { | ||
| 51 | + return GmFormat::BNSD; | ||
| 52 | + } else if constexpr (LAYOUT == LayOutTypeEnum::LAYOUT_TND) { | ||
| 53 | + return GmFormat::TND; | ||
| 54 | + } else { | ||
| 55 | + return GmFormat::NTD; | ||
| 56 | + } | ||
| 57 | + } else if constexpr (kvLayoutType == 1) { | ||
| 58 | + return GmFormat::PA_BnBsND; | ||
| 59 | + } else if constexpr (kvLayoutType == 2) { | ||
| 60 | + return GmFormat::PA_BnNBsD; | ||
| 61 | + } else { | ||
| 62 | + return GmFormat::PA_NZ; | ||
| 63 | + } | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +template <typename INPUT_T, typename T, LayOutTypeEnum layout = LayOutTypeEnum::None, | ||
| 67 | + S1TemplateType s1TemplateType = S1TemplateType::Aligned128, | ||
| 68 | + S2TemplateType s2TemplateType = S2TemplateType::Aligned128, | ||
| 69 | + DTemplateType dTemplateType = DTemplateType::Aligned128, | ||
| 70 | + DTemplateType dVTemplateType = DTemplateType::Aligned128, uint8_t KvLayoutType = 0, bool useDn = false> | ||
| 71 | +class QuantFlashAttnBlockCubeHif8 { | ||
| 72 | +public: | ||
| 73 | + /* ============确定L0A的类型============= */ | ||
| 74 | + struct L0ABuffSel { | ||
| 75 | + using Type = BuffersPolicyDB<BufferType::L0A>; | ||
| 76 | + }; | ||
| 77 | + /* ============确定L0B的类型============= */ | ||
| 78 | + template <uint32_t s2BaseSize, uint32_t dBaseSize> | ||
| 79 | + struct L0BBuffSel { | ||
| 80 | + using Type = std::conditional_t<(s2BaseSize == 256 && dBaseSize > 128), | ||
| 81 | + BuffersPolicySingleBuffer<BufferType::L0B>, BuffersPolicyDB<BufferType::L0B>>; | ||
| 82 | + }; | ||
| 83 | + | ||
| 84 | + /* ============确定L0C的类型============= */ | ||
| 85 | + template <uint32_t mBaseSize, uint32_t s2BaseSize, uint32_t dVBaseSize> | ||
| 86 | + struct L0CBuffSel { | ||
| 87 | + using Type = std::conditional_t<(mBaseSize * s2BaseSize * FLOAT_BYTES <= (L0C_SIZE * KB_TO_BYTES) / NUM_4 && | ||
| 88 | + mBaseSize * dVBaseSize * FLOAT_BYTES <= (L0C_SIZE * KB_TO_BYTES) / NUM_4), | ||
| 89 | + BuffersPolicy4buff<BufferType::L0C>, BuffersPolicyDB<BufferType::L0C>>; | ||
| 90 | + }; | ||
| 91 | + | ||
| 92 | + static constexpr uint32_t mBaseSize = (uint32_t)s1TemplateType; | ||
| 93 | + static constexpr uint32_t s2BaseSize = (uint32_t)s2TemplateType; | ||
| 94 | + static constexpr uint32_t dBaseSize = (uint32_t)dTemplateType; | ||
| 95 | + static constexpr uint32_t dVBaseSize = (uint32_t)dVTemplateType; | ||
| 96 | + static constexpr uint32_t l1BaseD = 128; | ||
| 97 | + static constexpr uint32_t MXFP_DIVISOR_SIZE = 64U; | ||
| 98 | + static constexpr LayOutTypeEnum LAYOUT = layout; | ||
| 99 | + static constexpr bool PAGE_ATTENTION = (KvLayoutType > 0); | ||
| 100 | + static constexpr bool USE_DN = useDn; | ||
| @@ -155,6 +155,7 @@ static constexpr ConfigParams ConfigValue[] = { | |||
| 155 | #define QFA_MXFP8_FP32_PREFILL 1 | 155 | #define QFA_MXFP8_FP32_PREFILL 1 |
| 156 | #define QFA_MXFP8_FP32_DECODE 2 | 156 | #define QFA_MXFP8_FP32_DECODE 2 |
| 157 | #define QFA_GQA_FP8_FULLQUANT 6 | 157 | #define QFA_GQA_FP8_FULLQUANT 6 |
| 158 | +#define QFA_HIF8_FP32 0 | ||
| 158 | 159 | ||
| 159 | #define false 0 | 160 | #define false 0 |
| 160 | #define true 1 | 161 | #define true 1 |
| @@ -31,11 +31,15 @@ ASCENDC_TPL_ARGS_DECL(QuantFlashAttn, | |||
| 31 | // Config (10-bit) | 31 | // Config (10-bit) |
| 32 | // 0: Config_S1Aligned128_S2Aligned512_DAligned64_DVAligned64 | 32 | // 0: Config_S1Aligned128_S2Aligned512_DAligned64_DVAligned64 |
| 33 | // 1: Config_S1Aligned128_S2Aligned512_DAligned128_DVAligned128 | 33 | // 1: Config_S1Aligned128_S2Aligned512_DAligned128_DVAligned128 |
| 34 | - // 2: Config_S1Aligned128_S2Aligned256_DAligned256_DVAligned256 | 34 | + // 2: Config_S1Aligned128_S2Aligned256_DAligned128_DVAligned128 |
| 35 | + // 3: Config_S1Aligned128_S2Aligned256_DAligned256_DVAligned256 | ||
| 36 | + // 4: Config_S1Aligned128_S2Aligned512_DAligned72_DVAligned72 | ||
| 35 | ASCENDC_TPL_UINT_DECL(Config, ASCENDC_TPL_10_BW, ASCENDC_TPL_UI_RANGE, 1, 0, 1023), | 37 | ASCENDC_TPL_UINT_DECL(Config, ASCENDC_TPL_10_BW, ASCENDC_TPL_UI_RANGE, 1, 0, 1023), |
| 36 | // QuantMode (5-bit) | 38 | // QuantMode (5-bit) |
| 37 | // 1: QFA_MXFP8_FP32_PREFILL | 39 | // 1: QFA_MXFP8_FP32_PREFILL |
| 38 | // 2: QFA_MXFP8_FP32_DECODE | 40 | // 2: QFA_MXFP8_FP32_DECODE |
| 41 | + // 6: QFA_GQA_FP8_FULLQUANT | ||
| 42 | + // 0: QFA_HIF8_FP32 | ||
| 39 | ASCENDC_TPL_UINT_DECL(QuantMode, ASCENDC_TPL_5_BW, ASCENDC_TPL_UI_RANGE, 1, 0, 31), | 43 | ASCENDC_TPL_UINT_DECL(QuantMode, ASCENDC_TPL_5_BW, ASCENDC_TPL_UI_RANGE, 1, 0, 31), |
| 40 | // HasAttenMask | 44 | // HasAttenMask |
| 41 | // false / true | 45 | // false / true |
| @@ -62,16 +66,23 @@ ASCENDC_TPL_SEL( | |||
| 62 | ASCENDC_TPL_BOOL_SEL(HasAttenMask, false, true), | 66 | ASCENDC_TPL_BOOL_SEL(HasAttenMask, false, true), |
| 63 | ASCENDC_TPL_UINT_SEL(KvLayoutType, ASCENDC_TPL_UI_LIST, KvLayoutType_NO_PA, KvLayoutType_PA_BBND, | 67 | ASCENDC_TPL_UINT_SEL(KvLayoutType, ASCENDC_TPL_UI_LIST, KvLayoutType_NO_PA, KvLayoutType_PA_BBND, |
| 64 | KvLayoutType_PA_BNBD, KvLayoutType_PA_NZ), | 68 | KvLayoutType_PA_BNBD, KvLayoutType_PA_NZ), |
| 65 | - ASCENDC_TPL_BOOL_SEL(IsFd, false), | 69 | + ASCENDC_TPL_BOOL_SEL(IsFd, false), ASCENDC_TPL_TILING_STRUCT_SEL(QuantFlashAttnTilingData)), |
| 66 | - ASCENDC_TPL_TILING_STRUCT_SEL(QuantFlashAttnTilingData)), | ||
| 67 | // FP8 | 70 | // FP8 |
| 68 | - ASCENDC_TPL_ARGS_SEL( | 71 | + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(InOutLayoutType, ASCENDC_TPL_UI_LIST, InOutLayoutType_NTD_TND), |
| 69 | - ASCENDC_TPL_UINT_SEL(InOutLayoutType, ASCENDC_TPL_UI_LIST, InOutLayoutType_NTD_TND), | 72 | + ASCENDC_TPL_UINT_SEL(Config, ASCENDC_TPL_UI_LIST, |
| 70 | - ASCENDC_TPL_UINT_SEL(Config, ASCENDC_TPL_UI_LIST, Config_S1Aligned128_S2Aligned256_DAligned128_DVAligned128), | 73 | + Config_S1Aligned128_S2Aligned256_DAligned128_DVAligned128), |
| 71 | - ASCENDC_TPL_UINT_SEL(QuantMode, ASCENDC_TPL_UI_LIST, QFA_GQA_FP8_FULLQUANT), | 74 | + ASCENDC_TPL_UINT_SEL(QuantMode, ASCENDC_TPL_UI_LIST, QFA_GQA_FP8_FULLQUANT), |
| 72 | - ASCENDC_TPL_BOOL_SEL(HasAttenMask, false, true), | 75 | + ASCENDC_TPL_BOOL_SEL(HasAttenMask, false, true), |
| 73 | - ASCENDC_TPL_UINT_SEL(KvLayoutType, ASCENDC_TPL_UI_LIST, KvLayoutType_PA_BNBD), | 76 | + ASCENDC_TPL_UINT_SEL(KvLayoutType, ASCENDC_TPL_UI_LIST, KvLayoutType_PA_BNBD), |
| 74 | - ASCENDC_TPL_BOOL_SEL(IsFd, false), | 77 | + ASCENDC_TPL_BOOL_SEL(IsFd, false), ASCENDC_TPL_TILING_STRUCT_SEL(QuantFlashAttnTilingData)), |
| 75 | - ASCENDC_TPL_TILING_STRUCT_SEL(QuantFlashAttnTilingData)), ); | 78 | + // HIF8 |
| 79 | + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(InOutLayoutType, ASCENDC_TPL_UI_LIST, InOutLayoutType_BSND_BSND, | ||
| 80 | + InOutLayoutType_BNSD_BNSD, InOutLayoutType_TND_TND), | ||
| 81 | + ASCENDC_TPL_UINT_SEL(Config, ASCENDC_TPL_UI_LIST, | ||
| 82 | + Config_S1Aligned128_S2Aligned256_DAligned128_DVAligned128), | ||
| 83 | + ASCENDC_TPL_UINT_SEL(QuantMode, ASCENDC_TPL_UI_LIST, QFA_HIF8_FP32), | ||
| 84 | + ASCENDC_TPL_BOOL_SEL(HasAttenMask, false, true), | ||
| 85 | + ASCENDC_TPL_UINT_SEL(KvLayoutType, ASCENDC_TPL_UI_LIST, KvLayoutType_NO_PA), | ||
| 86 | + ASCENDC_TPL_BOOL_SEL(IsFd, false), ASCENDC_TPL_TILING_STRUCT_SEL(QuantFlashAttnTilingData))); | ||
| 76 | 87 | ||
| 77 | #endif // TEMPLATE_TILING_KEY_QUANT_FLASH_ATTN_H_ | 88 | #endif // TEMPLATE_TILING_KEY_QUANT_FLASH_ATTN_H_ |
| @@ -19,6 +19,7 @@ | |||
| 19 | #include "util.h" | 19 | #include "util.h" |
| 20 | #include "arch35/quant_flash_attn_kernel_mxfp8.h" | 20 | #include "arch35/quant_flash_attn_kernel_mxfp8.h" |
| 21 | #include "arch35/quant_flash_attn_kernel_fp8.h" | 21 | #include "arch35/quant_flash_attn_kernel_fp8.h" |
| 22 | +#include "arch35/quant_flash_attn_kernel_hif8.h" | ||
| 22 | #include "arch35/quant_flash_attn_template_tiling_key.h" | 23 | #include "arch35/quant_flash_attn_template_tiling_key.h" |
| 23 | #include "arch35/quant_flash_attn_tiling_data.h" | 24 | #include "arch35/quant_flash_attn_tiling_data.h" |
| 24 | #if __has_include("../../common/op_kernel/arch35/flash_attention_score_common_regbase_arch35.h") | 25 | #if __has_include("../../common/op_kernel/arch35/flash_attention_score_common_regbase_arch35.h") |
| @@ -66,10 +67,12 @@ __aicore__ inline void quant_flash_attn_mxfp8( | |||
| 66 | dTemplateType, dVTemplateType, KvLayoutType, useDn, isDAligned>; | 67 | dTemplateType, dVTemplateType, KvLayoutType, useDn, isDAligned>; |
| 67 | using VecFaBlock = | 68 | using VecFaBlock = |
| 68 | BaseApi::QuantFlashAttnBlockVecMxfp8<INPUT_T, float, OUT_T, inputLayoutType, outputLayoutType, s1TemplateType, | 69 | BaseApi::QuantFlashAttnBlockVecMxfp8<INPUT_T, float, OUT_T, inputLayoutType, outputLayoutType, s1TemplateType, |
| 69 | - s2TemplateType, dTemplateType, dVTemplateType, hasAttenMask, KvLayoutType, isFdConst, useDn, isDAligned>; | 70 | + s2TemplateType, dTemplateType, dVTemplateType, hasAttenMask, KvLayoutType, |
| 71 | + isFdConst, useDn, isDAligned>; | ||
| 70 | using VecFdBlock = | 72 | using VecFdBlock = |
| 71 | BaseApi::QuantFlashAttnBlockVecFlashDecode<INPUT_T, float, OUT_T, inputLayoutType, outputLayoutType, | 73 | BaseApi::QuantFlashAttnBlockVecFlashDecode<INPUT_T, float, OUT_T, inputLayoutType, outputLayoutType, |
| 72 | - s1TemplateType, s2TemplateType, dTemplateType, dVTemplateType, hasAttenMask, KvLayoutType, useDn>; | 74 | + s1TemplateType, s2TemplateType, dTemplateType, dVTemplateType, |
| 75 | + hasAttenMask, KvLayoutType, useDn>; | ||
| 73 | 76 | ||
| 74 | using CubeBlockDummy = | 77 | using CubeBlockDummy = |
| 75 | BaseApi::QuantFlashAttnBlockCubeMxfp8Dummy<INPUT_T, float, inputLayoutType, s1TemplateType, s2TemplateType, | 78 | BaseApi::QuantFlashAttnBlockCubeMxfp8Dummy<INPUT_T, float, inputLayoutType, s1TemplateType, s2TemplateType, |
| @@ -80,7 +83,8 @@ __aicore__ inline void quant_flash_attn_mxfp8( | |||
| 80 | hasAttenMask, KvLayoutType, isFdConst, useDn>; | 83 | hasAttenMask, KvLayoutType, isFdConst, useDn>; |
| 81 | using VecFdBlockDummy = | 84 | using VecFdBlockDummy = |
| 82 | BaseApi::QuantFlashAttnBlockVecFlashDecodeDummy<INPUT_T, float, OUT_T, inputLayoutType, outputLayoutType, | 85 | BaseApi::QuantFlashAttnBlockVecFlashDecodeDummy<INPUT_T, float, OUT_T, inputLayoutType, outputLayoutType, |
| 83 | - s1TemplateType, s2TemplateType, dTemplateType, dVTemplateType, hasAttenMask, KvLayoutType, useDn>; | 86 | + s1TemplateType, s2TemplateType, dTemplateType, dVTemplateType, |
| 87 | + hasAttenMask, KvLayoutType, useDn>; | ||
| 84 | 88 | ||
| 85 | #ifdef __DAV_C310_CUBE__ | 89 | #ifdef __DAV_C310_CUBE__ |
| 86 | using Kernel = BaseApi::QuantFlashAttnKernelMxfp8<CubeBlock, VecFaBlockDummy, VecFdBlockDummy>; | 90 | using Kernel = BaseApi::QuantFlashAttnKernelMxfp8<CubeBlock, VecFaBlockDummy, VecFdBlockDummy>; |
| @@ -104,20 +108,17 @@ __aicore__ inline void quant_flash_attn_mxfp8( | |||
| 104 | // ───────────────────────────────────────────────────────── | 108 | // ───────────────────────────────────────────────────────── |
| 105 | template <typename INPUT_T, typename OUT_T, uint8_t inOutLayoutType, uint8_t KvLayoutType, bool hasAttenMask, | 109 | template <typename INPUT_T, typename OUT_T, uint8_t inOutLayoutType, uint8_t KvLayoutType, bool hasAttenMask, |
| 106 | uint8_t config> | 110 | uint8_t config> |
| 107 | -inline __aicore__ void | 111 | +inline __aicore__ void quant_flash_attn_gqa_fp8( |
| 108 | -quant_flash_attn_gqa_fp8(__gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint8_t *value, | 112 | + __gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint8_t *value, __gm__ uint8_t *qDescale, |
| 109 | - __gm__ uint8_t *qDescale, __gm__ uint8_t *kDescale, __gm__ uint8_t *vDescale, | 113 | + __gm__ uint8_t *kDescale, __gm__ uint8_t *vDescale, __gm__ uint8_t *blockTable, __gm__ uint8_t *pScale, |
| 110 | - __gm__ uint8_t *blockTable, __gm__ uint8_t *pScale, __gm__ uint8_t *cuSeqLensQ, | 114 | + __gm__ uint8_t *cuSeqLensQ, __gm__ uint8_t *cuSeqLensKv, __gm__ uint8_t *sequsedQ, __gm__ uint8_t *sequsedKv, |
| 111 | - __gm__ uint8_t *cuSeqLensKv, __gm__ uint8_t *sequsedQ, __gm__ uint8_t *sequsedKv, | 115 | + __gm__ uint8_t *sinks, __gm__ uint8_t *metadata, __gm__ uint8_t *attnOut, __gm__ uint8_t *softmaxLse, |
| 112 | - __gm__ uint8_t *sinks, __gm__ uint8_t *metadata, __gm__ uint8_t *attnOut, | 116 | + __gm__ uint8_t *workspace, __gm__ uint8_t *tiling) |
| 113 | - __gm__ uint8_t *softmaxLse, __gm__ uint8_t *workspace, __gm__ uint8_t *tiling) | ||
| 114 | { | 117 | { |
| 115 | fa_base_matmul::idCounterNum = 0; | 118 | fa_base_matmul::idCounterNum = 0; |
| 116 | 119 | ||
| 117 | - constexpr LayOutTypeEnum inputLayoutType = | 120 | + constexpr LayOutTypeEnum inputLayoutType = static_cast<LayOutTypeEnum>(InOutLayoutTypeValue[inOutLayoutType][0]); |
| 118 | - static_cast<LayOutTypeEnum>(InOutLayoutTypeValue[inOutLayoutType][0]); | 121 | + constexpr LayOutTypeEnum outputLayoutType = static_cast<LayOutTypeEnum>(InOutLayoutTypeValue[inOutLayoutType][1]); |
| 119 | - constexpr LayOutTypeEnum outputLayoutType = | ||
| 120 | - static_cast<LayOutTypeEnum>(InOutLayoutTypeValue[inOutLayoutType][1]); | ||
| 121 | 122 | ||
| 122 | constexpr S1TemplateType s1TemplateType = static_cast<S1TemplateType>(ConfigValue[config].s1); | 123 | constexpr S1TemplateType s1TemplateType = static_cast<S1TemplateType>(ConfigValue[config].s1); |
| 123 | constexpr S2TemplateType s2TemplateType = static_cast<S2TemplateType>(ConfigValue[config].s2); | 124 | constexpr S2TemplateType s2TemplateType = static_cast<S2TemplateType>(ConfigValue[config].s2); |
| @@ -131,11 +132,12 @@ quant_flash_attn_gqa_fp8(__gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint | |||
| 131 | dTemplateType, dVTemplateType, KvLayoutType, useDn>; | 132 | dTemplateType, dVTemplateType, KvLayoutType, useDn>; |
| 132 | using Fp8VecFaBlock = | 133 | using Fp8VecFaBlock = |
| 133 | BaseApi::QuantFlashAttnBlockVecGqaFp8<INPUT_T, float, OUT_T, inputLayoutType, outputLayoutType, s1TemplateType, | 134 | BaseApi::QuantFlashAttnBlockVecGqaFp8<INPUT_T, float, OUT_T, inputLayoutType, outputLayoutType, s1TemplateType, |
| 134 | - s2TemplateType, dTemplateType, dVTemplateType, | 135 | + s2TemplateType, dTemplateType, dVTemplateType, hasAttenMask, KvLayoutType, |
| 135 | - hasAttenMask, KvLayoutType, false, useDn>; | 136 | + false, useDn>; |
| 136 | using VecFdBlock = | 137 | using VecFdBlock = |
| 137 | BaseApi::QuantFlashAttnBlockVecFlashDecode<INPUT_T, float, OUT_T, inputLayoutType, outputLayoutType, | 138 | BaseApi::QuantFlashAttnBlockVecFlashDecode<INPUT_T, float, OUT_T, inputLayoutType, outputLayoutType, |
| 138 | - s1TemplateType, s2TemplateType, dTemplateType, dVTemplateType, hasAttenMask, KvLayoutType, useDn>; | 139 | + s1TemplateType, s2TemplateType, dTemplateType, dVTemplateType, |
| 140 | + hasAttenMask, KvLayoutType, useDn>; | ||
| 139 | 141 | ||
| 140 | using Fp8CubeBlockDummy = | 142 | using Fp8CubeBlockDummy = |
| 141 | BaseApi::QuantFlashAttnBlockCubeGqaFp8Dummy<INPUT_T, float, inputLayoutType, s1TemplateType, s2TemplateType, | 143 | BaseApi::QuantFlashAttnBlockCubeGqaFp8Dummy<INPUT_T, float, inputLayoutType, s1TemplateType, s2TemplateType, |
| @@ -146,7 +148,8 @@ quant_flash_attn_gqa_fp8(__gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint | |||
| 146 | hasAttenMask, KvLayoutType, false, useDn>; | 148 | hasAttenMask, KvLayoutType, false, useDn>; |
| 147 | using VecFdBlockDummy = | 149 | using VecFdBlockDummy = |
| 148 | BaseApi::QuantFlashAttnBlockVecFlashDecodeDummy<INPUT_T, float, OUT_T, inputLayoutType, outputLayoutType, | 150 | BaseApi::QuantFlashAttnBlockVecFlashDecodeDummy<INPUT_T, float, OUT_T, inputLayoutType, outputLayoutType, |
| 149 | - s1TemplateType, s2TemplateType, dTemplateType, dVTemplateType, hasAttenMask, KvLayoutType, useDn>; | 151 | + s1TemplateType, s2TemplateType, dTemplateType, dVTemplateType, |
| 152 | + hasAttenMask, KvLayoutType, useDn>; | ||
| 150 | 153 | ||
| 151 | #ifdef __DAV_C310_CUBE__ | 154 | #ifdef __DAV_C310_CUBE__ |
| 152 | using Kernel = BaseApi::QuantFlashAttnKernelFp8<Fp8CubeBlock, Fp8VecFaBlockDummy, VecFdBlockDummy>; | 155 | using Kernel = BaseApi::QuantFlashAttnKernelFp8<Fp8CubeBlock, Fp8VecFaBlockDummy, VecFdBlockDummy>; |
| @@ -159,8 +162,73 @@ quant_flash_attn_gqa_fp8(__gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint | |||
| 159 | 162 | ||
| 160 | TPipe tPipe; | 163 | TPipe tPipe; |
| 161 | Kernel op; | 164 | Kernel op; |
| 162 | - op.Init(query, key, value, sinks, cuSeqLensQ, cuSeqLensKv, blockTable, qDescale, kDescale, vDescale, | 165 | + op.Init(query, key, value, sinks, cuSeqLensQ, cuSeqLensKv, blockTable, qDescale, kDescale, vDescale, pScale, |
| 163 | - pScale, softmaxLse, attnOut, workspace, metadata, sequsedQ, sequsedKv, tilingData, | 166 | + softmaxLse, attnOut, workspace, metadata, sequsedQ, sequsedKv, tilingData, &tPipe); |
| 167 | + op.Process(); | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +template <uint8_t inOutLayoutType, uint16_t config, uint8_t quantMode, bool hasAttenMask, uint8_t KvLayoutType, | ||
| 171 | + bool isFd> | ||
| 172 | +__aicore__ inline void quant_flash_attn_hif8( | ||
| 173 | + __gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint8_t *value, __gm__ uint8_t *dequantScaleQuery, | ||
| 174 | + __gm__ uint8_t *dequantScaleKey, __gm__ uint8_t *dequantScaleValue, __gm__ uint8_t *blockTable, | ||
| 175 | + __gm__ uint8_t *pScale, __gm__ uint8_t *cuSeqLensQ, __gm__ uint8_t *cuSeqLensKv, __gm__ uint8_t *sequsedQ, | ||
| 176 | + __gm__ uint8_t *sequsedKv, __gm__ uint8_t *sinks, __gm__ uint8_t *attnMask, __gm__ uint8_t *metadata, | ||
| 177 | + __gm__ uint8_t *attnOut, __gm__ uint8_t *softmaxLse, __gm__ uint8_t *workspace, __gm__ uint8_t *tiling) | ||
| 178 | +{ | ||
| 179 | + using INPUT_T = hifloat8_t; | ||
| 180 | + using OUT_T = bfloat16_t; | ||
| 181 | + | ||
| 182 | + fa_base_matmul::idCounterNum = 0; | ||
| 183 | + | ||
| 184 | + constexpr LayOutTypeEnum inputLayoutType = static_cast<LayOutTypeEnum>(InOutLayoutTypeValue[inOutLayoutType][0]); | ||
| 185 | + constexpr LayOutTypeEnum outputLayoutType = static_cast<LayOutTypeEnum>(InOutLayoutTypeValue[inOutLayoutType][1]); | ||
| 186 | + | ||
| 187 | + constexpr S1TemplateType s1TemplateType = static_cast<S1TemplateType>(ConfigValue[config].s1); | ||
| 188 | + constexpr S2TemplateType s2TemplateType = static_cast<S2TemplateType>(ConfigValue[config].s2); | ||
| 189 | + constexpr DTemplateType dTemplateType = static_cast<DTemplateType>(ConfigValue[config].d); | ||
| 190 | + constexpr DTemplateType dVTemplateType = static_cast<DTemplateType>(ConfigValue[config].dv); | ||
| 191 | + | ||
| 192 | + constexpr bool isFdConst = false; | ||
| 193 | + constexpr bool useDn = true; | ||
| 194 | + | ||
| 195 | + using CubeBlock = | ||
| 196 | + BaseApi::QuantFlashAttnBlockCubeHif8<INPUT_T, float, inputLayoutType, s1TemplateType, s2TemplateType, | ||
| 197 | + dTemplateType, dVTemplateType, KvLayoutType, useDn>; | ||
| 198 | + using VecFaBlock = | ||
| 199 | + BaseApi::QuantFlashAttnBlockVecHif8<INPUT_T, float, OUT_T, inputLayoutType, outputLayoutType, s1TemplateType, | ||
| 200 | + s2TemplateType, dTemplateType, dVTemplateType, hasAttenMask, KvLayoutType, | ||
| 201 | + isFdConst, useDn>; | ||
| 202 | + using VecFdBlock = | ||
| 203 | + BaseApi::QuantFlashAttnBlockVecFlashDecode<INPUT_T, float, OUT_T, inputLayoutType, outputLayoutType, | ||
| 204 | + s1TemplateType, s2TemplateType, dTemplateType, dVTemplateType, | ||
| 205 | + hasAttenMask, KvLayoutType, useDn>; | ||
| 206 | + | ||
| 207 | + using CubeBlockDummy = | ||
| 208 | + BaseApi::QuantFlashAttnBlockCubeHif8Dummy<INPUT_T, float, inputLayoutType, s1TemplateType, s2TemplateType, | ||
| 209 | + dTemplateType, dVTemplateType, KvLayoutType, useDn>; | ||
| 210 | + using VecFaBlockDummy = | ||
| 211 | + BaseApi::QuantFlashAttnBlockVecHif8Dummy<INPUT_T, float, OUT_T, inputLayoutType, outputLayoutType, | ||
| 212 | + s1TemplateType, s2TemplateType, dTemplateType, dVTemplateType, | ||
| 213 | + hasAttenMask, KvLayoutType, isFdConst, useDn>; | ||
| 214 | + using VecFdBlockDummy = | ||
| 215 | + BaseApi::QuantFlashAttnBlockVecFlashDecodeDummy<INPUT_T, float, OUT_T, inputLayoutType, outputLayoutType, | ||
| 216 | + s1TemplateType, s2TemplateType, dTemplateType, dVTemplateType, | ||
| 217 | + hasAttenMask, KvLayoutType, useDn>; | ||
| 218 | + | ||
| 219 | +#ifdef __DAV_C310_CUBE__ | ||
| 220 | + using Kernel = BaseApi::QuantFlashAttnKernelHif8<CubeBlock, VecFaBlockDummy, VecFdBlockDummy>; | ||
| 221 | +#else | ||
| 222 | + using Kernel = BaseApi::QuantFlashAttnKernelHif8<CubeBlockDummy, VecFaBlock, VecFdBlock>; | ||
| 223 | +#endif | ||
| 224 | + | ||
| 225 | + const __gm__ QuantFlashAttnTilingData *__restrict tilingData = | ||
| 226 | + (const __gm__ QuantFlashAttnTilingData *__restrict)tiling; | ||
| 227 | + | ||
| 228 | + TPipe tPipe; | ||
| 229 | + Kernel op; | ||
| 230 | + op.Init(query, key, value, sinks, attnMask, cuSeqLensQ, cuSeqLensKv, blockTable, dequantScaleQuery, dequantScaleKey, | ||
| 231 | + dequantScaleValue, pScale, softmaxLse, attnOut, workspace, metadata, sequsedQ, sequsedKv, tilingData, | ||
| 164 | &tPipe); | 232 | &tPipe); |
| 165 | op.Process(); | 233 | op.Process(); |
| 166 | } | 234 | } |
| @@ -184,11 +252,15 @@ __global__ __aicore__ void quant_flash_attn( | |||
| 184 | cuSeqLensKv, sequsedQ, sequsedKv, sinks, attnMask, metadata, attnOut, softmaxLse, workspace, tiling); | 252 | cuSeqLensKv, sequsedQ, sequsedKv, sinks, attnMask, metadata, attnOut, softmaxLse, workspace, tiling); |
| 185 | } | 253 | } |
| 186 | if constexpr (quantMode == QFA_GQA_FP8_FULLQUANT) { | 254 | if constexpr (quantMode == QFA_GQA_FP8_FULLQUANT) { |
| 187 | - quant_flash_attn_gqa_fp8<fp8_e4m3fn_t, bfloat16_t, inOutLayoutType, KvLayoutType, hasAttenMask, | 255 | + quant_flash_attn_gqa_fp8<fp8_e4m3fn_t, bfloat16_t, inOutLayoutType, KvLayoutType, hasAttenMask, config>( |
| 188 | - config>( | 256 | + query, key, value, dequantScaleQuery, dequantScaleKey, dequantScaleValue, blockTable, pScale, cuSeqLensQ, |
| 189 | - query, key, value, dequantScaleQuery, dequantScaleKey, dequantScaleValue, blockTable, pScale, | 257 | + cuSeqLensKv, sequsedQ, sequsedKv, sinks, metadata, attnOut, softmaxLse, user, tiling); |
| 190 | - cuSeqLensQ, cuSeqLensKv, sequsedQ, sequsedKv, sinks, metadata, attnOut, softmaxLse, | 258 | + } |
| 191 | - user, tiling); | 259 | +#elif (ORIG_DTYPE_Q == DT_HIFLOAT8) |
| 260 | + if constexpr (quantMode == QFA_HIF8_FP32) { | ||
| 261 | + quant_flash_attn_hif8<inOutLayoutType, config, quantMode, hasAttenMask, KvLayoutType, isFd>( | ||
| 262 | + query, key, value, dequantScaleQuery, dequantScaleKey, dequantScaleValue, blockTable, pScale, cuSeqLensQ, | ||
| 263 | + cuSeqLensKv, sequsedQ, sequsedKv, sinks, attnMask, metadata, attnOut, softmaxLse, workspace, tiling); | ||
| 192 | } | 264 | } |
| 193 | #endif | 265 | #endif |
| 194 | } | 266 | } |
| @@ -101,6 +101,17 @@ CSV_PROFILES_GQA_FP8 = [ | |||
| 101 | ("qfa_gqa_fp8_excel_main.csv", "qfa_main_wrapper.run_main", "_gqa_fp8_main"), | 101 | ("qfa_gqa_fp8_excel_main.csv", "qfa_main_wrapper.run_main", "_gqa_fp8_main"), |
| 102 | ] | 102 | ] |
| 103 | 103 | ||
| 104 | +# 3 个 csv 的 api_name 和 testcase_name 后缀 (HIF8 per-tensor, quant_mode=0) | ||
| 105 | +CSV_PROFILES_HIF8 = [ | ||
| 106 | + ("qfa_hif8_excel.csv", "qfa_wrapper.npu_qfa", "_hif8"), | ||
| 107 | + ( | ||
| 108 | + "qfa_hif8_excel_metadata.csv", | ||
| 109 | + "qfa_metadata_wrapper.run_metadata", | ||
| 110 | + "_hif8_metadata", | ||
| 111 | + ), | ||
| 112 | + ("qfa_hif8_excel_main.csv", "qfa_main_wrapper.run_main", "_hif8_main"), | ||
| 113 | +] | ||
| 114 | + | ||
| 104 | # 向后兼容别名 (现有脚本若 import CSV_PROFILES) | 115 | # 向后兼容别名 (现有脚本若 import CSV_PROFILES) |
| 105 | CSV_PROFILES = CSV_PROFILES_MXFP8 | 116 | CSV_PROFILES = CSV_PROFILES_MXFP8 |
| 106 | 117 | ||
| @@ -113,7 +124,8 @@ DTYPE_MAP = { | |||
| 113 | "FLOAT8_E8M0": "float8_e8m0", | 124 | "FLOAT8_E8M0": "float8_e8m0", |
| 114 | "FP8_E8M0": "float8_e8m0", | 125 | "FP8_E8M0": "float8_e8m0", |
| 115 | "FLOAT4_E2M1": "float4_e2m1", | 126 | "FLOAT4_E2M1": "float4_e2m1", |
| 116 | - "HIFLOAT8": "hifloat8", | 127 | + "HIFLOAT8": "uint8", |
| 128 | + "HFLOAT8": "uint8", | ||
| 117 | "BF16": "bfloat16", | 129 | "BF16": "bfloat16", |
| 118 | "FP16": "float16", | 130 | "FP16": "float16", |
| 119 | "FP32": "float32", | 131 | "FP32": "float32", |
| @@ -348,7 +360,7 @@ def _build_tensor_lists(row, cols, quant_mode): | |||
| 348 | dtypes = [] | 360 | dtypes = [] |
| 349 | data_ranges = [] | 361 | data_ranges = [] |
| 350 | 362 | ||
| 351 | - descale_default = "float32" if quant_mode == 6 else "float8_e8m0" | 363 | + descale_default = "float32" if quant_mode in (6, 0) else "float8_e8m0" |
| 352 | 364 | ||
| 353 | for ( | 365 | for ( |
| 354 | shape_col, | 366 | shape_col, |
| @@ -371,8 +383,16 @@ def _build_tensor_lists(row, cols, quant_mode): | |||
| 371 | if shape is None: | 383 | if shape is None: |
| 372 | shape = (0,) | 384 | shape = (0,) |
| 373 | 385 | ||
| 374 | - # GQA FP8: p_scale 空 shape → 标量 (1,) float32(与原脚本 GQA 分支一致) | 386 | + # HIF8 (quant_mode=0): descale 是 per-tensor 标量 (1,), Excel 可能不填 shape |
| 375 | - if shape_col == "p_scale_shape" and shape == (0,) and quant_mode == 6: | 387 | + if ( |
| 388 | + shape_col in ("q_descale_shape", "k_descale_shape", "v_descale_shape") | ||
| 389 | + and shape == (0,) | ||
| 390 | + and quant_mode == 0 | ||
| 391 | + ): | ||
| 392 | + shape = (1,) | ||
| 393 | + | ||
| 394 | + # GQA FP8 / HIF8: p_scale 空 shape → 标量 (1,) float32(与原脚本分支一致) | ||
| 395 | + if shape_col == "p_scale_shape" and shape == (0,) and quant_mode in (6, 0): | ||
| 376 | shape = (1,) | 396 | shape = (1,) |
| 377 | dtype = "float32" | 397 | dtype = "float32" |
| 378 | 398 | ||
| @@ -456,6 +476,10 @@ def _build_attributes(row, cols): | |||
| 456 | # --- wrapper 接口适配参数(不是 op 参数推导,是 wrapper 签名必选参数) --- | 476 | # --- wrapper 接口适配参数(不是 op 参数推导,是 wrapper 签名必选参数) --- |
| 457 | layout_kv = _strip_or_none(row.get(cols.get("layout_kv"))) | 477 | layout_kv = _strip_or_none(row.get(cols.get("layout_kv"))) |
| 458 | layout_q_descale = _strip_or_none(row.get(cols.get("layout_q_descale"))) | 478 | layout_q_descale = _strip_or_none(row.get(cols.get("layout_q_descale"))) |
| 479 | + if layout_q_descale is None: | ||
| 480 | + _qm_raw = _str_to_int(row.get(cols.get("quant_mode"))) | ||
| 481 | + quant_mode = _qm_raw if _qm_raw is not None else 1 | ||
| 482 | + layout_q_descale = "BSND" if quant_mode == 0 else "TND" | ||
| 459 | # batch_size: Excel pure passthrough (可为 -1/正整数/None),透传给 metadata 的 batch_size。 | 483 | # batch_size: Excel pure passthrough (可为 -1/正整数/None),透传给 metadata 的 batch_size。 |
| 460 | # wrapper 内部从 cu_seqlens_q 推导正整数 B 供 inputs/golden 生成 BNSD 张量。 | 484 | # wrapper 内部从 cu_seqlens_q 推导正整数 B 供 inputs/golden 生成 BNSD 张量。 |
| 461 | _set_force( | 485 | _set_force( |
| @@ -486,7 +510,8 @@ def _build_attributes(row, cols): | |||
| 486 | else: | 510 | else: |
| 487 | bs_idx = 2 | 511 | bs_idx = 2 |
| 488 | raw_bs = k_shape[bs_idx] if len(k_shape) > bs_idx else 0 | 512 | raw_bs = k_shape[bs_idx] if len(k_shape) > bs_idx else 0 |
| 489 | - quant_mode_for_bs = _str_to_int(row.get(cols.get("quant_mode"))) or 1 | 513 | + _qm_bs_raw = _str_to_int(row.get(cols.get("quant_mode"))) |
| 514 | + quant_mode_for_bs = _qm_bs_raw if _qm_bs_raw is not None else 1 | ||
| 490 | if quant_mode_for_bs == 6: | 515 | if quant_mode_for_bs == 6: |
| 491 | block_size = max(0, raw_bs - K_SCALE_ROWS_GQA) | 516 | block_size = max(0, raw_bs - K_SCALE_ROWS_GQA) |
| 492 | else: | 517 | else: |
| @@ -551,7 +576,7 @@ def _parse_sheet_arg(s): | |||
| 551 | 576 | ||
| 552 | def main(): | 577 | def main(): |
| 553 | parser = argparse.ArgumentParser( | 578 | parser = argparse.ArgumentParser( |
| 554 | - description="redline.xlsx → 3 个 ttk 标准 CSV (mxfp8 或 gqa_fp8)" | 579 | + description="redline.xlsx → 3 个 ttk 标准 CSV (mxfp8 / gqa_fp8 / hif8)" |
| 555 | ) | 580 | ) |
| 556 | parser.add_argument( | 581 | parser.add_argument( |
| 557 | "--sheet", | 582 | "--sheet", |
| @@ -597,12 +622,16 @@ def main(): | |||
| 597 | if a_header != "testcase_name": | 622 | if a_header != "testcase_name": |
| 598 | raise RuntimeError(f"unexpected header A: {a_header!r}") | 623 | raise RuntimeError(f"unexpected header A: {a_header!r}") |
| 599 | 624 | ||
| 600 | - # 检测整 sheet 的 quant_mode (redline.xlsx 单 mode 约定: 全 mxfp8 或全 gqa_fp8) | 625 | + # 检测整 sheet 的 quant_mode (redline.xlsx 单 mode 约定: 全 mxfp8 或全 gqa_fp8 或全 hif8) |
| 601 | # 取首数据行 quant_mode 列判断; 省略默认 1 (MXFP8) | 626 | # 取首数据行 quant_mode 列判断; 省略默认 1 (MXFP8) |
| 602 | - first_qm = _str_to_int(data_rows[0].get(cols.get("quant_mode"))) or 1 | 627 | + _first_qm_raw = _str_to_int(data_rows[0].get(cols.get("quant_mode"))) |
| 628 | + first_qm = _first_qm_raw if _first_qm_raw is not None else 1 | ||
| 603 | if first_qm == 6: | 629 | if first_qm == 6: |
| 604 | profiles = CSV_PROFILES_GQA_FP8 | 630 | profiles = CSV_PROFILES_GQA_FP8 |
| 605 | mode_label = "GQA FP8 (quant_mode=6)" | 631 | mode_label = "GQA FP8 (quant_mode=6)" |
| 632 | + elif first_qm == 0: | ||
| 633 | + profiles = CSV_PROFILES_HIF8 | ||
| 634 | + mode_label = "HIF8 (quant_mode=0)" | ||
| 606 | else: | 635 | else: |
| 607 | profiles = CSV_PROFILES_MXFP8 | 636 | profiles = CSV_PROFILES_MXFP8 |
| 608 | mode_label = "MXFP8 (quant_mode=1)" | 637 | mode_label = "MXFP8 (quant_mode=1)" |
| @@ -1,219 +1,223 @@ | |||
| 1 | -#!/usr/bin/python3 | 1 | +#!/usr/bin/python3 |
| 2 | -# -*- coding: utf-8 -*- | 2 | +# -*- coding: utf-8 -*- |
| 3 | -# ----------------------------------------------------------------------------------------------------------- | 3 | +# ----------------------------------------------------------------------------------------------------------- |
| 4 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. | 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. |
| 5 | -# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of |
| 6 | -# CANN Open Software License Agreement Version 2.0 (the "License"). | 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). |
| 7 | -# Please refer to the License for details. You may not use this file except in compliance with the License. | 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. |
| 8 | -# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, |
| 9 | -# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. |
| 10 | -# See LICENSE in the root of the software repository for the full text of the License. | 10 | +# See LICENSE in the root of the software repository for the full text of the License. |
| 11 | -# ----------------------------------------------------------------------------------------------------------- | 11 | +# ----------------------------------------------------------------------------------------------------------- |
| 12 | - | 12 | + |
| 13 | -import logging | 13 | +import logging |
| 14 | -import os | 14 | +import os |
| 15 | -import sys | 15 | +import sys |
| 16 | - | 16 | + |
| 17 | -import numpy as np | 17 | +import numpy as np |
| 18 | -import torch | 18 | +import torch |
| 19 | - | 19 | + |
| 20 | -_ASSETS_DIR = os.path.dirname(os.path.abspath(__file__)) | 20 | +_ASSETS_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 21 | -_TESTS_DIR = os.path.join(_ASSETS_DIR, "..") | 21 | +_TESTS_DIR = os.path.join(_ASSETS_DIR, "..") |
| 22 | -if _TESTS_DIR not in sys.path: | 22 | +if _TESTS_DIR not in sys.path: |
| 23 | - sys.path.insert(0, _TESTS_DIR) | 23 | + sys.path.insert(0, _TESTS_DIR) |
| 24 | -import result_compare_method | 24 | +import result_compare_method |
| 25 | -import quant_flash_attn_golden as mxfp8_golden_mod | 25 | +import quant_flash_attn_golden as mxfp8_golden_mod |
| 26 | -import quant_flash_attn_fp8_golden as fp8_golden_mod | 26 | +import quant_flash_attn_fp8_golden as fp8_golden_mod |
| 27 | - | 27 | +import quant_flash_attn_hif8_golden as hif8_golden_mod |
| 28 | -logger = logging.getLogger(__name__) | 28 | + |
| 29 | - | 29 | +logger = logging.getLogger(__name__) |
| 30 | - | 30 | + |
| 31 | -def _resolve_csv_tolerance(idx): | 31 | + |
| 32 | - """从 golden 模块读 csv 注入的 precision_tolerances / absolute_precision。 | 32 | +def _resolve_csv_tolerance(idx): |
| 33 | - | 33 | + """从 golden 模块读 csv 注入的 precision_tolerances / absolute_precision。 |
| 34 | - ttk 框架不把 testcase 对象直接传给 custom compare, golden 插件在调用前把 | 34 | + |
| 35 | - csv 的 precision_tolerances / absolute_precision 暂存到对应 golden 模块上。 | 35 | + ttk 框架不把 testcase 对象直接传给 custom compare, golden 插件在调用前把 |
| 36 | - 按 quant_mode 分流: mxfp8 → mxfp8_golden_mod, gqa_fp8 → fp8_golden_mod。 | 36 | + csv 的 precision_tolerances / absolute_precision 暂存到对应 golden 模块上。 |
| 37 | - 本函数优先检查 fp8_golden_mod (quant_mode=6), 再检查 mxfp8_golden_mod, | 37 | + 按 quant_mode 分流: mxfp8 → mxfp8_golden_mod, gqa_fp8 → fp8_golden_mod。 |
| 38 | - 取首个非 None 的属性 (两个模块不会同时有值, 因一个 case 只走一条路径)。 | 38 | + 本函数优先检查 fp8_golden_mod (quant_mode=6), 再检查 mxfp8_golden_mod, |
| 39 | - 返回 (rtol, atol, diff_thd, pct_thd, max_diff_hd); csv 省略时返回 (None,)*5 | 39 | + 取首个非 None 的属性 (两个模块不会同时有值, 因一个 case 只走一条路径)。 |
| 40 | - 由 check_result 用默认值 (rtol/atol 按 dtype 分支, diff_thd=0.005, pct_thd=0.005, | 40 | + 返回 (rtol, atol, diff_thd, pct_thd, max_diff_hd); csv 省略时返回 (None,)*5 |
| 41 | - max_diff_hd=10)。 | 41 | + 由 check_result 用默认值 (rtol/atol 按 dtype 分支, diff_thd=0.005, pct_thd=0.005, |
| 42 | - | 42 | + max_diff_hd=10)。 |
| 43 | - precision_tolerances 格式: tuple of per-output tuple, 每条目可为 2-tuple 或 5-tuple | 43 | + |
| 44 | - 2-tuple (向后兼容): (rtol, atol) 如 ((0.0078125, 0.0001),) | 44 | + precision_tolerances 格式: tuple of per-output tuple, 每条目可为 2-tuple 或 5-tuple |
| 45 | - 5-tuple (新): (rtol, atol, diff_thd, pct_thd, max_diff_hd) | 45 | + 2-tuple (向后兼容): (rtol, atol) 如 ((0.0078125, 0.0001),) |
| 46 | - 如 ((0.0078125, 0.0001, 0.005, 0.005, 10),) | 46 | + 5-tuple (新): (rtol, atol, diff_thd, pct_thd, max_diff_hd) |
| 47 | - 5-tuple 的后三位 None → check_result 用默认值 (0.005/0.005/10) | 47 | + 如 ((0.0078125, 0.0001, 0.005, 0.005, 10),) |
| 48 | - """ | 48 | + 5-tuple 的后三位 None → check_result 用默认值 (0.005/0.005/10) |
| 49 | - # 优先检查 fp8_golden_mod (quant_mode=6 路径), 再检查 mxfp8_golden_mod | 49 | + """ |
| 50 | - pt = getattr(fp8_golden_mod, "_csv_precision_tolerances", None) | 50 | + # 优先检查 fp8_golden_mod (quant_mode=6 路径), 再检查 hif8_golden_mod, 再检查 mxfp8_golden_mod |
| 51 | - ap = getattr(fp8_golden_mod, "_csv_absolute_precision", None) | 51 | + pt = getattr(fp8_golden_mod, "_csv_precision_tolerances", None) |
| 52 | - if pt is None and ap is None: | 52 | + ap = getattr(fp8_golden_mod, "_csv_absolute_precision", None) |
| 53 | - pt = getattr(mxfp8_golden_mod, "_csv_precision_tolerances", None) | 53 | + if pt is None and ap is None: |
| 54 | - ap = getattr(mxfp8_golden_mod, "_csv_absolute_precision", None) | 54 | + pt = getattr(hif8_golden_mod, "_csv_precision_tolerances", None) |
| 55 | - rtol = None | 55 | + ap = getattr(hif8_golden_mod, "_csv_absolute_precision", None) |
| 56 | - atol = None | 56 | + if pt is None and ap is None: |
| 57 | - diff_thd = None | 57 | + pt = getattr(mxfp8_golden_mod, "_csv_precision_tolerances", None) |
| 58 | - pct_thd = None | 58 | + ap = getattr(mxfp8_golden_mod, "_csv_absolute_precision", None) |
| 59 | - max_diff_hd = None | 59 | + rtol = None |
| 60 | - if pt: | 60 | + atol = None |
| 61 | - # 优先取 idx 对应条目; idx 超出范围时回退到最后一个可用条目 (通常 idx=0) | 61 | + diff_thd = None |
| 62 | - pair = pt[idx] if idx < len(pt) else pt[-1] | 62 | + pct_thd = None |
| 63 | - if pair is not None and len(pair) >= 2: | 63 | + max_diff_hd = None |
| 64 | - rtol = float(pair[0]) | 64 | + if pt: |
| 65 | - atol = float(pair[1]) | 65 | + # 优先取 idx 对应条目; idx 超出范围时回退到最后一个可用条目 (通常 idx=0) |
| 66 | - # 5-tuple 的后三位 (向后兼容: 2-tuple 缺失 → None → check_result 用默认值) | 66 | + pair = pt[idx] if idx < len(pt) else pt[-1] |
| 67 | - if len(pair) >= 3 and pair[2] is not None: | 67 | + if pair is not None and len(pair) >= 2: |
| 68 | - diff_thd = float(pair[2]) | 68 | + rtol = float(pair[0]) |
| 69 | - if len(pair) >= 4 and pair[3] is not None: | 69 | + atol = float(pair[1]) |
| 70 | - pct_thd = float(pair[3]) | 70 | + # 5-tuple 的后三位 (向后兼容: 2-tuple 缺失 → None → check_result 用默认值) |
| 71 | - if len(pair) >= 5 and pair[4] is not None: | 71 | + if len(pair) >= 3 and pair[2] is not None: |
| 72 | - max_diff_hd = float(pair[4]) | 72 | + diff_thd = float(pair[2]) |
| 73 | - if atol is None and ap is not None: | 73 | + if len(pair) >= 4 and pair[3] is not None: |
| 74 | - if isinstance(ap, (tuple, list)): | 74 | + pct_thd = float(pair[3]) |
| 75 | - val = ap[idx] if idx < len(ap) else ap[-1] | 75 | + if len(pair) >= 5 and pair[4] is not None: |
| 76 | - if val is not None: | 76 | + max_diff_hd = float(pair[4]) |
| 77 | - atol = float(val) | 77 | + if atol is None and ap is not None: |
| 78 | - else: | 78 | + if isinstance(ap, (tuple, list)): |
| 79 | - atol = float(ap) | 79 | + val = ap[idx] if idx < len(ap) else ap[-1] |
| 80 | - # replay 模式: pt 为 None (golden 未注入) → 用 bf16 默认, 与 CSV atten 容差一致 | 80 | + if val is not None: |
| 81 | - if rtol is None and atol is None: | 81 | + atol = float(val) |
| 82 | - rtol, atol = 0.0078125, 0.0001 | 82 | + else: |
| 83 | - return rtol, atol, diff_thd, pct_thd, max_diff_hd | 83 | + atol = float(ap) |
| 84 | - | 84 | + # replay 模式: pt 为 None (golden 未注入) → 用 bf16 默认, 与 CSV atten 容差一致 |
| 85 | - | 85 | + if rtol is None and atol is None: |
| 86 | -def _to_torch(x): | 86 | + rtol, atol = 0.0078125, 0.0001 |
| 87 | - """numpy array → torch tensor; torch tensor → 原样返回; None → None | 87 | + return rtol, atol, diff_thd, pct_thd, max_diff_hd |
| 88 | - 处理 bfloat16: numpy 原生不支持 bfloat16(ml_dtypes), torch.from_numpy 会失败, | 88 | + |
| 89 | - 需要先 view uint8 再 reinterpret 为 bfloat16。 | 89 | + |
| 90 | - """ | 90 | +def _to_torch(x): |
| 91 | - if x is None: | 91 | + """numpy array → torch tensor; torch tensor → 原样返回; None → None |
| 92 | - return None | 92 | + 处理 bfloat16: numpy 原生不支持 bfloat16(ml_dtypes), torch.from_numpy 会失败, |
| 93 | - if isinstance(x, np.ndarray): | 93 | + 需要先 view uint8 再 reinterpret 为 bfloat16。 |
| 94 | - # bfloat16 在 numpy 里是 ml_dtypes.bfloat16, torch.from_numpy 不支持 | 94 | + """ |
| 95 | - if x.dtype.name == "bfloat16": | 95 | + if x is None: |
| 96 | - # 通过 uint8 view + torch view 还原 bfloat16 | 96 | + return None |
| 97 | - return torch.from_numpy(x.view(np.uint8)).view(torch.bfloat16) | 97 | + if isinstance(x, np.ndarray): |
| 98 | - return torch.from_numpy(x) | 98 | + # bfloat16 在 numpy 里是 ml_dtypes.bfloat16, torch.from_numpy 不支持 |
| 99 | - if isinstance(x, torch.Tensor): | 99 | + if x.dtype.name == "bfloat16": |
| 100 | - return x | 100 | + # 通过 uint8 view + torch view 还原 bfloat16 |
| 101 | - return torch.as_tensor(x) | 101 | + return torch.from_numpy(x.view(np.uint8)).view(torch.bfloat16) |
| 102 | - | 102 | + return torch.from_numpy(x) |
| 103 | - | 103 | + if isinstance(x, torch.Tensor): |
| 104 | -def compare(*outputs, **kwargs): | 104 | + return x |
| 105 | - """对比 NPU 输出与 golden 输出。 | 105 | + return torch.as_tensor(x) |
| 106 | - | 106 | + |
| 107 | - TTK 传参方式: [npu_out(, npu_lse), golden_out(, golden_lse)] | 107 | + |
| 108 | - 当 lse 未启用时, npu_lse 可能是空数组(size=0), golden 不含 lse。 | 108 | +def compare(*outputs, **kwargs): |
| 109 | - 所以输出数可能不等,需按实际非空输出配对。 | 109 | + """对比 NPU 输出与 golden 输出。 |
| 110 | - """ | 110 | + |
| 111 | - # 过滤掉 None,但保留空数组用于后续检查 | 111 | + TTK 传参方式: [npu_out(, npu_lse), golden_out(, golden_lse)] |
| 112 | - non_none = [o for o in outputs if o is not None] | 112 | + 当 lse 未启用时, npu_lse 可能是空数组(size=0), golden 不含 lse。 |
| 113 | - | 113 | + 所以输出数可能不等,需按实际非空输出配对。 |
| 114 | - if len(non_none) < 2: | 114 | + """ |
| 115 | - return { | 115 | + # 过滤掉 None,但保留空数组用于后续检查 |
| 116 | - "pass": False, | 116 | + non_none = [o for o in outputs if o is not None] |
| 117 | - "precision": "invalid", | 117 | + |
| 118 | - "error_info": f"not enough valid outputs: {len(non_none)}", | 118 | + if len(non_none) < 2: |
| 119 | - } | 119 | + return { |
| 120 | - | 120 | + "pass": False, |
| 121 | - # 检查是否都是空 tensor (actual_seq_q=[0] 时会出现) | 121 | + "precision": "invalid", |
| 122 | - all_empty = all( | 122 | + "error_info": f"not enough valid outputs: {len(non_none)}", |
| 123 | - (hasattr(o, "size") and o.size == 0) or (hasattr(o, "numel") and o.numel() == 0) | 123 | + } |
| 124 | - for o in non_none | 124 | + |
| 125 | - ) | 125 | + # 检查是否都是空 tensor (actual_seq_q=[0] 时会出现) |
| 126 | - if all_empty: | 126 | + all_empty = all( |
| 127 | - logger.info("[COMPARE] 所有输出都是空 tensor,视为 PASS") | 127 | + (hasattr(o, "size") and o.size == 0) or (hasattr(o, "numel") and o.numel() == 0) |
| 128 | - return { | 128 | + for o in non_none |
| 129 | - "pass": True, | 129 | + ) |
| 130 | - "precision": "100.0%", | 130 | + if all_empty: |
| 131 | - "error_info": None, | 131 | + logger.info("[COMPARE] 所有输出都是空 tensor,视为 PASS") |
| 132 | - "metrics": {"result": "Pass", "PctRlt": "100.0%", "MaxRE": 0.0}, | 132 | + return { |
| 133 | - } | 133 | + "pass": True, |
| 134 | - | 134 | + "precision": "100.0%", |
| 135 | - # 过滤掉空数组,只保留有效输出 | 135 | + "error_info": None, |
| 136 | - valid = [] | 136 | + "metrics": {"result": "Pass", "PctRlt": "100.0%", "MaxRE": 0.0}, |
| 137 | - for o in non_none: | 137 | + } |
| 138 | - if hasattr(o, "size") and o.size == 0: | 138 | + |
| 139 | - continue | 139 | + # 过滤掉空数组,只保留有效输出 |
| 140 | - if hasattr(o, "numel") and o.numel() == 0: | 140 | + valid = [] |
| 141 | - continue | 141 | + for o in non_none: |
| 142 | - valid.append(o) | 142 | + if hasattr(o, "size") and o.size == 0: |
| 143 | - | 143 | + continue |
| 144 | - if len(valid) < 2: | 144 | + if hasattr(o, "numel") and o.numel() == 0: |
| 145 | - return { | 145 | + continue |
| 146 | - "pass": False, | 146 | + valid.append(o) |
| 147 | - "precision": "invalid", | 147 | + |
| 148 | - "error_info": f"not enough valid outputs after filtering: {len(valid)}", | 148 | + if len(valid) < 2: |
| 149 | - } | 149 | + return { |
| 150 | - | 150 | + "pass": False, |
| 151 | - # 前半 NPU,后半 golden | 151 | + "precision": "invalid", |
| 152 | - half = len(valid) // 2 | 152 | + "error_info": f"not enough valid outputs after filtering: {len(valid)}", |
| 153 | - npu_outputs = valid[:half] | 153 | + } |
| 154 | - golden_outputs = valid[half:] | 154 | + |
| 155 | - | 155 | + # 前半 NPU,后半 golden |
| 156 | - all_pass = True | 156 | + half = len(valid) // 2 |
| 157 | - results = [] | 157 | + npu_outputs = valid[:half] |
| 158 | - | 158 | + golden_outputs = valid[half:] |
| 159 | - for idx, (npu_out, golden_out) in enumerate(zip(npu_outputs, golden_outputs)): | 159 | + |
| 160 | - label = "atten" if idx == 0 else f"out{idx}" | 160 | + all_pass = True |
| 161 | - npu_torch = _to_torch(npu_out) | 161 | + results = [] |
| 162 | - golden_torch = _to_torch(golden_out) | 162 | + |
| 163 | - rtol, atol, diff_thd, pct_thd, max_diff_hd = _resolve_csv_tolerance(idx) | 163 | + for idx, (npu_out, golden_out) in enumerate(zip(npu_outputs, golden_outputs)): |
| 164 | - logger.info( | 164 | + label = "atten" if idx == 0 else f"out{idx}" |
| 165 | - "[COMPARE] %s: csv rtol=%s atol=%s diff_thd=%s pct_thd=%s max_diff_hd=%s", | 165 | + npu_torch = _to_torch(npu_out) |
| 166 | - label, | 166 | + golden_torch = _to_torch(golden_out) |
| 167 | - rtol, | 167 | + rtol, atol, diff_thd, pct_thd, max_diff_hd = _resolve_csv_tolerance(idx) |
| 168 | - atol, | 168 | + logger.info( |
| 169 | - diff_thd, | 169 | + "[COMPARE] %s: csv rtol=%s atol=%s diff_thd=%s pct_thd=%s max_diff_hd=%s", |
| 170 | - pct_thd, | 170 | + label, |
| 171 | - max_diff_hd, | 171 | + rtol, |
| 172 | - ) | 172 | + atol, |
| 173 | - npu_shape = tuple(npu_torch.shape) if hasattr(npu_torch, "shape") else "N/A" | 173 | + diff_thd, |
| 174 | - npu_dtype = str(npu_torch.dtype) if hasattr(npu_torch, "dtype") else "N/A" | 174 | + pct_thd, |
| 175 | - golden_shape = ( | 175 | + max_diff_hd, |
| 176 | - tuple(golden_torch.shape) if hasattr(golden_torch, "shape") else "N/A" | 176 | + ) |
| 177 | - ) | 177 | + npu_shape = tuple(npu_torch.shape) if hasattr(npu_torch, "shape") else "N/A" |
| 178 | - golden_dtype = ( | 178 | + npu_dtype = str(npu_torch.dtype) if hasattr(npu_torch, "dtype") else "N/A" |
| 179 | - str(golden_torch.dtype) if hasattr(golden_torch, "dtype") else "N/A" | 179 | + golden_shape = ( |
| 180 | - ) | 180 | + tuple(golden_torch.shape) if hasattr(golden_torch, "shape") else "N/A" |
| 181 | - logger.info( | 181 | + ) |
| 182 | - "[COMPARE] %s: npu_shape=%s npu_dtype=%s | golden_shape=%s golden_dtype=%s", | 182 | + golden_dtype = ( |
| 183 | - label, | 183 | + str(golden_torch.dtype) if hasattr(golden_torch, "dtype") else "N/A" |
| 184 | - npu_shape, | 184 | + ) |
| 185 | - npu_dtype, | 185 | + logger.info( |
| 186 | - golden_shape, | 186 | + "[COMPARE] %s: npu_shape=%s npu_dtype=%s | golden_shape=%s golden_dtype=%s", |
| 187 | - golden_dtype, | 187 | + label, |
| 188 | - ) | 188 | + npu_shape, |
| 189 | - result, fulfill_percent, max_error = result_compare_method.check_result( | 189 | + npu_dtype, |
| 190 | - golden_torch, | 190 | + golden_shape, |
| 191 | - npu_torch, | 191 | + golden_dtype, |
| 192 | - rtol=rtol, | 192 | + ) |
| 193 | - atol=atol, | 193 | + result, fulfill_percent, max_error = result_compare_method.check_result( |
| 194 | - diff_thd=diff_thd, | 194 | + golden_torch, |
| 195 | - pct_thd=pct_thd, | 195 | + npu_torch, |
| 196 | - max_diff_hd=max_diff_hd, | 196 | + rtol=rtol, |
| 197 | - ) | 197 | + atol=atol, |
| 198 | - is_pass = result == "Pass" | 198 | + diff_thd=diff_thd, |
| 199 | - if not is_pass: | 199 | + pct_thd=pct_thd, |
| 200 | - all_pass = False | 200 | + max_diff_hd=max_diff_hd, |
| 201 | - results.append( | 201 | + ) |
| 202 | - { | 202 | + is_pass = result == "Pass" |
| 203 | - "pass": is_pass, | 203 | + if not is_pass: |
| 204 | - "precision": fulfill_percent, | 204 | + all_pass = False |
| 205 | - "error_info": None | 205 | + results.append( |
| 206 | - if is_pass | 206 | + { |
| 207 | - else f"{label}: result={result}, MaxRE={max_error}", | 207 | + "pass": is_pass, |
| 208 | - "metrics": { | 208 | + "precision": fulfill_percent, |
| 209 | - "label": label, | 209 | + "error_info": None |
| 210 | - "result": result, | 210 | + if is_pass |
| 211 | - "PctRlt": fulfill_percent, | 211 | + else f"{label}: result={result}, MaxRE={max_error}", |
| 212 | - "MaxRE": max_error, | 212 | + "metrics": { |
| 213 | - }, | 213 | + "label": label, |
| 214 | - } | 214 | + "result": result, |
| 215 | - ) | 215 | + "PctRlt": fulfill_percent, |
| 216 | - | 216 | + "MaxRE": max_error, |
| 217 | - if len(results) == 1: | 217 | + }, |
| 218 | - return results[0] | 218 | + } |
| 219 | - return results | 219 | + ) |
| 220 | + | ||
| 221 | + if len(results) == 1: | ||
| 222 | + return results[0] | ||
| 223 | + return results | ||
| @@ -25,6 +25,7 @@ if _TESTS_DIR not in sys.path: | |||
| 25 | sys.path.insert(0, _TESTS_DIR) | 25 | sys.path.insert(0, _TESTS_DIR) |
| 26 | import quant_flash_attn_golden as mxfp8_golden_mod | 26 | import quant_flash_attn_golden as mxfp8_golden_mod |
| 27 | import quant_flash_attn_fp8_golden as fp8_golden_mod | 27 | import quant_flash_attn_fp8_golden as fp8_golden_mod |
| 28 | +import quant_flash_attn_hif8_golden as hif8_golden_mod | ||
| 28 | 29 | ||
| 29 | logger = logging.getLogger(__name__) | 30 | logger = logging.getLogger(__name__) |
| 30 | 31 | ||
| @@ -36,9 +37,15 @@ def _apply_golden_globals(params, quant_mode=1): | |||
| 36 | 必须在调 prepare_npu_inputs 前把 csv attributes 全部注入. | 37 | 必须在调 prepare_npu_inputs 前把 csv attributes 全部注入. |
| 37 | 38 | ||
| 38 | quant_mode=6 → fp8_golden_mod (GQA FP8 全量化路径) | 39 | quant_mode=6 → fp8_golden_mod (GQA FP8 全量化路径) |
| 40 | + quant_mode=0 → hif8_golden_mod (HIF8 per-tensor 量化路径) | ||
| 39 | 其他 → mxfp8_golden_mod (MXFP8 路径) | 41 | 其他 → mxfp8_golden_mod (MXFP8 路径) |
| 40 | """ | 42 | """ |
| 41 | - target = fp8_golden_mod if quant_mode == 6 else mxfp8_golden_mod | 43 | + if quant_mode == 6: |
| 44 | + target = fp8_golden_mod | ||
| 45 | + elif quant_mode == 0: | ||
| 46 | + target = hif8_golden_mod | ||
| 47 | + else: | ||
| 48 | + target = mxfp8_golden_mod | ||
| 42 | for k, v in params.items(): | 49 | for k, v in params.items(): |
| 43 | setattr(target, k, v) | 50 | setattr(target, k, v) |
| 44 | 51 | ||
| @@ -232,6 +239,25 @@ class QuantFlashAttnAclGraph(torch.nn.Module): | |||
| 232 | if isinstance(block_table_cpu, torch.Tensor) and enable_pa | 239 | if isinstance(block_table_cpu, torch.Tensor) and enable_pa |
| 233 | else None, | 240 | else None, |
| 234 | ) | 241 | ) |
| 242 | + elif quant_mode == 0: | ||
| 243 | + inputs = hif8_golden_mod.prepare_npu_inputs( | ||
| 244 | + q_fp8, | ||
| 245 | + k_fp8, | ||
| 246 | + v_fp8, | ||
| 247 | + dequant_scale_q_cpu, | ||
| 248 | + dequant_scale_k_cpu, | ||
| 249 | + dequant_scale_v_cpu, | ||
| 250 | + p_scale_cpu, | ||
| 251 | + cu_seqlens_q_list, | ||
| 252 | + cu_seqlens_kv_list, | ||
| 253 | + seqused_q_list, | ||
| 254 | + seqused_kv_list, | ||
| 255 | + max_seqlen_q, | ||
| 256 | + max_seqlen_kv, | ||
| 257 | + block_table_cpu | ||
| 258 | + if isinstance(block_table_cpu, torch.Tensor) and enable_pa | ||
| 259 | + else None, | ||
| 260 | + ) | ||
| 235 | else: | 261 | else: |
| 236 | inputs = mxfp8_golden_mod.prepare_npu_inputs( | 262 | inputs = mxfp8_golden_mod.prepare_npu_inputs( |
| 237 | q_fp8, | 263 | q_fp8, |
| @@ -291,7 +317,7 @@ class QuantFlashAttnAclGraph(torch.nn.Module): | |||
| 291 | seqused_q=seqused_q_t, | 317 | seqused_q=seqused_q_t, |
| 292 | seqused_kv=seqused_kv_t, | 318 | seqused_kv=seqused_kv_t, |
| 293 | v_descale=inputs["dequant_scale_v"], | 319 | v_descale=inputs["dequant_scale_v"], |
| 294 | - batch_size=batch_size, | 320 | + batch_size=batch_size if not is_tnd_q else None, |
| 295 | mask_mode=int(inputs["sparse_mode"]), | 321 | mask_mode=int(inputs["sparse_mode"]), |
| 296 | layout_q=layout_q, | 322 | layout_q=layout_q, |
| 297 | layout_q_descale=inputs["layout_q_descale"], | 323 | layout_q_descale=inputs["layout_q_descale"], |
| @@ -701,3 +701,261 @@ def generate_qfa_gqa_fp8_inputs( | |||
| 701 | tuple(dequant_scale_k.shape), | 701 | tuple(dequant_scale_k.shape), |
| 702 | tuple(dequant_scale_v.shape), | 702 | tuple(dequant_scale_v.shape), |
| 703 | ) | 703 | ) |
| 704 | + | ||
| 705 | + | ||
| 706 | +def generate_qfa_hif8_inputs( | ||
| 707 | + q: torch.Tensor, | ||
| 708 | + k: torch.Tensor, | ||
| 709 | + v: torch.Tensor, | ||
| 710 | + dequant_scale_q: torch.Tensor, | ||
| 711 | + dequant_scale_k: torch.Tensor, | ||
| 712 | + dequant_scale_v: torch.Tensor, | ||
| 713 | + p_scale: torch.Tensor, | ||
| 714 | + block_table: torch.Tensor, | ||
| 715 | + cu_seqlens_q_t: torch.Tensor, | ||
| 716 | + cu_seqlens_kv_t: torch.Tensor, | ||
| 717 | + seqused_q_t: torch.Tensor, | ||
| 718 | + seqused_kv_t: torch.Tensor, | ||
| 719 | + sinks_t: torch.Tensor, | ||
| 720 | + attn_mask_t: torch.Tensor, | ||
| 721 | + metadata_t: torch.Tensor, | ||
| 722 | + *, | ||
| 723 | + batch_size: int, | ||
| 724 | + N_q: int, | ||
| 725 | + N_kv: int, | ||
| 726 | + D: int, | ||
| 727 | + cu_seqlens_q: List[int], | ||
| 728 | + cu_seqlens_kv: List[int], | ||
| 729 | + seqused_q: List[int], | ||
| 730 | + seqused_kv: List[int], | ||
| 731 | + max_seqlen_q: int, | ||
| 732 | + max_seqlen_kv: int, | ||
| 733 | + enable_pa: bool, | ||
| 734 | + kv_cache_layout: str, | ||
| 735 | + block_size: int, | ||
| 736 | + mask_mode: int, | ||
| 737 | + q_scale_layout: str, | ||
| 738 | + quant_mode: int = 0, | ||
| 739 | + enable_lse: bool = False, | ||
| 740 | + graph_path: int = 0, | ||
| 741 | + input_layout: str = "TND", | ||
| 742 | + layout_q: str = None, | ||
| 743 | + layout_kv: str = None, | ||
| 744 | + layout_out: str = None, | ||
| 745 | + is_contiguous: bool = True, | ||
| 746 | + device_id: int = 0, | ||
| 747 | + softmax_scale: float = None, | ||
| 748 | + data_range_q: float = 1.0, | ||
| 749 | + data_range_k: float = 1.0, | ||
| 750 | + data_range_v: float = 1.0, | ||
| 751 | + **kwargs, | ||
| 752 | +): | ||
| 753 | + """HIF8 输入生成 (quant_mode=0, per-tensor, 仅 TND, 无 PA)。 | ||
| 754 | + | ||
| 755 | + 输出 slot 约定 (in-place 写入 ttk 分配的 numpy slot): | ||
| 756 | + q slot: TND [T_q, N_q, D] uint8 (hifloat8 编码) | ||
| 757 | + k slot: TND [T_kv, N_kv, D] uint8 | ||
| 758 | + v slot: TND [T_kv, N_kv, D] uint8 | ||
| 759 | + dq slot: (1,) float32 per-tensor descale | ||
| 760 | + dk slot: (1,) float32 per-tensor descale | ||
| 761 | + dv slot: (1,) float32 per-tensor descale | ||
| 762 | + p_scale: (1,) float32 | ||
| 763 | + block_table: (0,) int32 (无 PA) | ||
| 764 | + """ | ||
| 765 | + import quant_flash_attn_hif8_golden as hif8_golden_mod | ||
| 766 | + | ||
| 767 | + input_layout = layout_q or input_layout | ||
| 768 | + cu_seqlens_q = list(cu_seqlens_q) if cu_seqlens_q is not None else [0] | ||
| 769 | + cu_seqlens_kv = list(cu_seqlens_kv) if cu_seqlens_kv is not None else [0] | ||
| 770 | + | ||
| 771 | + B = ( | ||
| 772 | + batch_size | ||
| 773 | + if batch_size is not None and batch_size > 0 | ||
| 774 | + else ( | ||
| 775 | + max(1, len(cu_seqlens_q) - 1) | ||
| 776 | + if cu_seqlens_q and len(cu_seqlens_q) >= 2 | ||
| 777 | + else len(list(seqused_q)) | ||
| 778 | + if seqused_q is not None and len(list(seqused_q)) > 0 | ||
| 779 | + else 1 | ||
| 780 | + ) | ||
| 781 | + ) | ||
| 782 | + | ||
| 783 | + if len(cu_seqlens_q) > 1: | ||
| 784 | + actual_seq_q = [ | ||
| 785 | + cu_seqlens_q[i + 1] - cu_seqlens_q[i] for i in range(len(cu_seqlens_q) - 1) | ||
| 786 | + ] | ||
| 787 | + elif seqused_q is not None and len(list(seqused_q)) > 0: | ||
| 788 | + actual_seq_q = list(seqused_q) | ||
| 789 | + elif max_seqlen_q is not None and max_seqlen_q > 0: | ||
| 790 | + actual_seq_q = [max_seqlen_q] * B | ||
| 791 | + else: | ||
| 792 | + actual_seq_q = [0] | ||
| 793 | + if len(cu_seqlens_kv) > 1: | ||
| 794 | + actual_seq_kv = [ | ||
| 795 | + cu_seqlens_kv[i + 1] - cu_seqlens_kv[i] | ||
| 796 | + for i in range(len(cu_seqlens_kv) - 1) | ||
| 797 | + ] | ||
| 798 | + elif seqused_kv is not None and len(list(seqused_kv)) > 0: | ||
| 799 | + actual_seq_kv = list(seqused_kv) | ||
| 800 | + elif max_seqlen_kv is not None and max_seqlen_kv > 0: | ||
| 801 | + actual_seq_kv = [max_seqlen_kv] * B | ||
| 802 | + else: | ||
| 803 | + actual_seq_kv = [0] | ||
| 804 | + | ||
| 805 | + # B 可能为-1 | ||
| 806 | + if B is None or B <= 0: | ||
| 807 | + B = len(actual_seq_q) | ||
| 808 | + | ||
| 809 | + max_sq = max(actual_seq_q) if actual_seq_q else D | ||
| 810 | + max_skv = max(actual_seq_kv) if actual_seq_kv else D | ||
| 811 | + | ||
| 812 | + for gkey, gval in [ | ||
| 813 | + ("B", B), | ||
| 814 | + ("N_q", N_q), | ||
| 815 | + ("N_kv", N_kv), | ||
| 816 | + ("D", D), | ||
| 817 | + ("CU_SEQLENS_Q", cu_seqlens_q), | ||
| 818 | + ("CU_SEQLENS_KV", cu_seqlens_kv if cu_seqlens_kv else None), | ||
| 819 | + ("SEQUSED_Q", list(seqused_q) if seqused_q is not None else None), | ||
| 820 | + ("SEQUSED_KV", list(seqused_kv) if seqused_kv is not None else None), | ||
| 821 | + ("MAX_SEQLEN_Q", max_seqlen_q), | ||
| 822 | + ("MAX_SEQLEN_KV", max_seqlen_kv), | ||
| 823 | + ("SPARSE_MODE", mask_mode), | ||
| 824 | + ("Q_SCALE_LAYOUT", q_scale_layout), | ||
| 825 | + ("INPUT_LAYOUT", input_layout), | ||
| 826 | + ("IS_CONTIGUOUS", is_contiguous), | ||
| 827 | + ("DEVICE_ID", device_id), | ||
| 828 | + ("GRAPH_PATH", graph_path), | ||
| 829 | + ("SOFTMAX_SCALE", softmax_scale), | ||
| 830 | + ]: | ||
| 831 | + setattr(hif8_golden_mod, gkey, gval) | ||
| 832 | + | ||
| 833 | + input_ranges = kwargs.get("input_ranges") | ||
| 834 | + | ||
| 835 | + def _range_of(idx, default=(-1.0, 1.0)): | ||
| 836 | + if input_ranges is None or idx >= len(input_ranges): | ||
| 837 | + return default | ||
| 838 | + r = input_ranges[idx] | ||
| 839 | + if r is None: | ||
| 840 | + return default | ||
| 841 | + return (float(r[0]), float(r[1])) | ||
| 842 | + | ||
| 843 | + rq_min, rq_max = _range_of(0, (-1.0, 1.0)) | ||
| 844 | + rk_min, rk_max = _range_of(1, (-1.0, 1.0)) | ||
| 845 | + rv_min, rv_max = _range_of(2, (-1.0, 1.0)) | ||
| 846 | + | ||
| 847 | + data_range_q_eff = ( | ||
| 848 | + data_range_q if data_range_q is not None and data_range_q > 0 else 1.0 | ||
| 849 | + ) | ||
| 850 | + data_range_k_eff = ( | ||
| 851 | + data_range_k if data_range_k is not None and data_range_k > 0 else 1.0 | ||
| 852 | + ) | ||
| 853 | + data_range_v_eff = ( | ||
| 854 | + data_range_v if data_range_v is not None and data_range_v > 0 else 1.0 | ||
| 855 | + ) | ||
| 856 | + | ||
| 857 | + torch.manual_seed(_SEED_MAP["q"]) | ||
| 858 | + q_fp16 = ( | ||
| 859 | + torch.rand(B, N_q, max_sq, D, dtype=torch.float16) * 2 - 1 | ||
| 860 | + ) * data_range_q_eff | ||
| 861 | + torch.manual_seed(_SEED_MAP["k"]) | ||
| 862 | + k_fp16 = ( | ||
| 863 | + torch.rand(B, N_kv, max_skv, D, dtype=torch.float16) * 2 - 1 | ||
| 864 | + ) * data_range_k_eff | ||
| 865 | + torch.manual_seed(_SEED_MAP["v"]) | ||
| 866 | + v_fp16 = ( | ||
| 867 | + torch.rand(B, N_kv, max_skv, D, dtype=torch.float16) * 2 - 1 | ||
| 868 | + ) * data_range_v_eff | ||
| 869 | + | ||
| 870 | + quant_scale_q = hif8_golden_mod.get_hif8_per_tensor_quant_scale( | ||
| 871 | + q_fp16.to(torch.float32) | ||
| 872 | + ) | ||
| 873 | + quant_scale_k = hif8_golden_mod.get_hif8_per_tensor_quant_scale( | ||
| 874 | + k_fp16.to(torch.float32) | ||
| 875 | + ) | ||
| 876 | + quant_scale_v = hif8_golden_mod.get_hif8_per_tensor_quant_scale( | ||
| 877 | + v_fp16.to(torch.float32) | ||
| 878 | + ) | ||
| 879 | + | ||
| 880 | + q_hif8_bnsd = hif8_golden_mod.hif8_per_tensor_quant( | ||
| 881 | + q_fp16.to(torch.float32), quant_scale_q | ||
| 882 | + ) | ||
| 883 | + k_hif8_bnsd = hif8_golden_mod.hif8_per_tensor_quant( | ||
| 884 | + k_fp16.to(torch.float32), quant_scale_k | ||
| 885 | + ) | ||
| 886 | + v_hif8_bnsd = hif8_golden_mod.hif8_per_tensor_quant( | ||
| 887 | + v_fp16.to(torch.float32), quant_scale_v | ||
| 888 | + ) | ||
| 889 | + | ||
| 890 | + q_final = ( | ||
| 891 | + hif8_golden_mod.convert_q_bnsd_to_layout( | ||
| 892 | + q_hif8_bnsd, | ||
| 893 | + actual_seq_q, | ||
| 894 | + input_layout, | ||
| 895 | + cu_seqlens=cu_seqlens_q | ||
| 896 | + if (input_layout == "TND" and len(cu_seqlens_q) > 1) | ||
| 897 | + else None, | ||
| 898 | + ) | ||
| 899 | + .contiguous() | ||
| 900 | + .view(torch.float8_e4m3fn) | ||
| 901 | + ) | ||
| 902 | + k_final = ( | ||
| 903 | + hif8_golden_mod.convert_kv_bnsd_to_layout( | ||
| 904 | + k_hif8_bnsd, | ||
| 905 | + actual_seq_kv, | ||
| 906 | + input_layout, | ||
| 907 | + cu_seqlens=cu_seqlens_kv | ||
| 908 | + if (input_layout == "TND" and len(cu_seqlens_kv) > 1) | ||
| 909 | + else None, | ||
| 910 | + ) | ||
| 911 | + .contiguous() | ||
| 912 | + .view(torch.float8_e4m3fn) | ||
| 913 | + ) | ||
| 914 | + v_final = ( | ||
| 915 | + hif8_golden_mod.convert_kv_bnsd_to_layout( | ||
| 916 | + v_hif8_bnsd, | ||
| 917 | + actual_seq_kv, | ||
| 918 | + input_layout, | ||
| 919 | + cu_seqlens=cu_seqlens_kv | ||
| 920 | + if (input_layout == "TND" and len(cu_seqlens_kv) > 1) | ||
| 921 | + else None, | ||
| 922 | + ) | ||
| 923 | + .contiguous() | ||
| 924 | + .view(torch.float8_e4m3fn) | ||
| 925 | + ) | ||
| 926 | + | ||
| 927 | + def _inplace_write(dst, src_torch, slot_name): | ||
| 928 | + if tuple(dst.shape) != tuple(src_torch.shape): | ||
| 929 | + raise ValueError( | ||
| 930 | + f"[INPUTS HIF8] {slot_name} shape mismatch: slot {tuple(dst.shape)} " | ||
| 931 | + f"!= computed {tuple(src_torch.shape)}." | ||
| 932 | + ) | ||
| 933 | + dst.copy_(src_torch.view(dst.dtype)) | ||
| 934 | + | ||
| 935 | + _inplace_write(q, q_final, "q (slot 0)") | ||
| 936 | + _inplace_write(k, k_final, "k (slot 1)") | ||
| 937 | + _inplace_write(v, v_final, "v (slot 2)") | ||
| 938 | + _inplace_write(dequant_scale_q, quant_scale_q, "descale_q (slot 3)") | ||
| 939 | + _inplace_write(dequant_scale_k, quant_scale_k, "descale_k (slot 4)") | ||
| 940 | + _inplace_write(dequant_scale_v, quant_scale_v, "descale_v (slot 5)") | ||
| 941 | + | ||
| 942 | + p_scale_value = kwargs.get("p_scale_value", 1.0) | ||
| 943 | + if isinstance(p_scale_value, torch.Tensor): | ||
| 944 | + p_scale_value = float(p_scale_value.item()) | ||
| 945 | + p_scale.copy_(torch.tensor([float(p_scale_value)], dtype=torch.float32)) | ||
| 946 | + block_table.copy_(torch.zeros_like(block_table)) | ||
| 947 | + | ||
| 948 | + # ----- slot 8-14: 用 attributes 真实值覆盖 ttk 随机生成的 cu_seqlens/seqused ----- | ||
| 949 | + _write_int32_list(cu_seqlens_q_t, cu_seqlens_q, "cu_seqlens_q (slot 8)") | ||
| 950 | + _write_int32_list(cu_seqlens_kv_t, cu_seqlens_kv, "cu_seqlens_kv (slot 9)") | ||
| 951 | + _write_int32_list(seqused_q_t, seqused_q, "seqused_q (slot 10)") | ||
| 952 | + _write_int32_list(seqused_kv_t, seqused_kv, "seqused_kv (slot 11)") | ||
| 953 | + | ||
| 954 | + logger.info( | ||
| 955 | + "[INPUTS] HIF8 in-place wrote q/k/v (q=%s), fp32 descale (dq=%s, dk=%s, dv=%s), " | ||
| 956 | + "fp32 p_scale, int32 block_table (pa=False)", | ||
| 957 | + tuple(q.shape), | ||
| 958 | + tuple(dequant_scale_q.shape), | ||
| 959 | + tuple(dequant_scale_k.shape), | ||
| 960 | + tuple(dequant_scale_v.shape), | ||
| 961 | + ) | ||
| @@ -38,6 +38,7 @@ if _TESTS_DIR not in sys.path: | |||
| 38 | sys.path.insert(0, _TESTS_DIR) | 38 | sys.path.insert(0, _TESTS_DIR) |
| 39 | import quant_flash_attn_golden as mxfp8_golden_mod | 39 | import quant_flash_attn_golden as mxfp8_golden_mod |
| 40 | import quant_flash_attn_fp8_golden as fp8_golden_mod | 40 | import quant_flash_attn_fp8_golden as fp8_golden_mod |
| 41 | +import quant_flash_attn_hif8_golden as hif8_golden_mod | ||
| 41 | 42 | ||
| 42 | logger = logging.getLogger(__name__) | 43 | logger = logging.getLogger(__name__) |
| 43 | 44 | ||
| @@ -46,9 +47,15 @@ def _apply_golden_globals(params, quant_mode=1): | |||
| 46 | """把 case 参数注入 golden 模块全局变量 (按 quant_mode 选择目标模块). | 47 | """把 case 参数注入 golden 模块全局变量 (按 quant_mode 选择目标模块). |
| 47 | 48 | ||
| 48 | quant_mode=6 → fp8_golden_mod (GQA FP8 全量化路径) | 49 | quant_mode=6 → fp8_golden_mod (GQA FP8 全量化路径) |
| 50 | + quant_mode=0 → hif8_golden_mod (HIF8 per-tensor 量化路径) | ||
| 49 | 其他 → mxfp8_golden_mod (MXFP8 路径) | 51 | 其他 → mxfp8_golden_mod (MXFP8 路径) |
| 50 | """ | 52 | """ |
| 51 | - target = fp8_golden_mod if quant_mode == 6 else mxfp8_golden_mod | 53 | + if quant_mode == 6: |
| 54 | + target = fp8_golden_mod | ||
| 55 | + elif quant_mode == 0: | ||
| 56 | + target = hif8_golden_mod | ||
| 57 | + else: | ||
| 58 | + target = mxfp8_golden_mod | ||
| 52 | for k, v in params.items(): | 59 | for k, v in params.items(): |
| 53 | setattr(target, k, v) | 60 | setattr(target, k, v) |
| 54 | 61 | ||
| @@ -199,6 +206,17 @@ def run_main( | |||
| 199 | q_fp8 = fp8_golden_mod.quant_fp16_to_fp8(q_cpu, quant_scale_q) | 206 | q_fp8 = fp8_golden_mod.quant_fp16_to_fp8(q_cpu, quant_scale_q) |
| 200 | k_fp8 = fp8_golden_mod.quant_fp16_to_fp8(k_cpu, quant_scale_k) | 207 | k_fp8 = fp8_golden_mod.quant_fp16_to_fp8(k_cpu, quant_scale_k) |
| 201 | v_fp8 = fp8_golden_mod.quant_fp16_to_fp8(v_cpu, quant_scale_v) | 208 | v_fp8 = fp8_golden_mod.quant_fp16_to_fp8(v_cpu, quant_scale_v) |
| 209 | + elif quant_mode == 0: | ||
| 210 | + # HIF8 per-tensor (Q/K/V per-tensor quant, descale=FP32 scalar) | ||
| 211 | + quant_scale_q = hif8_golden_mod.get_hif8_per_tensor_quant_scale(q_cpu) | ||
| 212 | + quant_scale_k = hif8_golden_mod.get_hif8_per_tensor_quant_scale(k_cpu) | ||
| 213 | + quant_scale_v = hif8_golden_mod.get_hif8_per_tensor_quant_scale(v_cpu) | ||
| 214 | + deq_q = quant_scale_q | ||
| 215 | + deq_k = quant_scale_k | ||
| 216 | + deq_v = quant_scale_v | ||
| 217 | + q_fp8 = hif8_golden_mod.hif8_per_tensor_quant(q_cpu, quant_scale_q) | ||
| 218 | + k_fp8 = hif8_golden_mod.hif8_per_tensor_quant(k_cpu, quant_scale_k) | ||
| 219 | + v_fp8 = hif8_golden_mod.hif8_per_tensor_quant(v_cpu, quant_scale_v) | ||
| 202 | else: | 220 | else: |
| 203 | # MXFP8 (per-token-group Q/K, per-channel-group V, descale=e8m0) | 221 | # MXFP8 (per-token-group Q/K, per-channel-group V, descale=e8m0) |
| 204 | quant_scale_q = mxfp8_golden_mod.get_mxfp8_per_token_group_quant_scale( | 222 | quant_scale_q = mxfp8_golden_mod.get_mxfp8_per_token_group_quant_scale( |
| @@ -235,7 +253,7 @@ def run_main( | |||
| 235 | .to(fp8_dtype) | 253 | .to(fp8_dtype) |
| 236 | ) | 254 | ) |
| 237 | 255 | ||
| 238 | - # 按 quant_mode 派发 prepare_npu_inputs (mxfp8 / gqa_fp8 路径 layout 不同) | 256 | + # 按 quant_mode 派发 prepare_npu_inputs (mxfp8 / gqa_fp8 / hif8 路径 layout 不同) |
| 239 | if quant_mode == 6: | 257 | if quant_mode == 6: |
| 240 | inputs = fp8_golden_mod.prepare_npu_inputs_gqa_fp8( | 258 | inputs = fp8_golden_mod.prepare_npu_inputs_gqa_fp8( |
| 241 | q_fp8, | 259 | q_fp8, |
| @@ -255,6 +273,25 @@ def run_main( | |||
| 255 | if isinstance(block_table_cpu, torch.Tensor) and enable_pa | 273 | if isinstance(block_table_cpu, torch.Tensor) and enable_pa |
| 256 | else None, | 274 | else None, |
| 257 | ) | 275 | ) |
| 276 | + elif quant_mode == 0: | ||
| 277 | + inputs = hif8_golden_mod.prepare_npu_inputs( | ||
| 278 | + q_fp8, | ||
| 279 | + k_fp8, | ||
| 280 | + v_fp8, | ||
| 281 | + deq_q, | ||
| 282 | + deq_k, | ||
| 283 | + deq_v, | ||
| 284 | + p_scale_cpu, | ||
| 285 | + cu_seqlens_q_list, | ||
| 286 | + cu_seqlens_kv_list, | ||
| 287 | + seqused_q_list, | ||
| 288 | + seqused_kv_list, | ||
| 289 | + max_seqlen_q, | ||
| 290 | + max_seqlen_kv, | ||
| 291 | + block_table_cpu | ||
| 292 | + if isinstance(block_table_cpu, torch.Tensor) and enable_pa | ||
| 293 | + else None, | ||
| 294 | + ) | ||
| 258 | else: | 295 | else: |
| 259 | inputs = mxfp8_golden_mod.prepare_npu_inputs( | 296 | inputs = mxfp8_golden_mod.prepare_npu_inputs( |
| 260 | q_fp8, | 297 | q_fp8, |
| @@ -295,7 +332,7 @@ def run_main( | |||
| 295 | seqused_q=seqused_q_t, | 332 | seqused_q=seqused_q_t, |
| 296 | seqused_kv=seqused_kv_t, | 333 | seqused_kv=seqused_kv_t, |
| 297 | v_descale=inputs["dequant_scale_v"], | 334 | v_descale=inputs["dequant_scale_v"], |
| 298 | - batch_size=batch_size, | 335 | + batch_size=batch_size if not is_tnd_q else None, |
| 299 | mask_mode=inputs["sparse_mode"], | 336 | mask_mode=inputs["sparse_mode"], |
| 300 | layout_q=layout_q, | 337 | layout_q=layout_q, |
| 301 | layout_q_descale=inputs["layout_q_descale"], | 338 | layout_q_descale=inputs["layout_q_descale"], |
| @@ -347,6 +384,8 @@ def run_main( | |||
| 347 | act_seqused_q = ( | 384 | act_seqused_q = ( |
| 348 | fp8_golden_mod._actual_seq_q() | 385 | fp8_golden_mod._actual_seq_q() |
| 349 | if quant_mode == 6 | 386 | if quant_mode == 6 |
| 387 | + else hif8_golden_mod._actual_seq_q() | ||
| 388 | + if quant_mode == 0 | ||
| 350 | else mxfp8_golden_mod._actual_seq_q() | 389 | else mxfp8_golden_mod._actual_seq_q() |
| 351 | ) | 390 | ) |
| 352 | # T_actual: 以 actual_seq_q (seqused_q 优先, 否则从 cu_seqlens_q 差分) 为准, | 391 | # T_actual: 以 actual_seq_q (seqused_q 优先, 否则从 cu_seqlens_q 差分) 为准, |
| @@ -35,6 +35,7 @@ if _TESTS_DIR not in sys.path: | |||
| 35 | sys.path.insert(0, _TESTS_DIR) | 35 | sys.path.insert(0, _TESTS_DIR) |
| 36 | import quant_flash_attn_golden as mxfp8_golden_mod | 36 | import quant_flash_attn_golden as mxfp8_golden_mod |
| 37 | import quant_flash_attn_fp8_golden as fp8_golden_mod | 37 | import quant_flash_attn_fp8_golden as fp8_golden_mod |
| 38 | +import quant_flash_attn_hif8_golden as hif8_golden_mod | ||
| 38 | 39 | ||
| 39 | logger = logging.getLogger(__name__) | 40 | logger = logging.getLogger(__name__) |
| 40 | 41 | ||
| @@ -43,9 +44,15 @@ def _apply_golden_globals(params, quant_mode=1): | |||
| 43 | """把 case 参数注入 golden 模块全局变量 (按 quant_mode 选择目标模块). | 44 | """把 case 参数注入 golden 模块全局变量 (按 quant_mode 选择目标模块). |
| 44 | 45 | ||
| 45 | quant_mode=6 → fp8_golden_mod (GQA FP8 全量化路径) | 46 | quant_mode=6 → fp8_golden_mod (GQA FP8 全量化路径) |
| 47 | + quant_mode=0 → hif8_golden_mod (HIF8 per-tensor 量化路径) | ||
| 46 | 其他 → mxfp8_golden_mod (MXFP8 路径) | 48 | 其他 → mxfp8_golden_mod (MXFP8 路径) |
| 47 | """ | 49 | """ |
| 48 | - target = fp8_golden_mod if quant_mode == 6 else mxfp8_golden_mod | 50 | + if quant_mode == 6: |
| 51 | + target = fp8_golden_mod | ||
| 52 | + elif quant_mode == 0: | ||
| 53 | + target = hif8_golden_mod | ||
| 54 | + else: | ||
| 55 | + target = mxfp8_golden_mod | ||
| 49 | for k, v in params.items(): | 56 | for k, v in params.items(): |
| 50 | setattr(target, k, v) | 57 | setattr(target, k, v) |
| 51 | 58 | ||
| @@ -196,6 +203,17 @@ def run_metadata( | |||
| 196 | q_fp8 = fp8_golden_mod.quant_fp16_to_fp8(q_cpu, quant_scale_q) | 203 | q_fp8 = fp8_golden_mod.quant_fp16_to_fp8(q_cpu, quant_scale_q) |
| 197 | k_fp8 = fp8_golden_mod.quant_fp16_to_fp8(k_cpu, quant_scale_k) | 204 | k_fp8 = fp8_golden_mod.quant_fp16_to_fp8(k_cpu, quant_scale_k) |
| 198 | v_fp8 = fp8_golden_mod.quant_fp16_to_fp8(v_cpu, quant_scale_v) | 205 | v_fp8 = fp8_golden_mod.quant_fp16_to_fp8(v_cpu, quant_scale_v) |
| 206 | + elif quant_mode == 0: | ||
| 207 | + # HIF8 per-tensor (Q/K/V per-tensor quant, descale=FP32 scalar) | ||
| 208 | + quant_scale_q = hif8_golden_mod.get_hif8_per_tensor_quant_scale(q_cpu) | ||
| 209 | + quant_scale_k = hif8_golden_mod.get_hif8_per_tensor_quant_scale(k_cpu) | ||
| 210 | + quant_scale_v = hif8_golden_mod.get_hif8_per_tensor_quant_scale(v_cpu) | ||
| 211 | + deq_q = quant_scale_q | ||
| 212 | + deq_k = quant_scale_k | ||
| 213 | + deq_v = quant_scale_v | ||
| 214 | + q_fp8 = hif8_golden_mod.hif8_per_tensor_quant(q_cpu, quant_scale_q) | ||
| 215 | + k_fp8 = hif8_golden_mod.hif8_per_tensor_quant(k_cpu, quant_scale_k) | ||
| 216 | + v_fp8 = hif8_golden_mod.hif8_per_tensor_quant(v_cpu, quant_scale_v) | ||
| 199 | else: | 217 | else: |
| 200 | # MXFP8 (per-token-group Q/K, per-channel-group V, descale=e8m0) | 218 | # MXFP8 (per-token-group Q/K, per-channel-group V, descale=e8m0) |
| 201 | quant_scale_q = mxfp8_golden_mod.get_mxfp8_per_token_group_quant_scale( | 219 | quant_scale_q = mxfp8_golden_mod.get_mxfp8_per_token_group_quant_scale( |
| @@ -252,6 +270,25 @@ def run_metadata( | |||
| 252 | if isinstance(block_table_cpu, torch.Tensor) and enable_pa | 270 | if isinstance(block_table_cpu, torch.Tensor) and enable_pa |
| 253 | else None, | 271 | else None, |
| 254 | ) | 272 | ) |
| 273 | + elif quant_mode == 0: | ||
| 274 | + inputs = hif8_golden_mod.prepare_npu_inputs( | ||
| 275 | + q_fp8, | ||
| 276 | + k_fp8, | ||
| 277 | + v_fp8, | ||
| 278 | + deq_q, | ||
| 279 | + deq_k, | ||
| 280 | + deq_v, | ||
| 281 | + p_scale_cpu, | ||
| 282 | + cu_seqlens_q_list, | ||
| 283 | + cu_seqlens_kv_list, | ||
| 284 | + seqused_q_list, | ||
| 285 | + seqused_kv_list, | ||
| 286 | + max_seqlen_q, | ||
| 287 | + max_seqlen_kv, | ||
| 288 | + block_table_cpu | ||
| 289 | + if isinstance(block_table_cpu, torch.Tensor) and enable_pa | ||
| 290 | + else None, | ||
| 291 | + ) | ||
| 255 | else: | 292 | else: |
| 256 | inputs = mxfp8_golden_mod.prepare_npu_inputs( | 293 | inputs = mxfp8_golden_mod.prepare_npu_inputs( |
| 257 | q_fp8, | 294 | q_fp8, |
| @@ -292,7 +329,7 @@ def run_metadata( | |||
| 292 | seqused_q=seqused_q_t, | 329 | seqused_q=seqused_q_t, |
| 293 | seqused_kv=seqused_kv_t, | 330 | seqused_kv=seqused_kv_t, |
| 294 | v_descale=inputs["dequant_scale_v"], | 331 | v_descale=inputs["dequant_scale_v"], |
| 295 | - batch_size=batch_size, | 332 | + batch_size=batch_size if not is_tnd_q else None, |
| 296 | mask_mode=inputs["sparse_mode"], | 333 | mask_mode=inputs["sparse_mode"], |
| 297 | layout_q=layout_q, | 334 | layout_q=layout_q, |
| 298 | layout_q_descale=inputs["layout_q_descale"], | 335 | layout_q_descale=inputs["layout_q_descale"], |
| @@ -1,228 +1,258 @@ | |||
| 1 | -#!/usr/bin/python3 | 1 | +#!/usr/bin/python3 |
| 2 | -# -*- coding: utf-8 -*- | 2 | +# -*- coding: utf-8 -*- |
| 3 | -# ----------------------------------------------------------------------------------------------------------- | 3 | +# ----------------------------------------------------------------------------------------------------------- |
| 4 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. | 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. |
| 5 | -# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of |
| 6 | -# CANN Open Software License Agreement Version 2.0 (the "License"). | 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). |
| 7 | -# Please refer to the License for details. You may not use this file except in compliance with the License. | 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. |
| 8 | -# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, |
| 9 | -# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. |
| 10 | -# See LICENSE in the root of the software repository for the full text of the License. | 10 | +# See LICENSE in the root of the software repository for the full text of the License. |
| 11 | -# ----------------------------------------------------------------------------------------------------------- | 11 | +# ----------------------------------------------------------------------------------------------------------- |
| 12 | - | 12 | + |
| 13 | -import logging | 13 | +import logging |
| 14 | -import os | 14 | +import os |
| 15 | -import sys | 15 | +import sys |
| 16 | - | 16 | + |
| 17 | -import torch | 17 | +import torch |
| 18 | -import torch_npu | 18 | +import torch_npu |
| 19 | - | 19 | + |
| 20 | -_TESTS_DIR = os.path.dirname(os.path.abspath(__file__)) | 20 | +_TESTS_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 21 | -if _TESTS_DIR not in sys.path: | 21 | +if _TESTS_DIR not in sys.path: |
| 22 | - sys.path.insert(0, _TESTS_DIR) | 22 | + sys.path.insert(0, _TESTS_DIR) |
| 23 | -import quant_flash_attn_golden as mxfp8_golden_mod | 23 | +import quant_flash_attn_golden as mxfp8_golden_mod |
| 24 | -import quant_flash_attn_fp8_golden as fp8_golden_mod | 24 | +import quant_flash_attn_fp8_golden as fp8_golden_mod |
| 25 | - | 25 | +import quant_flash_attn_hif8_golden as hif8_golden_mod |
| 26 | - | 26 | + |
| 27 | -logger = logging.getLogger(__name__) | 27 | + |
| 28 | - | 28 | +logger = logging.getLogger(__name__) |
| 29 | - | 29 | + |
| 30 | -def _apply_golden_globals(params, quant_mode=1): | 30 | + |
| 31 | - """把 case 参数注入 golden 模块全局变量 (按 quant_mode 选择目标模块). | 31 | +def _apply_golden_globals(params, quant_mode=1): |
| 32 | - | 32 | + """把 case 参数注入 golden 模块全局变量 (按 quant_mode 选择目标模块). |
| 33 | - quant_mode=6 → fp8_golden_mod (GQA FP8 全量化路径) | 33 | + |
| 34 | - 其他 → mxfp8_golden_mod (MXFP8 路径) | 34 | + quant_mode=6 → fp8_golden_mod (GQA FP8 全量化路径) |
| 35 | - """ | 35 | + quant_mode=0 → hif8_golden_mod (HIF8 per-tensor 量化路径) |
| 36 | - target = fp8_golden_mod if quant_mode == 6 else mxfp8_golden_mod | 36 | + 其他 → mxfp8_golden_mod (MXFP8 路径) |
| 37 | - for k, v in params.items(): | 37 | + """ |
| 38 | - setattr(target, k, v) | 38 | + if quant_mode == 6: |
| 39 | - | 39 | + target = fp8_golden_mod |
| 40 | - | 40 | + elif quant_mode == 0: |
| 41 | -def npu_qfa( | 41 | + target = hif8_golden_mod |
| 42 | - q: torch.Tensor, | 42 | + else: |
| 43 | - k: torch.Tensor, | 43 | + target = mxfp8_golden_mod |
| 44 | - v: torch.Tensor, | 44 | + for k, v in params.items(): |
| 45 | - dequant_scale_q: torch.Tensor, | 45 | + setattr(target, k, v) |
| 46 | - dequant_scale_k: torch.Tensor, | 46 | + |
| 47 | - dequant_scale_v: torch.Tensor, | 47 | + |
| 48 | - p_scale: torch.Tensor, | 48 | +def npu_qfa( |
| 49 | - block_table: torch.Tensor, | 49 | + q: torch.Tensor, |
| 50 | - cu_seqlens_q_t: torch.Tensor, | 50 | + k: torch.Tensor, |
| 51 | - cu_seqlens_kv_t: torch.Tensor, | 51 | + v: torch.Tensor, |
| 52 | - seqused_q_t: torch.Tensor, | 52 | + dequant_scale_q: torch.Tensor, |
| 53 | - seqused_kv_t: torch.Tensor, | 53 | + dequant_scale_k: torch.Tensor, |
| 54 | - sinks_t: torch.Tensor, | 54 | + dequant_scale_v: torch.Tensor, |
| 55 | - attn_mask_t: torch.Tensor, | 55 | + p_scale: torch.Tensor, |
| 56 | - metadata_t: torch.Tensor, | 56 | + block_table: torch.Tensor, |
| 57 | - *, | 57 | + cu_seqlens_q_t: torch.Tensor, |
| 58 | - batch_size: int, | 58 | + cu_seqlens_kv_t: torch.Tensor, |
| 59 | - N_q: int, | 59 | + seqused_q_t: torch.Tensor, |
| 60 | - N_kv: int, | 60 | + seqused_kv_t: torch.Tensor, |
| 61 | - D: int, | 61 | + sinks_t: torch.Tensor, |
| 62 | - max_seqlen_q: int, | 62 | + attn_mask_t: torch.Tensor, |
| 63 | - max_seqlen_kv: int, | 63 | + metadata_t: torch.Tensor, |
| 64 | - enable_pa: bool, | 64 | + *, |
| 65 | - kv_cache_layout: str, | 65 | + batch_size: int, |
| 66 | - block_size: int, | 66 | + N_q: int, |
| 67 | - mask_mode: int, | 67 | + N_kv: int, |
| 68 | - q_scale_layout: str, | 68 | + D: int, |
| 69 | - quant_mode: int = 1, | 69 | + max_seqlen_q: int, |
| 70 | - enable_lse: bool = False, | 70 | + max_seqlen_kv: int, |
| 71 | - graph_path: int = 0, | 71 | + enable_pa: bool, |
| 72 | - input_layout: str = "TND", | 72 | + kv_cache_layout: str, |
| 73 | - is_contiguous: bool = True, | 73 | + block_size: int, |
| 74 | - device_id: int = 0, | 74 | + mask_mode: int, |
| 75 | - softmax_scale: float = None, | 75 | + q_scale_layout: str, |
| 76 | - data_range_q: float = 1.0, | 76 | + quant_mode: int = 1, |
| 77 | - data_range_k: float = 1.0, | 77 | + enable_lse: bool = False, |
| 78 | - data_range_v: float = 1.0, | 78 | + graph_path: int = 0, |
| 79 | - layout_q: str = "TND", | 79 | + input_layout: str = "TND", |
| 80 | - layout_q_descale: str = "TND", | 80 | + is_contiguous: bool = True, |
| 81 | - layout_kv: str = "TND", | 81 | + device_id: int = 0, |
| 82 | - layout_out: str = "TND", | 82 | + softmax_scale: float = None, |
| 83 | - attn_mask_shape: tuple = None, | 83 | + data_range_q: float = 1.0, |
| 84 | - **kwargs, | 84 | + data_range_k: float = 1.0, |
| 85 | -): | 85 | + data_range_v: float = 1.0, |
| 86 | - """qfa_wrapper.npu_qfa — 15 个位置 tensor 与 CSV tensor_view_shapes 顺序一致: | 86 | + layout_q: str = "TND", |
| 87 | - | 87 | + layout_q_descale: str = "TND", |
| 88 | - 0 q, 1 k, 2 v, 3 q_descale, 4 k_descale, 5 v_descale, 6 p_scale, 7 block_table, | 88 | + layout_kv: str = "TND", |
| 89 | - 8 cu_seqlens_q, 9 cu_seqlens_kv, 10 seqused_q, 11 seqused_kv, | 89 | + layout_out: str = "TND", |
| 90 | - 12 sinks, 13 attn_mask, 14 metadata. | 90 | + attn_mask_shape: tuple = None, |
| 91 | - | 91 | + **kwargs, |
| 92 | - slot 8-14 的 tensor 值由 inputs.py (customize_inputs) 用 attributes 真实值覆盖; | 92 | +): |
| 93 | - 本函数从 cu_seqlens_q_t/seqused_q_t 等 tensor(.cpu().tolist())读回 list 计算。 | 93 | + """qfa_wrapper.npu_qfa — 15 个位置 tensor 与 CSV tensor_view_shapes 顺序一致: |
| 94 | - """ | 94 | + |
| 95 | - torch_npu.npu.set_device(int(device_id)) | 95 | + 0 q, 1 k, 2 v, 3 q_descale, 4 k_descale, 5 v_descale, 6 p_scale, 7 block_table, |
| 96 | - env_graph_path = os.environ.get("GRAPH_PATH") | 96 | + 8 cu_seqlens_q, 9 cu_seqlens_kv, 10 seqused_q, 11 seqused_kv, |
| 97 | - if env_graph_path is not None: | 97 | + 12 sinks, 13 attn_mask, 14 metadata. |
| 98 | - graph_path = int(env_graph_path) | 98 | + |
| 99 | - logger.info( | 99 | + slot 8-14 的 tensor 值由 inputs.py (customize_inputs) 用 attributes 真实值覆盖; |
| 100 | - "[WRAPPER] 使用环境变量 GRAPH_PATH=%d (覆盖 CSV graph_path)", graph_path | 100 | + 本函数从 cu_seqlens_q_t/seqused_q_t 等 tensor(.cpu().tolist())读回 list 计算。 |
| 101 | - ) | 101 | + """ |
| 102 | - | 102 | + torch_npu.npu.set_device(int(device_id)) |
| 103 | - # cu_seqlens/seqused 的真实值已由 inputs.py in-place 写入 tensor slot (_t), | 103 | + env_graph_path = os.environ.get("GRAPH_PATH") |
| 104 | - # 这里从 tensor 读回 list(wrapper 端 _t 在 NPU,需 .cpu().tolist())。 | 104 | + if env_graph_path is not None: |
| 105 | - def _tolist_t(t): | 105 | + graph_path = int(env_graph_path) |
| 106 | - if t is None: | 106 | + logger.info( |
| 107 | - return None | 107 | + "[WRAPPER] 使用环境变量 GRAPH_PATH=%d (覆盖 CSV graph_path)", graph_path |
| 108 | - return t.detach().cpu().tolist() if t.numel() > 0 else None | 108 | + ) |
| 109 | - | 109 | + |
| 110 | - cu_seqlens_q_list = _tolist_t(cu_seqlens_q_t) | 110 | + # cu_seqlens/seqused 的真实值已由 inputs.py in-place 写入 tensor slot (_t), |
| 111 | - cu_seqlens_kv_list = _tolist_t(cu_seqlens_kv_t) | 111 | + # 这里从 tensor 读回 list(wrapper 端 _t 在 NPU,需 .cpu().tolist())。 |
| 112 | - seqused_q_list = _tolist_t(seqused_q_t) | 112 | + def _tolist_t(t): |
| 113 | - seqused_kv_list = _tolist_t(seqused_kv_t) | 113 | + if t is None: |
| 114 | - | 114 | + return None |
| 115 | - # batch_size: CSV 原始值 (可为 -1), 透传给 metadata 的 batch_size; | 115 | + return t.detach().cpu().tolist() if t.numel() > 0 else None |
| 116 | - # B: 从 cu_seqlens_q 推导的正整数, 供 inputs/golden 生成 BNSD 张量。 | 116 | + |
| 117 | - B = ( | 117 | + cu_seqlens_q_list = _tolist_t(cu_seqlens_q_t) |
| 118 | - max(1, len(cu_seqlens_q_list) - 1) | 118 | + cu_seqlens_kv_list = _tolist_t(cu_seqlens_kv_t) |
| 119 | - if cu_seqlens_q_list and len(cu_seqlens_q_list) >= 2 | 119 | + seqused_q_list = _tolist_t(seqused_q_t) |
| 120 | - else 1 | 120 | + seqused_kv_list = _tolist_t(seqused_kv_t) |
| 121 | - ) | 121 | + |
| 122 | - | 122 | + # batch_size: CSV 原始值 (可为 -1), 透传给 metadata 的 batch_size; |
| 123 | - attn_mask_shape = tuple(attn_mask_t.shape) | 123 | + # B: 从 cu_seqlens_q 推导的正整数, 供 inputs/golden 生成 BNSD 张量。 |
| 124 | - | 124 | + B = ( |
| 125 | - _apply_golden_globals( | 125 | + max(1, len(cu_seqlens_q_list) - 1) |
| 126 | - { | 126 | + if cu_seqlens_q_list and len(cu_seqlens_q_list) >= 2 |
| 127 | - "B": B, | 127 | + else 1 |
| 128 | - "BATCH_SIZE": batch_size, | 128 | + ) |
| 129 | - "N_q": N_q, | 129 | + |
| 130 | - "N_kv": N_kv, | 130 | + attn_mask_shape = tuple(attn_mask_t.shape) |
| 131 | - "D": D, | 131 | + |
| 132 | - "CU_SEQLENS_Q": cu_seqlens_q_list, | 132 | + _apply_golden_globals( |
| 133 | - "CU_SEQLENS_KV": cu_seqlens_kv_list, | 133 | + { |
| 134 | - "SEQUSED_Q": seqused_q_list, | 134 | + "B": B, |
| 135 | - "SEQUSED_KV": seqused_kv_list, | 135 | + "BATCH_SIZE": batch_size, |
| 136 | - "MAX_SEQLEN_Q": max_seqlen_q, | 136 | + "N_q": N_q, |
| 137 | - "MAX_SEQLEN_KV": max_seqlen_kv, | 137 | + "N_kv": N_kv, |
| 138 | - "ENABLE_PA": enable_pa, | 138 | + "D": D, |
| 139 | - "KV_CACHE_LAYOUT": kv_cache_layout, | 139 | + "CU_SEQLENS_Q": cu_seqlens_q_list, |
| 140 | - "BLOCK_SIZE": block_size, | 140 | + "CU_SEQLENS_KV": cu_seqlens_kv_list, |
| 141 | - "SPARSE_MODE": mask_mode, | 141 | + "SEQUSED_Q": seqused_q_list, |
| 142 | - "ATTN_MASK_SHAPE": attn_mask_shape or (2048, 2048), | 142 | + "SEQUSED_KV": seqused_kv_list, |
| 143 | - "Q_SCALE_LAYOUT": q_scale_layout, | 143 | + "MAX_SEQLEN_Q": max_seqlen_q, |
| 144 | - "P_SCALE": (float(p_scale.item()) if p_scale.numel() > 0 else None) | 144 | + "MAX_SEQLEN_KV": max_seqlen_kv, |
| 145 | - if isinstance(p_scale, torch.Tensor) | 145 | + "ENABLE_PA": enable_pa, |
| 146 | - else float(p_scale), | 146 | + "KV_CACHE_LAYOUT": kv_cache_layout, |
| 147 | - "ENABLE_LSE": enable_lse, | 147 | + "BLOCK_SIZE": block_size, |
| 148 | - "FP8_DTYPE": torch.float8_e4m3fn, | 148 | + "SPARSE_MODE": mask_mode, |
| 149 | - "QUANT_MODE": quant_mode, | 149 | + "ATTN_MASK_SHAPE": attn_mask_shape or (2048, 2048), |
| 150 | - "QUANT_GROUP_SIZE": 32, | 150 | + "Q_SCALE_LAYOUT": q_scale_layout, |
| 151 | - "INPUT_LAYOUT": input_layout, | 151 | + "P_SCALE": (float(p_scale.item()) if p_scale.numel() > 0 else None) |
| 152 | - "IS_CONTIGUOUS": is_contiguous, | 152 | + if isinstance(p_scale, torch.Tensor) |
| 153 | - "DEVICE_ID": device_id, | 153 | + else float(p_scale), |
| 154 | - "GRAPH_PATH": graph_path, | 154 | + "ENABLE_LSE": enable_lse, |
| 155 | - "SOFTMAX_SCALE": softmax_scale, | 155 | + "FP8_DTYPE": torch.float8_e4m3fn, |
| 156 | - "LAYOUT_Q": layout_q, | 156 | + "QUANT_MODE": quant_mode, |
| 157 | - "LAYOUT_Q_DESCALE": layout_q_descale, | 157 | + "QUANT_GROUP_SIZE": 32, |
| 158 | - "LAYOUT_KV": layout_kv, | 158 | + "INPUT_LAYOUT": input_layout, |
| 159 | - "LAYOUT_OUT": layout_out, | 159 | + "IS_CONTIGUOUS": is_contiguous, |
| 160 | - }, | 160 | + "DEVICE_ID": device_id, |
| 161 | - quant_mode=quant_mode, | 161 | + "GRAPH_PATH": graph_path, |
| 162 | - ) | 162 | + "SOFTMAX_SCALE": softmax_scale, |
| 163 | - | 163 | + "LAYOUT_Q": layout_q, |
| 164 | - logger.info( | 164 | + "LAYOUT_Q_DESCALE": layout_q_descale, |
| 165 | - "[WRAPPER] graph_path=%d, quant_mode=%d, 透传 fp8 (q=%s, k=%s, dq=%s, dk=%s)", | 165 | + "LAYOUT_KV": layout_kv, |
| 166 | - graph_path, | 166 | + "LAYOUT_OUT": layout_out, |
| 167 | - quant_mode, | 167 | + }, |
| 168 | - tuple(q.shape), | 168 | + quant_mode=quant_mode, |
| 169 | - tuple(k.shape), | 169 | + ) |
| 170 | - tuple(dequant_scale_q.shape), | 170 | + |
| 171 | - tuple(dequant_scale_k.shape), | 171 | + logger.info( |
| 172 | - ) | 172 | + "[WRAPPER] graph_path=%d, quant_mode=%d, 透传 fp8 (q=%s, k=%s, dq=%s, dk=%s)", |
| 173 | - try: | 173 | + graph_path, |
| 174 | - if quant_mode == 6: | 174 | + quant_mode, |
| 175 | - atten_out, lse_out = fp8_golden_mod.npu_gqa_fp8_fa( | 175 | + tuple(q.shape), |
| 176 | - q, | 176 | + tuple(k.shape), |
| 177 | - k, | 177 | + tuple(dequant_scale_q.shape), |
| 178 | - v, | 178 | + tuple(dequant_scale_k.shape), |
| 179 | - dequant_scale_q, | 179 | + ) |
| 180 | - dequant_scale_k, | 180 | + try: |
| 181 | - dequant_scale_v, | 181 | + if quant_mode == 6: |
| 182 | - p_scale, | 182 | + atten_out, lse_out = fp8_golden_mod.npu_gqa_fp8_fa( |
| 183 | - cu_seqlens_q_list, | 183 | + q, |
| 184 | - cu_seqlens_kv_list, | 184 | + k, |
| 185 | - seqused_q_list, | 185 | + v, |
| 186 | - seqused_kv_list, | 186 | + dequant_scale_q, |
| 187 | - max_seqlen_q, | 187 | + dequant_scale_k, |
| 188 | - max_seqlen_kv, | 188 | + dequant_scale_v, |
| 189 | - block_table | 189 | + p_scale, |
| 190 | - if isinstance(block_table, torch.Tensor) and enable_pa | 190 | + cu_seqlens_q_list, |
| 191 | - else None, | 191 | + cu_seqlens_kv_list, |
| 192 | - cu_seqlens_q_t=cu_seqlens_q_t, | 192 | + seqused_q_list, |
| 193 | - cu_seqlens_kv_t=cu_seqlens_kv_t, | 193 | + seqused_kv_list, |
| 194 | - seqused_q_t=seqused_q_t, | 194 | + max_seqlen_q, |
| 195 | - seqused_kv_t=seqused_kv_t, | 195 | + max_seqlen_kv, |
| 196 | - ) | 196 | + block_table |
| 197 | - else: | 197 | + if isinstance(block_table, torch.Tensor) and enable_pa |
| 198 | - atten_out, lse_out = mxfp8_golden_mod.npu_mxfp8_fa( | 198 | + else None, |
| 199 | - q, | 199 | + cu_seqlens_q_t=cu_seqlens_q_t, |
| 200 | - k, | 200 | + cu_seqlens_kv_t=cu_seqlens_kv_t, |
| 201 | - v, | 201 | + seqused_q_t=seqused_q_t, |
| 202 | - dequant_scale_q, | 202 | + seqused_kv_t=seqused_kv_t, |
| 203 | - dequant_scale_k, | 203 | + ) |
| 204 | - dequant_scale_v, | 204 | + elif quant_mode == 0: |
| 205 | - p_scale, | 205 | + atten_out, lse_out = hif8_golden_mod.npu_hif8_fa( |
| 206 | - cu_seqlens_q_list, | 206 | + q, |
| 207 | - cu_seqlens_kv_list, | 207 | + k, |
| 208 | - seqused_q_list, | 208 | + v, |
| 209 | - seqused_kv_list, | 209 | + dequant_scale_q, |
| 210 | - max_seqlen_q, | 210 | + dequant_scale_k, |
| 211 | - max_seqlen_kv, | 211 | + dequant_scale_v, |
| 212 | - block_table | 212 | + p_scale, |
| 213 | - if isinstance(block_table, torch.Tensor) and enable_pa | 213 | + cu_seqlens_q_list, |
| 214 | - else None, | 214 | + cu_seqlens_kv_list, |
| 215 | - cu_seqlens_q_t=cu_seqlens_q_t, | 215 | + seqused_q_list, |
| 216 | - cu_seqlens_kv_t=cu_seqlens_kv_t, | 216 | + seqused_kv_list, |
| 217 | - seqused_q_t=seqused_q_t, | 217 | + max_seqlen_q, |
| 218 | - seqused_kv_t=seqused_kv_t, | 218 | + max_seqlen_kv, |
| 219 | - ) | 219 | + block_table |
| 220 | - except Exception as e: | 220 | + if isinstance(block_table, torch.Tensor) and enable_pa |
| 221 | - logger.error("[WRAPPER] NPU 调用失败: %s", str(e)) | 221 | + else None, |
| 222 | - raise | 222 | + cu_seqlens_q_t=cu_seqlens_q_t, |
| 223 | - | 223 | + cu_seqlens_kv_t=cu_seqlens_kv_t, |
| 224 | - if not enable_lse: | 224 | + seqused_q_t=seqused_q_t, |
| 225 | - lse_out = None | 225 | + seqused_kv_t=seqused_kv_t, |
| 226 | - else: | 226 | + ) |
| 227 | - lse_out = lse_out[:, : atten_out.shape[0]].contiguous() | 227 | + else: |
| 228 | - return atten_out, lse_out | 228 | + atten_out, lse_out = mxfp8_golden_mod.npu_mxfp8_fa( |
| 229 | + q, | ||
| 230 | + k, | ||
| 231 | + v, | ||
| 232 | + dequant_scale_q, | ||
| 233 | + dequant_scale_k, | ||
| 234 | + dequant_scale_v, | ||
| 235 | + p_scale, | ||
| 236 | + cu_seqlens_q_list, | ||
| 237 | + cu_seqlens_kv_list, | ||
| 238 | + seqused_q_list, | ||
| 239 | + seqused_kv_list, | ||
| 240 | + max_seqlen_q, | ||
| 241 | + max_seqlen_kv, | ||
| 242 | + block_table | ||
| 243 | + if isinstance(block_table, torch.Tensor) and enable_pa | ||
| 244 | + else None, | ||
| 245 | + cu_seqlens_q_t=cu_seqlens_q_t, | ||
| 246 | + cu_seqlens_kv_t=cu_seqlens_kv_t, | ||
| 247 | + seqused_q_t=seqused_q_t, | ||
| 248 | + seqused_kv_t=seqused_kv_t, | ||
| 249 | + ) | ||
| 250 | + except Exception as e: | ||
| 251 | + logger.error("[WRAPPER] NPU 调用失败: %s", str(e)) | ||
| 252 | + raise | ||
| 253 | + | ||
| 254 | + if not enable_lse: | ||
| 255 | + lse_out = None | ||
| 256 | + else: | ||
| 257 | + lse_out = lse_out[:, : atten_out.shape[0]].contiguous() | ||
| 258 | + return atten_out, lse_out | ||


1、此处应该使用AdjustSinnerAndSouter获取基本块大小,否则可能与metadata获取的不一致 2、调用时需要注意win_left和win_right在-1时,是否需要转换为正无穷传入。非常重要,非量化已经碰到bug了