* Copyright (c) 2025 Huawei Technologies Co., Ltd.
* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
* CANN Open Software License Agreement Version 2.0 (the "License").
* Please refer to the License for details. You may not use this file except in compliance with the License.
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
* See LICENSE in the root of the software repository for the full text of the License.
*/
* \file binary.cpp
* \brief
*/
#include "tilefwk/data_type.h"
#include "unary.h"
#include "binary.h"
#include "binary_tiled.h"
#include "tensor_transformation.h"
#include "interface/utils/operator_tracer.h"
#include "interface/configs/config_manager.h"
#include "tilefwk/error_code.h"
#include "passes/tile_graph_pass/graph_constraint/axis_combine.h"
namespace npu::tile_fwk {
std::vector<int64_t> BinaryOperationResultShape(LogicalTensorPtr operand1, LogicalTensorPtr operand2)
{
std::vector<int64_t> resultShape(operand1->shape.size());
for (size_t i = 0; i < resultShape.size(); i++) {
resultShape[i] = std::max(operand1->shape[i], operand2->shape[i]);
}
return resultShape;
}
LogicalTensorPtr BinaryOperationBroadCast(const LogicalTensorPtr& operand, const std::vector<int>& broadCastShape)
{
if (operand->shape.size() < broadCastShape.size()) {
auto broadCastDims = broadCastShape.size() - operand->shape.size();
std::vector<int64_t> unsqueezeShape(operand->shape);
unsqueezeShape.insert(unsqueezeShape.begin(), broadCastDims, 1);
auto tmpOperand = Reshape(operand, unsqueezeShape).GetStorage();
return tmpOperand;
}
return operand;
}
void CheckOperandsValid(const LogicalTensorPtr& operand1, const LogicalTensorPtr& operand2)
{
CHECK(VectorErrorCode::ERR_PARAM_INVALID, operand1->shape.size() == operand2->shape.size())
<< "The shape size of the two input tensors must be equal";
}
void CheckBinOpOperandsValid(const LogicalTensorPtr& operand1, const LogicalTensorPtr& operand2)
{
CheckOperandsValid(operand1, operand2);
for (size_t i = 0; i < operand1->shape.size(); ++i) {
if (operand1->shape[i] != operand2->shape[i] && (operand1->shape[i] != 1 && operand2->shape[i] != 1)) {
CHECK(VectorErrorCode::ERR_PARAM_INVALID, false) << "shape not support binary operation";
}
}
}
void BroadcastOperandTensor(LogicalTensorPtr& operand, LogicalTensorPtr& other, LogicalTensorPtr result,
Function& function, const TileShape& tileShape, std::vector<int64_t> dstShape)
{
if (dstShape.empty()) {
dstShape = result->shape;
}
if (operand->shape == dstShape) {
return;
}
auto expanded = std::make_shared<LogicalTensor>(function, operand->Datatype(), dstShape);
Expand(function, tileShape, operand, {other}, expanded);
operand = expanded;
}
void BinaryOperationOperandCheck(const std::vector<LogicalTensorPtr>& iOperand,
const std::vector<LogicalTensorPtr>& oOperand)
{
constexpr size_t inOpSize = NUM_VALUE_2;
constexpr size_t outOpSize = 1;
CHECK(VectorErrorCode::ERR_PARAM_INVALID, iOperand.size() == inOpSize) << "iOperand size should be 2";
CHECK(VectorErrorCode::ERR_PARAM_INVALID, oOperand.size() == outOpSize) << "oOperand size should be 1";
}
int BrcAxisBinaryOp(LogicalTensorPtr operand1, LogicalTensorPtr operand2, int64_t axisNum)
{
CHECK(VectorErrorCode::ERR_PARAM_INVALID, operand1->shape.size() == operand2->shape.size()) << "Dims not match";
int64_t shapeSize = operand1->shape.size();
int operandNum = 0;
int64_t idx = (axisNum < 0) ? (shapeSize + axisNum) : axisNum;
CHECK(VectorErrorCode::ERR_PARAM_INVALID, idx >= 0 && idx < shapeSize)
<< "axisNum " << axisNum << " out of range for shapeSize " << shapeSize;
if ((operand1->shape[idx] != 1) && (operand2->shape[idx] == 1)) {
operandNum = NUM_VALUE_2;
} else if ((operand1->shape[idx] == 1) && (operand2->shape[idx] != 1)) {
operandNum = 1;
}
return operandNum;
}
Tensor Add(const Tensor& self, const Tensor& other)
{
DECLARE_TRACER();
CheckVectorOperand(self.GetStorage(), "Add");
CheckVectorOperand(other.GetStorage(), "Add");
const auto& combinations = ConfigManager::Instance().GetOpSupportedInputDtypes(Opcode::OP_ADD);
CheckTensorDataTypeCombination({self.GetDataType(), other.GetDataType()}, combinations, "ADD");
RETURN_CALL(BinaryOperation<BinaryOpType::ADD>, *Program::GetInstance().GetCurrentFunction(), self, other);
}
Tensor Sub(const Tensor& self, const Tensor& other)
{
DECLARE_TRACER();
CheckVectorOperand(self.GetStorage(), "Sub");
CheckVectorOperand(other.GetStorage(), "Sub");
const auto& combinations = ConfigManager::Instance().GetOpSupportedInputDtypes(Opcode::OP_SUB);
CheckTensorDataTypeCombination({self.GetDataType(), other.GetDataType()}, combinations, "SUB");
RETURN_CALL(BinaryOperation<BinaryOpType::SUB>, *Program::GetInstance().GetCurrentFunction(), self, other);
}
Tensor Mul(const Tensor& self, const Tensor& other)
{
DECLARE_TRACER();
CheckVectorOperand(self.GetStorage(), "Mul");
CheckVectorOperand(other.GetStorage(), "Mul");
const auto& combinations = ConfigManager::Instance().GetOpSupportedInputDtypes(Opcode::OP_MUL);
CheckTensorDataTypeCombination({self.GetDataType(), other.GetDataType()}, combinations, "MUL");
RETURN_CALL(BinaryOperation<BinaryOpType::MUL>, *Program::GetInstance().GetCurrentFunction(), self, other);
}
Tensor Div(const Tensor& self, const Tensor& other, PrecisionType precisionType)
{
DECLARE_TRACER();
CheckVectorOperand(self.GetStorage(), "Div");
CheckVectorOperand(other.GetStorage(), "Div");
const auto& combinations = ConfigManager::Instance().GetOpSupportedInputDtypes(Opcode::OP_DIV);
CheckTensorDataTypeCombination({self.GetDataType(), other.GetDataType()}, combinations, "DIV");
auto isDivSupportedInt = [](DataType dt) { return dt == DT_INT16 || dt == DT_INT32 || dt == DT_INT64; };
if (isDivSupportedInt(self.GetDataType())) {
Tensor castSelf = Cast(self, DT_FP32, CastMode::CAST_NONE, SaturationMode::ON);
Tensor castOther = Cast(other, DT_FP32, CastMode::CAST_NONE, SaturationMode::ON);
auto [castResult, op] = TensorBinaryOperationWithOp<BinaryOpType::DIV>(
*Program::GetInstance().GetCurrentFunction(), castSelf, castOther);
op->SetAttribute(OpAttributeKey::precisionType, static_cast<int64_t>(precisionType));
return Tensor(castResult);
}
auto [result, op] = TensorBinaryOperationWithOp<BinaryOpType::DIV>(*Program::GetInstance().GetCurrentFunction(),
self, other);
op->SetAttribute(OpAttributeKey::precisionType, static_cast<int64_t>(precisionType));
return Tensor(result);
}
Tensor Fmod(const Tensor& self, const Tensor& other, PrecisionType precisionType)
{
DECLARE_TRACER();
CheckVectorOperand(self.GetStorage(), "Fmod");
CheckVectorOperand(other.GetStorage(), "Fmod");
CheckTensorsDataTypeConsistency(self.GetStorage(), other.GetStorage(), "MOD");
std::unordered_set<DataType> supportedTypes = {DT_FP16, DT_BF16, DT_FP32};
CheckTensorDataType(self.GetStorage(), supportedTypes, "MOD");
auto selfDtype = self.GetDataType();
if (selfDtype == DT_FP16) {
Tensor castSelf = Cast(self, DataType::DT_FP32, CastMode::CAST_NONE);
Tensor castOther = Cast(other, DataType::DT_FP32, CastMode::CAST_NONE);
auto [castResult, op] = TensorBinaryOperationWithOp<BinaryOpType::MOD>(
*Program::GetInstance().GetCurrentFunction(), castSelf, castOther);
op->SetAttribute(OpAttributeKey::precisionType, static_cast<int64_t>(precisionType));
return Cast(Tensor(castResult), selfDtype, CastMode::CAST_NONE);
}
auto [result, op] = TensorBinaryOperationWithOp<BinaryOpType::MOD>(*Program::GetInstance().GetCurrentFunction(),
self, other);
op->SetAttribute(OpAttributeKey::precisionType, static_cast<int64_t>(precisionType));
return Tensor(result);
}
DataType GetRemainderComputeType(DataType dtype)
{
static const std::unordered_map<NPUArch, std::unordered_set<DataType>> fp32ComputeTypes = {
{NPUArch::DAV_2201, {DT_INT16, DT_FP16}},
{NPUArch::DAV_3510, {DT_FP16}},
{NPUArch::DAV_9201, {DT_FP16}},
};
auto arch = Platform::Instance().GetSoc().GetNPUArch();
auto it = fp32ComputeTypes.find(arch);
auto types = it != fp32ComputeTypes.end() ? it->second : fp32ComputeTypes.find(NPUArch::DAV_2201)->second;
return types.count(dtype) != 0 ? DT_FP32 : dtype;
}
Tensor Remainder(const Tensor& self, const Tensor& other, PrecisionType precisionType)
{
DECLARE_TRACER();
CheckVectorOperand(self.GetStorage(), "Remainder");
CheckVectorOperand(other.GetStorage(), "Remainder");
const auto& combinations = ConfigManager::Instance().GetOpSupportedInputDtypes(Opcode::OP_REM);
CheckTensorDataTypeCombination({self.GetDataType(), other.GetDataType()}, combinations, "REM");
auto selfDtype = self.GetDataType();
auto computeType = GetRemainderComputeType(selfDtype);
if (computeType != selfDtype) {
Tensor castSelf = Cast(self, computeType, CastMode::CAST_NONE, SaturationMode::ON);
Tensor castOther = Cast(other, computeType, CastMode::CAST_NONE, SaturationMode::ON);
auto [result, op] = TensorBinaryOperationWithOp<BinaryOpType::REM>(*Program::GetInstance().GetCurrentFunction(),
castSelf, castOther);
op->SetAttribute(OpAttributeKey::precisionType, static_cast<int64_t>(precisionType));
Tensor castedResult = Cast(Tensor(result), selfDtype, CastMode::CAST_NONE, SaturationMode::ON);
return castedResult;
}
auto [result, op] = TensorBinaryOperationWithOp<BinaryOpType::REM>(*Program::GetInstance().GetCurrentFunction(),
self, other);
op->SetAttribute(OpAttributeKey::precisionType, static_cast<int64_t>(precisionType));
return Tensor(result);
}
Tensor Maximum(const Tensor& operand1, const Tensor& operand2, bool propagateNan)
{
DECLARE_TRACER();
CheckVectorOperand(operand1.GetStorage(), "Maximum");
CheckVectorOperand(operand2.GetStorage(), "Maximum");
const auto& combinations = ConfigManager::Instance().GetOpSupportedInputDtypes(Opcode::OP_MAXIMUM);
CheckTensorDataTypeCombination({operand1.GetDataType(), operand2.GetDataType()}, combinations, "MAXIMUM");
if (propagateNan || !IsFloat(operand1.GetDataType())) {
RETURN_CALL(BinaryOperation<BinaryOpType::MAXIMUM>, *Program::GetInstance().GetCurrentFunction(), operand1,
operand2);
}
if (operand1.GetDataType() == DT_BF16) {
auto result = Maximum(Cast(operand1, DT_FP32), Cast(operand2, DT_FP32), false);
return Cast(result, DT_BF16, CastMode::CAST_RINT);
}
auto [result, op] = TensorBinaryOperationWithOp<BinaryOpType::MAXIMUM, true>(
*Program::GetInstance().GetCurrentFunction(), operand1, operand2);
op->SetAttribute(OP_ATTR_PREFIX + "propagate_nan", false);
return result;
}
Tensor Minimum(const Tensor& operand1, const Tensor& operand2, bool propagateNan)
{
DECLARE_TRACER();
CheckVectorOperand(operand1.GetStorage(), "Minimum");
CheckVectorOperand(operand2.GetStorage(), "Minimum");
const auto& combinations = ConfigManager::Instance().GetOpSupportedInputDtypes(Opcode::OP_MINIMUM);
CheckTensorDataTypeCombination({operand1.GetDataType(), operand2.GetDataType()}, combinations, "MINIMUM");
if (propagateNan || !IsFloat(operand1.GetDataType())) {
RETURN_CALL(BinaryOperation<BinaryOpType::MINIMUM>, *Program::GetInstance().GetCurrentFunction(), operand1,
operand2);
}
if (operand1.GetDataType() == DT_BF16) {
auto result = Minimum(Cast(operand1, DT_FP32), Cast(operand2, DT_FP32), false);
return Cast(result, DT_BF16, CastMode::CAST_RINT);
}
auto [result, op] = TensorBinaryOperationWithOp<BinaryOpType::MINIMUM, true>(
*Program::GetInstance().GetCurrentFunction(), operand1, operand2);
op->SetAttribute(OP_ATTR_PREFIX + "propagate_nan", false);
return result;
}
static const std::unordered_set<DataType>& GetClipSupportedDtypes()
{
static const std::unordered_map<NPUArch, std::unordered_set<DataType>> supportedTypes = {
{NPUArch::DAV_2201, {DT_FP32, DT_FP16, DT_BF16, DT_INT32, DT_INT16}},
{NPUArch::DAV_3510, {DT_FP32, DT_FP16, DT_BF16, DT_INT32, DT_INT16, DT_INT64}},
{NPUArch::DAV_9201, {DT_FP32, DT_FP16, DT_BF16, DT_INT32, DT_INT16, DT_INT64}},
};
auto arch = Platform::Instance().GetSoc().GetNPUArch();
auto it = supportedTypes.find(arch);
return it != supportedTypes.end() ? it->second : supportedTypes.find(NPUArch::DAV_2201)->second;
}
Tensor Clip(const Tensor& self, const Element& min, const Element& max)
{
DECLARE_TRACER();
CheckVectorOperand(self.GetStorage(), "Clip");
const auto& supportedTypes = GetClipSupportedDtypes();
CheckTensorDataType(self.GetStorage(), supportedTypes, "CLIP");
Element min_ = min, max_ = max;
Tensor result = self;
if (min_.GetDataType() != DT_BOTTOM) {
CHECK(VectorErrorCode::ERR_PARAM_INVALID, min_.GetDataType() == self.GetDataType())
<< "The datatype of inputs should be same";
result = Maximum(result, min_);
}
if (max_.GetDataType() != DT_BOTTOM) {
CHECK(VectorErrorCode::ERR_PARAM_INVALID, max_.GetDataType() == self.GetDataType())
<< "The datatype of inputs should be same";
result = Minimum(result, max_);
}
result.GetStorage()->UpdateDynValidShape(self.GetStorage()->GetDynValidShape());
return result;
}
Tensor Clip(const Tensor& self, const Tensor& min, const Tensor& max)
{
DECLARE_TRACER();
CheckVectorOperand(self.GetStorage(), "Clip");
const auto& supportedTypes = GetClipSupportedDtypes();
CheckTensorDataType(self.GetStorage(), supportedTypes, "CLIP");
Tensor result = self;
if (min.GetStorage() != nullptr) {
CheckVectorOperand(min.GetStorage(), "Clip");
CheckTensorsFormatConsistency(self.GetStorage(), min.GetStorage(), "CLIP");
std::vector minBroadcastAxes = GetBroadcastAxes(min.GetShape(), self.GetShape());
CHECK(VectorErrorCode::ERR_PARAM_INVALID, minBroadcastAxes.size() <= 1)
<< "minBroadcastAxes size should be <= 1";
result = Maximum(result, min);
}
if (max.GetStorage() != nullptr) {
CheckVectorOperand(max.GetStorage(), "Clip");
CheckTensorsFormatConsistency(self.GetStorage(), max.GetStorage(), "CLIP");
std::vector maxBroadcastAxes = GetBroadcastAxes(max.GetShape(), self.GetShape());
CHECK(VectorErrorCode::ERR_PARAM_INVALID, maxBroadcastAxes.size() <= 1)
<< "maxBroadcastAxes size should be <= 1";
result = Minimum(result, max);
}
result.GetStorage()->UpdateDynValidShape(self.GetStorage()->GetDynValidShape());
return result;
}
Tensor Gcd(const Tensor& self, const Tensor& other)
{
DECLARE_TRACER();
CheckVectorOperand(self.GetStorage(), "Gcd");
CheckVectorOperand(other.GetStorage(), "Gcd");
CheckTensorsDataTypeConsistency(self.GetStorage(), other.GetStorage(), "GCD");
CheckTensorDimRange(self.GetStorage(), 1, NUM_VALUE_4, "GCD");
std::unordered_set<DataType> supportedTypes = {DT_INT8, DT_INT16, DT_INT32, DT_UINT8};
CheckTensorDataType(self.GetStorage(), supportedTypes, "GCD");
return TensorBinaryOperation<BinaryOpType::GCD>(*Program::GetInstance().GetCurrentFunction(), self, other);
}
Tensor FloorDiv(const Tensor& self, const Tensor& other)
{
DECLARE_TRACER();
CheckVectorOperand(self.GetStorage(), "FLOORDIV");
CheckVectorOperand(other.GetStorage(), "FLOORDIV");
const auto& combinations = ConfigManager::Instance().GetOpSupportedInputDtypes(Opcode::OP_FLOORDIV);
CheckTensorDataTypeCombination({self.GetDataType(), other.GetDataType()}, combinations, "FLOORDIV");
RETURN_CALL(BinaryOperation<BinaryOpType::FLOORDIV>, *Program::GetInstance().GetCurrentFunction(), self, other);
}
namespace {
bool IsDivModA5OnlyDtype(DataType dtype) { return dtype == DT_INT64 || dtype == DT_UINT64 || dtype == DT_UINT32; }
}
std::tuple<Tensor, Tensor> DivMod(const Tensor& self, const Tensor& other, PrecisionType precisionType)
{
(void)precisionType;
DECLARE_TRACER();
CheckVectorOperand(self.GetStorage(), "DivMod");
CheckVectorOperand(other.GetStorage(), "DivMod");
std::unordered_set<DataType> supportedTypes = {DT_INT8, DT_INT16, DT_INT32, DT_INT64,
DT_UINT8, DT_UINT16, DT_UINT32, DT_UINT64};
CheckTensorDataType(self.GetStorage(), supportedTypes, "DivMod");
DataType dtype = self.GetDataType();
CHECK(VectorErrorCode::ERR_PARAM_DTYPE_UNSUPPORTED, dtype == other.GetDataType())
<< "DivMod requires identical input dtypes (promotion is not supported): " << DataType2String(dtype) << " vs "
<< DataType2String(other.GetDataType());
if (IsDivModA5OnlyDtype(dtype)) {
CHECK(VectorErrorCode::ERR_PARAM_DTYPE_UNSUPPORTED,
Platform::Instance().GetSoc().GetNPUArch() == NPUArch::DAV_3510)
<< "DivMod only supports " << DataType2String(dtype) << " on A5 (DAV_3510)";
}
auto dividend = self.GetStorage();
auto divisor = other.GetStorage();
if (dividend->shape.size() != divisor->shape.size()) {
std::vector<int> broadCastShape = GetBroadCastShape(dividend, divisor);
dividend = BinaryOperationBroadCast(dividend, broadCastShape);
divisor = BinaryOperationBroadCast(divisor, broadCastShape);
}
CheckBinaryInputTensors(dividend, divisor, "DivMod");
std::vector<SymbolicScalar> resultValidShape;
std::vector<int64_t> resultShape = BinaryOperationResultShape(dividend, divisor);
size_t shapeSize = resultShape.size();
if ((!dividend->GetDynValidShape().empty()) && (!divisor->GetDynValidShape().empty())) {
for (size_t i = 0; i < shapeSize; ++i) {
if (resultShape[i] == dividend->shape[i]) {
resultValidShape.push_back(dividend->GetDynValidShape()[i]);
} else {
resultValidShape.push_back(divisor->GetDynValidShape()[i]);
}
}
}
auto function = Program::GetInstance().GetCurrentFunction();
auto format = dividend->Format();
auto quotientTensor = std::make_shared<LogicalTensor>(*function, dtype, resultShape, resultValidShape, format);
auto remainderTensor = std::make_shared<LogicalTensor>(*function, dtype, resultShape, resultValidShape, format);
function->AddOperation(Opcode::OP_DIVMOD, {dividend, divisor}, {quotientTensor, remainderTensor});
return {Tensor(quotientTensor), Tensor(remainderTensor)};
}
Tensor CeilDiv(const Tensor& self, const Tensor& other)
{
DECLARE_TRACER();
CheckVectorOperand(self.GetStorage(), "CeilDiv");
CheckVectorOperand(other.GetStorage(), "CeilDiv");
CheckTensorsDataTypeConsistency(self.GetStorage(), other.GetStorage(), "CEILDIV");
std::unordered_set<DataType> supportedTypes = {DT_INT32};
CheckTensorDataType(self.GetStorage(), supportedTypes, "CEILDIV");
Tensor selfFp32 = Cast(self, DataType::DT_FP32);
Tensor otherFp32 = Cast(other, DataType::DT_FP32);
Tensor resultFp32 = Div(selfFp32, otherFp32);
resultFp32 = Ceil(resultFp32);
Tensor result = Cast(resultFp32, DT_INT32);
Tensor target = Mul(result, other);
Tensor diff = Sub(self, target);
Tensor sgn_diff = Sign(diff);
Tensor sgn_other = Sign(other);
Tensor product_sgn = Mul(sgn_diff, sgn_other);
Tensor inc = Clip(product_sgn, Element(DT_INT32, 0), Element(DT_INT32, 1));
result = Add(result, inc);
return result;
}
int64_t GetOperationPrecisionType(const Operation& op)
{
if (op.HasAttr(OpAttributeKey::precisionType)) {
return op.GetIntAttribute(OpAttributeKey::precisionType);
}
return static_cast<int64_t>(PrecisionType::INTRINSIC);
}
int64_t GetRemainderTmpCols(int64_t tileCols, DataType dtype, Opcode opcode, int64_t precisionType)
{
const int64_t elementBytes = BytesOf(dtype);
const int64_t repeatCols = NUM_VALUE_256 / elementBytes;
const int64_t alignedCols = AlignUp(tileCols, repeatCols);
const int64_t maskBytes = (alignedCols + NUM_VALUE_8 - 1) / NUM_VALUE_8;
const int64_t legacyCols = alignedCols + AlignUp(maskBytes, NUM_VALUE_256) / elementBytes + repeatCols;
if (dtype != DT_FP32 || precisionType != static_cast<int64_t>(PrecisionType::HIGH_PRECISION) ||
Platform::Instance().GetSoc().GetNPUArch() != NPUArch::DAV_2201) {
const int64_t rowStride = AlignUp(tileCols, BLOCK_SIZE / elementBytes);
const int64_t compareMaskBytes = (rowStride + NUM_VALUE_8 - 1) / NUM_VALUE_8;
const int64_t compareMaskCols = AlignUp(compareMaskBytes, BLOCK_SIZE) / elementBytes;
const int64_t addressCols = BLOCK_SIZE / elementBytes;
const int64_t requiredCols = NUM_VALUE_3 * rowStride + compareMaskCols + addressCols;
return std::max(legacyCols, requiredCols);
}
const int64_t vectorCount = std::max<int64_t>(1, tileCols / repeatCols);
const int64_t workVectors = opcode == Opcode::OP_REMS ? NUM_VALUE_2 : NUM_VALUE_3;
const int64_t maskCols = AlignUp(vectorCount * repeatCols / NUM_VALUE_8, BLOCK_SIZE) / elementBytes;
const int64_t addressCols = BLOCK_SIZE / elementBytes;
const int64_t stateCols = vectorCount == 1 ? repeatCols : 0;
const int64_t highPrecisionCols = workVectors * vectorCount * repeatCols + maskCols + addressCols + stateCols;
return std::max(legacyCols, highPrecisionCols);
}
namespace {
void TileDivModOperation(Function& function, const TileShape& tileShape, size_t cur, LogicalInput& input1,
LogicalInput& input2, const LogicalTensorPtr& result1, const LogicalTensorPtr& result2,
TileInfo& resultTileInfo)
{
size_t shapeSize = input1.tensor->GetShape().size();
if (cur == shapeSize) {
auto inputTile1 = input1.tensor->View(function, input1.tileInfo.shape, input1.tileInfo.offset);
auto inputTile2 = input2.tensor->View(function, input2.tileInfo.shape, input2.tileInfo.offset);
auto resultTile1 = result1->View(function, resultTileInfo.shape, resultTileInfo.offset);
auto resultTile2 = result2->View(function, resultTileInfo.shape, resultTileInfo.offset);
auto tmpShape = resultTileInfo.shape;
auto alignSize = std::max<int64_t>(BLOCK_SIZE / BytesOf(result1->Datatype()), 8);
tmpShape.back() = AlignUp(tmpShape.back(), alignSize);
auto dtype = result1->Datatype();
int64_t tmpPlaneCount = NUM_VALUE_5;
if (Platform::Instance().GetSoc().GetNPUArch() == NPUArch::DAV_3510) {
if (dtype == DT_UINT16 || dtype == DT_UINT32 || dtype == DT_UINT64) {
tmpPlaneCount = NUM_VALUE_2;
} else if (dtype == DT_INT8 || dtype == DT_UINT8) {
tmpPlaneCount = NUM_VALUE_5;
} else if (dtype == DT_INT16) {
tmpPlaneCount = NUM_VALUE_3;
} else {
tmpPlaneCount = NUM_VALUE_4;
}
} else if (dtype == DT_INT16) {
tmpPlaneCount = NUM_VALUE_3;
} else if (dtype == DT_INT32 || dtype == DT_UINT16) {
tmpPlaneCount = NUM_VALUE_6;
}
tmpShape.front() *= tmpPlaneCount;
auto tmpType = result1->Datatype() == DT_INT64 ? DT_INT64 : DT_FP32;
auto tmpTensor = std::make_shared<LogicalTensor>(function, tmpType, tmpShape);
function.AddOperation(Opcode::OP_DIVMOD, {inputTile1, inputTile2}, {resultTile1, resultTile2, tmpTensor});
return;
}
auto& vecTile = tileShape.GetVecTile();
for (int64_t i = 0; i < result1->shape[cur]; i += vecTile[cur]) {
resultTileInfo.offset[cur] = i;
resultTileInfo.shape[cur] = std::min(result1->shape[cur] - resultTileInfo.offset[cur], vecTile[cur]);
input1.tileInfo.offset[cur] = i % input1.tensor->GetShape()[cur];
input1.tileInfo.shape[cur] = std::min(input1.tensor->GetShape()[cur] - input1.tileInfo.offset[cur],
vecTile[cur]);
input2.tileInfo.offset[cur] = i % input2.tensor->GetShape()[cur];
input2.tileInfo.shape[cur] = std::min(input2.tensor->GetShape()[cur] - input2.tileInfo.offset[cur],
vecTile[cur]);
TileDivModOperation(function, tileShape, cur + 1, input1, input2, result1, result2, resultTileInfo);
}
}
void DivModOperationTileFunc(Function& function, const TileShape& tileShape,
const std::vector<LogicalTensorPtr>& iOperand,
const std::vector<LogicalTensorPtr>& oOperand, [[maybe_unused]] const Operation& op)
{
LogicalTensorPtr operand1 = iOperand[0];
LogicalTensorPtr operand2 = iOperand[1];
BroadcastOperandTensor(operand1, operand2, oOperand[0], function, tileShape);
BroadcastOperandTensor(operand2, operand1, oOperand[0], function, tileShape);
TileInfo tileInfo1(operand1->shape.size(), operand1->offset.size());
TileInfo tileInfo2(operand2->shape.size(), operand2->offset.size());
TileInfo resultTileInfo(oOperand[0]->shape.size(), oOperand[0]->offset.size());
auto input1 = LogicalInput{operand1, tileInfo1};
auto input2 = LogicalInput{operand2, tileInfo2};
TileDivModOperation(function, tileShape, 0, input1, input2, oOperand[0], oOperand[1], resultTileInfo);
}
}
REGISTER_OPERATION_TILED_FUNC(OP_ADD, Opcode::OP_ADD, BinaryOperationTileFunc<BinaryOpType::ADD>);
REGISTER_OPERATION_TILED_FUNC(OP_SUB, Opcode::OP_SUB, BinaryOperationTileFunc<BinaryOpType::SUB>);
REGISTER_OPERATION_TILED_FUNC(OP_MUL, Opcode::OP_MUL, BinaryOperationTileFunc<BinaryOpType::MUL>);
REGISTER_OPERATION_TILED_FUNC(OP_DIV, Opcode::OP_DIV, BinaryOperationTileFunc<BinaryOpType::DIV>);
REGISTER_OPERATION_TILED_FUNC(OP_MAXIMUM, Opcode::OP_MAXIMUM, BinaryOperationTileFunc<BinaryOpType::MAXIMUM>);
REGISTER_OPERATION_TILED_FUNC(OP_MINIMUM, Opcode::OP_MINIMUM, BinaryOperationTileFunc<BinaryOpType::MINIMUM>);
REGISTER_OPERATION_TILED_FUNC(OP_MOD, Opcode::OP_MOD, BinaryOperationTileFunc<BinaryOpType::MOD>);
REGISTER_OPERATION_TILED_FUNC(OP_REM, Opcode::OP_REM, BinaryOperationTileFunc<BinaryOpType::REM>);
REGISTER_OPERATION_TILED_FUNC(OP_GCD, Opcode::OP_GCD, BinaryOperationTileFunc<BinaryOpType::GCD>);
REGISTER_OPERATION_TILED_FUNC(OP_FLOORDIV, Opcode::OP_FLOORDIV, BinaryOperationTileFunc<BinaryOpType::FLOORDIV>);
REGISTER_OPERATION_TILED_FUNC(OP_DIVMOD, Opcode::OP_DIVMOD, DivModOperationTileFunc);
}