Merged
feat: support QLI v2 MXFP8 and MXFP4 #9139
shanhangyangAdd on Jul 24
feat: support QLI v2 MXFP8 and MXFP4 #9139
Merged
Total: 27 files changed+4871-2377
Mattention/lightning_indexer_v2/op_kernel/arch35/vf/common/lightning_indexer_v2_vector1_base.h+59-57
| @@ -24,25 +24,25 @@ struct UIntSortTraits; | |||
| 24 | template <> | 24 | template <> |
| 25 | struct UIntSortTraits<float> { | 25 | struct UIntSortTraits<float> { |
| 26 | using UInt = uint32_t; | 26 | using UInt = uint32_t; |
| 27 | - static constexpr UInt ZERO = 0x00000000; | 27 | + static constexpr UInt ZERO = 0x00000000; |
| 28 | static constexpr UInt SIGN_MASK = 0x80000000; | 28 | static constexpr UInt SIGN_MASK = 0x80000000; |
| 29 | - static constexpr UInt NAN_MASK = 0xFFC00000; | 29 | + static constexpr UInt NAN_MASK = 0xFFC00000; |
| 30 | - static constexpr UInt ALL_ONE = 0xFFFFFFFF; | 30 | + static constexpr UInt ALL_ONE = 0xFFFFFFFF; |
| 31 | }; | 31 | }; |
| 32 | 32 | ||
| 33 | template <> | 33 | template <> |
| 34 | struct UIntSortTraits<bfloat16_t> { | 34 | struct UIntSortTraits<bfloat16_t> { |
| 35 | using UInt = uint16_t; | 35 | using UInt = uint16_t; |
| 36 | - static constexpr UInt ZERO = 0x0000; | 36 | + static constexpr UInt ZERO = 0x0000; |
| 37 | static constexpr UInt SIGN_MASK = 0x8000; | 37 | static constexpr UInt SIGN_MASK = 0x8000; |
| 38 | - static constexpr UInt NAN_MASK = 0xFFC0; | 38 | + static constexpr UInt NAN_MASK = 0xFFC0; |
| 39 | - static constexpr UInt ALL_ONE = 0xFFFF; | 39 | + static constexpr UInt ALL_ONE = 0xFFFF; |
| 40 | }; | 40 | }; |
| 41 | 41 | ||
| 42 | template <typename FloatT> | 42 | template <typename FloatT> |
| 43 | struct UIntSortConstCtx { | 43 | struct UIntSortConstCtx { |
| 44 | using Traits = UIntSortTraits<FloatT>; | 44 | using Traits = UIntSortTraits<FloatT>; |
| 45 | - using UInt = typename Traits::UInt; | 45 | + using UInt = typename Traits::UInt; |
| 46 | AscendC::MicroAPI::RegTensor<UInt> zeros; | 46 | AscendC::MicroAPI::RegTensor<UInt> zeros; |
| 47 | AscendC::MicroAPI::RegTensor<UInt> allOne; | 47 | AscendC::MicroAPI::RegTensor<UInt> allOne; |
| 48 | AscendC::MicroAPI::RegTensor<UInt> signMask; | 48 | AscendC::MicroAPI::RegTensor<UInt> signMask; |
| @@ -50,47 +50,46 @@ struct UIntSortConstCtx { | |||
| 50 | }; | 50 | }; |
| 51 | 51 | ||
| 52 | template <typename FloatT> | 52 | template <typename FloatT> |
| 53 | -__simd_callee__ inline void InitUIntSortConstCtx(UIntSortConstCtx<FloatT>& ctx, AscendC::MicroAPI::MaskReg& maskAll) | 53 | +__simd_callee__ inline void InitUIntSortConstCtx(UIntSortConstCtx<FloatT> &ctx, AscendC::MicroAPI::MaskReg &maskAll) |
| 54 | { | 54 | { |
| 55 | using Traits = UIntSortTraits<FloatT>; | 55 | using Traits = UIntSortTraits<FloatT>; |
| 56 | - AscendC::MicroAPI::Duplicate(ctx.zeros, Traits::ZERO, maskAll); | 56 | + AscendC::MicroAPI::Duplicate(ctx.zeros, Traits::ZERO, maskAll); |
| 57 | - AscendC::MicroAPI::Duplicate(ctx.allOne, Traits::ALL_ONE, maskAll); | 57 | + AscendC::MicroAPI::Duplicate(ctx.allOne, Traits::ALL_ONE, maskAll); |
| 58 | AscendC::MicroAPI::Duplicate(ctx.signMask, Traits::SIGN_MASK, maskAll); | 58 | AscendC::MicroAPI::Duplicate(ctx.signMask, Traits::SIGN_MASK, maskAll); |
| 59 | - AscendC::MicroAPI::Duplicate(ctx.nan, Traits::NAN_MASK, maskAll); | 59 | + AscendC::MicroAPI::Duplicate(ctx.nan, Traits::NAN_MASK, maskAll); |
| 60 | } | 60 | } |
| 61 | 61 | ||
| 62 | template <typename FloatT> | 62 | template <typename FloatT> |
| 63 | -__simd_callee__ inline void UIntToSortableKey(AscendC::MicroAPI::RegTensor<FloatT>& outKey, | 63 | +__simd_callee__ inline void UIntToSortableKey( |
| 64 | - AscendC::MicroAPI::RegTensor< | 64 | + AscendC::MicroAPI::RegTensor<FloatT> &outKey, |
| 65 | - typename UIntSortConstCtx<FloatT>::UInt>& inVal, | 65 | + AscendC::MicroAPI::RegTensor<typename UIntSortConstCtx<FloatT>::UInt> &inVal, UIntSortConstCtx<FloatT> &ctx, |
| 66 | - UIntSortConstCtx<FloatT>& ctx, | 66 | + AscendC::MicroAPI::MaskReg &maskAll) |
| 67 | - AscendC::MicroAPI::MaskReg& maskAll) | ||
| 68 | { | 67 | { |
| 69 | using Traits = UIntSortTraits<FloatT>; | 68 | using Traits = UIntSortTraits<FloatT>; |
| 70 | - using UInt = typename Traits::UInt; | 69 | + using UInt = typename Traits::UInt; |
| 71 | 70 | ||
| 72 | AscendC::MicroAPI::RegTensor<UInt> regTemp; | 71 | AscendC::MicroAPI::RegTensor<UInt> regTemp; |
| 73 | AscendC::MicroAPI::RegTensor<UInt> regMask; | 72 | AscendC::MicroAPI::RegTensor<UInt> regMask; |
| 74 | AscendC::MicroAPI::MaskReg regSelectZero; | 73 | AscendC::MicroAPI::MaskReg regSelectZero; |
| 75 | AscendC::MicroAPI::MaskReg regSelectSign; | 74 | AscendC::MicroAPI::MaskReg regSelectSign; |
| 76 | 75 | ||
| 77 | - auto& inBits = inVal; | 76 | + auto &inBits = inVal; |
| 78 | 77 | ||
| 79 | // 1. 0 check | 78 | // 1. 0 check |
| 80 | AscendC::MicroAPI::Compare<UInt, CMPMODE::EQ>(regSelectZero, inBits, ctx.zeros, maskAll); | 79 | AscendC::MicroAPI::Compare<UInt, CMPMODE::EQ>(regSelectZero, inBits, ctx.zeros, maskAll); |
| 81 | 80 | ||
| 82 | // 2. 0 -> -NAN | 81 | // 2. 0 -> -NAN |
| 83 | - AscendC::MicroAPI::Select((AscendC::MicroAPI::RegTensor<UInt>&)outKey, ctx.nan, inBits, regSelectZero); | 82 | + AscendC::MicroAPI::Select((AscendC::MicroAPI::RegTensor<UInt> &)outKey, ctx.nan, inBits, regSelectZero); |
| 84 | 83 | ||
| 85 | // 3. sign bit | 84 | // 3. sign bit |
| 86 | - AscendC::MicroAPI::And(regTemp, (AscendC::MicroAPI::RegTensor<UInt>&)outKey, ctx.signMask, maskAll); | 85 | + AscendC::MicroAPI::And(regTemp, (AscendC::MicroAPI::RegTensor<UInt> &)outKey, ctx.signMask, maskAll); |
| 87 | 86 | ||
| 88 | AscendC::MicroAPI::Compare<UInt, CMPMODE::GT>(regSelectSign, regTemp, ctx.zeros, maskAll); | 87 | AscendC::MicroAPI::Compare<UInt, CMPMODE::GT>(regSelectSign, regTemp, ctx.zeros, maskAll); |
| 89 | 88 | ||
| 90 | // 4. xor mask | 89 | // 4. xor mask |
| 91 | AscendC::MicroAPI::Select(regMask, ctx.signMask, ctx.allOne, regSelectSign); | 90 | AscendC::MicroAPI::Select(regMask, ctx.signMask, ctx.allOne, regSelectSign); |
| 92 | - AscendC::MicroAPI::Xor((AscendC::MicroAPI::RegTensor<UInt>&)outKey, | 91 | + AscendC::MicroAPI::Xor((AscendC::MicroAPI::RegTensor<UInt> &)outKey, (AscendC::MicroAPI::RegTensor<UInt> &)outKey, |
| 93 | - (AscendC::MicroAPI::RegTensor<UInt>&)outKey, regMask, maskAll); | 92 | + regMask, maskAll); |
| 94 | } | 93 | } |
| 95 | 94 | ||
| 96 | template <typename T> | 95 | template <typename T> |
| @@ -100,26 +99,26 @@ struct FloatSortTraits; | |||
| 100 | template <> | 99 | template <> |
| 101 | struct FloatSortTraits<float> { | 100 | struct FloatSortTraits<float> { |
| 102 | using UInt = uint32_t; | 101 | using UInt = uint32_t; |
| 103 | - static constexpr UInt ZERO = 0x00000000; | 102 | + static constexpr UInt ZERO = 0x00000000; |
| 104 | static constexpr UInt SIGN_MASK = 0x80000000; | 103 | static constexpr UInt SIGN_MASK = 0x80000000; |
| 105 | - static constexpr UInt NAN_MASK = 0x7FC00000; | 104 | + static constexpr UInt NAN_MASK = 0x7FC00000; |
| 106 | - static constexpr UInt ALL_ONE = 0xFFFFFFFF; | 105 | + static constexpr UInt ALL_ONE = 0xFFFFFFFF; |
| 107 | }; | 106 | }; |
| 108 | 107 | ||
| 109 | // bf16 | 108 | // bf16 |
| 110 | template <> | 109 | template <> |
| 111 | struct FloatSortTraits<bfloat16_t> { | 110 | struct FloatSortTraits<bfloat16_t> { |
| 112 | using UInt = uint16_t; | 111 | using UInt = uint16_t; |
| 113 | - static constexpr UInt ZERO = 0x0000; | 112 | + static constexpr UInt ZERO = 0x0000; |
| 114 | static constexpr UInt SIGN_MASK = 0x8000; | 113 | static constexpr UInt SIGN_MASK = 0x8000; |
| 115 | - static constexpr UInt NAN_MASK = 0x7FC0; | 114 | + static constexpr UInt NAN_MASK = 0x7FC0; |
| 116 | - static constexpr UInt ALL_ONE = 0xFFFF; | 115 | + static constexpr UInt ALL_ONE = 0xFFFF; |
| 117 | }; | 116 | }; |
| 118 | 117 | ||
| 119 | template <typename FloatT> | 118 | template <typename FloatT> |
| 120 | struct FloatSortConstCtx { | 119 | struct FloatSortConstCtx { |
| 121 | using Traits = FloatSortTraits<FloatT>; | 120 | using Traits = FloatSortTraits<FloatT>; |
| 122 | - using UInt = typename Traits::UInt; | 121 | + using UInt = typename Traits::UInt; |
| 123 | AscendC::MicroAPI::RegTensor<UInt> zeros; | 122 | AscendC::MicroAPI::RegTensor<UInt> zeros; |
| 124 | AscendC::MicroAPI::RegTensor<UInt> allOne; | 123 | AscendC::MicroAPI::RegTensor<UInt> allOne; |
| 125 | AscendC::MicroAPI::RegTensor<UInt> signMask; | 124 | AscendC::MicroAPI::RegTensor<UInt> signMask; |
| @@ -127,30 +126,29 @@ struct FloatSortConstCtx { | |||
| 127 | }; | 126 | }; |
| 128 | 127 | ||
| 129 | template <typename FloatT> | 128 | template <typename FloatT> |
| 130 | -__simd_callee__ inline void InitFloatSortConstCtx(FloatSortConstCtx<FloatT>& ctx, AscendC::MicroAPI::MaskReg& maskAll) | 129 | +__simd_callee__ inline void InitFloatSortConstCtx(FloatSortConstCtx<FloatT> &ctx, AscendC::MicroAPI::MaskReg &maskAll) |
| 131 | { | 130 | { |
| 132 | using Traits = FloatSortTraits<FloatT>; | 131 | using Traits = FloatSortTraits<FloatT>; |
| 133 | - AscendC::MicroAPI::Duplicate(ctx.zeros, Traits::ZERO, maskAll); | 132 | + AscendC::MicroAPI::Duplicate(ctx.zeros, Traits::ZERO, maskAll); |
| 134 | - AscendC::MicroAPI::Duplicate(ctx.allOne, Traits::ALL_ONE, maskAll); | 133 | + AscendC::MicroAPI::Duplicate(ctx.allOne, Traits::ALL_ONE, maskAll); |
| 135 | AscendC::MicroAPI::Duplicate(ctx.signMask, Traits::SIGN_MASK, maskAll); | 134 | AscendC::MicroAPI::Duplicate(ctx.signMask, Traits::SIGN_MASK, maskAll); |
| 136 | - AscendC::MicroAPI::Duplicate(ctx.nan, Traits::NAN_MASK, maskAll); | 135 | + AscendC::MicroAPI::Duplicate(ctx.nan, Traits::NAN_MASK, maskAll); |
| 137 | } | 136 | } |
| 138 | 137 | ||
| 139 | template <typename FloatT> | 138 | template <typename FloatT> |
| 140 | -__simd_callee__ inline void FloatToSortableKey(MicroAPI::RegTensor<typename FloatSortTraits<FloatT>::UInt>& outKey, | 139 | +__simd_callee__ inline void FloatToSortableKey(MicroAPI::RegTensor<typename FloatSortTraits<FloatT>::UInt> &outKey, |
| 141 | - MicroAPI::RegTensor<FloatT>& inVal, | 140 | + MicroAPI::RegTensor<FloatT> &inVal, FloatSortConstCtx<FloatT> &ctx, |
| 142 | - FloatSortConstCtx<FloatT>& ctx, | 141 | + MicroAPI::MaskReg &maskAll) |
| 143 | - MicroAPI::MaskReg& maskAll) | ||
| 144 | { | 142 | { |
| 145 | using Traits = FloatSortTraits<FloatT>; | 143 | using Traits = FloatSortTraits<FloatT>; |
| 146 | - using UInt = typename Traits::UInt; | 144 | + using UInt = typename Traits::UInt; |
| 147 | 145 | ||
| 148 | AscendC::MicroAPI::RegTensor<UInt> regTemp; | 146 | AscendC::MicroAPI::RegTensor<UInt> regTemp; |
| 149 | AscendC::MicroAPI::RegTensor<UInt> regMask; | 147 | AscendC::MicroAPI::RegTensor<UInt> regMask; |
| 150 | AscendC::MicroAPI::MaskReg regSelectNan; | 148 | AscendC::MicroAPI::MaskReg regSelectNan; |
| 151 | AscendC::MicroAPI::MaskReg regSelectSign; | 149 | AscendC::MicroAPI::MaskReg regSelectSign; |
| 152 | 150 | ||
| 153 | - auto& inBits = (AscendC::MicroAPI::RegTensor<UInt>&)inVal; | 151 | + auto &inBits = (AscendC::MicroAPI::RegTensor<UInt> &)inVal; |
| 154 | 152 | ||
| 155 | // 1. NaN check | 153 | // 1. NaN check |
| 156 | AscendC::MicroAPI::Compare<UInt, CMPMODE::EQ>(regSelectNan, inBits, ctx.nan, maskAll); | 154 | AscendC::MicroAPI::Compare<UInt, CMPMODE::EQ>(regSelectNan, inBits, ctx.nan, maskAll); |
| @@ -169,23 +167,22 @@ __simd_callee__ inline void FloatToSortableKey(MicroAPI::RegTensor<typename Floa | |||
| 169 | } | 167 | } |
| 170 | 168 | ||
| 171 | template <typename FloatT> | 169 | template <typename FloatT> |
| 172 | -__simd_callee__ inline void FloatX2ToSortableKey(MicroAPI::RegTensor<typename FloatSortTraits<FloatT>::UInt>& outKey0, | 170 | +__simd_callee__ inline void FloatX2ToSortableKey(MicroAPI::RegTensor<typename FloatSortTraits<FloatT>::UInt> &outKey0, |
| 173 | - MicroAPI::RegTensor<typename FloatSortTraits<FloatT>::UInt>& outKey1, | 171 | + MicroAPI::RegTensor<typename FloatSortTraits<FloatT>::UInt> &outKey1, |
| 174 | - MicroAPI::RegTensor<FloatT>& inVal0, | 172 | + MicroAPI::RegTensor<FloatT> &inVal0, |
| 175 | - MicroAPI::RegTensor<FloatT>& inVal1, | 173 | + MicroAPI::RegTensor<FloatT> &inVal1, FloatSortConstCtx<FloatT> &ctx, |
| 176 | - FloatSortConstCtx<FloatT>& ctx, | 174 | + MicroAPI::MaskReg &maskAll) |
| 177 | - MicroAPI::MaskReg& maskAll) | ||
| 178 | { | 175 | { |
| 179 | using Traits = FloatSortTraits<FloatT>; | 176 | using Traits = FloatSortTraits<FloatT>; |
| 180 | - using UInt = typename Traits::UInt; | 177 | + using UInt = typename Traits::UInt; |
| 181 | 178 | ||
| 182 | AscendC::MicroAPI::RegTensor<UInt> regTemp[2]; | 179 | AscendC::MicroAPI::RegTensor<UInt> regTemp[2]; |
| 183 | AscendC::MicroAPI::RegTensor<UInt> regMask[2]; | 180 | AscendC::MicroAPI::RegTensor<UInt> regMask[2]; |
| 184 | AscendC::MicroAPI::MaskReg regSelectNan[2]; | 181 | AscendC::MicroAPI::MaskReg regSelectNan[2]; |
| 185 | AscendC::MicroAPI::MaskReg regSelectSign[2]; | 182 | AscendC::MicroAPI::MaskReg regSelectSign[2]; |
| 186 | 183 | ||
| 187 | - auto& inBits0 = (AscendC::MicroAPI::RegTensor<UInt>&)inVal0; | 184 | + auto &inBits0 = (AscendC::MicroAPI::RegTensor<UInt> &)inVal0; |
| 188 | - auto& inBits1 = (AscendC::MicroAPI::RegTensor<UInt>&)inVal1; | 185 | + auto &inBits1 = (AscendC::MicroAPI::RegTensor<UInt> &)inVal1; |
| 189 | 186 | ||
| 190 | // 1. NaN check | 187 | // 1. NaN check |
| 191 | AscendC::MicroAPI::Compare<UInt, CMPMODE::EQ>(regSelectNan[0], inBits0, ctx.nan, maskAll); | 188 | AscendC::MicroAPI::Compare<UInt, CMPMODE::EQ>(regSelectNan[0], inBits0, ctx.nan, maskAll); |
| @@ -211,7 +208,7 @@ __simd_callee__ inline void FloatX2ToSortableKey(MicroAPI::RegTensor<typename Fl | |||
| 211 | 208 | ||
| 212 | template <typename T, size_t N> | 209 | template <typename T, size_t N> |
| 213 | __simd_callee__ inline void DuplicateZero(AscendC::MicroAPI::RegTensor<T> (®Array)[N], | 210 | __simd_callee__ inline void DuplicateZero(AscendC::MicroAPI::RegTensor<T> (®Array)[N], |
| 214 | - AscendC::MicroAPI::MaskReg& mask) | 211 | + AscendC::MicroAPI::MaskReg &mask) |
| 215 | { | 212 | { |
| 216 | static_assert(N <= 4, "N must be <= 4"); | 213 | static_assert(N <= 4, "N must be <= 4"); |
| 217 | // 不能用循环, 会导致fatal error: error in backend: Unsupported Inst must be hoisted. | 214 | // 不能用循环, 会导致fatal error: error in backend: Unsupported Inst must be hoisted. |
| @@ -232,8 +229,7 @@ __simd_callee__ inline void DuplicateZero(AscendC::MicroAPI::RegTensor<T> (®A | |||
| 232 | template <typename T, size_t N, bool ApplyRelu = true> | 229 | template <typename T, size_t N, bool ApplyRelu = true> |
| 233 | __simd_callee__ inline void WeightedAccum(AscendC::MicroAPI::RegTensor<T> (&accum)[N], | 230 | __simd_callee__ inline void WeightedAccum(AscendC::MicroAPI::RegTensor<T> (&accum)[N], |
| 234 | AscendC::MicroAPI::RegTensor<T> (&input)[N], | 231 | AscendC::MicroAPI::RegTensor<T> (&input)[N], |
| 235 | - AscendC::MicroAPI::RegTensor<T>& weight, | 232 | + AscendC::MicroAPI::RegTensor<T> &weight, AscendC::MicroAPI::MaskReg &mask) |
| 236 | - AscendC::MicroAPI::MaskReg& mask) | ||
| 237 | { | 233 | { |
| 238 | static_assert(N <= 2, "N must be <= 2"); | 234 | static_assert(N <= 2, "N must be <= 2"); |
| 239 | // ---- Relu block ---- | 235 | // ---- Relu block ---- |
| @@ -254,21 +250,27 @@ __simd_callee__ inline void WeightedAccum(AscendC::MicroAPI::RegTensor<T> (&accu | |||
| 254 | } | 250 | } |
| 255 | } | 251 | } |
| 256 | 252 | ||
| 257 | -__simd_callee__ inline void BroadcastLane(AscendC::MicroAPI::RegTensor<float>& dst, | 253 | +__simd_callee__ inline void BroadcastLane(AscendC::MicroAPI::RegTensor<float> &dst, |
| 258 | - AscendC::MicroAPI::RegTensor<float>& src, | 254 | + AscendC::MicroAPI::RegTensor<float> &src, uint16_t laneIdx) |
| 259 | - uint16_t laneIdx) | ||
| 260 | { | 255 | { |
| 261 | AscendC::MicroAPI::RegTensor<uint32_t> brcGatherIndex; | 256 | AscendC::MicroAPI::RegTensor<uint32_t> brcGatherIndex; |
| 262 | AscendC::MicroAPI::Duplicate(brcGatherIndex, laneIdx); | 257 | AscendC::MicroAPI::Duplicate(brcGatherIndex, laneIdx); |
| 263 | AscendC::MicroAPI::Gather(dst, src, brcGatherIndex); | 258 | AscendC::MicroAPI::Gather(dst, src, brcGatherIndex); |
| 264 | } | 259 | } |
| 265 | 260 | ||
| 266 | -__simd_callee__ inline void BroadcastLane(AscendC::MicroAPI::RegTensor<float>& dst, | 261 | +__simd_callee__ inline void BroadcastLane(AscendC::MicroAPI::RegTensor<bfloat16_t> &dst, |
| 267 | - __local_mem__ float* src, | 262 | + AscendC::MicroAPI::RegTensor<bfloat16_t> &src, uint16_t laneIdx) |
| 263 | +{ | ||
| 264 | + AscendC::MicroAPI::RegTensor<uint16_t> brcGatherIndex; | ||
| 265 | + AscendC::MicroAPI::Duplicate(brcGatherIndex, laneIdx); | ||
| 266 | + AscendC::MicroAPI::Gather(dst, src, brcGatherIndex); | ||
| 267 | +} | ||
| 268 | + | ||
| 269 | +__simd_callee__ inline void BroadcastLane(AscendC::MicroAPI::RegTensor<float> &dst, __local_mem__ float *src, | ||
| 268 | uint16_t laneIdx) | 270 | uint16_t laneIdx) |
| 269 | { | 271 | { |
| 270 | AscendC::MicroAPI::LoadAlign<float, AscendC::MicroAPI::LoadDist::DIST_BRC_B32>(dst, src + laneIdx); | 272 | AscendC::MicroAPI::LoadAlign<float, AscendC::MicroAPI::LoadDist::DIST_BRC_B32>(dst, src + laneIdx); |
| 271 | } | 273 | } |
| 272 | 274 | ||
| 273 | -} | 275 | +} // namespace liV2Vector1 |
| 274 | #endif | 276 | #endif |
| @@ -26,11 +26,11 @@ | |||
| 26 | 26 | ||
| 27 | | 参数名 | 输入/输出/属性 | 描述 | 数据类型 | 数据格式 | | 27 | | 参数名 | 输入/输出/属性 | 描述 | 数据类型 | 数据格式 | |
| 28 | |----------------------------|-----------|----------------------------------------------------------------------|----------------|------------| | 28 | |----------------------------|-----------|----------------------------------------------------------------------|----------------|------------| |
| 29 | -| query | 输入 | 公式中的$Q_{index}^{Quant}\in\R^{g\times d}$,表示输入Index Query,不支持非连续。| INT8、FLOAT8_e4m3fn、HIFLOAT8 | ND | | 29 | +| query | 输入 | 公式中的$Q_{index}^{Quant}\in\R^{g\times d}$,表示输入Index Query,不支持非连续。| INT8、FLOAT8_e4m3fn、HIFLOAT8、FLOAT4_e2m1 | ND | |
| 30 | -| key | 输入 | 公式中的$K_{index}^{Quant}\in\R^{S_{k}\times d}$,表示压缩后的输入Index Key,支持0轴非连续。| INT8、FLOAT8_e4m3fn、HIFLOAT8 | ND | | 30 | +| key | 输入 | 公式中的$K_{index}^{Quant}\in\R^{S_{k}\times d}$,表示压缩后的输入Index Key,支持0轴非连续。| INT8、FLOAT8_e4m3fn、HIFLOAT8、FLOAT4_e2m1 | ND | |
| 31 | | weights | 输入 | 公式中的$W$,表示权重系数,不支持非连续。 | FLOAT16、FLOAT32 | ND | | 31 | | weights | 输入 | 公式中的$W$,表示权重系数,不支持非连续。 | FLOAT16、FLOAT32 | ND | |
| 32 | -| query_dequant_scale | 输入 | 公式中的$Scale_Q$,表示Index Query的反量化系数,不支持非连续。shape与weights一致 | FLOAT16、FLOAT32 | ND | | 32 | +| query_dequant_scale | 输入 | 公式中的$Scale_Q$,表示Index Query的反量化系数,不支持非连续。非MX场景shape与weights一致;`quant_mode`为3/5时,shape为将`query`的D轴替换为(D/64, 2) | FLOAT16、FLOAT32、FLOAT8_e8m0 | ND | |
| 33 | -| key_dequant_scale | 输入 | 公式中的$Scale_K$,表示Index Key的反量化系数,支持0轴非连续。| FLOAT16、FLOAT32 | ND | | 33 | +| key_dequant_scale | 输入 | 公式中的$Scale_K$,表示Index Key的反量化系数,支持0轴非连续。`quant_mode`为3/5时,shape为将`key`的D轴替换为(D/64, 2) | FLOAT16、FLOAT32、FLOAT8_e8m0 | ND | |
| 34 | | cu_seqlens_q | 可选输入 | layout_q为TND时必须传入,表示每个Batch中`query`的有效token数前缀和。;layout_q为BSND时不能传入 | INT32 | ND | | 34 | | cu_seqlens_q | 可选输入 | layout_q为TND时必须传入,表示每个Batch中`query`的有效token数前缀和。;layout_q为BSND时不能传入 | INT32 | ND | |
| 35 | | cu_seqlens_k | 可选输入 | layout_k为TND时必须传入,表示每个Batch中`key`的有效token数前缀和;layout_k为PA_BSND或BSND时不能传入 | INT32 | ND | | 35 | | cu_seqlens_k | 可选输入 | layout_k为TND时必须传入,表示每个Batch中`key`的有效token数前缀和;layout_k为PA_BSND或BSND时不能传入 | INT32 | ND | |
| 36 | | seqused_q | 可选输入 | layout_q为BSND时可选传入,表示每个Batch中`query`的有效token数,可传入None表示与query的S长度相同 | INT32 | ND | | 36 | | seqused_q | 可选输入 | layout_q为BSND时可选传入,表示每个Batch中`query`的有效token数,可传入None表示与query的S长度相同 | INT32 | ND | |
| @@ -50,6 +50,13 @@ | |||
| 50 | | sparse_indices | 输出 | 公式中的输出Out,参与稀疏attention计算的token索引值。 | INT32 | ND | | 50 | | sparse_indices | 输出 | 公式中的输出Out,参与稀疏attention计算的token索引值。 | INT32 | ND | |
| 51 | | sparse_values | 输出 | 公式中的Indices输出对应的value值。shape与sparse_indices一致。仅当return_value为True时输出有效值,否则输出bf16负无穷 | BFLOAT16 | ND | | 51 | | sparse_values | 输出 | 公式中的Indices输出对应的value值。shape与sparse_indices一致。仅当return_value为True时输出有效值,否则输出bf16负无穷 | BFLOAT16 | ND | |
| 52 | 52 | ||
| 53 | +## 约束说明 | ||
| 54 | + | ||
| 55 | +- <term>Ascend 950PR/Ascend 950DT</term>: | ||
| 56 | + - `query`、`key`在`quant_mode`为1/3时支持FLOAT8_e4m3fn,`quant_mode`为4时支持HIFLOAT8,`quant_mode`为5时支持FLOAT4_e2m1,不支持INT8。 | ||
| 57 | + - `quant_mode`为3/5时,`query_dequant_scale`和`key_dequant_scale`仅支持FLOAT8_e8m0。 | ||
| 58 | + - `quant_mode`为5时,`query`和`key`的逻辑数据类型为FLOAT4_e2m1,每个物理字节打包两个E2M1逻辑元素。 | ||
| 59 | + | ||
| 53 | ## 调用示例 | 60 | ## 调用示例 |
| 54 | 61 | ||
| 55 | | 调用方式 | 调用样例 | 说明 | | 62 | | 调用方式 | 调用样例 | 说明 | |
| @@ -20,21 +20,9 @@ class QuantLightningIndexerV2 : public OpDef { | |||
| 20 | public: | 20 | public: |
| 21 | explicit QuantLightningIndexerV2(const char *name) : OpDef(name) | 21 | explicit QuantLightningIndexerV2(const char *name) : OpDef(name) |
| 22 | { | 22 | { |
| 23 | - this->Input("q") | 23 | + this->Input("q").ParamType(REQUIRED).DataType({ge::DT_INT8}).FormatList({ge::FORMAT_ND}).AutoContiguous(); |
| 24 | - .ParamType(REQUIRED) | 24 | + this->Input("k").ParamType(REQUIRED).DataType({ge::DT_INT8}).FormatList({ge::FORMAT_ND}).IgnoreContiguous(); |
| 25 | - .DataType({ge::DT_INT8}) | 25 | + this->Input("w").ParamType(REQUIRED).DataType({ge::DT_FLOAT16}).FormatList({ge::FORMAT_ND}).AutoContiguous(); |
| 26 | - .FormatList({ge::FORMAT_ND}) | ||
| 27 | - .AutoContiguous(); | ||
| 28 | - this->Input("k") | ||
| 29 | - .ParamType(REQUIRED) | ||
| 30 | - .DataType({ge::DT_INT8}) | ||
| 31 | - .FormatList({ge::FORMAT_ND}) | ||
| 32 | - .IgnoreContiguous(); | ||
| 33 | - this->Input("w") | ||
| 34 | - .ParamType(REQUIRED) | ||
| 35 | - .DataType({ge::DT_FLOAT16}) | ||
| 36 | - .FormatList({ge::FORMAT_ND}) | ||
| 37 | - .AutoContiguous(); | ||
| 38 | this->Input("q_descale") | 26 | this->Input("q_descale") |
| 39 | .ParamType(REQUIRED) | 27 | .ParamType(REQUIRED) |
| 40 | .DataTypeList({ge::DT_FLOAT16}) | 28 | .DataTypeList({ge::DT_FLOAT16}) |
| @@ -85,22 +73,16 @@ public: | |||
| 85 | .DataTypeList({ge::DT_INT32}) | 73 | .DataTypeList({ge::DT_INT32}) |
| 86 | .FormatList({ge::FORMAT_ND}) | 74 | .FormatList({ge::FORMAT_ND}) |
| 87 | .AutoContiguous(); | 75 | .AutoContiguous(); |
| 88 | - this->Output("sparse_indices") | 76 | + this->Output("sparse_indices").ParamType(REQUIRED).DataTypeList({ge::DT_INT32}).FormatList({ge::FORMAT_ND}); |
| 89 | - .ParamType(REQUIRED) | 77 | + this->Output("sparse_values").ParamType(REQUIRED).DataTypeList({ge::DT_BF16}).FormatList({ge::FORMAT_ND}); |
| 90 | - .DataTypeList({ge::DT_INT32}) | 78 | + this->Attr("topk").AttrType(REQUIRED).Int(2048); // 2048: 筛选前2048个作为输出index |
| 91 | - .FormatList({ge::FORMAT_ND}); | ||
| 92 | - this->Output("sparse_values") | ||
| 93 | - .ParamType(REQUIRED) | ||
| 94 | - .DataTypeList({ge::DT_BF16}) | ||
| 95 | - .FormatList({ge::FORMAT_ND}); | ||
| 96 | - this->Attr("topk").AttrType(REQUIRED).Int(2048); // 2048: 筛选前2048个作为输出index | ||
| 97 | this->Attr("quant_mode").AttrType(REQUIRED).Int(1); // 1: per-token-head | 79 | this->Attr("quant_mode").AttrType(REQUIRED).Int(1); // 1: per-token-head |
| 98 | - this->Attr("max_seqlen_q").AttrType(OPTIONAL).Int(-1); // -1: 默认值,表示任意可能长度 | 80 | + this->Attr("max_seqlen_q").AttrType(OPTIONAL).Int(-1); // -1: 默认值,表示任意可能长度 |
| 99 | this->Attr("layout_q").AttrType(OPTIONAL).String("BSND"); | 81 | this->Attr("layout_q").AttrType(OPTIONAL).String("BSND"); |
| 100 | this->Attr("layout_k").AttrType(OPTIONAL).String("BSND"); | 82 | this->Attr("layout_k").AttrType(OPTIONAL).String("BSND"); |
| 101 | - this->Attr("mask_mode").AttrType(OPTIONAL).Int(0); // 0: 默认值,无mask | 83 | + this->Attr("mask_mode").AttrType(OPTIONAL).Int(0); // 0: 默认值,无mask |
| 102 | this->Attr("cmp_ratio").AttrType(OPTIONAL).Int(1); | 84 | this->Attr("cmp_ratio").AttrType(OPTIONAL).Int(1); |
| 103 | - this->Attr("return_value").AttrType(OPTIONAL).Int(0); // 0: 默认值 | 85 | + this->Attr("return_value").AttrType(OPTIONAL).Int(0); // 0: 默认值 |
| 104 | OpAICoreConfig aicore_config; | 86 | OpAICoreConfig aicore_config; |
| 105 | aicore_config.DynamicCompileStaticFlag(true) | 87 | aicore_config.DynamicCompileStaticFlag(true) |
| 106 | .DynamicFormatFlag(true) | 88 | .DynamicFormatFlag(true) |
| @@ -112,29 +94,30 @@ public: | |||
| 112 | this->AICore().AddConfig("ascend910_93", aicore_config); | 94 | this->AICore().AddConfig("ascend910_93", aicore_config); |
| 113 | 95 | ||
| 114 | OpAICoreConfig aicore_config_95; | 96 | OpAICoreConfig aicore_config_95; |
| 97 | + // fp8/mxfp8/hif8/mxfp4 | ||
| 115 | aicore_config_95.Input("q") | 98 | aicore_config_95.Input("q") |
| 116 | .ParamType(REQUIRED) | 99 | .ParamType(REQUIRED) |
| 117 | - .DataType({ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8}) | 100 | + .DataType({ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8, ge::DT_FLOAT4_E2M1}) |
| 118 | .FormatList({ge::FORMAT_ND}) | 101 | .FormatList({ge::FORMAT_ND}) |
| 119 | .AutoContiguous(); | 102 | .AutoContiguous(); |
| 120 | aicore_config_95.Input("k") | 103 | aicore_config_95.Input("k") |
| 121 | .ParamType(REQUIRED) | 104 | .ParamType(REQUIRED) |
| 122 | - .DataType({ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8}) | 105 | + .DataType({ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8, ge::DT_FLOAT4_E2M1}) |
| 123 | .FormatList({ge::FORMAT_ND}) | 106 | .FormatList({ge::FORMAT_ND}) |
| 124 | .IgnoreContiguous(); | 107 | .IgnoreContiguous(); |
| 125 | aicore_config_95.Input("w") | 108 | aicore_config_95.Input("w") |
| 126 | .ParamType(REQUIRED) | 109 | .ParamType(REQUIRED) |
| 127 | - .DataType({ge::DT_FLOAT, ge::DT_FLOAT}) | 110 | + .DataTypeList({ge::DT_FLOAT}) |
| 128 | .FormatList({ge::FORMAT_ND}) | 111 | .FormatList({ge::FORMAT_ND}) |
| 129 | .AutoContiguous(); | 112 | .AutoContiguous(); |
| 130 | aicore_config_95.Input("q_descale") | 113 | aicore_config_95.Input("q_descale") |
| 131 | .ParamType(REQUIRED) | 114 | .ParamType(REQUIRED) |
| 132 | - .DataTypeList({ge::DT_FLOAT}) | 115 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT, ge::DT_FLOAT8_E8M0}) |
| 133 | .FormatList({ge::FORMAT_ND}) | 116 | .FormatList({ge::FORMAT_ND}) |
| 134 | .AutoContiguous(); | 117 | .AutoContiguous(); |
| 135 | aicore_config_95.Input("k_descale") | 118 | aicore_config_95.Input("k_descale") |
| 136 | .ParamType(REQUIRED) | 119 | .ParamType(REQUIRED) |
| 137 | - .DataTypeList({ge::DT_FLOAT}) | 120 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT, ge::DT_FLOAT8_E8M0}) |
| 138 | .FormatList({ge::FORMAT_ND}) | 121 | .FormatList({ge::FORMAT_ND}) |
| 139 | .IgnoreContiguous(); | 122 | .IgnoreContiguous(); |
| 140 | aicore_config_95.Input("cu_seqlens_q") | 123 | aicore_config_95.Input("cu_seqlens_q") |
| @@ -195,4 +178,4 @@ public: | |||
| 195 | } | 178 | } |
| 196 | }; | 179 | }; |
| 197 | OP_ADD(QuantLightningIndexerV2); | 180 | OP_ADD(QuantLightningIndexerV2); |
| 198 | -} // namespace ops | 181 | +} // namespace ops |
| @@ -56,8 +56,11 @@ static const std::map<ge::DataType, std::string> DATATYPE_TO_STRING_MAP = { | |||
| 56 | {ge::DT_INT4, "DT_INT4"}, // dt_variant type | 56 | {ge::DT_INT4, "DT_INT4"}, // dt_variant type |
| 57 | {ge::DT_UINT1, "DT_UINT1"}, // dt_variant type | 57 | {ge::DT_UINT1, "DT_UINT1"}, // dt_variant type |
| 58 | {ge::DT_INT2, "DT_INT2"}, // dt_variant type | 58 | {ge::DT_INT2, "DT_INT2"}, // dt_variant type |
| 59 | - {ge::DT_UINT2, "DT_UINT2"} // dt_variant type | 59 | + {ge::DT_UINT2, "DT_UINT2"}, // dt_variant type |
| 60 | -}; | 60 | + {ge::DT_HIFLOAT8, "DT_HIFLOAT8"}, |
| 61 | + {ge::DT_FLOAT8_E4M3FN, "DT_FLOAT8_E4M3FN"}, | ||
| 62 | + {ge::DT_FLOAT8_E8M0, "DT_FLOAT8_E8M0"}, | ||
| 63 | + {ge::DT_FLOAT4_E2M1, "DT_FLOAT4_E2M1"}}; | ||
| 61 | 64 | ||
| 62 | std::string QLIV2DataTypeToSerialString(ge::DataType type) | 65 | std::string QLIV2DataTypeToSerialString(ge::DataType type) |
| 63 | { | 66 | { |
| @@ -278,7 +281,7 @@ ge::graphStatus QLIV2InfoParser::CheckAttrParaInfo() | |||
| 278 | } else if (npuArch_ == NpuArch::DAV_3510) { | 281 | } else if (npuArch_ == NpuArch::DAV_3510) { |
| 279 | OP_CHECK_IF(((std::string(opParamInfo_.layOutKey) != "PA_BBND") && | 282 | OP_CHECK_IF(((std::string(opParamInfo_.layOutKey) != "PA_BBND") && |
| 280 | (std::string(opParamInfo_.layOutKey) != "BSND") && (std::string(opParamInfo_.layOutKey) != "TND")), | 283 | (std::string(opParamInfo_.layOutKey) != "BSND") && (std::string(opParamInfo_.layOutKey) != "TND")), |
| 281 | - OP_LOGE(opName_, "input attr layout_key only supported PA_BSND, BSND or TND"), | 284 | + OP_LOGE(opName_, "input attr layout_key only supported PA_BBND, BSND or TND"), |
| 282 | return ge::GRAPH_FAILED); | 285 | return ge::GRAPH_FAILED); |
| 283 | } | 286 | } |
| 284 | 287 | ||
| @@ -322,8 +325,10 @@ ge::graphStatus QLIV2InfoParser::CheckAttrParaInfo() | |||
| 322 | OP_CHECK_IF(*opParamInfo_.quantMode != 2, OP_LOGE(opName_, "input attr quant_mode only supported 2."), | 325 | OP_CHECK_IF(*opParamInfo_.quantMode != 2, OP_LOGE(opName_, "input attr quant_mode only supported 2."), |
| 323 | return ge::GRAPH_FAILED); | 326 | return ge::GRAPH_FAILED); |
| 324 | } else if (npuArch_ == NpuArch::DAV_3510) { | 327 | } else if (npuArch_ == NpuArch::DAV_3510) { |
| 325 | - OP_CHECK_IF((*opParamInfo_.quantMode != 1) && (*opParamInfo_.quantMode != 4), | 328 | + OP_CHECK_IF((*opParamInfo_.quantMode != QUANT_MODE_FP8) && (*opParamInfo_.quantMode != QUANT_MODE_MXFP8) && |
| 326 | - OP_LOGE(opName_, "input attr quant_mode only supported 1 and 4."), return ge::GRAPH_FAILED); | 329 | + (*opParamInfo_.quantMode != QUANT_MODE_HIFLOAT8) && |
| 330 | + (*opParamInfo_.quantMode != QUANT_MODE_MXFP4), | ||
| 331 | + OP_LOGE(opName_, "input attr quant_mode only supported 1, 3, 4 and 5."), return ge::GRAPH_FAILED); | ||
| 327 | } | 332 | } |
| 328 | 333 | ||
| 329 | if (npuArch_ == NpuArch::DAV_2201) { | 334 | if (npuArch_ == NpuArch::DAV_2201) { |
| @@ -399,30 +404,28 @@ ge::graphStatus QLIV2InfoParser::GetAndCheckInOutDataType() | |||
| 399 | "The data types of the input query_dequant_scale and key_dequant_scale must be float16"), | 404 | "The data types of the input query_dequant_scale and key_dequant_scale must be float16"), |
| 400 | return ge::GRAPH_FAILED); | 405 | return ge::GRAPH_FAILED); |
| 401 | } else if (npuArch_ == NpuArch::DAV_3510) { | 406 | } else if (npuArch_ == NpuArch::DAV_3510) { |
| 402 | - if (*opParamInfo_.quantMode == 1) { | 407 | + ge::DataType expectQType = ge::DT_FLOAT8_E4M3FN; |
| 403 | - OP_CHECK_IF( | 408 | + ge::DataType expectScaleType = ge::DT_FLOAT; |
| 404 | - inputQType_ != ge::DT_FLOAT8_E4M3FN, | 409 | + if (*opParamInfo_.quantMode == QUANT_MODE_MXFP8) { |
| 405 | - OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( | 410 | + expectScaleType = ge::DT_FLOAT8_E8M0; |
| 406 | - opName_, "query and key", | 411 | + } else if (*opParamInfo_.quantMode == QUANT_MODE_HIFLOAT8) { |
| 407 | - QLIV2DataTypeToSerialString(inputQType_) + " and " + QLIV2DataTypeToSerialString(inputKType_), | 412 | + expectQType = ge::DT_HIFLOAT8; |
| 408 | - "When quant_mode is 1, the data types of the input query and key must be float8_e4m3"), | 413 | + } else if (*opParamInfo_.quantMode == QUANT_MODE_MXFP4) { |
| 409 | - return ge::GRAPH_FAILED); | 414 | + expectQType = ge::DT_FLOAT4_E2M1; |
| 410 | - } else if (*opParamInfo_.quantMode == 4) { | 415 | + expectScaleType = ge::DT_FLOAT8_E8M0; |
| 411 | - OP_CHECK_IF( | ||
| 412 | - inputQType_ != ge::DT_HIFLOAT8, | ||
| 413 | - OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( | ||
| 414 | - opName_, "query and key", | ||
| 415 | - QLIV2DataTypeToSerialString(inputQType_) + " and " + QLIV2DataTypeToSerialString(inputKType_), | ||
| 416 | - "When quant_mode is 4, the data types of the input query and key" | ||
| 417 | - " must be hifloat8."), | ||
| 418 | - return ge::GRAPH_FAILED); | ||
| 419 | } | 416 | } |
| 420 | - OP_CHECK_IF(inputQueryScaleType_ != ge::DT_FLOAT, | 417 | + OP_CHECK_IF(inputQType_ != expectQType, |
| 418 | + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( | ||
| 419 | + opName_, "query and key", | ||
| 420 | + QLIV2DataTypeToSerialString(inputQType_) + " and " + QLIV2DataTypeToSerialString(inputKType_), | ||
| 421 | + "The data types of the input query and key must match quant_mode"), | ||
| 422 | + return ge::GRAPH_FAILED); | ||
| 423 | + OP_CHECK_IF(inputQueryScaleType_ != expectScaleType, | ||
| 421 | OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( | 424 | OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( |
| 422 | opName_, "query_dequant_scale and key_dequant_scale", | 425 | opName_, "query_dequant_scale and key_dequant_scale", |
| 423 | QLIV2DataTypeToSerialString(inputQueryScaleType_) + " and " + | 426 | QLIV2DataTypeToSerialString(inputQueryScaleType_) + " and " + |
| 424 | QLIV2DataTypeToSerialString(inputKeyScaleType_), | 427 | QLIV2DataTypeToSerialString(inputKeyScaleType_), |
| 425 | - "The data types of the input query_dequant_scale and key_dequant_scale must be float"), | 428 | + "The data types of the input query_dequant_scale and key_dequant_scale must match quant_mode"), |
| 426 | return ge::GRAPH_FAILED); | 429 | return ge::GRAPH_FAILED); |
| 427 | } | 430 | } |
| 428 | 431 | ||
| @@ -1112,8 +1115,9 @@ ge::graphStatus QLIV2InfoParser::CheckScaleShape() | |||
| 1112 | uint32_t kShapeDim = opParamInfo_.key.shape->GetStorageShape().GetDimNum(); | 1115 | uint32_t kShapeDim = opParamInfo_.key.shape->GetStorageShape().GetDimNum(); |
| 1113 | uint32_t qDequantScaleShapeDim = opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDimNum(); | 1116 | uint32_t qDequantScaleShapeDim = opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDimNum(); |
| 1114 | uint32_t kDequantScaleShapeDim = opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDimNum(); | 1117 | uint32_t kDequantScaleShapeDim = opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDimNum(); |
| 1118 | + bool isMxQuantMode = (*opParamInfo_.quantMode == QUANT_MODE_MXFP8) || (*opParamInfo_.quantMode == QUANT_MODE_MXFP4); | ||
| 1115 | 1119 | ||
| 1116 | - if (*opParamInfo_.quantMode == 4) { | 1120 | + if (*opParamInfo_.quantMode == QUANT_MODE_HIFLOAT8) { |
| 1117 | OP_CHECK_IF(qDequantScaleShapeDim != 1, | 1121 | OP_CHECK_IF(qDequantScaleShapeDim != 1, |
| 1118 | OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( | 1122 | OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( |
| 1119 | opName_, "query_dequant_scale", std::to_string(qDequantScaleShapeDim).c_str(), | 1123 | opName_, "query_dequant_scale", std::to_string(qDequantScaleShapeDim).c_str(), |
| @@ -1136,6 +1140,48 @@ ge::graphStatus QLIV2InfoParser::CheckScaleShape() | |||
| 1136 | Ops::Base::ToString(opParamInfo_.key_dequant_scale.shape->GetStorageShape()).c_str(), | 1140 | Ops::Base::ToString(opParamInfo_.key_dequant_scale.shape->GetStorageShape()).c_str(), |
| 1137 | "when quant_mode is 4, key_dequant_scale's shape[0] should be 1"), | 1141 | "when quant_mode is 4, key_dequant_scale's shape[0] should be 1"), |
| 1138 | return ge::GRAPH_FAILED); | 1142 | return ge::GRAPH_FAILED); |
| 1143 | + } else if (isMxQuantMode) { | ||
| 1144 | + OP_CHECK_IF(headDim_ % MX_SCALE_SHAPE_ALIGN != 0, | ||
| 1145 | + OP_LOGE(opName_, "when quant_mode is %d, head_dim should be a multiple of %u, but now is %u", | ||
| 1146 | + *opParamInfo_.quantMode, MX_SCALE_SHAPE_ALIGN, headDim_), | ||
| 1147 | + return ge::GRAPH_FAILED); | ||
| 1148 | + OP_CHECK_IF(qDequantScaleShapeDim != (qShapeDim + 1), | ||
| 1149 | + OP_LOGE(opName_, "when quant_mode is %d, query_dequant_scale dim num should be %u, but now is %u", | ||
| 1150 | + *opParamInfo_.quantMode, qShapeDim + 1, qDequantScaleShapeDim), | ||
| 1151 | + return ge::GRAPH_FAILED); | ||
| 1152 | + OP_CHECK_IF(kDequantScaleShapeDim != (kShapeDim + 1), | ||
| 1153 | + OP_LOGE(opName_, "when quant_mode is %d, key_dequant_scale dim num should be %u, but now is %u", | ||
| 1154 | + *opParamInfo_.quantMode, kShapeDim + 1, kDequantScaleShapeDim), | ||
| 1155 | + return ge::GRAPH_FAILED); | ||
| 1156 | + for (uint32_t i = 0; i < (qShapeDim - 1); i++) { | ||
| 1157 | + uint32_t dimValueQueryScale = opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDim(i); | ||
| 1158 | + uint32_t dimValueQuery = opParamInfo_.query.shape->GetStorageShape().GetDim(i); | ||
| 1159 | + OP_CHECK_IF(dimValueQueryScale != dimValueQuery, | ||
| 1160 | + OP_LOGE(opName_, "query_dequant_scale's shape[%u] %u and query's shape[%u] %u are not the same", | ||
| 1161 | + i, dimValueQueryScale, i, dimValueQuery), | ||
| 1162 | + return ge::GRAPH_FAILED); | ||
| 1163 | + } | ||
| 1164 | + for (uint32_t i = 0; i < (kShapeDim - 1); i++) { | ||
| 1165 | + uint32_t dimValueKeyScale = opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDim(i); | ||
| 1166 | + uint32_t dimValueKey = opParamInfo_.key.shape->GetStorageShape().GetDim(i); | ||
| 1167 | + OP_CHECK_IF(dimValueKeyScale != dimValueKey, | ||
| 1168 | + OP_LOGE(opName_, "key_dequant_scale's shape[%u] %u and key's shape[%u] %u are not the same", i, | ||
| 1169 | + dimValueKeyScale, i, dimValueKey), | ||
| 1170 | + return ge::GRAPH_FAILED); | ||
| 1171 | + } | ||
| 1172 | + uint32_t expectScaleD = headDim_ / MX_SCALE_SHAPE_ALIGN; | ||
| 1173 | + OP_CHECK_IF( | ||
| 1174 | + (opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDim(qShapeDim - 1) != expectScaleD) || | ||
| 1175 | + (opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDim(qShapeDim) != MX_E8M0_SCALE_PACK_NUM), | ||
| 1176 | + OP_LOGE(opName_, "when quant_mode is %d, query_dequant_scale's last dims should be [%u, %u].", | ||
| 1177 | + *opParamInfo_.quantMode, expectScaleD, MX_E8M0_SCALE_PACK_NUM), | ||
| 1178 | + return ge::GRAPH_FAILED); | ||
| 1179 | + OP_CHECK_IF( | ||
| 1180 | + (opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDim(kShapeDim - 1) != expectScaleD) || | ||
| 1181 | + (opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDim(kShapeDim) != MX_E8M0_SCALE_PACK_NUM), | ||
| 1182 | + OP_LOGE(opName_, "when quant_mode is %d, key_dequant_scale's last dims should be [%u, %u].", | ||
| 1183 | + *opParamInfo_.quantMode, expectScaleD, MX_E8M0_SCALE_PACK_NUM), | ||
| 1184 | + return ge::GRAPH_FAILED); | ||
| 1139 | } else { | 1185 | } else { |
| 1140 | OP_CHECK_IF( | 1186 | OP_CHECK_IF( |
| 1141 | qDequantScaleShapeDim != (qShapeDim - 1), | 1187 | qDequantScaleShapeDim != (qShapeDim - 1), |
| @@ -1157,7 +1203,7 @@ ge::graphStatus QLIV2InfoParser::CheckScaleShape() | |||
| 1157 | Ops::Base::ToString(opParamInfo_.query_dequant_scale.shape->GetStorageShape()) + " and " + | 1203 | Ops::Base::ToString(opParamInfo_.query_dequant_scale.shape->GetStorageShape()) + " and " + |
| 1158 | Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()), | 1204 | Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()), |
| 1159 | "query_dequant_scale's shape[" + std::to_string(i) + "] and query's shape[" + | 1205 | "query_dequant_scale's shape[" + std::to_string(i) + "] and query's shape[" + |
| 1160 | - std::to_string(i) + "] is not same"), | 1206 | + std::to_string(i) + "] are not the same"), |
| 1161 | return ge::GRAPH_FAILED); | 1207 | return ge::GRAPH_FAILED); |
| 1162 | } | 1208 | } |
| 1163 | // check k scale | 1209 | // check k scale |
| @@ -1170,7 +1216,7 @@ ge::graphStatus QLIV2InfoParser::CheckScaleShape() | |||
| 1170 | Ops::Base::ToString(opParamInfo_.key_dequant_scale.shape->GetStorageShape()) + " and " + | 1216 | Ops::Base::ToString(opParamInfo_.key_dequant_scale.shape->GetStorageShape()) + " and " + |
| 1171 | Ops::Base::ToString(opParamInfo_.key.shape->GetStorageShape()), | 1217 | Ops::Base::ToString(opParamInfo_.key.shape->GetStorageShape()), |
| 1172 | "key_dequant_scale's shape[" + std::to_string(i) + "] and key's shape[" + | 1218 | "key_dequant_scale's shape[" + std::to_string(i) + "] and key's shape[" + |
| 1173 | - std::to_string(i) + "] is not same"), | 1219 | + std::to_string(i) + "] are not the same"), |
| 1174 | return ge::GRAPH_FAILED); | 1220 | return ge::GRAPH_FAILED); |
| 1175 | } | 1221 | } |
| 1176 | } | 1222 | } |
| @@ -1205,14 +1251,26 @@ ge::graphStatus QLIV2InfoParser::CheckKeyContiguous() const | |||
| 1205 | } | 1251 | } |
| 1206 | } | 1252 | } |
| 1207 | } | 1253 | } |
| 1208 | - if ((*opParamInfo_.quantMode != 4) && !keyDequantScaleStridesVec_.empty() && | 1254 | + bool isMxQuantMode = (*opParamInfo_.quantMode == QUANT_MODE_MXFP8) || (*opParamInfo_.quantMode == QUANT_MODE_MXFP4); |
| 1255 | + if ((*opParamInfo_.quantMode != QUANT_MODE_HIFLOAT8) && !keyDequantScaleStridesVec_.empty() && | ||
| 1209 | opParamInfo_.key_dequant_scale.shape != nullptr) { | 1256 | opParamInfo_.key_dequant_scale.shape != nullptr) { |
| 1210 | auto &shape = opParamInfo_.key_dequant_scale.shape->GetStorageShape(); | 1257 | auto &shape = opParamInfo_.key_dequant_scale.shape->GetStorageShape(); |
| 1211 | std::vector<uint32_t> expectedStrides; | 1258 | std::vector<uint32_t> expectedStrides; |
| 1212 | - if (kLayout_ == DataLayout::BSND || kLayout_ == DataLayout::PA_BBND) { | 1259 | + if (isMxQuantMode) { |
| 1213 | - expectedStrides = {shape.GetDim(1) * shape.GetDim(2), shape.GetDim(2), 1}; | 1260 | + if (kLayout_ == DataLayout::BSND || kLayout_ == DataLayout::PA_BBND) { |
| 1214 | - } else if (kLayout_ == DataLayout::TND) { | 1261 | + expectedStrides = {shape.GetDim(1) * shape.GetDim(2) * shape.GetDim(3) * shape.GetDim(4), |
| 1215 | - expectedStrides = {shape.GetDim(1), 1}; | 1262 | + shape.GetDim(2) * shape.GetDim(3) * shape.GetDim(4), |
| 1263 | + shape.GetDim(3) * shape.GetDim(4), shape.GetDim(4), 1}; | ||
| 1264 | + } else if (kLayout_ == DataLayout::TND) { | ||
| 1265 | + expectedStrides = {shape.GetDim(1) * shape.GetDim(2) * shape.GetDim(3), | ||
| 1266 | + shape.GetDim(2) * shape.GetDim(3), shape.GetDim(3), 1}; | ||
| 1267 | + } | ||
| 1268 | + } else { | ||
| 1269 | + if (kLayout_ == DataLayout::BSND || kLayout_ == DataLayout::PA_BBND) { | ||
| 1270 | + expectedStrides = {shape.GetDim(1) * shape.GetDim(2), shape.GetDim(2), 1}; | ||
| 1271 | + } else if (kLayout_ == DataLayout::TND) { | ||
| 1272 | + expectedStrides = {shape.GetDim(1), 1}; | ||
| 1273 | + } | ||
| 1216 | } | 1274 | } |
| 1217 | for (size_t i = checkStartIdx; i < expectedStrides.size(); ++i) { | 1275 | for (size_t i = checkStartIdx; i < expectedStrides.size(); ++i) { |
| 1218 | if (i < keyDequantScaleStridesVec_.size() && keyDequantScaleStridesVec_[i] != expectedStrides[i]) { | 1276 | if (i < keyDequantScaleStridesVec_.size() && keyDequantScaleStridesVec_[i] != expectedStrides[i]) { |
| @@ -1221,6 +1279,33 @@ ge::graphStatus QLIV2InfoParser::CheckKeyContiguous() const | |||
| 1221 | } | 1279 | } |
| 1222 | } | 1280 | } |
| 1223 | } | 1281 | } |
| 1282 | + if (kLayout_ == DataLayout::PA_BBND) { | ||
| 1283 | + if (!keyStridesVec_.empty()) { | ||
| 1284 | + if (*opParamInfo_.quantMode == QUANT_MODE_MXFP4) { | ||
| 1285 | + OP_CHECK_IF( | ||
| 1286 | + keyStridesVec_[0] <= 0 || keyStridesVec_[0] % MXFP4_PACK_NUM != 0, | ||
| 1287 | + OP_LOGE(opName_, | ||
| 1288 | + "when quant_mode is 5 and layout_k is PA_BBND, key stride0 must be positive and satisfy " | ||
| 1289 | + "2-element FP4 packing alignment, but got %u", | ||
| 1290 | + keyStridesVec_[0]), | ||
| 1291 | + return ge::GRAPH_FAILED); | ||
| 1292 | + } else { | ||
| 1293 | + OP_CHECK_IF(keyStridesVec_[0] <= 0, | ||
| 1294 | + OP_LOGE(opName_, "when layout_k is PA_BBND, key stride0 must be positive, but got %u", | ||
| 1295 | + keyStridesVec_[0]), | ||
| 1296 | + return ge::GRAPH_FAILED); | ||
| 1297 | + } | ||
| 1298 | + } | ||
| 1299 | + if (isMxQuantMode && !keyDequantScaleStridesVec_.empty()) { | ||
| 1300 | + OP_CHECK_IF( | ||
| 1301 | + keyDequantScaleStridesVec_[0] <= 0 || keyDequantScaleStridesVec_[0] % MX_E8M0_SCALE_PACK_NUM != 0, | ||
| 1302 | + OP_LOGE(opName_, | ||
| 1303 | + "when quant_mode is 3 or 5 and layout_k is PA_BBND, key_dequant_scale stride0 must be positive " | ||
| 1304 | + "and satisfy 2-element E8M0 packing alignment, but got %u", | ||
| 1305 | + keyDequantScaleStridesVec_[0]), | ||
| 1306 | + return ge::GRAPH_FAILED); | ||
| 1307 | + } | ||
| 1308 | + } | ||
| 1224 | OP_CHECK_IF( | 1309 | OP_CHECK_IF( |
| 1225 | keyNonContiguous || scaleNonContiguous, | 1310 | keyNonContiguous || scaleNonContiguous, |
| 1226 | OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "keyNonContiguous and scaleNonContiguous", | 1311 | OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "keyNonContiguous and scaleNonContiguous", |
| @@ -1264,12 +1349,19 @@ void QLIV2InfoParser::GenerateInfo(QLIV2TilingInfo &QLIV2Info) | |||
| 1264 | QLIV2Info.keyStridesVec = keyStridesVec_; | 1349 | QLIV2Info.keyStridesVec = keyStridesVec_; |
| 1265 | QLIV2Info.keyDequantScaleStridesVec = keyDequantScaleStridesVec_; | 1350 | QLIV2Info.keyDequantScaleStridesVec = keyDequantScaleStridesVec_; |
| 1266 | if (!keyStridesVec_.empty()) { | 1351 | if (!keyStridesVec_.empty()) { |
| 1267 | - QLIV2Info.keyStride0 = static_cast<uint32_t>(keyStridesVec_[0]); | 1352 | + uint32_t keyStride0 = static_cast<uint32_t>(keyStridesVec_[0]); |
| 1353 | + if (*opParamInfo_.quantMode == QUANT_MODE_MXFP4) { | ||
| 1354 | + // FP4 shape stride以逻辑元素计数,kernel侧以打包后的uint8为寻址单位。 | ||
| 1355 | + keyStride0 /= MXFP4_PACK_NUM; | ||
| 1356 | + } | ||
| 1357 | + QLIV2Info.keyStride0 = keyStride0; | ||
| 1268 | } else { | 1358 | } else { |
| 1269 | QLIV2Info.keyStride0 = 0; // 非PA无需使用stride | 1359 | QLIV2Info.keyStride0 = 0; // 非PA无需使用stride |
| 1270 | } | 1360 | } |
| 1271 | if (!keyDequantScaleStridesVec_.empty()) { | 1361 | if (!keyDequantScaleStridesVec_.empty()) { |
| 1272 | QLIV2Info.keyDequantScaleStride0 = static_cast<uint32_t>(keyDequantScaleStridesVec_[0]); | 1362 | QLIV2Info.keyDequantScaleStride0 = static_cast<uint32_t>(keyDequantScaleStridesVec_[0]); |
| 1363 | + } else if ((*opParamInfo_.quantMode == QUANT_MODE_MXFP8) || (*opParamInfo_.quantMode == QUANT_MODE_MXFP4)) { | ||
| 1364 | + QLIV2Info.keyDequantScaleStride0 = static_cast<uint32_t>(blockSize_) * (headDim_ / MX_SCALE_GROUP_SIZE); | ||
| 1273 | } else { | 1365 | } else { |
| 1274 | QLIV2Info.keyDequantScaleStride0 = 0; | 1366 | QLIV2Info.keyDequantScaleStride0 = 0; |
| 1275 | } | 1367 | } |
| @@ -37,11 +37,7 @@ struct TilingOptionalParaInfo { | |||
| 37 | const gert::Tensor *tensor; | 37 | const gert::Tensor *tensor; |
| 38 | }; | 38 | }; |
| 39 | 39 | ||
| 40 | -enum class DataLayout : uint32_t { | 40 | +enum class DataLayout : uint32_t { BSND = 0, TND = 1, PA_BBND = 2 }; |
| 41 | - BSND = 0, | ||
| 42 | - TND = 1, | ||
| 43 | - PA_BBND = 2 | ||
| 44 | -}; | ||
| 45 | 41 | ||
| 46 | // ------------------算子原型索引常量定义---------------- | 42 | // ------------------算子原型索引常量定义---------------- |
| 47 | // Inputs Index | 43 | // Inputs Index |
| @@ -88,6 +84,14 @@ constexpr uint32_t BLOCK_SIZE_LIMIT = 1024; | |||
| 88 | constexpr uint32_t BLOCK_SIZE_FACTOR = 16; | 84 | constexpr uint32_t BLOCK_SIZE_FACTOR = 16; |
| 89 | constexpr uint32_t SPARSE_MODE_LOWER = 3; | 85 | constexpr uint32_t SPARSE_MODE_LOWER = 3; |
| 90 | constexpr uint32_t METADATA_LIMIT = 1024; | 86 | constexpr uint32_t METADATA_LIMIT = 1024; |
| 87 | +constexpr int32_t QUANT_MODE_FP8 = 1; | ||
| 88 | +constexpr int32_t QUANT_MODE_MXFP8 = 3; | ||
| 89 | +constexpr int32_t QUANT_MODE_HIFLOAT8 = 4; | ||
| 90 | +constexpr int32_t QUANT_MODE_MXFP4 = 5; | ||
| 91 | +constexpr uint32_t MX_SCALE_SHAPE_ALIGN = 64; | ||
| 92 | +constexpr uint32_t MX_E8M0_SCALE_PACK_NUM = 2; // MX的E8M0 scale形状最后一维打包数为2 | ||
| 93 | +constexpr uint32_t MXFP4_PACK_NUM = 2; // 每个uint8承载2个FP4 E2M1逻辑元素 | ||
| 94 | +constexpr uint32_t MX_SCALE_GROUP_SIZE = 32; // MX量化每32个D维元素对应1个E8M0 scale | ||
| 91 | 95 | ||
| 92 | // -----------算子TilingData定义--------------- | 96 | // -----------算子TilingData定义--------------- |
| 93 | BEGIN_TILING_DATA_DEF(QLIV2TilingData) | 97 | BEGIN_TILING_DATA_DEF(QLIV2TilingData) |
| @@ -269,5 +273,5 @@ private: | |||
| 269 | QLIV2TilingData tilingData_; | 273 | QLIV2TilingData tilingData_; |
| 270 | }; | 274 | }; |
| 271 | 275 | ||
| 272 | -} // namespace optiling | 276 | +} // namespace optiling |
| 273 | -#endif // QUANT_LIGHTNING_INDEXER_V2_TILING_H | 277 | +#endif // QUANT_LIGHTNING_INDEXER_V2_TILING_H |
| @@ -16,30 +16,42 @@ | |||
| 16 | #define QUANT_LIGHTNING_INDEXER_V2_COMMON_H | 16 | #define QUANT_LIGHTNING_INDEXER_V2_COMMON_H |
| 17 | using namespace AscendC; | 17 | using namespace AscendC; |
| 18 | namespace QLIV2Common { | 18 | namespace QLIV2Common { |
| 19 | +using FP8E4M3 = fp8_e4m3fn_t; | ||
| 20 | +using FP4E2M1 = fp4x2_e2m1_t; | ||
| 21 | +using FP8E8M0 = fp8_e8m0_t; | ||
| 22 | + | ||
| 23 | +constexpr uint32_t MX_SCALE_GROUP_SIZE = 32; // 每32个D维度元素一个scale | ||
| 24 | +constexpr uint32_t FP8_TWO = 2; // 2个FP8E8M0打包成1个BF16 | ||
| 25 | +constexpr uint32_t FP4_PACK_NUM = 2; // 2个FP4E2M1打包成1个字节存储 | ||
| 19 | 26 | ||
| 20 | // 与tiling的layout保持一致 | 27 | // 与tiling的layout保持一致 |
| 21 | -enum class LI_LAYOUT : uint32_t { | 28 | +enum class LI_LAYOUT : uint32_t { BSND = 0, TND = 1, PA_BBND = 2 }; |
| 22 | - BSND = 0, | ||
| 23 | - TND = 1, | ||
| 24 | - PA_BBND = 2 | ||
| 25 | -}; | ||
| 26 | 29 | ||
| 27 | template <typename Q_T, typename K_T, typename QK_T, typename SCORE_T, typename OUT_T, | 30 | template <typename Q_T, typename K_T, typename QK_T, typename SCORE_T, typename OUT_T, |
| 28 | - const bool PAGE_ATTENTION = false, | 31 | + const bool PAGE_ATTENTION = false, LI_LAYOUT Q_LAYOUT_T = LI_LAYOUT::BSND, |
| 29 | - LI_LAYOUT Q_LAYOUT_T = LI_LAYOUT::BSND, LI_LAYOUT K_LAYOUT_T = LI_LAYOUT::PA_BBND, typename... Args> | 32 | + LI_LAYOUT K_LAYOUT_T = LI_LAYOUT::PA_BBND, typename SCALE_T = float, typename WEIGHT_T = float, |
| 33 | + typename... Args> | ||
| 30 | struct QLIV2Type { | 34 | struct QLIV2Type { |
| 31 | - static_assert( | 35 | + static_assert((std::is_same_v<QK_T, float> && |
| 32 | - (std::is_same_v<QK_T, float> && | 36 | + (std::is_same_v<SCORE_T, uint32_t> || std::is_same_v<SCORE_T, uint16_t>)) || |
| 33 | - (std::is_same_v<SCORE_T, uint32_t> || std::is_same_v<SCORE_T, uint16_t>)) || | 37 | + (std::is_same_v<QK_T, bfloat16_t> && std::is_same_v<SCORE_T, uint16_t>), |
| 34 | - (std::is_same_v<QK_T, bfloat16_t> && | 38 | + "Invalid combination of QK_T and SCORE_T"); |
| 35 | - std::is_same_v<SCORE_T, uint16_t>), | 39 | + using rawQueryType = Q_T; |
| 36 | - "Invalid combination of QK_T and SCORE_T" | 40 | + using rawKeyType = K_T; |
| 37 | - ); | 41 | + |
| 38 | - using queryType = Q_T; | 42 | + static constexpr bool isMxFp8 = std::is_same_v<rawQueryType, FP8E4M3> && std::is_same_v<rawKeyType, FP8E4M3> && |
| 39 | - using keyType = K_T; | 43 | + std::is_same_v<SCALE_T, FP8E8M0>; |
| 44 | + static constexpr bool isMxFp4 = std::is_same_v<rawQueryType, FP4E2M1> && std::is_same_v<rawKeyType, FP4E2M1> && | ||
| 45 | + std::is_same_v<SCALE_T, FP8E8M0>; | ||
| 46 | + static constexpr bool isMx = isMxFp8 || isMxFp4; | ||
| 47 | + | ||
| 48 | + using queryType = std::conditional_t<isMxFp4, uint8_t, rawQueryType>; | ||
| 49 | + using keyType = std::conditional_t<isMxFp4, uint8_t, rawKeyType>; | ||
| 40 | using queryKeyType = QK_T; | 50 | using queryKeyType = QK_T; |
| 41 | using scoreType = SCORE_T; | 51 | using scoreType = SCORE_T; |
| 42 | using outputType = OUT_T; | 52 | using outputType = OUT_T; |
| 53 | + using scaleType = SCALE_T; | ||
| 54 | + using weightType = WEIGHT_T; | ||
| 43 | 55 | ||
| 44 | static constexpr bool pageAttention = PAGE_ATTENTION; | 56 | static constexpr bool pageAttention = PAGE_ATTENTION; |
| 45 | static constexpr LI_LAYOUT layout = Q_LAYOUT_T; | 57 | static constexpr LI_LAYOUT layout = Q_LAYOUT_T; |
| @@ -71,6 +83,7 @@ struct RunInfo { | |||
| 71 | uint32_t curSequsedK; | 83 | uint32_t curSequsedK; |
| 72 | uint64_t tensorQueryOffset; | 84 | uint64_t tensorQueryOffset; |
| 73 | uint64_t tensorKeyOffset; | 85 | uint64_t tensorKeyOffset; |
| 86 | + uint64_t tensorQScaleOffset; // MX场景qScale在Cube核使用的偏移 | ||
| 74 | uint64_t tensorKeyScaleOffset; | 87 | uint64_t tensorKeyScaleOffset; |
| 75 | uint64_t tensorWeightsOffset; | 88 | uint64_t tensorWeightsOffset; |
| 76 | uint64_t indiceOutOffset; | 89 | uint64_t indiceOutOffset; |
| @@ -124,50 +137,50 @@ struct ConstInfo { | |||
| 124 | uint64_t qHeadNum = 0ULL; | 137 | uint64_t qHeadNum = 0ULL; |
| 125 | uint64_t kHeadNum; | 138 | uint64_t kHeadNum; |
| 126 | uint64_t headDim; | 139 | uint64_t headDim; |
| 127 | - uint64_t sparseCount; // topK选取大小 | 140 | + uint64_t sparseCount; // topK选取大小 |
| 128 | - uint64_t kSeqSize = 0ULL; // kv最大S长度 | 141 | + uint64_t kSeqSize = 0ULL; // kv最大S长度 |
| 129 | - uint64_t qSeqSize = 1ULL; // q最大S长度 | 142 | + uint64_t qSeqSize = 1ULL; // q最大S长度 |
| 130 | - uint32_t kCacheBlockSize = 0; // PA场景的block size | 143 | + uint32_t kCacheBlockSize = 0; // PA场景的block size |
| 131 | - uint32_t maxBlockNumPerBatch = 0; // PA场景的最大单batch block number | 144 | + uint32_t maxBlockNumPerBatch = 0; // PA场景的最大单batch block number |
| 132 | - LI_LAYOUT outputLayout; // 输出的格式 | 145 | + LI_LAYOUT outputLayout; // 输出的格式 |
| 133 | bool attenMaskFlag = false; | 146 | bool attenMaskFlag = false; |
| 134 | uint32_t cmpRatio = 1; | 147 | uint32_t cmpRatio = 1; |
| 135 | uint32_t keyStride0 = 0; | 148 | uint32_t keyStride0 = 0; |
| 136 | uint32_t keyDequantScaleStride0 = 0; | 149 | uint32_t keyDequantScaleStride0 = 0; |
| 137 | int32_t maxSeqlenQ = -1; | 150 | int32_t maxSeqlenQ = -1; |
| 138 | - uint32_t quantMode = 1; // quant模式,默认为1 | 151 | + uint32_t quantMode = 1; // quant模式,默认为1 |
| 139 | - | 152 | + |
| 140 | - uint32_t actualLenQDims = 0U; // query的actualSeqLength 的维度 | 153 | + uint32_t actualLenQDims = 0U; // query的actualSeqLength 的维度 |
| 141 | - uint32_t actualLenDims = 0U; // KV 的actualSeqLength 的维度 | 154 | + uint32_t actualLenDims = 0U; // KV 的actualSeqLength 的维度 |
| 142 | - uint32_t cmpResiduaKLenDims = 0U; // cmpResidualK的维度 | 155 | + uint32_t cmpResiduaKLenDims = 0U; // cmpResidualK的维度 |
| 143 | - bool isAccumSeqS1 = false; // 是否累加模式 | 156 | + bool isAccumSeqS1 = false; // 是否累加模式 |
| 144 | - bool isAccumSeqS2 = false; // 是否累加模式 | 157 | + bool isAccumSeqS2 = false; // 是否累加模式 |
| 145 | bool isLDOpen = false; | 158 | bool isLDOpen = false; |
| 146 | bool returnValue = false; | 159 | bool returnValue = false; |
| 147 | }; | 160 | }; |
| 148 | 161 | ||
| 149 | struct LdSplitCoreInfo { | 162 | struct LdSplitCoreInfo { |
| 150 | - bool isLdCoreEnable = false; // 当前核是否参与规约任务 | 163 | + bool isLdCoreEnable = false; // 当前核是否参与规约任务 |
| 151 | - uint32_t saveWorkSpaceIdx = 0U; // 存放LD参数的地址 | 164 | + uint32_t saveWorkSpaceIdx = 0U; // 存放LD参数的地址 |
| 152 | - uint32_t bn2Idx = 0U; // 归约任务 | 165 | + uint32_t bn2Idx = 0U; // 归约任务 |
| 153 | uint32_t bIdx = 0U; | 166 | uint32_t bIdx = 0U; |
| 154 | uint32_t n2Idx = 0U; | 167 | uint32_t n2Idx = 0U; |
| 155 | uint32_t mIdx = 0U; | 168 | uint32_t mIdx = 0U; |
| 156 | - uint32_t workspaceIdx = 0U; // 当前AIV核上规约任务的索引 | 169 | + uint32_t workspaceIdx = 0U; // 当前AIV核上规约任务的索引 |
| 157 | - uint32_t workspaceNum = 0U; // 当前AIV核上规约任务的S2切分数量 | 170 | + uint32_t workspaceNum = 0U; // 当前AIV核上规约任务的S2切分数量 |
| 158 | uint32_t mStart = 0U; | 171 | uint32_t mStart = 0U; |
| 159 | uint32_t mNum = 0U; | 172 | uint32_t mNum = 0U; |
| 160 | - uint64_t indiceOutCoreOffset = 0U; // 最终输出索引搬出Topk的初始偏移地址 | 173 | + uint64_t indiceOutCoreOffset = 0U; // 最终输出索引搬出Topk的初始偏移地址 |
| 161 | }; | 174 | }; |
| 162 | 175 | ||
| 163 | struct SplitCoreInfo { | 176 | struct SplitCoreInfo { |
| 164 | - uint32_t s2Start = 0U; // S2的起始位置 | 177 | + uint32_t s2Start = 0U; // S2的起始位置 |
| 165 | - uint32_t s2End = 0U; // S2循环index上限 | 178 | + uint32_t s2End = 0U; // S2循环index上限 |
| 166 | uint32_t bN2Start = 0U; | 179 | uint32_t bN2Start = 0U; |
| 167 | uint32_t bN2End = 0U; | 180 | uint32_t bN2End = 0U; |
| 168 | uint32_t gS1Start = 0U; | 181 | uint32_t gS1Start = 0U; |
| 169 | uint32_t gS1End = 0U; | 182 | uint32_t gS1End = 0U; |
| 170 | - bool isLD = false; // 当前核是否需要进行Decode归约任务 | 183 | + bool isLD = false; // 当前核是否需要进行Decode归约任务 |
| 171 | bool isCoreEnable = false; | 184 | bool isCoreEnable = false; |
| 172 | }; | 185 | }; |
| 173 | 186 | ||
| @@ -194,19 +207,19 @@ __aicore__ inline T CeilDiv(T num, T rnd) | |||
| 194 | { | 207 | { |
| 195 | return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd))); | 208 | return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd))); |
| 196 | } | 209 | } |
| 197 | -} // namespace QLIV2Common | 210 | +} // namespace QLIV2Common |
| 198 | 211 | ||
| 199 | // bank冲突优化 | 212 | // bank冲突优化 |
| 200 | // david 256KB bank layout | 213 | // david 256KB bank layout |
| 201 | // shape ( bank_depth ( banks bank_groups block)) (512 ( 2 8 32)) | 214 | // shape ( bank_depth ( banks bank_groups block)) (512 ( 2 8 32)) |
| 202 | // stride (banks*bank_groups*block (bank_groups*block block 1)) (512 (256 32 1)) | 215 | // stride (banks*bank_groups*block (bank_groups*block block 1)) (512 (256 32 1)) |
| 203 | -#define UB_BLOCK 32 // 32B | 216 | +#define UB_BLOCK 32 // 32B |
| 204 | -#define UB_BANK_GROUPS 8 | 217 | +#define UB_BANK_GROUPS 8 |
| 205 | -#define UB_BANKS 2 | 218 | +#define UB_BANKS 2 |
| 206 | -#define UB_BANK_DEPTH 512 | 219 | +#define UB_BANK_DEPTH 512 |
| 207 | 220 | ||
| 208 | -#define UB_BANK_GROUP_STRIDE UB_BLOCK // 32B | 221 | +#define UB_BANK_GROUP_STRIDE UB_BLOCK // 32B |
| 209 | -#define UB_BANK_STRIDE (UB_BANK_GROUPS * UB_BLOCK) // 256B | 222 | +#define UB_BANK_STRIDE (UB_BANK_GROUPS * UB_BLOCK) // 256B |
| 210 | -#define UB_BANK_DEPTH_STRIDE (UB_BANKS * UB_BANK_GROUPS * UB_BLOCK) // 512B | 223 | +#define UB_BANK_DEPTH_STRIDE (UB_BANKS * UB_BANK_GROUPS * UB_BLOCK) // 512B |
| 211 | 224 | ||
| 212 | -#endif // QUANT_LIGHTNING_INDEXER_V2_COMMON_H | 225 | +#endif // QUANT_LIGHTNING_INDEXER_V2_COMMON_H |
| @@ -78,6 +78,9 @@ public: | |||
| 78 | static constexpr LI_LAYOUT K_LAYOUT_T = QLIV2T::keyLayout; | 78 | static constexpr LI_LAYOUT K_LAYOUT_T = QLIV2T::keyLayout; |
| 79 | 79 | ||
| 80 | using SCORE_T = typename QLIV2T::scoreType; | 80 | using SCORE_T = typename QLIV2T::scoreType; |
| 81 | + using SCALE_T = typename QLIV2T::scaleType; | ||
| 82 | + using WEIGHT_T = typename QLIV2T::weightType; | ||
| 83 | + static constexpr bool IS_MX = QLIV2T::isMx; | ||
| 81 | 84 | ||
| 82 | QLIV2Matmul<QLIV2T> matmulService; | 85 | QLIV2Matmul<QLIV2T> matmulService; |
| 83 | QLIV2Vector<QLIV2T> vectorService; | 86 | QLIV2Vector<QLIV2T> vectorService; |
| @@ -103,6 +106,7 @@ protected: | |||
| 103 | // offset | 106 | // offset |
| 104 | uint64_t queryCoreOffset = 0ULL; | 107 | uint64_t queryCoreOffset = 0ULL; |
| 105 | uint64_t keyCoreOffset = 0ULL; | 108 | uint64_t keyCoreOffset = 0ULL; |
| 109 | + uint64_t qScaleCoreOffset = 0ULL; // MX场景qScale偏移 | ||
| 106 | uint64_t keyScaleCoreOffset = 0ULL; | 110 | uint64_t keyScaleCoreOffset = 0ULL; |
| 107 | uint64_t weightsCoreOffset = 0ULL; | 111 | uint64_t weightsCoreOffset = 0ULL; |
| 108 | uint64_t indiceOutCoreOffset = 0ULL; | 112 | uint64_t indiceOutCoreOffset = 0ULL; |
| @@ -118,9 +122,9 @@ protected: | |||
| 118 | // ================================Global Buffer区================================= | 122 | // ================================Global Buffer区================================= |
| 119 | GlobalTensor<Q_T> queryGm; | 123 | GlobalTensor<Q_T> queryGm; |
| 120 | GlobalTensor<K_T> keyGm; | 124 | GlobalTensor<K_T> keyGm; |
| 121 | - GlobalTensor<float> weightsGm; | 125 | + GlobalTensor<WEIGHT_T> weightsGm; |
| 122 | - GlobalTensor<float> qScaleGm; | 126 | + GlobalTensor<bfloat16_t> mxQueryScaleGmBf16; |
| 123 | - GlobalTensor<float> kScaleGm; | 127 | + GlobalTensor<bfloat16_t> mxKeyScaleGmBf16; |
| 124 | GlobalTensor<uint32_t> metadataGm; | 128 | GlobalTensor<uint32_t> metadataGm; |
| 125 | 129 | ||
| 126 | GlobalTensor<int32_t> indiceOutGm; | 130 | GlobalTensor<int32_t> indiceOutGm; |
| @@ -421,11 +425,10 @@ __aicore__ inline void QLIV2Preload<QLIV2T>::SplitCoreByAICPU(uint32_t cubeCoreI | |||
| 421 | } else { // BSND | 425 | } else { // BSND |
| 422 | actualSeqQPrefixSum = (ldInfo.bIdx <= 0) ? 0 : static_cast<uint64_t>(ldInfo.bIdx) * constInfo.qSeqSize; | 426 | actualSeqQPrefixSum = (ldInfo.bIdx <= 0) ? 0 : static_cast<uint64_t>(ldInfo.bIdx) * constInfo.qSeqSize; |
| 423 | } | 427 | } |
| 424 | - ldInfo.indiceOutCoreOffset = | 428 | + ldInfo.indiceOutCoreOffset = actualSeqQPrefixSum * constInfo.kHeadNum * constInfo.sparseCount + |
| 425 | - static_cast<uint64_t>(actualSeqQPrefixSum) * constInfo.kHeadNum * constInfo.sparseCount + | 429 | + static_cast<uint64_t>(ldInfo.n2Idx) * constInfo.sparseCount + |
| 426 | - ldInfo.n2Idx * constInfo.sparseCount + | 430 | + static_cast<uint64_t>(ldInfo.mIdx) * constInfo.s1BaseSize * constInfo.kHeadNum * |
| 427 | - static_cast<uint64_t>(ldInfo.mIdx) * constInfo.s1BaseSize * constInfo.kHeadNum * | 431 | + constInfo.sparseCount; // 搬出Topk的初始偏移地址 |
| 428 | - constInfo.sparseCount; // 搬出Topk的初始偏移地址 | ||
| 429 | } | 432 | } |
| 430 | } | 433 | } |
| 431 | 434 | ||
| @@ -438,10 +441,9 @@ __aicore__ inline void QLIV2Preload<QLIV2T>::DealActSeqLenIsZero(uint32_t bIdx, | |||
| 438 | uint32_t s1Count = cuSeqlensQGm.GetValue(bIdx + 1) - tBase; | 441 | uint32_t s1Count = cuSeqlensQGm.GetValue(bIdx + 1) - tBase; |
| 439 | 442 | ||
| 440 | for (uint32_t s1Idx = s1Start; s1Idx < s1Count; s1Idx++) { | 443 | for (uint32_t s1Idx = s1Start; s1Idx < s1Count; s1Idx++) { |
| 441 | - // T轴、s1轴偏移 + N2轴偏移 | ||
| 442 | uint64_t indiceOutOffset = | 444 | uint64_t indiceOutOffset = |
| 443 | (static_cast<uint64_t>(tBase) + s1Idx) * constInfo.kHeadNum * constInfo.sparseCount + | 445 | (static_cast<uint64_t>(tBase) + s1Idx) * constInfo.kHeadNum * constInfo.sparseCount + |
| 444 | - static_cast<uint64_t>(n2Idx) * constInfo.sparseCount; | 446 | + static_cast<uint64_t>(n2Idx) * constInfo.sparseCount; // N2轴偏移 |
| 445 | vectorService.CleanInvalidOutput(indiceOutOffset); | 447 | vectorService.CleanInvalidOutput(indiceOutOffset); |
| 446 | } | 448 | } |
| 447 | } else if (constInfo.outputLayout == LI_LAYOUT::BSND) { | 449 | } else if (constInfo.outputLayout == LI_LAYOUT::BSND) { |
| @@ -449,8 +451,8 @@ __aicore__ inline void QLIV2Preload<QLIV2T>::DealActSeqLenIsZero(uint32_t bIdx, | |||
| 449 | // B,S1,N2,K | 451 | // B,S1,N2,K |
| 450 | uint64_t indiceOutOffset = | 452 | uint64_t indiceOutOffset = |
| 451 | static_cast<uint64_t>(bIdx) * constInfo.qSeqSize * constInfo.kHeadNum * constInfo.sparseCount + | 453 | static_cast<uint64_t>(bIdx) * constInfo.qSeqSize * constInfo.kHeadNum * constInfo.sparseCount + |
| 452 | - static_cast<uint64_t>(s1Idx) * constInfo.kHeadNum * constInfo.sparseCount + // B轴、S1轴偏移 | 454 | + static_cast<uint64_t>(s1Idx) * constInfo.kHeadNum * constInfo.sparseCount + |
| 453 | - static_cast<uint64_t>(n2Idx) * constInfo.sparseCount; // N2轴偏移 | 455 | + static_cast<uint64_t>(n2Idx) * constInfo.sparseCount; // N2轴偏移 |
| 454 | vectorService.CleanInvalidOutput(indiceOutOffset); | 456 | vectorService.CleanInvalidOutput(indiceOutOffset); |
| 455 | } | 457 | } |
| 456 | } | 458 | } |
| @@ -502,18 +504,23 @@ __aicore__ inline void QLIV2Preload<QLIV2T>::Init( | |||
| 502 | 504 | ||
| 503 | if ASCEND_IS_AIV { | 505 | if ASCEND_IS_AIV { |
| 504 | indiceOutGm.SetGlobalBuffer((__gm__ int32_t *)sparseIndices); | 506 | indiceOutGm.SetGlobalBuffer((__gm__ int32_t *)sparseIndices); |
| 505 | - weightsGm.SetGlobalBuffer((__gm__ float *)weights); | 507 | + weightsGm.SetGlobalBuffer((__gm__ WEIGHT_T *)weights); |
| 506 | - qScaleGm.SetGlobalBuffer((__gm__ float *)queryScale); | ||
| 507 | - kScaleGm.SetGlobalBuffer((__gm__ float *)keyScale); | ||
| 508 | blockTableGm.SetGlobalBuffer((__gm__ int32_t *)blockTable); | 508 | blockTableGm.SetGlobalBuffer((__gm__ int32_t *)blockTable); |
| 509 | valueOutGm.SetGlobalBuffer((__gm__ bfloat16_t *)sparseValues); | 509 | valueOutGm.SetGlobalBuffer((__gm__ bfloat16_t *)sparseValues); |
| 510 | if (outputIdxOffset != nullptr) { | 510 | if (outputIdxOffset != nullptr) { |
| 511 | isOutputIdxOffsetValid = true; | 511 | isOutputIdxOffsetValid = true; |
| 512 | outputIdxOffsetGm.SetGlobalBuffer((__gm__ int32_t *)outputIdxOffset); | 512 | outputIdxOffsetGm.SetGlobalBuffer((__gm__ int32_t *)outputIdxOffset); |
| 513 | } | 513 | } |
| 514 | - vectorService.InitVecInputTensor(weightsGm, qScaleGm, kScaleGm, indiceOutGm, blockTableGm, valueOutGm, | 514 | + if constexpr (IS_MX) { |
| 515 | - outputIdxOffsetGm); | 515 | + vectorService.InitVecInputTensor(weightsGm, indiceOutGm, blockTableGm, valueOutGm, outputIdxOffsetGm); |
| 516 | - | 516 | + } else { |
| 517 | + GlobalTensor<float> qScaleGmForVec; | ||
| 518 | + GlobalTensor<float> kScaleGmForVec; | ||
| 519 | + qScaleGmForVec.SetGlobalBuffer((__gm__ float *)queryScale); | ||
| 520 | + kScaleGmForVec.SetGlobalBuffer((__gm__ float *)keyScale); | ||
| 521 | + vectorService.InitVecInputTensor(weightsGm, indiceOutGm, blockTableGm, valueOutGm, outputIdxOffsetGm, | ||
| 522 | + qScaleGmForVec, kScaleGmForVec); | ||
| 523 | + } | ||
| 517 | vectorService.InitVecWorkspaceTensor(scoreGm, ldScoreGm, ldIndexGm); | 524 | vectorService.InitVecWorkspaceTensor(scoreGm, ldScoreGm, ldIndexGm); |
| 518 | vectorService.InitParams(constInfo, ldInfo, tiling); | 525 | vectorService.InitParams(constInfo, ldInfo, tiling); |
| 519 | } else { | 526 | } else { |
| @@ -523,7 +530,13 @@ __aicore__ inline void QLIV2Preload<QLIV2T>::Init( | |||
| 523 | blockTableGm.SetGlobalBuffer((__gm__ int32_t *)blockTable); | 530 | blockTableGm.SetGlobalBuffer((__gm__ int32_t *)blockTable); |
| 524 | } | 531 | } |
| 525 | keyGm.SetGlobalBuffer((__gm__ K_T *)key); | 532 | keyGm.SetGlobalBuffer((__gm__ K_T *)key); |
| 526 | - matmulService.InitMm1GlobalTensor(blockTableGm, keyGm, queryGm); | 533 | + if constexpr (IS_MX) { |
| 534 | + mxQueryScaleGmBf16.SetGlobalBuffer((__gm__ bfloat16_t *)queryScale); | ||
| 535 | + mxKeyScaleGmBf16.SetGlobalBuffer((__gm__ bfloat16_t *)keyScale); | ||
| 536 | + matmulService.InitMm1GlobalTensor(blockTableGm, keyGm, queryGm, mxKeyScaleGmBf16, mxQueryScaleGmBf16); | ||
| 537 | + } else { | ||
| 538 | + matmulService.InitMm1GlobalTensor(blockTableGm, keyGm, queryGm); | ||
| 539 | + } | ||
| 527 | } | 540 | } |
| 528 | InitBuffers(); | 541 | InitBuffers(); |
| 529 | } | 542 | } |
| @@ -630,6 +643,10 @@ __aicore__ inline void QLIV2Preload<QLIV2T>::CalcRunInfo(uint32_t loop, uint32_t | |||
| 630 | runInfo.isAllLoopEnd = (runInfo.bN2Idx == splitCoreInfo.bN2End) && (runInfo.gS1Idx == splitCoreInfo.gS1End) && | 643 | runInfo.isAllLoopEnd = (runInfo.bN2Idx == splitCoreInfo.bN2End) && (runInfo.gS1Idx == splitCoreInfo.gS1End) && |
| 631 | (runInfo.s2Idx == splitCoreInfo.s2End); | 644 | (runInfo.s2Idx == splitCoreInfo.s2End); |
| 632 | runInfo.isOutputIdxOffsetValid = isOutputIdxOffsetValid; | 645 | runInfo.isOutputIdxOffsetValid = isOutputIdxOffsetValid; |
| 646 | + uint64_t qkHeadDim = constInfo.headDim; | ||
| 647 | + if constexpr (QLIV2T::isMxFp4) { | ||
| 648 | + qkHeadDim = constInfo.headDim / FP4_PACK_NUM; | ||
| 649 | + } | ||
| 633 | if (runInfo.isFirstS2InnerLoop) { | 650 | if (runInfo.isFirstS2InnerLoop) { |
| 634 | uint64_t actualSeqQPrefixSum; | 651 | uint64_t actualSeqQPrefixSum; |
| 635 | if constexpr (Q_LAYOUT_T == LI_LAYOUT::TND) { | 652 | if constexpr (Q_LAYOUT_T == LI_LAYOUT::TND) { |
| @@ -647,9 +664,9 @@ __aicore__ inline void QLIV2Preload<QLIV2T>::CalcRunInfo(uint32_t loop, uint32_t | |||
| 647 | } else { // BSND | 664 | } else { // BSND |
| 648 | actualSeqQPrefixSum = (runInfo.bIdx <= 0) ? 0 : static_cast<uint64_t>(runInfo.bIdx) * constInfo.qSeqSize; | 665 | actualSeqQPrefixSum = (runInfo.bIdx <= 0) ? 0 : static_cast<uint64_t>(runInfo.bIdx) * constInfo.qSeqSize; |
| 649 | } | 666 | } |
| 650 | - uint64_t tndBIdxOffset = actualSeqQPrefixSum * constInfo.qHeadNum * constInfo.headDim; | 667 | + uint64_t tndBIdxOffset = actualSeqQPrefixSum * constInfo.qHeadNum * qkHeadDim; |
| 651 | // B,S1,N1(N2,G),D | 668 | // B,S1,N1(N2,G),D |
| 652 | - queryCoreOffset = tndBIdxOffset + runInfo.gS1Idx * constInfo.mBaseSize * constInfo.headDim; | 669 | + queryCoreOffset = tndBIdxOffset + runInfo.gS1Idx * constInfo.mBaseSize * qkHeadDim; |
| 653 | // B,S1,N1(N2,G)/T,N1(N2,G) | 670 | // B,S1,N1(N2,G)/T,N1(N2,G) |
| 654 | weightsCoreOffset = actualSeqQPrefixSum * constInfo.qHeadNum + runInfo.n2Idx * constInfo.gSize; | 671 | weightsCoreOffset = actualSeqQPrefixSum * constInfo.qHeadNum + runInfo.n2Idx * constInfo.gSize; |
| 655 | // B,S1,N2,k/T,N2,k | 672 | // B,S1,N2,k/T,N2,k |
| @@ -659,6 +676,14 @@ __aicore__ inline void QLIV2Preload<QLIV2T>::CalcRunInfo(uint32_t loop, uint32_t | |||
| 659 | actualSeqQPrefixSum * constInfo.kHeadNum * constInfo.sparseCount + runInfo.n2Idx * constInfo.sparseCount; | 676 | actualSeqQPrefixSum * constInfo.kHeadNum * constInfo.sparseCount + runInfo.n2Idx * constInfo.sparseCount; |
| 660 | outputIdxCoreOffset = | 677 | outputIdxCoreOffset = |
| 661 | (actualSeqQPrefixSum + runInfo.gS1Idx * constInfo.s1BaseSize) * constInfo.kHeadNum + runInfo.n2Idx; | 678 | (actualSeqQPrefixSum + runInfo.gS1Idx * constInfo.s1BaseSize) * constInfo.kHeadNum + runInfo.n2Idx; |
| 679 | + if constexpr (IS_MX) { | ||
| 680 | + // MX: qScale offset, shape [B, S1, N1, D/64, 2] | ||
| 681 | + uint64_t qScalePrefixSum = | ||
| 682 | + actualSeqQPrefixSum * constInfo.qHeadNum * (constInfo.headDim / MX_SCALE_GROUP_SIZE); | ||
| 683 | + uint64_t qScaleS1Offset = | ||
| 684 | + static_cast<uint64_t>(runInfo.gS1Idx) * constInfo.mBaseSize * (constInfo.headDim / MX_SCALE_GROUP_SIZE); | ||
| 685 | + qScaleCoreOffset = qScalePrefixSum + qScaleS1Offset; | ||
| 686 | + } | ||
| 662 | } | 687 | } |
| 663 | uint64_t actualSeqKPrefixSum; | 688 | uint64_t actualSeqKPrefixSum; |
| 664 | if constexpr (K_LAYOUT_T == LI_LAYOUT::TND) { // T N2 D, cu_seqlens_k | 689 | if constexpr (K_LAYOUT_T == LI_LAYOUT::TND) { // T N2 D, cu_seqlens_k |
| @@ -666,19 +691,23 @@ __aicore__ inline void QLIV2Preload<QLIV2T>::CalcRunInfo(uint32_t loop, uint32_t | |||
| 666 | } else { | 691 | } else { |
| 667 | actualSeqKPrefixSum = (runInfo.bIdx <= 0) ? 0 : runInfo.bIdx * constInfo.kSeqSize; | 692 | actualSeqKPrefixSum = (runInfo.bIdx <= 0) ? 0 : runInfo.bIdx * constInfo.kSeqSize; |
| 668 | } | 693 | } |
| 669 | - uint64_t tndBIdxOffsetForK = actualSeqKPrefixSum * constInfo.kHeadNum * constInfo.headDim; | 694 | + uint64_t tndBIdxOffsetForK = actualSeqKPrefixSum * constInfo.kHeadNum * qkHeadDim; |
| 670 | - keyCoreOffset = tndBIdxOffsetForK + runInfo.s2Idx * constInfo.s2BaseSize * constInfo.kHeadNum * constInfo.headDim; | 695 | + keyCoreOffset = tndBIdxOffsetForK + runInfo.s2Idx * constInfo.s2BaseSize * constInfo.kHeadNum * qkHeadDim; |
| 671 | - keyScaleCoreOffset = (actualSeqKPrefixSum + runInfo.s2Idx * constInfo.s2BaseSize) * constInfo.kHeadNum; | 696 | + uint64_t keyScaleS2Offset = actualSeqKPrefixSum + static_cast<uint64_t>(runInfo.s2Idx) * constInfo.s2BaseSize; |
| 697 | + if constexpr (IS_MX) { | ||
| 698 | + // MX: kScale offset, shape [B, S2, N2, D/64, 2] | ||
| 699 | + keyScaleCoreOffset = keyScaleS2Offset * constInfo.kHeadNum * (constInfo.headDim / MX_SCALE_GROUP_SIZE); | ||
| 700 | + } else { | ||
| 701 | + keyScaleCoreOffset = keyScaleS2Offset * constInfo.kHeadNum; | ||
| 702 | + } | ||
| 672 | runInfo.tensorQueryOffset = queryCoreOffset; | 703 | runInfo.tensorQueryOffset = queryCoreOffset; |
| 673 | runInfo.tensorKeyOffset = keyCoreOffset; | 704 | runInfo.tensorKeyOffset = keyCoreOffset; |
| 705 | + runInfo.tensorQScaleOffset = qScaleCoreOffset; | ||
| 674 | runInfo.tensorKeyScaleOffset = keyScaleCoreOffset; | 706 | runInfo.tensorKeyScaleOffset = keyScaleCoreOffset; |
| 675 | runInfo.tensorWeightsOffset = weightsCoreOffset; | 707 | runInfo.tensorWeightsOffset = weightsCoreOffset; |
| 676 | runInfo.indiceOutOffset = indiceOutCoreOffset; | 708 | runInfo.indiceOutOffset = indiceOutCoreOffset; |
| 677 | runInfo.valueOutOffset = valueOutCoreOffset; | 709 | runInfo.valueOutOffset = valueOutCoreOffset; |
| 678 | runInfo.outputIdxCoreOffset = outputIdxCoreOffset; | 710 | runInfo.outputIdxCoreOffset = outputIdxCoreOffset; |
| 679 | - if (runInfo.needTndPadding) { | ||
| 680 | - vectorService.DoTndPadding(runInfo); | ||
| 681 | - } | ||
| 682 | } | 711 | } |
| 683 | 712 | ||
| 684 | template <typename QLIV2T> | 713 | template <typename QLIV2T> |
| @@ -790,6 +819,9 @@ __aicore__ inline void QLIV2Preload<QLIV2T>::ProcessBaseBlock(uint32_t loop, uin | |||
| 790 | if ASCEND_IS_AIC { | 819 | if ASCEND_IS_AIC { |
| 791 | matmulService.ComputeMm1(runInfo); | 820 | matmulService.ComputeMm1(runInfo); |
| 792 | } else { | 821 | } else { |
| 822 | + if (runInfo.needTndPadding) { | ||
| 823 | + vectorService.DoTndPadding(runInfo); | ||
| 824 | + } | ||
| 793 | vectorService.ProcessVec1(runInfo); | 825 | vectorService.ProcessVec1(runInfo); |
| 794 | if (runInfo.isLastS2InnerLoop) { // 本核s2last | 826 | if (runInfo.isLastS2InnerLoop) { // 本核s2last |
| 795 | vectorService.ProcessTopK(runInfo); | 827 | vectorService.ProcessTopK(runInfo); |
Mattention/quant_lightning_indexer_v2/op_kernel/arch35/quant_lightning_indexer_v2_service_cube.h+296-110
Mattention/quant_lightning_indexer_v2/op_kernel/arch35/quant_lightning_indexer_v2_service_vector.h+84-56
| @@ -26,7 +26,6 @@ | |||
| 26 | 26 | ||
| 27 | namespace QLIV2Kernel { | 27 | namespace QLIV2Kernel { |
| 28 | using namespace QLIV2Common; | 28 | using namespace QLIV2Common; |
| 29 | -// ProcessTopK(非LD路径)每次处理的s2长度 | ||
| 30 | constexpr uint32_t TRUNK_LEN_16K = 16384; | 29 | constexpr uint32_t TRUNK_LEN_16K = 16384; |
| 31 | // LD阶段UB目标占用(248KB = 256KB UB - 8KB 系统保留) | 30 | // LD阶段UB目标占用(248KB = 256KB UB - 8KB 系统保留) |
| 32 | constexpr uint32_t LD_UB_TARGET_BYTES = 248 * 1024; | 31 | constexpr uint32_t LD_UB_TARGET_BYTES = 248 * 1024; |
| @@ -40,6 +39,9 @@ public: | |||
| 40 | 39 | ||
| 41 | using QK_T = typename QLIV2T::queryKeyType; | 40 | using QK_T = typename QLIV2T::queryKeyType; |
| 42 | using SCORE_T = typename QLIV2T::scoreType; | 41 | using SCORE_T = typename QLIV2T::scoreType; |
| 42 | + using WEIGHT_T = typename QLIV2T::weightType; | ||
| 43 | + static constexpr bool IS_MX = QLIV2T::isMx; | ||
| 44 | + static constexpr bool IS_MXFP4 = QLIV2T::isMxFp4; | ||
| 43 | 45 | ||
| 44 | __aicore__ inline QLIV2Vector(){}; | 46 | __aicore__ inline QLIV2Vector(){}; |
| 45 | __aicore__ inline void ProcessVec1(const QLIV2Common::RunInfo &info); | 47 | __aicore__ inline void ProcessVec1(const QLIV2Common::RunInfo &info); |
| @@ -51,10 +53,10 @@ public: | |||
| 51 | const QLIV2TilingData *__restrict tilingData); | 53 | const QLIV2TilingData *__restrict tilingData); |
| 52 | __aicore__ inline void InitVecWorkspaceTensor(GlobalTensor<SCORE_T> scoreGm, GlobalTensor<SCORE_T> ldScoreGm, | 54 | __aicore__ inline void InitVecWorkspaceTensor(GlobalTensor<SCORE_T> scoreGm, GlobalTensor<SCORE_T> ldScoreGm, |
| 53 | GlobalTensor<int32_t> ldIndexGm); | 55 | GlobalTensor<int32_t> ldIndexGm); |
| 54 | - __aicore__ inline void InitVecInputTensor(GlobalTensor<float> weightsGm, GlobalTensor<float> qScaleGm, | 56 | + __aicore__ inline void InitVecInputTensor(GlobalTensor<WEIGHT_T> weightsGm, GlobalTensor<int32_t> indiceOutGm, |
| 55 | - GlobalTensor<float> kScaleGm, GlobalTensor<int32_t> indiceOutGm, | ||
| 56 | GlobalTensor<int32_t> blockTableGm, GlobalTensor<bfloat16_t> valueOutGm, | 57 | GlobalTensor<int32_t> blockTableGm, GlobalTensor<bfloat16_t> valueOutGm, |
| 57 | - GlobalTensor<int32_t> outputIdxOffsetGm); | 58 | + GlobalTensor<int32_t> outputIdxOffsetGm, |
| 59 | + GlobalTensor<float> qScaleGm = {}, GlobalTensor<float> kScaleGm = {}); | ||
| 58 | __aicore__ inline void CleanInvalidOutput(int64_t invalidS1offset); | 60 | __aicore__ inline void CleanInvalidOutput(int64_t invalidS1offset); |
| 59 | __aicore__ inline void AllocEventID(); | 61 | __aicore__ inline void AllocEventID(); |
| 60 | __aicore__ inline void FreeEventID(); | 62 | __aicore__ inline void FreeEventID(); |
| @@ -63,7 +65,7 @@ public: | |||
| 63 | 65 | ||
| 64 | protected: | 66 | protected: |
| 65 | GlobalTensor<SCORE_T> scoreGm; | 67 | GlobalTensor<SCORE_T> scoreGm; |
| 66 | - GlobalTensor<float> weightsGm; | 68 | + GlobalTensor<WEIGHT_T> weightsGm; |
| 67 | GlobalTensor<SCORE_T> ldScoreGm; | 69 | GlobalTensor<SCORE_T> ldScoreGm; |
| 68 | GlobalTensor<int32_t> ldIndexGm; | 70 | GlobalTensor<int32_t> ldIndexGm; |
| 69 | GlobalTensor<float> qScaleGm; | 71 | GlobalTensor<float> qScaleGm; |
| @@ -100,7 +102,7 @@ private: | |||
| 100 | LocalTensor<QK_T> resMm1UB_; | 102 | LocalTensor<QK_T> resMm1UB_; |
| 101 | // tmp buff for weight | 103 | // tmp buff for weight |
| 102 | TBuf<TPosition::VECCALC> weightBuf_; | 104 | TBuf<TPosition::VECCALC> weightBuf_; |
| 103 | - LocalTensor<float> weightUB_; | 105 | + LocalTensor<WEIGHT_T> weightUB_; |
| 104 | // tmp buff for weight cast float | 106 | // tmp buff for weight cast float |
| 105 | TBuf<TPosition::VECCALC> weightTempBuf_; | 107 | TBuf<TPosition::VECCALC> weightTempBuf_; |
| 106 | LocalTensor<float> weightTempUB_; | 108 | LocalTensor<float> weightTempUB_; |
| @@ -170,12 +172,11 @@ private: | |||
| 170 | template <typename QLIV2T> | 172 | template <typename QLIV2T> |
| 171 | __aicore__ inline void QLIV2Vector<QLIV2T>::InitBuffers(TPipe *pipe) | 173 | __aicore__ inline void QLIV2Vector<QLIV2T>::InitBuffers(TPipe *pipe) |
| 172 | { | 174 | { |
| 173 | - // 大小:2(开dB) 2 * 64 * 128 * 4 = 128KB | ||
| 174 | pipe->InitBuffer(resMm1Buf_, 2 * CeilDiv(constInfo_.mBaseSize, 2) * s2BaseSize_ * sizeof(QK_T)); | 175 | pipe->InitBuffer(resMm1Buf_, 2 * CeilDiv(constInfo_.mBaseSize, 2) * s2BaseSize_ * sizeof(QK_T)); |
| 175 | resMm1UB_ = resMm1Buf_.Get<QK_T>(); // qk | 176 | resMm1UB_ = resMm1Buf_.Get<QK_T>(); // qk |
| 176 | - // 大小:2(开dB) * 2 * 64 * 2 = 0.5KB | 177 | + // weight buffer按WEIGHT_T访问;UB_BANK_DEPTH_STRIDE的单位已经是字节,无需再乘数据类型大小。 |
| 177 | pipe->InitBuffer(weightBuf_, 2 * CeilDiv(s1BaseSize_, 2) * UB_BANK_DEPTH_STRIDE); | 178 | pipe->InitBuffer(weightBuf_, 2 * CeilDiv(s1BaseSize_, 2) * UB_BANK_DEPTH_STRIDE); |
| 178 | - weightUB_ = weightBuf_.Get<float>(); // weight | 179 | + weightUB_ = weightBuf_.Get<WEIGHT_T>(); // weight |
| 179 | pipe->InitBuffer(weightTempBuf_, 2 * CeilDiv(s1BaseSize_, 2) * UB_BANK_DEPTH_STRIDE); | 180 | pipe->InitBuffer(weightTempBuf_, 2 * CeilDiv(s1BaseSize_, 2) * UB_BANK_DEPTH_STRIDE); |
| 180 | weightTempUB_ = weightTempBuf_.Get<float>(); | 181 | weightTempUB_ = weightTempBuf_.Get<float>(); |
| 181 | // 大小:2(开dB) * 128 * 4 = 1KB | 182 | // 大小:2(开dB) * 128 * 4 = 1KB |
| @@ -207,8 +208,10 @@ __aicore__ inline void QLIV2Vector<QLIV2T>::InitBuffers(TPipe *pipe) | |||
| 207 | topkSharedTmpLocal_ = topkSharedTmpBuf_.Get<uint32_t>(); | 208 | topkSharedTmpLocal_ = topkSharedTmpBuf_.Get<uint32_t>(); |
| 208 | topkOp_.InitBuffers(topkSharedTmpLocal_, indicesOutLocal_); | 209 | topkOp_.InitBuffers(topkSharedTmpLocal_, indicesOutLocal_); |
| 209 | 210 | ||
| 210 | - // 刷-1 | 211 | + // MX场景不走vector侧kScale路径 |
| 211 | - Duplicate(kScaleUB_, float(0), 2 * s2BaseSize_ * 16); | 212 | + if constexpr (!IS_MX) { |
| 213 | + Duplicate(kScaleUB_, float(0), 2 * s2BaseSize_ * 16); | ||
| 214 | + } | ||
| 212 | } | 215 | } |
| 213 | 216 | ||
| 214 | template <typename QLIV2T> | 217 | template <typename QLIV2T> |
| @@ -287,25 +290,29 @@ __aicore__ inline void QLIV2Vector<QLIV2T>::InitParams(const struct QLIV2Common: | |||
| 287 | topkCountAlign16_ = QLIV2Common::Align(constInfo.sparseCount, (uint64_t)16); // topkCount对齐到16 | 290 | topkCountAlign16_ = QLIV2Common::Align(constInfo.sparseCount, (uint64_t)16); // topkCount对齐到16 |
| 288 | topkOp_.Init(topkCount_, trunkLen_); | 291 | topkOp_.Init(topkCount_, trunkLen_); |
| 289 | 292 | ||
| 290 | - if (constInfo_.quantMode == 4) { | 293 | + if constexpr (!IS_MX) { |
| 291 | - globalQScale_ = qScaleGm.GetValue(0); | 294 | + if (constInfo_.quantMode == 4) { |
| 292 | - globalKScale_ = kScaleGm.GetValue(0); | 295 | + globalQScale_ = qScaleGm.GetValue(0); |
| 296 | + globalKScale_ = kScaleGm.GetValue(0); | ||
| 297 | + } | ||
| 293 | } | 298 | } |
| 294 | } | 299 | } |
| 295 | 300 | ||
| 296 | template <typename QLIV2T> | 301 | template <typename QLIV2T> |
| 297 | __aicore__ inline void QLIV2Vector<QLIV2T>::InitVecInputTensor( | 302 | __aicore__ inline void QLIV2Vector<QLIV2T>::InitVecInputTensor( |
| 298 | - GlobalTensor<float> weightsGm, GlobalTensor<float> qScaleGm, GlobalTensor<float> kScaleGm, | 303 | + GlobalTensor<WEIGHT_T> weightsGm, GlobalTensor<int32_t> indiceOutGm, GlobalTensor<int32_t> blockTableGm, |
| 299 | - GlobalTensor<int32_t> indiceOutGm, GlobalTensor<int32_t> blockTableGm, GlobalTensor<bfloat16_t> valueOutGm, | 304 | + GlobalTensor<bfloat16_t> valueOutGm, GlobalTensor<int32_t> outputIdxOffsetGm, GlobalTensor<float> qScaleGm, |
| 300 | - GlobalTensor<int32_t> outputIdxOffsetGm) | 305 | + GlobalTensor<float> kScaleGm) |
| 301 | { | 306 | { |
| 302 | this->weightsGm = weightsGm; | 307 | this->weightsGm = weightsGm; |
| 303 | - this->qScaleGm = qScaleGm; | ||
| 304 | - this->kScaleGm = kScaleGm; | ||
| 305 | this->indiceOutGm = indiceOutGm; | 308 | this->indiceOutGm = indiceOutGm; |
| 306 | this->blockTableGm = blockTableGm; | 309 | this->blockTableGm = blockTableGm; |
| 307 | this->valueOutGm = valueOutGm; | 310 | this->valueOutGm = valueOutGm; |
| 308 | this->outputIdxOffsetGm = outputIdxOffsetGm; | 311 | this->outputIdxOffsetGm = outputIdxOffsetGm; |
| 312 | + if constexpr (!IS_MX) { | ||
| 313 | + this->qScaleGm = qScaleGm; | ||
| 314 | + this->kScaleGm = kScaleGm; | ||
| 315 | + } | ||
| 309 | } | 316 | } |
| 310 | 317 | ||
| 311 | template <typename QLIV2T> | 318 | template <typename QLIV2T> |
| @@ -321,8 +328,10 @@ __aicore__ inline void QLIV2Vector<QLIV2T>::InitVecWorkspaceTensor(GlobalTensor< | |||
| 321 | template <typename QLIV2T> | 328 | template <typename QLIV2T> |
| 322 | __aicore__ inline void QLIV2Vector<QLIV2T>::AllocEventID() | 329 | __aicore__ inline void QLIV2Vector<QLIV2T>::AllocEventID() |
| 323 | { | 330 | { |
| 324 | - SetFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_KSCALE + 0); | 331 | + if constexpr (!IS_MX) { |
| 325 | - SetFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_KSCALE + 1); | 332 | + SetFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_KSCALE + 0); |
| 333 | + SetFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_KSCALE + 1); | ||
| 334 | + } | ||
| 326 | SetFlag<HardEvent::MTE3_V>(VEC1_MTE3_V_EVENT + 0); | 335 | SetFlag<HardEvent::MTE3_V>(VEC1_MTE3_V_EVENT + 0); |
| 327 | SetFlag<HardEvent::MTE3_V>(VEC1_MTE3_V_EVENT + 1); | 336 | SetFlag<HardEvent::MTE3_V>(VEC1_MTE3_V_EVENT + 1); |
| 328 | SetFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_QSCALE + 0); | 337 | SetFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_QSCALE + 0); |
| @@ -336,8 +345,10 @@ __aicore__ inline void QLIV2Vector<QLIV2T>::AllocEventID() | |||
| 336 | template <typename QLIV2T> | 345 | template <typename QLIV2T> |
| 337 | __aicore__ inline void QLIV2Vector<QLIV2T>::FreeEventID() | 346 | __aicore__ inline void QLIV2Vector<QLIV2T>::FreeEventID() |
| 338 | { | 347 | { |
| 339 | - WaitFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_KSCALE + 0); | 348 | + if constexpr (!IS_MX) { |
| 340 | - WaitFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_KSCALE + 1); | 349 | + WaitFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_KSCALE + 0); |
| 350 | + WaitFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_KSCALE + 1); | ||
| 351 | + } | ||
| 341 | WaitFlag<HardEvent::MTE3_V>(VEC1_MTE3_V_EVENT + 0); | 352 | WaitFlag<HardEvent::MTE3_V>(VEC1_MTE3_V_EVENT + 0); |
| 342 | WaitFlag<HardEvent::MTE3_V>(VEC1_MTE3_V_EVENT + 1); | 353 | WaitFlag<HardEvent::MTE3_V>(VEC1_MTE3_V_EVENT + 1); |
| 343 | WaitFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_QSCALE + 0); | 354 | WaitFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_QSCALE + 0); |
| @@ -478,35 +489,44 @@ __aicore__ inline void QLIV2Vector<QLIV2T>::ProcessVec1(const QLIV2Common::RunIn | |||
| 478 | WaitFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_QSCALE + qScalepingpong); | 489 | WaitFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_QSCALE + qScalepingpong); |
| 479 | // weightsGm --> weightUB_ | 490 | // weightsGm --> weightUB_ |
| 480 | int64_t weightGmOffset = info.tensorWeightsOffset + curAivS1Idx * kHeadNum_ * gSize_; | 491 | int64_t weightGmOffset = info.tensorWeightsOffset + curAivS1Idx * kHeadNum_ * gSize_; |
| 481 | - DataCopyPadExtParams<float> padWeightsParams{false, 0, 0, 0}; | 492 | + DataCopyPadExtParams<WEIGHT_T> padWeightsParams{false, 0, 0, 0}; |
| 482 | DataCopyExtParams qwDataCopyExtParams; | 493 | DataCopyExtParams qwDataCopyExtParams; |
| 483 | qwDataCopyExtParams.blockCount = curAivS1ProcNum; | 494 | qwDataCopyExtParams.blockCount = curAivS1ProcNum; |
| 484 | - qwDataCopyExtParams.blockLen = gSize_ * sizeof(float); | 495 | + qwDataCopyExtParams.blockLen = gSize_ * sizeof(WEIGHT_T); |
| 485 | qwDataCopyExtParams.srcStride = 0; | 496 | qwDataCopyExtParams.srcStride = 0; |
| 486 | qwDataCopyExtParams.dstStride = (UB_BANK_DEPTH_STRIDE - qwDataCopyExtParams.blockLen) / 32; | 497 | qwDataCopyExtParams.dstStride = (UB_BANK_DEPTH_STRIDE - qwDataCopyExtParams.blockLen) / 32; |
| 487 | - DataCopyPad(weightUB_[qScalepingpong * (UB_BANK_STRIDE / sizeof(float))], weightsGm[weightGmOffset], | 498 | + DataCopyPad(weightUB_[qScalepingpong * (UB_BANK_STRIDE / sizeof(WEIGHT_T))], weightsGm[weightGmOffset], |
| 488 | qwDataCopyExtParams, padWeightsParams); | 499 | qwDataCopyExtParams, padWeightsParams); |
| 489 | 500 | ||
| 490 | - if (constInfo_.quantMode != 4) { | 501 | + if constexpr (!IS_MX) { |
| 491 | - // qScaleGm --> qScaleUB_ | 502 | + if (constInfo_.quantMode != 4) { |
| 492 | - DataCopyPadExtParams<float> padQScaleParams{false, 0, 0, 0}; | 503 | + // qScaleGm --> qScaleUB_ |
| 493 | - DataCopyPad(qScaleUB_[qScalepingpong * (UB_BANK_STRIDE / sizeof(float))], qScaleGm[weightGmOffset], | 504 | + DataCopyPadExtParams<float> padQScaleParams{false, 0, 0, 0}; |
| 494 | - qwDataCopyExtParams, padQScaleParams); | 505 | + DataCopyExtParams qScaleDataCopyExtParams; |
| 506 | + qScaleDataCopyExtParams.blockCount = curAivS1ProcNum; | ||
| 507 | + qScaleDataCopyExtParams.blockLen = gSize_ * sizeof(float); | ||
| 508 | + qScaleDataCopyExtParams.srcStride = 0; | ||
| 509 | + qScaleDataCopyExtParams.dstStride = (UB_BANK_DEPTH_STRIDE - qScaleDataCopyExtParams.blockLen) / 32; | ||
| 510 | + DataCopyPad(qScaleUB_[qScalepingpong * (UB_BANK_STRIDE / sizeof(float))], qScaleGm[weightGmOffset], | ||
| 511 | + qScaleDataCopyExtParams, padQScaleParams); | ||
| 512 | + } | ||
| 495 | } | 513 | } |
| 496 | 514 | ||
| 497 | SetFlag<HardEvent::MTE2_V>(VEC1_MTE2_V_EVENT_QSCALE + qScalepingpong); | 515 | SetFlag<HardEvent::MTE2_V>(VEC1_MTE2_V_EVENT_QSCALE + qScalepingpong); |
| 498 | WaitFlag<HardEvent::MTE2_V>(VEC1_MTE2_V_EVENT_QSCALE + qScalepingpong); | 516 | WaitFlag<HardEvent::MTE2_V>(VEC1_MTE2_V_EVENT_QSCALE + qScalepingpong); |
| 499 | } | 517 | } |
| 500 | 518 | ||
| 501 | - if (((info.s2Idx - info.s2Start) % 16 == 0) && (constInfo_.quantMode != 4)) { | 519 | + if constexpr (!IS_MX) { |
| 502 | - WaitFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_KSCALE + kScalepingpong); | 520 | + if (((info.s2Idx - info.s2Start) % 16 == 0) && (constInfo_.quantMode != 4)) { |
| 503 | - uint32_t getLen = 16 * s2BaseSize_ > (info.validS2Len - info.s2Idx * s2BaseSize_) ? | 521 | + WaitFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_KSCALE + kScalepingpong); |
| 504 | - info.validS2Len - info.s2Idx * s2BaseSize_ : | 522 | + uint32_t getLen = 16 * s2BaseSize_ > (info.validS2Len - info.s2Idx * s2BaseSize_) ? |
| 505 | - 16 * s2BaseSize_; | 523 | + info.validS2Len - info.s2Idx * s2BaseSize_ : |
| 506 | - // kScaleGm --> kScaleUB_ | 524 | + 16 * s2BaseSize_; |
| 507 | - GetKeyScale(info, kScaleUB_, info.bIdx, curS2Idx, getLen); | 525 | + // kScaleGm --> kScaleUB_ |
| 508 | - SetFlag<HardEvent::MTE2_V>(VEC1_MTE2_V_EVENT_KSCALE + kScalepingpong); | 526 | + GetKeyScale(info, kScaleUB_, info.bIdx, curS2Idx, getLen); |
| 509 | - WaitFlag<HardEvent::MTE2_V>(VEC1_MTE2_V_EVENT_KSCALE + kScalepingpong); | 527 | + SetFlag<HardEvent::MTE2_V>(VEC1_MTE2_V_EVENT_KSCALE + kScalepingpong); |
| 528 | + WaitFlag<HardEvent::MTE2_V>(VEC1_MTE2_V_EVENT_KSCALE + kScalepingpong); | ||
| 529 | + } | ||
| 510 | } | 530 | } |
| 511 | 531 | ||
| 512 | WaitFlag<HardEvent::MTE3_V>(VEC1_MTE3_V_EVENT + pingpong); | 532 | WaitFlag<HardEvent::MTE3_V>(VEC1_MTE3_V_EVENT + pingpong); |
| @@ -517,34 +537,45 @@ __aicore__ inline void QLIV2Vector<QLIV2T>::ProcessVec1(const QLIV2Common::RunIn | |||
| 517 | 537 | ||
| 518 | static_assert(std::is_same_v<SCORE_T, uint16_t>); | 538 | static_assert(std::is_same_v<SCORE_T, uint16_t>); |
| 519 | auto outBase = vec1OutUB_[pingpong * (UB_BANK_STRIDE / sizeof(SCORE_T))]; | 539 | auto outBase = vec1OutUB_[pingpong * (UB_BANK_STRIDE / sizeof(SCORE_T))]; |
| 520 | - auto weightBase = weightUB_[qScalepingpong * (UB_BANK_STRIDE / sizeof(float))]; | 540 | + auto weightBase = weightUB_[qScalepingpong * (UB_BANK_STRIDE / sizeof(WEIGHT_T))]; |
| 521 | auto weightTempBase = weightTempUB_[qScalepingpong * (UB_BANK_STRIDE / sizeof(float))]; | 541 | auto weightTempBase = weightTempUB_[qScalepingpong * (UB_BANK_STRIDE / sizeof(float))]; |
| 522 | 542 | ||
| 523 | auto qkBase = resMm1UB_[pingpong * (UB_BANK_STRIDE / sizeof(QK_T))]; | 543 | auto qkBase = resMm1UB_[pingpong * (UB_BANK_STRIDE / sizeof(QK_T))]; |
| 524 | auto qkVLstride = (UB_BANK_DEPTH_STRIDE / sizeof(QK_T)) / 2 * constInfo_.mBaseSize; | 544 | auto qkVLstride = (UB_BANK_DEPTH_STRIDE / sizeof(QK_T)) / 2 * constInfo_.mBaseSize; |
| 525 | - if (constInfo_.quantMode == 4) { // 4: per_tensor量化 | 545 | + if constexpr (IS_MXFP4) { |
| 546 | + vector1::BatchMulWeightAndReduceSumMXFP4(outBase, UB_BANK_DEPTH_STRIDE / sizeof(SCORE_T), qkBase, qkVLstride, | ||
| 547 | + (uint32_t)(gSize_ * UB_BANK_DEPTH_STRIDE / sizeof(QK_T)), weightBase, | ||
| 548 | + UB_BANK_DEPTH_STRIDE / sizeof(WEIGHT_T), gSize_, curAivS1ProcNum); | ||
| 549 | + } else if constexpr (IS_MX) { | ||
| 550 | + vector1::BatchMulWeightAndReduceSumMX(outBase, UB_BANK_DEPTH_STRIDE / sizeof(SCORE_T), qkBase, qkVLstride, | ||
| 551 | + (uint32_t)(gSize_ * UB_BANK_DEPTH_STRIDE / sizeof(QK_T)), weightBase, | ||
| 552 | + UB_BANK_DEPTH_STRIDE / sizeof(WEIGHT_T), weightTempBase, gSize_, | ||
| 553 | + curAivS1ProcNum); | ||
| 554 | + } else if (constInfo_.quantMode == 4) { // 4: per_tensor量化 | ||
| 526 | // quantMode为4时不适用sacle的UB | 555 | // quantMode为4时不适用sacle的UB |
| 527 | float kScaleValue = globalKScale_; | 556 | float kScaleValue = globalKScale_; |
| 528 | float qScaleValue = globalQScale_; | 557 | float qScaleValue = globalQScale_; |
| 529 | vector1::BatchMulWeightAndReduceSumPerTensor( | 558 | vector1::BatchMulWeightAndReduceSumPerTensor( |
| 530 | outBase, UB_BANK_DEPTH_STRIDE / sizeof(SCORE_T), qkBase, qkVLstride, | 559 | outBase, UB_BANK_DEPTH_STRIDE / sizeof(SCORE_T), qkBase, qkVLstride, |
| 531 | - (uint32_t)(gSize_ * UB_BANK_DEPTH_STRIDE / sizeof(QK_T)), weightBase, UB_BANK_DEPTH_STRIDE / sizeof(float), | 560 | + (uint32_t)(gSize_ * UB_BANK_DEPTH_STRIDE / sizeof(QK_T)), weightBase, |
| 532 | - weightTempBase, kScaleValue, qScaleValue, gSize_, curAivS1ProcNum); | 561 | + UB_BANK_DEPTH_STRIDE / sizeof(WEIGHT_T), weightTempBase, kScaleValue, qScaleValue, gSize_, curAivS1ProcNum); |
| 533 | } else { | 562 | } else { |
| 534 | auto qScaleBase = qScaleUB_[qScalepingpong * (UB_BANK_STRIDE / sizeof(float))]; | 563 | auto qScaleBase = qScaleUB_[qScalepingpong * (UB_BANK_STRIDE / sizeof(float))]; |
| 535 | auto kScaleBase = | 564 | auto kScaleBase = |
| 536 | kScaleUB_[kScalepingpong * 16 * s2BaseSize_ + ((info.s2Idx - info.s2Start) % 16) * s2BaseSize_]; | 565 | kScaleUB_[kScalepingpong * 16 * s2BaseSize_ + ((info.s2Idx - info.s2Start) % 16) * s2BaseSize_]; |
| 537 | vector1::BatchMulWeightAndReduceSum(outBase, UB_BANK_DEPTH_STRIDE / sizeof(SCORE_T), qkBase, qkVLstride, | 566 | vector1::BatchMulWeightAndReduceSum(outBase, UB_BANK_DEPTH_STRIDE / sizeof(SCORE_T), qkBase, qkVLstride, |
| 538 | (uint32_t)(gSize_ * UB_BANK_DEPTH_STRIDE / sizeof(QK_T)), weightBase, | 567 | (uint32_t)(gSize_ * UB_BANK_DEPTH_STRIDE / sizeof(QK_T)), weightBase, |
| 539 | - UB_BANK_DEPTH_STRIDE / sizeof(float), weightTempBase, kScaleBase, | 568 | + UB_BANK_DEPTH_STRIDE / sizeof(WEIGHT_T), weightTempBase, kScaleBase, |
| 540 | (uint32_t)0, qScaleBase, UB_BANK_DEPTH_STRIDE / sizeof(float), gSize_, | 569 | (uint32_t)0, qScaleBase, UB_BANK_DEPTH_STRIDE / sizeof(float), gSize_, |
| 541 | curAivS1ProcNum); | 570 | curAivS1ProcNum); |
| 542 | } | 571 | } |
| 543 | if (info.isFirstS2InnerLoop) { | 572 | if (info.isFirstS2InnerLoop) { |
| 544 | SetFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_QSCALE + qScalepingpong); | 573 | SetFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_QSCALE + qScalepingpong); |
| 545 | } | 574 | } |
| 546 | - if (((info.s2Idx - info.s2Start) % 16 == 0) && (constInfo_.quantMode != 4)) { | 575 | + if constexpr (!IS_MX) { |
| 547 | - SetFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_KSCALE + kScalepingpong); | 576 | + if (((info.s2Idx - info.s2Start) % 16 == 0) && (constInfo_.quantMode != 4)) { |
| 577 | + SetFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT_KSCALE + kScalepingpong); | ||
| 578 | + } | ||
| 548 | } | 579 | } |
| 549 | SetFlag<HardEvent::V_MTE3>(VEC1_V_MTE3_EVENT + pingpong); | 580 | SetFlag<HardEvent::V_MTE3>(VEC1_V_MTE3_EVENT + pingpong); |
| 550 | WaitFlag<HardEvent::V_MTE3>(VEC1_V_MTE3_EVENT + pingpong); | 581 | WaitFlag<HardEvent::V_MTE3>(VEC1_V_MTE3_EVENT + pingpong); |
| @@ -787,12 +818,6 @@ __aicore__ inline void QLIV2Vector<QLIV2T>::ProcessTopK(const QLIV2Common::RunIn | |||
| 787 | topkCount_ - (validS2Len / 8 * 8 + 64)); | 818 | topkCount_ - (validS2Len / 8 * 8 + 64)); |
| 788 | } | 819 | } |
| 789 | SetFlag<HardEvent::V_MTE2>(TOPK_V_MTE2_EVENT); | 820 | SetFlag<HardEvent::V_MTE2>(TOPK_V_MTE2_EVENT); |
| 790 | - SetFlag<HardEvent::V_MTE3>(TOPK_V_MTE3_EVENT); | ||
| 791 | - WaitFlag<HardEvent::V_MTE3>(TOPK_V_MTE3_EVENT); | ||
| 792 | - | ||
| 793 | - AscendC::DataCopyPad(indiceOutGm[info.indiceOutOffset + (curS1Idx + rowIdx) * topkCount_], | ||
| 794 | - indicesOutLocal_.ReinterpretCast<int32_t>(), copyOutParams); | ||
| 795 | - | ||
| 796 | if (returnValueFlag) { | 821 | if (returnValueFlag) { |
| 797 | WaitFlag<HardEvent::V_MTE2>(TOPK_V_MTE2_EVENT); | 822 | WaitFlag<HardEvent::V_MTE2>(TOPK_V_MTE2_EVENT); |
| 798 | vector1::UIntToFloatReturnValue(valueOutLocal_, scoreOutLocal_, topkCountAlign256_); | 823 | vector1::UIntToFloatReturnValue(valueOutLocal_, scoreOutLocal_, topkCountAlign256_); |
| @@ -812,15 +837,18 @@ __aicore__ inline void QLIV2Vector<QLIV2T>::ProcessTopK(const QLIV2Common::RunIn | |||
| 812 | constInfo_.NEG_INF_BFLOAT, topkCount_ - (validS2Len / 16 * 16 + 64)); | 837 | constInfo_.NEG_INF_BFLOAT, topkCount_ - (validS2Len / 16 * 16 + 64)); |
| 813 | } | 838 | } |
| 814 | SetFlag<HardEvent::V_MTE2>(TOPK_V_MTE2_EVENT); | 839 | SetFlag<HardEvent::V_MTE2>(TOPK_V_MTE2_EVENT); |
| 815 | - SetFlag<HardEvent::V_MTE3>(TOPK_V_MTE3_EVENT); | 840 | + } |
| 816 | - WaitFlag<HardEvent::V_MTE3>(TOPK_V_MTE3_EVENT); | ||
| 817 | 841 | ||
| 842 | + SetFlag<HardEvent::V_MTE3>(TOPK_V_MTE3_EVENT); | ||
| 843 | + WaitFlag<HardEvent::V_MTE3>(TOPK_V_MTE3_EVENT); | ||
| 844 | + AscendC::DataCopyPad(indiceOutGm[info.indiceOutOffset + (curS1Idx + rowIdx) * topkCount_], | ||
| 845 | + indicesOutLocal_.ReinterpretCast<int32_t>(), copyOutParams); | ||
| 846 | + if (returnValueFlag) { | ||
| 818 | AscendC::DataCopyParams copyOutValueParams; | 847 | AscendC::DataCopyParams copyOutValueParams; |
| 819 | copyOutValueParams.blockCount = 1; | 848 | copyOutValueParams.blockCount = 1; |
| 820 | copyOutValueParams.blockLen = topkCount_ * sizeof(bfloat16_t); // bytes | 849 | copyOutValueParams.blockLen = topkCount_ * sizeof(bfloat16_t); // bytes |
| 821 | copyOutValueParams.srcStride = 0; | 850 | copyOutValueParams.srcStride = 0; |
| 822 | copyOutValueParams.dstStride = 0; | 851 | copyOutValueParams.dstStride = 0; |
| 823 | - // 搬运到GM | ||
| 824 | AscendC::DataCopyPad(valueOutGm[info.valueOutOffset + (curS1Idx + rowIdx) * topkCount_], valueOutLocal_, | 852 | AscendC::DataCopyPad(valueOutGm[info.valueOutOffset + (curS1Idx + rowIdx) * topkCount_], valueOutLocal_, |
| 825 | copyOutValueParams); | 853 | copyOutValueParams); |
| 826 | } | 854 | } |
Mattention/quant_lightning_indexer_v2/op_kernel/arch35/vf/quant_lightning_indexer_v2_vector1.h+413-235
| @@ -16,56 +16,57 @@ | |||
| 16 | #include "kernel_operator.h" | 16 | #include "kernel_operator.h" |
| 17 | #include "lib/matmul_intf.h" | 17 | #include "lib/matmul_intf.h" |
| 18 | #if (__CCE_AICORE__ == 310) | 18 | #if (__CCE_AICORE__ == 310) |
| 19 | - #include "arch35/quant_lightning_indexer_v2_kernel.h" | 19 | +#include "arch35/quant_lightning_indexer_v2_kernel.h" |
| 20 | #else | 20 | #else |
| 21 | - #include "arch22/quant_lightning_indexer_v2_kernel.h" | 21 | +#include "arch22/quant_lightning_indexer_v2_kernel.h" |
| 22 | #endif | 22 | #endif |
| 23 | #include "quant_lightning_indexer_v2_template_tiling_key.h" | 23 | #include "quant_lightning_indexer_v2_template_tiling_key.h" |
| 24 | using namespace QLIV2Kernel; | 24 | using namespace QLIV2Kernel; |
| 25 | using namespace optiling::detail; | 25 | using namespace optiling::detail; |
| 26 | 26 | ||
| 27 | -#define INVOKE_LI_NO_KFC_OP_IMPL(templateClass, ...) \ | 27 | +#define INVOKE_LI_NO_KFC_OP_IMPL(templateClass, ...) \ |
| 28 | - do { \ | 28 | + do { \ |
| 29 | - templateClass<QLIV2Type<__VA_ARGS__>> op; \ | 29 | + templateClass<QLIV2Type<__VA_ARGS__>> op; \ |
| 30 | - GET_TILING_DATA_WITH_STRUCT(QLIV2TilingData, tiling_data_in, tiling); \ | 30 | + op.Init(query, key, weights, queryScale, keyScale, cuSeqlensQ, cuSeqlensK, sequsedQ, sequsedK, cmpResidualK, \ |
| 31 | - const QLIV2TilingData *__restrict tiling_data = &tiling_data_in; \ | 31 | + blockTable, outputIdxOffset, metadata, sparseIndices, sparseValues, user, tiling_data, &tPipe); \ |
| 32 | - op.Init(query, key, weights, queryScale, keyScale, cuSeqlensQ, cuSeqlensK, sequsedQ, sequsedK, \ | 32 | + op.Process(); \ |
| 33 | - cmpResidualK, blockTable, outputIdxOffset, metadata, \ | ||
| 34 | - sparseIndices, sparseValues, user, tiling_data, &tPipe); \ | ||
| 35 | - op.Process(); \ | ||
| 36 | } while (0) | 33 | } while (0) |
| 37 | 34 | ||
| 38 | template <int DT_Q, int DT_K, int DT_OUT, int PAGE_ATTENTION, int Q_LAYOUT_T, int K_LAYOUT_T> | 35 | template <int DT_Q, int DT_K, int DT_OUT, int PAGE_ATTENTION, int Q_LAYOUT_T, int K_LAYOUT_T> |
| 39 | -__global__ __aicore__ void quant_lightning_indexer_v2(__gm__ uint8_t *query, __gm__ uint8_t *key, | 36 | +__global__ __aicore__ void quant_lightning_indexer_v2( |
| 40 | - __gm__ uint8_t *weights, | 37 | + __gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint8_t *weights, __gm__ uint8_t *queryScale, |
| 41 | - __gm__ uint8_t *queryScale, __gm__ uint8_t *keyScale, | 38 | + __gm__ uint8_t *keyScale, __gm__ uint8_t *cuSeqlensQ, __gm__ uint8_t *cuSeqlensK, __gm__ uint8_t *sequsedQ, |
| 42 | - __gm__ uint8_t *cuSeqlensQ, __gm__ uint8_t *cuSeqlensK, | 39 | + __gm__ uint8_t *sequsedK, __gm__ uint8_t *cmpResidualK, __gm__ uint8_t *blockTable, __gm__ uint8_t *outputIdxOffset, |
| 43 | - __gm__ uint8_t *sequsedQ, __gm__ uint8_t *sequsedK, | 40 | + __gm__ uint8_t *metadata, __gm__ uint8_t *sparseIndices, __gm__ uint8_t *sparseValues, __gm__ uint8_t *workspace, |
| 44 | - __gm__ uint8_t *cmpResidualK, __gm__ uint8_t *blockTable, | 41 | + __gm__ uint8_t *tiling) |
| 45 | - __gm__ uint8_t *outputIdxOffset, __gm__ uint8_t *metadata, | ||
| 46 | - __gm__ uint8_t *sparseIndices, __gm__ uint8_t *sparseValues, | ||
| 47 | - __gm__ uint8_t *workspace, __gm__ uint8_t *tiling) | ||
| 48 | { | 42 | { |
| 49 | TPipe tPipe; | 43 | TPipe tPipe; |
| 50 | __gm__ uint8_t *user = GetUserWorkspace(workspace); | 44 | __gm__ uint8_t *user = GetUserWorkspace(workspace); |
| 51 | KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); | 45 | KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); |
| 46 | + GET_TILING_DATA_WITH_STRUCT(QLIV2TilingData, tiling_data_in, tiling); | ||
| 47 | + const QLIV2TilingData *__restrict tiling_data = &tiling_data_in; | ||
| 52 | 48 | ||
| 53 | #if (__CCE_AICORE__ == 310) | 49 | #if (__CCE_AICORE__ == 310) |
| 54 | - if (ORIG_DTYPE_Q == DT_FLOAT8_E4M3FN) { | 50 | + constexpr uint32_t QUANT_MODE_FP8 = 1; |
| 55 | - INVOKE_LI_NO_KFC_OP_IMPL(QLIV2Preload, fp8_e4m3fn_t, fp8_e4m3fn_t, float, uint16_t, int32_t, | 51 | + constexpr uint32_t QUANT_MODE_MXFP8 = 3; |
| 56 | - PAGE_ATTENTION, LI_LAYOUT(Q_LAYOUT_T), LI_LAYOUT(K_LAYOUT_T), | 52 | + constexpr uint32_t QUANT_MODE_HIFLOAT8 = 4; |
| 57 | - float32_t, float32_t, float32_t); | 53 | + constexpr uint32_t QUANT_MODE_MXFP4 = 5; |
| 58 | - } else if (ORIG_DTYPE_Q == DT_HIFLOAT8) { | 54 | + if (tiling_data->quantMode == QUANT_MODE_FP8) { |
| 59 | - INVOKE_LI_NO_KFC_OP_IMPL(QLIV2Preload, hifloat8, hifloat8, float, uint16_t, int32_t, | 55 | + INVOKE_LI_NO_KFC_OP_IMPL(QLIV2Preload, fp8_e4m3fn_t, fp8_e4m3fn_t, float, uint16_t, int32_t, PAGE_ATTENTION, |
| 60 | - PAGE_ATTENTION, LI_LAYOUT(Q_LAYOUT_T), LI_LAYOUT(K_LAYOUT_T), | 56 | + LI_LAYOUT(Q_LAYOUT_T), LI_LAYOUT(K_LAYOUT_T), float, float, float); |
| 61 | - bfloat16_t, float32_t, float32_t); | 57 | + } else if (tiling_data->quantMode == QUANT_MODE_MXFP8) { |
| 62 | - } else { | 58 | + INVOKE_LI_NO_KFC_OP_IMPL(QLIV2Preload, fp8_e4m3fn_t, fp8_e4m3fn_t, float, uint16_t, int32_t, PAGE_ATTENTION, |
| 63 | - INVOKE_LI_NO_KFC_OP_IMPL(QLIV2Preload, int8_t, int8_t, float, uint16_t, int32_t, | 59 | + LI_LAYOUT(Q_LAYOUT_T), LI_LAYOUT(K_LAYOUT_T), fp8_e8m0_t, float, float); |
| 64 | - PAGE_ATTENTION, LI_LAYOUT(Q_LAYOUT_T), LI_LAYOUT(K_LAYOUT_T), | 60 | + } else if (tiling_data->quantMode == QUANT_MODE_HIFLOAT8) { |
| 65 | - half, half, int32_t); | 61 | + INVOKE_LI_NO_KFC_OP_IMPL(QLIV2Preload, hifloat8, hifloat8, float, uint16_t, int32_t, PAGE_ATTENTION, |
| 62 | + LI_LAYOUT(Q_LAYOUT_T), LI_LAYOUT(K_LAYOUT_T), float, float, float); | ||
| 63 | + } else if (tiling_data->quantMode == QUANT_MODE_MXFP4) { | ||
| 64 | + INVOKE_LI_NO_KFC_OP_IMPL(QLIV2Preload, fp4x2_e2m1_t, fp4x2_e2m1_t, bfloat16_t, uint16_t, int32_t, | ||
| 65 | + PAGE_ATTENTION, LI_LAYOUT(Q_LAYOUT_T), LI_LAYOUT(K_LAYOUT_T), fp8_e8m0_t, float, | ||
| 66 | + float); | ||
| 66 | } | 67 | } |
| 67 | #else | 68 | #else |
| 68 | - INVOKE_LI_NO_KFC_OP_IMPL(QLIV2Preload, int8_t, int8_t, float, uint16_t, int32_t, | 69 | + INVOKE_LI_NO_KFC_OP_IMPL(QLIV2Preload, int8_t, int8_t, float, uint16_t, int32_t, PAGE_ATTENTION, |
| 69 | - PAGE_ATTENTION, LI_LAYOUT(Q_LAYOUT_T), LI_LAYOUT(K_LAYOUT_T)); | 70 | + LI_LAYOUT(Q_LAYOUT_T), LI_LAYOUT(K_LAYOUT_T)); |
| 70 | #endif | 71 | #endif |
| 71 | } | 72 | } |
Mattention/quant_lightning_indexer_v2/op_kernel/quant_lightning_indexer_v2_template_tiling_key.h+82-65
| @@ -20,8 +20,9 @@ | |||
| 20 | 20 | ||
| 21 | #define QLIV2_TPL_INT8 2 | 21 | #define QLIV2_TPL_INT8 2 |
| 22 | #define QLIV2_TPL_INT32 3 | 22 | #define QLIV2_TPL_INT32 3 |
| 23 | -#define QLIV2_TPL_FLOAT32_E4M3FN 36 | 23 | +#define QLIV2_TPL_FLOAT8_E4M3FN 36 |
| 24 | #define QLIV2_TPL_HIFLOAT8 34 | 24 | #define QLIV2_TPL_HIFLOAT8 34 |
| 25 | +#define QLIV2_TPL_FLOAT4_E2M1 40 | ||
| 25 | #define QLIV2_LAYOUT_BSND 0 | 26 | #define QLIV2_LAYOUT_BSND 0 |
| 26 | #define QLIV2_LAYOUT_TND 1 | 27 | #define QLIV2_LAYOUT_TND 1 |
| 27 | #define QLIV2_LAYOUT_PA_BBND 2 | 28 | #define QLIV2_LAYOUT_PA_BBND 2 |
| @@ -30,71 +31,87 @@ | |||
| 30 | 31 | ||
| 31 | // 模板参数支持的范围定义 | 32 | // 模板参数支持的范围定义 |
| 32 | #if (__CCE_AICORE__ == 310) | 33 | #if (__CCE_AICORE__ == 310) |
| 33 | - ASCENDC_TPL_ARGS_DECL(QuantLightningIndexerV2, // 算子OpType | 34 | +ASCENDC_TPL_ARGS_DECL(QuantLightningIndexerV2, // 算子OpType |
| 34 | - ASCENDC_TPL_DTYPE_DECL(DT_Q, QLIV2_TPL_FLOAT32_E4M3FN, QLIV2_TPL_HIFLOAT8), | 35 | + ASCENDC_TPL_DTYPE_DECL(DT_Q, QLIV2_TPL_FLOAT8_E4M3FN, QLIV2_TPL_HIFLOAT8, QLIV2_TPL_FLOAT4_E2M1), |
| 35 | - ASCENDC_TPL_DTYPE_DECL(DT_K, QLIV2_TPL_FLOAT32_E4M3FN, QLIV2_TPL_HIFLOAT8), | 36 | + ASCENDC_TPL_DTYPE_DECL(DT_K, QLIV2_TPL_FLOAT8_E4M3FN, QLIV2_TPL_HIFLOAT8, QLIV2_TPL_FLOAT4_E2M1), |
| 36 | - ASCENDC_TPL_DTYPE_DECL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_DECL(PAGE_ATTENTION, 1, 0), | 37 | + ASCENDC_TPL_DTYPE_DECL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_DECL(PAGE_ATTENTION, 1, 0), |
| 37 | - ASCENDC_TPL_UINT_DECL(Q_LAYOUT_T, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND, | 38 | + ASCENDC_TPL_UINT_DECL(Q_LAYOUT_T, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND, |
| 38 | - QLIV2_LAYOUT_TND), | 39 | + QLIV2_LAYOUT_TND), |
| 39 | - ASCENDC_TPL_UINT_DECL(K_LAYOUT_T, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, | 40 | + ASCENDC_TPL_UINT_DECL(K_LAYOUT_T, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND, |
| 40 | - QLIV2_LAYOUT_BSND, QLIV2_LAYOUT_TND, QLIV2_LAYOUT_PA_BBND),); | 41 | + QLIV2_LAYOUT_TND, QLIV2_LAYOUT_PA_BBND), ); |
| 41 | - // 支持的模板参数组合 | 42 | +// 支持的模板参数组合 |
| 42 | - // 用于调用GET_TPL_TILING_KEY获取TilingKey时,接口内部校验TilingKey是否合法 | 43 | +// 用于调用GET_TPL_TILING_KEY获取TilingKey时,接口内部校验TilingKey是否合法 |
| 43 | - ASCENDC_TPL_SEL( | 44 | +ASCENDC_TPL_SEL( |
| 44 | - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_FLOAT32_E4M3FN), ASCENDC_TPL_DTYPE_SEL(DT_K, | 45 | + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_FLOAT8_E4M3FN), |
| 45 | - QLIV2_TPL_FLOAT32_E4M3FN), | 46 | + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_FLOAT8_E4M3FN), |
| 46 | - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), | 47 | + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), |
| 47 | - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND, QLIV2_LAYOUT_TND), | 48 | + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND, QLIV2_LAYOUT_TND), |
| 48 | - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_PA_BBND),), | 49 | + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_PA_BBND), ), |
| 49 | - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_FLOAT32_E4M3FN), ASCENDC_TPL_DTYPE_SEL(DT_K, | 50 | + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_FLOAT8_E4M3FN), |
| 50 | - QLIV2_TPL_FLOAT32_E4M3FN), | 51 | + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_FLOAT8_E4M3FN), |
| 51 | - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), | 52 | + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), |
| 52 | - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND), | 53 | + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND), |
| 53 | - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND),), | 54 | + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND), ), |
| 54 | - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_FLOAT32_E4M3FN), ASCENDC_TPL_DTYPE_SEL(DT_K, | 55 | + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_FLOAT8_E4M3FN), |
| 55 | - QLIV2_TPL_FLOAT32_E4M3FN), | 56 | + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_FLOAT8_E4M3FN), |
| 56 | - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), | 57 | + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), |
| 57 | - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_TND), | 58 | + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_TND), |
| 58 | - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_TND),), | 59 | + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_TND), ), |
| 59 | 60 | ||
| 60 | - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_HIFLOAT8), | 61 | + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_HIFLOAT8), |
| 61 | - ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_HIFLOAT8), | 62 | + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_HIFLOAT8), |
| 62 | - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), | 63 | + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), |
| 63 | - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND, QLIV2_LAYOUT_TND), | 64 | + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND, QLIV2_LAYOUT_TND), |
| 64 | - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_PA_BBND),), | 65 | + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_PA_BBND), ), |
| 65 | - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_HIFLOAT8), | 66 | + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_HIFLOAT8), |
| 66 | - ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_HIFLOAT8), | 67 | + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_HIFLOAT8), |
| 67 | - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), | 68 | + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), |
| 68 | - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND), | 69 | + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND), |
| 69 | - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND),), | 70 | + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND), ), |
| 70 | - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_HIFLOAT8), | 71 | + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_HIFLOAT8), |
| 71 | - ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_HIFLOAT8), | 72 | + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_HIFLOAT8), |
| 72 | - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), | 73 | + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), |
| 73 | - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_TND), | 74 | + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_TND), |
| 74 | - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_TND),),); | 75 | + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_TND), ), |
| 76 | + | ||
| 77 | + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_FLOAT4_E2M1), | ||
| 78 | + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_FLOAT4_E2M1), | ||
| 79 | + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), | ||
| 80 | + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND, QLIV2_LAYOUT_TND), | ||
| 81 | + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_PA_BBND), ), | ||
| 82 | + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_FLOAT4_E2M1), | ||
| 83 | + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_FLOAT4_E2M1), | ||
| 84 | + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), | ||
| 85 | + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND), | ||
| 86 | + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND), ), | ||
| 87 | + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_FLOAT4_E2M1), | ||
| 88 | + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_FLOAT4_E2M1), | ||
| 89 | + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), | ||
| 90 | + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_TND), | ||
| 91 | + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_TND), ), ); | ||
| 75 | #else | 92 | #else |
| 76 | - ASCENDC_TPL_ARGS_DECL(QuantLightningIndexerV2, // 算子OpType | 93 | +ASCENDC_TPL_ARGS_DECL(QuantLightningIndexerV2, // 算子OpType |
| 77 | - ASCENDC_TPL_DTYPE_DECL(DT_Q, QLIV2_TPL_INT8), ASCENDC_TPL_DTYPE_DECL(DT_K, QLIV2_TPL_INT8), | 94 | + ASCENDC_TPL_DTYPE_DECL(DT_Q, QLIV2_TPL_INT8), ASCENDC_TPL_DTYPE_DECL(DT_K, QLIV2_TPL_INT8), |
| 78 | - ASCENDC_TPL_DTYPE_DECL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_DECL(PAGE_ATTENTION, 1, 0), | 95 | + ASCENDC_TPL_DTYPE_DECL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_DECL(PAGE_ATTENTION, 1, 0), |
| 79 | - ASCENDC_TPL_UINT_DECL(Q_LAYOUT_T, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND, | 96 | + ASCENDC_TPL_UINT_DECL(Q_LAYOUT_T, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND, |
| 80 | - QLIV2_LAYOUT_TND), | 97 | + QLIV2_LAYOUT_TND), |
| 81 | - ASCENDC_TPL_UINT_DECL(K_LAYOUT_T, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, | 98 | + ASCENDC_TPL_UINT_DECL(K_LAYOUT_T, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND, |
| 82 | - QLIV2_LAYOUT_BSND, QLIV2_LAYOUT_TND, QLIV2_LAYOUT_PA_BBND),); | 99 | + QLIV2_LAYOUT_TND, QLIV2_LAYOUT_PA_BBND), ); |
| 83 | - // 支持的模板参数组合 | 100 | +// 支持的模板参数组合 |
| 84 | - // 用于调用GET_TPL_TILING_KEY获取TilingKey时,接口内部校验TilingKey是否合法 | 101 | +// 用于调用GET_TPL_TILING_KEY获取TilingKey时,接口内部校验TilingKey是否合法 |
| 85 | - ASCENDC_TPL_SEL( | 102 | +ASCENDC_TPL_SEL( |
| 86 | - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_INT8), ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_INT8), | 103 | + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_INT8), ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_INT8), |
| 87 | - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), | 104 | + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), |
| 88 | - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND, QLIV2_LAYOUT_TND), | 105 | + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND, QLIV2_LAYOUT_TND), |
| 89 | - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_PA_BBND),), | 106 | + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_PA_BBND), ), |
| 90 | - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_INT8), ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_INT8), | 107 | + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_INT8), ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_INT8), |
| 91 | - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), | 108 | + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), |
| 92 | - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND), | 109 | + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND), |
| 93 | - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND),), | 110 | + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_BSND), ), |
| 94 | - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_INT8), ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_INT8), | 111 | + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2_TPL_INT8), ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2_TPL_INT8), |
| 95 | - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), | 112 | + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2_TPL_INT32), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), |
| 96 | - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_TND), | 113 | + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_TND), |
| 97 | - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_TND),),); | 114 | + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2_LAYOUT_TND), ), ); |
| 98 | #endif | 115 | #endif |
| 99 | 116 | ||
| 100 | -#endif // QUANT_LIGHTNING_INDEXER_V2_TEMPLATE_TILING_KEY_H | 117 | +#endif // QUANT_LIGHTNING_INDEXER_V2_TEMPLATE_TILING_KEY_H |
| @@ -22,10 +22,17 @@ | |||
| 22 | - **key_layout**: PA_BBND、BSND、TND | 22 | - **key_layout**: PA_BBND、BSND、TND |
| 23 | 23 | ||
| 24 | - **数据类型**: | 24 | - **数据类型**: |
| 25 | - - **qk_dtype**: FLOAT8_E4M3FN、INT8、HIFLOAT8 | 25 | + - **qk_dtype**: FLOAT8_E4M3FN、INT8、HIFLOAT8、FLOAT4_E2M1 |
| 26 | - - **dequant_dtype**: FP32(Ascend950)、FP16(Ascend910_93) | 26 | + - **dequant_dtype**: FP32(Ascend950)、FP16(Ascend910_93)、FLOAT8_E8M0(MXFP8/MXFP4) |
| 27 | - **actual_seq_dtype**: INT32 | 27 | - **actual_seq_dtype**: INT32 |
| 28 | 28 | ||
| 29 | +### PyTorch MX类型约定 | ||
| 30 | + | ||
| 31 | +- `quant_mode`为3/5时,`query_dequant_scale`和`key_dequant_scale`必须为`torch.float8_e8m0fnu`。 | ||
| 32 | +- `quant_mode`为5时,`query`和`key`的算子逻辑数据类型为`FLOAT4_E2M1`(文档简写为`float4_e2m1`): | ||
| 33 | + - PyTorch提供`torch.float4_e2m1fn_x2`时,优先使用该原生打包类型;名称中的`x2`表示每个物理字节打包两个E2M1逻辑元素。 | ||
| 34 | + - PyTorch未提供该类型时,使用`torch.uint8`承载已打包数据,封装层会将其按`ACL_FLOAT4_E2M1`传入算子。 | ||
| 35 | + | ||
| 29 | - **运行模式**: | 36 | - **运行模式**: |
| 30 | - **eager**:直接调用 `torch.ops.cann_ops_transformer.quant_lightning_indexer` | 37 | - **eager**:直接调用 `torch.ops.cann_ops_transformer.quant_lightning_indexer` |
| 31 | - **graph**:通过 `torch.compile` + `torchair` 后端编译执行(需torchair支持) | 38 | - **graph**:通过 `torch.compile` + `torchair` 后端编译执行(需torchair支持) |
| @@ -211,8 +218,8 @@ bash batch_isolated_run.sh ./pt_path 1 graph # graph模式 + 性能采集 | |||
| 211 | | head_dim | int | `128` | | 218 | | head_dim | int | `128` | |
| 212 | | block_size | int | `512` | | 219 | | block_size | int | `512` | |
| 213 | | block_num | int | `8` | | 220 | | block_num | int | `8` | |
| 214 | -| qk_dtype | str | `FLOAT8_E4M3FN` / `INT8` / `HIFLOAT8` | | 221 | +| qk_dtype | str | `FLOAT8_E4M3FN` / `INT8` / `HIFLOAT8` / `FLOAT4_E2M1` | |
| 215 | -| dequant_dtype | str | `FP32` / `FP16` | | 222 | +| dequant_dtype | str | `FP32` / `FP16` / `FLOAT8_E8M0` | |
| 216 | | actual_seq_dtype | str | `INT32` | | 223 | | actual_seq_dtype | str | `INT32` | |
| 217 | | cu_seqlens_q | None/str | `None` 或 `"[0, 1]"` | | 224 | | cu_seqlens_q | None/str | `None` 或 `"[0, 1]"` | |
| 218 | | cu_seqlens_k | None/str | `None` 或 `"[0, 1]"` | | 225 | | cu_seqlens_k | None/str | `None` 或 `"[0, 1]"` | |
| @@ -236,7 +243,7 @@ bash batch_isolated_run.sh ./pt_path 1 graph # graph模式 + 性能采集 | |||
| 236 | 243 | ||
| 237 | **注意事项**: | 244 | **注意事项**: |
| 238 | 245 | ||
| 239 | -- `dequant_dtype`:Ascend950仅支持`FP32`,Ascend910_93支持`FP16` | 246 | +- `dequant_dtype`:Ascend950的`quant_mode=3/5`仅支持`FLOAT8_E8M0`,其他量化模式支持`FP32`;Ascend910_93支持`FP16` |
| 240 | - `cmp_ratio > 1`且`sparse_mode != 0`时,`cmp_residual_k`必填(长度=batch_size的列表) | 247 | - `cmp_ratio > 1`且`sparse_mode != 0`时,`cmp_residual_k`必填(长度=batch_size的列表) |
| 241 | - `return_value=1`时,`output_idx_offset`需提供有效值 | 248 | - `return_value=1`时,`output_idx_offset`需提供有效值 |
| 242 | - Ascend910_93要求`quant_mode=2` | 249 | - Ascend910_93要求`quant_mode=2` |
Mattention/quant_lightning_indexer_v2/tests/pytest/batch/quant_lightning_indexer_v2_pt_loadprocess.py+125-92
| @@ -11,7 +11,7 @@ | |||
| 11 | # ----------------------------------------------------------------------------------------------------------- | 11 | # ----------------------------------------------------------------------------------------------------------- |
| 12 | 12 | ||
| 13 | import os | 13 | import os |
| 14 | -import pandas as pd | 14 | +import pandas as pd |
| 15 | import numpy as np | 15 | import numpy as np |
| 16 | import torch | 16 | import torch |
| 17 | import torch_npu | 17 | import torch_npu |
| @@ -21,34 +21,35 @@ import math | |||
| 21 | import ast | 21 | import ast |
| 22 | import cann_ops_transformer | 22 | import cann_ops_transformer |
| 23 | 23 | ||
| 24 | + | ||
| 24 | def test_qliv2_process(filepath, device_id=0): | 25 | def test_qliv2_process(filepath, device_id=0): |
| 25 | # 加载测试数据 | 26 | # 加载测试数据 |
| 26 | test_data = torch.load(filepath, map_location="cpu") | 27 | test_data = torch.load(filepath, map_location="cpu") |
| 27 | 28 | ||
| 28 | - params = test_data['params'] | 29 | + params = test_data["params"] |
| 29 | - cpu_result = test_data['cpu_result'] | 30 | + cpu_result = test_data["cpu_result"] |
| 30 | - topk_value = test_data['topk_value'] | 31 | + topk_value = test_data["topk_value"] |
| 31 | - cpu_topk_value = test_data['cpu_topk_value'] | 32 | + cpu_topk_value = test_data["cpu_topk_value"] |
| 32 | print("执行用例:", filepath) | 33 | print("执行用例:", filepath) |
| 33 | torch_npu.npu.set_device(device_id) | 34 | torch_npu.npu.set_device(device_id) |
| 34 | 35 | ||
| 35 | - if params[10] == 'FLOAT8_E4M3FN': | 36 | + if params[10] == "FLOAT8_E4M3FN": |
| 36 | - query = test_data['query'].to(dtype=torch.float8_e4m3fn).npu() | 37 | + query = test_data["query"].to(dtype=torch.float8_e4m3fn).npu() |
| 37 | - key = test_data['key'].to(dtype=torch.float8_e4m3fn).npu() | 38 | + key = test_data["key"].to(dtype=torch.float8_e4m3fn).npu() |
| 38 | - if 'blockFusion' in test_data and test_data['blockFusion'] is not None: | 39 | + if "blockFusion" in test_data and test_data["blockFusion"] is not None: |
| 39 | - blockFusion = test_data['blockFusion'].to(dtype=torch.float8_e4m3fn).npu() | 40 | + blockFusion = test_data["blockFusion"].to(dtype=torch.float8_e4m3fn).npu() |
| 40 | else: | 41 | else: |
| 41 | - query = test_data['query'].npu() | 42 | + query = test_data["query"].npu() |
| 42 | - key = test_data['key'].npu() | 43 | + key = test_data["key"].npu() |
| 43 | - if 'blockFusion' in test_data and test_data['blockFusion'] is not None: | 44 | + if "blockFusion" in test_data and test_data["blockFusion"] is not None: |
| 44 | - blockFusion = test_data['blockFusion'].npu() | 45 | + blockFusion = test_data["blockFusion"].npu() |
| 45 | 46 | ||
| 46 | - max_seqlen_q = params[18] | 47 | + max_seqlen_q = params[19] |
| 47 | - return_value = params[30] | 48 | + return_value = params[31] |
| 48 | - weights =test_data['weights'].npu() | 49 | + weights = test_data["weights"].npu() |
| 49 | - query_dequant_scale = test_data['query_dequant_scale'].npu() | 50 | + query_dequant_scale = test_data["query_dequant_scale"].npu() |
| 50 | - key_dequant_scale = test_data['key_dequant_scale'].npu() | 51 | + key_dequant_scale = test_data["key_dequant_scale"].npu() |
| 51 | - if 'blockFusion' in test_data and test_data['blockFusion'] is not None: | 52 | + if "blockFusion" in test_data and test_data["blockFusion"] is not None: |
| 52 | block_num = params[9] | 53 | block_num = params[9] |
| 53 | block_size = params[8] | 54 | block_size = params[8] |
| 54 | head_dim = params[7] | 55 | head_dim = params[7] |
| @@ -57,96 +58,116 @@ def test_qliv2_process(filepath, device_id=0): | |||
| 57 | head_dim = int(head_dim) | 58 | head_dim = int(head_dim) |
| 58 | block_size = int(block_size) | 59 | block_size = int(block_size) |
| 59 | block_num = int(block_num) | 60 | block_num = int(block_num) |
| 60 | - dequant_dtype_str = params[11] | 61 | + dequant_dtype_str = params[12] |
| 61 | - if dequant_dtype_str == 'FP16' or dequant_dtype_str == torch.float16: | 62 | + if dequant_dtype_str == "FP16" or dequant_dtype_str == torch.float16: |
| 62 | dequant_dtype = torch.float16 | 63 | dequant_dtype = torch.float16 |
| 63 | - elif dequant_dtype_str == 'FP32' or dequant_dtype_str == torch.float32: | 64 | + elif dequant_dtype_str == "FP32" or dequant_dtype_str == torch.float32: |
| 64 | dequant_dtype = torch.float32 | 65 | dequant_dtype = torch.float32 |
| 65 | else: | 66 | else: |
| 66 | dequant_dtype = torch.float16 | 67 | dequant_dtype = torch.float16 |
| 67 | - key = blockFusion[:, :block_size * k_head_num * head_dim].view(block_num, block_size, k_head_num, head_dim) | 68 | + key = blockFusion[:, : block_size * k_head_num * head_dim].view( |
| 68 | - key_dequant_scale = blockFusion[:, block_size * k_head_num * head_dim:].view(dequant_dtype).view(block_num, block_size, k_head_num) | 69 | + block_num, block_size, k_head_num, head_dim |
| 69 | - if test_data['seqused_q'] is not None: | 70 | + ) |
| 70 | - seqused_q = test_data['seqused_q'].npu() | 71 | + key_dequant_scale = ( |
| 72 | + blockFusion[:, block_size * k_head_num * head_dim :] | ||
| 73 | + .view(dequant_dtype) | ||
| 74 | + .view(block_num, block_size, k_head_num) | ||
| 75 | + ) | ||
| 76 | + if test_data["seqused_q"] is not None: | ||
| 77 | + seqused_q = test_data["seqused_q"].npu() | ||
| 71 | else: | 78 | else: |
| 72 | seqused_q = None | 79 | seqused_q = None |
| 73 | - if test_data['seqused_k'] is not None: | 80 | + if test_data["seqused_k"] is not None: |
| 74 | - seqused_k = test_data['seqused_k'].npu() | 81 | + seqused_k = test_data["seqused_k"].npu() |
| 75 | else: | 82 | else: |
| 76 | seqused_k = None | 83 | seqused_k = None |
| 77 | - if test_data['output_idx_offset'] is not None: | 84 | + if test_data["output_idx_offset"] is not None: |
| 78 | - output_idx_offset = test_data['output_idx_offset'].npu() | 85 | + output_idx_offset = test_data["output_idx_offset"].npu() |
| 79 | else: | 86 | else: |
| 80 | output_idx_offset = None | 87 | output_idx_offset = None |
| 81 | - if test_data['cu_seqlens_query'] is not None: | 88 | + if test_data["cu_seqlens_query"] is not None: |
| 82 | - cu_seqlens_query = test_data['cu_seqlens_query'].npu() | 89 | + cu_seqlens_query = test_data["cu_seqlens_query"].npu() |
| 83 | else: | 90 | else: |
| 84 | cu_seqlens_query = None | 91 | cu_seqlens_query = None |
| 85 | - if test_data['cu_seqlens_key'] is not None: | 92 | + if test_data["cu_seqlens_key"] is not None: |
| 86 | - cu_seqlens_key = test_data['cu_seqlens_key'].npu() | 93 | + cu_seqlens_key = test_data["cu_seqlens_key"].npu() |
| 87 | else: | 94 | else: |
| 88 | cu_seqlens_key = None | 95 | cu_seqlens_key = None |
| 89 | - if test_data['block_table'] is not None: | 96 | + if test_data["block_table"] is not None: |
| 90 | - block_table = test_data['block_table'].npu() | 97 | + block_table = test_data["block_table"].npu() |
| 91 | else: | 98 | else: |
| 92 | block_table = None | 99 | block_table = None |
| 93 | - quant_mode = test_data['quant_mode'] | 100 | + quant_mode = test_data["quant_mode"] |
| 94 | - layout_query = test_data['layout_query'] | 101 | + layout_query = test_data["layout_query"] |
| 95 | - layout_key = test_data['layout_key'] | 102 | + layout_key = test_data["layout_key"] |
| 96 | - sparse_count = test_data['sparse_count'] | 103 | + sparse_count = test_data["sparse_count"] |
| 97 | - sparse_mode = test_data['sparse_mode'] | 104 | + sparse_mode = test_data["sparse_mode"] |
| 98 | - cmp_ratio = test_data['cmp_ratio'] | 105 | + cmp_ratio = test_data["cmp_ratio"] |
| 99 | - if test_data['cmp_residual_k_for_npu'] is not None: | 106 | + if test_data["cmp_residual_k_for_npu"] is not None: |
| 100 | - cmp_residual_k_for_npu = test_data['cmp_residual_k_for_npu'].npu() | 107 | + cmp_residual_k_for_npu = test_data["cmp_residual_k_for_npu"].npu() |
| 101 | else: | 108 | else: |
| 102 | cmp_residual_k_for_npu = None | 109 | cmp_residual_k_for_npu = None |
| 103 | 110 | ||
| 104 | - max_seqlen_q_meta = test_data['max_seqlen_q_meta'] | 111 | + max_seqlen_q_meta = test_data["max_seqlen_q_meta"] |
| 105 | - max_seqlen_k_meta = test_data['max_seqlen_k_meta'] | 112 | + max_seqlen_k_meta = test_data["max_seqlen_k_meta"] |
| 106 | metadata = torch.ops.cann_ops_transformer.quant_lightning_indexer_metadata( | 113 | metadata = torch.ops.cann_ops_transformer.quant_lightning_indexer_metadata( |
| 107 | - cu_seqlens_q = cu_seqlens_query, | 114 | + cu_seqlens_q=cu_seqlens_query, |
| 108 | - cu_seqlens_k = cu_seqlens_key, | 115 | + cu_seqlens_k=cu_seqlens_key, |
| 109 | - seqused_q = seqused_q, | 116 | + seqused_q=seqused_q, |
| 110 | - seqused_k = seqused_k, | 117 | + seqused_k=seqused_k, |
| 111 | - cmp_residual_k = cmp_residual_k_for_npu, | 118 | + cmp_residual_k=cmp_residual_k_for_npu, |
| 112 | - batch_size = params[0], | 119 | + batch_size=params[0], |
| 113 | - max_seqlen_q = max_seqlen_q_meta, | 120 | + max_seqlen_q=max_seqlen_q_meta, |
| 114 | - max_seqlen_k = max_seqlen_k_meta, | 121 | + max_seqlen_k=max_seqlen_k_meta, |
| 115 | - num_heads_q = params[5], | 122 | + num_heads_q=params[5], |
| 116 | - num_heads_k = params[6], | 123 | + num_heads_k=params[6], |
| 117 | - head_dim = params[7], | 124 | + head_dim=params[7], |
| 118 | - topk = sparse_count, | 125 | + topk=sparse_count, |
| 119 | - quant_mode = quant_mode, | 126 | + quant_mode=quant_mode, |
| 120 | - mask_mode = sparse_mode, | 127 | + mask_mode=sparse_mode, |
| 121 | - layout_q = layout_query, | 128 | + layout_q=layout_query, |
| 122 | - layout_k = layout_key, | 129 | + layout_k=layout_key, |
| 123 | - cmp_ratio = cmp_ratio) | 130 | + cmp_ratio=cmp_ratio, |
| 131 | + ) | ||
| 124 | metadata = metadata.npu() | 132 | metadata = metadata.npu() |
| 125 | 133 | ||
| 126 | - #调用qli算子 | 134 | + # 调用qli算子 |
| 127 | - npu_result, npu_value = torch.ops.cann_ops_transformer.quant_lightning_indexer(query, key, weights, | 135 | + npu_result, npu_value = torch.ops.cann_ops_transformer.quant_lightning_indexer( |
| 128 | - query_dequant_scale, | 136 | + query, |
| 129 | - key_dequant_scale, | 137 | + key, |
| 130 | - cu_seqlens_q = cu_seqlens_query, | 138 | + weights, |
| 131 | - cu_seqlens_k = cu_seqlens_key, | 139 | + query_dequant_scale, |
| 132 | - seqused_q = seqused_q, | 140 | + key_dequant_scale, |
| 133 | - seqused_k = seqused_k, | 141 | + cu_seqlens_q=cu_seqlens_query, |
| 134 | - cmp_residual_k = cmp_residual_k_for_npu, | 142 | + cu_seqlens_k=cu_seqlens_key, |
| 135 | - output_idx_offset = output_idx_offset, | 143 | + seqused_q=seqused_q, |
| 136 | - max_seqlen_q = max_seqlen_q, | 144 | + seqused_k=seqused_k, |
| 137 | - block_table=block_table, | 145 | + cmp_residual_k=cmp_residual_k_for_npu, |
| 138 | - metadata = metadata, | 146 | + output_idx_offset=output_idx_offset, |
| 139 | - quant_mode = quant_mode, | 147 | + max_seqlen_q=max_seqlen_q, |
| 140 | - layout_q = layout_query, | 148 | + block_table=block_table, |
| 141 | - layout_k = layout_key, | 149 | + metadata=metadata, |
| 142 | - topk = sparse_count, | 150 | + quant_mode=quant_mode, |
| 143 | - mask_mode = sparse_mode, | 151 | + layout_q=layout_query, |
| 144 | - cmp_ratio = cmp_ratio, | 152 | + layout_k=layout_key, |
| 145 | - return_value = return_value) | 153 | + topk=sparse_count, |
| 146 | - | 154 | + mask_mode=sparse_mode, |
| 155 | + cmp_ratio=cmp_ratio, | ||
| 156 | + return_value=return_value, | ||
| 157 | + ) | ||
| 158 | + | ||
| 147 | torch.npu.synchronize() | 159 | torch.npu.synchronize() |
| 148 | - npu_topk_value, _ = npu_value.sort(dim=-1, descending=True) | 160 | + npu_topk_value, npu_sort_order = npu_value.sort(dim=-1, descending=True) |
| 149 | - return cpu_result, npu_result, topk_value, cpu_topk_value, npu_topk_value, output_idx_offset, params | 161 | + npu_result = torch.gather(npu_result, dim=-1, index=npu_sort_order) |
| 162 | + return ( | ||
| 163 | + cpu_result, | ||
| 164 | + npu_result, | ||
| 165 | + topk_value, | ||
| 166 | + cpu_topk_value, | ||
| 167 | + npu_topk_value, | ||
| 168 | + output_idx_offset, | ||
| 169 | + params, | ||
| 170 | + ) | ||
| 150 | 171 | ||
| 151 | 172 | ||
| 152 | def test_qliv2_process_graph(filepath, device_id=0): | 173 | def test_qliv2_process_graph(filepath, device_id=0): |
| @@ -156,12 +177,24 @@ def test_qliv2_process_graph(filepath, device_id=0): | |||
| 156 | 与 eager 模式共用相同的 .pt 数据,仅算子调用路径不同(compile vs eager)。 | 177 | 与 eager 模式共用相同的 .pt 数据,仅算子调用路径不同(compile vs eager)。 |
| 157 | """ | 178 | """ |
| 158 | import quant_lightning_indexer_v2_acl_graph | 179 | import quant_lightning_indexer_v2_acl_graph |
| 180 | + | ||
| 159 | test_data = torch.load(filepath, map_location="cpu") | 181 | test_data = torch.load(filepath, map_location="cpu") |
| 160 | - params = test_data['params'] | 182 | + params = test_data["params"] |
| 161 | - output_idx_offset = test_data.get('output_idx_offset', None) | 183 | + output_idx_offset = test_data.get("output_idx_offset", None) |
| 162 | 184 | ||
| 163 | torch_npu.npu.set_device(device_id) | 185 | torch_npu.npu.set_device(device_id) |
| 164 | - cpu_result, npu_result, topk_value, cpu_topk_value, npu_topk_value = \ | 186 | + cpu_result, npu_result, topk_value, cpu_topk_value, npu_topk_value = ( |
| 165 | - quant_lightning_indexer_v2_acl_graph.qliv2_output_acl_graph_from_pt(params, test_data) | 187 | + quant_lightning_indexer_v2_acl_graph.qliv2_output_acl_graph_from_pt( |
| 188 | + params, test_data | ||
| 189 | + ) | ||
| 190 | + ) | ||
| 166 | 191 | ||
| 167 | - return cpu_result, npu_result, topk_value, cpu_topk_value, npu_topk_value, output_idx_offset, params | 192 | + return ( |
| 193 | + cpu_result, | ||
| 194 | + npu_result, | ||
| 195 | + topk_value, | ||
| 196 | + cpu_topk_value, | ||
| 197 | + npu_topk_value, | ||
| 198 | + output_idx_offset, | ||
| 199 | + params, | ||
| 200 | + ) | ||
Mattention/quant_lightning_indexer_v2/tests/pytest/batch/quant_lightning_indexer_v2_pt_save.py+90-50
| @@ -16,6 +16,7 @@ from quant_lightning_indexer_v2_golden import generate_qliv2_test_data | |||
| 16 | import pandas as pd | 16 | import pandas as pd |
| 17 | import numpy as np | 17 | import numpy as np |
| 18 | import torch | 18 | import torch |
| 19 | + | ||
| 19 | try: | 20 | try: |
| 20 | import torch_npu | 21 | import torch_npu |
| 21 | except ImportError: | 22 | except ImportError: |
| @@ -26,8 +27,8 @@ import math | |||
| 26 | import ast | 27 | import ast |
| 27 | import argparse | 28 | import argparse |
| 28 | 29 | ||
| 29 | -def load_excel_test_cases(excel_file_path: str, sheetname: str): | ||
| 30 | 30 | ||
| 31 | +def load_excel_test_cases(excel_file_path: str, sheetname: str): | ||
| 31 | """ | 32 | """ |
| 32 | 从 Excel 文件加载测试用例。 | 33 | 从 Excel 文件加载测试用例。 |
| 33 | 34 | ||
| @@ -41,7 +42,7 @@ def load_excel_test_cases(excel_file_path: str, sheetname: str): | |||
| 41 | """ | 42 | """ |
| 42 | # 优先使用传入的 sheetname,否则尝试从环境变量获取 | 43 | # 优先使用传入的 sheetname,否则尝试从环境变量获取 |
| 43 | if sheetname is None: | 44 | if sheetname is None: |
| 44 | - sheetname = 'Sheet1' | 45 | + sheetname = "Sheet1" |
| 45 | 46 | ||
| 46 | # 检查文件是否存在 | 47 | # 检查文件是否存在 |
| 47 | if not os.path.exists(excel_file_path): | 48 | if not os.path.exists(excel_file_path): |
| @@ -54,58 +55,92 @@ def load_excel_test_cases(excel_file_path: str, sheetname: str): | |||
| 54 | 55 | ||
| 55 | # 定义必需的列名 | 56 | # 定义必需的列名 |
| 56 | required_columns = [ | 57 | required_columns = [ |
| 57 | - 'Testcase_Name', 'batch_size', 'q_seq','k_seq','q_t_size', 'k_t_size', | 58 | + "Testcase_Name", |
| 58 | - 'q_head_num', 'k_head_num', 'head_dim', 'block_size', 'block_num', | 59 | + "batch_size", |
| 59 | - 'qk_dtype', 'dequant_dtype', 'actual_seq_dtype', 'cu_seqlens_q', 'cu_seqlens_k', | 60 | + "q_seq", |
| 60 | - 'seqused_q', 'seqused_k', 'cmp_residual_k', 'max_seqlen_q', 'quant_mode', | 61 | + "k_seq", |
| 61 | - 'layout_query', 'layout_key', 'sparse_count', 'sparse_mode', 'query_datarange', | 62 | + "q_t_size", |
| 62 | - 'key_datarange', 'weights_datarange', 'q_scale_datarange', | 63 | + "k_t_size", |
| 63 | - 'k_scale_datarange', 'cmp_ratio', 'return_value', 'output_idx_offset' | 64 | + "q_head_num", |
| 65 | + "k_head_num", | ||
| 66 | + "head_dim", | ||
| 67 | + "block_size", | ||
| 68 | + "block_num", | ||
| 69 | + "qk_dtype", | ||
| 70 | + "dequant_dtype", | ||
| 71 | + "actual_seq_dtype", | ||
| 72 | + "cu_seqlens_q", | ||
| 73 | + "cu_seqlens_k", | ||
| 74 | + "seqused_q", | ||
| 75 | + "seqused_k", | ||
| 76 | + "cmp_residual_k", | ||
| 77 | + "max_seqlen_q", | ||
| 78 | + "quant_mode", | ||
| 79 | + "layout_query", | ||
| 80 | + "layout_key", | ||
| 81 | + "sparse_count", | ||
| 82 | + "sparse_mode", | ||
| 83 | + "query_datarange", | ||
| 84 | + "key_datarange", | ||
| 85 | + "weights_datarange", | ||
| 86 | + "q_scale_datarange", | ||
| 87 | + "k_scale_datarange", | ||
| 88 | + "cmp_ratio", | ||
| 89 | + "return_value", | ||
| 90 | + "output_idx_offset", | ||
| 64 | ] | 91 | ] |
| 65 | 92 | ||
| 66 | # 检查是否缺少必要列 | 93 | # 检查是否缺少必要列 |
| 67 | missing_cols = [col for col in required_columns if col not in df.columns] | 94 | missing_cols = [col for col in required_columns if col not in df.columns] |
| 68 | if missing_cols: | 95 | if missing_cols: |
| 69 | - pytest.skip(f"Missing required columns in Excel: {missing_cols}", allow_module_level=True) | 96 | + pytest.skip( |
| 97 | + f"Missing required columns in Excel: {missing_cols}", | ||
| 98 | + allow_module_level=True, | ||
| 99 | + ) | ||
| 70 | 100 | ||
| 71 | # 构建测试用例列表 | 101 | # 构建测试用例列表 |
| 72 | test_cases = [] | 102 | test_cases = [] |
| 73 | for _, row in df.iterrows(): | 103 | for _, row in df.iterrows(): |
| 74 | - test_cases.append(( | 104 | + test_cases.append( |
| 75 | - row['Testcase_Name'], | 105 | + ( |
| 76 | - row['batch_size'], | 106 | + row["Testcase_Name"], |
| 77 | - row['q_seq'], | 107 | + row["batch_size"], |
| 78 | - row['k_seq'], | 108 | + row["q_seq"], |
| 79 | - row['q_t_size'], | 109 | + row["k_seq"], |
| 80 | - row['k_t_size'], | 110 | + row["q_t_size"], |
| 81 | - row['q_head_num'], | 111 | + row["k_t_size"], |
| 82 | - row['k_head_num'], | 112 | + row["q_head_num"], |
| 83 | - row['head_dim'], | 113 | + row["k_head_num"], |
| 84 | - row['block_size'], | 114 | + row["head_dim"], |
| 85 | - row['block_num'], | 115 | + row["block_size"], |
| 86 | - row['qk_dtype'], | 116 | + row["block_num"], |
| 87 | - row['dequant_dtype'], | 117 | + row["qk_dtype"], |
| 88 | - row['actual_seq_dtype'], | 118 | + row["weight_dtype"] |
| 89 | - row['cu_seqlens_q'], | 119 | + if "weight_dtype" in row and row["weight_dtype"] is not None |
| 90 | - row['cu_seqlens_k'], | 120 | + else row["dequant_dtype"], |
| 91 | - row['seqused_q'], | 121 | + row["dequant_dtype"], |
| 92 | - row['seqused_k'], | 122 | + row["actual_seq_dtype"], |
| 93 | - row['cmp_residual_k'], | 123 | + row["cu_seqlens_q"], |
| 94 | - row['max_seqlen_q'], | 124 | + row["cu_seqlens_k"], |
| 95 | - row['quant_mode'], | 125 | + row["seqused_q"], |
| 96 | - row['layout_query'], | 126 | + row["seqused_k"], |
| 97 | - row['layout_key'], | 127 | + row["cmp_residual_k"], |
| 98 | - row['sparse_count'], | 128 | + row["max_seqlen_q"], |
| 99 | - row['sparse_mode'], | 129 | + row["quant_mode"], |
| 100 | - row['query_datarange'], | 130 | + row["layout_query"], |
| 101 | - row['key_datarange'], | 131 | + row["layout_key"], |
| 102 | - row['weights_datarange'], | 132 | + row["sparse_count"], |
| 103 | - row['q_scale_datarange'], | 133 | + row["sparse_mode"], |
| 104 | - row['k_scale_datarange'], | 134 | + row["query_datarange"], |
| 105 | - row['cmp_ratio'], | 135 | + row["key_datarange"], |
| 106 | - row['return_value'], | 136 | + row["weights_datarange"], |
| 107 | - row['output_idx_offset'] | 137 | + row["q_scale_datarange"], |
| 108 | - )) | 138 | + row["k_scale_datarange"], |
| 139 | + row["cmp_ratio"], | ||
| 140 | + row["return_value"], | ||
| 141 | + row["output_idx_offset"], | ||
| 142 | + ) | ||
| 143 | + ) | ||
| 109 | 144 | ||
| 110 | return test_cases | 145 | return test_cases |
| 111 | 146 | ||
| @@ -113,6 +148,7 @@ def load_excel_test_cases(excel_file_path: str, sheetname: str): | |||
| 113 | pytest.skip(f"Failed to read Excel file: {e}", allow_module_level=True) | 148 | pytest.skip(f"Failed to read Excel file: {e}", allow_module_level=True) |
| 114 | return None | 149 | return None |
| 115 | 150 | ||
| 151 | + | ||
| 116 | def save_test_case(test_cases, file_path): | 152 | def save_test_case(test_cases, file_path): |
| 117 | print("正在保存pt文件...") | 153 | print("正在保存pt文件...") |
| 118 | # 创建输出目录 | 154 | # 创建输出目录 |
| @@ -134,16 +170,20 @@ def save_test_case(test_cases, file_path): | |||
| 134 | print(f"[失败] 生成 pt 文件失败: {case[0]} (索引: {idx})") | 170 | print(f"[失败] 生成 pt 文件失败: {case[0]} (索引: {idx})") |
| 135 | print(f"错误详情: {e}") | 171 | print(f"错误详情: {e}") |
| 136 | 172 | ||
| 173 | + | ||
| 137 | def main(): | 174 | def main(): |
| 138 | - parser = argparse.ArgumentParser(description='qliv2_pt_save.py 接收路径参数') | 175 | + parser = argparse.ArgumentParser(description="qliv2_pt_save.py 接收路径参数") |
| 139 | - parser.add_argument('path1', type=str, help='第一个路径') | 176 | + parser.add_argument("path1", type=str, help="第一个路径") |
| 140 | - parser.add_argument('path2', type=str, help='第二个路径') | 177 | + parser.add_argument("path2", type=str, help="第二个路径") |
| 141 | - parser.add_argument('--sheet', '-S', type=str, default='Sheet1', help='Sheet 页名(默认: Sheet1)') | 178 | + parser.add_argument( |
| 179 | + "--sheet", "-S", type=str, default="Sheet1", help="Sheet 页名(默认: Sheet1)" | ||
| 180 | + ) | ||
| 142 | args = parser.parse_args() | 181 | args = parser.parse_args() |
| 143 | path1 = args.path1 | 182 | path1 = args.path1 |
| 144 | path2 = args.path2 | 183 | path2 = args.path2 |
| 145 | - testcase = load_excel_test_cases(path1, args.sheet) | 184 | + testcase = load_excel_test_cases(path1, args.sheet) |
| 146 | save_test_case(testcase, path2) | 185 | save_test_case(testcase, path2) |
| 147 | 186 | ||
| 187 | + | ||
| 148 | if __name__ == "__main__": | 188 | if __name__ == "__main__": |
| 149 | main() | 189 | main() |
| @@ -19,25 +19,53 @@ import pandas as pd | |||
| 19 | 19 | ||
| 20 | 20 | ||
| 21 | PARAM_NAMES = ( | 21 | PARAM_NAMES = ( |
| 22 | - "batch_size", "q_seq", "k_seq", "q_t_size", "k_t_size", "q_head_num", | 22 | + "batch_size", |
| 23 | - "k_head_num", "head_dim", "block_size", "block_num", "qk_dtype", | 23 | + "q_seq", |
| 24 | - "dequant_dtype", "actual_seq_dtype", "cu_seq_q", "cu_seq_k", "act_seq_q", | 24 | + "k_seq", |
| 25 | - "act_seq_k", "cmp_residual_k", "max_seqlen_q", "quant_mode", "layout_query", | 25 | + "q_t_size", |
| 26 | - "layout_key", "sparse_count", "sparse_mode", "query_datarange", "key_datarange", | 26 | + "k_t_size", |
| 27 | - "weights_datarange", "q_scale_datarange", "k_scale_datarange", "cmp_ratio", | 27 | + "q_head_num", |
| 28 | - "return_value", "output_idx_offset", | 28 | + "k_head_num", |
| 29 | + "head_dim", | ||
| 30 | + "block_size", | ||
| 31 | + "block_num", | ||
| 32 | + "qk_dtype", | ||
| 33 | + "weight_dtype", | ||
| 34 | + "dequant_dtype", | ||
| 35 | + "actual_seq_dtype", | ||
| 36 | + "cu_seq_q", | ||
| 37 | + "cu_seq_k", | ||
| 38 | + "act_seq_q", | ||
| 39 | + "act_seq_k", | ||
| 40 | + "cmp_residual_k", | ||
| 41 | + "max_seqlen_q", | ||
| 42 | + "quant_mode", | ||
| 43 | + "layout_query", | ||
| 44 | + "layout_key", | ||
| 45 | + "sparse_count", | ||
| 46 | + "sparse_mode", | ||
| 47 | + "query_datarange", | ||
| 48 | + "key_datarange", | ||
| 49 | + "weights_datarange", | ||
| 50 | + "q_scale_datarange", | ||
| 51 | + "k_scale_datarange", | ||
| 52 | + "cmp_ratio", | ||
| 53 | + "return_value", | ||
| 54 | + "output_idx_offset", | ||
| 29 | ) | 55 | ) |
| 30 | 56 | ||
| 31 | 57 | ||
| 32 | -def ensure_comparison_passed(case_name, result, fulfill_percent, | 58 | +def ensure_comparison_passed( |
| 33 | - result_return_value="N/A", | 59 | + case_name, |
| 34 | - fulfill_percent_return_value=0): | 60 | + result, |
| 61 | + fulfill_percent, | ||
| 62 | + result_return_value="N/A", | ||
| 63 | + fulfill_percent_return_value=0, | ||
| 64 | +): | ||
| 35 | """Raise a serializable error when an accuracy comparison fails.""" | 65 | """Raise a serializable error when an accuracy comparison fails.""" |
| 36 | failures = [] | 66 | failures = [] |
| 37 | if result != "Pass": | 67 | if result != "Pass": |
| 38 | - failures.append( | 68 | + failures.append(f"index result={result}, fulfill_percent={fulfill_percent}") |
| 39 | - f"index result={result}, fulfill_percent={fulfill_percent}" | ||
| 40 | - ) | ||
| 41 | if result_return_value not in ("N/A", "Pass"): | 69 | if result_return_value not in ("N/A", "Pass"): |
| 42 | failures.append( | 70 | failures.append( |
| 43 | "value result=" | 71 | "value result=" |
| @@ -84,7 +112,9 @@ class QliV2CaseSelector: | |||
| 84 | @classmethod | 112 | @classmethod |
| 85 | def resolve(cls, pt_dir, explicit_files="", case_names="", case_indexes=""): | 113 | def resolve(cls, pt_dir, explicit_files="", case_names="", case_indexes=""): |
| 86 | if explicit_files: | 114 | if explicit_files: |
| 87 | - candidates = [Path(item.strip()) for item in explicit_files.split(",") if item.strip()] | 115 | + candidates = [ |
| 116 | + Path(item.strip()) for item in explicit_files.split(",") if item.strip() | ||
| 117 | + ] | ||
| 88 | else: | 118 | else: |
| 89 | directory = Path(pt_dir) | 119 | directory = Path(pt_dir) |
| 90 | if not directory.is_dir(): | 120 | if not directory.is_dir(): |
| @@ -137,15 +167,21 @@ class QliV2ResultWriter: | |||
| 137 | readable = ( | 167 | readable = ( |
| 138 | f"QLI_B{values[0]}_S1{values[1]}_S2{values[2]}_" | 168 | f"QLI_B{values[0]}_S1{values[1]}_S2{values[2]}_" |
| 139 | f"N1{values[5]}_N2{values[6]}_D{values[7]}_" | 169 | f"N1{values[5]}_N2{values[6]}_D{values[7]}_" |
| 140 | - f"{values[20]}_{values[21]}_{values[10]}_" | 170 | + f"{values[21]}_{values[22]}_{values[10]}_" |
| 141 | - f"QM{values[19]}_SM{values[23]}_CR{values[29]}_" | 171 | + f"QM{values[20]}_SM{values[24]}_CR{values[30]}_" |
| 142 | - f"K{values[22]}_RV{values[30]}" | 172 | + f"K{values[23]}_RV{values[31]}" |
| 143 | ) | 173 | ) |
| 144 | return re.sub(r"[^A-Za-z0-9_.-]+", "_", readable) | 174 | return re.sub(r"[^A-Za-z0-9_.-]+", "_", readable) |
| 145 | 175 | ||
| 146 | @staticmethod | 176 | @staticmethod |
| 147 | - def row(case_name, params, result, fulfill_percent, | 177 | + def row( |
| 148 | - result_return_value="N/A", fulfill_percent_return_value=0): | 178 | + case_name, |
| 179 | + params, | ||
| 180 | + result, | ||
| 181 | + fulfill_percent, | ||
| 182 | + result_return_value="N/A", | ||
| 183 | + fulfill_percent_return_value=0, | ||
| 184 | + ): | ||
| 149 | values = list(params) | 185 | values = list(params) |
| 150 | if len(values) != len(PARAM_NAMES): | 186 | if len(values) != len(PARAM_NAMES): |
| 151 | raise ValueError( | 187 | raise ValueError( |
| @@ -153,12 +189,14 @@ class QliV2ResultWriter: | |||
| 153 | ) | 189 | ) |
| 154 | row = {"case_name": case_name} | 190 | row = {"case_name": case_name} |
| 155 | row.update(dict(zip(PARAM_NAMES, values))) | 191 | row.update(dict(zip(PARAM_NAMES, values))) |
| 156 | - row.update({ | 192 | + row.update( |
| 157 | - "result": result, | 193 | + { |
| 158 | - "fulfill_percent": fulfill_percent, | 194 | + "result": result, |
| 159 | - "result_return_value": result_return_value, | 195 | + "fulfill_percent": fulfill_percent, |
| 160 | - "fulfill_percent_return_value": fulfill_percent_return_value, | 196 | + "result_return_value": result_return_value, |
| 161 | - }) | 197 | + "fulfill_percent_return_value": fulfill_percent_return_value, |
| 198 | + } | ||
| 199 | + ) | ||
| 162 | return row | 200 | return row |
| 163 | 201 | ||
| 164 | @staticmethod | 202 | @staticmethod |
| @@ -168,7 +206,9 @@ class QliV2ResultWriter: | |||
| 168 | if output.exists(): | 206 | if output.exists(): |
| 169 | frame = pd.read_excel(output) | 207 | frame = pd.read_excel(output) |
| 170 | expected_columns = list(row.keys()) | 208 | expected_columns = list(row.keys()) |
| 171 | - legacy_columns = [name for name in expected_columns if name != "return_value"] | 209 | + legacy_columns = [ |
| 210 | + name for name in expected_columns if name != "return_value" | ||
| 211 | + ] | ||
| 172 | if list(frame.columns) == legacy_columns: | 212 | if list(frame.columns) == legacy_columns: |
| 173 | frame["return_value"] = None | 213 | frame["return_value"] = None |
| 174 | frame = frame[expected_columns] | 214 | frame = frame[expected_columns] |
| @@ -20,33 +20,60 @@ from torchair.configs.compiler_config import CompilerConfig | |||
| 20 | import cann_ops_transformer | 20 | import cann_ops_transformer |
| 21 | import quant_lightning_indexer_v2_golden | 21 | import quant_lightning_indexer_v2_golden |
| 22 | 22 | ||
| 23 | +QUANT_MODE_MXFP4 = 5 | ||
| 24 | + | ||
| 23 | 25 | ||
| 24 | class QLIV2Network(nn.Module): | 26 | class QLIV2Network(nn.Module): |
| 25 | def __init__(self): | 27 | def __init__(self): |
| 26 | super(QLIV2Network, self).__init__() | 28 | super(QLIV2Network, self).__init__() |
| 27 | 29 | ||
| 28 | - def forward(self, query, key, weights, query_dequant_scale, key_dequant_scale, cu_seqlens_q, cu_seqlens_k, | 30 | + def forward( |
| 29 | - seqused_q, seqused_k, cmp_residual_k, output_idx_offset, max_seqlen_q, block_table, metadata, | 31 | + self, |
| 30 | - quant_mode, layout_query, layout_key, sparse_count, sparse_mode, cmp_ratio, return_value): | 32 | + query, |
| 31 | - return torch.ops.cann_ops_transformer.quant_lightning_indexer(query, key, weights, | 33 | + key, |
| 32 | - query_dequant_scale, | 34 | + weights, |
| 33 | - key_dequant_scale, | 35 | + query_dequant_scale, |
| 34 | - cu_seqlens_q=cu_seqlens_q, | 36 | + key_dequant_scale, |
| 35 | - cu_seqlens_k=cu_seqlens_k, | 37 | + cu_seqlens_q, |
| 36 | - seqused_q=seqused_q, | 38 | + cu_seqlens_k, |
| 37 | - seqused_k=seqused_k, | 39 | + seqused_q, |
| 38 | - cmp_residual_k=cmp_residual_k, | 40 | + seqused_k, |
| 39 | - output_idx_offset=output_idx_offset, | 41 | + cmp_residual_k, |
| 40 | - max_seqlen_q=max_seqlen_q, | 42 | + output_idx_offset, |
| 41 | - block_table=block_table, | 43 | + max_seqlen_q, |
| 42 | - metadata=metadata, | 44 | + block_table, |
| 43 | - quant_mode=quant_mode, | 45 | + metadata, |
| 44 | - layout_q=layout_query, | 46 | + quant_mode, |
| 45 | - layout_k=layout_key, | 47 | + layout_query, |
| 46 | - topk=sparse_count, | 48 | + layout_key, |
| 47 | - mask_mode=sparse_mode, | 49 | + sparse_count, |
| 48 | - cmp_ratio=cmp_ratio, | 50 | + sparse_mode, |
| 49 | - return_value=return_value) | 51 | + cmp_ratio, |
| 52 | + return_value, | ||
| 53 | + ): | ||
| 54 | + return torch.ops.cann_ops_transformer.quant_lightning_indexer( | ||
| 55 | + query, | ||
| 56 | + key, | ||
| 57 | + weights, | ||
| 58 | + query_dequant_scale, | ||
| 59 | + key_dequant_scale, | ||
| 60 | + cu_seqlens_q=cu_seqlens_q, | ||
| 61 | + cu_seqlens_k=cu_seqlens_k, | ||
| 62 | + seqused_q=seqused_q, | ||
| 63 | + seqused_k=seqused_k, | ||
| 64 | + cmp_residual_k=cmp_residual_k, | ||
| 65 | + output_idx_offset=output_idx_offset, | ||
| 66 | + max_seqlen_q=max_seqlen_q, | ||
| 67 | + block_table=block_table, | ||
| 68 | + metadata=metadata, | ||
| 69 | + quant_mode=quant_mode, | ||
| 70 | + layout_q=layout_query, | ||
| 71 | + layout_k=layout_key, | ||
| 72 | + topk=sparse_count, | ||
| 73 | + mask_mode=sparse_mode, | ||
| 74 | + cmp_ratio=cmp_ratio, | ||
| 75 | + return_value=return_value, | ||
| 76 | + ) | ||
| 50 | 77 | ||
| 51 | 78 | ||
| 52 | def _qliv2_prepare_tensors_and_metadata(params, tensor_dict): | 79 | def _qliv2_prepare_tensors_and_metadata(params, tensor_dict): |
| @@ -55,46 +82,83 @@ def _qliv2_prepare_tensors_and_metadata(params, tensor_dict): | |||
| 55 | 兼容两个来源:generate_qliv2_test_data 返回值和 .pt 文件加载,二者都在 CPU。 | 82 | 兼容两个来源:generate_qliv2_test_data 返回值和 .pt 文件加载,二者都在 CPU。 |
| 56 | """ | 83 | """ |
| 57 | qk_dtype = params[10] | 84 | qk_dtype = params[10] |
| 85 | + quant_mode = tensor_dict["quant_mode"] | ||
| 58 | 86 | ||
| 59 | - if qk_dtype == 'FLOAT8_E4M3FN' or qk_dtype == torch.float8_e4m3fn: | 87 | + if quant_mode == QUANT_MODE_MXFP4: |
| 88 | + # TorchAir通过foreach_copy搬运图输入,当前不支持FP4 shell dtype;使用相同存储的 | ||
| 89 | + # packed uint8视图,C++入口会根据quant_mode恢复ACL_FLOAT4_E2M1语义。 | ||
| 90 | + query = tensor_dict["query"].view(torch.uint8).npu() | ||
| 91 | + key = tensor_dict["key"].view(torch.uint8).npu() | ||
| 92 | + if "blockFusion" in tensor_dict and tensor_dict["blockFusion"] is not None: | ||
| 93 | + blockFusion = tensor_dict["blockFusion"].view(torch.uint8).npu() | ||
| 94 | + elif qk_dtype == "FLOAT8_E4M3FN" or qk_dtype == torch.float8_e4m3fn: | ||
| 60 | query = tensor_dict["query"].to(dtype=torch.float8_e4m3fn).npu() | 95 | query = tensor_dict["query"].to(dtype=torch.float8_e4m3fn).npu() |
| 61 | key = tensor_dict["key"].to(dtype=torch.float8_e4m3fn).npu() | 96 | key = tensor_dict["key"].to(dtype=torch.float8_e4m3fn).npu() |
| 62 | - if 'blockFusion' in tensor_dict and tensor_dict['blockFusion'] is not None: | 97 | + if "blockFusion" in tensor_dict and tensor_dict["blockFusion"] is not None: |
| 63 | - blockFusion = tensor_dict['blockFusion'].to(dtype=torch.float8_e4m3fn).npu() | 98 | + blockFusion = tensor_dict["blockFusion"].to(dtype=torch.float8_e4m3fn).npu() |
| 64 | else: | 99 | else: |
| 65 | query = tensor_dict["query"].npu() | 100 | query = tensor_dict["query"].npu() |
| 66 | key = tensor_dict["key"].npu() | 101 | key = tensor_dict["key"].npu() |
| 67 | - if 'blockFusion' in tensor_dict and tensor_dict['blockFusion'] is not None: | 102 | + if "blockFusion" in tensor_dict and tensor_dict["blockFusion"] is not None: |
| 68 | - blockFusion = tensor_dict['blockFusion'].npu() | 103 | + blockFusion = tensor_dict["blockFusion"].npu() |
| 69 | 104 | ||
| 70 | weights = tensor_dict["weights"].npu() | 105 | weights = tensor_dict["weights"].npu() |
| 71 | query_dequant_scale = tensor_dict["query_dequant_scale"].npu() | 106 | query_dequant_scale = tensor_dict["query_dequant_scale"].npu() |
| 72 | key_dequant_scale = tensor_dict["key_dequant_scale"].npu() | 107 | key_dequant_scale = tensor_dict["key_dequant_scale"].npu() |
| 73 | 108 | ||
| 74 | - if 'blockFusion' in tensor_dict and tensor_dict['blockFusion'] is not None: | 109 | + if "blockFusion" in tensor_dict and tensor_dict["blockFusion"] is not None: |
| 75 | block_num = int(params[9]) | 110 | block_num = int(params[9]) |
| 76 | block_size = int(params[8]) | 111 | block_size = int(params[8]) |
| 77 | head_dim = int(params[7]) | 112 | head_dim = int(params[7]) |
| 78 | k_head_num = int(params[6]) | 113 | k_head_num = int(params[6]) |
| 79 | - dequant_dtype_str = params[11] | 114 | + dequant_dtype_str = params[12] |
| 80 | - if dequant_dtype_str == 'FP16' or dequant_dtype_str == torch.float16: | 115 | + if dequant_dtype_str == "FP16" or dequant_dtype_str == torch.float16: |
| 81 | dequant_dtype = torch.float16 | 116 | dequant_dtype = torch.float16 |
| 82 | - elif dequant_dtype_str == 'FP32' or dequant_dtype_str == torch.float32: | 117 | + elif dequant_dtype_str == "FP32" or dequant_dtype_str == torch.float32: |
| 83 | dequant_dtype = torch.float32 | 118 | dequant_dtype = torch.float32 |
| 84 | else: | 119 | else: |
| 85 | dequant_dtype = torch.float16 | 120 | dequant_dtype = torch.float16 |
| 86 | - key = blockFusion[:, :block_size * k_head_num * head_dim].view(block_num, block_size, k_head_num, head_dim) | 121 | + key = blockFusion[:, : block_size * k_head_num * head_dim].view( |
| 87 | - key_dequant_scale = blockFusion[:, block_size * k_head_num * head_dim:].view(dequant_dtype).view(block_num, block_size, k_head_num) | 122 | + block_num, block_size, k_head_num, head_dim |
| 123 | + ) | ||
| 124 | + key_dequant_scale = ( | ||
| 125 | + blockFusion[:, block_size * k_head_num * head_dim :] | ||
| 126 | + .view(dequant_dtype) | ||
| 127 | + .view(block_num, block_size, k_head_num) | ||
| 128 | + ) | ||
| 88 | 129 | ||
| 89 | - cu_seqlens_query = tensor_dict["cu_seqlens_query"].npu() if tensor_dict["cu_seqlens_query"] is not None else None | 130 | + cu_seqlens_query = ( |
| 90 | - cu_seqlens_key = tensor_dict["cu_seqlens_key"].npu() if tensor_dict["cu_seqlens_key"] is not None else None | 131 | + tensor_dict["cu_seqlens_query"].npu() |
| 91 | - seqused_q = tensor_dict["seqused_q"].npu() if tensor_dict["seqused_q"] is not None else None | 132 | + if tensor_dict["cu_seqlens_query"] is not None |
| 92 | - seqused_k = tensor_dict["seqused_k"].npu() if tensor_dict["seqused_k"] is not None else None | 133 | + else None |
| 93 | - output_idx_offset = tensor_dict["output_idx_offset"].npu() if tensor_dict["output_idx_offset"] is not None else None | 134 | + ) |
| 94 | - block_table = tensor_dict["block_table"].npu() if tensor_dict["block_table"] is not None else None | 135 | + cu_seqlens_key = ( |
| 95 | - cmp_residual_k_for_npu = tensor_dict["cmp_residual_k_for_npu"].npu() if tensor_dict.get("cmp_residual_k_for_npu") is not None else None | 136 | + tensor_dict["cu_seqlens_key"].npu() |
| 137 | + if tensor_dict["cu_seqlens_key"] is not None | ||
| 138 | + else None | ||
| 139 | + ) | ||
| 140 | + seqused_q = ( | ||
| 141 | + tensor_dict["seqused_q"].npu() if tensor_dict["seqused_q"] is not None else None | ||
| 142 | + ) | ||
| 143 | + seqused_k = ( | ||
| 144 | + tensor_dict["seqused_k"].npu() if tensor_dict["seqused_k"] is not None else None | ||
| 145 | + ) | ||
| 146 | + output_idx_offset = ( | ||
| 147 | + tensor_dict["output_idx_offset"].npu() | ||
| 148 | + if tensor_dict["output_idx_offset"] is not None | ||
| 149 | + else None | ||
| 150 | + ) | ||
| 151 | + block_table = ( | ||
| 152 | + tensor_dict["block_table"].npu() | ||
| 153 | + if tensor_dict["block_table"] is not None | ||
| 154 | + else None | ||
| 155 | + ) | ||
| 156 | + cmp_residual_k_for_npu = ( | ||
| 157 | + tensor_dict["cmp_residual_k_for_npu"].npu() | ||
| 158 | + if tensor_dict.get("cmp_residual_k_for_npu") is not None | ||
| 159 | + else None | ||
| 160 | + ) | ||
| 96 | 161 | ||
| 97 | - quant_mode = tensor_dict["quant_mode"] | ||
| 98 | layout_query = tensor_dict["layout_query"] | 162 | layout_query = tensor_dict["layout_query"] |
| 99 | layout_key = tensor_dict["layout_key"] | 163 | layout_key = tensor_dict["layout_key"] |
| 100 | sparse_count = tensor_dict["sparse_count"] | 164 | sparse_count = tensor_dict["sparse_count"] |
| @@ -125,7 +189,8 @@ def _qliv2_prepare_tensors_and_metadata(params, tensor_dict): | |||
| 125 | mask_mode=sparse_mode, | 189 | mask_mode=sparse_mode, |
| 126 | layout_q=layout_query, | 190 | layout_q=layout_query, |
| 127 | layout_k=layout_key, | 191 | layout_k=layout_key, |
| 128 | - cmp_ratio=cmp_ratio) | 192 | + cmp_ratio=cmp_ratio, |
| 193 | + ) | ||
| 129 | metadata = metadata.npu() | 194 | metadata = metadata.npu() |
| 130 | 195 | ||
| 131 | run_args = { | 196 | run_args = { |
| @@ -140,7 +205,7 @@ def _qliv2_prepare_tensors_and_metadata(params, tensor_dict): | |||
| 140 | "seqused_k": seqused_k, | 205 | "seqused_k": seqused_k, |
| 141 | "cmp_residual_k": cmp_residual_k_for_npu, | 206 | "cmp_residual_k": cmp_residual_k_for_npu, |
| 142 | "output_idx_offset": output_idx_offset, | 207 | "output_idx_offset": output_idx_offset, |
| 143 | - "max_seqlen_q": params[18], | 208 | + "max_seqlen_q": params[19], |
| 144 | "block_table": block_table, | 209 | "block_table": block_table, |
| 145 | "metadata": metadata, | 210 | "metadata": metadata, |
| 146 | "quant_mode": quant_mode, | 211 | "quant_mode": quant_mode, |
| @@ -149,7 +214,7 @@ def _qliv2_prepare_tensors_and_metadata(params, tensor_dict): | |||
| 149 | "sparse_count": sparse_count, | 214 | "sparse_count": sparse_count, |
| 150 | "sparse_mode": sparse_mode, | 215 | "sparse_mode": sparse_mode, |
| 151 | "cmp_ratio": cmp_ratio, | 216 | "cmp_ratio": cmp_ratio, |
| 152 | - "return_value": params[30], | 217 | + "return_value": params[31], |
| 153 | } | 218 | } |
| 154 | return run_args | 219 | return run_args |
| 155 | 220 | ||
| @@ -162,10 +227,19 @@ def _qliv2_run_compiled_graph(run_args): | |||
| 162 | config.mode = "reduce-overhead" | 227 | config.mode = "reduce-overhead" |
| 163 | npu_backend = torchair.get_npu_backend(compiler_config=config) | 228 | npu_backend = torchair.get_npu_backend(compiler_config=config) |
| 164 | torch._dynamo.reset() | 229 | torch._dynamo.reset() |
| 165 | - npu_mode = torch.compile(QLIV2Network().npu(), fullgraph=False, backend=npu_backend, dynamic=False) | 230 | + npu_mode = torch.compile( |
| 231 | + QLIV2Network().npu(), fullgraph=False, backend=npu_backend, dynamic=False | ||
| 232 | + ) | ||
| 166 | npu_result, npu_topk_value = npu_mode(**run_args) | 233 | npu_result, npu_topk_value = npu_mode(**run_args) |
| 167 | torch.npu.synchronize() | 234 | torch.npu.synchronize() |
| 168 | - npu_topk_value, _ = npu_topk_value.sort(dim=-1, descending=True) | 235 | + if run_args["return_value"]: |
| 236 | + if npu_topk_value.shape != npu_result.shape: | ||
| 237 | + raise RuntimeError( | ||
| 238 | + "sparse_values and sparse_indices must have the same shape when return_value=1, " | ||
| 239 | + f"but got {tuple(npu_topk_value.shape)} and {tuple(npu_result.shape)}" | ||
| 240 | + ) | ||
| 241 | + npu_topk_value, npu_sort_order = npu_topk_value.sort(dim=-1, descending=True) | ||
| 242 | + npu_result = torch.gather(npu_result, dim=-1, index=npu_sort_order) | ||
| 169 | return npu_result, npu_topk_value | 243 | return npu_result, npu_topk_value |
| 170 | 244 | ||
| 171 | 245 | ||
| @@ -56,13 +56,15 @@ try: | |||
| 56 | ) | 56 | ) |
| 57 | print(f"找到 {len(TESTCASE_FILES)} 个测试用例文件") | 57 | print(f"找到 {len(TESTCASE_FILES)} 个测试用例文件") |
| 58 | except ValueError as error: | 58 | except ValueError as error: |
| 59 | - has_explicit_selection = any(( | 59 | + has_explicit_selection = any( |
| 60 | - TEST_INPUT_PATH_ENV, | 60 | + ( |
| 61 | - SINGLE_CASE_PATH, | 61 | + TEST_INPUT_PATH_ENV, |
| 62 | - PT_FILE_LIST, | 62 | + SINGLE_CASE_PATH, |
| 63 | - CASE_NAMES, | 63 | + PT_FILE_LIST, |
| 64 | - CASE_INDEXES, | 64 | + CASE_NAMES, |
| 65 | - )) | 65 | + CASE_INDEXES, |
| 66 | + ) | ||
| 67 | + ) | ||
| 66 | if has_explicit_selection: | 68 | if has_explicit_selection: |
| 67 | raise | 69 | raise |
| 68 | print(f"未配置 batch PT 用例,跳过收集: {error}") | 70 | print(f"未配置 batch PT 用例,跳过收集: {error}") |
| @@ -72,23 +74,55 @@ except ValueError as error: | |||
| 72 | def qliv2(testcase_file): | 74 | def qliv2(testcase_file): |
| 73 | try: | 75 | try: |
| 74 | if RUN_MODE == "graph": | 76 | if RUN_MODE == "graph": |
| 75 | - cpu_result, npu_result, topk_value, cpu_topk_value, npu_topk_value, output_idx_offset, params = \ | 77 | + ( |
| 76 | - quant_lightning_indexer_v2_pt_loadprocess.test_qliv2_process_graph( | 78 | + cpu_result, |
| 77 | - testcase_file, device_id=DEVICE_ID | 79 | + npu_result, |
| 78 | - ) | 80 | + topk_value, |
| 81 | + cpu_topk_value, | ||
| 82 | + npu_topk_value, | ||
| 83 | + output_idx_offset, | ||
| 84 | + params, | ||
| 85 | + ) = quant_lightning_indexer_v2_pt_loadprocess.test_qliv2_process_graph( | ||
| 86 | + testcase_file, device_id=DEVICE_ID | ||
| 87 | + ) | ||
| 79 | else: | 88 | else: |
| 80 | - cpu_result, npu_result, topk_value, cpu_topk_value, npu_topk_value, output_idx_offset, params = \ | 89 | + ( |
| 81 | - quant_lightning_indexer_v2_pt_loadprocess.test_qliv2_process( | 90 | + cpu_result, |
| 82 | - testcase_file, device_id=DEVICE_ID | 91 | + npu_result, |
| 83 | - ) | 92 | + topk_value, |
| 93 | + cpu_topk_value, | ||
| 94 | + npu_topk_value, | ||
| 95 | + output_idx_offset, | ||
| 96 | + params, | ||
| 97 | + ) = quant_lightning_indexer_v2_pt_loadprocess.test_qliv2_process( | ||
| 98 | + testcase_file, device_id=DEVICE_ID | ||
| 99 | + ) | ||
| 84 | if npu_result is not None: | 100 | if npu_result is not None: |
| 85 | - result, fulfill_percent = result_compare_method.check_result(cpu_result, npu_result, topk_value, output_idx_offset, params, cpu_topk_value, npu_topk_value) | 101 | + result, fulfill_percent = result_compare_method.check_result( |
| 102 | + cpu_result, | ||
| 103 | + npu_result, | ||
| 104 | + topk_value, | ||
| 105 | + output_idx_offset, | ||
| 106 | + params, | ||
| 107 | + cpu_topk_value, | ||
| 108 | + npu_topk_value, | ||
| 109 | + ) | ||
| 86 | else: | 110 | else: |
| 87 | result = "Failed" | 111 | result = "Failed" |
| 88 | fulfill_percent = 0 | 112 | fulfill_percent = 0 |
| 89 | - return_value = params[30] | 113 | + return_value = params[31] |
| 90 | if return_value: | 114 | if return_value: |
| 91 | - result_return_value, fulfill_precent_return_value = result_compare_method.check_result_return_value(cpu_topk_value, npu_topk_value, params) | 115 | + result_return_value, fulfill_precent_return_value = ( |
| 116 | + result_compare_method.check_result_return_value( | ||
| 117 | + cpu_topk_value, | ||
| 118 | + npu_topk_value, | ||
| 119 | + params, | ||
| 120 | + cpu_result, | ||
| 121 | + npu_result, | ||
| 122 | + topk_value, | ||
| 123 | + output_idx_offset, | ||
| 124 | + ) | ||
| 125 | + ) | ||
| 92 | print(f"result_return_value: {result_return_value}") | 126 | print(f"result_return_value: {result_return_value}") |
| 93 | print(f"fulfill_precent_return_value: {fulfill_precent_return_value}") | 127 | print(f"fulfill_precent_return_value: {fulfill_precent_return_value}") |
| 94 | else: | 128 | else: |
| @@ -100,7 +134,7 @@ def qliv2(testcase_file): | |||
| 100 | fulfill_percent = 0 | 134 | fulfill_percent = 0 |
| 101 | result_return_value = "N/A" | 135 | result_return_value = "N/A" |
| 102 | fulfill_precent_return_value = 0 | 136 | fulfill_precent_return_value = 0 |
| 103 | - params = [None] * 32 | 137 | + params = [None] * 33 |
| 104 | 138 | ||
| 105 | row_data = QliV2ResultWriter.row( | 139 | row_data = QliV2ResultWriter.row( |
| 106 | Path(testcase_file).stem, | 140 | Path(testcase_file).stem, |
| @@ -116,6 +150,7 @@ def qliv2(testcase_file): | |||
| 116 | return f"用例执行失败:{Path(testcase_file).stem}" | 150 | return f"用例执行失败:{Path(testcase_file).stem}" |
| 117 | return None | 151 | return None |
| 118 | 152 | ||
| 153 | + | ||
| 119 | @pytest.mark.ci | 154 | @pytest.mark.ci |
| 120 | @pytest.mark.parametrize("testcase_file", TESTCASE_FILES) | 155 | @pytest.mark.parametrize("testcase_file", TESTCASE_FILES) |
| 121 | def test_qliv2(testcase_file): | 156 | def test_qliv2(testcase_file): |
Mattention/quant_lightning_indexer_v2/tests/pytest/test_quant_lightning_indexer_v2_paramset.py+429-357
| @@ -28,17 +28,50 @@ SAVE_PT_DIR = os.environ.get("QLIV2_SINGLE_SAVE_PT_DIR", "").strip() | |||
| 28 | RESULT_PATH = os.environ.get("QLIV2_SINGLE_RESULT_PATH", "").strip() | 28 | RESULT_PATH = os.environ.get("QLIV2_SINGLE_RESULT_PATH", "").strip() |
| 29 | 29 | ||
| 30 | param_names = [ | 30 | param_names = [ |
| 31 | - "batch_size", "q_seq", "k_seq", "q_t_size", "k_t_size", "q_head_num", "k_head_num","head_dim", | 31 | + "batch_size", |
| 32 | - "block_size", "block_num", "qk_dtype", "dequant_dtype", "actual_seq_dtype", "cu_seqlens_q", | 32 | + "q_seq", |
| 33 | - "cu_seqlens_k", "seqused_q", "seqused_k", "cmp_residual_k", "max_seqlen_q", "quant_mode", | 33 | + "k_seq", |
| 34 | - "layout_query", "layout_key", "sparse_count", "sparse_mode", "query_datarange", "key_datarange", | 34 | + "q_t_size", |
| 35 | - "weights_datarange", "q_scale_datarange", "k_scale_datarange", "cmp_ratio", "return_value", | 35 | + "k_t_size", |
| 36 | - "output_idx_offset", "run_mode" | 36 | + "q_head_num", |
| 37 | + "k_head_num", | ||
| 38 | + "head_dim", | ||
| 39 | + "block_size", | ||
| 40 | + "block_num", | ||
| 41 | + "qk_dtype", | ||
| 42 | + "weight_dtype", | ||
| 43 | + "dequant_dtype", | ||
| 44 | + "actual_seq_dtype", | ||
| 45 | + "cu_seqlens_q", | ||
| 46 | + "cu_seqlens_k", | ||
| 47 | + "seqused_q", | ||
| 48 | + "seqused_k", | ||
| 49 | + "cmp_residual_k", | ||
| 50 | + "max_seqlen_q", | ||
| 51 | + "quant_mode", | ||
| 52 | + "layout_query", | ||
| 53 | + "layout_key", | ||
| 54 | + "sparse_count", | ||
| 55 | + "sparse_mode", | ||
| 56 | + "query_datarange", | ||
| 57 | + "key_datarange", | ||
| 58 | + "weights_datarange", | ||
| 59 | + "q_scale_datarange", | ||
| 60 | + "k_scale_datarange", | ||
| 61 | + "cmp_ratio", | ||
| 62 | + "return_value", | ||
| 63 | + "output_idx_offset", | ||
| 64 | + "run_mode", | ||
| 37 | ] | 65 | ] |
| 38 | 66 | ||
| 39 | param_combinations = [] | 67 | param_combinations = [] |
| 40 | for paramset_name, params in ENABLED_PARAMSETS: | 68 | for paramset_name, params in ENABLED_PARAMSETS: |
| 41 | - param_values = [params.get(name, ["eager"]) for name in param_names] | 69 | + param_values = [ |
| 70 | + params.get( | ||
| 71 | + name, params["dequant_dtype"] if name == "weight_dtype" else ["eager"] | ||
| 72 | + ) | ||
| 73 | + for name in param_names | ||
| 74 | + ] | ||
| 42 | combinations = list(itertools.product(*param_values)) | 75 | combinations = list(itertools.product(*param_values)) |
| 43 | for combo_index, combo in enumerate(combinations, start=1): | 76 | for combo_index, combo in enumerate(combinations, start=1): |
| 44 | param_dict = dict(zip(param_names, combo)) | 77 | param_dict = dict(zip(param_names, combo)) |
| @@ -52,88 +85,158 @@ for paramset_name, params in ENABLED_PARAMSETS: | |||
| 52 | 85 | ||
| 53 | @pytest.mark.ci | 86 | @pytest.mark.ci |
| 54 | @pytest.mark.parametrize("param_combinations", param_combinations) | 87 | @pytest.mark.parametrize("param_combinations", param_combinations) |
| 55 | -def test_qliv2(param_combinations): # Init params and tensors | 88 | +def test_qliv2(param_combinations): # Init params and tensors |
| 56 | - batch_size = param_combinations['batch_size'] | 89 | + batch_size = param_combinations["batch_size"] |
| 57 | - q_seq = param_combinations['q_seq'] | 90 | + q_seq = param_combinations["q_seq"] |
| 58 | - k_seq = param_combinations['k_seq'] | 91 | + k_seq = param_combinations["k_seq"] |
| 59 | - q_t_size = param_combinations['q_t_size'] | 92 | + q_t_size = param_combinations["q_t_size"] |
| 60 | - k_t_size = param_combinations['k_t_size'] | 93 | + k_t_size = param_combinations["k_t_size"] |
| 61 | - q_head_num = param_combinations['q_head_num'] | 94 | + q_head_num = param_combinations["q_head_num"] |
| 62 | - k_head_num = param_combinations['k_head_num'] | 95 | + k_head_num = param_combinations["k_head_num"] |
| 63 | - head_dim = param_combinations['head_dim'] | 96 | + head_dim = param_combinations["head_dim"] |
| 64 | - block_size = param_combinations['block_size'] | 97 | + block_size = param_combinations["block_size"] |
| 65 | - block_num = param_combinations['block_num'] | 98 | + block_num = param_combinations["block_num"] |
| 66 | - qk_dtype= param_combinations['qk_dtype'] | 99 | + qk_dtype = param_combinations["qk_dtype"] |
| 67 | - dequant_dtype = param_combinations['dequant_dtype'] | 100 | + weight_dtype = param_combinations["weight_dtype"] |
| 68 | - actual_seq_dtype = param_combinations['actual_seq_dtype'] | 101 | + dequant_dtype = param_combinations["dequant_dtype"] |
| 69 | - cu_seqlens_q = param_combinations['cu_seqlens_q'] | 102 | + actual_seq_dtype = param_combinations["actual_seq_dtype"] |
| 70 | - cu_seqlens_k = param_combinations['cu_seqlens_k'] | 103 | + cu_seqlens_q = param_combinations["cu_seqlens_q"] |
| 71 | - seqused_q = param_combinations['seqused_q'] | 104 | + cu_seqlens_k = param_combinations["cu_seqlens_k"] |
| 72 | - seqused_k = param_combinations['seqused_k'] | 105 | + seqused_q = param_combinations["seqused_q"] |
| 73 | - cmp_residual_k = param_combinations['cmp_residual_k'] | 106 | + seqused_k = param_combinations["seqused_k"] |
| 74 | - max_seqlen_q = param_combinations['max_seqlen_q'] | 107 | + cmp_residual_k = param_combinations["cmp_residual_k"] |
| 75 | - quant_mode = param_combinations['quant_mode'] | 108 | + max_seqlen_q = param_combinations["max_seqlen_q"] |
| 76 | - layout_query = param_combinations['layout_query'] | 109 | + quant_mode = param_combinations["quant_mode"] |
| 77 | - layout_key = param_combinations['layout_key'] | 110 | + layout_query = param_combinations["layout_query"] |
| 78 | - sparse_count = param_combinations['sparse_count'] | 111 | + layout_key = param_combinations["layout_key"] |
| 79 | - sparse_mode = param_combinations['sparse_mode'] | 112 | + sparse_count = param_combinations["sparse_count"] |
| 80 | - query_datarange = param_combinations['query_datarange'] | 113 | + sparse_mode = param_combinations["sparse_mode"] |
| 81 | - key_datarange = param_combinations['key_datarange'] | 114 | + query_datarange = param_combinations["query_datarange"] |
| 82 | - weights_datarange = param_combinations['weights_datarange'] | 115 | + key_datarange = param_combinations["key_datarange"] |
| 83 | - q_scale_datarange = param_combinations['q_scale_datarange'] | 116 | + weights_datarange = param_combinations["weights_datarange"] |
| 84 | - k_scale_datarange = param_combinations['k_scale_datarange'] | 117 | + q_scale_datarange = param_combinations["q_scale_datarange"] |
| 85 | - cmp_ratio = param_combinations['cmp_ratio'] | 118 | + k_scale_datarange = param_combinations["k_scale_datarange"] |
| 86 | - return_value = param_combinations['return_value'] | 119 | + cmp_ratio = param_combinations["cmp_ratio"] |
| 87 | - output_idx_offset = param_combinations['output_idx_offset'] | 120 | + return_value = param_combinations["return_value"] |
| 88 | - run_mode = os.environ.get("QLIV2_RUN_MODE", param_combinations['run_mode']).strip().lower() | 121 | + output_idx_offset = param_combinations["output_idx_offset"] |
| 122 | + run_mode = ( | ||
| 123 | + os.environ.get("QLIV2_RUN_MODE", param_combinations["run_mode"]).strip().lower() | ||
| 124 | + ) | ||
| 89 | torch_npu.npu.set_device(0) | 125 | torch_npu.npu.set_device(0) |
| 90 | - test_data = batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size,\ | 126 | + test_data = ( |
| 91 | - block_num, qk_dtype, dequant_dtype, actual_seq_dtype, cu_seqlens_q, cu_seqlens_k, seqused_q,\ | 127 | + batch_size, |
| 92 | - seqused_k, cmp_residual_k, max_seqlen_q, quant_mode, layout_query, layout_key, sparse_count,\ | 128 | + q_seq, |
| 93 | - sparse_mode, query_datarange, key_datarange, weights_datarange, q_scale_datarange,\ | 129 | + k_seq, |
| 94 | - k_scale_datarange, cmp_ratio, return_value, output_idx_offset | 130 | + q_t_size, |
| 131 | + k_t_size, | ||
| 132 | + q_head_num, | ||
| 133 | + k_head_num, | ||
| 134 | + head_dim, | ||
| 135 | + block_size, | ||
| 136 | + block_num, | ||
| 137 | + qk_dtype, | ||
| 138 | + weight_dtype, | ||
| 139 | + dequant_dtype, | ||
| 140 | + actual_seq_dtype, | ||
| 141 | + cu_seqlens_q, | ||
| 142 | + cu_seqlens_k, | ||
| 143 | + seqused_q, | ||
| 144 | + seqused_k, | ||
| 145 | + cmp_residual_k, | ||
| 146 | + max_seqlen_q, | ||
| 147 | + quant_mode, | ||
| 148 | + layout_query, | ||
| 149 | + layout_key, | ||
| 150 | + sparse_count, | ||
| 151 | + sparse_mode, | ||
| 152 | + query_datarange, | ||
| 153 | + key_datarange, | ||
| 154 | + weights_datarange, | ||
| 155 | + q_scale_datarange, | ||
| 156 | + k_scale_datarange, | ||
| 157 | + cmp_ratio, | ||
| 158 | + return_value, | ||
| 159 | + output_idx_offset, | ||
| 160 | + ) | ||
| 95 | 161 | ||
| 96 | case_name = QliV2ResultWriter.case_name( | 162 | case_name = QliV2ResultWriter.case_name( |
| 97 | test_data, | 163 | test_data, |
| 98 | explicit_name=param_combinations["case_name"], | 164 | explicit_name=param_combinations["case_name"], |
| 99 | ) | 165 | ) |
| 100 | if SAVE_PT_DIR: | 166 | if SAVE_PT_DIR: |
| 101 | - case_data = quant_lightning_indexer_v2_golden.generate_qliv2_test_data(test_data) | 167 | + case_data = quant_lightning_indexer_v2_golden.generate_qliv2_test_data( |
| 168 | + test_data | ||
| 169 | + ) | ||
| 102 | case_path = Path(SAVE_PT_DIR) / f"{case_name}.pt" | 170 | case_path = Path(SAVE_PT_DIR) / f"{case_name}.pt" |
| 103 | case_path.parent.mkdir(parents=True, exist_ok=True) | 171 | case_path.parent.mkdir(parents=True, exist_ok=True) |
| 104 | torch.save(case_data, case_path) | 172 | torch.save(case_data, case_path) |
| 105 | print(f"当前用例 PT 已保存: {case_path}") | 173 | print(f"当前用例 PT 已保存: {case_path}") |
| 106 | if run_mode == "eager": | 174 | if run_mode == "eager": |
| 107 | - cpu_result, npu_result, topk_value, cpu_topk_value, npu_topk_value, \ | 175 | + ( |
| 108 | - output_idx_offset, _ = quant_lightning_indexer_v2_pt_loadprocess.test_qliv2_process( | 176 | + cpu_result, |
| 109 | - case_path, device_id=0 | 177 | + npu_result, |
| 110 | - ) | 178 | + topk_value, |
| 179 | + cpu_topk_value, | ||
| 180 | + npu_topk_value, | ||
| 181 | + output_idx_offset, | ||
| 182 | + _, | ||
| 183 | + ) = quant_lightning_indexer_v2_pt_loadprocess.test_qliv2_process( | ||
| 184 | + case_path, device_id=0 | ||
| 185 | + ) | ||
| 111 | elif run_mode == "graph": | 186 | elif run_mode == "graph": |
| 112 | - cpu_result, npu_result, topk_value, cpu_topk_value, npu_topk_value, \ | 187 | + ( |
| 113 | - output_idx_offset, _ = quant_lightning_indexer_v2_pt_loadprocess.test_qliv2_process_graph( | 188 | + cpu_result, |
| 114 | - case_path, device_id=0 | 189 | + npu_result, |
| 115 | - ) | 190 | + topk_value, |
| 191 | + cpu_topk_value, | ||
| 192 | + npu_topk_value, | ||
| 193 | + output_idx_offset, | ||
| 194 | + _, | ||
| 195 | + ) = quant_lightning_indexer_v2_pt_loadprocess.test_qliv2_process_graph( | ||
| 196 | + case_path, device_id=0 | ||
| 197 | + ) | ||
| 116 | else: | 198 | else: |
| 117 | raise ValueError(f"unsupported run_mode: {run_mode}") | 199 | raise ValueError(f"unsupported run_mode: {run_mode}") |
| 118 | elif run_mode == "eager": | 200 | elif run_mode == "eager": |
| 119 | - cpu_result, npu_result, topk_value, cpu_topk_value, npu_topk_value = \ | 201 | + cpu_result, npu_result, topk_value, cpu_topk_value, npu_topk_value = ( |
| 120 | quant_lightning_indexer_v2_golden.qliv2_output_single(test_data) | 202 | quant_lightning_indexer_v2_golden.qliv2_output_single(test_data) |
| 203 | + ) | ||
| 121 | elif run_mode == "graph": | 204 | elif run_mode == "graph": |
| 122 | import quant_lightning_indexer_v2_acl_graph | 205 | import quant_lightning_indexer_v2_acl_graph |
| 123 | - cpu_result, npu_result, topk_value, cpu_topk_value, npu_topk_value = \ | 206 | + |
| 207 | + cpu_result, npu_result, topk_value, cpu_topk_value, npu_topk_value = ( | ||
| 124 | quant_lightning_indexer_v2_acl_graph.qliv2_output_acl_graph(test_data) | 208 | quant_lightning_indexer_v2_acl_graph.qliv2_output_acl_graph(test_data) |
| 209 | + ) | ||
| 125 | else: | 210 | else: |
| 126 | raise ValueError(f"unsupported run_mode: {run_mode}") | 211 | raise ValueError(f"unsupported run_mode: {run_mode}") |
| 127 | # print("npu_result", npu_result) | 212 | # print("npu_result", npu_result) |
| 128 | # print("cpu_result:", cpu_result) | 213 | # print("cpu_result:", cpu_result) |
| 129 | # Compare result accuracy | 214 | # Compare result accuracy |
| 130 | - result, fulfill_percent = result_compare_method.check_result(cpu_result, npu_result, topk_value, output_idx_offset, test_data, cpu_topk_value, npu_topk_value) | 215 | + result, fulfill_percent = result_compare_method.check_result( |
| 216 | + cpu_result, | ||
| 217 | + npu_result, | ||
| 218 | + topk_value, | ||
| 219 | + output_idx_offset, | ||
| 220 | + test_data, | ||
| 221 | + cpu_topk_value, | ||
| 222 | + npu_topk_value, | ||
| 223 | + ) | ||
| 131 | print("result", result) | 224 | print("result", result) |
| 132 | print("result", fulfill_percent) | 225 | print("result", fulfill_percent) |
| 133 | result_return_value = "N/A" | 226 | result_return_value = "N/A" |
| 134 | fulfill_precent_return_value = 0 | 227 | fulfill_precent_return_value = 0 |
| 135 | if return_value: | 228 | if return_value: |
| 136 | - result_return_value, fulfill_precent_return_value = result_compare_method.check_result_return_value(cpu_topk_value, npu_topk_value, test_data) | 229 | + result_return_value, fulfill_precent_return_value = ( |
| 230 | + result_compare_method.check_result_return_value( | ||
| 231 | + cpu_topk_value, | ||
| 232 | + npu_topk_value, | ||
| 233 | + test_data, | ||
| 234 | + cpu_result, | ||
| 235 | + npu_result, | ||
| 236 | + topk_value, | ||
| 237 | + output_idx_offset, | ||
| 238 | + ) | ||
| 239 | + ) | ||
| 137 | print(f"result_return_value: {result_return_value}") | 240 | print(f"result_return_value: {result_return_value}") |
| 138 | print(f"result_return_value: {fulfill_precent_return_value}") | 241 | print(f"result_return_value: {fulfill_precent_return_value}") |
| 139 | 242 | ||
| @@ -100,7 +100,7 @@ | |||
| 100 | <tr> | 100 | <tr> |
| 101 | <td>quant_mode</td> | 101 | <td>quant_mode</td> |
| 102 | <td>属性</td> | 102 | <td>属性</td> |
| 103 | - <td>表示量化模式,当前仅支持1/2/4。1表示qk: fp8(e4m3) per-token-head, scale: fp32;2表示qk: int8 per-token-head, scale: fp16, w: fp16;4表示qk: hif8 per-tensor, scale: fp32。</td> | 103 | + <td>表示量化模式,当前支持1/2/3/4/5。1表示qk: fp8(e4m3) per-token-head, scale: fp32;2表示qk: int8 per-token-head, scale: fp16, w: fp16;3表示qk: mxfp8(e4m3), scale: fp8(e8m0);4表示qk: hif8 per-tensor, scale: fp32;5表示qk: mxfp4(e2m1), scale: fp8(e8m0)。</td> |
| 104 | <td>INT32</td> | 104 | <td>INT32</td> |
| 105 | <td>-</td> | 105 | <td>-</td> |
| 106 | </tr> | 106 | </tr> |
| @@ -163,7 +163,7 @@ | |||
| 163 | </tbody> | 163 | </tbody> |
| 164 | </table> | 164 | </table> |
| 165 | 165 | ||
| 166 | - <ul><li><term>Ascend 950PR/Ascend 950DT</term> :不支持quant_mode = 2。</li><li><term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term> :不支持num_heads_q = 32,不支持quant_mode = 1/4,不支持layout_k = BSND/TND,不支持cmp_ratio在[1,128]任意取值,仅支持cmp_ratio = 1/2/4/8/16/32/64/128。</li><li><term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term> :不支持num_heads_q = 32,不支持quant_mode = 1/4,不支持layout_k = BSND/TND,不支持cmp_ratio在[1,128]任意取值,仅支持cmp_ratio = 1/2/4/8/16/32/64/128。</li></ul> | 166 | + <ul><li><term>Ascend 950PR/Ascend 950DT</term> :不支持quant_mode = 2。</li><li><term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term> :不支持num_heads_q = 32,不支持quant_mode = 1/3/4/5,不支持layout_k = BSND/TND,不支持cmp_ratio在[1,128]任意取值,仅支持cmp_ratio = 1/2/4/8/16/32/64/128。</li><li><term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term> :不支持num_heads_q = 32,不支持quant_mode = 1/3/4/5,不支持layout_k = BSND/TND,不支持cmp_ratio在[1,128]任意取值,仅支持cmp_ratio = 1/2/4/8/16/32/64/128。</li></ul> |
| 167 | 167 | ||
| 168 | ## 约束说明 | 168 | ## 约束说明 |
| 169 | 169 | ||
Mattention/quant_lightning_indexer_v2_metadata/op_host/quant_lightning_indexer_v2_metadata_check.h+100-83
| @@ -27,7 +27,9 @@ namespace { | |||
| 27 | 27 | ||
| 28 | inline constexpr int64_t QLI_V2_QUANT_MODE_1 = 1; | 28 | inline constexpr int64_t QLI_V2_QUANT_MODE_1 = 1; |
| 29 | inline constexpr int64_t QLI_V2_QUANT_MODE_2 = 2; | 29 | inline constexpr int64_t QLI_V2_QUANT_MODE_2 = 2; |
| 30 | +inline constexpr int64_t QLI_V2_QUANT_MODE_3 = 3; | ||
| 30 | inline constexpr int64_t QLI_V2_QUANT_MODE_4 = 4; | 31 | inline constexpr int64_t QLI_V2_QUANT_MODE_4 = 4; |
| 32 | +inline constexpr int64_t QLI_V2_QUANT_MODE_5 = 5; | ||
| 31 | inline constexpr int64_t QLI_V2_NO_MASK_MODE = 0; | 33 | inline constexpr int64_t QLI_V2_NO_MASK_MODE = 0; |
| 32 | inline constexpr int64_t QLI_V2_CAUSAL_MASK_MODE = 3; | 34 | inline constexpr int64_t QLI_V2_CAUSAL_MASK_MODE = 3; |
| 33 | inline constexpr int64_t QLI_V2_CMP_RATIO_LOWER_BOUND = 1; | 35 | inline constexpr int64_t QLI_V2_CMP_RATIO_LOWER_BOUND = 1; |
| @@ -62,7 +64,7 @@ aclDataType GetDataTypeQliV2(const aclTensor *tensor) | |||
| 62 | } | 64 | } |
| 63 | 65 | ||
| 64 | int64_t GetQueryBatchSizeQliV2(int64_t batchSize, const aclTensor *cuSeqlensQOptional, | 66 | int64_t GetQueryBatchSizeQliV2(int64_t batchSize, const aclTensor *cuSeqlensQOptional, |
| 65 | - const aclTensor *sequsedQOptional, const char *layoutQOptional) | 67 | + const aclTensor *sequsedQOptional, const char *layoutQOptional) |
| 66 | { | 68 | { |
| 67 | // 1. 如果sequsedQOptional 传了,使用sequsedQOptional获取BatchSize | 69 | // 1. 如果sequsedQOptional 传了,使用sequsedQOptional获取BatchSize |
| 68 | if (IsTensorExistQliV2(sequsedQOptional)) { | 70 | if (IsTensorExistQliV2(sequsedQOptional)) { |
| @@ -70,7 +72,8 @@ int64_t GetQueryBatchSizeQliV2(int64_t batchSize, const aclTensor *cuSeqlensQOpt | |||
| 70 | } | 72 | } |
| 71 | // 2. 如果sequsedQOptional 没传,使用cuSeqlensQOptional获取BatchSize | 73 | // 2. 如果sequsedQOptional 没传,使用cuSeqlensQOptional获取BatchSize |
| 72 | if (strcmp(layoutQOptional, "TND") == 0) { | 74 | if (strcmp(layoutQOptional, "TND") == 0) { |
| 73 | - if (IsTensorExistQliV2(cuSeqlensQOptional)) { // 前序校验已保证layout_q = TND时,cu_seqlens_q必须传入,此通路必达 | 75 | + if (IsTensorExistQliV2( |
| 76 | + cuSeqlensQOptional)) { // 前序校验已保证layout_q = TND时,cu_seqlens_q必须传入,此通路必达 | ||
| 74 | return cuSeqlensQOptional->GetViewShape().GetDim(0) - 1; | 77 | return cuSeqlensQOptional->GetViewShape().GetDim(0) - 1; |
| 75 | } | 78 | } |
| 76 | } | 79 | } |
| @@ -79,7 +82,7 @@ int64_t GetQueryBatchSizeQliV2(int64_t batchSize, const aclTensor *cuSeqlensQOpt | |||
| 79 | } | 82 | } |
| 80 | 83 | ||
| 81 | int64_t GetKeyBatchSizeQliV2(int64_t batchSize, const aclTensor *cuSeqlensKOptional, const aclTensor *sequsedKOptional, | 84 | int64_t GetKeyBatchSizeQliV2(int64_t batchSize, const aclTensor *cuSeqlensKOptional, const aclTensor *sequsedKOptional, |
| 82 | - const char *layoutKOptional) | 85 | + const char *layoutKOptional) |
| 83 | { | 86 | { |
| 84 | // 1. 如果sequsedKOptional 传了,使用sequsedKOptional获取BatchSize | 87 | // 1. 如果sequsedKOptional 传了,使用sequsedKOptional获取BatchSize |
| 85 | if (IsTensorExistQliV2(sequsedKOptional)) { | 88 | if (IsTensorExistQliV2(sequsedKOptional)) { |
| @@ -87,7 +90,8 @@ int64_t GetKeyBatchSizeQliV2(int64_t batchSize, const aclTensor *cuSeqlensKOptio | |||
| 87 | } | 90 | } |
| 88 | // 如果是 TND,必须使用 cuSeqlensKOptional获取BatchSize | 91 | // 如果是 TND,必须使用 cuSeqlensKOptional获取BatchSize |
| 89 | if (strcmp(layoutKOptional, "TND") == 0) { | 92 | if (strcmp(layoutKOptional, "TND") == 0) { |
| 90 | - if (IsTensorExistQliV2(cuSeqlensKOptional)) { // 前序校验已保证layout_k = TND时,cu_seqlens_k必须传入,此通路必达 | 93 | + if (IsTensorExistQliV2( |
| 94 | + cuSeqlensKOptional)) { // 前序校验已保证layout_k = TND时,cu_seqlens_k必须传入,此通路必达 | ||
| 91 | return cuSeqlensKOptional->GetViewShape().GetDim(0) - 1; | 95 | return cuSeqlensKOptional->GetViewShape().GetDim(0) - 1; |
| 92 | } | 96 | } |
| 93 | } | 97 | } |
| @@ -96,130 +100,136 @@ int64_t GetKeyBatchSizeQliV2(int64_t batchSize, const aclTensor *cuSeqlensKOptio | |||
| 96 | } | 100 | } |
| 97 | 101 | ||
| 98 | aclnnStatus CheckSingleParamQliV2(int64_t numHeadsQ, int64_t numHeadsK, int64_t topk, int64_t quantMode, | 102 | aclnnStatus CheckSingleParamQliV2(int64_t numHeadsQ, int64_t numHeadsK, int64_t topk, int64_t quantMode, |
| 99 | - int64_t batchSize, int64_t maxSeqlenQ, int64_t maxSeqlenK, const char *layoutQOptional, const char *layoutKOptional, | 103 | + int64_t batchSize, int64_t maxSeqlenQ, int64_t maxSeqlenK, |
| 100 | - int64_t maskMode, int64_t cmpRatio, uint32_t aicCoreNum, uint32_t aivCoreNum, const std::string &socVersion) | 104 | + const char *layoutQOptional, const char *layoutKOptional, int64_t maskMode, |
| 105 | + int64_t cmpRatio, uint32_t aicCoreNum, uint32_t aivCoreNum, | ||
| 106 | + const std::string &socVersion) | ||
| 101 | { | 107 | { |
| 102 | // num_heads_k 校验 | 108 | // num_heads_k 校验 |
| 103 | - CHECK_COND(numHeadsK == 1, ACLNN_ERR_PARAM_INVALID, | 109 | + CHECK_COND(numHeadsK == 1, ACLNN_ERR_PARAM_INVALID, "num_heads_kv should only be 1, but got %lld", numHeadsK); |
| 104 | - "num_heads_kv should only be 1, but got %lld", numHeadsK); | ||
| 105 | // batch_size 非负校验 | 110 | // batch_size 非负校验 |
| 106 | - CHECK_COND(batchSize >= 0, ACLNN_ERR_PARAM_INVALID, | 111 | + CHECK_COND(batchSize >= 0, ACLNN_ERR_PARAM_INVALID, "batch_size should not be negative, but got %lld", batchSize); |
| 107 | - "batch_size should not be negative, but got %lld", batchSize); | ||
| 108 | // max_seqlen_q 校验 | 112 | // max_seqlen_q 校验 |
| 109 | - CHECK_COND(maxSeqlenQ >= -1, ACLNN_ERR_PARAM_INVALID, | 113 | + CHECK_COND(maxSeqlenQ >= -1, ACLNN_ERR_PARAM_INVALID, "max_seqlen_q should be >= -1, but got %lld", maxSeqlenQ); |
| 110 | - "max_seqlen_q should be >= -1, but got %lld", maxSeqlenQ); | ||
| 111 | // max_seqlen_k 校验 | 114 | // max_seqlen_k 校验 |
| 112 | - CHECK_COND(maxSeqlenK >= -1, ACLNN_ERR_PARAM_INVALID, | 115 | + CHECK_COND(maxSeqlenK >= -1, ACLNN_ERR_PARAM_INVALID, "max_seqlen_k should be >= -1, but got %lld", maxSeqlenK); |
| 113 | - "max_seqlen_k should be >= -1, but got %lld", maxSeqlenK); | ||
| 114 | // mask_mode 校验 | 116 | // mask_mode 校验 |
| 115 | - CHECK_COND((maskMode == QLI_V2_NO_MASK_MODE) || (maskMode == QLI_V2_CAUSAL_MASK_MODE), | 117 | + CHECK_COND((maskMode == QLI_V2_NO_MASK_MODE) || (maskMode == QLI_V2_CAUSAL_MASK_MODE), ACLNN_ERR_PARAM_INVALID, |
| 116 | - ACLNN_ERR_PARAM_INVALID, | 118 | + "mask_mode should be %lld/%lld, but got %lld", QLI_V2_NO_MASK_MODE, QLI_V2_CAUSAL_MASK_MODE, maskMode); |
| 117 | - "mask_mode should be %lld/%lld, but got %lld", QLI_V2_NO_MASK_MODE, QLI_V2_CAUSAL_MASK_MODE, maskMode); | ||
| 118 | // layout_q 校验 | 119 | // layout_q 校验 |
| 119 | CHECK_COND((layoutQOptional != nullptr), ACLNN_ERR_PARAM_INVALID, "layout_q is null!"); | 120 | CHECK_COND((layoutQOptional != nullptr), ACLNN_ERR_PARAM_INVALID, "layout_q is null!"); |
| 120 | CHECK_COND((strcmp(layoutQOptional, "TND") == 0) || (strcmp(layoutQOptional, "BSND") == 0), ACLNN_ERR_PARAM_INVALID, | 121 | CHECK_COND((strcmp(layoutQOptional, "TND") == 0) || (strcmp(layoutQOptional, "BSND") == 0), ACLNN_ERR_PARAM_INVALID, |
| 121 | - "layout_q must be TND or BSND, but got %s", layoutQOptional); | 122 | + "layout_q must be TND or BSND, but got %s", layoutQOptional); |
| 122 | // layout_k 校验 | 123 | // layout_k 校验 |
| 123 | CHECK_COND((layoutKOptional != nullptr), ACLNN_ERR_PARAM_INVALID, "layout_k is null!"); | 124 | CHECK_COND((layoutKOptional != nullptr), ACLNN_ERR_PARAM_INVALID, "layout_k is null!"); |
| 124 | if ((strcmp(layoutKOptional, "PA_BBND") != 0)) { | 125 | if ((strcmp(layoutKOptional, "PA_BBND") != 0)) { |
| 125 | CHECK_COND((strcmp(layoutQOptional, layoutKOptional) == 0), ACLNN_ERR_PARAM_INVALID, | 126 | CHECK_COND((strcmp(layoutQOptional, layoutKOptional) == 0), ACLNN_ERR_PARAM_INVALID, |
| 126 | - "For layout_k != PA_BBND, layout_q and layout_k must be the same!"); | 127 | + "For layout_k != PA_BBND, layout_q and layout_k must be the same!"); |
| 127 | } | 128 | } |
| 128 | // 校验 A2/A3 参数 | 129 | // 校验 A2/A3 参数 |
| 129 | if (socVersion.find("Ascend950") == std::string::npos) { | 130 | if (socVersion.find("Ascend950") == std::string::npos) { |
| 130 | // num_heads_q 校验 | 131 | // num_heads_q 校验 |
| 131 | CHECK_COND(numHeadsQ == QLI_V2_NUM_HEADS_Q_UPPER_BOUND, ACLNN_ERR_PARAM_INVALID, | 132 | CHECK_COND(numHeadsQ == QLI_V2_NUM_HEADS_Q_UPPER_BOUND, ACLNN_ERR_PARAM_INVALID, |
| 132 | - "For Atlas A2/A3, num_heads_q should be %lld, but got %lld", QLI_V2_NUM_HEADS_Q_UPPER_BOUND, numHeadsQ); | 133 | + "For Atlas A2/A3, num_heads_q should be %lld, but got %lld", QLI_V2_NUM_HEADS_Q_UPPER_BOUND, |
| 134 | + numHeadsQ); | ||
| 133 | // topk 校验 | 135 | // topk 校验 |
| 134 | CHECK_COND(topk >= QLI_V2_TOPK_LOWER_BOUND && topk <= QLI_V2_A3_TOPK_UPPER_BOUND, ACLNN_ERR_PARAM_INVALID, | 136 | CHECK_COND(topk >= QLI_V2_TOPK_LOWER_BOUND && topk <= QLI_V2_A3_TOPK_UPPER_BOUND, ACLNN_ERR_PARAM_INVALID, |
| 135 | - "For Atlas A2/A3, topk should be [%lld, %lld], but got %lld", | 137 | + "For Atlas A2/A3, topk should be [%lld, %lld], but got %lld", QLI_V2_TOPK_LOWER_BOUND, |
| 136 | - QLI_V2_TOPK_LOWER_BOUND, QLI_V2_A3_TOPK_UPPER_BOUND, topk); | 138 | + QLI_V2_A3_TOPK_UPPER_BOUND, topk); |
| 137 | // quant_mode 校验 | 139 | // quant_mode 校验 |
| 138 | CHECK_COND(quantMode == QLI_V2_QUANT_MODE_2, ACLNN_ERR_PARAM_INVALID, | 140 | CHECK_COND(quantMode == QLI_V2_QUANT_MODE_2, ACLNN_ERR_PARAM_INVALID, |
| 139 | - "For Atlas A2/A3, quant_mode should be 2, but got %lld", quantMode); | 141 | + "For Atlas A2/A3, quant_mode should be 2, but got %lld", quantMode); |
| 140 | // cmp_ratio 校验 | 142 | // cmp_ratio 校验 |
| 141 | CHECK_COND((cmpRatio >= QLI_V2_CMP_RATIO_LOWER_BOUND) && (cmpRatio <= QLI_V2_CMP_RATIO_UPPER_BOUND) && | 143 | CHECK_COND((cmpRatio >= QLI_V2_CMP_RATIO_LOWER_BOUND) && (cmpRatio <= QLI_V2_CMP_RATIO_UPPER_BOUND) && |
| 142 | - ((cmpRatio & (cmpRatio - 1)) == 0), ACLNN_ERR_PARAM_INVALID, | 144 | + ((cmpRatio & (cmpRatio - 1)) == 0), |
| 143 | - "For Atlas A2/A3, cmp_ratio should be 1/2/4/8/16/32/64/128, but got %lld", cmpRatio); | 145 | + ACLNN_ERR_PARAM_INVALID, "For Atlas A2/A3, cmp_ratio should be 1/2/4/8/16/32/64/128, but got %lld", |
| 146 | + cmpRatio); | ||
| 144 | CHECK_COND(strcmp(layoutKOptional, "PA_BBND") == 0, ACLNN_ERR_PARAM_INVALID, | 147 | CHECK_COND(strcmp(layoutKOptional, "PA_BBND") == 0, ACLNN_ERR_PARAM_INVALID, |
| 145 | - "For Atlas A2/A3, layout_k must be PA_BBND, but got %s", layoutKOptional); | 148 | + "For Atlas A2/A3, layout_k must be PA_BBND, but got %s", layoutKOptional); |
| 146 | } else { // 校验 A5参数 | 149 | } else { // 校验 A5参数 |
| 147 | // num_heads_q 校验 | 150 | // num_heads_q 校验 |
| 148 | CHECK_COND(numHeadsQ >= QLI_V2_NUM_HEADS_Q_LOWER_BOUND && numHeadsQ <= QLI_V2_NUM_HEADS_Q_UPPER_BOUND, | 151 | CHECK_COND(numHeadsQ >= QLI_V2_NUM_HEADS_Q_LOWER_BOUND && numHeadsQ <= QLI_V2_NUM_HEADS_Q_UPPER_BOUND, |
| 149 | - ACLNN_ERR_PARAM_INVALID, "For Ascend 950PR/Ascend 950DT, num_heads_q should be [%lld, %lld], but got %lld", | 152 | + ACLNN_ERR_PARAM_INVALID, |
| 150 | - QLI_V2_NUM_HEADS_Q_LOWER_BOUND, QLI_V2_NUM_HEADS_Q_UPPER_BOUND, numHeadsQ); | 153 | + "For Ascend 950PR/Ascend 950DT, num_heads_q should be [%lld, %lld], but got %lld", |
| 154 | + QLI_V2_NUM_HEADS_Q_LOWER_BOUND, QLI_V2_NUM_HEADS_Q_UPPER_BOUND, numHeadsQ); | ||
| 151 | // topk 校验 | 155 | // topk 校验 |
| 152 | CHECK_COND(topk >= QLI_V2_TOPK_LOWER_BOUND && topk <= QLI_V2_A5_TOPK_UPPER_BOUND, ACLNN_ERR_PARAM_INVALID, | 156 | CHECK_COND(topk >= QLI_V2_TOPK_LOWER_BOUND && topk <= QLI_V2_A5_TOPK_UPPER_BOUND, ACLNN_ERR_PARAM_INVALID, |
| 153 | - "For Ascend 950PR/Ascend 950DT, topk should be [%lld, %lld], but got %lld", | 157 | + "For Ascend 950PR/Ascend 950DT, topk should be [%lld, %lld], but got %lld", QLI_V2_TOPK_LOWER_BOUND, |
| 154 | - QLI_V2_TOPK_LOWER_BOUND, QLI_V2_A5_TOPK_UPPER_BOUND, topk); | 158 | + QLI_V2_A5_TOPK_UPPER_BOUND, topk); |
| 155 | // quant_mode 校验 | 159 | // quant_mode 校验 |
| 156 | CHECK_COND((quantMode == QLI_V2_QUANT_MODE_1) || (quantMode == QLI_V2_QUANT_MODE_2) || | 160 | CHECK_COND((quantMode == QLI_V2_QUANT_MODE_1) || (quantMode == QLI_V2_QUANT_MODE_2) || |
| 157 | - (quantMode == QLI_V2_QUANT_MODE_4), ACLNN_ERR_PARAM_INVALID, | 161 | + (quantMode == QLI_V2_QUANT_MODE_3) || (quantMode == QLI_V2_QUANT_MODE_4) || |
| 158 | - "For Ascend 950PR/Ascend 950DT, quant_mode should be %lld/%lld/%lld, but got %lld", | 162 | + (quantMode == QLI_V2_QUANT_MODE_5), |
| 159 | - QLI_V2_QUANT_MODE_1, QLI_V2_QUANT_MODE_2, QLI_V2_QUANT_MODE_4, quantMode); | 163 | + ACLNN_ERR_PARAM_INVALID, |
| 164 | + "For Ascend 950PR/Ascend 950DT, quant_mode should be %lld/%lld/%lld/%lld/%lld, but got %lld", | ||
| 165 | + QLI_V2_QUANT_MODE_1, QLI_V2_QUANT_MODE_2, QLI_V2_QUANT_MODE_3, QLI_V2_QUANT_MODE_4, | ||
| 166 | + QLI_V2_QUANT_MODE_5, quantMode); | ||
| 160 | // cmp_ratio 校验 | 167 | // cmp_ratio 校验 |
| 161 | CHECK_COND((cmpRatio >= QLI_V2_CMP_RATIO_LOWER_BOUND) && (cmpRatio <= QLI_V2_CMP_RATIO_UPPER_BOUND), | 168 | CHECK_COND((cmpRatio >= QLI_V2_CMP_RATIO_LOWER_BOUND) && (cmpRatio <= QLI_V2_CMP_RATIO_UPPER_BOUND), |
| 162 | - ACLNN_ERR_PARAM_INVALID, "For Ascend 950PR/Ascend 950DT, cmp_ratio should be between [%lld, %lld], " | 169 | + ACLNN_ERR_PARAM_INVALID, |
| 163 | - "but got %lld", QLI_V2_CMP_RATIO_LOWER_BOUND, QLI_V2_CMP_RATIO_UPPER_BOUND, cmpRatio); | 170 | + "For Ascend 950PR/Ascend 950DT, cmp_ratio should be between [%lld, %lld], " |
| 164 | - CHECK_COND((strcmp(layoutKOptional, "TND") == 0) || (strcmp(layoutKOptional, "BSND") == 0) || \ | 171 | + "but got %lld", |
| 165 | - (strcmp(layoutKOptional, "PA_BBND") == 0), ACLNN_ERR_PARAM_INVALID, | 172 | + QLI_V2_CMP_RATIO_LOWER_BOUND, QLI_V2_CMP_RATIO_UPPER_BOUND, cmpRatio); |
| 166 | - "For Ascend 950PR/Ascend 950DT, layout_k must be TND/BSND/PA_BBND, but got %s", layoutKOptional); | 173 | + CHECK_COND((strcmp(layoutKOptional, "TND") == 0) || (strcmp(layoutKOptional, "BSND") == 0) || |
| 174 | + (strcmp(layoutKOptional, "PA_BBND") == 0), | ||
| 175 | + ACLNN_ERR_PARAM_INVALID, | ||
| 176 | + "For Ascend 950PR/Ascend 950DT, layout_k must be TND/BSND/PA_BBND, but got %s", layoutKOptional); | ||
| 167 | } | 177 | } |
| 168 | // 核心数校验 | 178 | // 核心数校验 |
| 169 | CHECK_COND(aicCoreNum > 0, ACLNN_ERR_PARAM_INVALID, "AIC num should be larger than 0, but got %u", aicCoreNum); | 179 | CHECK_COND(aicCoreNum > 0, ACLNN_ERR_PARAM_INVALID, "AIC num should be larger than 0, but got %u", aicCoreNum); |
| 170 | CHECK_COND(aicCoreNum <= optiling::AIC_CORE_MAX_NUM, ACLNN_ERR_PARAM_INVALID, | 180 | CHECK_COND(aicCoreNum <= optiling::AIC_CORE_MAX_NUM, ACLNN_ERR_PARAM_INVALID, |
| 171 | - "The maximum supported AIC num is %u, but got %u", optiling::AIC_CORE_MAX_NUM, aicCoreNum); | 181 | + "The maximum supported AIC num is %u, but got %u", optiling::AIC_CORE_MAX_NUM, aicCoreNum); |
| 172 | CHECK_COND(aivCoreNum > 0, ACLNN_ERR_PARAM_INVALID, "AIV num should be larger than 0, but got %u", aivCoreNum); | 182 | CHECK_COND(aivCoreNum > 0, ACLNN_ERR_PARAM_INVALID, "AIV num should be larger than 0, but got %u", aivCoreNum); |
| 173 | CHECK_COND(aivCoreNum <= optiling::AIV_CORE_MAX_NUM, ACLNN_ERR_PARAM_INVALID, | 183 | CHECK_COND(aivCoreNum <= optiling::AIV_CORE_MAX_NUM, ACLNN_ERR_PARAM_INVALID, |
| 174 | - "The maximum supported AIV num is %u, but got %u", optiling::AIV_CORE_MAX_NUM, aivCoreNum); | 184 | + "The maximum supported AIV num is %u, but got %u", optiling::AIV_CORE_MAX_NUM, aivCoreNum); |
| 175 | return ACLNN_SUCCESS; | 185 | return ACLNN_SUCCESS; |
| 176 | } | 186 | } |
| 177 | 187 | ||
| 178 | aclnnStatus CheckExistenceQliV2(int64_t maskMode, int64_t cmpRatio, const aclTensor *cuSeqlensQOptional, | 188 | aclnnStatus CheckExistenceQliV2(int64_t maskMode, int64_t cmpRatio, const aclTensor *cuSeqlensQOptional, |
| 179 | - const aclTensor *cuSeqlensKOptional, const aclTensor *sequsedQOptional, const aclTensor *sequsedKOptional, | 189 | + const aclTensor *cuSeqlensKOptional, const aclTensor *sequsedQOptional, |
| 180 | - const aclTensor *cmpResidualKOptional, int64_t maxSeqlenQ, int64_t maxSeqlenK, const char *layoutQOptional, | 190 | + const aclTensor *sequsedKOptional, const aclTensor *cmpResidualKOptional, |
| 181 | - const char *layoutKOptional, const aclTensor *metadata) | 191 | + int64_t maxSeqlenQ, int64_t maxSeqlenK, const char *layoutQOptional, |
| 192 | + const char *layoutKOptional, const aclTensor *metadata) | ||
| 182 | { | 193 | { |
| 183 | // cu_seqlens_q 存在性校验 | 194 | // cu_seqlens_q 存在性校验 |
| 184 | if (strcmp(layoutQOptional, "TND") == 0) { | 195 | if (strcmp(layoutQOptional, "TND") == 0) { |
| 185 | CHECK_COND(IsTensorExistQliV2(cuSeqlensQOptional), ACLNN_ERR_PARAM_INVALID, | 196 | CHECK_COND(IsTensorExistQliV2(cuSeqlensQOptional), ACLNN_ERR_PARAM_INVALID, |
| 186 | - "For layout_q TND, cu_seqlens_q must be provided!"); | 197 | + "For layout_q TND, cu_seqlens_q must be provided!"); |
| 187 | } | 198 | } |
| 188 | // layout_q BSND, seqused_q 不存在时,max_seqlen_q 不能为-1 | 199 | // layout_q BSND, seqused_q 不存在时,max_seqlen_q 不能为-1 |
| 189 | if (strcmp(layoutQOptional, "BSND") == 0 && !IsTensorExistQliV2(sequsedQOptional)) { | 200 | if (strcmp(layoutQOptional, "BSND") == 0 && !IsTensorExistQliV2(sequsedQOptional)) { |
| 190 | CHECK_COND(maxSeqlenQ > -1, ACLNN_ERR_PARAM_INVALID, | 201 | CHECK_COND(maxSeqlenQ > -1, ACLNN_ERR_PARAM_INVALID, |
| 191 | - "When layout_q is BSND and seqused_q is not provided, max_seqlen_q can not be -1!"); | 202 | + "When layout_q is BSND and seqused_q is not provided, max_seqlen_q can not be -1!"); |
| 192 | } | 203 | } |
| 193 | // cu_seqlens_k 存在性校验 | 204 | // cu_seqlens_k 存在性校验 |
| 194 | if (strcmp(layoutKOptional, "TND") == 0) { | 205 | if (strcmp(layoutKOptional, "TND") == 0) { |
| 195 | CHECK_COND(IsTensorExistQliV2(cuSeqlensKOptional), ACLNN_ERR_PARAM_INVALID, | 206 | CHECK_COND(IsTensorExistQliV2(cuSeqlensKOptional), ACLNN_ERR_PARAM_INVALID, |
| 196 | - "For layout_k TND, cu_seqlens_k must be provided!"); | 207 | + "For layout_k TND, cu_seqlens_k must be provided!"); |
| 197 | } | 208 | } |
| 198 | // seqused_k 存在性校验 | 209 | // seqused_k 存在性校验 |
| 199 | if (strcmp(layoutKOptional, "PA_BBND") == 0) { | 210 | if (strcmp(layoutKOptional, "PA_BBND") == 0) { |
| 200 | CHECK_COND(IsTensorExistQliV2(sequsedKOptional), ACLNN_ERR_PARAM_INVALID, | 211 | CHECK_COND(IsTensorExistQliV2(sequsedKOptional), ACLNN_ERR_PARAM_INVALID, |
| 201 | - "For layout_k PA_BBND, seqused_k must be provided!"); | 212 | + "For layout_k PA_BBND, seqused_k must be provided!"); |
| 202 | } | 213 | } |
| 203 | // layout_k BSND, seqused_k 不存在时,max_seqlen_k 不能为-1 | 214 | // layout_k BSND, seqused_k 不存在时,max_seqlen_k 不能为-1 |
| 204 | if (strcmp(layoutKOptional, "BSND") == 0 && !IsTensorExistQliV2(sequsedKOptional)) { | 215 | if (strcmp(layoutKOptional, "BSND") == 0 && !IsTensorExistQliV2(sequsedKOptional)) { |
| 205 | CHECK_COND(maxSeqlenK > -1, ACLNN_ERR_PARAM_INVALID, | 216 | CHECK_COND(maxSeqlenK > -1, ACLNN_ERR_PARAM_INVALID, |
| 206 | - "When layout_k is BSND and seqused_k is not provided, max_seqlen_k can not be -1!"); | 217 | + "When layout_k is BSND and seqused_k is not provided, max_seqlen_k can not be -1!"); |
| 207 | } | 218 | } |
| 208 | // cmp_residual_k 存在性校验 | 219 | // cmp_residual_k 存在性校验 |
| 209 | if (cmpRatio != QLI_V2_CMP_RATIO_LOWER_BOUND && maskMode == QLI_V2_CAUSAL_MASK_MODE) { | 220 | if (cmpRatio != QLI_V2_CMP_RATIO_LOWER_BOUND && maskMode == QLI_V2_CAUSAL_MASK_MODE) { |
| 210 | CHECK_COND(IsTensorExistQliV2(cmpResidualKOptional), ACLNN_ERR_PARAM_INVALID, | 221 | CHECK_COND(IsTensorExistQliV2(cmpResidualKOptional), ACLNN_ERR_PARAM_INVALID, |
| 211 | - "When cmp_ratio is not 1 and mask_mode is CAUSAL, cmp_residual_k must be provided!"); | 222 | + "When cmp_ratio is not 1 and mask_mode is CAUSAL, cmp_residual_k must be provided!"); |
| 212 | } | 223 | } |
| 213 | // metadata 存在性校验 | 224 | // metadata 存在性校验 |
| 214 | - CHECK_COND(IsTensorExistQliV2(metadata), ACLNN_ERR_PARAM_INVALID, | 225 | + CHECK_COND(IsTensorExistQliV2(metadata), ACLNN_ERR_PARAM_INVALID, "Output metadata is nullptr!"); |
| 215 | - "Output metadata is nullptr!"); | ||
| 216 | return ACLNN_SUCCESS; | 226 | return ACLNN_SUCCESS; |
| 217 | } | 227 | } |
| 218 | 228 | ||
| 219 | aclnnStatus CheckConsistencyQliV2(int64_t batchSize, const aclTensor *cuSeqlensQOptional, | 229 | aclnnStatus CheckConsistencyQliV2(int64_t batchSize, const aclTensor *cuSeqlensQOptional, |
| 220 | - const aclTensor *cuSeqlensKOptional, const aclTensor *sequsedQOptional, const aclTensor *sequsedKOptional, | 230 | + const aclTensor *cuSeqlensKOptional, const aclTensor *sequsedQOptional, |
| 221 | - const aclTensor *cmpResidualKOptional, const char *layoutQOptional, const char *layoutKOptional, | 231 | + const aclTensor *sequsedKOptional, const aclTensor *cmpResidualKOptional, |
| 222 | - const aclTensor *metadata) | 232 | + const char *layoutQOptional, const char *layoutKOptional, const aclTensor *metadata) |
| 223 | { | 233 | { |
| 224 | int64_t dimNum = -1; | 234 | int64_t dimNum = -1; |
| 225 | aclDataType dataType = aclDataType::ACL_DT_UNDEFINED; | 235 | aclDataType dataType = aclDataType::ACL_DT_UNDEFINED; |
| @@ -230,7 +240,7 @@ aclnnStatus CheckConsistencyQliV2(int64_t batchSize, const aclTensor *cuSeqlensQ | |||
| 230 | CHECK_COND(dimNum == 1, ACLNN_ERR_PARAM_INVALID, "The dim num of cu_seqlens_q must be 1, but got %lld", dimNum); | 240 | CHECK_COND(dimNum == 1, ACLNN_ERR_PARAM_INVALID, "The dim num of cu_seqlens_q must be 1, but got %lld", dimNum); |
| 231 | dataType = GetDataTypeQliV2(cuSeqlensQOptional); | 241 | dataType = GetDataTypeQliV2(cuSeqlensQOptional); |
| 232 | CHECK_COND(dataType == aclDataType::ACL_INT32, ACLNN_ERR_PARAM_INVALID, | 242 | CHECK_COND(dataType == aclDataType::ACL_INT32, ACLNN_ERR_PARAM_INVALID, |
| 233 | - "The data type of cu_seqlens_q must be int32, but got %d", static_cast<int32_t>(dataType)); | 243 | + "The data type of cu_seqlens_q must be int32, but got %d", static_cast<int32_t>(dataType)); |
| 234 | } | 244 | } |
| 235 | // 校验 cu_seqlens_k | 245 | // 校验 cu_seqlens_k |
| 236 | if (IsTensorExistQliV2(cuSeqlensKOptional)) { | 246 | if (IsTensorExistQliV2(cuSeqlensKOptional)) { |
| @@ -238,7 +248,7 @@ aclnnStatus CheckConsistencyQliV2(int64_t batchSize, const aclTensor *cuSeqlensQ | |||
| 238 | CHECK_COND(dimNum == 1, ACLNN_ERR_PARAM_INVALID, "The dim num of cu_seqlens_k must be 1, but got %lld", dimNum); | 248 | CHECK_COND(dimNum == 1, ACLNN_ERR_PARAM_INVALID, "The dim num of cu_seqlens_k must be 1, but got %lld", dimNum); |
| 239 | dataType = GetDataTypeQliV2(cuSeqlensKOptional); | 249 | dataType = GetDataTypeQliV2(cuSeqlensKOptional); |
| 240 | CHECK_COND(dataType == aclDataType::ACL_INT32, ACLNN_ERR_PARAM_INVALID, | 250 | CHECK_COND(dataType == aclDataType::ACL_INT32, ACLNN_ERR_PARAM_INVALID, |
| 241 | - "The data type of cu_seqlens_k must be int32, but got %d", static_cast<int32_t>(dataType)); | 251 | + "The data type of cu_seqlens_k must be int32, but got %d", static_cast<int32_t>(dataType)); |
| 242 | } | 252 | } |
| 243 | // 校验 seqused_q | 253 | // 校验 seqused_q |
| 244 | if (IsTensorExistQliV2(sequsedQOptional)) { | 254 | if (IsTensorExistQliV2(sequsedQOptional)) { |
| @@ -246,7 +256,7 @@ aclnnStatus CheckConsistencyQliV2(int64_t batchSize, const aclTensor *cuSeqlensQ | |||
| 246 | CHECK_COND(dimNum == 1, ACLNN_ERR_PARAM_INVALID, "The dim num of seqused_q must be 1, but got %lld", dimNum); | 256 | CHECK_COND(dimNum == 1, ACLNN_ERR_PARAM_INVALID, "The dim num of seqused_q must be 1, but got %lld", dimNum); |
| 247 | dataType = GetDataTypeQliV2(sequsedQOptional); | 257 | dataType = GetDataTypeQliV2(sequsedQOptional); |
| 248 | CHECK_COND(dataType == aclDataType::ACL_INT32, ACLNN_ERR_PARAM_INVALID, | 258 | CHECK_COND(dataType == aclDataType::ACL_INT32, ACLNN_ERR_PARAM_INVALID, |
| 249 | - "The data type of seqused_q must be int32, but got %d", static_cast<int32_t>(dataType)); | 259 | + "The data type of seqused_q must be int32, but got %d", static_cast<int32_t>(dataType)); |
| 250 | } | 260 | } |
| 251 | // 校验 seqused_k | 261 | // 校验 seqused_k |
| 252 | if (IsTensorExistQliV2(sequsedKOptional)) { | 262 | if (IsTensorExistQliV2(sequsedKOptional)) { |
| @@ -254,16 +264,16 @@ aclnnStatus CheckConsistencyQliV2(int64_t batchSize, const aclTensor *cuSeqlensQ | |||
| 254 | CHECK_COND(dimNum == 1, ACLNN_ERR_PARAM_INVALID, "The dim num of seqused_k must be 1, but got %lld", dimNum); | 264 | CHECK_COND(dimNum == 1, ACLNN_ERR_PARAM_INVALID, "The dim num of seqused_k must be 1, but got %lld", dimNum); |
| 255 | dataType = GetDataTypeQliV2(sequsedKOptional); | 265 | dataType = GetDataTypeQliV2(sequsedKOptional); |
| 256 | CHECK_COND(dataType == aclDataType::ACL_INT32, ACLNN_ERR_PARAM_INVALID, | 266 | CHECK_COND(dataType == aclDataType::ACL_INT32, ACLNN_ERR_PARAM_INVALID, |
| 257 | - "The data type of seqused_k must be int32, but got %d", static_cast<int32_t>(dataType)); | 267 | + "The data type of seqused_k must be int32, but got %d", static_cast<int32_t>(dataType)); |
| 258 | } | 268 | } |
| 259 | // 校验 cmp_residual_k | 269 | // 校验 cmp_residual_k |
| 260 | if (IsTensorExistQliV2(cmpResidualKOptional)) { | 270 | if (IsTensorExistQliV2(cmpResidualKOptional)) { |
| 261 | dimNum = GetDimNumQliV2(cmpResidualKOptional); | 271 | dimNum = GetDimNumQliV2(cmpResidualKOptional); |
| 262 | - CHECK_COND(dimNum == 1, ACLNN_ERR_PARAM_INVALID, | 272 | + CHECK_COND(dimNum == 1, ACLNN_ERR_PARAM_INVALID, "The dim num of cmp_residual_k must be 1, but got %lld", |
| 263 | - "The dim num of cmp_residual_k must be 1, but got %lld", dimNum); | 273 | + dimNum); |
| 264 | dataType = GetDataTypeQliV2(cmpResidualKOptional); | 274 | dataType = GetDataTypeQliV2(cmpResidualKOptional); |
| 265 | CHECK_COND(dataType == aclDataType::ACL_INT32, ACLNN_ERR_PARAM_INVALID, | 275 | CHECK_COND(dataType == aclDataType::ACL_INT32, ACLNN_ERR_PARAM_INVALID, |
| 266 | - "The data type of cmp_residual_k must be int32, but got %d", static_cast<int32_t>(dataType)); | 276 | + "The data type of cmp_residual_k must be int32, but got %d", static_cast<int32_t>(dataType)); |
| 267 | } | 277 | } |
| 268 | // 校验 metadata | 278 | // 校验 metadata |
| 269 | if (IsTensorExistQliV2(metadata)) { | 279 | if (IsTensorExistQliV2(metadata)) { |
| @@ -271,11 +281,11 @@ aclnnStatus CheckConsistencyQliV2(int64_t batchSize, const aclTensor *cuSeqlensQ | |||
| 271 | CHECK_COND(dimNum == 1, ACLNN_ERR_PARAM_INVALID, "The dim num of metadata must be 1, but got %lld", dimNum); | 281 | CHECK_COND(dimNum == 1, ACLNN_ERR_PARAM_INVALID, "The dim num of metadata must be 1, but got %lld", dimNum); |
| 272 | dataType = GetDataTypeQliV2(metadata); | 282 | dataType = GetDataTypeQliV2(metadata); |
| 273 | CHECK_COND(dataType == aclDataType::ACL_INT32, ACLNN_ERR_PARAM_INVALID, | 283 | CHECK_COND(dataType == aclDataType::ACL_INT32, ACLNN_ERR_PARAM_INVALID, |
| 274 | - "The data type of metadata must be int32, but got %d", static_cast<int32_t>(dataType)); | 284 | + "The data type of metadata must be int32, but got %d", static_cast<int32_t>(dataType)); |
| 275 | // 校验 metadata 元素数 | 285 | // 校验 metadata 元素数 |
| 276 | if (metadata->GetViewShape().GetDim(0) != optiling::QLI_V2_METADATA_TOTAL_SIZE) { | 286 | if (metadata->GetViewShape().GetDim(0) != optiling::QLI_V2_METADATA_TOTAL_SIZE) { |
| 277 | OP_LOGE(ACLNN_ERR_PARAM_INVALID, "The element num of metadata must be %u, but got %lld", | 287 | OP_LOGE(ACLNN_ERR_PARAM_INVALID, "The element num of metadata must be %u, but got %lld", |
| 278 | - optiling::QLI_V2_METADATA_TOTAL_SIZE, metadata->GetViewShape().GetDim(0)); | 288 | + optiling::QLI_V2_METADATA_TOTAL_SIZE, metadata->GetViewShape().GetDim(0)); |
| 279 | return ACLNN_ERR_PARAM_INVALID; | 289 | return ACLNN_ERR_PARAM_INVALID; |
| 280 | } | 290 | } |
| 281 | } | 291 | } |
| @@ -283,54 +293,61 @@ aclnnStatus CheckConsistencyQliV2(int64_t batchSize, const aclTensor *cuSeqlensQ | |||
| 283 | int64_t queryBatchSize = GetQueryBatchSizeQliV2(batchSize, cuSeqlensQOptional, sequsedQOptional, layoutQOptional); | 293 | int64_t queryBatchSize = GetQueryBatchSizeQliV2(batchSize, cuSeqlensQOptional, sequsedQOptional, layoutQOptional); |
| 284 | int64_t keyBatchSize = GetKeyBatchSizeQliV2(batchSize, cuSeqlensKOptional, sequsedKOptional, layoutKOptional); | 294 | int64_t keyBatchSize = GetKeyBatchSizeQliV2(batchSize, cuSeqlensKOptional, sequsedKOptional, layoutKOptional); |
| 285 | CHECK_COND(queryBatchSize == keyBatchSize, ACLNN_ERR_PARAM_INVALID, | 295 | CHECK_COND(queryBatchSize == keyBatchSize, ACLNN_ERR_PARAM_INVALID, |
| 286 | - "The batch_size obtained from query should be the same as that obtained from key, but got %lld and %lld", | 296 | + "The batch_size obtained from query should be the same as that obtained from key, but got %lld and %lld", |
| 287 | - queryBatchSize, keyBatchSize); | 297 | + queryBatchSize, keyBatchSize); |
| 288 | // 校验TND场景q维度一致性 | 298 | // 校验TND场景q维度一致性 |
| 289 | if (strcmp(layoutQOptional, "TND") == 0 && IsTensorExistQliV2(sequsedQOptional)) { | 299 | if (strcmp(layoutQOptional, "TND") == 0 && IsTensorExistQliV2(sequsedQOptional)) { |
| 290 | int64_t cuSeqlensQBatchSize = cuSeqlensQOptional->GetViewShape().GetDim(0) - 1; | 300 | int64_t cuSeqlensQBatchSize = cuSeqlensQOptional->GetViewShape().GetDim(0) - 1; |
| 291 | - CHECK_COND(cuSeqlensQBatchSize == queryBatchSize, ACLNN_ERR_PARAM_INVALID, | 301 | + CHECK_COND( |
| 302 | + cuSeqlensQBatchSize == queryBatchSize, ACLNN_ERR_PARAM_INVALID, | ||
| 292 | "When layout_q is TND and seqused_q is passed, The batch_size obtained from cu_seqlens_q should be the " | 303 | "When layout_q is TND and seqused_q is passed, The batch_size obtained from cu_seqlens_q should be the " |
| 293 | - "same as that obtained from seqused_q, but got %lld and %lld", cuSeqlensQBatchSize, queryBatchSize); | 304 | + "same as that obtained from seqused_q, but got %lld and %lld", |
| 305 | + cuSeqlensQBatchSize, queryBatchSize); | ||
| 294 | } | 306 | } |
| 295 | // 校验TND场景k维度一致性 | 307 | // 校验TND场景k维度一致性 |
| 296 | if (strcmp(layoutKOptional, "TND") == 0 && IsTensorExistQliV2(sequsedKOptional)) { | 308 | if (strcmp(layoutKOptional, "TND") == 0 && IsTensorExistQliV2(sequsedKOptional)) { |
| 297 | int64_t cuSeqlensKBatchSize = cuSeqlensKOptional->GetViewShape().GetDim(0) - 1; | 309 | int64_t cuSeqlensKBatchSize = cuSeqlensKOptional->GetViewShape().GetDim(0) - 1; |
| 298 | - CHECK_COND(cuSeqlensKBatchSize == keyBatchSize, ACLNN_ERR_PARAM_INVALID, | 310 | + CHECK_COND( |
| 311 | + cuSeqlensKBatchSize == keyBatchSize, ACLNN_ERR_PARAM_INVALID, | ||
| 299 | "When layout_k is TND and seqused_k is passed, The batch_size obtained from cu_seqlens_k should be the " | 312 | "When layout_k is TND and seqused_k is passed, The batch_size obtained from cu_seqlens_k should be the " |
| 300 | - "same as that obtained from seqused_k, but got %lld and %lld", cuSeqlensKBatchSize, keyBatchSize); | 313 | + "same as that obtained from seqused_k, but got %lld and %lld", |
| 314 | + cuSeqlensKBatchSize, keyBatchSize); | ||
| 301 | } | 315 | } |
| 302 | // 校验 cmp_residual_k 元素数 | 316 | // 校验 cmp_residual_k 元素数 |
| 303 | if (IsTensorExistQliV2(cmpResidualKOptional)) { | 317 | if (IsTensorExistQliV2(cmpResidualKOptional)) { |
| 304 | auto cmpResidualKBatch = cmpResidualKOptional->GetViewShape().GetDim(0); | 318 | auto cmpResidualKBatch = cmpResidualKOptional->GetViewShape().GetDim(0); |
| 305 | CHECK_COND(cmpResidualKBatch == queryBatchSize, ACLNN_ERR_PARAM_INVALID, | 319 | CHECK_COND(cmpResidualKBatch == queryBatchSize, ACLNN_ERR_PARAM_INVALID, |
| 306 | - "The batch_size of cmp_residual_k should match the valid batch size, but got %lld and %lld", | 320 | + "The batch_size of cmp_residual_k should match the valid batch size, but got %lld and %lld", |
| 307 | - cmpResidualKBatch, queryBatchSize); | 321 | + cmpResidualKBatch, queryBatchSize); |
| 308 | } | 322 | } |
| 309 | return ACLNN_SUCCESS; | 323 | return ACLNN_SUCCESS; |
| 310 | } | 324 | } |
| 311 | 325 | ||
| 312 | -aclnnStatus ParamsCheckQliV2( | 326 | +aclnnStatus ParamsCheckQliV2(const aclTensor *cuSeqlensQOptional, const aclTensor *cuSeqlensKOptional, |
| 313 | - const aclTensor *cuSeqlensQOptional, const aclTensor *cuSeqlensKOptional, const aclTensor *sequsedQOptional, | 327 | + const aclTensor *sequsedQOptional, const aclTensor *sequsedKOptional, |
| 314 | - const aclTensor *sequsedKOptional, const aclTensor *cmpResidualKOptional, int64_t numHeadsQ, int64_t numHeadsK, | 328 | + const aclTensor *cmpResidualKOptional, int64_t numHeadsQ, int64_t numHeadsK, |
| 315 | - int64_t headDim, int64_t topk, int64_t quantMode, int64_t batchSize, int64_t maxSeqlenQ, int64_t maxSeqlenK, | 329 | + int64_t headDim, int64_t topk, int64_t quantMode, int64_t batchSize, int64_t maxSeqlenQ, |
| 316 | - char *layoutQOptional, char *layoutKOptional, int64_t maskMode, int64_t cmpRatio, const aclTensor *metadata, | 330 | + int64_t maxSeqlenK, char *layoutQOptional, char *layoutKOptional, int64_t maskMode, |
| 317 | - uint32_t aicCoreNum, uint32_t aivCoreNum, const std::string &socVersion) | 331 | + int64_t cmpRatio, const aclTensor *metadata, uint32_t aicCoreNum, uint32_t aivCoreNum, |
| 332 | + const std::string &socVersion) | ||
| 318 | { | 333 | { |
| 319 | - auto ret = CheckSingleParamQliV2(numHeadsQ, numHeadsK, topk, quantMode, batchSize, maxSeqlenQ, maxSeqlenK, | 334 | + auto ret = |
| 320 | - layoutQOptional, layoutKOptional, maskMode, cmpRatio, aicCoreNum, aivCoreNum, socVersion); | 335 | + CheckSingleParamQliV2(numHeadsQ, numHeadsK, topk, quantMode, batchSize, maxSeqlenQ, maxSeqlenK, layoutQOptional, |
| 336 | + layoutKOptional, maskMode, cmpRatio, aicCoreNum, aivCoreNum, socVersion); | ||
| 321 | CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); | 337 | CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); |
| 322 | 338 | ||
| 323 | ret = CheckExistenceQliV2(maskMode, cmpRatio, cuSeqlensQOptional, cuSeqlensKOptional, sequsedQOptional, | 339 | ret = CheckExistenceQliV2(maskMode, cmpRatio, cuSeqlensQOptional, cuSeqlensKOptional, sequsedQOptional, |
| 324 | - sequsedKOptional, cmpResidualKOptional, maxSeqlenQ, maxSeqlenK, layoutQOptional, layoutKOptional, metadata); | 340 | + sequsedKOptional, cmpResidualKOptional, maxSeqlenQ, maxSeqlenK, layoutQOptional, |
| 341 | + layoutKOptional, metadata); | ||
| 325 | CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); | 342 | CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); |
| 326 | 343 | ||
| 327 | - ret = CheckConsistencyQliV2(batchSize, cuSeqlensQOptional, cuSeqlensKOptional, sequsedQOptional, | 344 | + ret = CheckConsistencyQliV2(batchSize, cuSeqlensQOptional, cuSeqlensKOptional, sequsedQOptional, sequsedKOptional, |
| 328 | - sequsedKOptional, cmpResidualKOptional, layoutQOptional, layoutKOptional, metadata); | 345 | + cmpResidualKOptional, layoutQOptional, layoutKOptional, metadata); |
| 329 | CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); | 346 | CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); |
| 330 | 347 | ||
| 331 | return ACLNN_SUCCESS; | 348 | return ACLNN_SUCCESS; |
| 332 | } | 349 | } |
| 333 | -} | 350 | +} // namespace |
| 334 | 351 | ||
| 335 | #ifdef __cplusplus | 352 | #ifdef __cplusplus |
| 336 | } | 353 | } |
| @@ -75,53 +75,54 @@ constexpr int64_t FP4_IN_INT8 = 2; | |||
| 75 | constexpr int64_t PENULTIMATE_DIM = 2; | 75 | constexpr int64_t PENULTIMATE_DIM = 2; |
| 76 | const int g_toAclOffset = 256; | 76 | const int g_toAclOffset = 256; |
| 77 | 77 | ||
| 78 | -#define AT_ALL_SCALAR_TYPE_AND_ACL_DATATYPE_PAIR(_) \ | 78 | +#define AT_ALL_SCALAR_TYPE_AND_ACL_DATATYPE_PAIR(_) \ |
| 79 | - _(at::ScalarType::Byte, ACL_UINT8) \ | 79 | + _(at::ScalarType::Byte, ACL_UINT8) \ |
| 80 | - _(at::ScalarType::Char, ACL_INT8) \ | 80 | + _(at::ScalarType::Char, ACL_INT8) \ |
| 81 | - _(at::ScalarType::Short, ACL_INT16) \ | 81 | + _(at::ScalarType::Short, ACL_INT16) \ |
| 82 | - _(at::ScalarType::Int, ACL_INT32) \ | 82 | + _(at::ScalarType::Int, ACL_INT32) \ |
| 83 | - _(at::ScalarType::Long, ACL_INT64) \ | 83 | + _(at::ScalarType::Long, ACL_INT64) \ |
| 84 | - _(at::ScalarType::Half, ACL_FLOAT16) \ | 84 | + _(at::ScalarType::Half, ACL_FLOAT16) \ |
| 85 | - _(at::ScalarType::Float, ACL_FLOAT) \ | 85 | + _(at::ScalarType::Float, ACL_FLOAT) \ |
| 86 | - _(at::ScalarType::Double, ACL_DOUBLE) \ | 86 | + _(at::ScalarType::Double, ACL_DOUBLE) \ |
| 87 | - _(at::ScalarType::ComplexHalf, ACL_COMPLEX32) \ | 87 | + _(at::ScalarType::ComplexHalf, ACL_COMPLEX32) \ |
| 88 | - _(at::ScalarType::ComplexFloat, ACL_COMPLEX64) \ | 88 | + _(at::ScalarType::ComplexFloat, ACL_COMPLEX64) \ |
| 89 | - _(at::ScalarType::ComplexDouble, ACL_COMPLEX128) \ | 89 | + _(at::ScalarType::ComplexDouble, ACL_COMPLEX128) \ |
| 90 | - _(at::ScalarType::Bool, ACL_BOOL) \ | 90 | + _(at::ScalarType::Bool, ACL_BOOL) \ |
| 91 | - _(at::ScalarType::QInt8, ACL_DT_UNDEFINED) \ | 91 | + _(at::ScalarType::QInt8, ACL_DT_UNDEFINED) \ |
| 92 | - _(at::ScalarType::QUInt8, ACL_DT_UNDEFINED) \ | 92 | + _(at::ScalarType::QUInt8, ACL_DT_UNDEFINED) \ |
| 93 | - _(at::ScalarType::QInt32, ACL_DT_UNDEFINED) \ | 93 | + _(at::ScalarType::QInt32, ACL_DT_UNDEFINED) \ |
| 94 | - _(at::ScalarType::BFloat16, ACL_BF16) \ | 94 | + _(at::ScalarType::BFloat16, ACL_BF16) \ |
| 95 | - _(at::ScalarType::QUInt4x2, ACL_DT_UNDEFINED) \ | 95 | + _(at::ScalarType::QUInt4x2, ACL_DT_UNDEFINED) \ |
| 96 | - _(at::ScalarType::QUInt2x4, ACL_DT_UNDEFINED) \ | 96 | + _(at::ScalarType::QUInt2x4, ACL_DT_UNDEFINED) \ |
| 97 | - _(at::ScalarType::Bits1x8, ACL_DT_UNDEFINED) \ | 97 | + _(at::ScalarType::Bits1x8, ACL_DT_UNDEFINED) \ |
| 98 | - _(at::ScalarType::Bits2x4, ACL_DT_UNDEFINED) \ | 98 | + _(at::ScalarType::Bits2x4, ACL_DT_UNDEFINED) \ |
| 99 | - _(at::ScalarType::Bits4x2, ACL_DT_UNDEFINED) \ | 99 | + _(at::ScalarType::Bits4x2, ACL_DT_UNDEFINED) \ |
| 100 | - _(at::ScalarType::Bits8, ACL_DT_UNDEFINED) \ | 100 | + _(at::ScalarType::Bits8, ACL_DT_UNDEFINED) \ |
| 101 | - _(at::ScalarType::Bits16, ACL_DT_UNDEFINED) \ | 101 | + _(at::ScalarType::Bits16, ACL_DT_UNDEFINED) \ |
| 102 | - _(at::ScalarType::Float8_e5m2, ACL_FLOAT8_E5M2) \ | 102 | + _(at::ScalarType::Float8_e5m2, ACL_FLOAT8_E5M2) \ |
| 103 | - _(at::ScalarType::Float8_e4m3fn, ACL_FLOAT8_E4M3FN) \ | 103 | + _(at::ScalarType::Float8_e4m3fn, ACL_FLOAT8_E4M3FN) \ |
| 104 | - _(at::ScalarType::Float8_e5m2fnuz, ACL_DT_UNDEFINED) \ | 104 | + _(at::ScalarType::Float8_e5m2fnuz, ACL_DT_UNDEFINED) \ |
| 105 | - _(at::ScalarType::Float8_e4m3fnuz, ACL_DT_UNDEFINED) \ | 105 | + _(at::ScalarType::Float8_e4m3fnuz, ACL_DT_UNDEFINED) \ |
| 106 | - _(at::ScalarType::UInt16, ACL_UINT16) \ | 106 | + _(at::ScalarType::UInt16, ACL_UINT16) \ |
| 107 | - _(at::ScalarType::UInt32, ACL_UINT32) \ | 107 | + _(at::ScalarType::UInt32, ACL_UINT32) \ |
| 108 | - _(at::ScalarType::UInt64, ACL_UINT64) \ | 108 | + _(at::ScalarType::UInt64, ACL_UINT64) \ |
| 109 | - _(at::ScalarType::UInt1, ACL_DT_UNDEFINED) \ | 109 | + _(at::ScalarType::UInt1, ACL_DT_UNDEFINED) \ |
| 110 | - _(at::ScalarType::UInt2, ACL_DT_UNDEFINED) \ | 110 | + _(at::ScalarType::UInt2, ACL_DT_UNDEFINED) \ |
| 111 | - _(at::ScalarType::UInt3, ACL_DT_UNDEFINED) \ | 111 | + _(at::ScalarType::UInt3, ACL_DT_UNDEFINED) \ |
| 112 | - _(at::ScalarType::UInt4, ACL_DT_UNDEFINED) \ | 112 | + _(at::ScalarType::UInt4, ACL_DT_UNDEFINED) \ |
| 113 | - _(at::ScalarType::UInt5, ACL_DT_UNDEFINED) \ | 113 | + _(at::ScalarType::UInt5, ACL_DT_UNDEFINED) \ |
| 114 | - _(at::ScalarType::UInt6, ACL_DT_UNDEFINED) \ | 114 | + _(at::ScalarType::UInt6, ACL_DT_UNDEFINED) \ |
| 115 | - _(at::ScalarType::UInt7, ACL_DT_UNDEFINED) \ | 115 | + _(at::ScalarType::UInt7, ACL_DT_UNDEFINED) \ |
| 116 | - _(at::ScalarType::Int1, ACL_DT_UNDEFINED) \ | 116 | + _(at::ScalarType::Int1, ACL_DT_UNDEFINED) \ |
| 117 | - _(at::ScalarType::Int2, ACL_DT_UNDEFINED) \ | 117 | + _(at::ScalarType::Int2, ACL_DT_UNDEFINED) \ |
| 118 | - _(at::ScalarType::Int3, ACL_DT_UNDEFINED) \ | 118 | + _(at::ScalarType::Int3, ACL_DT_UNDEFINED) \ |
| 119 | - _(at::ScalarType::Int4, ACL_DT_UNDEFINED) \ | 119 | + _(at::ScalarType::Int4, ACL_DT_UNDEFINED) \ |
| 120 | - _(at::ScalarType::Int5, ACL_DT_UNDEFINED) \ | 120 | + _(at::ScalarType::Int5, ACL_DT_UNDEFINED) \ |
| 121 | - _(at::ScalarType::Int6, ACL_DT_UNDEFINED) \ | 121 | + _(at::ScalarType::Int6, ACL_DT_UNDEFINED) \ |
| 122 | - _(at::ScalarType::Int7, ACL_DT_UNDEFINED) \ | 122 | + _(at::ScalarType::Int7, ACL_DT_UNDEFINED) \ |
| 123 | - _(at::ScalarType::Float8_e8m0fnu, ACL_FLOAT8_E8M0) \ | 123 | + _(at::ScalarType::Float8_e8m0fnu, ACL_FLOAT8_E8M0) \ |
| 124 | - _(at::ScalarType::Undefined, ACL_DT_UNDEFINED) \ | 124 | + _(at::ScalarType::Float4_e2m1fn_x2, ACL_FLOAT4_E2M1) \ |
| 125 | + _(at::ScalarType::Undefined, ACL_DT_UNDEFINED) \ | ||
| 125 | _(at::ScalarType::NumOptions, ACL_DT_UNDEFINED) | 126 | _(at::ScalarType::NumOptions, ACL_DT_UNDEFINED) |
| 126 | 127 | ||
| 127 | constexpr aclDataType kATenScalarTypeToAclDataTypeTable[] = { | 128 | constexpr aclDataType kATenScalarTypeToAclDataTypeTable[] = { |
| @@ -134,19 +135,16 @@ constexpr aclDataType kATenScalarTypeToAclDataTypeTable[] = { | |||
| 134 | 135 | ||
| 135 | enum class DType { | 136 | enum class DType { |
| 136 | UNDEFINED = -1, | 137 | UNDEFINED = -1, |
| 137 | - ENUM_OFFSET(FLOAT, ACL_FLOAT) | 138 | + ENUM_OFFSET(FLOAT, ACL_FLOAT) ENUM_OFFSET(FLOAT16, ACL_FLOAT16) ENUM_OFFSET(INT8, ACL_INT8) ENUM_OFFSET( |
| 138 | - ENUM_OFFSET(FLOAT16, ACL_FLOAT16) ENUM_OFFSET(INT8, ACL_INT8) ENUM_OFFSET(INT32, ACL_INT32) | 139 | + INT32, ACL_INT32) ENUM_OFFSET(UINT8, ACL_UINT8) ENUM_OFFSET(INT16, ACL_INT16) ENUM_OFFSET(UINT16, ACL_UINT16) |
| 139 | - ENUM_OFFSET(UINT8, ACL_UINT8) ENUM_OFFSET(INT16, ACL_INT16) ENUM_OFFSET(UINT16, ACL_UINT16) | 140 | + ENUM_OFFSET(UINT32, ACL_UINT32) ENUM_OFFSET(INT64, ACL_INT64) ENUM_OFFSET(UINT64, ACL_UINT64) |
| 140 | - ENUM_OFFSET(UINT32, ACL_UINT32) ENUM_OFFSET(INT64, ACL_INT64) ENUM_OFFSET(UINT64, ACL_UINT64) | 141 | + ENUM_OFFSET(DOUBLE, ACL_DOUBLE) ENUM_OFFSET(BOOL, ACL_BOOL) ENUM_OFFSET(STRING, ACL_STRING) ENUM_OFFSET( |
| 141 | - ENUM_OFFSET(DOUBLE, ACL_DOUBLE) ENUM_OFFSET(BOOL, ACL_BOOL) ENUM_OFFSET(STRING, ACL_STRING) | 142 | + COMPLEX64, ACL_COMPLEX64) ENUM_OFFSET(COMPLEX128, ACL_COMPLEX128) ENUM_OFFSET(BF16, ACL_BF16) |
| 142 | - ENUM_OFFSET(COMPLEX64, ACL_COMPLEX64) ENUM_OFFSET(COMPLEX128, ACL_COMPLEX128) | 143 | + ENUM_OFFSET(INT4, ACL_INT4) ENUM_OFFSET(UINT1, ACL_UINT1) ENUM_OFFSET(COMPLEX32, ACL_COMPLEX32) |
| 143 | - ENUM_OFFSET(BF16, ACL_BF16) ENUM_OFFSET(INT4, ACL_INT4) ENUM_OFFSET(UINT1, ACL_UINT1) | 144 | + ENUM_OFFSET(HIFLOAT8, ACL_HIFLOAT8) ENUM_OFFSET(FLOAT8_E5M2, ACL_FLOAT8_E5M2) |
| 144 | - ENUM_OFFSET(COMPLEX32, ACL_COMPLEX32) ENUM_OFFSET(HIFLOAT8, ACL_HIFLOAT8) | 145 | + ENUM_OFFSET(FLOAT8_E4M3FN, ACL_FLOAT8_E4M3FN) ENUM_OFFSET(FLOAT8_E8M0, ACL_FLOAT8_E8M0) |
| 145 | - ENUM_OFFSET(FLOAT8_E5M2, ACL_FLOAT8_E5M2) ENUM_OFFSET(FLOAT8_E4M3FN, ACL_FLOAT8_E4M3FN) | 146 | + ENUM_OFFSET(FLOAT6_E3M2, ACL_FLOAT6_E3M2) ENUM_OFFSET(FLOAT6_E2M3, ACL_FLOAT6_E2M3) |
| 146 | - ENUM_OFFSET(FLOAT8_E8M0, ACL_FLOAT8_E8M0) ENUM_OFFSET(FLOAT6_E3M2, ACL_FLOAT6_E3M2) | 147 | + ENUM_OFFSET(FLOAT4_E2M1, ACL_FLOAT4_E2M1) ENUM_OFFSET(FLOAT4_E1M2, ACL_FLOAT4_E1M2) |
| 147 | - ENUM_OFFSET(FLOAT6_E2M3, ACL_FLOAT6_E2M3) | ||
| 148 | - ENUM_OFFSET(FLOAT4_E2M1, ACL_FLOAT4_E2M1) | ||
| 149 | - ENUM_OFFSET(FLOAT4_E1M2, ACL_FLOAT4_E1M2) | ||
| 150 | }; | 148 | }; |
| 151 | 149 | ||
| 152 | namespace op_infer { | 150 | namespace op_infer { |
| @@ -178,6 +176,18 @@ inline bool Is4BitDtype(const aclDataType acl_data_type) | |||
| 178 | return acl_data_type == ACL_FLOAT4_E2M1 || acl_data_type == ACL_FLOAT4_E1M2 || acl_data_type == ACL_INT4; | 176 | return acl_data_type == ACL_FLOAT4_E2M1 || acl_data_type == ACL_FLOAT4_E1M2 || acl_data_type == ACL_INT4; |
| 179 | } | 177 | } |
| 180 | 178 | ||
| 179 | +inline int64_t ConvertToAclStorageOffset(const at::Tensor &at_tensor, const aclDataType acl_data_type) | ||
| 180 | +{ | ||
| 181 | + int64_t storageOffset = at_tensor.storage_offset(); | ||
| 182 | + if (Is4BitDtype(acl_data_type)) { | ||
| 183 | + // ACL 4-bit descriptors express offsets in logical nibble elements. | ||
| 184 | + TORCH_CHECK(storageOffset <= INT64_MAX / FP4_IN_INT8, | ||
| 185 | + "4-bit tensor storage offset is too large to convert to logical elements: ", storageOffset); | ||
| 186 | + storageOffset *= FP4_IN_INT8; | ||
| 187 | + } | ||
| 188 | + return storageOffset; | ||
| 189 | +} | ||
| 190 | + | ||
| 181 | static std::unordered_map<aclFormat, aclFormat> FORMAT_FAKE_TO_REAL{ | 191 | static std::unordered_map<aclFormat, aclFormat> FORMAT_FAKE_TO_REAL{ |
| 182 | {ACL_FORMAT_FRACTAL_NZ_C0_16, ACL_FORMAT_FRACTAL_NZ_C0_32}, {ACL_FORMAT_FRACTAL_NZ, ACL_FORMAT_FRACTAL_NZ}}; | 192 | {ACL_FORMAT_FRACTAL_NZ_C0_16, ACL_FORMAT_FRACTAL_NZ_C0_32}, {ACL_FORMAT_FRACTAL_NZ, ACL_FORMAT_FRACTAL_NZ}}; |
| 183 | 193 | ||
| @@ -233,13 +243,13 @@ enum QuantMode { | |||
| 233 | 243 | ||
| 234 | #define GET_OP_API_FUNC(apiName) reinterpret_cast<_##apiName>(GetOpApiFuncAddr(#apiName)) | 244 | #define GET_OP_API_FUNC(apiName) reinterpret_cast<_##apiName>(GetOpApiFuncAddr(#apiName)) |
| 235 | 245 | ||
| 236 | -#define MEMCPY_TO_BUF(data_expression, size_expression) \ | 246 | +#define MEMCPY_TO_BUF(data_expression, size_expression) \ |
| 237 | - if (g_hashOffset + (size_expression) > kHashBufSize) { \ | 247 | + if (g_hashOffset + (size_expression) > kHashBufSize) { \ |
| 238 | - g_hashOffset = kHashBufMaxSize; \ | 248 | + g_hashOffset = kHashBufMaxSize; \ |
| 239 | - return; \ | 249 | + return; \ |
| 240 | - } \ | 250 | + } \ |
| 241 | - auto ret = memcpy_s(g_hashBuf + g_hashOffset, size_expression, data_expression, size_expression); \ | 251 | + auto ret = memcpy_s(g_hashBuf + g_hashOffset, size_expression, data_expression, size_expression); \ |
| 242 | - TORCH_CHECK(ret == 0, "memcpy_s failed, error:", ret); \ | 252 | + TORCH_CHECK(ret == 0, "memcpy_s failed, error:", ret); \ |
| 243 | g_hashOffset += size_expression; | 253 | g_hashOffset += size_expression; |
| 244 | 254 | ||
| 245 | aclDataType ConvertToAclDataType(const at::ScalarType &data_type) | 255 | aclDataType ConvertToAclDataType(const at::ScalarType &data_type) |
| @@ -261,20 +271,11 @@ inline aclDataType GetAclDataType(int64_t t) | |||
| 261 | return ConvertToAclDataType(static_cast<at::ScalarType>(t)); | 271 | return ConvertToAclDataType(static_cast<at::ScalarType>(t)); |
| 262 | } | 272 | } |
| 263 | 273 | ||
| 264 | -inline const char *GetOpApiLibName(void) | 274 | +inline const char *GetOpApiLibName(void) { return "libopapi.so"; } |
| 265 | -{ | ||
| 266 | - return "libopapi.so"; | ||
| 267 | -} | ||
| 268 | 275 | ||
| 269 | -inline const char *GetTransformerOpApiLibName(void) | 276 | +inline const char *GetTransformerOpApiLibName(void) { return "libopapi_transformer.so"; } |
| 270 | -{ | ||
| 271 | - return "libopapi_transformer.so"; | ||
| 272 | -} | ||
| 273 | 277 | ||
| 274 | -inline const char *GetCustOpApiLibName(void) | 278 | +inline const char *GetCustOpApiLibName(void) { return "libcust_opapi.so"; } |
| 275 | -{ | ||
| 276 | - return "libcust_opapi.so"; | ||
| 277 | -} | ||
| 278 | 279 | ||
| 279 | inline void *GetOpApiFuncAddrInLib(void *handler, const char *libName, const char *apiName) | 280 | inline void *GetOpApiFuncAddrInLib(void *handler, const char *libName, const char *apiName) |
| 280 | { | 281 | { |
| @@ -477,9 +478,10 @@ inline aclTensor *ConvertType(const at::Tensor &at_tensor) | |||
| 477 | storageDims.size(), const_cast<void *>(aclInput.storage().data())); | 478 | storageDims.size(), const_cast<void *>(aclInput.storage().data())); |
| 478 | } | 479 | } |
| 479 | 480 | ||
| 480 | - auto acl_tensor = aclCreateTensor(wrapperShape.data(), at_tensor.sizes().size(), acl_data_type, | 481 | + auto acl_tensor = |
| 481 | - wrapperStride.data(), at_tensor.storage_offset(), format, storageDims.data(), | 482 | + aclCreateTensor(wrapperShape.data(), at_tensor.sizes().size(), acl_data_type, wrapperStride.data(), |
| 482 | - storageDims.size(), const_cast<void *>(at_tensor.storage().data())); | 483 | + ConvertToAclStorageOffset(at_tensor, acl_data_type), format, storageDims.data(), |
| 484 | + storageDims.size(), const_cast<void *>(at_tensor.storage().data())); | ||
| 483 | return acl_tensor; | 485 | return acl_tensor; |
| 484 | } | 486 | } |
| 485 | 487 | ||
| @@ -538,30 +540,26 @@ inline aclScalar *ConvertType(const at::Scalar &at_scalar) | |||
| 538 | std::string(c10::toString(scalar_data_type)) + " has not been supported") | 540 | std::string(c10::toString(scalar_data_type)) + " has not been supported") |
| 539 | aclScalar *acl_scalar = nullptr; | 541 | aclScalar *acl_scalar = nullptr; |
| 540 | switch (scalar_data_type) { | 542 | switch (scalar_data_type) { |
| 541 | - case at::ScalarType::Double: | 543 | + case at::ScalarType::Double: { |
| 542 | - { | 544 | + double value = at_scalar.toDouble(); |
| 543 | - double value = at_scalar.toDouble(); | 545 | + acl_scalar = aclCreateScalar(&value, acl_data_type); |
| 544 | - acl_scalar = aclCreateScalar(&value, acl_data_type); | 546 | + break; |
| 545 | - break; | 547 | + } |
| 546 | - } | 548 | + case at::ScalarType::Long: { |
| 547 | - case at::ScalarType::Long: | 549 | + int64_t value = at_scalar.toLong(); |
| 548 | - { | 550 | + acl_scalar = aclCreateScalar(&value, acl_data_type); |
| 549 | - int64_t value = at_scalar.toLong(); | 551 | + break; |
| 550 | - acl_scalar = aclCreateScalar(&value, acl_data_type); | 552 | + } |
| 551 | - break; | 553 | + case at::ScalarType::Bool: { |
| 552 | - } | 554 | + bool value = at_scalar.toBool(); |
| 553 | - case at::ScalarType::Bool: | 555 | + acl_scalar = aclCreateScalar(&value, acl_data_type); |
| 554 | - { | 556 | + break; |
| 555 | - bool value = at_scalar.toBool(); | 557 | + } |
| 556 | - acl_scalar = aclCreateScalar(&value, acl_data_type); | 558 | + case at::ScalarType::ComplexDouble: { |
| 557 | - break; | 559 | + auto value = at_scalar.toComplexDouble(); |
| 558 | - } | 560 | + acl_scalar = aclCreateScalar(&value, acl_data_type); |
| 559 | - case at::ScalarType::ComplexDouble: | 561 | + break; |
| 560 | - { | 562 | + } |
| 561 | - auto value = at_scalar.toComplexDouble(); | ||
| 562 | - acl_scalar = aclCreateScalar(&value, acl_data_type); | ||
| 563 | - break; | ||
| 564 | - } | ||
| 565 | default: | 563 | default: |
| 566 | acl_scalar = nullptr; | 564 | acl_scalar = nullptr; |
| 567 | break; | 565 | break; |
| @@ -644,15 +642,9 @@ inline aclScalar *ConvertType(const c10::optional<at::Scalar> &opt_scalar) | |||
| 644 | return nullptr; | 642 | return nullptr; |
| 645 | } | 643 | } |
| 646 | 644 | ||
| 647 | -inline aclDataType ConvertType(const at::ScalarType scalarType) | 645 | +inline aclDataType ConvertType(const at::ScalarType scalarType) { return ConvertToAclDataType(scalarType); } |
| 648 | -{ | ||
| 649 | - return ConvertToAclDataType(scalarType); | ||
| 650 | -} | ||
| 651 | 646 | ||
| 652 | -inline const char *ConvertType(const string &str) | 647 | +inline const char *ConvertType(const string &str) { return str.c_str(); } |
| 653 | -{ | ||
| 654 | - return str.c_str(); | ||
| 655 | -} | ||
| 656 | 648 | ||
| 657 | aclTensor *ConvertType(const TensorWrapper &tensor_r) | 649 | aclTensor *ConvertType(const TensorWrapper &tensor_r) |
| 658 | { | 650 | { |
| @@ -711,9 +703,10 @@ aclTensor *ConvertType(const TensorWrapper &tensor_r) | |||
| 711 | } | 703 | } |
| 712 | } | 704 | } |
| 713 | 705 | ||
| 714 | - auto acl_tensor = aclCreateTensor(wrapperShape.data(), at_tensor.sizes().size(), acl_data_type, | 706 | + auto acl_tensor = |
| 715 | - wrapperStride.data(), at_tensor.storage_offset(), format, storageDims.data(), | 707 | + aclCreateTensor(wrapperShape.data(), at_tensor.sizes().size(), acl_data_type, wrapperStride.data(), |
| 716 | - storageDims.size(), const_cast<void *>(at_tensor.storage().data())); | 708 | + ConvertToAclStorageOffset(at_tensor, acl_data_type), format, storageDims.data(), |
| 709 | + storageDims.size(), const_cast<void *>(at_tensor.storage().data())); | ||
| 717 | return acl_tensor; | 710 | return acl_tensor; |
| 718 | } | 711 | } |
| 719 | 712 | ||
| @@ -906,8 +899,7 @@ struct is_at_tensor_list<at::TensorList> : std::true_type {}; | |||
| 906 | */ | 899 | */ |
| 907 | template <std::size_t I = 0, typename... Ts> | 900 | template <std::size_t I = 0, typename... Ts> |
| 908 | typename std::enable_if<I == sizeof...(Ts), void>::type GetFirstTensor(const std::tuple<Ts...> &t, at::Tensor &res) | 901 | typename std::enable_if<I == sizeof...(Ts), void>::type GetFirstTensor(const std::tuple<Ts...> &t, at::Tensor &res) |
| 909 | -{ | 902 | +{} |
| 910 | -} | ||
| 911 | 903 | ||
| 912 | template <std::size_t I = 0, typename... Ts> | 904 | template <std::size_t I = 0, typename... Ts> |
| 913 | typename std::enable_if < I<sizeof...(Ts), void>::type GetFirstTensor(const std::tuple<Ts...> &t, at::Tensor &res) | 905 | typename std::enable_if < I<sizeof...(Ts), void>::type GetFirstTensor(const std::tuple<Ts...> &t, at::Tensor &res) |
| @@ -934,60 +926,60 @@ auto DecodeDevice(Ts &...args) -> at::Device | |||
| 934 | return ft.device(); | 926 | return ft.device(); |
| 935 | } | 927 | } |
| 936 | 928 | ||
| 937 | -#define ACLNN_CMD(aclnn_api, ...) \ | 929 | +#define ACLNN_CMD(aclnn_api, ...) \ |
| 938 | - do { \ | 930 | + do { \ |
| 939 | - auto device = DecodeDevice(__VA_ARGS__); \ | 931 | + auto device = DecodeDevice(__VA_ARGS__); \ |
| 940 | - const c10::OptionalDeviceGuard device_guard(device); \ | 932 | + const c10::OptionalDeviceGuard device_guard(device); \ |
| 941 | - static const auto getWorkspaceSizeFuncAddr = GetOpApiFuncAddr(#aclnn_api "GetWorkspaceSize"); \ | 933 | + static const auto getWorkspaceSizeFuncAddr = GetOpApiFuncAddr(#aclnn_api "GetWorkspaceSize"); \ |
| 942 | - static const auto opApiFuncAddr = GetOpApiFuncAddr(#aclnn_api); \ | 934 | + static const auto opApiFuncAddr = GetOpApiFuncAddr(#aclnn_api); \ |
| 943 | - static const auto initMemAddr = GetOpApiFuncAddr("InitHugeMemThreadLocal"); \ | 935 | + static const auto initMemAddr = GetOpApiFuncAddr("InitHugeMemThreadLocal"); \ |
| 944 | - static const auto unInitMemAddr = GetOpApiFuncAddr("UnInitHugeMemThreadLocal"); \ | 936 | + static const auto unInitMemAddr = GetOpApiFuncAddr("UnInitHugeMemThreadLocal"); \ |
| 945 | - static const auto releaseMemAddr = GetOpApiFuncAddr("ReleaseHugeMem"); \ | 937 | + static const auto releaseMemAddr = GetOpApiFuncAddr("ReleaseHugeMem"); \ |
| 946 | - TORCH_CHECK(getWorkspaceSizeFuncAddr != nullptr && opApiFuncAddr != nullptr, #aclnn_api, " or ", \ | 938 | + TORCH_CHECK(getWorkspaceSizeFuncAddr != nullptr && opApiFuncAddr != nullptr, #aclnn_api, " or ", \ |
| 947 | #aclnn_api "GetWorkspaceSize", " not in ", GetOpApiLibName(), ", or ", GetOpApiLibName(), ", or ", \ | 939 | #aclnn_api "GetWorkspaceSize", " not in ", GetOpApiLibName(), ", or ", GetOpApiLibName(), ", or ", \ |
| 948 | - GetTransformerOpApiLibName(), "not found."); \ | 940 | + GetTransformerOpApiLibName(), "not found."); \ |
| 949 | - auto acl_stream = c10_npu::getCurrentNPUStream().stream(false); \ | 941 | + auto acl_stream = c10_npu::getCurrentNPUStream().stream(false); \ |
| 950 | - uint64_t workspace_size = 0; \ | 942 | + uint64_t workspace_size = 0; \ |
| 951 | - uint64_t *workspace_size_addr = &workspace_size; \ | 943 | + uint64_t *workspace_size_addr = &workspace_size; \ |
| 952 | - aclOpExecutor *executor = nullptr; \ | 944 | + aclOpExecutor *executor = nullptr; \ |
| 953 | - aclOpExecutor **executor_addr = &executor; \ | 945 | + aclOpExecutor **executor_addr = &executor; \ |
| 954 | - InitHugeMemThreadLocal initMemFunc = reinterpret_cast<InitHugeMemThreadLocal>(initMemAddr); \ | 946 | + InitHugeMemThreadLocal initMemFunc = reinterpret_cast<InitHugeMemThreadLocal>(initMemAddr); \ |
| 955 | - UnInitHugeMemThreadLocal unInitMemFunc = reinterpret_cast<UnInitHugeMemThreadLocal>(unInitMemAddr); \ | 947 | + UnInitHugeMemThreadLocal unInitMemFunc = reinterpret_cast<UnInitHugeMemThreadLocal>(unInitMemAddr); \ |
| 956 | - if (initMemFunc) { \ | 948 | + if (initMemFunc) { \ |
| 957 | - initMemFunc(nullptr, false); \ | 949 | + initMemFunc(nullptr, false); \ |
| 958 | - } \ | 950 | + } \ |
| 959 | - auto deterministic = at::globalContext().deterministicAlgorithms(); \ | 951 | + auto deterministic = at::globalContext().deterministicAlgorithms(); \ |
| 960 | - aclrtCtxSetSysParamOpt(aclSysParamOpt::ACL_OPT_DETERMINISTIC, deterministic ? 1 : 0); \ | 952 | + aclrtCtxSetSysParamOpt(aclSysParamOpt::ACL_OPT_DETERMINISTIC, deterministic ? 1 : 0); \ |
| 961 | - auto converted_params = ConvertTypes(__VA_ARGS__, workspace_size_addr, executor_addr); \ | 953 | + auto converted_params = ConvertTypes(__VA_ARGS__, workspace_size_addr, executor_addr); \ |
| 962 | - static auto getWorkspaceSizeFunc = ConvertToOpApiFunc(converted_params, getWorkspaceSizeFuncAddr); \ | 954 | + static auto getWorkspaceSizeFunc = ConvertToOpApiFunc(converted_params, getWorkspaceSizeFuncAddr); \ |
| 963 | - auto workspace_status = call(getWorkspaceSizeFunc, converted_params); \ | 955 | + auto workspace_status = call(getWorkspaceSizeFunc, converted_params); \ |
| 964 | - TORCH_CHECK(workspace_status == 0, "call " #aclnn_api " failed, detail:", aclGetRecentErrMsg()); \ | 956 | + TORCH_CHECK(workspace_status == 0, "call " #aclnn_api " failed, detail:", aclGetRecentErrMsg()); \ |
| 965 | - at::Tensor workspace_tensor; \ | 957 | + at::Tensor workspace_tensor; \ |
| 966 | - void *workspace_addr = nullptr; \ | 958 | + void *workspace_addr = nullptr; \ |
| 967 | - if (workspace_size != 0) { \ | 959 | + if (workspace_size != 0) { \ |
| 968 | - at::TensorOptions options = at::TensorOptions(torch_npu::utils::get_npu_device_type()); \ | 960 | + at::TensorOptions options = at::TensorOptions(torch_npu::utils::get_npu_device_type()); \ |
| 969 | - workspace_tensor = at::empty({workspace_size}, options.dtype(at::kByte)); \ | 961 | + workspace_tensor = at::empty({workspace_size}, options.dtype(at::kByte)); \ |
| 970 | - workspace_addr = const_cast<void *>(workspace_tensor.storage().data()); \ | 962 | + workspace_addr = const_cast<void *>(workspace_tensor.storage().data()); \ |
| 971 | - } \ | 963 | + } \ |
| 972 | - auto acl_call = [converted_params, workspace_addr, workspace_size, acl_stream, executor]() -> int { \ | 964 | + auto acl_call = [converted_params, workspace_addr, workspace_size, acl_stream, executor]() -> int { \ |
| 973 | - typedef int (*OpApiFunc)(void *, uint64_t, aclOpExecutor *, const aclrtStream); \ | 965 | + typedef int (*OpApiFunc)(void *, uint64_t, aclOpExecutor *, const aclrtStream); \ |
| 974 | - OpApiFunc opApiFunc = reinterpret_cast<OpApiFunc>(opApiFuncAddr); \ | 966 | + OpApiFunc opApiFunc = reinterpret_cast<OpApiFunc>(opApiFuncAddr); \ |
| 975 | - auto api_ret = opApiFunc(workspace_addr, workspace_size, executor, acl_stream); \ | 967 | + auto api_ret = opApiFunc(workspace_addr, workspace_size, executor, acl_stream); \ |
| 976 | - TORCH_CHECK(api_ret == 0, "call " #aclnn_api " failed, detail:", aclGetRecentErrMsg()); \ | 968 | + TORCH_CHECK(api_ret == 0, "call " #aclnn_api " failed, detail:", aclGetRecentErrMsg()); \ |
| 977 | - ReleaseConvertTypes(converted_params); \ | 969 | + ReleaseConvertTypes(converted_params); \ |
| 978 | - ReleaseHugeMem releaseMemFunc = reinterpret_cast<ReleaseHugeMem>(releaseMemAddr); \ | 970 | + ReleaseHugeMem releaseMemFunc = reinterpret_cast<ReleaseHugeMem>(releaseMemAddr); \ |
| 979 | - if (releaseMemFunc) { \ | 971 | + if (releaseMemFunc) { \ |
| 980 | - releaseMemFunc(nullptr, false); \ | 972 | + releaseMemFunc(nullptr, false); \ |
| 981 | - } \ | 973 | + } \ |
| 982 | - return api_ret; \ | 974 | + return api_ret; \ |
| 983 | - }; \ | 975 | + }; \ |
| 984 | - at_npu::native::OpCommand cmd; \ | 976 | + at_npu::native::OpCommand cmd; \ |
| 985 | - cmd.Name(#aclnn_api); \ | 977 | + cmd.Name(#aclnn_api); \ |
| 986 | - cmd.SetCustomHandler(acl_call); \ | 978 | + cmd.SetCustomHandler(acl_call); \ |
| 987 | - cmd.Run(); \ | 979 | + cmd.Run(); \ |
| 988 | - if (unInitMemFunc) { \ | 980 | + if (unInitMemFunc) { \ |
| 989 | - unInitMemFunc(nullptr, false); \ | 981 | + unInitMemFunc(nullptr, false); \ |
| 990 | - } \ | 982 | + } \ |
| 991 | } while (false) | 983 | } while (false) |
| 992 | 984 | ||
| 993 | #endif // CANN_OPS_TRANSFORMER_ACLNN_COMMON_H | 985 | #endif // CANN_OPS_TRANSFORMER_ACLNN_COMMON_H |
| @@ -107,7 +107,7 @@ cann_ops_transformer.quant_lightning_indexer( | |||
| 107 | | num_heads_k | int | 必选 | 表示Key的head个数,当前仅支持1。 | int32 | - | | 107 | | num_heads_k | int | 必选 | 表示Key的head个数,当前仅支持1。 | int32 | - | |
| 108 | | head_dim | int | 必选 | 表示注意力头的维度,当前仅支持128。 | int32 | - | | 108 | | head_dim | int | 必选 | 表示注意力头的维度,当前仅支持128。 | int32 | - | |
| 109 | | topk | int | 必选 | 表示从Query中筛选出的关键稀疏token的个数,当前仅支持[1, 2048]。 | int32 | - | | 109 | | topk | int | 必选 | 表示从Query中筛选出的关键稀疏token的个数,当前仅支持[1, 2048]。 | int32 | - | |
| 110 | -| quant_mode | int | 必选 | 表示量化模式。1表示Per-Token-Head float8_e4m3fn量化;2表示Per-Token-Head int8量化;4表示Per-Tensor HIfloat8量化。 | int32 | - | | 110 | +| quant_mode | int | 必选 | 表示量化模式,当前支持1/2/3/4/5。1表示qk: fp8(e4m3fn) per-token-head, scale: fp32;2表示qk: int8 per-token-head, scale: fp16, w: fp16;3表示qk: mxfp8(e4m3fn), scale: fp8(e8m0);4表示qk: hifloat8 per-tensor, scale: fp32;5表示qk: mxfp4(e2m1), scale: fp8(e8m0)。 | int32 | - | |
| 111 | | cu_seqlens_q | Tensor | 可选 | 表示不同Batch中Query的有效Sequence Length,仅layout_q为TND场景下必传,第一个值固定为0。数据格式为ND,支持非连续的Tensor。 | int32 | (B+1, ) | | 111 | | cu_seqlens_q | Tensor | 可选 | 表示不同Batch中Query的有效Sequence Length,仅layout_q为TND场景下必传,第一个值固定为0。数据格式为ND,支持非连续的Tensor。 | int32 | (B+1, ) | |
| 112 | | cu_seqlens_k | Tensor | 可选 | 表示不同Batch中Key的有效Sequence Length,仅layout_k为TND场景下必传,第一个值固定为0。数据格式为ND,支持非连续的Tensor。 | int32 | (B+1, ) | | 112 | | cu_seqlens_k | Tensor | 可选 | 表示不同Batch中Key的有效Sequence Length,仅layout_k为TND场景下必传,第一个值固定为0。数据格式为ND,支持非连续的Tensor。 | int32 | (B+1, ) | |
| 113 | | seqused_q | Tensor | 可选 | 表示不同Batch中Query实际参与运算的Sequence Length。数据格式为ND,支持非连续的Tensor。 | int32 | (B, ) | | 113 | | seqused_q | Tensor | 可选 | 表示不同Batch中Query实际参与运算的Sequence Length。数据格式为ND,支持非连续的Tensor。 | int32 | (B, ) | |
| @@ -125,23 +125,23 @@ cann_ops_transformer.quant_lightning_indexer( | |||
| 125 | - <term>Ascend 950PR/Ascend 950DT</term>:不支持quant_mode = 2。 | 125 | - <term>Ascend 950PR/Ascend 950DT</term>:不支持quant_mode = 2。 |
| 126 | <!-- end id5 --> | 126 | <!-- end id5 --> |
| 127 | <!-- npu="A3" id6 --> | 127 | <!-- npu="A3" id6 --> |
| 128 | -- <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term>:不支持num_heads_q = 32,不支持quant_mode = 1/4,不支持layout_k = BSND/TND,不支持cmp_ratio在[1, 128]任意取值,仅支持cmp_ratio = 1/2/4/8/16/32/64/128。 | 128 | +- <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term>:不支持num_heads_q = 32,不支持quant_mode = 1/3/4/5,不支持layout_k = BSND/TND,不支持cmp_ratio在[1, 128]任意取值,仅支持cmp_ratio = 1/2/4/8/16/32/64/128。 |
| 129 | <!-- end id6 --> | 129 | <!-- end id6 --> |
| 130 | <!-- npu="910b" id7 --> | 130 | <!-- npu="910b" id7 --> |
| 131 | -- <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term>:不支持num_heads_q = 32,不支持quant_mode = 1/4,不支持layout_k = BSND/TND,不支持cmp_ratio在[1, 128]任意取值,仅支持cmp_ratio = 1/2/4/8/16/32/64/128。 | 131 | +- <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term>:不支持num_heads_q = 32,不支持quant_mode = 1/3/4/5,不支持layout_k = BSND/TND,不支持cmp_ratio在[1, 128]任意取值,仅支持cmp_ratio = 1/2/4/8/16/32/64/128。 |
| 132 | <!-- end id7 --> | 132 | <!-- end id7 --> |
| 133 | 133 | ||
| 134 | ### quant_lightning_indexer | 134 | ### quant_lightning_indexer |
| 135 | 135 | ||
| 136 | | 参数名 | 参数类型 | 可选/必选 | 描述 | 数据类型 | 维度(shape) | | 136 | | 参数名 | 参数类型 | 可选/必选 | 描述 | 数据类型 | 维度(shape) | |
| 137 | |--------|----------|-----------|------|----------|-------------| | 137 | |--------|----------|-----------|------|----------|-------------| |
| 138 | -| query | Tensor | 必选 | 公式中的量化输入$Q_{index}^{Quant}$。不支持空tensor。数据格式为ND。 | int8、float8_e4m3fn、HIfloat8 | layout_q为BSND时shape为(B,S1,N1,D);layout_q为TND时shape为(T1,N1,D) | | 138 | +| query | Tensor | 必选 | 公式中的量化输入$Q_{index}^{Quant}$。不支持空tensor。数据格式为ND。 | int8、float8_e4m3fn、HIfloat8、float4_e2m1 | layout_q为BSND时shape为(B,S1,N1,D);layout_q为TND时shape为(T1,N1,D) | |
| 139 | -| key | Tensor | 必选 | 公式中的量化输入$K_{index}^{Quant}$。不支持空tensor。数据格式为ND,仅PA_BBND场景下0轴支持非连续。PA_BBND场景下block_size取值为16的倍数,最大支持1024。 | int8、float8_e4m3fn、HIfloat8 | layout_k为BSND时shape为(B,S2,N2,D);layout_k为TND时shape为(T2,N2,D);layout_k为PA_BBND时shape为(block_num,block_size,N2,D) | | 139 | +| key | Tensor | 必选 | 公式中的量化输入$K_{index}^{Quant}$。不支持空tensor。数据格式为ND,仅PA_BBND场景下0轴支持非连续。PA_BBND场景下block_size取值为16的倍数,最大支持1024。 | int8、float8_e4m3fn、HIfloat8、float4_e2m1 | layout_k为BSND时shape为(B,S2,N2,D);layout_k为TND时shape为(T2,N2,D);layout_k为PA_BBND时shape为(block_num,block_size,N2,D) | |
| 140 | | weights | Tensor | 必选 | 公式中的权重系数$W$。不支持空tensor。数据格式为ND。 | float16、float32 | layout_q为BSND时shape为(B,S1,N1);layout_q为TND时shape为(T1,N1) | | 140 | | weights | Tensor | 必选 | 公式中的权重系数$W$。不支持空tensor。数据格式为ND。 | float16、float32 | layout_q为BSND时shape为(B,S1,N1);layout_q为TND时shape为(T1,N1) | |
| 141 | -| query_dequant_scale | Tensor | 必选 | 公式中的$Scale_Q$,表示Index Query的反量化系数。不支持空tensor。数据格式为ND。 | float16、float32 | shape与weights保持一致 | | 141 | +| query_dequant_scale | Tensor | 必选 | 公式中的$Scale_Q$,表示Index Query的反量化系数。不支持空tensor。数据格式为ND。 | float16、float32、float8_e8m0 | quant_mode为3/5时,layout_q为BSND时shape为(B,S1,N1,D/64,2),layout_q为TND时shape为(T1,N1,D/64,2);quant_mode为4时shape必须为(1,);其他场景shape与weights保持一致 | |
| 142 | -| key_dequant_scale | Tensor | 必选 | 公式中的$Scale_K$,表示Index Key的反量化系数。不支持空tensor。数据格式为ND,仅PA_BBND场景下0轴支持非连续。 | float16、float32 | layout_k为PA_BBND时shape为(block_num,block_size,N2);layout_k为BSND时shape为(B,S2,N2);layout_k为TND时shape为(T2,N2)。quant_mode为4时shape必须为(1,),表示Per-Tensor量化 | | 142 | +| key_dequant_scale | Tensor | 必选 | 公式中的$Scale_K$,表示Index Key的反量化系数。不支持空tensor。数据格式为ND,仅PA_BBND场景下0轴支持非连续。 | float16、float32、float8_e8m0 | quant_mode为3/5时,layout_k为PA_BBND时shape为(block_num,block_size,N2,D/64,2),layout_k为BSND时shape为(B,S2,N2,D/64,2),layout_k为TND时shape为(T2,N2,D/64,2);quant_mode为4时shape必须为(1,);其他场景分别为(block_num,block_size,N2)、(B,S2,N2)或(T2,N2) | |
| 143 | | topk | int | 必选 | topK阶段需要保留的block数量,当前支持[1, 2048]。 | int32 | - | | 143 | | topk | int | 必选 | topK阶段需要保留的block数量,当前支持[1, 2048]。 | int32 | - | |
| 144 | -| quant_mode | int | 必选 | 表示量化模式,当前仅支持1/2/4。1表示qk: fp8(e4m3fn) per-token-head, scale: fp32;2表示qk: int8 per-token-head, scale: fp16, w: fp16;4表示qk: hifloat8 per-tensor, scale: fp32。 | int32 | - | | 144 | +| quant_mode | int | 必选 | 表示量化模式,当前支持1/2/3/4/5。1表示qk: fp8(e4m3fn) per-token-head, scale: fp32;2表示qk: int8 per-token-head, scale: fp16, w: fp16;3表示qk: mxfp8(e4m3fn), scale: fp8(e8m0);4表示qk: hifloat8 per-tensor, scale: fp32;5表示qk: mxfp4(e2m1), scale: fp8(e8m0)。 | int32 | - | |
| 145 | | cu_seqlens_q | Tensor | 可选 | 当前Batch及前序Batch中query的有效token数的累加和,后一个元素的值必须大于等于前一个元素的值。仅layout_q为TND场景下必传,第一个值固定为0。数据格式为ND。 | int32 | (B+1,) | | 145 | | cu_seqlens_q | Tensor | 可选 | 当前Batch及前序Batch中query的有效token数的累加和,后一个元素的值必须大于等于前一个元素的值。仅layout_q为TND场景下必传,第一个值固定为0。数据格式为ND。 | int32 | (B+1,) | |
| 146 | | cu_seqlens_k | Tensor | 可选 | 当前Batch及前序Batch中key的有效token数的累加和,后一个元素的值必须大于等于前一个元素的值。仅layout_k为TND场景下必传,第一个值固定为0。数据格式为ND。 | int32 | (B+1,) | | 146 | | cu_seqlens_k | Tensor | 可选 | 当前Batch及前序Batch中key的有效token数的累加和,后一个元素的值必须大于等于前一个元素的值。仅layout_k为TND场景下必传,第一个值固定为0。数据格式为ND。 | int32 | (B+1,) | |
| 147 | | seqused_q | Tensor | 可选 | 不同Batch中query的真实使用长度,每个Batch的有效token数不超过query中的维度S大小且不小于0。数据格式为ND。 | int32 | (B,) | | 147 | | seqused_q | Tensor | 可选 | 不同Batch中query的真实使用长度,每个Batch的有效token数不超过query中的维度S大小且不小于0。数据格式为ND。 | int32 | (B,) | |
| @@ -159,8 +159,9 @@ cann_ops_transformer.quant_lightning_indexer( | |||
| 159 | 159 | ||
| 160 | <!-- npu="950" id10 --> | 160 | <!-- npu="950" id10 --> |
| 161 | - <term>Ascend 950PR/Ascend 950DT</term>: | 161 | - <term>Ascend 950PR/Ascend 950DT</term>: |
| 162 | - - query、key在quant_mode为1时支持float8_e4m3fn,quant_mode为4时支持HIfloat8,不支持int8。 | 162 | + - query、key在quant_mode为1/3时支持float8_e4m3fn,quant_mode为4时支持HIfloat8,quant_mode为5时支持float4_e2m1,不支持int8。 |
| 163 | - - weights、query_dequant_scale和key_dequant_scale支持float32,不支持float16。 | 163 | + - query_dequant_scale和key_dequant_scale在quant_mode为3/5时支持float8_e8m0,quant_mode为1/4时支持float32。 |
| 164 | + - weights支持float32,不支持float16。 | ||
| 164 | - query的N支持32或64。 | 165 | - query的N支持32或64。 |
| 165 | <!-- end id10 --> | 166 | <!-- end id10 --> |
| 166 | <!-- npu="A3,910b" id11 --> | 167 | <!-- npu="A3,910b" id11 --> |
| @@ -19,9 +19,59 @@ | |||
| 19 | namespace op_api { | 19 | namespace op_api { |
| 20 | using namespace at_npu::native; | 20 | using namespace at_npu::native; |
| 21 | 21 | ||
| 22 | -inline TensorWrapper MakeWrapper(const at::Tensor &tensor, aclDataType tensorAcltype) | 22 | +inline TensorWrapper MakeWrapper(const at::Tensor &tensor) |
| 23 | { | 23 | { |
| 24 | - return {tensor, tensorAcltype}; | 24 | + return {tensor, ConvertToAclDataType(tensor.scalar_type())}; |
| 25 | +} | ||
| 26 | + | ||
| 27 | +inline bool IsMxQuantMode(int64_t quantMode) { return quantMode == 3 || quantMode == 5; } | ||
| 28 | + | ||
| 29 | +inline bool IsE8M0Tensor(const at::Tensor &tensor) { return tensor.scalar_type() == at::kFloat8_e8m0fnu; } | ||
| 30 | + | ||
| 31 | +inline bool IsFp4CompatibleTensor(const at::Tensor &tensor) | ||
| 32 | +{ | ||
| 33 | + return tensor.scalar_type() == at::kFloat4_e2m1fn_x2 || tensor.scalar_type() == at::kByte; | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +constexpr int64_t E8M0_SCALE_PACK_NUM = 2; | ||
| 37 | + | ||
| 38 | +inline void FixQLIV2AclDtypes(int64_t quantMode, TensorWrapper &queryWrapper, TensorWrapper &keyWrapper, | ||
| 39 | + TensorWrapper &queryScaleWrapper, TensorWrapper &keyScaleWrapper) | ||
| 40 | +{ | ||
| 41 | + if (quantMode == 4) { | ||
| 42 | + TORCH_CHECK(queryWrapper.tensor_.scalar_type() == at::kByte, "When quant_mode is 4, query must be hifp8 type"); | ||
| 43 | + TORCH_CHECK(keyWrapper.tensor_.scalar_type() == at::kByte, "When quant_mode is 4, key must be hifp8 type"); | ||
| 44 | + queryWrapper.dtype = ACL_HIFLOAT8; | ||
| 45 | + keyWrapper.dtype = ACL_HIFLOAT8; | ||
| 46 | + return; | ||
| 47 | + } | ||
| 48 | + | ||
| 49 | + if (quantMode == 5) { | ||
| 50 | + TORCH_CHECK(IsFp4CompatibleTensor(queryWrapper.tensor_), | ||
| 51 | + "When quant_mode is 5, query must be torch.float4_e2m1fn_x2 or packed torch.uint8"); | ||
| 52 | + TORCH_CHECK(IsFp4CompatibleTensor(keyWrapper.tensor_), | ||
| 53 | + "When quant_mode is 5, key must be torch.float4_e2m1fn_x2 or packed torch.uint8"); | ||
| 54 | + queryWrapper.dtype = ACL_FLOAT4_E2M1; | ||
| 55 | + keyWrapper.dtype = ACL_FLOAT4_E2M1; | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + if (IsMxQuantMode(quantMode)) { | ||
| 59 | + TORCH_CHECK(IsE8M0Tensor(queryScaleWrapper.tensor_), | ||
| 60 | + "When quant_mode is 3 or 5, query_dequant_scale must be torch.float8_e8m0fnu"); | ||
| 61 | + TORCH_CHECK(IsE8M0Tensor(keyScaleWrapper.tensor_), | ||
| 62 | + "When quant_mode is 3 or 5, key_dequant_scale must be torch.float8_e8m0fnu"); | ||
| 63 | + // Cube loads E8M0 scales in two-byte groups through a bfloat16_t view. | ||
| 64 | + TORCH_CHECK(queryScaleWrapper.tensor_.storage_offset() % E8M0_SCALE_PACK_NUM == 0, | ||
| 65 | + "When quant_mode is 3 or 5, query_dequant_scale storage offset must satisfy 2-element E8M0 packing " | ||
| 66 | + "alignment, but got ", | ||
| 67 | + queryScaleWrapper.tensor_.storage_offset()); | ||
| 68 | + TORCH_CHECK(keyScaleWrapper.tensor_.storage_offset() % E8M0_SCALE_PACK_NUM == 0, | ||
| 69 | + "When quant_mode is 3 or 5, key_dequant_scale storage offset must satisfy 2-element E8M0 packing " | ||
| 70 | + "alignment, but got ", | ||
| 71 | + keyScaleWrapper.tensor_.storage_offset()); | ||
| 72 | + queryScaleWrapper.dtype = ACL_FLOAT8_E8M0; | ||
| 73 | + keyScaleWrapper.dtype = ACL_FLOAT8_E8M0; | ||
| 74 | + } | ||
| 25 | } | 75 | } |
| 26 | 76 | ||
| 27 | // npu tensor max size | 77 | // npu tensor max size |
| @@ -74,9 +124,9 @@ at::Tensor QuantLightningIndexerMetadata(int64_t numHeadsQ, int64_t numHeadsK, i | |||
| 74 | } | 124 | } |
| 75 | 125 | ||
| 76 | // 工具函数,推导输出shape | 126 | // 工具函数,推导输出shape |
| 77 | -std::tuple<at::Tensor, at::Tensor> | 127 | +std::tuple<at::Tensor, at::Tensor> ConstructQuantLightningIndexerOutputTensor( |
| 78 | -ConstructQuantLightningIndexerOutputTensor(const at::Tensor &query, const at::Tensor &key, int64_t sparseCount, | 128 | + const at::Tensor &query, const at::Tensor &key, int64_t sparseCount, std::string queryLayoutStr, |
| 79 | - std::string queryLayoutStr, std::string keyLayoutStr, int64_t returnValue) | 129 | + std::string keyLayoutStr, int64_t returnValue) |
| 80 | { | 130 | { |
| 81 | at::SmallVector<int64_t, SIZE> outputSize; | 131 | at::SmallVector<int64_t, SIZE> outputSize; |
| 82 | for (size_t i = 0; i < query.sizes().size(); i++) { | 132 | for (size_t i = 0; i < query.sizes().size(); i++) { |
| @@ -111,15 +161,14 @@ ConstructQuantLightningIndexerOutputTensor(const at::Tensor &query, const at::Te | |||
| 111 | return std::tuple<at::Tensor, at::Tensor>(sparseIndicesOut, sparseValuesOut); | 161 | return std::tuple<at::Tensor, at::Tensor>(sparseIndicesOut, sparseValuesOut); |
| 112 | } | 162 | } |
| 113 | 163 | ||
| 114 | -std::tuple<at::Tensor, at::Tensor> | 164 | +std::tuple<at::Tensor, at::Tensor> QuantLightningIndexer( |
| 115 | -QuantLightningIndexer(const at::Tensor &query, const at::Tensor &key, const at::Tensor &weights, | 165 | + const at::Tensor &query, const at::Tensor &key, const at::Tensor &weights, const at::Tensor &queryDequantScale, |
| 116 | - const at::Tensor &queryDequantScale, const at::Tensor &keyDequantScale, int64_t topk, | 166 | + const at::Tensor &keyDequantScale, int64_t topk, int64_t quantMode, const c10::optional<at::Tensor> &cuSeqlensQ, |
| 117 | - int64_t quantMode, const c10::optional<at::Tensor> &cuSeqlensQ, | 167 | + const c10::optional<at::Tensor> &cuSeqlensK, const c10::optional<at::Tensor> &sequsedQ, |
| 118 | - const c10::optional<at::Tensor> &cuSeqlensK, const c10::optional<at::Tensor> &sequsedQ, | 168 | + const c10::optional<at::Tensor> &sequsedK, const c10::optional<at::Tensor> &cmpResidualK, |
| 119 | - const c10::optional<at::Tensor> &sequsedK, const c10::optional<at::Tensor> &cmpResidualK, | 169 | + const c10::optional<at::Tensor> &blockTable, const c10::optional<at::Tensor> &outputIdxOffset, |
| 120 | - const c10::optional<at::Tensor> &blockTable, const c10::optional<at::Tensor> &outputIdxOffset, | 170 | + const c10::optional<at::Tensor> &metadata, int64_t maxSeqlenQ, c10::string_view layoutQ, c10::string_view layoutK, |
| 121 | - const c10::optional<at::Tensor> &metadata, int64_t maxSeqlenQ, c10::string_view layoutQ, | 171 | + int64_t maskMode, int64_t cmpRatio, int64_t returnValue) |
| 122 | - c10::string_view layoutK, int64_t maskMode, int64_t cmpRatio, int64_t returnValue) | ||
| 123 | { | 172 | { |
| 124 | TORCH_CHECK(query.numel() > 0, "Tensor query is empty.") | 173 | TORCH_CHECK(query.numel() > 0, "Tensor query is empty.") |
| 125 | TORCH_CHECK(key.numel() > 0, "Tensor key is empty.") | 174 | TORCH_CHECK(key.numel() > 0, "Tensor key is empty.") |
| @@ -136,22 +185,16 @@ QuantLightningIndexer(const at::Tensor &query, const at::Tensor &key, const at:: | |||
| 136 | char *queryLayoutPtr = const_cast<char *>(queryLayoutStr.c_str()); | 185 | char *queryLayoutPtr = const_cast<char *>(queryLayoutStr.c_str()); |
| 137 | char *keyLayoutPtr = const_cast<char *>(keyLayoutStr.c_str()); | 186 | char *keyLayoutPtr = const_cast<char *>(keyLayoutStr.c_str()); |
| 138 | 187 | ||
| 139 | - if (quantMode == 4) { | 188 | + auto queryWrapper = MakeWrapper(query); |
| 140 | - // hifp8接收数据类型为Uint8 | 189 | + auto keyWrapper = MakeWrapper(key); |
| 141 | - TORCH_CHECK(query.scalar_type() == at::kByte, "When quant_mode is 4, query must be hifp8 type"); | 190 | + auto queryScaleWrapper = MakeWrapper(queryDequantScale); |
| 142 | - TORCH_CHECK(key.scalar_type() == at::kByte, "When quant_mode is 4, key must be hifp8 type"); | 191 | + auto keyScaleWrapper = MakeWrapper(keyDequantScale); |
| 143 | - TensorWrapper queryWrapper = MakeWrapper(query, ACL_HIFLOAT8); | 192 | + FixQLIV2AclDtypes(quantMode, queryWrapper, keyWrapper, queryScaleWrapper, keyScaleWrapper); |
| 144 | - TensorWrapper keyWrapper = MakeWrapper(key, ACL_HIFLOAT8); | 193 | + |
| 145 | - ACLNN_CMD(aclnnQuantLightningIndexerV2, queryWrapper, keyWrapper, weights, queryDequantScale, keyDequantScale, | 194 | + ACLNN_CMD(aclnnQuantLightningIndexerV2, queryWrapper, keyWrapper, weights, queryScaleWrapper, keyScaleWrapper, |
| 146 | - cuSeqlensQ, cuSeqlensK, sequsedQ, sequsedK, cmpResidualK, blockTable, outputIdxOffset, metadata, topk, | 195 | + cuSeqlensQ, cuSeqlensK, sequsedQ, sequsedK, cmpResidualK, blockTable, outputIdxOffset, metadata, topk, |
| 147 | - quantMode, maxSeqlenQ, queryLayoutPtr, keyLayoutPtr, maskMode, cmpRatio, returnValue, | 196 | + quantMode, maxSeqlenQ, queryLayoutPtr, keyLayoutPtr, maskMode, cmpRatio, returnValue, sparseIndicesOut, |
| 148 | - sparseIndicesOut, sparseValuesOut); | 197 | + sparseValuesOut); |
| 149 | - } else { | ||
| 150 | - ACLNN_CMD(aclnnQuantLightningIndexerV2, query, key, weights, queryDequantScale, keyDequantScale, cuSeqlensQ, | ||
| 151 | - cuSeqlensK, sequsedQ, sequsedK, cmpResidualK, blockTable, outputIdxOffset, metadata, topk, quantMode, | ||
| 152 | - maxSeqlenQ, queryLayoutPtr, keyLayoutPtr, maskMode, cmpRatio, returnValue, sparseIndicesOut, | ||
| 153 | - sparseValuesOut); | ||
| 154 | - } | ||
| 155 | 198 | ||
| 156 | return std::tuple<at::Tensor, at::Tensor>(sparseIndicesOut, sparseValuesOut); | 199 | return std::tuple<at::Tensor, at::Tensor>(sparseIndicesOut, sparseValuesOut); |
| 157 | } | 200 | } |