Merged
fix(operation): Change scaleA/B to per-batch when using scaleMM+BatchMatmul. #5571
yang_rAdd on Aug 20
fix(operation): Change scaleA/B to per-batch when using scaleMM+BatchMatmul. #5571
Merged
yang_rAdd on Aug 20
Total: 6 files changed+391-111
@@ -53,6 +53,18 @@ inline bool CheckValidShape(const LogicalTensorPtr& tensorPtr)
53 return tensorPtr->GetDynValidShape().size() == SHAPE_DIM2;53 return tensorPtr->GetDynValidShape().size() == SHAPE_DIM2;
shi-dingkun

描述里把文档修改去掉

likedislike
54}54}
55 55 
56+static void CheckDynValidShapeDim(const Tensor& tensor, const std::string& tensorName)
57+{
58+ if (tensor.GetStorage() == nullptr) {
59+ return;
60+ }
61+ const auto shapeDim = tensor.GetShape().size();
62+ const auto validShapeDim = tensor.GetStorage()->GetDynValidShape().size();
63+ CHECK(ExternalError::INVALID_SHAPE, validShapeDim == shapeDim)
64+ << tensorName << " valid shape dimension must equal shape dimension. valid shape dimension: " << validShapeDim
65+ << ", shape dimension: " << shapeDim;
66+}
67+ 
56inline size_t GetAlignSize(DataType dataType)68inline size_t GetAlignSize(DataType dataType)
57{69{
58 bool isB4 = std::find(FP4_TYPES.begin(), FP4_TYPES.end(), dataType) != FP4_TYPES.end();70 bool isB4 = std::find(FP4_TYPES.begin(), FP4_TYPES.end(), dataType) != FP4_TYPES.end();
@@ -511,7 +523,9 @@ void CheckBiasShapeParam(const Tensor& operand2, bool transB, const MatmulExtend
511 CHECK(ExternalError::INVALID_FORMAT, param.biasTensor.Format() == TileOpFormat::TILEOP_ND)523 CHECK(ExternalError::INVALID_FORMAT, param.biasTensor.Format() == TileOpFormat::TILEOP_ND)
512 << "Only support TILEOP_ND.";524 << "Only support TILEOP_ND.";
513 const Shape biasShape = param.biasTensor.GetShape();525 const Shape biasShape = param.biasTensor.GetShape();
514- CHECK(ExternalError::INVALID_SHAPE, biasShape.size() > 1 && biasShape[biasShape.size() - SHAPE_DIM2] == 1)526+ CHECK(ExternalError::INVALID_SHAPE, biasShape.size() >= SHAPE_DIM2)
527+ << "Bias tensor shape must have at least " << SHAPE_DIM2 << " dimensions, got " << biasShape.size();
528+ CHECK(ExternalError::INVALID_SHAPE, biasShape[biasShape.size() - SHAPE_DIM2] == 1)
515 << "Bias tensor shape of the penultimate dimension mismatch: "529 << "Bias tensor shape of the penultimate dimension mismatch: "
516 << "Expected shape of the penultimate dimension to be 1, got " << biasShape[biasShape.size() - SHAPE_DIM2];530 << "Expected shape of the penultimate dimension to be 1, got " << biasShape[biasShape.size() - SHAPE_DIM2];
517 const Shape bShape = operand2.GetShape();531 const Shape bShape = operand2.GetShape();
@@ -608,7 +622,9 @@ void CheckFixpipeParam(const Tensor& operand2, DataType outDtype, bool transB, c
608 "outDtype to be DT_INT8.";622 "outDtype to be DT_INT8.";
609 623 
610 const Shape scaleShape = param.scaleTensor.GetShape();624 const Shape scaleShape = param.scaleTensor.GetShape();
611- CHECK(ExternalError::INVALID_SHAPE, scaleShape.size() > 1 && scaleShape[scaleShape.size() - SHAPE_DIM2] == 1)625+ CHECK(ExternalError::INVALID_SHAPE, scaleShape.size() >= SHAPE_DIM2)
626+ << "Scale tensor shape must have at least " << SHAPE_DIM2 << " dimensions, got " << scaleShape.size();
627+ CHECK(ExternalError::INVALID_SHAPE, scaleShape[scaleShape.size() - SHAPE_DIM2] == 1)
612 << "Scale tensor shape of the penultimate dimension mismatch. "628 << "Scale tensor shape of the penultimate dimension mismatch. "
613 << "Expected shape of the penultimate dimension to be 1, got "629 << "Expected shape of the penultimate dimension to be 1, got "
614 << scaleShape[scaleShape.size() - SHAPE_DIM2];630 << scaleShape[scaleShape.size() - SHAPE_DIM2];
@@ -744,6 +760,8 @@ Status CheckMatmulOperands(DataType outType, const Tensor& operand1, const Tenso
744 // output NZ format valid check760 // output NZ format valid check
745 CheckCMatrixNZFormatAligned(outType, operand2, attrParam);761 CheckCMatrixNZFormatAligned(outType, operand2, attrParam);
746 // bias and scale valid check762 // bias and scale valid check
763+ CheckDynValidShapeDim(param.biasTensor, "biasTensor");
764+ CheckDynValidShapeDim(param.scaleTensor, "scaleTensor");
747 if (Platform::Instance().GetSoc().GetNPUArch() == NPUArch::DAV_3510) {765 if (Platform::Instance().GetSoc().GetNPUArch() == NPUArch::DAV_3510) {
748 CheckA5BiasParam(operand2, attrParam.transB, param);766 CheckA5BiasParam(operand2, attrParam.transB, param);
749 } else {767 } else {
@@ -759,29 +777,64 @@ Status CheckMatmulOperands(DataType outType, const Tensor& operand1, const Tenso
759void CheckMXMatmulShape(const Tensor& aTensor, const Tensor& aScaleTensor, const Tensor& bTensor,777void CheckMXMatmulShape(const Tensor& aTensor, const Tensor& aScaleTensor, const Tensor& bTensor,
760 const Tensor& bScaleTensor, const MatmulAttrParam& attrParam)778 const Tensor& bScaleTensor, const MatmulAttrParam& attrParam)
761{779{
762- CHECK(ExternalError::INVALID_SHAPE,780+ const int64_t aTensorDim = aTensor.GetShape().size();
763- aScaleTensor.GetShape().size() == SHAPE_DIM3 && bScaleTensor.GetShape().size() == SHAPE_DIM3)781+ const int64_t bTensorDim = bTensor.GetShape().size();
764- << "The dimension of scaleTensor for mxmatmul must be equal to 3! The dimension of ascaleTensor: "782+ CHECK(ExternalError::INVALID_SHAPE, aTensorDim >= SHAPE_DIM2 && aTensorDim <= SHAPE_DIM4)
765- << aScaleTensor.GetShape().size() << ", The dimension of bscaleTensor: " << bScaleTensor.GetShape().size();783+ << "The dimension of aTensor must be 2, 3 or 4 for mxmatmul! Current dim: " << aTensorDim;
784+ CHECK(ExternalError::INVALID_SHAPE, bTensorDim == aTensorDim)
785+ << "The dimensions of aTensor and bTensor must be equal. aTensor dim: " << aTensorDim
786+ << ", bTensor dim: " << bTensorDim;
766 787 
767- CHECK(ExternalError::INVALID_SHAPE, aTensor.GetShape().size() >= 2)788+ const int64_t expectedScaleDim = aTensorDim + 1;
768- << "aTensor dimension must be >= 2 for matmul! Current dim: " << aTensor.GetShape().size();789+ const int64_t aScaleTensorDim = aScaleTensor.GetShape().size();
769- CHECK(ExternalError::INVALID_SHAPE, bTensor.GetShape().size() >= 2)790+ const int64_t bScaleTensorDim = bScaleTensor.GetShape().size();
770- << "bTensor dimension must be >= 2 for matmul! Current dim: " << bTensor.GetShape().size();791+ CHECK(ExternalError::INVALID_SHAPE, aScaleTensorDim == expectedScaleDim && bScaleTensorDim == expectedScaleDim)
792+ << "For mxmatmul, the scale tensor must have one more dimension than the input tensor. Expected: "
793+ << expectedScaleDim << ", aScaleTensor dim: " << aScaleTensorDim << ", bScaleTensor dim: " << bScaleTensorDim;
771 794 
772- const int64_t aDimOffset = aTensor.GetShape().size() - 2;795+ const int64_t aTensorValidDim = aTensor.GetStorage()->GetDynValidShape().size();
773- const int64_t bDimOffset = bTensor.GetShape().size() - 2;796+ const int64_t bTensorValidDim = bTensor.GetStorage()->GetDynValidShape().size();
797+ CHECK(ExternalError::INVALID_SHAPE, aTensorValidDim == aTensorDim && bTensorValidDim == bTensorDim)
798+ << "MX operand valid shape dim must equal shape dim. aTensor valid=" << aTensorValidDim
799+ << " shape=" << aTensorDim << ", bTensor valid=" << bTensorValidDim << " shape=" << bTensorDim;
800+ const int64_t aScaleValidDim = aScaleTensor.GetStorage()->GetDynValidShape().size();
801+ const int64_t bScaleValidDim = bScaleTensor.GetStorage()->GetDynValidShape().size();
802+ CHECK(ExternalError::INVALID_SHAPE, aScaleValidDim == expectedScaleDim && bScaleValidDim == expectedScaleDim)
803+ << "MX scale valid shape dim must equal shape dim. aScale valid=" << aScaleValidDim
804+ << " shape=" << expectedScaleDim << ", bScale valid=" << bScaleValidDim << " shape=" << expectedScaleDim;
774 805 
775- int64_t mSize = attrParam.transA ? aTensor.GetShape()[aDimOffset + 1] : aTensor.GetShape()[aDimOffset];806+ const int64_t batchDim = aTensorDim - SHAPE_DIM2;
776- int64_t nSize = attrParam.transB ? bTensor.GetShape()[bDimOffset] : bTensor.GetShape()[bDimOffset + 1];807+ for (int64_t batchIdx = 0; batchIdx < batchDim; ++batchIdx) {
777- int64_t kSize = attrParam.transA ? aTensor.GetShape()[aDimOffset] : aTensor.GetShape()[aDimOffset + 1];808+ const int64_t aBatchSize = aTensor.GetShape()[batchIdx];
809+ const int64_t bBatchSize = bTensor.GetShape()[batchIdx];
810+ CHECK(ExternalError::INVALID_SHAPE, aScaleTensor.GetShape()[batchIdx] == aBatchSize)
811+ << "aScaleTensor batch axis " << batchIdx
812+ << " must equal the paired aTensor batch axis. Expected: " << aBatchSize
813+ << ", but got: " << aScaleTensor.GetShape()[batchIdx];
814+ CHECK(ExternalError::INVALID_SHAPE, bScaleTensor.GetShape()[batchIdx] == bBatchSize)
815+ << "bScaleTensor batch axis " << batchIdx
816+ << " must equal the paired bTensor batch axis. Expected: " << bBatchSize
817+ << ", but got: " << bScaleTensor.GetShape()[batchIdx];
818+ }
778 819 
779- int64_t mScaleSize = attrParam.transAScale ? aScaleTensor.GetShape()[1] : aScaleTensor.GetShape()[0];820+ const int64_t aDimIndex = aTensorDim - SHAPE_DIM2;
780- int64_t kAScaleSize0 = attrParam.transAScale ? aScaleTensor.GetShape()[0] : aScaleTensor.GetShape()[1];821+ const int64_t bDimIndex = bTensorDim - SHAPE_DIM2;
781- int64_t kAScaleSize1 = aScaleTensor.GetShape()[SHAPE_DIM2];822+ const int64_t scaleDimIndex = expectedScaleDim - SHAPE_DIM3;
782- int64_t kBScaleSize0 = attrParam.transBScale ? bScaleTensor.GetShape()[1] : bScaleTensor.GetShape()[0];823+ 
783- int64_t kBScaleSize1 = bScaleTensor.GetShape()[SHAPE_DIM2];824+ int64_t mSize = attrParam.transA ? aTensor.GetShape()[aDimIndex + 1] : aTensor.GetShape()[aDimIndex];
784- int64_t nScaleSize = attrParam.transBScale ? bScaleTensor.GetShape()[0] : bScaleTensor.GetShape()[1];825+ int64_t nSize = attrParam.transB ? bTensor.GetShape()[bDimIndex] : bTensor.GetShape()[bDimIndex + 1];
826+ int64_t kSize = attrParam.transA ? aTensor.GetShape()[aDimIndex] : aTensor.GetShape()[aDimIndex + 1];
827+ 
828+ int64_t mScaleSize = attrParam.transAScale ? aScaleTensor.GetShape()[scaleDimIndex + 1] :
829+ aScaleTensor.GetShape()[scaleDimIndex];
830+ int64_t kAScaleSize0 = attrParam.transAScale ? aScaleTensor.GetShape()[scaleDimIndex] :
831+ aScaleTensor.GetShape()[scaleDimIndex + 1];
832+ int64_t kAScaleSize1 = aScaleTensor.GetShape()[scaleDimIndex + SHAPE_DIM2];
833+ int64_t kBScaleSize0 = attrParam.transBScale ? bScaleTensor.GetShape()[scaleDimIndex + 1] :
834+ bScaleTensor.GetShape()[scaleDimIndex];
835+ int64_t kBScaleSize1 = bScaleTensor.GetShape()[scaleDimIndex + SHAPE_DIM2];
836+ int64_t nScaleSize = attrParam.transBScale ? bScaleTensor.GetShape()[scaleDimIndex] :
837+ bScaleTensor.GetShape()[scaleDimIndex + 1];
785 838 
786 CHECK(ExternalError::INVALID_SHAPE, kAScaleSize0 == kBScaleSize0)839 CHECK(ExternalError::INVALID_SHAPE, kAScaleSize0 == kBScaleSize0)
787 << "Scale Matrix K dimension mismatch, kAScaleSize: " << kAScaleSize0 << ", kBScaleSize: " << kBScaleSize0;840 << "Scale Matrix K dimension mismatch, kAScaleSize: " << kAScaleSize0 << ", kBScaleSize: " << kBScaleSize0;
@@ -1996,6 +2049,52 @@ Tensor BatchMatmul(DataType dataType, const Tensor& aMatrix, const Tensor& bMatr
1996 }2049 }
1997}2050}
1998 2051 
2052+Tensor GetBatchScaleTensor3D(int64_t batchSize, int64_t bIdx, const Tensor& scale,
2053+ std::vector<SymbolicScalar>& validShape4D)
2054+{
2055+ const Shape& scaleShape = scale.GetShape();
2056+ const int64_t offsetBatch = batchSize == 1 ? 0 : bIdx;
2057+ const Shape singleBatchShape = {1, scaleShape[1], scaleShape[SHAPE_DIM2], scaleShape[SHAPE_DIM3]};
2058+ Tensor scaleSingleBatch = View(scale, singleBatchShape,
2059+ GetViewValidShape(validShape4D, {offsetBatch, 0, 0, 0}, {}, singleBatchShape),
2060+ {offsetBatch, 0, 0, 0});
2061+ ASSERT(MatmulErrorCode::ERR_RUNTIME_NULLPTR, scaleSingleBatch.GetStorage() != nullptr)
2062+ << "scaleSingleBatch 3D of View result must not be null";
2063+ auto singleBatchValidShape = scaleSingleBatch.GetStorage()->GetDynValidShape();
2064+ const auto batchValid = singleBatchValidShape[0];
2065+ Tensor scale3D = Reshape(scaleSingleBatch, {scaleShape[1], scaleShape[SHAPE_DIM2], scaleShape[SHAPE_DIM3]},
2066+ std::vector<SymbolicScalar>({batchValid * singleBatchValidShape[1],
2067+ batchValid * singleBatchValidShape[SHAPE_DIM2],
2068+ batchValid * singleBatchValidShape[SHAPE_DIM3]}));
2069+ ASSERT(MatmulErrorCode::ERR_RUNTIME_NULLPTR, scale3D.GetStorage() != nullptr)
2070+ << "scaleSingleBatch 3D of Reshape result must not be null";
2071+ return scale3D;
2072+}
2073+ 
2074+Tensor GetBatchScaleTensor4D(int64_t batchSize1, int64_t batchSize2, int64_t bIdx1, int64_t bIdx2, const Tensor& scale,
2075+ std::vector<SymbolicScalar>& validShape5D)
2076+{
2077+ const Shape& scaleShape = scale.GetShape();
2078+ const int64_t offsetBatch1 = batchSize1 == 1 ? 0 : bIdx1;
2079+ const int64_t offsetBatch2 = batchSize2 == 1 ? 0 : bIdx2;
2080+ const Shape singleBatchShape = {1, 1, scaleShape[SHAPE_DIM2], scaleShape[SHAPE_DIM3], scaleShape[SHAPE_DIM4]};
2081+ Tensor scaleSingleBatch = View(
2082+ scale, singleBatchShape,
2083+ GetViewValidShape(validShape5D, {offsetBatch1, offsetBatch2, 0, 0, 0}, {}, singleBatchShape),
2084+ {offsetBatch1, offsetBatch2, 0, 0, 0});
2085+ ASSERT(MatmulErrorCode::ERR_RUNTIME_NULLPTR, scaleSingleBatch.GetStorage() != nullptr)
2086+ << "scaleSingleBatch 4D of View result must not be null";
2087+ auto singleBatchValidShape = scaleSingleBatch.GetStorage()->GetDynValidShape();
2088+ const auto batchValid = singleBatchValidShape[0] * singleBatchValidShape[1];
2089+ Tensor scale3D = Reshape(scaleSingleBatch, {scaleShape[SHAPE_DIM2], scaleShape[SHAPE_DIM3], scaleShape[SHAPE_DIM4]},
2090+ std::vector<SymbolicScalar>({batchValid * singleBatchValidShape[SHAPE_DIM2],
2091+ batchValid * singleBatchValidShape[SHAPE_DIM3],
2092+ batchValid * singleBatchValidShape[SHAPE_DIM4]}));
2093+ ASSERT(MatmulErrorCode::ERR_RUNTIME_NULLPTR, scale3D.GetStorage() != nullptr)
2094+ << "scaleSingleBatch 4D of Reshape result must not be null";
2095+ return scale3D;
2096+}
2097+ 
1999Tensor ConstructBatchMatmulMXTensorGraph3D(DataType dataType, const Tensor& aMatrix, const Tensor& aScale,2098Tensor ConstructBatchMatmulMXTensorGraph3D(DataType dataType, const Tensor& aMatrix, const Tensor& aScale,
2000 const Tensor& bMatrix, const Tensor& bScale,2099 const Tensor& bMatrix, const Tensor& bScale,
2001 const MatmulAttrParam& attrParam, const MatmulExtendParam& param = {})2100 const MatmulAttrParam& attrParam, const MatmulExtendParam& param = {})
@@ -2022,6 +2121,8 @@ Tensor ConstructBatchMatmulMXTensorGraph3D(DataType dataType, const Tensor& aMat
2022 for (int64_t bIdx = 0; bIdx < batchSize; bIdx++) {2121 for (int64_t bIdx = 0; bIdx < batchSize; bIdx++) {
2023 auto [aTensor, aTensorSingleBatch] = GetBatchTensor3D(batchSizeA, bIdx, aMatrix, aValidShape3D);2122 auto [aTensor, aTensorSingleBatch] = GetBatchTensor3D(batchSizeA, bIdx, aMatrix, aValidShape3D);
2024 auto [bTensor, bTensorSingleBatch] = GetBatchTensor3D(batchSizeB, bIdx, bMatrix, bValidShape3D);2123 auto [bTensor, bTensorSingleBatch] = GetBatchTensor3D(batchSizeB, bIdx, bMatrix, bValidShape3D);
2124+ Tensor aScaleTensor = GetBatchScaleTensor3D(batchSizeA, bIdx, aScale, aScaleValidShape4D);
2125+ Tensor bScaleTensor = GetBatchScaleTensor3D(batchSizeB, bIdx, bScale, bScaleValidShape4D);
2025 2126 
2026 const auto bValid = batchSizeA == 1 ? bTensorSingleBatch.GetStorage()->GetDynValidShape()[0] :2127 const auto bValid = batchSizeA == 1 ? bTensorSingleBatch.GetStorage()->GetDynValidShape()[0] :
2027 aTensorSingleBatch.GetStorage()->GetDynValidShape()[0];2128 aTensorSingleBatch.GetStorage()->GetDynValidShape()[0];
@@ -2050,8 +2151,8 @@ Tensor ConstructBatchMatmulMXTensorGraph3D(DataType dataType, const Tensor& aMat
2050 }2151 }
2051 batchParam.reluType = param.reluType;2152 batchParam.reluType = param.reluType;
2052 batchParam.scaleValue = param.scaleValue;2153 batchParam.scaleValue = param.scaleValue;
2053- MatmulGraphNodes tensorGraphNodes(aTensor.GetStorage(), aScale.GetStorage(), bTensor.GetStorage(),2154+ MatmulGraphNodes tensorGraphNodes(aTensor.GetStorage(), aScaleTensor.GetStorage(), bTensor.GetStorage(),
2054- bScale.GetStorage());2155+ bScaleTensor.GetStorage());
2055 tensorGraphNodes.outTensorPtr = cTensor.GetStorage();2156 tensorGraphNodes.outTensorPtr = cTensor.GetStorage();
2056 AddAMulBNode(tensorGraphNodes, attrParam, batchParam);2157 AddAMulBNode(tensorGraphNodes, attrParam, batchParam);
2057 ASSERT(MatmulErrorCode::ERR_RUNTIME_NULLPTR, cTensor.GetStorage() != nullptr)2158 ASSERT(MatmulErrorCode::ERR_RUNTIME_NULLPTR, cTensor.GetStorage() != nullptr)
@@ -2098,6 +2199,10 @@ Tensor ConstructBatchMatmulMXTensorGraph4D(DataType dataType, const Tensor& aMat
2098 aValidShape4D);2199 aValidShape4D);
2099 auto [bTensor, bTensorSingleBatch] = GetBatchTensor4D(batchSizeB1, batchSizeB2, bIdx1, bIdx2, bMatrix,2200 auto [bTensor, bTensorSingleBatch] = GetBatchTensor4D(batchSizeB1, batchSizeB2, bIdx1, bIdx2, bMatrix,
2100 bValidShape4D);2201 bValidShape4D);
2202+ Tensor aScaleTensor = GetBatchScaleTensor4D(batchSizeA1, batchSizeA2, bIdx1, bIdx2, aScale,
2203+ aScaleValidShape5D);
2204+ Tensor bScaleTensor = GetBatchScaleTensor4D(batchSizeB1, batchSizeB2, bIdx1, bIdx2, bScale,
2205+ bScaleValidShape5D);
2101 2206 
2102 const auto b0Valid = batchSizeA1 == 1 ? bTensorSingleBatch.GetStorage()->GetDynValidShape()[0] :2207 const auto b0Valid = batchSizeA1 == 1 ? bTensorSingleBatch.GetStorage()->GetDynValidShape()[0] :
2103 aTensorSingleBatch.GetStorage()->GetDynValidShape()[0];2208 aTensorSingleBatch.GetStorage()->GetDynValidShape()[0];
@@ -2115,8 +2220,8 @@ Tensor ConstructBatchMatmulMXTensorGraph4D(DataType dataType, const Tensor& aMat
2115 batchParam.scaleValue = param.scaleValue;2220 batchParam.scaleValue = param.scaleValue;
2116 Tensor cTensor(dataType, {mView, nView}, "cTensorSingleBatch");2221 Tensor cTensor(dataType, {mView, nView}, "cTensorSingleBatch");
2117 cTensor.GetStorage()->UpdateDynValidShape({b0Valid * b1Valid * mValid, nValid});2222 cTensor.GetStorage()->UpdateDynValidShape({b0Valid * b1Valid * mValid, nValid});
2118- MatmulGraphNodes tensorGraphNodes(aTensor.GetStorage(), aScale.GetStorage(), bTensor.GetStorage(),2223+ MatmulGraphNodes tensorGraphNodes(aTensor.GetStorage(), aScaleTensor.GetStorage(), bTensor.GetStorage(),
2119- bScale.GetStorage());2224+ bScaleTensor.GetStorage());
2120 tensorGraphNodes.outTensorPtr = cTensor.GetStorage();2225 tensorGraphNodes.outTensorPtr = cTensor.GetStorage();
2121 AddAMulBNode(tensorGraphNodes, attrParam, batchParam);2226 AddAMulBNode(tensorGraphNodes, attrParam, batchParam);
2122 ASSERT(MatmulErrorCode::ERR_RUNTIME_NULLPTR, cTensor.GetStorage() != nullptr)2227 ASSERT(MatmulErrorCode::ERR_RUNTIME_NULLPTR, cTensor.GetStorage() != nullptr)
@@ -135,9 +135,9 @@ TEST_F(MatmulOperationTest, Test_BatchMatmulMX_Bias_3D)
135 Platform::Instance().ReloadMemoryPaths("3510");135 Platform::Instance().ReloadMemoryPaths("3510");
136 TileShape::Current().SetCubeTile({128, 128}, {128, 128}, {128, 128});136 TileShape::Current().SetCubeTile({128, 128}, {128, 128}, {128, 128});
137 Tensor matA(DT_FP8E5M2, {2, 128, 256}, "matA");137 Tensor matA(DT_FP8E5M2, {2, 128, 256}, "matA");
138- Tensor matB(DT_FP8E5M2, {2, 256, 128}, "matB");138+ Tensor matB(DT_FP8E5M2, {1, 256, 128}, "matB");
139- Tensor scaleA(DT_FP8E8M0, {128, 4, 2}, "scaleA");139+ Tensor scaleA(DT_FP8E8M0, {2, 128, 4, 2}, "scaleA");
140- Tensor scaleB(DT_FP8E8M0, {4, 128, 2}, "scaleB");140+ Tensor scaleB(DT_FP8E8M0, {1, 4, 128, 2}, "scaleB");
141 Tensor matBias(DT_BF16, {1, 128}, "biasA");141 Tensor matBias(DT_BF16, {1, 128}, "biasA");
142 Tensor result;142 Tensor result;
143 Matrix::MatmulExtendParam extendParam;143 Matrix::MatmulExtendParam extendParam;
@@ -154,10 +154,10 @@ TEST_F(MatmulOperationTest, Test_BatchMatmulMX_Bias_4D)
154 Platform::Instance().GetSoc().SetNPUArch(NPUArch::DAV_3510);154 Platform::Instance().GetSoc().SetNPUArch(NPUArch::DAV_3510);
155 Platform::Instance().ReloadMemoryPaths("3510");155 Platform::Instance().ReloadMemoryPaths("3510");
156 TileShape::Current().SetCubeTile({128, 128}, {128, 128}, {128, 128});156 TileShape::Current().SetCubeTile({128, 128}, {128, 128}, {128, 128});
157- Tensor matA(DT_FP8E5M2, {2, 2, 128, 256}, "matA");157+ Tensor matA(DT_FP8E5M2, {2, 1, 128, 256}, "matA");
158- Tensor matB(DT_FP8E5M2, {2, 2, 256, 128}, "matB");158+ Tensor matB(DT_FP8E5M2, {1, 3, 256, 128}, "matB");
159- Tensor scaleA(DT_FP8E8M0, {128, 4, 2}, "scaleA");159+ Tensor scaleA(DT_FP8E8M0, {2, 1, 128, 4, 2}, "scaleA");
160- Tensor scaleB(DT_FP8E8M0, {4, 128, 2}, "scaleB");160+ Tensor scaleB(DT_FP8E8M0, {1, 3, 4, 128, 2}, "scaleB");
161 Tensor matBias(DT_BF16, {1, 128}, "biasA");161 Tensor matBias(DT_BF16, {1, 128}, "biasA");
162 Tensor result;162 Tensor result;
163 Matrix::MatmulExtendParam extendParam;163 Matrix::MatmulExtendParam extendParam;
@@ -161,15 +161,15 @@ def scaled_mm(
161 """161 """
162 Performs matrix multiplication with support for transposition, and extended features like bias addition.162 Performs matrix multiplication with support for transposition, and extended features like bias addition.
163 163 
164- Supports one primary computation modes:164+ `mat_a` and `mat_b` can be 2-D, 3-D or 4-D. Their batch dimensions support broadcasting.
165- 1. Standard matrix multiplication of two matrices.
166 165 
167- `mat_a` and `mat_b` can be 2-D.166+ `scale_a` and `scale_b` must have one more dimension than the matrix inputs. The batch dimensions of `scale_a`
168- - If `mat_a` is (n x k) and `mat_b` is (k x m), output is (n x m).167+ must equal those of `mat_a`, and the batch dimensions of `scale_b` must equal those of `mat_b`. Each matrix and
169- 168+ its paired scale use the same batch broadcasting index.
170- `scale_a` and `scale_b` can be 3-D.169+ - 2-D matrices use 3-D scales: (m, kScale, 2) and (kScale, n, 2).
171- - If `mat_a` is (n x k), `scale_a` is (n x kScale x 2)170+ - 3-D matrices use 4-D scales: (batchA, m, kScale, 2) and (batchB, kScale, n, 2).
172- - If `mat_b` is (k x m), `scale_b` is (kScale x m x 2)171+ - 4-D matrices use 5-D scales: (batchA0, batchA1, m, kScale, 2) and
172+ (batchB0, batchB1, kScale, n, 2).
173 173 
174 Parameters174 Parameters
175 ----------175 ----------
@@ -209,8 +209,8 @@ def scaled_mm(
209 Raises209 Raises
210 ------210 ------
211 RuntimeError211 RuntimeError
212- If mat_a and mat_b dimensions are invalid (!=2-D), or scale_a and scale_b dimensions are invalid (!=3-D),212+ If matrix or scale dimensions are invalid, scale batch dimensions do not equal their paired matrix batch
213- or if matrix dimensions are incompatible.213+ dimensions, or matrix dimensions are incompatible.
214 214 
215 Examples215 Examples
216 --------216 --------
@@ -228,23 +228,37 @@ def scaled_mm(
228 b_scale = pypto.tensor((2, 64, 2), pypto.DT_FP8E8M0, "scale_b")228 b_scale = pypto.tensor((2, 64, 2), pypto.DT_FP8E8M0, "scale_b")
229 bias = pypto.tensor((1, 64), pypto.DT_FP16, "tensor_bias")229 bias = pypto.tensor((1, 64), pypto.DT_FP16, "tensor_bias")
230 extend_params = {'bias_tensor': bias}230 extend_params = {'bias_tensor': bias}
231- pypto.scaled_mm(a, b, pypto.DT_FP16, extend_params=extend_params)231+ pypto.scaled_mm(a, b, pypto.DT_FP16, a_scale, b_scale, extend_params=extend_params)
232+ 
233+ # 3-D broadcasting: A and scale_a share batch 1; B and scale_b share batch 4
234+ a = pypto.tensor((1, 16, 128), pypto.DT_FP8E4M3, "tensor_a")
235+ b = pypto.tensor((4, 128, 64), pypto.DT_FP8E4M3, "tensor_b")
236+ a_scale = pypto.tensor((1, 16, 2, 2), pypto.DT_FP8E8M0, "scale_a")
237+ b_scale = pypto.tensor((4, 2, 64, 2), pypto.DT_FP8E8M0, "scale_b")
238+ pypto.scaled_mm(a, b, pypto.DT_BF16, a_scale, b_scale)
239+ 
240+ # 4-D cross broadcasting: each scale follows its paired matrix batch shape
241+ a = pypto.tensor((2, 1, 16, 128), pypto.DT_FP8E4M3, "tensor_a")
242+ b = pypto.tensor((1, 3, 128, 64), pypto.DT_FP8E4M3, "tensor_b")
243+ a_scale = pypto.tensor((2, 1, 16, 2, 2), pypto.DT_FP8E8M0, "scale_a")
244+ b_scale = pypto.tensor((1, 3, 2, 64, 2), pypto.DT_FP8E8M0, "scale_b")
245+ pypto.scaled_mm(a, b, pypto.DT_BF16, a_scale, b_scale)
232 246 
233 # Standard batch matrix multiplication247 # Standard batch matrix multiplication
234 a = pypto.tensor((3, 16, 128), pypto.DT_FP8E4M3, "tensor_a")248 a = pypto.tensor((3, 16, 128), pypto.DT_FP8E4M3, "tensor_a")
235 b = pypto.tensor((3, 128, 64), pypto.DT_FP8E4M3, "tensor_b")249 b = pypto.tensor((3, 128, 64), pypto.DT_FP8E4M3, "tensor_b")
236- a_scale = pypto.tensor((16, 2, 2), pypto.DT_FP8E8M0, "scale_a")250+ a_scale = pypto.tensor((3, 16, 2, 2), pypto.DT_FP8E8M0, "scale_a")
237- b_scale = pypto.tensor((2, 64, 2), pypto.DT_FP8E8M0, "scale_b")251+ b_scale = pypto.tensor((3, 2, 64, 2), pypto.DT_FP8E8M0, "scale_b")
238 pypto.scaled_mm(a, b, pypto.DT_BF16, a_scale, b_scale)252 pypto.scaled_mm(a, b, pypto.DT_BF16, a_scale, b_scale)
239 253 
240 # Standard batch matrix with bias addition254 # Standard batch matrix with bias addition
241 a = pypto.tensor((3, 16, 128), pypto.DT_FP8E4M3, "tensor_a")255 a = pypto.tensor((3, 16, 128), pypto.DT_FP8E4M3, "tensor_a")
242 b = pypto.tensor((3, 128, 64), pypto.DT_FP8E4M3, "tensor_b")256 b = pypto.tensor((3, 128, 64), pypto.DT_FP8E4M3, "tensor_b")
243- a_scale = pypto.tensor((16, 2, 2), pypto.DT_FP8E8M0, "scale_a")257+ a_scale = pypto.tensor((3, 16, 2, 2), pypto.DT_FP8E8M0, "scale_a")
244- b_scale = pypto.tensor((2, 64, 2), pypto.DT_FP8E8M0, "scale_b")258+ b_scale = pypto.tensor((3, 2, 64, 2), pypto.DT_FP8E8M0, "scale_b")
245 bias = pypto.tensor((1, 64), pypto.DT_FP16, "tensor_bias")259 bias = pypto.tensor((1, 64), pypto.DT_FP16, "tensor_bias")
246 extend_params = {'bias_tensor': bias}260 extend_params = {'bias_tensor': bias}
247- pypto.scaled_mm(a, b, pypto.DT_FP16, extend_params=extend_params)261+ pypto.scaled_mm(a, b, pypto.DT_FP16, a_scale, b_scale, extend_params=extend_params)
248 """262 """
249 __validate_inputs(mat_a, mat_b, out_dtype, [a_trans, b_trans, c_matrix_nz, extend_params])263 __validate_inputs(mat_a, mat_b, out_dtype, [a_trans, b_trans, c_matrix_nz, extend_params])
250 __validate_scaled_inputs(mat_a, mat_b, scale_a, scale_b, extend_params)264 __validate_scaled_inputs(mat_a, mat_b, scale_a, scale_b, extend_params)
@@ -442,7 +456,6 @@ def __validate_scaled_inputs(input_tensor1, input_tensor2, input_scale1, input_s
442 scale_a_dim = input_scale1.Dim()456 scale_a_dim = input_scale1.Dim()
443 scale_b_dim = input_scale2.Dim()457 scale_b_dim = input_scale2.Dim()
444 supported_dims = (2, 3, 4)458 supported_dims = (2, 3, 4)
445- shape_dim_3 = 3
446 459 
447 if (460 if (
448 input_tensor1.GetDataType() == pypto_impl.DataType.DT_FP4_E1M2461 input_tensor1.GetDataType() == pypto_impl.DataType.DT_FP4_E1M2
@@ -464,11 +477,13 @@ def __validate_scaled_inputs(input_tensor1, input_tensor2, input_scale1, input_s
464 f"got input_dim: {input_dim}, other_dim: {other_dim}."477 f"got input_dim: {input_dim}, other_dim: {other_dim}."
465 ),478 ),
466 )479 )
467- if scale_a_dim != scale_b_dim or scale_a_dim != shape_dim_3:480+ expected_scale_dim = input_dim + 1
481+ if scale_a_dim != scale_b_dim or scale_a_dim != expected_scale_dim:
468 raise PyptoError(482 raise PyptoError(
469 0xF00003,483 0xF00003,
470 RuntimeError(484 RuntimeError(
471- "Tensor dimension mismatch. Expect scale_a_dim == scale_b_dim and both equal to 3, "485+ "Tensor dimension mismatch. Expect scale_a_dim == scale_b_dim and both equal to input_dim + 1 "
486+ f"({expected_scale_dim}), "
472 f"got scale_a_dim: {scale_a_dim}, scale_b_dim: {scale_b_dim}."487 f"got scale_a_dim: {scale_a_dim}, scale_b_dim: {scale_b_dim}."
473 ),488 ),
474 )489 )
@@ -492,15 +507,37 @@ def __validate_scaled_shape(input_tensor1, input_tensor2, input_scale1, input_sc
492 n_dim = (other_valid_shape[-1]) if not b_trans else (other_valid_shape[-2])507 n_dim = (other_valid_shape[-1]) if not b_trans else (other_valid_shape[-2])
493 scale1_valid_shape = __get_valid_shape(input_scale1)508 scale1_valid_shape = __get_valid_shape(input_scale1)
494 scale2_valid_shape = __get_valid_shape(input_scale2)509 scale2_valid_shape = __get_valid_shape(input_scale2)
510+ input_shape = input_tensor1.GetShape()
511+ other_shape = input_tensor2.GetShape()
512+ scale1_shape = input_scale1.GetShape()
513+ scale2_shape = input_scale2.GetShape()
514+ batch_dim = input_tensor1.Dim() - 2
515+ for batch_idx in range(batch_dim):
516+ if scale1_shape[batch_idx] != input_shape[batch_idx]:
517+ raise PyptoError(
518+ 0xF00003,
519+ RuntimeError(
520+ f"Scale batch dimension mismatch at axis {batch_idx}. Expected scale_a batch dimension to "
521+ f"equal paired mat_a batch dimension {input_shape[batch_idx]}, got {scale1_shape[batch_idx]}."
522+ ),
523+ )
524+ if scale2_shape[batch_idx] != other_shape[batch_idx]:
525+ raise PyptoError(
526+ 0xF00003,
527+ RuntimeError(
528+ f"Scale batch dimension mismatch at axis {batch_idx}. Expected scale_b batch dimension to "
529+ f"equal paired mat_b batch dimension {other_shape[batch_idx]}, got {scale2_shape[batch_idx]}."
530+ ),
531+ )
495 m_scale_dim, k_a_scale0_dim, k_a_scale1_dim = (532 m_scale_dim, k_a_scale0_dim, k_a_scale1_dim = (
496- (scale1_valid_shape[0], scale1_valid_shape[1], scale1_valid_shape[shape_dim_2])533+ (scale1_valid_shape[-3], scale1_valid_shape[-2], scale1_valid_shape[-1])
497 if not a_scale_trans534 if not a_scale_trans
498- else (scale1_valid_shape[1], scale1_valid_shape[0], scale1_valid_shape[shape_dim_2])535+ else (scale1_valid_shape[-2], scale1_valid_shape[-3], scale1_valid_shape[-1])
499 )536 )
500 k_b_scale0_dim, n_scale_dim, k_b_scale1_dim = (537 k_b_scale0_dim, n_scale_dim, k_b_scale1_dim = (
501- (scale2_valid_shape[0], scale2_valid_shape[1], scale2_valid_shape[shape_dim_2])538+ (scale2_valid_shape[-3], scale2_valid_shape[-2], scale2_valid_shape[-1])
502 if not b_scale_trans539 if not b_scale_trans
503- else (scale2_valid_shape[1], scale2_valid_shape[0], scale2_valid_shape[shape_dim_2])540+ else (scale2_valid_shape[-2], scale2_valid_shape[-3], scale2_valid_shape[-1])
504 )541 )
505 542 
506 __validate_scale_k0_dimensions(k_a_scale0_dim, k_b_scale0_dim)543 __validate_scale_k0_dimensions(k_a_scale0_dim, k_b_scale0_dim)
@@ -523,13 +560,16 @@ def __validate_scale_k0_dimensions(k_a_scale0_dim, k_b_scale0_dim):
523 560 
524def __validate_scale_k1_dimensions(k_a_scale1_dim, k_b_scale1_dim, shape_dim_2):561def __validate_scale_k1_dimensions(k_a_scale1_dim, k_b_scale1_dim, shape_dim_2):
525 is_value_concrete = k_a_scale1_dim.is_concrete() and k_b_scale1_dim.is_concrete()562 is_value_concrete = k_a_scale1_dim.is_concrete() and k_b_scale1_dim.is_concrete()
526- if is_value_concrete and k_a_scale1_dim != k_b_scale1_dim and k_a_scale1_dim != shape_dim_2:563+ if is_value_concrete and (
564+ k_a_scale1_dim != k_b_scale1_dim
565+ or k_a_scale1_dim != shape_dim_2
566+ or k_b_scale1_dim != shape_dim_2
567+ ):
527 raise PyptoError(568 raise PyptoError(
528 0xF00003,569 0xF00003,
529 RuntimeError(570 RuntimeError(
530- "Scale Matrix Kscale1 dimension mismatch. Expect scale_a_shape[2] == scale_b_shape[2] "571+ "Scale Matrix Kscale1 dimension mismatch. Expect the last dimensions of scale_a and scale_b "
531- f"and both equal to 2, got scale_a_shape[2]: {k_a_scale1_dim}, "572+ f"to both equal 2, got scale_a: {k_a_scale1_dim}, scale_b: {k_b_scale1_dim}."
532- f"scale_b_shape[2]: {k_b_scale1_dim}."
533 ),573 ),
534 )574 )
535 575 
@@ -189,14 +189,34 @@ def get_tensor_views_3d(params: TensorViewParams3D):
189 b_view = params.b_tensor[batch_b_start:batch_b_end, 0:params.k, params.n_offset:params.n_offset + params.vn]189 b_view = params.b_tensor[batch_b_start:batch_b_end, 0:params.k, params.n_offset:params.n_offset + params.vn]
190 190 
191 if params.config.scale_a_trans:191 if params.config.scale_a_trans:
192- scale_a_view = params.scale_a_tensor[0:params.scale_k, params.m_offset:params.m_offset + params.vm, :]192+ scale_a_view = params.scale_a_tensor[
193+ batch_a_start:batch_a_end,
194+ 0:params.scale_k,
195+ params.m_offset:params.m_offset + params.vm,
196+ :,
197+ ]
193 else:198 else:
194- scale_a_view = params.scale_a_tensor[params.m_offset:params.m_offset + params.vm, 0:params.scale_k, :]199+ scale_a_view = params.scale_a_tensor[
200+ batch_a_start:batch_a_end,
201+ params.m_offset:params.m_offset + params.vm,
202+ 0:params.scale_k,
203+ :,
204+ ]
195 205 
196 if params.config.scale_b_trans:206 if params.config.scale_b_trans:
197- scale_b_view = params.scale_b_tensor[params.n_offset:params.n_offset + params.vn, 0:params.scale_k, :]207+ scale_b_view = params.scale_b_tensor[
208+ batch_b_start:batch_b_end,
209+ params.n_offset:params.n_offset + params.vn,
210+ 0:params.scale_k,
211+ :,
212+ ]
198 else:213 else:
199- scale_b_view = params.scale_b_tensor[0:params.scale_k, params.n_offset:params.n_offset + params.vn, :]214+ scale_b_view = params.scale_b_tensor[
215+ batch_b_start:batch_b_end,
216+ 0:params.scale_k,
217+ params.n_offset:params.n_offset + params.vn,
218+ :,
219+ ]
200 220 
201 return a_view, b_view, scale_a_view, scale_b_view221 return a_view, b_view, scale_a_view, scale_b_view
202 222 
@@ -291,7 +311,7 @@ def d3_kernel_common(params: ScaledBmmKernelParams, config):
291 tile_b, vm, vn = config.view_shape311 tile_b, vm, vn = config.view_shape
292 m_loop, n_loop = (output_m + vm - 1) // vm, (output_n + vn - 1) // vn312 m_loop, n_loop = (output_m + vm - 1) // vm, (output_n + vn - 1) // vn
293 batch_loop = (batch + tile_b - 1) // tile_b313 batch_loop = (batch + tile_b - 1) // tile_b
294- scale_k = k // K_BLOCK_SIZE_64314+ scale_k = (k + K_BLOCK_SIZE_64 - 1) // K_BLOCK_SIZE_64
295 315 
296 pypto.set_vec_tile_shapes(config.m_tile_shape[0], config.n_tile_shape[0])316 pypto.set_vec_tile_shapes(config.m_tile_shape[0], config.n_tile_shape[0])
297 pypto.set_matrix_size([output_m, k, output_n])317 pypto.set_matrix_size([output_m, k, output_n])
@@ -433,13 +453,37 @@ def get_4d_tensor_views(params: TensorViewParams4D):
433 params.n_offset:params.n_offset + params.vn,453 params.n_offset:params.n_offset + params.vn,
434 ]454 ]
435 if params.config.scale_a_trans:455 if params.config.scale_a_trans:
436- scale_a_view = params.scale_a_tensor[0:params.scale_k, params.m_offset:params.m_offset + params.vm, :]456+ scale_a_view = params.scale_a_tensor[
457+ batch_a_outer_start:batch_a_outer_end,
458+ batch_a_inner_start:batch_a_inner_end,
459+ 0:params.scale_k,
460+ params.m_offset:params.m_offset + params.vm,
461+ :,
462+ ]
437 else:463 else:
438- scale_a_view = params.scale_a_tensor[params.m_offset:params.m_offset + params.vm, 0:params.scale_k, :]464+ scale_a_view = params.scale_a_tensor[
465+ batch_a_outer_start:batch_a_outer_end,
466+ batch_a_inner_start:batch_a_inner_end,
467+ params.m_offset:params.m_offset + params.vm,
468+ 0:params.scale_k,
469+ :,
470+ ]
439 if params.config.scale_b_trans:471 if params.config.scale_b_trans:
440- scale_b_view = params.scale_b_tensor[params.n_offset:params.n_offset + params.vn, 0:params.scale_k, :]472+ scale_b_view = params.scale_b_tensor[
473+ batch_b_outer_start:batch_b_outer_end,
474+ batch_b_inner_start:batch_b_inner_end,
475+ params.n_offset:params.n_offset + params.vn,
476+ 0:params.scale_k,
477+ :,
478+ ]
441 else:479 else:
442- scale_b_view = params.scale_b_tensor[0:params.scale_k, params.n_offset:params.n_offset + params.vn, :]480+ scale_b_view = params.scale_b_tensor[
481+ batch_b_outer_start:batch_b_outer_end,
482+ batch_b_inner_start:batch_b_inner_end,
483+ 0:params.scale_k,
484+ params.n_offset:params.n_offset + params.vn,
485+ :,
486+ ]
443 return a_view, b_view, scale_a_view, scale_b_view487 return a_view, b_view, scale_a_view, scale_b_view
444 488 
445 489 
@@ -458,7 +502,7 @@ def d4_kernel_common(params: ScaledBmmKernelParams, config):
458 m_loop, n_loop = (output_m + vm - 1) // vm, (output_n + vn - 1) // vn502 m_loop, n_loop = (output_m + vm - 1) // vm, (output_n + vn - 1) // vn
459 batch_outer_loop = (b0 + tile_b0 - 1) // tile_b0503 batch_outer_loop = (b0 + tile_b0 - 1) // tile_b0
460 batch_inner_loop = (b1 + tile_b1 - 1) // tile_b1504 batch_inner_loop = (b1 + tile_b1 - 1) // tile_b1
461- scale_k = k // K_BLOCK_SIZE_64505+ scale_k = (k + K_BLOCK_SIZE_64 - 1) // K_BLOCK_SIZE_64
462 506 
463 pypto.set_vec_tile_shapes(config.m_tile_shape[0], config.n_tile_shape[0])507 pypto.set_vec_tile_shapes(config.m_tile_shape[0], config.n_tile_shape[0])
464 pypto.set_matrix_size([output_m, k, output_n])508 pypto.set_matrix_size([output_m, k, output_n])
@@ -496,8 +540,12 @@ def scaled_bmm_kernel_3d_no_bias(
496 a_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),540 a_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),
497 b_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),541 b_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),
498 out_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),542 out_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),
499- scale_a_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0),543+ scale_a_tensor: pypto.Tensor(
500- scale_b_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0),544+ [pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0
545+ ),
546+ scale_b_tensor: pypto.Tensor(
547+ [pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0
548+ ),
501 scale_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC]),549 scale_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC]),
502 config: ScaledBmmConfig,550 config: ScaledBmmConfig,
503):551):
@@ -518,8 +566,12 @@ def scaled_bmm_kernel_3d_bias_1n(
518 a_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),566 a_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),
519 b_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),567 b_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),
520 out_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),568 out_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),
521- scale_a_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0),569+ scale_a_tensor: pypto.Tensor(
522- scale_b_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0),570+ [pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0
571+ ),
572+ scale_b_tensor: pypto.Tensor(
573+ [pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0
574+ ),
523 bias_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC]),575 bias_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC]),
524 scale_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC]),576 scale_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC]),
525 config: ScaledBmmConfig,577 config: ScaledBmmConfig,
@@ -541,8 +593,12 @@ def scaled_bmm_kernel_3d_bias_b1n(
541 a_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),593 a_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),
542 b_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),594 b_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),
543 out_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),595 out_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),
544- scale_a_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0),596+ scale_a_tensor: pypto.Tensor(
545- scale_b_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0),597+ [pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0
598+ ),
599+ scale_b_tensor: pypto.Tensor(
600+ [pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0
601+ ),
546 bias_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),602 bias_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC]),
547 scale_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC]),603 scale_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC]),
548 config: ScaledBmmConfig,604 config: ScaledBmmConfig,
@@ -564,8 +620,12 @@ def scaled_bmm_kernel_4d_no_bias(
564 a_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC]),620 a_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC]),
565 b_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC]),621 b_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC]),
566 out_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC]),622 out_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC]),
567- scale_a_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0),623+ scale_a_tensor: pypto.Tensor(
568- scale_b_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0),624+ [pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0
625+ ),
626+ scale_b_tensor: pypto.Tensor(
627+ [pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0
628+ ),
569 scale_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC]),629 scale_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC]),
570 config: ScaledBmmConfig,630 config: ScaledBmmConfig,
571):631):
@@ -586,8 +646,12 @@ def scaled_bmm_kernel_4d_bias_1n(
586 a_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC]),646 a_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC]),
587 b_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC]),647 b_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC]),
588 out_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC]),648 out_tensor: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC]),
589- scale_a_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0),649+ scale_a_tensor: pypto.Tensor(
590- scale_b_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0),650+ [pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0
651+ ),
652+ scale_b_tensor: pypto.Tensor(
653+ [pypto.DYNAMIC, pypto.STATIC, pypto.STATIC, pypto.STATIC, pypto.STATIC], dtype=pypto.DT_FP8E8M0
654+ ),
591 bias_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC]),655 bias_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC]),
592 scale_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC]),656 scale_tensor: pypto.Tensor([pypto.STATIC, pypto.STATIC]),
593 config: ScaledBmmConfig,657 config: ScaledBmmConfig,
@@ -606,48 +670,39 @@ def scaled_bmm_kernel_4d_bias_1n(
606 670 
607def _process_scale_tensors(scale_a_cpu, scale_b_cpu, config):671def _process_scale_tensors(scale_a_cpu, scale_b_cpu, config):
608 if len(config.a_shape) == 3:672 if len(config.a_shape) == 3:
609- b, m, k, n = config.get_logical_dims_3d()673+ _, m, k, n = config.get_logical_dims_3d()
610 else:674 else:
611- b0, b1, m, k, n = config.get_logical_dims_4d()675+ _, _, m, k, n = config.get_logical_dims_4d()
612 676 
613 scale_k_32 = k // K_BLOCK_SIZE_32677 scale_k_32 = k // K_BLOCK_SIZE_32
678+ scale_a_batch_shape = scale_a_cpu.shape[:-3]
679+ scale_b_batch_shape = scale_b_cpu.shape[:-3]
614 680 
615 if config.scale_b_trans:681 if config.scale_b_trans:
616- scale_b_tmp = scale_b_cpu.view(n, scale_k_32).T682+ scale_b_tmp = scale_b_cpu.reshape(*scale_b_batch_shape, n, scale_k_32).transpose(-2, -1)
617 else:683 else:
618- scale_b_tmp = torch.transpose(scale_b_cpu, -2, -1).reshape(scale_k_32, n)684+ scale_b_tmp = torch.transpose(scale_b_cpu, -2, -1).reshape(*scale_b_batch_shape, scale_k_32, n)
619 685 
620 if config.scale_a_trans:686 if config.scale_a_trans:
621- scale_a_tmp = torch.transpose(scale_a_cpu, -2, -1).reshape(scale_k_32, m).T687+ scale_a_tmp = torch.transpose(scale_a_cpu, -2, -1).reshape(
688+ *scale_a_batch_shape, scale_k_32, m
689+ ).transpose(-2, -1)
622 else:690 else:
623- scale_a_tmp = scale_a_cpu.view(m, scale_k_32)691+ scale_a_tmp = scale_a_cpu.reshape(*scale_a_batch_shape, m, scale_k_32)
624 692 
625- scale_a_tmp = scale_a_tmp.to(torch.float32).repeat_interleave(32, dim=1)693+ scale_a_tmp = scale_a_tmp.to(torch.float32).repeat_interleave(32, dim=-1)
626- scale_b_tmp = scale_b_tmp.to(torch.float32).repeat_interleave(32, dim=0)694+ scale_b_tmp = scale_b_tmp.to(torch.float32).repeat_interleave(32, dim=-2)
627 695 
628 return scale_a_tmp, scale_b_tmp696 return scale_a_tmp, scale_b_tmp
629 697 
630 698 
631def _compute_golden(params: GoldenComputeParams):699def _compute_golden(params: GoldenComputeParams):
632 config = params.config700 config = params.config
633- k = config.get_logical_dims_3d()[2] if len(config.a_shape) == 3 else config.get_logical_dims_4d()[3]
634- scale_k_32 = k // K_BLOCK_SIZE_32
635 output_m = config.out_shape[-2]701 output_m = config.out_shape[-2]
636 output_n = config.out_shape[-1]702 output_n = config.out_shape[-1]
637 padding_m = abs(output_m - params.m)703 padding_m = abs(output_m - params.m)
638 padding_n = abs(output_n - params.n)704 padding_n = abs(output_n - params.n)
639- if config.scale_b_trans:705+ scale_a_tmp, scale_b_tmp = _process_scale_tensors(params.scale_a_cpu, params.scale_b_cpu, config)
640- scale_b_tmp = params.scale_b_cpu.view(params.n, scale_k_32).T
641- else:
642- scale_b_tmp = torch.transpose(params.scale_b_cpu, -2, -1).reshape(scale_k_32, params.n)
643- 
644- if config.scale_a_trans:
645- scale_a_tmp = torch.transpose(params.scale_a_cpu, -2, -1).reshape(scale_k_32, params.m).T
646- else:
647- scale_a_tmp = params.scale_a_cpu.view(params.m, scale_k_32)
648- 
649- scale_a_tmp = scale_a_tmp.to(torch.float32).repeat_interleave(32, dim=1)
650- scale_b_tmp = scale_b_tmp.to(torch.float32).repeat_interleave(32, dim=0)
651 706 
652 mat_a_tmp = (707 mat_a_tmp = (
653 params.mat_a_cpu.to(torch.float32).transpose(-2, -1) if config.a_trans else params.mat_a_cpu.to(torch.float32)708 params.mat_a_cpu.to(torch.float32).transpose(-2, -1) if config.a_trans else params.mat_a_cpu.to(torch.float32)
@@ -689,9 +744,11 @@ def prepare_inputs(config: ScaledBmmConfig, device_id: int):
689 b = max(b0, b1)744 b = max(b0, b1)
690 745 
691 output_n = out_shape[-1]746 output_n = out_shape[-1]
692- scale_k = k // K_BLOCK_SIZE_64747+ scale_k = (k + K_BLOCK_SIZE_64 - 1) // K_BLOCK_SIZE_64
693- scale_a_shape = [scale_k, m, SHAPE_DIM_2] if config.scale_a_trans else [m, scale_k, SHAPE_DIM_2]748+ scale_a_tail_shape = [scale_k, m, SHAPE_DIM_2] if config.scale_a_trans else [m, scale_k, SHAPE_DIM_2]
694- scale_b_shape = [n, scale_k, SHAPE_DIM_2] if config.scale_b_trans else [scale_k, n, SHAPE_DIM_2]749+ scale_b_tail_shape = [n, scale_k, SHAPE_DIM_2] if config.scale_b_trans else [scale_k, n, SHAPE_DIM_2]
750+ scale_a_shape = list(config.a_shape[:-2]) + scale_a_tail_shape
751+ scale_b_shape = list(config.b_shape[:-2]) + scale_b_tail_shape
695 752 
696 torch_in_dtype = ScaledBmmConfig.pto_to_torch(config.in_dtype)753 torch_in_dtype = ScaledBmmConfig.pto_to_torch(config.in_dtype)
697 mat_a_cpu = torch.rand(list(config.a_shape), dtype=torch.float32).uniform_(-3, 3).to(torch_in_dtype)754 mat_a_cpu = torch.rand(list(config.a_shape), dtype=torch.float32).uniform_(-3, 3).to(torch_in_dtype)
@@ -863,8 +920,12 @@ def run_scaled_bmm_demo(run_mode):
863 920 
864 a_view = a_tensor[b_offset:b_offset + b_view_size, m_offset:m_offset + vm_view_size, :]921 a_view = a_tensor[b_offset:b_offset + b_view_size, m_offset:m_offset + vm_view_size, :]
865 b_view = b_tensor[b_offset:b_offset + b_view_size, :, n_offset:n_offset + vn_view_size]922 b_view = b_tensor[b_offset:b_offset + b_view_size, :, n_offset:n_offset + vn_view_size]
866- scale_a_view = scale_a_tensor[m_offset:m_offset + vm_view_size, :, :]923+ scale_a_view = scale_a_tensor[
867- scale_b_view = scale_b_tensor[:, n_offset:n_offset + vn_view_size, :]924+ b_offset:b_offset + b_view_size, m_offset:m_offset + vm_view_size, :, :
925+ ]
926+ scale_b_view = scale_b_tensor[
927+ b_offset:b_offset + b_view_size, :, n_offset:n_offset + vn_view_size, :
928+ ]
868 929 
869 out_view = pypto.scaled_mm(930 out_view = pypto.scaled_mm(
870 a_view,931 a_view,
@@ -888,8 +949,18 @@ def run_scaled_bmm_demo(run_mode):
888 device = "npu:0" if run_mode == "npu" else "cpu"949 device = "npu:0" if run_mode == "npu" else "cpu"
889 a = torch.randn([b_size, m_size, k_size], dtype=torch.float32).uniform_(-3, 3).to(torch.float8_e4m3fn).to(device)950 a = torch.randn([b_size, m_size, k_size], dtype=torch.float32).uniform_(-3, 3).to(torch.float8_e4m3fn).to(device)
890 b = torch.randn([b_size, k_size, n_size], dtype=torch.float32).uniform_(-3, 3).to(torch.float8_e4m3fn).to(device)951 b = torch.randn([b_size, k_size, n_size], dtype=torch.float32).uniform_(-3, 3).to(torch.float8_e4m3fn).to(device)
891- scale_a = torch.randn([m_size, scale_k, 2], dtype=torch.float32).uniform_(0, 1).to(torch.float8_e8m0fnu).to(device)952+ scale_a = (
892- scale_b = torch.randn([scale_k, n_size, 2], dtype=torch.float32).uniform_(0, 1).to(torch.float8_e8m0fnu).to(device)953+ torch.randn([b_size, m_size, scale_k, 2], dtype=torch.float32)
954+ .uniform_(0, 1)
955+ .to(torch.float8_e8m0fnu)
956+ .to(device)
957+ )
958+ scale_b = (
959+ torch.randn([b_size, scale_k, n_size, 2], dtype=torch.float32)
960+ .uniform_(0, 1)
961+ .to(torch.float8_e8m0fnu)
962+ .to(device)
963+ )
893 out = torch.zeros([b_size, m_size, n_size], dtype=torch.float16).to(device)964 out = torch.zeros([b_size, m_size, n_size], dtype=torch.float16).to(device)
894 scaled_bmm_demo_kernel(a, b, out, scale_a, scale_b)965 scaled_bmm_demo_kernel(a, b, out, scale_a, scale_b)
895 966 
@@ -170,8 +170,8 @@ SCALED_BMM_TESTS = [
170 {170 {
171 "id": "BMM3D_BIAS_1N_UNALIGN",171 "id": "BMM3D_BIAS_1N_UNALIGN",
172 "name": "scaled_bmm_3d_bias_1n",172 "name": "scaled_bmm_3d_bias_1n",
173- "a_shape": [5, 135, 192],173+ "a_shape": [1, 135, 192],
174- "b_shape": [1, 192, 351],174+ "b_shape": [5, 192, 351],
175 "out_shape": [5, 135, 351],175 "out_shape": [5, 135, 351],
176 "m_tile_shape": [64, 128],176 "m_tile_shape": [64, 128],
177 "k_tile_shape": [64, 256],177 "k_tile_shape": [64, 256],
@@ -195,7 +195,7 @@ SCALED_BMM_TESTS = [
195 {195 {
196 "id": "BMM4D_BIAS_UNALIGN_QUANT_PERCHENNEL",196 "id": "BMM4D_BIAS_UNALIGN_QUANT_PERCHENNEL",
197 "name": "scaled_bmm_4d_bias_quant_perchennel",197 "name": "scaled_bmm_4d_bias_quant_perchennel",
198- "a_shape": [2, 3, 383, 320],198+ "a_shape": [2, 1, 383, 320],
199 "b_shape": [1, 3, 178, 320],199 "b_shape": [1, 3, 178, 320],
200 "out_shape": [2, 3, 384, 178],200 "out_shape": [2, 3, 384, 178],
201 "m_tile_shape": [128, 256],201 "m_tile_shape": [128, 256],
@@ -0,0 +1,64 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""Batch scale shape validation tests for pypto.scaled_mm."""
12+ 
13+from contextlib import contextmanager
14+ 
15+import pytest
16+ 
17+import pypto
18+from pypto.error import PyptoError
19+ 
20+ 
21+@contextmanager
22+def npuarch(arch: str):
23+ try:
24+ old_arch = pypto.platform.npuarch
25+ pypto.platform.npuarch = arch
26+ yield
27+ finally:
28+ pypto.platform.npuarch = old_arch
29+ 
30+ 
31+@npuarch("DAV_3510")
32+def test_scaled_mm_3d_rejects_shared_scale():
33+ mat_a = pypto.tensor([2, 16, 128], pypto.DT_FP8E4M3, "mat_a")
34+ mat_b = pypto.tensor([2, 128, 32], pypto.DT_FP8E4M3, "mat_b")
35+ scale_a = pypto.tensor([16, 2, 2], pypto.DT_FP8E8M0, "scale_a")
36+ scale_b = pypto.tensor([2, 32, 2], pypto.DT_FP8E8M0, "scale_b")
37+ 
38+ with pytest.raises(PyptoError, match=r"input_dim \+ 1 \(4\)"):
39+ pypto.scaled_mm(mat_a, mat_b, pypto.DT_FP16, scale_a, scale_b)
40+ 
41+ 
42+@npuarch("DAV_3510")
43+def test_scaled_mm_4d_accepts_paired_scale_batch_shape():
44+ mat_a = pypto.tensor([2, 1, 16, 128], pypto.DT_FP8E4M3, "mat_a")
45+ mat_b = pypto.tensor([1, 3, 128, 32], pypto.DT_FP8E4M3, "mat_b")
46+ scale_a = pypto.tensor([2, 1, 16, 2, 2], pypto.DT_FP8E8M0, "scale_a")
47+ scale_b = pypto.tensor([1, 3, 2, 32, 2], pypto.DT_FP8E8M0, "scale_b")
48+ 
49+ with pypto.function("SCALED_MM_BATCH", mat_a, mat_b):
50+ pypto.set_cube_tile_shapes([32, 32],[128, 128],[32, 32])
51+ result = pypto.scaled_mm(mat_a, mat_b, pypto.DT_FP16, scale_a, scale_b)
52+ 
53+ assert result.shape == [2, 3, 16, 32]
54+ 
55+ 
56+@npuarch("DAV_3510")
57+def test_scaled_mm_4d_rejects_output_batch_scale_shape():
58+ mat_a = pypto.tensor([2, 1, 16, 128], pypto.DT_FP8E4M3, "mat_a")
59+ mat_b = pypto.tensor([1, 3, 128, 32], pypto.DT_FP8E4M3, "mat_b")
60+ scale_a = pypto.tensor([2, 3, 16, 2, 2], pypto.DT_FP8E8M0, "scale_a")
61+ scale_b = pypto.tensor([1, 3, 2, 32, 2], pypto.DT_FP8E8M0, "scale_b")
62+ 
63+ with pytest.raises(PyptoError, match="Scale batch dimension mismatch at axis 1"):
64+ pypto.scaled_mm(mat_a, mat_b, pypto.DT_FP16, scale_a, scale_b)